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
2226dfc22c3e7a283016ed69b2fcdec3311d6e24
kong/plugins/acme/api.lua
kong/plugins/acme/api.lua
local client = require "kong.plugins.acme.client" local http = require "resty.http" local function find_plugin() for plugin, err in kong.db.plugins:each(1000) do if err then return nil, err end if plugin.name == "acme" then return plugin end end end return { ["/acme"] = { POST = function(self) local plugin, err = find_plugin() if err then return kong.response.exit(500, { message = err }) elseif not plugin then return kong.response.exit(404) end local conf = plugin.config local host = self.params.host if not host or type(host) ~= "string" then return kong.response.exit(400, { message = "host must be provided and containing a single domain" }) end -- we don't allow port for security reason in test_only mode if string.find(host, ":") ~= nil then return kong.response.exit(400, { message = "port is not allowed in host" }) end if self.params.test_http_challenge_flow == "true" then local check_path = string.format("http://%s/.well-known/acme-challenge/", host) local httpc = http.new() local res, err = httpc:request_uri(check_path .. "x") if not err then if ngx.re.match("no Route matched with those values", res.body) then err = check_path .. "* doesn't map to a route in Kong" elseif res.body ~= "Not found\n" then err = "unexpected response found :" .. (res.body or "<nil>") if res.status ~= 404 then err = err .. string.format(", unexpected status code: %d", res.status) end else return kong.response.exit(200, { message = "sanity test for host " .. host .. " passed"}) end end return kong.response.exit(400, { message = "problem found running sanity check for " .. host .. ": " .. err}) end err = client.update_certificate(conf, host, nil) if err then return kong.response.exit(500, { message = "failed to update certificate: " .. err }) end err = client.store_renew_config(conf, host) if err then return kong.response.exit(500, { message = "failed to store renew config: " .. err }) end local msg = "certificate for host " .. host .. " is created" return kong.response.exit(201, { message = msg }) end, PATCH = function() client.renew_certificate() return kong.response.exit(202, { message = "Renewal process started successfully" }) end, }, }
local client = require "kong.plugins.acme.client" local http = require "resty.http" local function find_plugin() for plugin, err in kong.db.plugins:each(1000) do if err then return nil, err end if plugin.name == "acme" then return plugin end end end return { ["/acme"] = { POST = function(self) local plugin, err = find_plugin() if err then return kong.response.exit(500, { message = err }) elseif not plugin then return kong.response.exit(404) end local conf = plugin.config local host = self.params.host if not host or type(host) ~= "string" then return kong.response.exit(400, { message = "host must be provided and containing a single domain" }) end -- we don't allow port for security reason in test_only mode if string.find(host, ":") ~= nil then return kong.response.exit(400, { message = "port is not allowed in host" }) end -- string "true" automatically becomes boolean true from lapis if self.params.test_http_challenge_flow == true then local check_path = string.format("http://%s/.well-known/acme-challenge/", host) local httpc = http.new() local res, err = httpc:request_uri(check_path .. "x") if not err then if ngx.re.match("no Route matched with those values", res.body) then err = check_path .. "* doesn't map to a route in Kong" elseif res.body ~= "Not found\n" then err = "unexpected response found :" .. (res.body or "<nil>") if res.status ~= 404 then err = err .. string.format(", unexpected status code: %d", res.status) end else return kong.response.exit(200, { message = "sanity test for host " .. host .. " passed"}) end end return kong.response.exit(400, { message = "problem found running sanity check for " .. host .. ": " .. err}) end err = client.update_certificate(conf, host, nil) if err then return kong.response.exit(500, { message = "failed to update certificate: " .. err }) end err = client.store_renew_config(conf, host) if err then return kong.response.exit(500, { message = "failed to store renew config: " .. err }) end local msg = "certificate for host " .. host .. " is created" return kong.response.exit(201, { message = msg }) end, PATCH = function() client.renew_certificate() return kong.response.exit(202, { message = "Renewal process started successfully" }) end, }, }
fix(acme) fix sanity check params to correctly test flow only (#40)
fix(acme) fix sanity check params to correctly test flow only (#40)
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
98336c4fcf0443df02292c9e8947a8cb4e968f1f
love2d/game.lua
love2d/game.lua
love.game = {} require "world" require "external/gui/gui" require "conf" function love.game.newGame() local o = {} o.state = 1 o.world = nil o.version = "0.0.0" o.x = 30 o.y = 20 o.xVel = 0.1 o.yVel = -0.1 o.init = function() o.world = love.game.newWorld() o.world.init() o.setupMenu() o.setState(states.MAIN_MENU) -- set the starting state (use e. g. MAIN_MENU if you work on the menus) end o.setupMenu = function() o.menu = love.gui.newGui() -- Buttons -- A man can dream... --[[ local buttons = {{o.playButton, "Play"}, {o.creditsButton, "Credits"}, {o.exitButton, "Exit"}} local i = 0 for button in buttons do button[1] = o.menu.newButton(5, i*(spacing + button_height), 120, padding + font_h, button[2], nil) i = i + 1 end --]] o.buttonImage = G.newImage("res/gfx/gui-arrow.png") G.setFont(FONT_LARGE) local padding = 7 local fontH = FONT_MEDIUM:getHeight() local spacing = 25 local buttonH = padding + fontH local buttonX = love.window.getWidth()/2 - 140/2 local windowH = love.window.getHeight()/2 local nButtons = 3 local totalButtonH = nButtons*(spacing + buttonH) o.playButton = o.menu.newButton(buttonX, windowH - totalButtonH/2 + 0*(spacing + buttonH), 140, buttonH, "Play", o.buttonImage) o.playButton.setFont(FONT_LARGE) o.creditsButton = o.menu.newButton(buttonX, windowH - totalButtonH/2 + 1*(spacing + buttonH), 140, buttonH, "Credits", o.buttonImage) o.creditsButton.setFont(FONT_LARGE) o.exitButton = o.menu.newButton(buttonX, windowH - totalButtonH/2 + 2*(spacing + buttonH), 140, buttonH, "Exit", o.buttonImage) o.creditsButton.setFont(FONT_LARGE) -- Background image local scale = function(x, min1, max1, min2, max2) return min2 + ((x - min1) / (max1 - min1)) * (max2 - min2) end local distance = function(x1, y1, x2, y2) return math.sqrt((x2 - x1) ^ 2 + (y2 - y1) ^ 2) end local imageData = love.image.newImageData(1024, 1024) local maxDist = math.sqrt(512)^2 imageData:mapPixel(function(x, y) local dist = distance(1024/2, 1024/2, x, y) local color = 255 - (dist/maxDist)*255 local color = color > 255 and 255 or color local diff = 215 - 159 return 159 + diff*color/255, 159 + diff*color/255, 159 + diff*color/255, 255 end) o.backgroundImage = G.newImage(imageData) end o.update = function(dt) if o.state == states.PAUSED then return end if o.state == states.MAIN_MENU then if o.playButton.hit then o.setState(states.GAMEPLAY) TEsound.stop(love.sounds.bgm.activeBgm,false) --love.sounds.playBgm("lizardGuitarFx") elseif o.creditsButton.hit then o.setState(states.CREDITS) love.sounds.playBgm("lizardGuitarSlow") elseif o.exitButton.hit then love.event.quit() end o.menu.update(dt) elseif o.state == states.GAMEPLAY then o.world.update(dt) end end o.draw = function() if o.state == states.MAIN_MENU then G.setColor(255, 255, 255) G.draw(o.backgroundImage, 0, 0, 0, love.window.getWidth()/o.backgroundImage:getWidth(), love.window.getHeight()/o.backgroundImage:getHeight()) o.menu.draw() local font = FONT_XLARGE G.setFont(font) G.setColor(151*0.80, 147*0.80, 141*0.80) G.printf("The Tale of Some Reptile", 0, love.window.getHeight()/4 - font:getHeight()/2, love.window.getWidth(), "center") -- debug --G.setColor(255, 0, 0) --G.rectangle("fill", love.window.getWidth()/2 - 20, love.window.getHeight()/2 - 20, 40, 40) G.setColor(255, 255, 255) elseif o.state == states.GAMEPLAY then o.world.draw() elseif o.state == states.CREDITS then G.print("Credits!", o.x, o.y) elseif o.state == states.PAUSED then -- Draw world as backdrop G.setColor(255, 255, 255, 255) o.world.draw() -- Draw transparent rectangle for the 'faded' effect local w = love.window.getWidth() local h = love.window.getHeight() G.setColor(255, 255, 255, 96) G.rectangle("fill", 0, 0, w, h) -- Draw centered (H&V) text G.setColor(0, 0, 0) local font = FONT_XLARGE G.setFont(font) G.printf("Paused.", 0, h/2 - font:getHeight()/2, w, "center") G.setColor(255, 255, 255) end end o.setState = function(state) o.state = state end o.setVersion = function(version) o.version = version end return o end
love.game = {} require "world" require "external/gui/gui" require "conf" function love.game.newGame() local o = {} o.state = 1 o.world = nil o.version = "0.0.0" o.x = 30 o.y = 20 o.xVel = 0.1 o.yVel = -0.1 o.init = function() o.world = love.game.newWorld() o.world.init() o.setupMenu() o.setupCredits() o.setState(states.MAIN_MENU) -- set the starting state (use e. g. MAIN_MENU if you work on the menus) end -- TODO own class for credits o.setupCredits = function() if not o.peopleTextual then o.people = { "Markus Vill", "Nicolai Czempin", "Bernd Hildebrandt", "Marcus Ihde", "Meral Leyla", "Aldo Briessmann", "Sotos", "Terence-Lee Davis", "Francisco Pinto", } table.sort(o.people) -- 2lazy o.peopleTextual = "" for i, person in ipairs(o.people) do o.peopleTextual = o.peopleTextual .. person if i ~= #o.people then o.peopleTextual = o.peopleTextual .. "\n\n" end end o.creditsFont = FONT_MEDIUM local nLines = select(2, o.peopleTextual:gsub('\n', '\n')) o.creditsHPos = W.getHeight()/2 - .75*nLines/2*o.creditsFont:getHeight() end end -- TODO move this method elsewhere o.setupMenu = function() o.menu = love.gui.newGui() -- Buttons -- A man can dream... --[[ local buttons = {{o.playButton, "Play"}, {o.creditsButton, "Credits"}, {o.exitButton, "Exit"}} local i = 0 for button in buttons do button[1] = o.menu.newButton(5, i*(spacing + button_height), 120, padding + font_h, button[2], nil) i = i + 1 end --]] o.buttonImage = G.newImage("res/gfx/gui-arrow.png") G.setFont(FONT_LARGE) local padding = 7 local fontH = FONT_MEDIUM:getHeight() local spacing = 25 local buttonH = padding + fontH local buttonX = W.getWidth()/2 - 140/2 local windowH = W.getHeight()/2 local nButtons = 3 local totalButtonH = nButtons*(spacing + buttonH) o.playButton = o.menu.newButton(buttonX, windowH - totalButtonH/2 + 0*(spacing + buttonH), 140, buttonH, "Play", o.buttonImage) o.playButton.setFont(FONT_LARGE) o.creditsButton = o.menu.newButton(buttonX, windowH - totalButtonH/2 + 1*(spacing + buttonH), 140, buttonH, "Credits", o.buttonImage) o.creditsButton.setFont(FONT_LARGE) o.exitButton = o.menu.newButton(buttonX, windowH - totalButtonH/2 + 2*(spacing + buttonH), 140, buttonH, "Exit", o.buttonImage) o.creditsButton.setFont(FONT_LARGE) -- Background image local scale = function(x, min1, max1, min2, max2) return min2 + ((x - min1) / (max1 - min1)) * (max2 - min2) end local distance = function(x1, y1, x2, y2) return math.sqrt((x2 - x1) ^ 2 + (y2 - y1) ^ 2) end local imageData = love.image.newImageData(1024, 1024) local maxDist = math.sqrt(512)^2 imageData:mapPixel(function(x, y) local dist = distance(1024/2, 1024/2, x, y) local color = 255 - (dist/maxDist)*255 local color = color > 255 and 255 or color local diff = 215 - 159 return 159 + diff*color/255, 159 + diff*color/255, 159 + diff*color/255, 255 end) o.backgroundImage = G.newImage(imageData) end o.update = function(dt) if o.state == states.PAUSED then return end if o.state == states.MAIN_MENU then if o.playButton.hit then o.setState(states.GAMEPLAY) TEsound.stop(S.bgm.activeBgm,false) --S.playBgm("lizardGuitarFx") elseif o.creditsButton.hit then o.setState(states.CREDITS) S.playBgm("lizardGuitarSlow") elseif o.exitButton.hit then love.event.quit() end o.menu.update(dt) elseif o.state == states.GAMEPLAY then o.world.update(dt) end end o.drawBackgroundImage = function() G.setColor(255, 255, 255) G.draw(o.backgroundImage, 0, 0, 0, W.getWidth()/o.backgroundImage:getWidth(), W.getHeight()/o.backgroundImage:getHeight()) end o.drawTitle = function(titleText) local font = FONT_XLARGE G.setFont(font) G.setColor(120, 118, 112) G.printf(titleText, 0, W.getHeight()/4 - font:getHeight()/2, W.getWidth(), "center") G.setColor(255, 255, 255) end o.drawCredits = function() o.drawBackgroundImage() o.drawTitle("Credits") local hh = W.getHeight()/2 local w = W.getWidth() G.setFont(o.creditsFont) G.setColor(81, 81, 81) G.printf(o.peopleTextual, 0, o.creditsHPos, w, "center") G.setColor(255, 255, 255) end o.drawPause = function() -- Draw world as backdrop G.setColor(255, 255, 255, 255) o.world.draw() -- Draw transparent rectangle for the 'faded' effect local w = W.getWidth() local h = W.getHeight() G.setColor(255, 255, 255, 96) G.rectangle("fill", 0, 0, w, h) -- Draw centered (H&V) text G.setColor(0, 0, 0) local font = FONT_XLARGE G.setFont(font) G.printf("Paused.", 0, h/2 - font:getHeight()/2, w, "center") G.setColor(255, 255, 255) end o.draw = function() if o.state == states.MAIN_MENU then o.drawBackgroundImage() o.menu.draw() o.drawTitle("The Tale of Some Reptile") -- debug --G.setColor(255, 0, 0) --G.rectangle("fill", W.getWidth()/2 - 20, W.getHeight()/2 - 20, 40, 40) elseif o.state == states.GAMEPLAY then o.world.draw() elseif o.state == states.CREDITS then o.drawCredits() elseif o.state == states.PAUSED then o.drawPause() end end o.setState = function(state) o.state = state end o.setVersion = function(version) o.version = version end return o end
Added proper credits and slightly refactored game.lua (still many smells to fix)
Added proper credits and slightly refactored game.lua (still many smells to fix)
Lua
mit
nczempin/lizard-journey
b36e5079a6f1a78a47444370538005335bb18fa7
test_scripts/Polices/build_options/ATF_PM_change_status_UPDATE_NEEDED_after_timeout_expired.lua
test_scripts/Polices/build_options/ATF_PM_change_status_UPDATE_NEEDED_after_timeout_expired.lua
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate][GENIVI] PoliciesManager changes status to “UPDATE_NEEDED” -- -- Description: -- SDL should request PTU in case new application is registered and is not listed in PT -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- Connect mobile phone over WiFi. -- 2. Performed steps -- Register new application -- SDL-> <app ID> ->OnSystemRequest(params, url, ) -- Timeout expires -- -- Expected result: --SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" config.defaultProtocolVersion = 2 --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') --[[ 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') --[[ Local Variables ]] local OnSystemRequest_time = nil local registerAppInterfaceParams = { syncMsgVersion = { majorVersion = 3, minorVersion = 0 }, appName = "Media Application", isMediaApplication = true, languageDesired = 'EN-US', hmiDisplayLanguageDesired = 'EN-US', appHMIType = {"NAVIGATION"}, appID = "MyTestApp", deviceInfo = { os = "Android", carrier = "Megafon", firmwareRev = "Name: Linux, Version: 3.4.0-perf", osVersion = "4.4.2", maxNumberRFCOMMPorts = 1 } } --[[ Local Functions ]] local function timestamp() local f = io.popen("date +%s") local o = f:read("*all") f:close() return (o:gsub("\n", "")) end local function policyUpdate(self) local pathToSnaphot = "/tmp/fs/mp/images/ivsu_cache/ptu.json" local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestIdGetURLS) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", appID = self.applications ["Test Application"], fileName = "PTU" } ) end) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY" }) :Do(function(_,_) local CorIdSystemRequest = self.mobileSession:SendRPC ("SystemRequest", { requestType = "PROPRIETARY", fileName = "PTU" }, pathToSnaphot ) EXPECT_HMICALL("BasicCommunication.SystemRequest") :Do(function(_,data) self.hmiConnection:SendResponse(data.id,"BasicCommunication.SystemRequest", "SUCCESS", {}) end) EXPECT_RESPONSE(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"}) :Do(function(_,_) self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate", { policyfile = "/tmp/fs/mp/images/ivsu_cache/PTU" }) end) :Do(function(_,_) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"}) end) end) end --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Preconditions_Update_Policy() policyUpdate(self) end function Test:Precondition_CreateNewSession() self.mobileSession1 = mobile_session.MobileSession( self, self.mobileConnection) self.mobileSession1:StartService(7) end function Test:Precondition_RegisterApplication_In_NewSession() local corId = self.mobileSession1:SendRPC("RegisterAppInterface", registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = "Media Application" }}) :Do(function (_, _) OnSystemRequest_time = timestamp() end) self.mobileSession1:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" }) self.mobileSession1:ExpectNotification("OnPermissionsChange") 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 else return false end end):Times(2) end --[[ Test ]] commonFunctions:newTestCasesGroup ("Test") function Test:TestStep_Start_New_PolicyUpdate_Wait_UPDATE_NEEDED_status() local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestIdGetURLS) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = "PTU" } ) end) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY" }) EXPECT_HMINOTIFICATION ("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}) :Timeout(60000) :Do(function (_,_) local diff = tonumber(timestamp()) - tonumber(OnSystemRequest_time) if diff > 60000 and diff < 61000 then return true else return false end end) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") Test["StopSDL"] = function() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate][GENIVI] PoliciesManager changes status to “UPDATE_NEEDED” -- -- Description: -- SDL should request PTU in case new application is registered and is not listed in PT -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- Connect mobile phone over WiFi. -- 2. Performed steps -- Register new application -- SDL-> <app ID> ->OnSystemRequest(params, url, ) -- Timeout expires -- -- Expected result: --SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" config.defaultProtocolVersion = 2 --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') --[[ General Precondition before ATF start ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') --[[ Local Variables ]] local OnSystemRequest_time = nil local registerAppInterfaceParams = { syncMsgVersion = { majorVersion = 3, minorVersion = 0 }, appName = "Media Application", isMediaApplication = true, languageDesired = 'EN-US', hmiDisplayLanguageDesired = 'EN-US', appHMIType = {"NAVIGATION"}, appID = "MyTestApp", deviceInfo = { os = "Android", carrier = "Megafon", firmwareRev = "Name: Linux, Version: 3.4.0-perf", osVersion = "4.4.2", maxNumberRFCOMMPorts = 1 } } --[[ Local Functions ]] local function timestamp() local f = io.popen("date +%s") local o = f:read("*all") f:close() return (o:gsub("\n", "")) end local function policyUpdate(self) local pathToSnaphot = "files/ptu.json" local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestIdGetURLS) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", appID = self.applications ["Test Application"], fileName = "PTU" } ) end) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY" }) :Do(function(_,_) local CorIdSystemRequest = self.mobileSession:SendRPC ("SystemRequest", { requestType = "PROPRIETARY", fileName = "PTU" }, pathToSnaphot ) EXPECT_HMICALL("BasicCommunication.SystemRequest") :Do(function(_,data) self.hmiConnection:SendResponse(data.id,"BasicCommunication.SystemRequest", "SUCCESS", {}) end) EXPECT_RESPONSE(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"}) :Do(function(_,_) self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate", { policyfile = "/tmp/fs/mp/images/ivsu_cache/PTU" }) end) :Do(function(_,_) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"}) end) end) end --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Preconditions_Update_Policy() policyUpdate(self) end function Test:Precondition_CreateNewSession() self.mobileSession1 = mobile_session.MobileSession( self, self.mobileConnection) self.mobileSession1:StartService(7) end function Test:Precondition_RegisterApplication_In_NewSession() local corId = self.mobileSession1:SendRPC("RegisterAppInterface", registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = "Media Application" }}) :Do(function (_, _) OnSystemRequest_time = timestamp() end) self.mobileSession1:ExpectResponse(corId, { success = true, resultCode = "SUCCESS" }) self.mobileSession1:ExpectNotification("OnPermissionsChange") 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 else return false end end):Times(2) end --[[ Test ]] commonFunctions:newTestCasesGroup ("Test") function Test:TestStep_Start_New_PolicyUpdate_Wait_UPDATE_NEEDED_status() local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestIdGetURLS) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = "PTU" } ) end) EXPECT_NOTIFICATION("OnSystemRequest", {requestType = "PROPRIETARY" }) EXPECT_HMINOTIFICATION ("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}) :Timeout(60000) :Do(function (_,_) local diff = tonumber(timestamp()) - tonumber(OnSystemRequest_time) if diff > 60000 and diff < 61000 then return true else return false end end) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") Test["StopSDL"] = function() 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
a1ab08e58522b06f8a71e8c15c2d152cd32a250b
src/lua/switch.lua
src/lua/switch.lua
-- Copyright 2012 Snabb GmbH -- -- Ethernet switch module. -- -- Packets are represented as tables with the following fields: -- inputport = port the packet was received on -- src, dst = string representations of the ethernet src/dst addresses -- length = number of bytes of data -- data = pointer to memory buffer containing data module(...,package.seeall) require("shm") local ffi = require("ffi") local fabric = ffi.load("fabric") local dev = fabric.open_shm("/tmp/ba") local c = require("c") local port = require("port") local C = ffi.C -- Ethernet frame format ffi.cdef[[ struct ethh { uint8_t dst[6]; uint8_t src[6]; uint16_t type; // NOTE: Network byte order! } __attribute__ ((__packed__)); ]] -- Counters -- Switch ports local ports = { port.new(1, "/tmp/a"), port.new(2, "/tmp/b") } port.trace("/tmp/switch.pcap") -- Switch logic local fdb = {} -- { MAC -> [Port] } function main () while true do -- print("Main loop") for _,port in ipairs(ports) do if port:available() then local frame = port:receive() local packet = makepacket(port, frame.data, frame.length) input(packet) end end C.usleep(100000) end end function makepacket (inputport, data, length) return {inputport = inputport, length = length, data = data, src = ffi.string(data, 6), dst = ffi.string(data + 6, 6)} end -- Input a packet into the switching logic. function input (packet) fdb:update(packet) output(packet) end -- Output `eth' to the appropriate ports. function output (packet) print("Sending packet to " .. #fdb:lookup(packet)) for _,port in ipairs(fdb:lookup(packet)) do if not port:transmit(packet, port) then print "TX overflow" end end end -- Forwarding database function fdb:update (packet) self[packet.src] = packet.inputport end function fdb:lookup (packet) if self[packet.dst] then return {self[packet.dst]} else return ports end end
-- Copyright 2012 Snabb GmbH -- -- Ethernet switch module. -- -- Packets are represented as tables with the following fields: -- inputport = port the packet was received on -- src, dst = string representations of the ethernet src/dst addresses -- length = number of bytes of data -- data = pointer to memory buffer containing data module(...,package.seeall) require("shm") local ffi = require("ffi") local fabric = ffi.load("fabric") local dev = fabric.open_shm("/tmp/ba") local c = require("c") local port = require("port") local C = ffi.C -- Ethernet frame format ffi.cdef[[ struct ethh { uint8_t dst[6]; uint8_t src[6]; uint16_t type; // NOTE: Network byte order! } __attribute__ ((__packed__)); ]] -- Counters -- Switch ports local ports = { port.new(1, "/tmp/a"), port.new(2, "/tmp/b") } port.trace("/tmp/switch.pcap") -- Switch logic local fdb = {} -- { MAC -> [Port] } function main () while true do -- print("Main loop") for _,port in ipairs(ports) do if port:available() then local frame = port:receive() local packet = makepacket(port, frame.data, frame.length) input(packet) end end C.usleep(100000) end end function makepacket (inputport, data, length) return {inputport = inputport, length = length, data = data, src = ffi.string(data, 6), dst = ffi.string(data + 6, 6)} end -- Input a packet into the switching logic. function input (packet) fdb:update(packet) output(packet) end -- Output `eth' to the appropriate ports. function output (packet) print("Sending packet to " .. #fdb:lookup(packet)) for _,port in ipairs(fdb:lookup(packet)) do if port ~= packet.inputport then if not port:transmit(packet, port) then print "TX overflow" end end end end -- Forwarding database function fdb:update (packet) self[packet.src] = packet.inputport end function fdb:lookup (packet) if self[packet.dst] then return {self[packet.dst]} else return ports end end
switch.lua: Fixed a bug -- don't send packets back out the ingress port.
switch.lua: Fixed a bug -- don't send packets back out the ingress port.
Lua
apache-2.0
dpino/snabb,wingo/snabb,virtualopensystems/snabbswitch,heryii/snabb,SnabbCo/snabbswitch,dpino/snabb,kbara/snabb,plajjan/snabbswitch,dpino/snabbswitch,kbara/snabb,andywingo/snabbswitch,justincormack/snabbswitch,snabbco/snabb,kbara/snabb,eugeneia/snabb,wingo/snabb,pavel-odintsov/snabbswitch,snabbco/snabb,eugeneia/snabb,Igalia/snabb,wingo/snabbswitch,alexandergall/snabbswitch,plajjan/snabbswitch,kbara/snabb,wingo/snabbswitch,Igalia/snabb,kellabyte/snabbswitch,lukego/snabbswitch,SnabbCo/snabbswitch,andywingo/snabbswitch,snabbco/snabb,kbara/snabb,eugeneia/snabb,eugeneia/snabbswitch,dwdm/snabbswitch,eugeneia/snabbswitch,wingo/snabb,lukego/snabb,mixflowtech/logsensor,eugeneia/snabb,alexandergall/snabbswitch,heryii/snabb,SnabbCo/snabbswitch,alexandergall/snabbswitch,heryii/snabb,dpino/snabbswitch,pirate/snabbswitch,pirate/snabbswitch,Igalia/snabbswitch,snabbco/snabb,snabbco/snabb,xdel/snabbswitch,justincormack/snabbswitch,snabbnfv-goodies/snabbswitch,xdel/snabbswitch,javierguerragiraldez/snabbswitch,hb9cwp/snabbswitch,dpino/snabb,hb9cwp/snabbswitch,heryii/snabb,Igalia/snabb,snabbco/snabb,plajjan/snabbswitch,alexandergall/snabbswitch,dpino/snabbswitch,wingo/snabb,pavel-odintsov/snabbswitch,aperezdc/snabbswitch,eugeneia/snabb,pavel-odintsov/snabbswitch,kbara/snabb,andywingo/snabbswitch,fhanik/snabbswitch,dpino/snabb,fhanik/snabbswitch,Igalia/snabb,eugeneia/snabb,Igalia/snabbswitch,Igalia/snabb,aperezdc/snabbswitch,snabbnfv-goodies/snabbswitch,aperezdc/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,justincormack/snabbswitch,wingo/snabbswitch,eugeneia/snabb,eugeneia/snabb,pirate/snabbswitch,mixflowtech/logsensor,snabbnfv-goodies/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,kellabyte/snabbswitch,snabbco/snabb,virtualopensystems/snabbswitch,dpino/snabb,heryii/snabb,dpino/snabb,lukego/snabbswitch,hb9cwp/snabbswitch,javierguerragiraldez/snabbswitch,wingo/snabb,dwdm/snabbswitch,aperezdc/snabbswitch,Igalia/snabb,wingo/snabb,mixflowtech/logsensor,kellabyte/snabbswitch,Igalia/snabb,lukego/snabbswitch,virtualopensystems/snabbswitch,Igalia/snabb,hb9cwp/snabbswitch,alexandergall/snabbswitch,fhanik/snabbswitch,Igalia/snabbswitch,mixflowtech/logsensor,heryii/snabb,Igalia/snabbswitch,xdel/snabbswitch,plajjan/snabbswitch,justincormack/snabbswitch,lukego/snabb,Igalia/snabbswitch,lukego/snabbswitch,dwdm/snabbswitch,mixflowtech/logsensor,lukego/snabb,dpino/snabbswitch,snabbco/snabb,andywingo/snabbswitch,lukego/snabb,snabbnfv-goodies/snabbswitch,dpino/snabb,eugeneia/snabbswitch,eugeneia/snabbswitch,javierguerragiraldez/snabbswitch,wingo/snabbswitch
8679302e3ae285af670514a2d6ec9f764cd41bba
mock/common/LinePath2D.lua
mock/common/LinePath2D.lua
module 'mock' -------------------------------------------------------------------- CLASS: LinePath2D ( Component ) :MODEL{ Field 'verts' :array( 'number' ) :getset( 'Verts' ) :no_edit(); Field 'looped' :boolean() :isset( 'Looped' ); Field 'reverse' :action(); } registerComponent( 'LinePath2D', LinePath2D ) function LinePath2D:__init() self.looped = false self.boundRect = {0,0,0,0} self.outputVerts = {} self:setVerts{ 0,0, 0,100, 100,100, 100, 0 } end function LinePath2D:setLooped( looped ) self.looped = looped self:updateVerts() end function LinePath2D:isLooped() return self.looped end function LinePath2D:onAttach( ent ) -- LinePath2D.__super.onAttach( self, ent ) self:updateVerts() end function LinePath2D:getVerts() return self.verts end function LinePath2D:setVerts( verts ) self.verts = verts self:updateVerts() end function LinePath2D:getStartPoint( world ) local verts = self.verts local x, y = verts[ 1 ], verts[ 2 ] if world then x, y, z = self:getEntity():modelToWorld( x, y, 0 ) end return x, y, 0 end function LinePath2D:getEndPoint( world ) local verts = self.verts local count = #verts local x, y = verts[ count-1 ], verts[ count ] if world then x, y, z = self:getEntity():modelToWorld( x, y, 0 ) end return x, y, 0 end function LinePath2D:updateVerts() if not self._entity then return end local verts = self.verts local x0,y0,x1,y1 for i = 1, #verts, 2 do local x, y = verts[ i ], verts[ i + 1 ] x0 = x0 and ( x < x0 and x or x0 ) or x y0 = y0 and ( y < y0 and y or y0 ) or y x1 = x1 and ( x > x1 and x or x1 ) or x y1 = y1 and ( y > y1 and y or y1 ) or y end self.boundRect = { x0 or 0, y0 or 0, x1 or 0, y1 or 0 } local outputVerts = { unpack(verts) } if self:isLooped() then table.insert( outputVerts, outputVerts[ 1 ] ) table.insert( outputVerts, outputVerts[ 2 ] ) end local length = 0 local length2 = 0 local x0,y0 for i = 1, #outputVerts, 2 do local x, y = outputVerts[ i ], outputVerts[ i+1 ] if i > 1 then local l2 = distanceSqrd( x0,y0, x,y ) local l = math.sqrt( l2 ) length = length + l length2 = length2 + l2 end x0,y0 = x, y end self.totalLength = length self.totalLength2 = length2 self.outputVerts = outputVerts end function LinePath2D:onDraw() gfx.setPenWidth( self.penWidth ) draw.drawLine( unpack( self.outputVerts ) ) end function LinePath2D:onGetRect() return unpack( self.boundRect ) end function LinePath2D:reverse() self.verts = table.reversed2( self.verts ) self:updateVerts() end local insert = table.insert function LinePath2D:makeSubPath( x0, y0, x1, y1 ) local px0, py0, va0, vb0 = self:projectPoint( x0, y0 ) local px1, py1, va1, vb1 = self:projectPoint( x1, y1 ) local looped = self.looped local output = {} insert( output, px0 ) insert( output, py0 ) local verts = self.verts local vcount = #verts/2 local ent = self:getEntity() local l = 0 local _x, _y = px0, py0 if va0 > va1 then for i = va0, vb1, -1 do local k = ( i - 1 ) * 2 local x, y = verts[ k + 1 ], verts[ k + 2 ] x, y = ent:modelToWorld( x, y ) insert( output, x ) insert( output, y ) l = l + distance( x, y, _x, _y) _x, _y = x, y end elseif va0 < va1 then for i = vb0, va1, 1 do local k = ( i - 1 ) * 2 local x, y = verts[ k + 1 ], verts[ k + 2 ] x, y = ent:modelToWorld( x, y ) insert( output, x ) insert( output, y ) l = l + distance( x, y, _x, _y) _x, _y = x, y end end insert( output, px1 ) insert( output, py1 ) l = l + distance( px1, py1, _x, _y) if looped and l > self.totalLength/2 then --make reversed path output = {} insert( output, px0 ) insert( output, py0 ) print( va0, va1 ) if va0 > va1 then -- dir+ if vb0 == 1 then vb0 = vcount + 1 end local va1 = va1 + vcount local vb1 = vb1 + vcount print( vcount, vb0, va1, 1 ) for i = vb0, va1, 1 do i = ( ( i - 1 ) % vcount ) + 1 local k = ( i - 1 ) * 2 local x, y = verts[ k + 1 ], verts[ k + 2 ] x, y = ent:modelToWorld( x, y ) insert( output, x ) insert( output, y ) end elseif va0 < va1 then local va0 = va0 + vcount local vb0 = vb0 + vcount if vb1 == 1 then vb1 = vcount + 1 end print( vcount, va0, vb1, -1 ) for i = va0, vb1, -1 do i = ( ( i - 1 ) % vcount ) + 1 local k = ( i - 1 ) * 2 local x, y = verts[ k + 1 ], verts[ k + 2 ] x, y = ent:modelToWorld( x, y ) insert( output, x ) insert( output, y ) end end insert( output, px1 ) insert( output, py1 ) end return output end function LinePath2D:projectPoint( x, y ) local ent = self:getEntity() x, y = ent:worldToModel( x, y ) local verts = self.verts local vcount = #verts / 2 local dstMin = math.huge local mx, my local va, vb if not self.looped then vcount = vcount - 1 end for v0 = 1, vcount do local i = ( v0 - 1 ) * 2 local v1 = v0 == vcount and 1 or ( v0 + 1 ) local j = ( v1 - 1 ) * 2 local x1,y1 = verts[ i + 1 ], verts[ i + 2 ] local x2,y2 = verts[ j + 1 ], verts[ j + 2 ] local px,py = projectPointToLine( x1,y1, x2,y2, x,y ) local dst = distanceSqrd( px,py, x,y ) if dst < dstMin then dstMin = dst mx = px my = py va = v0 vb = v1 end end mx, my = ent:modelToWorld( mx, my ) return mx, my, va, vb end -------------------------------------------------------------------- --EDITOR -------------------------------------------------------------------- function LinePath2D:onBuildGizmo() return mock_edit.DrawScriptGizmo() end function LinePath2D:onDrawGizmo( selected ) GIIHelper.setVertexTransform( self:getEntity():getProp( 'render' ) ) if selected then MOAIGfxDevice.setPenColor( hexcolor'#f67bff' ) else MOAIGfxDevice.setPenColor( hexcolor'#b96b99' ) end local verts = self.outputVerts local count = #verts local x1, y1 = verts[ count - 1 ], verts[ count ] MOAIDraw.drawCircle( x1, y1, 10 ) MOAIDraw.drawLine( unpack( self.outputVerts ) ) end
module 'mock' -------------------------------------------------------------------- CLASS: LinePath2D ( Component ) :MODEL{ Field 'verts' :array( 'number' ) :getset( 'Verts' ) :no_edit(); Field 'looped' :boolean() :isset( 'Looped' ); Field 'reverse' :action(); } registerComponent( 'LinePath2D', LinePath2D ) function LinePath2D:__init() self.looped = false self.boundRect = {0,0,0,0} self.outputVerts = {} self:setVerts{ 0,0, 0,100, 100,100, 100, 0 } end function LinePath2D:setLooped( looped ) self.looped = looped self:updateVerts() end function LinePath2D:isLooped() return self.looped end function LinePath2D:onAttach( ent ) -- LinePath2D.__super.onAttach( self, ent ) self:updateVerts() end function LinePath2D:getVerts() return self.verts end function LinePath2D:setVerts( verts ) self.verts = verts self:updateVerts() end function LinePath2D:getStartPoint( world ) local verts = self.verts local x, y = verts[ 1 ], verts[ 2 ] if world then local ent = self:getEntity() ent:forceUpdate() x, y, z = ent:modelToWorld( x, y, 0 ) end return x, y, 0 end function LinePath2D:getEndPoint( world ) local verts = self.verts local count = #verts local x, y = verts[ count-1 ], verts[ count ] if world then local ent = self:getEntity() ent:forceUpdate() x, y, z = ent:modelToWorld( x, y, 0 ) end return x, y, 0 end function LinePath2D:updateVerts() if not self._entity then return end local verts = self.verts local x0,y0,x1,y1 for i = 1, #verts, 2 do local x, y = verts[ i ], verts[ i + 1 ] x0 = x0 and ( x < x0 and x or x0 ) or x y0 = y0 and ( y < y0 and y or y0 ) or y x1 = x1 and ( x > x1 and x or x1 ) or x y1 = y1 and ( y > y1 and y or y1 ) or y end self.boundRect = { x0 or 0, y0 or 0, x1 or 0, y1 or 0 } local outputVerts = { unpack(verts) } if self:isLooped() then table.insert( outputVerts, outputVerts[ 1 ] ) table.insert( outputVerts, outputVerts[ 2 ] ) end local length = 0 local length2 = 0 local x0,y0 for i = 1, #outputVerts, 2 do local x, y = outputVerts[ i ], outputVerts[ i+1 ] if i > 1 then local l2 = distanceSqrd( x0,y0, x,y ) local l = math.sqrt( l2 ) length = length + l length2 = length2 + l2 end x0,y0 = x, y end self.totalLength = length self.totalLength2 = length2 self.outputVerts = outputVerts end function LinePath2D:onDraw() gfx.setPenWidth( self.penWidth ) draw.drawLine( unpack( self.outputVerts ) ) end function LinePath2D:onGetRect() return unpack( self.boundRect ) end function LinePath2D:reverse() self.verts = table.reversed2( self.verts ) self:updateVerts() end local insert = table.insert function LinePath2D:makeSubPath( x0, y0, x1, y1 ) local px0, py0, va0, vb0 = self:projectPoint( x0, y0 ) local px1, py1, va1, vb1 = self:projectPoint( x1, y1 ) local looped = self.looped local output = {} insert( output, px0 ) insert( output, py0 ) local verts = self.verts local vcount = #verts/2 local ent = self:getEntity() ent:forceUpdate() local l = 0 local _x, _y = px0, py0 if va0 > va1 then for i = va0, vb1, -1 do local k = ( i - 1 ) * 2 local x, y = verts[ k + 1 ], verts[ k + 2 ] x, y = ent:modelToWorld( x, y ) insert( output, x ) insert( output, y ) l = l + distance( x, y, _x, _y) _x, _y = x, y end elseif va0 < va1 then for i = vb0, va1, 1 do local k = ( i - 1 ) * 2 local x, y = verts[ k + 1 ], verts[ k + 2 ] x, y = ent:modelToWorld( x, y ) insert( output, x ) insert( output, y ) l = l + distance( x, y, _x, _y) _x, _y = x, y end end insert( output, px1 ) insert( output, py1 ) l = l + distance( px1, py1, _x, _y) if looped and l > self.totalLength/2 then --make reversed path output = {} insert( output, px0 ) insert( output, py0 ) print( va0, va1 ) if va0 > va1 then -- dir+ if vb0 == 1 then vb0 = vcount + 1 end local va1 = va1 + vcount local vb1 = vb1 + vcount print( vcount, vb0, va1, 1 ) for i = vb0, va1, 1 do i = ( ( i - 1 ) % vcount ) + 1 local k = ( i - 1 ) * 2 local x, y = verts[ k + 1 ], verts[ k + 2 ] x, y = ent:modelToWorld( x, y ) insert( output, x ) insert( output, y ) end elseif va0 < va1 then local va0 = va0 + vcount local vb0 = vb0 + vcount if vb1 == 1 then vb1 = vcount + 1 end print( vcount, va0, vb1, -1 ) for i = va0, vb1, -1 do i = ( ( i - 1 ) % vcount ) + 1 local k = ( i - 1 ) * 2 local x, y = verts[ k + 1 ], verts[ k + 2 ] x, y = ent:modelToWorld( x, y ) insert( output, x ) insert( output, y ) end end insert( output, px1 ) insert( output, py1 ) end return output end function LinePath2D:projectPoint( x, y ) local ent = self:getEntity() ent:forceUpdate() x, y = ent:worldToModel( x, y ) local verts = self.verts local vcount = #verts / 2 local dstMin = math.huge local mx, my local va, vb local tail = self.looped and vcount or vcount - 1 for v0 = 1, tail do local i = ( v0 - 1 ) * 2 local v1 = ( v0 == vcount ) and 1 or ( v0 + 1 ) local j = ( v1 - 1 ) * 2 local x1,y1 = verts[ i + 1 ], verts[ i + 2 ] local x2,y2 = verts[ j + 1 ], verts[ j + 2 ] local px,py = projectPointToLine( x1,y1, x2,y2, x,y ) local dst = distanceSqrd( px,py, x,y ) if dst < dstMin then dstMin = dst mx = px my = py va = v0 vb = v1 end end mx, my = ent:modelToWorld( mx, my ) return mx, my, va, vb end -------------------------------------------------------------------- --EDITOR -------------------------------------------------------------------- function LinePath2D:onBuildGizmo() return mock_edit.DrawScriptGizmo() end function LinePath2D:onDrawGizmo( selected ) GIIHelper.setVertexTransform( self:getEntity():getProp( 'render' ) ) if selected then MOAIGfxDevice.setPenColor( hexcolor'#f67bff' ) else MOAIGfxDevice.setPenColor( hexcolor'#b96b99' ) end local verts = self.outputVerts local count = #verts local x1, y1 = verts[ count - 1 ], verts[ count ] MOAIDraw.drawCircle( x1, y1, 10 ) MOAIDraw.drawLine( unpack( self.outputVerts ) ) end
move path fix
move path fix
Lua
mit
tommo/mock
58d287464df637e298a25e66941ed6079085dda0
test_scripts/Polices/build_options/ATF_Start_PTU_retry_sequence.lua
test_scripts/Polices/build_options/ATF_Start_PTU_retry_sequence.lua
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] Local Policy Table retry sequence start -- -- Description: -- In case PoliciesManager does not receive the Updated PT during time defined in -- "timeout_after_x_seconds" section of Local PT, it must start the retry sequence. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- Application not in PT is registered -> PTU is triggered -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[]) -- HMI -> SDL: SDL.GetURLs (<service>) -- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType: PROPRIETARY) -- 2. Performed steps -- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON") -- Expected result: -- Timeout expires and retry sequence started -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[TODO: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local commonPreconditions = require ('user_modules/shared_testcases/commonPreconditions') local testCasesForPolicyTableSnapshot = require ('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') local commonTestCases = require ('user_modules/shared_testcases/commonTestCases') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() commonPreconditions:Connecttest_without_ExitBySDLDisconnect_WithoutOpenConnectionRegisterApp("connecttest_RAI.lua") --[[ General Settings for configuration ]] Test = require('user_modules/connecttest_RAI') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_Connect_mobile() self:connectMobile() end function Test:Precondition_Start_new_session() self.mobileSession = mobile_session.MobileSession( self, self.mobileConnection) self.mobileSession:StartService(7) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:Start_Retry_Sequence_PROPRIETARY() local time_update_needed = {} local time_system_request = {} local endpoints = {} local is_test_fail = false local timeout_preloaded = testCasesForPolicyTableSnapshot:get_data_from_Preloaded_PT("module_config.timeout_after_x_seconds") local seconds_between_retries1 = testCasesForPolicyTableSnapshot:get_data_from_Preloaded_PT("module_config.seconds_between_retries.1") local time_wait = (timeout_preloaded*seconds_between_retries1*1000 + 2000) --first retry sequence local function verify_retry_sequence(occurences) time_update_needed[#time_update_needed + 1] = timestamp() local time_1 = time_update_needed[#time_update_needed] local time_2 = time_system_request[#time_system_request] local timeout = (time_1 - time_2) if( ( timeout > (timeout_preloaded*1000 + 2000) ) or ( timeout < (timeout_preloaded*1000 - 2000) )) then is_test_fail = true commonFunctions:printError("ERROR: timeout for retry sequence "..occurences.." is not as expected: "..timeout_preloaded.."msec(5sec tolerance). real: "..timeout.."ms") else print("timeout is as expected for retry sequence "..occurences..": "..tostring(timeout_preloaded*1000).."ms. real: "..timeout) end return true end self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered", { application = { appName = config.application1.appName } }) :Do(function(_,_) EXPECT_HMICALL("BasicCommunication.PolicyUpdate") :Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS", urls = endpoints} } ) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate" }) EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY", fileType = "JSON"}) :Do(function(_,_) time_system_request[#time_system_request + 1] = timestamp() end) end) end) end) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}, {status = "UPDATING"}, {status = "UPDATE_NEEDED"}):Times(3):Timeout(time_wait) :Do(function(exp_pu, data) if(data.params.status == "UPDATE_NEEDED" and exp_pu.occurences > 1) then verify_retry_sequence(1) end end) commonTestCases:DelayedExp(time_wait) if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirements summary: -- [PolicyTableUpdate] Local Policy Table retry sequence start -- -- Description: -- In case PoliciesManager does not receive the Updated PT during time defined in -- "timeout_after_x_seconds" section of Local PT, it must start the retry sequence. -- 1. Used preconditions -- SDL is built with "-DEXTENDED_POLICY: PROPRIETARY" flag -- Application not in PT is registered -> PTU is triggered -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) -- SDL->HMI:SDL.PolicyUpdate(file, timeout, retry[]) -- HMI -> SDL: SDL.GetURLs (<service>) -- HMI->SDL: BasicCommunication.OnSystemRequest ('url', requestType: PROPRIETARY) -- 2. Performed steps -- SDL->app: OnSystemRequest ('url', requestType:PROPRIETARY, fileType="JSON") -- Expected result: -- Timeout expires and retry sequence started -- SDL->HMI: SDL.OnStatusUpdate(UPDATE_NEEDED) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local commonTestCases = require('user_modules/shared_testcases/commonTestCases') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local testCasesForPolicyTableSnapshot = require('user_modules/shared_testcases/testCasesForPolicyTableSnapshot') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() testCasesForPolicyTable.Delete_Policy_table_snapshot() --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_Sending_PTS_to_mobile_application() local time_update_needed = {} local time_system_request = {} local endpoints = {} local is_test_fail = false local SystemFilesPath = commonFunctions:read_parameter_from_smart_device_link_ini("SystemFilesPath") local PathToSnapshot = commonFunctions:read_parameter_from_smart_device_link_ini("PathToSnapshot") local file_pts = SystemFilesPath.."/"..PathToSnapshot local seconds_between_retries = {} local timeout_pts = testCasesForPolicyTableSnapshot:get_data_from_PTS("module_config.timeout_after_x_seconds") for i = 1, #testCasesForPolicyTableSnapshot.pts_seconds_between_retries do seconds_between_retries[i] = testCasesForPolicyTableSnapshot.pts_seconds_between_retries[i].value end local time_wait = (timeout_pts*seconds_between_retries[1]*1000 + 2000) commonTestCases:DelayedExp(time_wait) -- tolerance 10 sec for i = 1, #testCasesForPolicyTableSnapshot.pts_endpoints do if (testCasesForPolicyTableSnapshot.pts_endpoints[i].service == "0x07") then endpoints[#endpoints + 1] = { url = testCasesForPolicyTableSnapshot.pts_endpoints[i].value, appID = nil} end end local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 }) EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS", urls = endpoints} } ) :Do(function(_,_) self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ requestType = "PROPRIETARY", fileName = "PolicyTableUpdate" }) --first retry sequence local function verify_retry_sequence(occurences) --time_update_needed[#time_update_needed + 1] = testCasesForPolicyTable.time_trigger time_update_needed[#time_update_needed + 1] = timestamp() local time_1 = time_update_needed[#time_update_needed] local time_2 = time_system_request[#time_system_request] local timeout = (time_1 - time_2) if( ( timeout > (timeout_pts*1000 + 2000) ) or ( timeout < (timeout_pts*1000 - 2000) )) then is_test_fail = true commonFunctions:printError("ERROR: timeout for retry sequence "..occurences.." is not as expected: "..timeout_pts.."msec(5sec tolerance). real: "..timeout.."ms") else print("timeout is as expected for retry sequence "..occurences..": "..timeout_pts.."ms. real: "..timeout) end return true end EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY", fileType = "JSON"}) :Do(function(_,_) time_system_request[#time_system_request + 1] = timestamp() end) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATING"}, {status = "UPDATE_NEEDED"}):Times(2):Timeout(64000) :Do(function(exp_pu, data) print(exp_pu.occurences..":"..data.params.status) if(data.params.status == "UPDATE_NEEDED") then verify_retry_sequence(exp_pu.occurences - 1) end end) --TODO(istoimenova): Remove when "[GENIVI] PTU is restarted each 10 sec." is fixed. EXPECT_HMICALL("BasicCommunication.PolicyUpdate"):Times(0) :Do(function(_,data) is_test_fail = true commonFunctions:printError("ERROR: PTU sequence is restarted again!") self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) end) if(is_test_fail == true) then self:FailTestCase("Test is FAILED. See prints.") end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop() 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
cf4327e605788211bd562da6131a761dd9d6d0a8
OS/DiskOS/Libraries/GUI/imageButton.lua
OS/DiskOS/Libraries/GUI/imageButton.lua
local path = select(1,...):sub(1,-(string.len("imageButton")+1)) local base = require(path..".base") --Wrap a function, used to add functions alias names. local function wrap(f) return function(self,...) local args = {pcall(self[f],self,...)} if args[1] then return select(2,unpack(args)) else return error(tostring(args[2])) end end end --Button with a text label local imgbtn = class("DiskOS.GUI.imageButton",base) --Default Values: function imgbtn:initialize(gui,x,y)--,w,h) base.initialize(self,gui,x,y,w,h) --self.fgimg <- The image when the button is not held --self.bgimg <- The image when the button is held --self.img <- The image when using single-image mode. --self.fcol <- The front color in single-image mode. --self.bcol <- The back color in singel-image mode. end function imgbtn:setImage(img,fcol,bcol,nodraw) self.fgimg, self.bgimg = nil, nil self.img, self.fcol, self.bcol = img or self.img, fcol or self.fcol, bcol or self.bcol if self.img and type(self.img) ~= "number" then self:setSize(self.img:size(),true) end if not nodraw then self:draw() end return self end function imgbtn:setFGImage(img,nodraw) self.img, self.fcol, self.bcol = nil,nil,nil self.fgimg = img if self.fgimg and type(self.fgimg) ~= "number" then self:setSize(self.fgimg:size(),true) end if not nodraw then self:draw() end return self end function imgbtn:setBGImage(img,nodraw) self.img, self.fcol, self.bcol = nil,nil,nil self.bgimg = img if self.bgimg and type(self.bgimg) ~= "number" then self:setSize(self.bgimg:size(),true) end if not nodraw then self:draw() end return self end function imgbtn:getImage() return self.img, self.fcol, self.bcol end function imgbtn:getFGImage() return self.fgimg end function imgbtn:getBGImage() return self.bgimg end --Draw the imgbtn function imgbtn:draw() local fgcol = self:getFGColor() local bgcol = self:getBGColor() local fgimg = self:getFGImage() local bgimg = self:getBGImage() local img, fcol, bcol = self:getImage() local sheet = self:sheet() local x,y = self:getPosition() local down = self:isDown() if down then fgcol, bgcol = bgcol, fgcol end if img then --Single-image Mode pushPalette() pal(fcol,bgcol) pal(bcol,fgcol) if type(img) == "number" then --SpriteSheet mode sheet:draw(img,x,y) else --Normal image img:draw(x,y) end popPalette() else --Multiple images local i = down and bgimg or fgimg if type(i) == "number" then --SpriteSheet mode sheet:draw(i,x,y) else --Normal image i:draw(x,y) end end end --Internal functions-- --Handle cursor press function imgbtn:pressed(x,y) if isInRect(x,y,{self:getRect()}) then self:draw() --Update the button return true end end --Handle cursor release function imgbtn:released(x,y) if isInRect(x,y,{self:getRect()}) then if self.onclick then self:onclick() end end self:draw() --Update the button end --Provide prefered cursor function imgbtn:cursor(x,y) local down = self:isDown() if isInRect(x,y,{self:getRect()}) then if down then return "handpress" else return "handrelease" end end end return imgbtn
local path = select(1,...):sub(1,-(string.len("imageButton")+1)) local base = require(path..".base") --Wrap a function, used to add functions alias names. local function wrap(f) return function(self,...) local args = {pcall(self[f],self,...)} if args[1] then return select(2,unpack(args)) else return error(tostring(args[2])) end end end --Button with a text label local imgbtn = class("DiskOS.GUI.imageButton",base) --Default Values: function imgbtn:initialize(gui,x,y)--,w,h) base.initialize(self,gui,x,y,w,h) --self.fgimg <- The image when the button is not held --self.bgimg <- The image when the button is held --self.img <- The image when using single-image mode. --self.fcol <- The front color in single-image mode. --self.bcol <- The back color in singel-image mode. end function imgbtn:setImage(img,fcol,bcol,nodraw) self.fgimg, self.bgimg = nil, nil self.img, self.fcol, self.bcol = img or self.img, fcol or self.fcol, bcol or self.bcol if self.img and type(self.img) ~= "number" then local imgW, imgH = self.img:size() self:setSize(imgW,imgH,true) end if not nodraw then self:draw() end return self end function imgbtn:setFGImage(img,nodraw) self.img, self.fcol, self.bcol = nil,nil,nil self.fgimg = img if self.fgimg and type(self.fgimg) ~= "number" then local imgW, imgH = self.fgimg:size() self:setSize(imgW,imgH,true) end if not nodraw then self:draw() end return self end function imgbtn:setBGImage(img,nodraw) self.img, self.fcol, self.bcol = nil,nil,nil self.bgimg = img if self.bgimg and type(self.bgimg) ~= "number" then local imgW, imgH = self.bgimg:size() self:setSize(imgW,imgH,true) end if not nodraw then self:draw() end return self end function imgbtn:getImage() return self.img, self.fcol, self.bcol end function imgbtn:getFGImage() return self.fgimg end function imgbtn:getBGImage() return self.bgimg end --Draw the imgbtn function imgbtn:draw() local fgcol = self:getFGColor() local bgcol = self:getBGColor() local fgimg = self:getFGImage() local bgimg = self:getBGImage() local img, fcol, bcol = self:getImage() local sheet = self:getSheet() local x,y = self:getPosition() local down = self:isDown() if down then fgcol, bgcol = bgcol, fgcol end if img then --Single-image Mode pushPalette() pal(fcol,bgcol) pal(bcol,fgcol) if type(img) == "number" then --SpriteSheet mode sheet:draw(img,x,y) else --Normal image img:draw(x,y) end popPalette() else --Multiple images local i = down and bgimg or fgimg if type(i) == "number" then --SpriteSheet mode sheet:draw(i,x,y) else --Normal image i:draw(x,y) end end end --Internal functions-- --Handle cursor press function imgbtn:pressed(x,y) if isInRect(x,y,{self:getRect()}) then self:draw() --Update the button return true end end --Handle cursor release function imgbtn:released(x,y) if isInRect(x,y,{self:getRect()}) then if self.onclick then self:onclick() end end self:draw() --Update the button end --Provide prefered cursor function imgbtn:cursor(x,y) local down = self:isDown() if isInRect(x,y,{self:getRect()}) then if down then return "handpress" else return "handrelease" end end end return imgbtn
Bugfix image crash
Bugfix image crash
Lua
mit
RamiLego4Game/LIKO-12
e33752b08673a0622ff18933f9a182df9d9217ad
api/elasticsearch/client.lua
api/elasticsearch/client.lua
local oo = require "loop.base" require "broker" ElasticsearchBroker = oo.class({}, Broker) local DEFAULT_ES_PORT = 9200 local DEFAULT_ES_SERVER = "127.0.0.1" local DEFAULT_ES_PROTOCOL = PROTOCOLS.HTTP local request_path = "%s/_search" function ElasticsearchBroker:__init(server, port, protocol) server = server or DEFAULT_ES_SERVER port = port or DEFAULT_ES_PORT protocol = protocol or DEFAULT_ES_PROTOCOL local broker = Broker(server, port, protocol) local self = oo.rawnew(self, {}) self.broker = broker return self end local count_path = "%s/_count" function ElasticsearchBroker:count(index) return self.broker:request(METHOD.GET, count_path:format(index)) end function ElasticsearchBroker:dispatch(request) if (#request.data.aggs == 0) then request.data.aggs = nil end return self.broker:request(METHOD.POST, request_path:format(request.index), request.data) end Request = oo.class{} function Request:__init(index) if (type(index) ~= "string") then error("\'index\' should be a string, instead " .. type(index) .. " was provided") end local self = oo.rawnew(self, {}) self.index = index self.data = {} self.data.size = 0 self.data.aggs = {} return self end -- Average aggregation function Request:average(field, name) self.data.aggs = self.data.aggs or {} self.data.aggs[name] = { avg = { field = field } } end -- Terms aggregation function Request:terms(field, name) self.data.aggs = self.data.aggs or {} self.data.aggs[name] = { terms = { field = field } } end function Request:exists(field) self.data.filter = { exists = { field = field } } end function Request:stats(field, name) self.data.aggs[name] = { stats = { field = field } } end function Request:filter(field, value) self.data.query = { filtered = { filter = { term = { [field] = value } } } } end
local oo = require "loop.base" require "broker" ElasticsearchBroker = oo.class({}, Broker) local DEFAULT_ES_PORT = 9200 local DEFAULT_ES_SERVER = "127.0.0.1" local DEFAULT_ES_PROTOCOL = PROTOCOLS.HTTP local request_path = "%s/_search" function ElasticsearchBroker:__init(server, port, protocol) server = server or DEFAULT_ES_SERVER port = port or DEFAULT_ES_PORT protocol = protocol or DEFAULT_ES_PROTOCOL local broker = Broker(server, port, protocol) local self = oo.rawnew(self, {}) self.broker = broker return self end local count_path = "%s/_count" function ElasticsearchBroker:count(index) return self.broker:request(METHOD.GET, count_path:format(index)) end function ElasticsearchBroker:dispatch(request) local has_aggs = false for k, v in pairs(request.data.aggs) do has_aggs = true; break end if (not has_aggs) then request.data.aggs = nil end return self.broker:request(METHOD.POST, request_path:format(request.index), request.data) end Request = oo.class{} function Request:__init(index) if (type(index) ~= "string") then error("\'index\' should be a string, instead " .. type(index) .. " was provided") end local self = oo.rawnew(self, {}) self.index = index self.data = {} self.data.size = 0 self.data.aggs = {} return self end -- Average aggregation function Request:average(field, name) self.data.aggs = self.data.aggs or {} self.data.aggs[name] = { avg = { field = field } } end -- Terms aggregation function Request:terms(field, name) self.data.aggs = self.data.aggs or {} self.data.aggs[name] = { terms = { field = field } } end function Request:exists(field) self.data.filter = { exists = { field = field } } end function Request:stats(field, name) self.data.aggs[name] = { stats = { field = field } } end function Request:filter(field, value) self.data.query = { filtered = { filter = { term = { [field] = value } } } } end
Fixing aggs dictionary key count
Fixing aggs dictionary key count
Lua
apache-2.0
airtonjal/Lua-JSON-Tester
58d36c482a29916d4131847852c4cfe2b1c76e03
test_scripts/Polices/build_options/006_ATF_P_TC_Policy_Table_Update_Trigger_After_N_Kilometers_HTTP.lua
test_scripts/Polices/build_options/006_ATF_P_TC_Policy_Table_Update_Trigger_After_N_Kilometers_HTTP.lua
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PTU] Trigger: kilometers -- -- Description: -- If SDL is subscribed via SubscribeVehicleData(odometer) right after ignition on, SDL gets OnVehcileData ("odometer") notification from HMI -- and the difference between current "odometer" value_2 and "odometer" value_1 when the previous UpdatedPollicyTable was applied is equal or -- greater than to the value of "exchange_after_x_kilometers" field ("module_config" section) of policies database, SDL must trigger a -- PolicyTableUpdate sequence -- 1. Used preconditions: -- SDL is built with "-DEXTENDED_POLICY: HTTP" flag -- The odometer value was "1234" when previous PTU was successfully applied. -- Policies DataBase contains "exchange_after_x_kilometers" = 1000 -- 2. Performed steps: -- SDL->HMI: Vehicleinfo.SubscribeVehicleData ("odometer") -- HMI->SDL: Vehicleinfo.SubscribeVehicleData (SUCCESS) -- user sets odometer to 2200 -- HMI->SDL: Vehicleinfo.OnVehicleData ("odometer:2200") -- SDL: checks wether amount of kilometers sinse previous update is equal or greater "exchange_after_x_kilometers" -- user sets odometer to 2250 -- HMI->SDL: Vehicleinfo.OnVehicleData ("odometer:2250") -- SDL: checks wether amount of kilometers sinse previous update is equal or greater "exchange_after_x_kilometers" -- SDL->HMI: OnStatusUpdate (UPDATE_NEEDED) -- -- Expected result: -- PTU flow started --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --ToDo: Should be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ Required Shared libraries ]] local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local commonSteps = require ('user_modules/shared_testcases/commonSteps') local testCasesForPolicyTable = require ('user_modules/shared_testcases/testCasesForPolicyTable') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFiles() commonSteps:DeletePolicyTable() --[[ Local Functions ]] local function UpdatePolicy() local PermissionForSubscribeVehicleData = [[ "SubscribeVehicleData": { "hmi_levels": [ "BACKGROUND", "FULL", "LIMITED" ], "parameters" : ["odometer"] } ]].. ", \n" local PermissionForOnVehicleData = [[ "OnVehicleData": { "hmi_levels": [ "BACKGROUND", "FULL", "LIMITED" ], "parameters" : ["odometer"] } ]].. ", \n" local PermissionLinesForBase4 = PermissionForSubscribeVehicleData..PermissionForOnVehicleData local PTName = testCasesForPolicyTable:createPolicyTableFile_temp(PermissionLinesForBase4, nil, nil, {"SubscribeVehicleData","OnVehicleData"}) testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt(PTName) end UpdatePolicy() --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require("user_modules/AppTypes") require('mobile_session') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_Activate_App_Start_PTU() local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications["Test Application"], level = "FULL"}) EXPECT_HMIRESPONSE(RequestId) :Do(function(_,data) if data.result.isSDLAllowed ~= true then RequestId = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}}) EXPECT_HMIRESPONSE(RequestId) :Do(function(_,_) self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}}) EXPECT_HMICALL("BasicCommunication.ActivateApp") :Do(function(_,data2) self.hmiConnection:SendResponse(data2.id,"BasicCommunication.ActivateApp", "SUCCESS", {}) end) :Times(2) end) EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN" }) end end) end function Test:Preconditions_Set_Odometer_Value1() local cidVehicle = self.mobileSession:SendRPC("SubscribeVehicleData", {odometer = true}) EXPECT_HMICALL("VehicleInfo.SubscribeVehicleData") :Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) EXPECT_RESPONSE(cidVehicle, { success = true, resultCode = "SUCCESS" }) :Do(function() self.hmiConnection:SendNotification("VehicleInfo.OnVehicleData", {odometer = 1234}) EXPECT_NOTIFICATION("OnVehicleData", {odometer = 1234}) end) end function Test.Precondition_Update_Policy_With_New_Exchange_After_X_Kilometers_Value() commonFunctions:check_ptu_sequence_fully(Test, "files/jsons/Policies/Policy_Table_Update/odometer_ptu.json", "PolicyTableUpdate") end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_Set_Odometer_Value_NO_PTU_Is_Triggered() self.hmiConnection:SendNotification("VehicleInfo.OnVehicleData", {odometer = 2200}) EXPECT_NOTIFICATION("OnVehicleData", {odometer = 2200}) EXPECT_HMICALL("BasicCommunication.PolicyUpdate"):Times(0) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}):Times(0) end function Test.TestStep_Set_Odometer_Value_And_Check_That_PTU_Is_Triggered() commonFunctions:trigger_ptu_by_odometer(Test) end function Test.TestStep_Update_Policy_With_New_Exchange_After_X_Kilometers_Value() commonFunctions:check_ptu_sequence_fully(Test, "files/jsons/Policies/Policy_Table_Update/odometer_ptu.json", "PolicyTableUpdate") end --[[ Postcondition ]] commonFunctions:newTestCasesGroup("Postconditions") testCasesForPolicyTable:Restore_preloaded_pt() function Test.Postcondition_Stop() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PTU] Trigger: kilometers -- -- Description: -- If SDL is subscribed via SubscribeVehicleData(odometer) right after ignition on, SDL gets OnVehcileData ("odometer") notification from HMI -- and the difference between current "odometer" value_2 and "odometer" value_1 when the previous UpdatedPollicyTable was applied is equal or -- greater than to the value of "exchange_after_x_kilometers" field ("module_config" section) of policies database, SDL must trigger a -- PolicyTableUpdate sequence -- 1. Used preconditions: -- SDL is built with "-DEXTENDED_POLICY: HTTP" flag -- The odometer value was "1234" when previous PTU was successfully applied. -- Policies DataBase contains "exchange_after_x_kilometers" = 1000 -- 2. Performed steps: -- SDL->HMI: Vehicleinfo.SubscribeVehicleData ("odometer") -- HMI->SDL: Vehicleinfo.SubscribeVehicleData (SUCCESS) -- user sets odometer to 2200 -- HMI->SDL: Vehicleinfo.OnVehicleData ("odometer:2200") -- SDL: checks wether amount of kilometers sinse previous update is equal or greater "exchange_after_x_kilometers" -- user sets odometer to 2250 -- HMI->SDL: Vehicleinfo.OnVehicleData ("odometer:2250") -- SDL: checks wether amount of kilometers sinse previous update is equal or greater "exchange_after_x_kilometers" -- SDL->HMI: OnStatusUpdate (UPDATE_NEEDED) -- -- Expected result: -- PTU flow started --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --ToDo: Should be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ Required Shared libraries ]] local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local commonSteps = require ('user_modules/shared_testcases/commonSteps') local testCasesForPolicyTable = require ('user_modules/shared_testcases/testCasesForPolicyTable') --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFiles() commonSteps:DeletePolicyTable() --[[ Local Functions ]] local function UpdatePolicy() local PermissionForSubscribeVehicleData = [[ "SubscribeVehicleData": { "hmi_levels": [ "BACKGROUND", "FULL", "LIMITED" ], "parameters" : ["odometer"] } ]].. ", \n" local PermissionForOnVehicleData = [[ "OnVehicleData": { "hmi_levels": [ "BACKGROUND", "FULL", "LIMITED" ], "parameters" : ["odometer"] } ]].. ", \n" local PermissionLinesForBase4 = PermissionForSubscribeVehicleData..PermissionForOnVehicleData local PTName = testCasesForPolicyTable:createPolicyTableFile_temp(PermissionLinesForBase4, nil, nil, {"SubscribeVehicleData","OnVehicleData"}) testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt(PTName) end UpdatePolicy() --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require("user_modules/AppTypes") require('mobile_session') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test:Precondition_Activate_App_Start_PTU() local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications["Test Application"], level = "FULL"}) EXPECT_HMIRESPONSE(RequestId) :Do(function(_,data) if data.result.isSDLAllowed ~= true then RequestId = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}}) EXPECT_HMIRESPONSE(RequestId) :Do(function(_,_) self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}}) EXPECT_HMICALL("BasicCommunication.ActivateApp") :Do(function(_,data2) self.hmiConnection:SendResponse(data2.id,"BasicCommunication.ActivateApp", "SUCCESS", {}) end) :Times(2) end) EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN" }) end end) end function Test:Preconditions_Set_Odometer_Value1() local cid_vehicle = self.mobileSession:SendRPC("SubscribeVehicleData", {odometer = true}) EXPECT_HMICALL("VehicleInfo.SubscribeVehicleData") :Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) EXPECT_RESPONSE(cid_vehicle, { success = true, resultCode = "SUCCESS" }) end function Test:Precondition_Update_Policy_With_New_Exchange_After_X_Kilometers_Value() local ptu_file_name = "files/jsons/Policies/Policy_Table_Update/exchange_after_1000_kilometers_ptu.json" local corId = self.mobileSession:SendRPC("SystemRequest", { requestType = "HTTP", fileName = "PolicyTableUpdate" }, ptu_file_name) EXPECT_RESPONSE(corId, { success = true, resultCode = "SUCCESS" }) EXPECT_HMICALL("VehicleInfo.GetVehicleData", { odometer = true }) :Do(function(_, d) self.hmiConnection:SendResponse(d.id, d.method, "SUCCESS", { odometer = 1234 }) end) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep_Set_Odometer_Value_NO_PTU_Is_Triggered() self.hmiConnection:SendNotification("VehicleInfo.OnVehicleData", {odometer = 2200}) EXPECT_NOTIFICATION("OnVehicleData", {odometer = 2200}) EXPECT_HMICALL("BasicCommunication.PolicyUpdate"):Times(0) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}):Times(0) end function Test:TestStep_Set_Odometer_Value_And_Check_That_PTU_Is_Triggered() self.hmiConnection:SendNotification("VehicleInfo.OnVehicleData", {odometer = 2250}) EXPECT_NOTIFICATION("OnVehicleData", {odometer = 2250}) -- self.mobileSession:ExpectNotification("OnSystemRequest", { requestType = "HTTP" }) EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}) end --[[ Postcondition ]] commonFunctions:newTestCasesGroup("Postconditions") testCasesForPolicyTable:Restore_preloaded_pt() function Test.Postcondition_Stop() StopSDL() end return Test
Fix issues in script after clarification
Fix issues in script after clarification
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
ea62b0b94566e59e06c0801483e9c2dcef02d1ec
spec/plugins/logging_spec.lua
spec/plugins/logging_spec.lua
local IO = require "kong.tools.io" local uuid = require "uuid" local cjson = require "cjson" local stringy = require "stringy" local spec_helper = require "spec.spec_helpers" local http_client = require "kong.tools.http_client" -- This is important to seed the UUID generator uuid.seed() local STUB_GET_URL = spec_helper.STUB_GET_URL local TCP_PORT = 20777 local UDP_PORT = 20778 local HTTP_PORT = 20779 local FILE_LOG_PATH = spec_helper.get_env().configuration.nginx_working_dir.."/file_log_spec_output.log" local function create_mock_bin() local res, status = http_client.post("http://mockbin.org/bin/create", '{ "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "headers": [], "cookies": [], "content": { "mimeType" : "application/json" }, "redirectURL": "", "headersSize": 0, "bodySize": 0 }', { ["content-type"] = "application/json" }) assert.are.equal(201, status) return res:sub(2, res:len() - 1) end local mock_bin = create_mock_bin() describe("Logging Plugins", function() setup(function() spec_helper.prepare_db() spec_helper.insert_fixtures { api = { { name = "tests tcp logging", public_dns = "tcp_logging.com", target_url = "http://mockbin.com" }, { name = "tests tcp logging2", public_dns = "tcp_logging2.com", target_url = "http://localhost:"..HTTP_PORT }, { name = "tests udp logging", public_dns = "udp_logging.com", target_url = "http://mockbin.com" }, { name = "tests http logging", public_dns = "http_logging.com", target_url = "http://mockbin.com" }, { name = "tests https logging", public_dns = "https_logging.com", target_url = "http://mockbin.com" }, { name = "tests file logging", public_dns = "file_logging.com", target_url = "http://mockbin.com" } }, plugin_configuration = { { name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 1 }, { name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 2 }, { name = "udplog", value = { host = "127.0.0.1", port = UDP_PORT }, __api = 3 }, { name = "httplog", value = { http_endpoint = "http://localhost:"..HTTP_PORT }, __api = 4 }, { name = "httplog", value = { http_endpoint = "https://mockbin.org/bin/"..mock_bin }, __api = 5 }, { name = "filelog", value = { path = FILE_LOG_PATH }, __api = 6 } } } spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) it("should log to TCP", function() local thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "tcp_logging.com" }) assert.are.equal(200, status) -- Getting back the TCP server input local ok, res = thread:join() assert.truthy(ok) assert.truthy(res) -- Making sure it's alright local log_message = cjson.decode(res) assert.are.same("127.0.0.1", log_message.client_ip) end) it("should log proper latencies", function() local http_thread = spec_helper.start_http_server(HTTP_PORT) -- Starting the mock TCP server local tcp_thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server -- Making the request local _, status = http_client.get(spec_helper.PROXY_URL.."/delay", nil, { host = "tcp_logging2.com" }) assert.are.equal(200, status) -- Getting back the TCP server input local ok, res = tcp_thread:join() assert.truthy(ok) assert.truthy(res) -- Making sure it's alright local log_message = cjson.decode(res) assert.truthy(log_message.latencies.proxy < 3000) assert.truthy(log_message.latencies.kong < 20) assert.truthy(log_message.latencies.request >= log_message.latencies.kong + log_message.latencies.proxy) http_thread:join() end) it("should log to UDP", function() local thread = spec_helper.start_udp_server(UDP_PORT) -- Starting the mock TCP server -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "udp_logging.com" }) assert.are.equal(200, status) -- Getting back the TCP server input local ok, res = thread:join() assert.truthy(ok) assert.truthy(res) -- Making sure it's alright local log_message = cjson.decode(res) assert.are.same("127.0.0.1", log_message.client_ip) end) it("should log to HTTP", function() local thread = spec_helper.start_http_server(HTTP_PORT) -- Starting the mock TCP server -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "http_logging.com" }) assert.are.equal(200, status) -- Getting back the TCP server input local ok, res = thread:join() assert.truthy(ok) assert.truthy(res) -- Making sure it's alright assert.are.same("POST / HTTP/1.1", res[1]) local log_message = cjson.decode(res[7]) assert.are.same("127.0.0.1", log_message.client_ip) end) it("should log to HTTPs", function() -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "https_logging.com" }) assert.are.equal(200, status) local res, status, body repeat res, status = http_client.get("http://mockbin.org/bin/"..mock_bin.."/log", nil, { accept = "application/json" }) assert.are.equal(200, status) body = cjson.decode(res) os.execute("sleep 0.2") until(#body.log.entries > 0) assert.are.equal(1, #body.log.entries) local log_message = cjson.decode(body.log.entries[1].request.postData.text) -- Making sure it's alright assert.are.same("127.0.0.1", log_message.client_ip) end) it("should log to file", function() os.remove(FILE_LOG_PATH) local uuid = string.gsub(uuid(), "-", "") -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "file_logging.com", file_log_uuid = uuid } ) assert.are.equal(200, status) while not (IO.file_exists(FILE_LOG_PATH) and IO.file_size(FILE_LOG_PATH) > 0) do -- Wait for the file to be created, and for the log to be appended end local file_log = IO.read_file(FILE_LOG_PATH) local log_message = cjson.decode(stringy.strip(file_log)) assert.are.same("127.0.0.1", log_message.client_ip) assert.are.same(uuid, log_message.request.headers.file_log_uuid) end) end)
local IO = require "kong.tools.io" local uuid = require "uuid" local cjson = require "cjson" local stringy = require "stringy" local spec_helper = require "spec.spec_helpers" local http_client = require "kong.tools.http_client" -- This is important to seed the UUID generator uuid.seed() local STUB_GET_URL = spec_helper.STUB_GET_URL local TCP_PORT = 20777 local UDP_PORT = 20778 local HTTP_PORT = 20779 local HTTP_DELAY_PORT = 20780 local FILE_LOG_PATH = spec_helper.get_env().configuration.nginx_working_dir.."/file_log_spec_output.log" local function create_mock_bin() local res, status = http_client.post("http://mockbin.org/bin/create", '{ "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "headers": [], "cookies": [], "content": { "mimeType" : "application/json" }, "redirectURL": "", "headersSize": 0, "bodySize": 0 }', { ["content-type"] = "application/json" }) assert.are.equal(201, status) return res:sub(2, res:len() - 1) end local mock_bin = create_mock_bin() describe("Logging Plugins", function() setup(function() spec_helper.prepare_db() spec_helper.insert_fixtures { api = { { name = "tests tcp logging", public_dns = "tcp_logging.com", target_url = "http://mockbin.com" }, { name = "tests tcp logging2", public_dns = "tcp_logging2.com", target_url = "http://localhost:"..HTTP_DELAY_PORT }, { name = "tests udp logging", public_dns = "udp_logging.com", target_url = "http://mockbin.com" }, { name = "tests http logging", public_dns = "http_logging.com", target_url = "http://mockbin.com" }, { name = "tests https logging", public_dns = "https_logging.com", target_url = "http://mockbin.com" }, { name = "tests file logging", public_dns = "file_logging.com", target_url = "http://mockbin.com" } }, plugin_configuration = { { name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 1 }, { name = "tcplog", value = { host = "127.0.0.1", port = TCP_PORT }, __api = 2 }, { name = "udplog", value = { host = "127.0.0.1", port = UDP_PORT }, __api = 3 }, { name = "httplog", value = { http_endpoint = "http://localhost:"..HTTP_PORT }, __api = 4 }, { name = "httplog", value = { http_endpoint = "https://mockbin.org/bin/"..mock_bin }, __api = 5 }, { name = "filelog", value = { path = FILE_LOG_PATH }, __api = 6 } } } spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) it("should log to TCP", function() local thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "tcp_logging.com" }) assert.are.equal(200, status) -- Getting back the TCP server input local ok, res = thread:join() assert.truthy(ok) assert.truthy(res) -- Making sure it's alright local log_message = cjson.decode(res) assert.are.same("127.0.0.1", log_message.client_ip) end) it("should log proper latencies", function() local http_thread = spec_helper.start_http_server(HTTP_DELAY_PORT) -- Starting the mock TCP server local tcp_thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server -- Making the request local _, status = http_client.get(spec_helper.PROXY_URL.."/delay", nil, { host = "tcp_logging2.com" }) assert.are.equal(200, status) -- Getting back the TCP server input local ok, res = tcp_thread:join() assert.truthy(ok) assert.truthy(res) -- Making sure it's alright local log_message = cjson.decode(res) assert.truthy(log_message.latencies.proxy < 3000) assert.truthy(log_message.latencies.kong < 100) assert.truthy(log_message.latencies.request >= log_message.latencies.kong + log_message.latencies.proxy) http_thread:join() end) it("should log to UDP", function() local thread = spec_helper.start_udp_server(UDP_PORT) -- Starting the mock TCP server -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "udp_logging.com" }) assert.are.equal(200, status) -- Getting back the TCP server input local ok, res = thread:join() assert.truthy(ok) assert.truthy(res) -- Making sure it's alright local log_message = cjson.decode(res) assert.are.same("127.0.0.1", log_message.client_ip) end) it("should log to HTTP", function() local thread = spec_helper.start_http_server(HTTP_PORT) -- Starting the mock TCP server -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "http_logging.com" }) assert.are.equal(200, status) -- Getting back the TCP server input local ok, res = thread:join() assert.truthy(ok) assert.truthy(res) -- Making sure it's alright assert.are.same("POST / HTTP/1.1", res[1]) local log_message = cjson.decode(res[7]) assert.are.same("127.0.0.1", log_message.client_ip) end) it("should log to HTTPs", function() -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "https_logging.com" }) assert.are.equal(200, status) local res, status, body repeat res, status = http_client.get("http://mockbin.org/bin/"..mock_bin.."/log", nil, { accept = "application/json" }) assert.are.equal(200, status) body = cjson.decode(res) os.execute("sleep 0.2") until(#body.log.entries > 0) assert.are.equal(1, #body.log.entries) local log_message = cjson.decode(body.log.entries[1].request.postData.text) -- Making sure it's alright assert.are.same("127.0.0.1", log_message.client_ip) end) it("should log to file", function() os.remove(FILE_LOG_PATH) local uuid = string.gsub(uuid(), "-", "") -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "file_logging.com", file_log_uuid = uuid } ) assert.are.equal(200, status) while not (IO.file_exists(FILE_LOG_PATH) and IO.file_size(FILE_LOG_PATH) > 0) do -- Wait for the file to be created, and for the log to be appended end local file_log = IO.read_file(FILE_LOG_PATH) local log_message = cjson.decode(stringy.strip(file_log)) assert.are.same("127.0.0.1", log_message.client_ip) assert.are.same(uuid, log_message.request.headers.file_log_uuid) end) end)
Fixing tests
Fixing tests Former-commit-id: fb1c0ee051969877c8289444db7d064bfe094e7c
Lua
apache-2.0
ind9/kong,shiprabehera/kong,ejoncas/kong,rafael/kong,Kong/kong,smanolache/kong,jerizm/kong,Mashape/kong,Kong/kong,isdom/kong,isdom/kong,kyroskoh/kong,jebenexer/kong,streamdataio/kong,akh00/kong,ccyphers/kong,ind9/kong,rafael/kong,ajayk/kong,kyroskoh/kong,li-wl/kong,icyxp/kong,salazar/kong,vzaramel/kong,ejoncas/kong,Vermeille/kong,streamdataio/kong,beauli/kong,vzaramel/kong,xvaara/kong,Kong/kong
b3a046edacb223bf2209dfd70131c132efb94a97
src/luarocks/test/command.lua
src/luarocks/test/command.lua
local command = {} local fs = require("luarocks.fs") local dir = require("luarocks.dir") local cfg = require("luarocks.core.cfg") local unpack = table.unpack or unpack function command.detect_type() if fs.exists("test.lua") then return true end return false end function command.run_tests(test, args) if not test then test = { script = "test.lua" } end if not test.script and not test.command then test.script = "test.lua" end if type(test.flags) == "table" then -- insert any flags given in test.flags at the front of args for i = 1, #test.flags do table.insert(args, i, test.flags[i]) end end if test.script then if not fs.exists(test.script) then return nil, "Test script " .. test.script .. " does not exist" end local lua = fs.Q(dir.path(cfg.variables["LUA_BINDIR"], cfg.lua_interpreter)) -- get lua interpreter configured return fs.execute(lua, test.script, unpack(args)) elseif test.command then return fs.execute(test.command, unpack(args)) end end return command
local command = {} local fs = require("luarocks.fs") local dir = require("luarocks.dir") local cfg = require("luarocks.core.cfg") local unpack = table.unpack or unpack function command.detect_type() if fs.exists("test.lua") then return true end return false end function command.run_tests(test, args) if not test then test = { script = "test.lua" } end if not test.script and not test.command then test.script = "test.lua" end if type(test.flags) == "table" then -- insert any flags given in test.flags at the front of args for i = 1, #test.flags do table.insert(args, i, test.flags[i]) end end local ok if test.script then if not fs.exists(test.script) then return nil, "Test script " .. test.script .. " does not exist" end local lua = fs.Q(dir.path(cfg.variables["LUA_BINDIR"], cfg.lua_interpreter)) -- get lua interpreter configured ok = fs.execute(lua, test.script, unpack(args)) elseif test.command then ok = fs.execute(test.command, unpack(args)) end if ok then return true else return nil, "tests failed with non-zero exit code" end end return command
test: fix reporting failures on 'command' backend
test: fix reporting failures on 'command' backend
Lua
mit
luarocks/luarocks,keplerproject/luarocks,keplerproject/luarocks,tarantool/luarocks,luarocks/luarocks,tarantool/luarocks,tarantool/luarocks,luarocks/luarocks,keplerproject/luarocks,keplerproject/luarocks
90e16f60354646e78fa68175b3d1ab2dca5e6c25
pythonlua/luainit.lua
pythonlua/luainit.lua
--[[ Begin the lua pythonization. --]] local string_meta = getmetatable("") string_meta.__add = function(v1, v2) if type(v1) == "string" and type(v2) == "string" then return v1 .. v2 end return v1 + v2 end local str = tostring local int = tonumber local function len(t) return #t end local function range(from, to, step) assert(from ~= nil) if to == nil then to = from from = 1 end if step == nil then step = to > from and 1 or -1 end local i = from return function() ret = i if (step > 0 and i > to) or (step < 0 and i < to) then return nil end i = i + step return ret end end local function list(t) local methods = {} methods.append = function(value) table.insert(t, value) end local iterator_index = nil setmetatable(t, { __index = function(self, index) if type(index) == "number" and index < 0 then return rawget(t, #t + index + 1) end return methods[index] end, __call = function(self, _, idx) if idx == nil and iterator_index ~= nil then iterator_index = nil end local v = nil iterator_index, v = next(t, iterator_index) return v end, }) t.is_list = true return t end function dict(t) local methods = {} methods.items = function() return pairs(t) end local key_index = nil setmetatable(t, { __index = methods, __call = function(self, _, idx) if idx == nil and key_index ~= nil then key_index = nil end key_index, _ = next(t, key_index) return key_index end, }) t.is_dict = true return t end function enumerate(t, start) start = start or 1 local i, v = next(t, nil) return function() local index, value = i, v i, v = next(t, i) if index == nil then return nil end return index + start - 1, value end end local function staticmethod(old_fun) local wrapper = function(first, ...) return old_fun(...) end return wrapper end local function operator_in(item, items) if type(items) == "table" then for v in items do if v == item then return true end end elseif type(items) == "string" and type(item) == "string" then return string.find(items, item, 1, true) ~= nil end return false end -- Lua classes local function class(class_init, bases) bases = bases or {} local c = {} for _, base in ipairs(bases) do for k, v in pairs(base) do c[k] = v end end c._bases = bases c = class_init(c) local mt = getmetatable(c) or {} mt.__call = function(_, ...) local object = {} setmetatable(object, { __index = function(tbl, idx) local method = c[idx] if type(method) == "function" then return function(...) return c[idx](object, ...) end end return method end, }) if type(object.__init__) == "function" then object.__init__(...) end return object end setmetatable(c, mt) return c end --[[ End of the lua pythonization. --]]
--[[ Begin the lua pythonization. --]] local string_meta = getmetatable("") string_meta.__add = function(v1, v2) if type(v1) == "string" and type(v2) == "string" then return v1 .. v2 end return v1 + v2 end local str = tostring local int = tonumber local function len(t) if type(t._data) == "table" then return #t._data end return #t end local function range(from, to, step) assert(from ~= nil) if to == nil then to = from from = 1 end if step == nil then step = to > from and 1 or -1 end local i = from return function() ret = i if (step > 0 and i > to) or (step < 0 and i < to) then return nil end i = i + step return ret end end local function list(t) local result = {} local methods = {} methods.append = function(value) table.insert(result._data, value) end local iterator_index = nil setmetatable(result, { __index = function(self, index) if type(index) == "number" and index < 0 then return rawget(result._data, #result._data + index + 1) end return methods[index] end, __call = function(self, _, idx) if idx == nil and iterator_index ~= nil then iterator_index = nil end local v = nil iterator_index, v = next(result._data, iterator_index) return v end, }) result.is_list = true result._data = {} for _, v in ipairs(t) do table.insert(result._data, v) end return result end function dict(t) local result = {} local methods = {} methods.items = function() return pairs(result._data) end local key_index = nil setmetatable(t, { __index = methods, __call = function(self, _, idx) if idx == nil and key_index ~= nil then key_index = nil end key_index, _ = next(result._data, key_index) return key_index end, }) result.is_dict = true result._data = {} for k, v in pairs(t) do result._data[k] = v end return result end function enumerate(t, start) start = start or 1 local i, v = next(t, nil) return function() local index, value = i, v i, v = next(t, i) if index == nil then return nil end return index + start - 1, value end end local function staticmethod(old_fun) local wrapper = function(first, ...) return old_fun(...) end return wrapper end local function operator_in(item, items) if type(items) == "table" then for v in items do if v == item then return true end end elseif type(items) == "string" and type(item) == "string" then return string.find(items, item, 1, true) ~= nil end return false end -- Lua classes local function class(class_init, bases) bases = bases or {} local c = {} for _, base in ipairs(bases) do for k, v in pairs(base) do c[k] = v end end c._bases = bases c = class_init(c) local mt = getmetatable(c) or {} mt.__call = function(_, ...) local object = {} setmetatable(object, { __index = function(tbl, idx) local method = c[idx] if type(method) == "function" then return function(...) return c[idx](object, ...) end end return method end, }) if type(object.__init__) == "function" then object.__init__(...) end return object end setmetatable(c, mt) return c end --[[ End of the lua pythonization. --]]
Fixed list and dict bugs
Fixed list and dict bugs
Lua
apache-2.0
NeonMercury/python-lua
1f5c03d4013f6995fdfc0ec1d3bcf763f9081315
plugins/translate.lua
plugins/translate.lua
local translate = {} local HTTPS = require('ssl.https') local URL = require('socket.url') local JSON = require('dkjson') local functions = require('functions') function translate:init(configuration) translate.command = 'translate (text)' translate.triggers = functions.triggers(self.info.username, configuration.command_prefix):t('translate', true):t('tl', true).table translate.inline_triggers = translate.triggers translate.documentation = configuration.command_prefix .. 'translate (text) - Translates input or the replied-to message into mattata\'s language. Alias: ' .. configuration.command_prefix .. 'tl.' end function translate:inline_callback(inline_query, configuration) local url = configuration.apis.translate .. configuration.keys.translate .. '&lang=' .. configuration.language .. '&text=' .. URL.escape(inline_query.query) local jstr = HTTPS.request(url) local jdat = JSON.decode(jstr) local results = '[{"type":"article","id":"50","title":"/translate","description":"' .. functions.md_escape(jdat.text[1]):gsub('/translate ', '') .. '","input_message_content":{"message_text":"' .. functions.md_escape(jdat.text[1]) .. '","parse_mode":"Markdown"}}]' functions.answer_inline_query(inline_query, results, 50) end function translate:action(msg, configuration) local input = functions.input(msg.text) if not input then functions.send_reply(msg, translate.documentation) return end local url = configuration.apis.translate .. configuration.keys.translate .. '&lang=' .. configuration.language .. '&text=' .. URL.escape(input) local jstr, res = HTTPS.request(url) if res ~= 200 then functions.send_reply(msg, configuration.errors.connection) return end local jdat = JSON.decode(jstr) functions.send_reply(msg, functions.md_escape(jdat.text[1])) end return translate
local translate = {} local HTTPS = require('ssl.https') local URL = require('socket.url') local JSON = require('dkjson') local functions = require('functions') function translate:init(configuration) translate.command = 'translate (text)' translate.triggers = functions.triggers(self.info.username, configuration.command_prefix):t('translate', true):t('tl', true).table translate.inline_triggers = translate.triggers translate.documentation = configuration.command_prefix .. 'translate (text) - Translates input or the replied-to message into mattata\'s language. Alias: ' .. configuration.command_prefix .. 'tl.' end function translate:inline_callback(inline_query, configuration) local url = configuration.apis.translate .. configuration.keys.translate .. '&lang=' .. configuration.language .. '&text=' .. URL.escape(inline_query.query) local jstr = HTTPS.request(url) local jdat = JSON.decode(jstr) local results = '[{"type":"article","id":"50","title":"/translate","description":"' .. functions.md_escape(jdat.text[1]):gsub('/translate ', '') .. '","input_message_content":{"message_text":"' .. functions.md_escape(jdat.text[1]) .. '","parse_mode":"Markdown"}}]' functions.answer_inline_query(inline_query, results, 50) end function translate:action(msg, configuration) local input = functions.input(msg.text) local url = configuration.apis.translate .. configuration.keys.translate .. '&lang=' .. configuration.language .. '&text=' if msg.reply_to_message then url = url .. URL.escape(msg.reply_to_message.text) local jstr, res = HTTPS.request(url) if res ~= 200 then functions.send_reply(msg, configuration.errors.connection) return end local jdat = JSON.decode(jstr) functions.send_reply(msg, functions.md_escape(jdat.text[1])) return else if not input then functions.send_reply(msg, translate.documentation) return end url = url .. URL.escape(input) local jstr, res = HTTPS.request(url) if res ~= 200 then functions.send_reply(msg, configuration.errors.connection) return end local jdat = JSON.decode(jstr) functions.send_reply(msg, functions.md_escape(jdat.text[1])) return end end return translate
mattata v2.2.1
mattata v2.2.1 Fixed a small bug with /translate where messages couldn't be translated via reply - credit to eliKAAS for discovering this issue.
Lua
mit
barreeeiroo/BarrePolice
f6f9b22492f44dd7b07932098d35f183608ce55e
pkg/polarssl.pkg/xmake.lua
pkg/polarssl.pkg/xmake.lua
-- add polarssl package option("polarssl") -- show menu set_showmenu(true) -- set category set_category("package") -- set description set_description("The polarssl package") -- add defines to config.h if checking ok add_defines_h_if_ok("$(prefix)_PACKAGE_HAVE_POLARSSL") -- add links for checking add_links("polarssl") -- add link directories add_linkdirs("lib/$(plat)/$(arch)") -- add c includes for checking add_cincludes("polarssl/polarssl.h") -- add include directories add_includedirs("inc/$(plat)", "inc")
-- add polarssl package option("polarssl") -- show menu set_showmenu(true) -- set category set_category("package") -- set description set_description("The polarssl package") -- add defines to config.h if checking ok add_defines_h_if_ok("$(prefix)_PACKAGE_HAVE_POLARSSL") -- add links for checking add_links("polarssl") -- add link directories add_linkdirs("lib/$(plat)/$(arch)") -- add c includes for checking add_cincludes("polarssl/polarssl.h") -- add include directories add_includedirs("inc/$(plat)", "inc") -- add c functions add_cfuncs("ssl_init")
fix check polarssl
fix check polarssl
Lua
apache-2.0
waruqi/tbox,waruqi/tbox,tboox/tbox,tboox/tbox
c5b6f4294325652899ccca0419d7058cfadd7c85
modules/luci-base/luasrc/controller/admin/index.lua
modules/luci-base/luasrc/controller/admin/index.lua
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.admin.index", package.seeall) function index() function toplevel_page(page, preflookup, preftarget) if preflookup and preftarget then if lookup(preflookup) then page.target = preftarget end end if not page.target then page.target = firstchild() end end local uci = require("luci.model.uci").cursor() local root = node() if not root.target then root.target = alias("admin") root.index = true end local page = node("admin") page.title = _("Administration") page.order = 10 page.sysauth = "root" page.sysauth_authenticator = "htmlauth" page.ucidata = true page.index = true page.target = firstnode() -- Empty menu tree to be populated by addons and modules page = node("admin", "status") page.title = _("Status") page.order = 10 page.index = true -- overview is from mod-admin-full toplevel_page(page, "admin/status/overview", alias("admin", "status", "overview")) page = node("admin", "system") page.title = _("System") page.order = 20 page.index = true -- system/system is from mod-admin-full toplevel_page(page, "admin/system/system", alias("admin", "system", "system")) -- Only used if applications add items page = node("admin", "services") page.title = _("Services") page.order = 40 page.index = true toplevel_page(page, false, false) -- Even for mod-admin-full network just uses first submenu item as landing page = node("admin", "network") page.title = _("Network") page.order = 50 page.index = true toplevel_page(page, false, false) if nixio.fs.access("/etc/config/dhcp") then page = entry({"admin", "dhcplease_status"}, call("lease_status"), nil) page.leaf = true end local has_wifi = false uci:foreach("wireless", "wifi-device", function(s) has_wifi = true return false end) if has_wifi then page = entry({"admin", "wireless_assoclist"}, call("wifi_assoclist"), nil) page.leaf = true page = entry({"admin", "wireless_deauth"}, post("wifi_deauth"), nil) page.leaf = true end page = entry({"admin", "translations"}, call("action_translations"), nil) page.leaf = true page = entry({"admin", "ubus"}, call("action_ubus"), nil) page.leaf = true -- Logout is last entry({"admin", "logout"}, call("action_logout"), _("Logout"), 999) end function action_logout() local dsp = require "luci.dispatcher" local utl = require "luci.util" local sid = dsp.context.authsession if sid then utl.ubus("session", "destroy", { ubus_rpc_session = sid }) luci.http.header("Set-Cookie", "sysauth=%s; expires=%s; path=%s" %{ '', 'Thu, 01 Jan 1970 01:00:00 GMT', dsp.build_url() }) end luci.http.redirect(dsp.build_url()) end function action_translations(lang) local i18n = require "luci.i18n" local http = require "luci.http" local fs = require "nixio".fs if lang and #lang > 0 then lang = i18n.setlanguage(lang) if lang then local s = fs.stat("%s/base.%s.lmo" %{ i18n.i18ndir, lang }) if s then http.header("Cache-Control", "public, max-age=31536000") http.header("ETag", "%x-%x-%x" %{ s["ino"], s["size"], s["mtime"] }) end end end http.prepare_content("application/javascript; charset=utf-8") http.write("window.TR=") http.write_json(i18n.dump()) end local function ubus_reply(id, data, code, errmsg) local reply = { jsonrpc = "2.0", id = id } if errmsg then reply.error = { code = code, message = errmsg } else reply.result = { code, data } end return reply end local ubus_types = { nil, "array", "object", "string", nil, -- INT64 "number", nil, -- INT16, "boolean", "double" } local function ubus_request(req) if type(req) ~= "table" or type(req.method) ~= "string" or type(req.params) ~= "table" or #req.params < 2 or req.jsonrpc ~= "2.0" or req.id == nil then return ubus_reply(req.id, nil, -32600, "Invalid request") elseif req.method == "call" then local sid, obj, fun, arg = req.params[1], req.params[2], req.params[3], req.params[4] or {} if type(arg) ~= "table" or arg.ubus_rpc_session ~= nil then return ubus_reply(req.id, nil, -32602, "Invalid parameters") end if sid == "00000000000000000000000000000000" then sid = luci.dispatcher.context.authsession end arg.ubus_rpc_session = sid local res, code = luci.util.ubus(obj, fun, arg) return ubus_reply(req.id, res, code or 0) elseif req.method == "list" then if type(params) ~= "table" or #params == 0 then local objs = { luci.util.ubus() } return ubus_reply(req.id, objs, 0) else local n, rv = nil, {} for n = 1, #params do if type(params[n]) ~= "string" then return ubus_reply(req.id, nil, -32602, "Invalid parameters") end local sig = luci.util.ubus(params[n]) if sig and type(sig) == "table" then rv[params[n]] = {} local m, p for m, p in pairs(sig) do if type(p) == "table" then rv[params[n]][m] = {} local pn, pt for pn, pt in pairs(p) do rv[params[n]][m][pn] = ubus_types[pt] or "unknown" end end end end end return ubus_reply(req.id, rv, 0) end end return ubus_reply(req.id, nil, -32601, "Method not found") end function action_ubus() local parser = require "luci.jsonc".new() luci.http.context.request:setfilehandler(function(_, s) parser:parse(s or "") end) luci.http.context.request:content() local json = parser:get() if json == nil or type(json) ~= "table" then luci.http.prepare_content("application/json") luci.http.write_json(ubus_reply(nil, nil, -32700, "Parse error")) return end local response if #json == 0 then response = ubus_request(json) else response = {} local _, request for _, request in ipairs(json) do response[_] = ubus_request(request) end end luci.http.prepare_content("application/json") luci.http.write_json(response) end function lease_status() local s = require "luci.tools.status" luci.http.prepare_content("application/json") luci.http.write('[') luci.http.write_json(s.dhcp_leases()) luci.http.write(',') luci.http.write_json(s.dhcp6_leases()) luci.http.write(']') end function wifi_assoclist() local s = require "luci.tools.status" luci.http.prepare_content("application/json") luci.http.write_json(s.wifi_assoclist()) end function wifi_deauth() local iface = luci.http.formvalue("iface") local bssid = luci.http.formvalue("bssid") if iface and bssid then luci.util.ubus("hostapd.%s" % iface, "del_client", { addr = bssid, deauth = true, reason = 5, ban_time = 60000 }) end luci.http.status(200, "OK") end
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.admin.index", package.seeall) function index() function toplevel_page(page, preflookup, preftarget) if preflookup and preftarget then if lookup(preflookup) then page.target = preftarget end end if not page.target then page.target = firstchild() end end local uci = require("luci.model.uci").cursor() local root = node() if not root.target then root.target = alias("admin") root.index = true end local page = node("admin") page.title = _("Administration") page.order = 10 page.sysauth = "root" page.sysauth_authenticator = "htmlauth" page.ucidata = true page.index = true page.target = firstnode() -- Empty menu tree to be populated by addons and modules page = node("admin", "status") page.title = _("Status") page.order = 10 page.index = true -- overview is from mod-admin-full toplevel_page(page, "admin/status/overview", alias("admin", "status", "overview")) page = node("admin", "system") page.title = _("System") page.order = 20 page.index = true -- system/system is from mod-admin-full toplevel_page(page, "admin/system/system", alias("admin", "system", "system")) -- Only used if applications add items page = node("admin", "services") page.title = _("Services") page.order = 40 page.index = true toplevel_page(page, false, false) -- Even for mod-admin-full network just uses first submenu item as landing page = node("admin", "network") page.title = _("Network") page.order = 50 page.index = true toplevel_page(page, false, false) if nixio.fs.access("/etc/config/dhcp") then page = entry({"admin", "dhcplease_status"}, call("lease_status"), nil) page.leaf = true end local has_wifi = false uci:foreach("wireless", "wifi-device", function(s) has_wifi = true return false end) if has_wifi then page = entry({"admin", "wireless_assoclist"}, call("wifi_assoclist"), nil) page.leaf = true page = entry({"admin", "wireless_deauth"}, post("wifi_deauth"), nil) page.leaf = true end page = entry({"admin", "translations"}, call("action_translations"), nil) page.leaf = true page = entry({"admin", "ubus"}, call("action_ubus"), nil) page.leaf = true -- Logout is last entry({"admin", "logout"}, call("action_logout"), _("Logout"), 999) end function action_logout() local dsp = require "luci.dispatcher" local utl = require "luci.util" local sid = dsp.context.authsession if sid then utl.ubus("session", "destroy", { ubus_rpc_session = sid }) luci.http.header("Set-Cookie", "sysauth=%s; expires=%s; path=%s" %{ '', 'Thu, 01 Jan 1970 01:00:00 GMT', dsp.build_url() }) end luci.http.redirect(dsp.build_url()) end function action_translations(lang) local i18n = require "luci.i18n" local http = require "luci.http" local fs = require "nixio".fs if lang and #lang > 0 then lang = i18n.setlanguage(lang) if lang then local s = fs.stat("%s/base.%s.lmo" %{ i18n.i18ndir, lang }) if s then http.header("Cache-Control", "public, max-age=31536000") http.header("ETag", "%x-%x-%x" %{ s["ino"], s["size"], s["mtime"] }) end end end http.prepare_content("application/javascript; charset=utf-8") http.write("window.TR=") http.write_json(i18n.dump()) end local function ubus_reply(id, data, code, errmsg) local reply = { jsonrpc = "2.0", id = id } if errmsg then reply.error = { code = code, message = errmsg } else reply.result = { code, data } end return reply end local ubus_types = { nil, "array", "object", "string", nil, -- INT64 "number", nil, -- INT16, "boolean", "double" } local function ubus_request(req) if type(req) ~= "table" or type(req.method) ~= "string" or type(req.params) ~= "table" or #req.params < 2 or req.jsonrpc ~= "2.0" or req.id == nil then return ubus_reply(nil, nil, -32600, "Invalid request") elseif req.method == "call" then local sid, obj, fun, arg = req.params[1], req.params[2], req.params[3], req.params[4] or {} if type(arg) ~= "table" or arg.ubus_rpc_session ~= nil then return ubus_reply(req.id, nil, -32602, "Invalid parameters") end if sid == "00000000000000000000000000000000" then sid = luci.dispatcher.context.authsession end arg.ubus_rpc_session = sid local res, code = luci.util.ubus(obj, fun, arg) return ubus_reply(req.id, res, code or 0) elseif req.method == "list" then if type(params) ~= "table" or #params == 0 then local objs = { luci.util.ubus() } return ubus_reply(req.id, objs, 0) else local n, rv = nil, {} for n = 1, #params do if type(params[n]) ~= "string" then return ubus_reply(req.id, nil, -32602, "Invalid parameters") end local sig = luci.util.ubus(params[n]) if sig and type(sig) == "table" then rv[params[n]] = {} local m, p for m, p in pairs(sig) do if type(p) == "table" then rv[params[n]][m] = {} local pn, pt for pn, pt in pairs(p) do rv[params[n]][m][pn] = ubus_types[pt] or "unknown" end end end end end return ubus_reply(req.id, rv, 0) end end return ubus_reply(req.id, nil, -32601, "Method not found") end function action_ubus() local parser = require "luci.jsonc".new() luci.http.context.request:setfilehandler(function(_, s) if not s then return nil end local ok, err = parser:parse(s) return (not err or nil) end) luci.http.context.request:content() local json = parser:get() if json == nil or type(json) ~= "table" then luci.http.prepare_content("application/json") luci.http.write_json(ubus_reply(nil, nil, -32700, "Parse error")) return end local response if #json == 0 then response = ubus_request(json) else response = {} local _, request for _, request in ipairs(json) do response[_] = ubus_request(request) end end luci.http.prepare_content("application/json") luci.http.write_json(response) end function lease_status() local s = require "luci.tools.status" luci.http.prepare_content("application/json") luci.http.write('[') luci.http.write_json(s.dhcp_leases()) luci.http.write(',') luci.http.write_json(s.dhcp6_leases()) luci.http.write(']') end function wifi_assoclist() local s = require "luci.tools.status" luci.http.prepare_content("application/json") luci.http.write_json(s.wifi_assoclist()) end function wifi_deauth() local iface = luci.http.formvalue("iface") local bssid = luci.http.formvalue("bssid") if iface and bssid then luci.util.ubus("hostapd.%s" % iface, "del_client", { addr = bssid, deauth = true, reason = 5, ban_time = 60000 }) end luci.http.status(200, "OK") end
luci-base: fix handling of large ubus HTTP requests
luci-base: fix handling of large ubus HTTP requests Properly handle ubus POST requests exceeding the default chunk size and fix a possible nil dereference when rejecting incoming requests due to bad JSON message framing. Signed-off-by: Jo-Philipp Wich <bd73d35759d75cc215150d1bbc94f1b1078bee01@mein.io>
Lua
apache-2.0
nmav/luci,lbthomsen/openwrt-luci,artynet/luci,rogerpueyo/luci,hnyman/luci,tobiaswaldvogel/luci,Noltari/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,Noltari/luci,nmav/luci,nmav/luci,tobiaswaldvogel/luci,openwrt/luci,artynet/luci,hnyman/luci,nmav/luci,lbthomsen/openwrt-luci,openwrt/luci,openwrt/luci,openwrt/luci,lbthomsen/openwrt-luci,hnyman/luci,Noltari/luci,hnyman/luci,rogerpueyo/luci,nmav/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,artynet/luci,nmav/luci,rogerpueyo/luci,rogerpueyo/luci,lbthomsen/openwrt-luci,Noltari/luci,Noltari/luci,artynet/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,openwrt/luci,Noltari/luci,Noltari/luci,nmav/luci,tobiaswaldvogel/luci,Noltari/luci,rogerpueyo/luci,artynet/luci,openwrt/luci,lbthomsen/openwrt-luci,nmav/luci,artynet/luci,rogerpueyo/luci,hnyman/luci,Noltari/luci,nmav/luci,openwrt/luci,hnyman/luci,openwrt/luci,artynet/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,rogerpueyo/luci,artynet/luci,lbthomsen/openwrt-luci,hnyman/luci,hnyman/luci,artynet/luci
929eca2ea45cc3adeab8c3780d94980a7012541a
packages/features.lua
packages/features.lua
local lpeg = require("lpeg") local S, P, C = lpeg.S, lpeg.P, lpeg.C local Cf, Ct = lpeg.Cf, lpeg.Ct local opentype = { -- Mapping of opentype features to friendly names Ligatures = { Required = "rlig", Common = "liga", Contextual = "clig", Rare = "dlig", Discretionary = "dlig", Historic = "hlig" }, Fractions = { On = "frac", Alternate = "afrc" }, StylisticSet = function (i) return string.format("ss%02i", tonumber(i)) end, Letters = { Uppercase = "case", SmallCaps = "smcp", PetiteCaps = "pcap", UppercaseSmallCaps = "c2sc", UppercasePetiteCaps = "c2pc", Unicase = "unic" }, Numbers = { Uppercase = "lnum", Lining = "lnum", LowerCase = "onum", OldStyle = "onum", Proportional = "pnum", monospaced = "tnum", SlashedZero = "zero", Arabic = "anum" }, Contextuals = { Swash = "cswh", Alternate = "calt", WordInitial = "init", WordFinal = "fina", LineFinal = "falt", Inner = "medi" }, VerticalPosition = { Superior = "sups", Inferior = "subs", Numerator = "numr", Denominator = "dnom", ScientificInferior = "sinf", Ordinal = "ordn" }, -- XXX Character variant support not implemented yet Style = { Alternate = "salt", Italic = "ital", Ruby = "ruby", Swash = "swsh", Historic = "hist", TitlingCaps = "titl", HorizontalKana = "hkna", VerticalKana = "vkna" }, Diacritics = { MarkToBase = "mark", MarkToMark = "mkmk", AboveBase = "abvm", BelowBase = "blwm" }, Kerning = { Uppercase = "cpsp", On = "kern" }, CJKShape = { Traditional = "trad", Simplified = "smpl", JIS1978 = "jp78", JIS1983 = "jp83", JIS1990 = "jp90", Expert = "expt", NLC = "nlck" }, CharacterWidth = { Proportional = "pwid", Full = "fwid", Half = "hwid", Third = "twid", Quarter = "qwid", AlternateProportional = "palt", AlternateHalf = "halt" } } local function tagpos (pos, k, v) return k, { posneg = pos, value = v } end -- Parser for feature strings local featurename = C((1 - S",;:=")^1) local value = C(SILE.parserBits.integer) local tag = C(S"+-") * featurename * (P"=" * value)^0 * S",;:"^-1 / tagpos local featurestring = Cf(Ct"" * tag^0, rawset) local featurestring2table = function (str) return featurestring:match(str) or SU.error("Unparsable Opentype feature string '"..str.."'") end local table2featurestring = function (tbl) local t2 = {} for k, v in pairs(tbl) do t2[#t2+1] = v.posneg..k..(v.value and "="..v.value or "") end return table.concat(t2, ";") end SILE.registerCommand("add-font-feature", function (options, _) local t = featurestring2table(SILE.settings.get("font.features")) for k, v in pairs(options) do if not opentype[k] then SU.warn("Unknown Opentype feature "..k) else local posneg = "+" v = v:gsub("^No", function () posneg= "-"; return "" end) local res if type(opentype[k]) == "function" then res = opentype[k](v) else res = opentype[k][v] end if not res then SU.error("Bad OpenType value "..v.." for feature "..k) end if type(res) == "string" then t[res] = {posneg = posneg} else t[res.key] = { posneg = posneg, value = res.value} end end end SILE.settings.set("font.features", table2featurestring(t)) end) SILE.registerCommand("remove-font-feature", function (options, _) local t = featurestring2table(SILE.settings.get("font.features")) for k, v in pairs(options) do if not opentype[k] then SU.warn("Unknown Opentype feature "..k) else v = v:gsub("^No", "") local res if type(opentype[k]) == "function" then res = opentype[k](v) else res = opentype[k][v] end if not res then SU.error("Bad OpenType value "..v.." for feature "..k) end if type(res) == "string" then t[res] = nil else t[res.key] = nil end end end SILE.settings.set("font.features", table2featurestring(t)) end) return { documentation = [[\begin{document} As mentioned in Chapter 3, SILE automatically applies ligatures defined by the fonts that you use. These ligatures are defined by tables of \em{features} within the font file. As well as ligatures (multiple glyphs displayed as a single glyph), the features tables also declare other glyph substitutions. The \code{features} package provides an interface to selecting the features that you want SILE to apply to a font. The features available will be specific to the font file; some fonts come with documentation explaining their supported features. Discussion of OpenType features is beyond the scope of this manual. These features can be turned on and off by passing ‘raw’ feature names to the \code{\\font} command like so: \begin{verbatim} \line \\font[features="+dlig,+hlig"]{...} \% turn on discretionary and historic ligatures \line \end{verbatim} However, this is unwieldy and requires memorizing the feature codes. \code{features} provides two commands, \code{\\add-font-feature} and \code{\\remove-font-feature}, which make it easier to access OpenType features. The interface is patterned on the TeX package \code{fontspec}; for full documentation of the OpenType features supported, see the documentation for that package.\footnote{\code{http://texdoc.net/texmf-dist/doc/latex/fontspec/fontspec.pdf}} Here is how you would turn on discretionary and historic ligatures with the \code{features} package: \begin{verbatim} \line \\add-font-feature[Ligatures=Rare]\\add-font-feature[Ligatures=Discretionary] ... \\remove-font-feature[Ligatures=Rare]\\remove-font-feature[Ligatures=Discretionary] \line \end{verbatim} \end{document}]] }
local lpeg = require("lpeg") local S, P, C = lpeg.S, lpeg.P, lpeg.C local Cf, Ct = lpeg.Cf, lpeg.Ct local opentype = { -- Mapping of opentype features to friendly names Ligatures = { Required = "rlig", Common = "liga", Contextual = "clig", Rare = "dlig", Discretionary = "dlig", Historic = "hlig" }, Fractions = { On = "frac", Alternate = "afrc" }, StylisticSet = function (i) return string.format("ss%02i", tonumber(i)) end, CharacterVariant = function (i) return string.format("cv%02i", tonumber(i)) end, Letters = { Uppercase = "case", SmallCaps = "smcp", PetiteCaps = "pcap", UppercaseSmallCaps = "c2sc", UppercasePetiteCaps = "c2pc", Unicase = "unic" }, Numbers = { Uppercase = "lnum", Lining = "lnum", LowerCase = "onum", OldStyle = "onum", Proportional = "pnum", monospaced = "tnum", SlashedZero = "zero", Arabic = "anum" }, Contextuals = { Swash = "cswh", Alternate = "calt", WordInitial = "init", WordFinal = "fina", LineFinal = "falt", Inner = "medi" }, VerticalPosition = { Superior = "sups", Inferior = "subs", Numerator = "numr", Denominator = "dnom", ScientificInferior = "sinf", Ordinal = "ordn" }, -- XXX Character variant support not implemented yet Style = { Alternate = "salt", Italic = "ital", Ruby = "ruby", Swash = "swsh", Historic = "hist", TitlingCaps = "titl", HorizontalKana = "hkna", VerticalKana = "vkna" }, Diacritics = { MarkToBase = "mark", MarkToMark = "mkmk", AboveBase = "abvm", BelowBase = "blwm" }, Kerning = { Uppercase = "cpsp", On = "kern" }, CJKShape = { Traditional = "trad", Simplified = "smpl", JIS1978 = "jp78", JIS1983 = "jp83", JIS1990 = "jp90", Expert = "expt", NLC = "nlck" }, CharacterWidth = { Proportional = "pwid", Full = "fwid", Half = "hwid", Third = "twid", Quarter = "qwid", AlternateProportional = "palt", AlternateHalf = "halt" } } local function tagpos (pos, k, v) return k, { posneg = pos, value = v } end -- Parser for feature strings local featurename = C((1 - S",;:=")^1) local value = C(SILE.parserBits.integer) local tag = C(S"+-") * featurename * (P"=" * value)^0 * S",;:"^-1 / tagpos local featurestring = Cf(Ct"" * tag^0, rawset) local featurestring2table = function (str) return featurestring:match(str) or SU.error("Unparsable Opentype feature string '"..str.."'") end local table2featurestring = function (tbl) local t2 = {} for k, v in pairs(tbl) do t2[#t2+1] = v.posneg..k..(v.value and "="..v.value or "") end return table.concat(t2, ";") end SILE.registerCommand("add-font-feature", function (options, _) local t = featurestring2table(SILE.settings.get("font.features")) for k, v in pairs(options) do if not opentype[k] then SU.warn("Unknown Opentype feature "..k) else local posneg = "+" v = v:gsub("^No", function () posneg= "-"; return "" end) local res if type(opentype[k]) == "function" then res = opentype[k](v) else res = opentype[k][v] end if not res then SU.error("Bad OpenType value "..v.." for feature "..k) end if type(res) == "string" then t[res] = {posneg = posneg} else t[res.key] = { posneg = posneg, value = res.value} end end end SILE.settings.set("font.features", table2featurestring(t)) end) SILE.registerCommand("remove-font-feature", function (options, _) local t = featurestring2table(SILE.settings.get("font.features")) for k, v in pairs(options) do if not opentype[k] then SU.warn("Unknown Opentype feature "..k) else v = v:gsub("^No", "") local res if type(opentype[k]) == "function" then res = opentype[k](v) else res = opentype[k][v] end if not res then SU.error("Bad OpenType value "..v.." for feature "..k) end if type(res) == "string" then t[res] = nil else t[res.key] = nil end end end SILE.settings.set("font.features", table2featurestring(t)) end) return { documentation = [[\begin{document} As mentioned in Chapter 3, SILE automatically applies ligatures defined by the fonts that you use. These ligatures are defined by tables of \em{features} within the font file. As well as ligatures (multiple glyphs displayed as a single glyph), the features tables also declare other glyph substitutions. The \code{features} package provides an interface to selecting the features that you want SILE to apply to a font. The features available will be specific to the font file; some fonts come with documentation explaining their supported features. Discussion of OpenType features is beyond the scope of this manual. These features can be turned on and off by passing ‘raw’ feature names to the \code{\\font} command like so: \begin{verbatim} \line \\font[features="+dlig,+hlig"]{...} \% turn on discretionary and historic ligatures \line \end{verbatim} However, this is unwieldy and requires memorizing the feature codes. \code{features} provides two commands, \code{\\add-font-feature} and \code{\\remove-font-feature}, which make it easier to access OpenType features. The interface is patterned on the TeX package \code{fontspec}; for full documentation of the OpenType features supported, see the documentation for that package.\footnote{\code{http://texdoc.net/texmf-dist/doc/latex/fontspec/fontspec.pdf}} Here is how you would turn on discretionary and historic ligatures with the \code{features} package: \begin{verbatim} \line \\add-font-feature[Ligatures=Rare]\\add-font-feature[Ligatures=Discretionary] ... \\remove-font-feature[Ligatures=Rare]\\remove-font-feature[Ligatures=Discretionary] \line \end{verbatim} \end{document}]] }
fix(packages): Add CharacterVariant to features
fix(packages): Add CharacterVariant to features
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
2ea4224e153b0dd3560f897fe40a2e3e4a220ce9
mod_push_appserver_fcm/mod_push_appserver_fcm.lua
mod_push_appserver_fcm/mod_push_appserver_fcm.lua
-- mod_push_appserver_fcm -- -- Copyright (C) 2017 Thilo Molitor -- -- This file is MIT/X11 licensed. -- -- Submodule implementing FCM communication -- -- imports -- unlock prosody globals and allow ltn12 to pollute the global space -- this fixes issue #8 in prosody 0.11, see also https://issues.prosody.im/1033 prosody.unlock_globals() require "ltn12"; prosody.lock_globals() local https = require "ssl.https"; local string = require "string"; local t_remove = table.remove; local datetime = require "util.datetime"; local json = require "util.json"; local pretty = require "pl.pretty"; -- this is the master module module:depends("push_appserver"); -- configuration local fcm_key = module:get_option_string("push_appserver_fcm_key", nil); --push api key (no default) local capath = module:get_option_string("push_appserver_fcm_capath", "/etc/ssl/certs"); --ca path on debian systems local ciphers = module:get_option_string("push_appserver_fcm_ciphers", "ECDHE-RSA-AES256-GCM-SHA384:".. "ECDHE-ECDSA-AES256-GCM-SHA384:".. "ECDHE-RSA-AES128-GCM-SHA256:".. "ECDHE-ECDSA-AES128-GCM-SHA256" ); --supported ciphers local push_ttl = module:get_option_number("push_appserver_fcm_push_ttl", nil); --no ttl (equals 4 weeks) local push_priority = module:get_option_string("push_appserver_fcm_push_priority", "high"); --high priority pushes (can be "high" or "normal") local push_endpoint = "https://fcm.googleapis.com/fcm/send"; -- high level network (https) functions local function send_request(data) local respbody = {} -- for the response body prosody.unlock_globals(); -- unlock globals (https.request() tries to access global PROXY) local result, status_code, headers, status_line = https.request({ method = "POST", url = push_endpoint, source = ltn12.source.string(data), headers = { ["authorization"] = "key="..tostring(fcm_key), ["content-type"] = "application/json", ["content-length"] = tostring(#data) }, sink = ltn12.sink.table(respbody), -- luasec tls options mode = "client", protocol = "tlsv1_2", verify = {"peer", "fail_if_no_peer_cert"}, capath = capath, ciphers = ciphers, options = { "no_sslv2", "no_sslv3", "no_ticket", "no_compression", "cipher_server_preference", "single_dh_use", "single_ecdh_use", }, }); prosody.lock_globals(); -- lock globals again if not result then return nil, status_code; end -- status_code contains the error message in case of failure -- return body as string by concatenating table filled by sink return table.concat(respbody), status_code, status_line, headers; end -- handlers local function fcm_handler(event) local settings = event.settings; local data = { ["to"] = tostring(settings["token"]), ["collapse_key"] = "mod_push_appserver_fcm.collapse", ["priority"] = (push_priority=="high" and "high" or "normal"), ["data"] = {}, }; if push_ttl and push_ttl > 0 then data["time_to_live"] = push_ttl; end -- ttl is optional (google's default: 4 weeks) data = json.encode(data); module:log("debug", "sending to %s, json string: %s", push_endpoint, data); local response, status_code, status_line = send_request(data); if not response then module:log("error", "Could not send FCM request: %s", tostring(status_code)); return tostring(status_code); -- return error message end module:log("debug", "response status code: %s, raw response body: %s", tostring(status_code), response); if status_code ~= 200 then local fcm_error; if status_code == 400 then fcm_error="Invalid JSON or unknown fields."; end if status_code == 401 then fcm_error="There was an error authenticating the sender account."; end if status_code >= 500 and status_code < 600 then fcm_error="Internal server error, please retry again later."; end module:log("error", "Got FCM error: %s", fcm_error); return fcm_error; end response = json.decode(response); module:log("debug", "decoded: %s", pretty.write(response)); -- handle errors if response.failure > 0 then module:log("error", "FCM returned %s failures:", tostring(response.failure)); local fcm_error = true; for k, result in pairs(response.results) do if result.error and #result.error then module:log("error", "Got FCM error:", result.error); fcm_error = tostring(result.error); -- return last error to mod_push_appserver end end return fcm_error; end -- handle success for k, result in pairs(response.results) do if result.message_id then module:log("debug", "got FCM message id: '%s'", tostring(result.message_id)); end end return false; -- no error occured end -- setup module:hook("incoming-push-to-fcm", fcm_handler); module:log("info", "Appserver FCM submodule loaded"); function module.unload() if module.unhook then module:unhook("incoming-push-to-fcm", fcm_handler); end module:log("info", "Appserver FCM submodule unloaded"); end
-- mod_push_appserver_fcm -- -- Copyright (C) 2017 Thilo Molitor -- -- This file is MIT/X11 licensed. -- -- Submodule implementing FCM communication -- -- imports -- unlock prosody globals and allow ltn12 to pollute the global space -- this fixes issue #8 in prosody 0.11, see also https://issues.prosody.im/1033 prosody.unlock_globals() require "ltn12"; local https = require "ssl.https"; prosody.lock_globals() local string = require "string"; local t_remove = table.remove; local datetime = require "util.datetime"; local json = require "util.json"; local pretty = require "pl.pretty"; -- this is the master module module:depends("push_appserver"); -- configuration local fcm_key = module:get_option_string("push_appserver_fcm_key", nil); --push api key (no default) local capath = module:get_option_string("push_appserver_fcm_capath", "/etc/ssl/certs"); --ca path on debian systems local ciphers = module:get_option_string("push_appserver_fcm_ciphers", "ECDHE-RSA-AES256-GCM-SHA384:".. "ECDHE-ECDSA-AES256-GCM-SHA384:".. "ECDHE-RSA-AES128-GCM-SHA256:".. "ECDHE-ECDSA-AES128-GCM-SHA256" ); --supported ciphers local push_ttl = module:get_option_number("push_appserver_fcm_push_ttl", nil); --no ttl (equals 4 weeks) local push_priority = module:get_option_string("push_appserver_fcm_push_priority", "high"); --high priority pushes (can be "high" or "normal") local push_endpoint = "https://fcm.googleapis.com/fcm/send"; -- high level network (https) functions local function send_request(data) local respbody = {} -- for the response body prosody.unlock_globals(); -- unlock globals (https.request() tries to access global PROXY) local result, status_code, headers, status_line = https.request({ method = "POST", url = push_endpoint, source = ltn12.source.string(data), headers = { ["authorization"] = "key="..tostring(fcm_key), ["content-type"] = "application/json", ["content-length"] = tostring(#data) }, sink = ltn12.sink.table(respbody), -- luasec tls options mode = "client", protocol = "tlsv1_2", verify = {"peer", "fail_if_no_peer_cert"}, capath = capath, ciphers = ciphers, options = { "no_sslv2", "no_sslv3", "no_ticket", "no_compression", "cipher_server_preference", "single_dh_use", "single_ecdh_use", }, }); prosody.lock_globals(); -- lock globals again if not result then return nil, status_code; end -- status_code contains the error message in case of failure -- return body as string by concatenating table filled by sink return table.concat(respbody), status_code, status_line, headers; end -- handlers local function fcm_handler(event) local settings = event.settings; local data = { ["to"] = tostring(settings["token"]), ["collapse_key"] = "mod_push_appserver_fcm.collapse", ["priority"] = (push_priority=="high" and "high" or "normal"), ["data"] = {}, }; if push_ttl and push_ttl > 0 then data["time_to_live"] = push_ttl; end -- ttl is optional (google's default: 4 weeks) data = json.encode(data); module:log("debug", "sending to %s, json string: %s", push_endpoint, data); local response, status_code, status_line = send_request(data); if not response then module:log("error", "Could not send FCM request: %s", tostring(status_code)); return tostring(status_code); -- return error message end module:log("debug", "response status code: %s, raw response body: %s", tostring(status_code), response); if status_code ~= 200 then local fcm_error; if status_code == 400 then fcm_error="Invalid JSON or unknown fields."; end if status_code == 401 then fcm_error="There was an error authenticating the sender account."; end if status_code >= 500 and status_code < 600 then fcm_error="Internal server error, please retry again later."; end module:log("error", "Got FCM error: %s", fcm_error); return fcm_error; end response = json.decode(response); module:log("debug", "decoded: %s", pretty.write(response)); -- handle errors if response.failure > 0 then module:log("error", "FCM returned %s failures:", tostring(response.failure)); local fcm_error = true; for k, result in pairs(response.results) do if result.error and #result.error then module:log("error", "Got FCM error:", result.error); fcm_error = tostring(result.error); -- return last error to mod_push_appserver end end return fcm_error; end -- handle success for k, result in pairs(response.results) do if result.message_id then module:log("debug", "got FCM message id: '%s'", tostring(result.message_id)); end end return false; -- no error occured end -- setup module:hook("incoming-push-to-fcm", fcm_handler); module:log("info", "Appserver FCM submodule loaded"); function module.unload() if module.unhook then module:unhook("incoming-push-to-fcm", fcm_handler); end module:log("info", "Appserver FCM submodule unloaded"); end
Better fix for #8
Better fix for #8
Lua
mit
tmolitor-stud-tu/mod_push_appserver,tmolitor-stud-tu/mod_push_appserver
5c27022f29c4183169f0e6b0c1ce3dfd3e2a3a17
zpm.lua
zpm.lua
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] workspace "SerLib" cppdialect "C++14" zefiros.setDefaults("serialisation")
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] workspace "SerLib" cppdialect "C++14" zefiros.setDefaults("serialisation") -- use another path in case of a coverage build if os.getenv('BUILD_CONFIGURATION') == 'coverage' then project "serialisation-test" defines { "TEST_FILES_DIR=\"test/test-files/\"" } end
Fix coverage build
Fix coverage build
Lua
mit
Zefiros-Software/SerLib2
b65778b7391aa30ced8034861d10a6a75b651870
src/nodish/stream.lua
src/nodish/stream.lua
local ev = require'ev' local S = require'syscall' local loop = ev.Loop.default local EAGAIN = S.c.E.AGAIN local readable = function(emitter) self = emitter assert(self.watchers) self.add_read_watcher = function(_,fd) assert(self._read) if self.watchers.read then return end local watchers = self.watchers watchers.read = ev.IO.new(function(loop,io) self:emit('readable') repeat local data,err,closed = self:_read() if data then if #data > 0 then if watchers.timer then watchers.timer:again(loop) end self:emit('data',data) else self:emit('fin') if closed then self:emit('close') end io:stop(loop) return end elseif err and err.errno ~= EAGAIN then self:emit('error',err) err = nil end until err end,fd,ev.READ) end self.pause = function() self.watchers.read:stop(loop) end self.resume = function() self.watchers.read:start(loop) end self.pipe = function(_,writable,auto_fin) self:on('data',function(data) writable:write(data) end) if auto_fin then self:on('fin',function() writable:fin() end) end end end local writable = function(emitter) local self = emitter local pending local ended self.add_write_watcher = function(_,fd) assert(self._write) if self.watchers.write then return end local pos = 1 local left local watchers = self.watchers watchers.write = ev.IO.new(function(loop,io) local written,err = self:_write(pending:sub(pos)) if written > 0 then pos = pos + written if pos > #pending then pos = 1 pending = nil io:stop(loop) self:emit('drain') if ended then self:emit('finish') end end elseif err and err.errno ~= EAGAIN then io:stop(loop) self:emit('error',err) return end if watchers.timer then watchers.timer:again(loop) end end,fd,ev.WRITE) end self.write = function(_,data) if pending then pending = pending..data elseif ended then error('writable.fin has been called') else pending = data self.watchers.write:start(loop) end end self.fin = function(_,data) if data then self:write(data) elseif not pending then -- process.next_tick(function() self:emit('finish') -- end) end ended = true end end return { readable = readable, writable = writable }
local ev = require'ev' local S = require'syscall' local loop = ev.Loop.default local EAGAIN = S.c.E.AGAIN local readable = function(emitter) self = emitter assert(self.watchers) self.add_read_watcher = function(_,fd) assert(self._read) if self.watchers.read then return end local watchers = self.watchers watchers.read = ev.IO.new(function(loop,io) self:emit('readable') repeat local data,err,closed = self:_read() if data then if #data > 0 then if watchers.timer then watchers.timer:again(loop) end self:emit('data',data) else self:emit('fin') if closed then self:emit('close') end io:stop(loop) return end elseif err and err.errno ~= EAGAIN then self:emit('error',err) err = nil end until err end,fd,ev.READ) end self.pause = function() self.watchers.read:stop(loop) end self.resume = function() self.watchers.read:start(loop) end self.pipe = function(_,writable,auto_fin) self:on('data',function(data) writable:write(data) end) if auto_fin then self:on('fin',function() writable:fin() end) end end end local nexttick local writable = function(emitter) local self = emitter local pending local ended self.add_write_watcher = function(_,fd) assert(self._write) if self.watchers.write then return end local pos = 1 local left local watchers = self.watchers watchers.write = ev.IO.new(function(loop,io) local written,err = self:_write(pending:sub(pos)) if written > 0 then pos = pos + written if pos > #pending then pos = 1 pending = nil io:stop(loop) self:emit('drain') if ended then self:emit('finish') end end elseif err and err.errno ~= EAGAIN then io:stop(loop) self:emit('error',err) return end if watchers.timer then watchers.timer:again(loop) end end,fd,ev.WRITE) end self.write = function(_,data) if pending then pending = pending..data elseif ended then error('writable.fin has been called') else pending = data self.watchers.write:start(loop) end end self.fin = function(_,data) if data then self:write(data) elseif not pending then -- TODO fix cyclic module dep if not nexttick then nexttick = require'nodish.process'.nexttick end nexttick(function() self:emit('finish') end) end ended = true end end return { readable = readable, writable = writable }
fix nexttick usage
fix nexttick usage
Lua
mit
lipp/nodish
762c4de31d7e8d561495aa5cbafccbe8061e2e90
otouto/plugins/antilink.lua
otouto/plugins/antilink.lua
local bindings = require('otouto.bindings') local utilities = require('otouto.utilities') local autils = require('otouto.administration') local antilink = {} function antilink:init() assert(self.named_plugins.flags, antilink.name .. ' requires flags') self.named_plugins.flags.flags[antilink.name] = 'Posting links to other groups is not allowed.' -- Build the antilink patterns. Additional future domains can be added to -- this list to keep it up to date. antilink.patterns = {} for _, domain in pairs{ 'telegram.me', 'telegram.dog', 'tlgrm.me', 't.me' } do local s = '' -- We build the pattern character by character from the domains. -- May become an issue when emoji TLDs become mainstream. ;) for char in domain:gmatch('.') do if char:match('%l') then s = s .. '[' .. char:upper() .. char .. ']' -- all characters which must be escaped elseif char:match('[%%%.%^%$%+%-%*%?]') then s = s .. '%' .. char else s = s .. char end end table.insert(antilink.patterns, s) end antilink.triggers = utilities.clone_table(antilink.patterns) table.insert(antilink.triggers, '@[%w_]+') -- Infractions are stored, and users are globally banned after three. if not self.database.administration.antilink then self.database.administration.antilink = {} end antilink.store = self.database.administration.antilink antilink.internal = true end function antilink:action(msg, group, user) if not group.flags.antilink then return true end if user.rank > 1 then return true end if msg.forward_from and ( (msg.forward_from.id == self.info.id) or (msg.forward_from.id == self.config.log_chat) or (msg.forward_from.id == self.config.administration.log_chat) ) then return true end if antilink.check(self, msg) then antilink.store[user.id_str] = antilink.store[user.id_str] or { count = 0, groups = {}, } antilink.store[user.id_str].count = antilink.store[user.id_str].count +1 antilink.store[user.id_str].groups[tostring(msg.chat.id)] = true antilink.store[user.id_str].latest = os.time() if antilink.store[user.id_str].count == 3 then self.database.administration.hammers[user.id_str] = true bindings.deleteMessage{ chat_id = msg.chat.id, message_id = msg.message_id } autils.log(self, msg.chat.title, msg.from.id, 'Globally banned', 'antilink', 'Three illegal links within a day.') for chat_id_str in pairs(antilink.store[user.id_str].groups) do bindings.kickChatMember{ chat_id = chat_id_str, user_id = msg.from.id } end antilink.store[user.id_str] = nil else autils.strike(self, msg, antilink.name) end else return true end end function antilink:cron() if antilink.last_clear ~= os.date('%H') then for id_str, store in pairs(antilink.store) do if store.latest + 86400 > os.time() then antilink.store[id_str] = nil end end antilink.last_clear = os.date('%H') end end antilink.edit_action = antilink.action -- Links can come from the message text or from entities, and can be joinchat -- links (t.me/joinchat/abcdefgh), username links (t.me/abcdefgh), or usernames -- (@abcdefgh). function antilink.check(self, msg) for _, pattern in pairs(antilink.patterns) do -- Iterate through links in the message, and determine if they refer to -- external groups. for link in msg.text:gmatch(pattern..'%g*') do if antilink.parse_and_detect(self, link, pattern) then return true end end -- Iterate through the messages's entities, if any, and determine if -- they're links to external groups. if msg.entities then for _, entity in ipairs(msg.entities) do if entity.url and antilink.parse_and_detect(self, entity.url, pattern) then return true end end end end -- Iterate through all usernames in the message text, and determine if they -- are external group links. for username in msg.text:gmatch('@([%w_]+)') do if antilink.is_username_external(self, username) then return true end end end -- This function takes a link or username (parsed from a message or found in an -- entity) and returns true if that link or username refers to a supergroup -- outside of the realm. function antilink.parse_and_detect(self, link, pattern) local code = link:match(pattern .. -- /joinchat/ABC-def_123 '/[Jj][Oo][Ii][Nn][Cc][Hh][Aa][Tt]/([%w_%-]+)') local username = link:match(pattern .. '/([%w_]+)') if (code and antilink.is_code_external(self, code)) or (username and antilink.is_username_external(self, username)) then return true end end -- This function determines whether or not a given joinchat "code" refers to -- a group outside the realm (true/false) function antilink.is_code_external(self, code) -- Prepare the code to be used as a pattern by escaping any hyphens. -- Also, add an anchor. local pattern = '/' .. code:gsub('%-', '%%-') .. '$' -- Iterate through groups and return false if the joinchat code belongs to -- any one of them. for _, group in pairs(self.database.administration.groups) do if group.link:match(pattern) then return false end end return true end -- This function determines whether or not a username refers to a supergroup -- outside the realm (true/false). function antilink.is_username_external(self, username) local res = bindings.getChat{chat_id = '@' .. username} -- If the username is an external supergroup or channel, return true. if res and (res.result.type=='supergroup' or res.result.type=='channel') and not self.database.administration.groups[tostring(res.result.id)] then return true end return false end return antilink
local bindings = require('otouto.bindings') local utilities = require('otouto.utilities') local autils = require('otouto.administration') local antilink = {} function antilink:init() assert(self.named_plugins.flags, antilink.name .. ' requires flags') self.named_plugins.flags.flags[antilink.name] = 'Posting links to other groups is not allowed.' -- Build the antilink patterns. Additional future domains can be added to -- this list to keep it up to date. antilink.patterns = {} for _, domain in pairs{ 'telegram.me', 'telegram.dog', 'tlgrm.me', 't.me' } do local s = '' -- We build the pattern character by character from the domains. -- May become an issue when emoji TLDs become mainstream. ;) for char in domain:gmatch('.') do if char:match('%l') then s = s .. '[' .. char:upper() .. char .. ']' -- all characters which must be escaped elseif char:match('[%%%.%^%$%+%-%*%?]') then s = s .. '%' .. char else s = s .. char end end table.insert(antilink.patterns, s) end antilink.triggers = utilities.clone_table(antilink.patterns) table.insert(antilink.triggers, '@[%w_]+') -- Infractions are stored, and users are globally banned after three within -- one day of each other. if not self.database.administration.antilink then self.database.administration.antilink = {} end antilink.store = self.database.administration.antilink antilink.internal = true end function antilink:action(msg, group, user) if not group.flags.antilink then return true end if user.rank > 1 then return true end if msg.forward_from and ( (msg.forward_from.id == self.info.id) or (msg.forward_from.id == self.config.log_chat) or (msg.forward_from.id == self.config.administration.log_chat) ) then return true end if antilink.check(self, msg) then antilink.store[user.id_str] = antilink.store[user.id_str] or { count = 0, groups = {}, } antilink.store[user.id_str].count = antilink.store[user.id_str].count +1 antilink.store[user.id_str].groups[tostring(msg.chat.id)] = true antilink.store[user.id_str].latest = os.time() if antilink.store[user.id_str].count == 3 then self.database.administration.hammers[user.id_str] = true bindings.deleteMessage{ chat_id = msg.chat.id, message_id = msg.message_id } autils.log(self, msg.chat.title, msg.from.id, 'Globally banned', 'antilink', 'Three illegal links within a day.') for chat_id_str in pairs(antilink.store[user.id_str].groups) do bindings.kickChatMember{ chat_id = chat_id_str, user_id = msg.from.id } end antilink.store[user.id_str] = nil else autils.strike(self, msg, antilink.name) end else return true end end function antilink:cron() if antilink.last_clear ~= os.date('%H') then for id_str, u in pairs(antilink.store) do if os.time() > u.latest + 86400 then antilink.store[id_str] = nil end end antilink.last_clear = os.date('%H') end end antilink.edit_action = antilink.action -- Links can come from the message text or from entities, and can be joinchat -- links (t.me/joinchat/abcdefgh), username links (t.me/abcdefgh), or usernames -- (@abcdefgh). function antilink.check(self, msg) for _, pattern in pairs(antilink.patterns) do -- Iterate through links in the message, and determine if they refer to -- external groups. for link in msg.text:gmatch(pattern..'%g*') do if antilink.parse_and_detect(self, link, pattern) then return true end end -- Iterate through the messages's entities, if any, and determine if -- they're links to external groups. if msg.entities then for _, entity in ipairs(msg.entities) do if entity.url and antilink.parse_and_detect(self, entity.url, pattern) then return true end end end end -- Iterate through all usernames in the message text, and determine if they -- are external group links. for username in msg.text:gmatch('@([%w_]+)') do if antilink.is_username_external(self, username) then return true end end end -- This function takes a link or username (parsed from a message or found in an -- entity) and returns true if that link or username refers to a supergroup -- outside of the realm. function antilink.parse_and_detect(self, link, pattern) local code = link:match(pattern .. -- /joinchat/ABC-def_123 '/[Jj][Oo][Ii][Nn][Cc][Hh][Aa][Tt]/([%w_%-]+)') local username = link:match(pattern .. '/([%w_]+)') if (code and antilink.is_code_external(self, code)) or (username and antilink.is_username_external(self, username)) then return true end end -- This function determines whether or not a given joinchat "code" refers to -- a group outside the realm (true/false) function antilink.is_code_external(self, code) -- Prepare the code to be used as a pattern by escaping any hyphens. -- Also, add an anchor. local pattern = '/' .. code:gsub('%-', '%%-') .. '$' -- Iterate through groups and return false if the joinchat code belongs to -- any one of them. for _, group in pairs(self.database.administration.groups) do if group.link:match(pattern) then return false end end return true end -- This function determines whether or not a username refers to a supergroup -- outside the realm (true/false). function antilink.is_username_external(self, username) local res = bindings.getChat{chat_id = '@' .. username} -- If the username is an external supergroup or channel, return true. if res and (res.result.type=='supergroup' or res.result.type=='channel') and not self.database.administration.groups[tostring(res.result.id)] then return true end return false end return antilink
more antilink improvements, moving store to the db and some bugfixes
more antilink improvements, moving store to the db and some bugfixes
Lua
agpl-3.0
topkecleon/otouto
eafbb9ec5dcad8c1942cbe8e5698bf9d549394a3
scene/info.lua
scene/info.lua
-- -- Ekran wyświetlający komunikat. -- -- Wymagane moduły local app = require( 'lib.app' ) local preference = require( 'preference' ) local composer = require( 'composer' ) local fx = require( 'com.ponywolf.ponyfx' ) local tiled = require( 'com.ponywolf.ponytiled' ) local json = require( 'json' ) -- Lokalne zmienne local scene = composer.newScene() local info, ui local resumeGame = false function scene:create( event ) local sceneGroup = self.view local buttonSound = audio.loadSound( 'scene/endless/sfx/select.wav' ) -- Wczytanie mapy local uiData = json.decodeFile( system.pathForFile( 'scene/menu/ui/info.json', system.ResourceDirectory ) ) info = tiled.new( uiData, 'scene/menu/ui' ) info.x, info.y = display.contentCenterX - info.designedWidth/2, display.contentCenterY - info.designedHeight/2 -- Obsługa przycisków info.extensions = 'scene.menu.lib.' info:extend( 'button', 'label' ) function ui( event ) local phase = event.phase local name = event.buttonName if phase == 'released' then app.playSound( buttonSound ) if ( name == 'ok' ) then resumeGame = true composer.hideOverlay( 'slideUp' ) elseif ( name == 'chooseball' ) then composer.showOverlay('scene.chooseball', { isModal=true, effect='fromTop', params={} } ) end end return true end sceneGroup:insert( info ) end function scene:show( event ) local phase = event.phase if ( phase == 'will' ) then elseif ( phase == 'did' ) then app.addRuntimeEvents( {'ui', ui} ) end end function scene:hide( event ) local phase = event.phase local previousScene = event.parent if ( phase == 'will' ) then app.removeAllRuntimeEvents() elseif ( phase == 'did' ) then if resumeGame then previousScene:resumeGame() end end end function scene:destroy( event ) audio.stop() audio.dispose( buttonSound ) --collectgarbage() end scene:addEventListener( 'create' ) scene:addEventListener( 'show' ) scene:addEventListener( 'hide' ) scene:addEventListener( 'destroy' ) return scene
-- -- Ekran wyświetlający komunikat. -- -- Wymagane moduły local app = require( 'lib.app' ) local preference = require( 'preference' ) local composer = require( 'composer' ) local fx = require( 'com.ponywolf.ponyfx' ) local tiled = require( 'com.ponywolf.ponytiled' ) local json = require( 'json' ) -- Lokalne zmienne local scene = composer.newScene() local info, ui local resumeGame = false function scene:create( event ) local sceneGroup = self.view local buttonSound = audio.loadSound( 'scene/endless/sfx/select.wav' ) -- Wczytanie mapy local uiData = json.decodeFile( system.pathForFile( 'scene/menu/ui/info.json', system.ResourceDirectory ) ) info = tiled.new( uiData, 'scene/menu/ui' ) info.x, info.y = display.contentCenterX - info.designedWidth/2, display.contentCenterY - info.designedHeight/2 -- Obsługa przycisków info.extensions = 'scene.menu.lib.' info:extend( 'button', 'label' ) function ui( event ) local phase = event.phase local name = event.buttonName if phase == 'released' then app.playSound( buttonSound ) if ( name == 'ok' ) then resumeGame = true composer.hideOverlay( 'slideUp' ) elseif ( name == 'chooseball' ) then timer.performWithDelay( 100, function() composer.showOverlay('scene.chooseball', { isModal=true, effect='fromTop', params={} } ) end ) end end return true end sceneGroup:insert( info ) end function scene:show( event ) local phase = event.phase if ( phase == 'will' ) then elseif ( phase == 'did' ) then app.addRuntimeEvents( {'ui', ui} ) end end function scene:hide( event ) local phase = event.phase local previousScene = event.parent if ( phase == 'will' ) then app.removeAllRuntimeEvents() elseif ( phase == 'did' ) then if resumeGame then previousScene:resumeGame() end end end function scene:destroy( event ) audio.stop() audio.dispose( buttonSound ) --collectgarbage() end scene:addEventListener( 'create' ) scene:addEventListener( 'show' ) scene:addEventListener( 'hide' ) scene:addEventListener( 'destroy' ) return scene
Bugfix with no sound
Bugfix with no sound
Lua
mit
ldurniat/The-Great-Pong,ldurniat/My-Pong-Game
79c656da2d4a725c7845e40fc0ddedc70ad046b2
spawn/init.lua
spawn/init.lua
local kill = require "spawn.kill" local posix = require "spawn.posix" local sigset = require "spawn.sigset" local wait = require "spawn.wait" local default_file_actions = posix.new_file_actions() local default_attr = posix.new_attr() local function start(program, ...) return posix.spawnp(program, default_file_actions, default_attr, { program, ... }, nil) end local function run(program, ...) return wait.waitpid(start(program, ...)) end local function system(arg) return run("/bin/sh", "-c", arg) end return { kill = kill; posix = posix; sigset = sigset; wait = wait; start = start; run = run; system = system; }
local kill = require "spawn.kill" local posix = require "spawn.posix" local sigset = require "spawn.sigset" local wait = require "spawn.wait" local default_file_actions = posix.new_file_actions() local default_attr = posix.new_attr() local function start(program, ...) return posix.spawnp(program, default_file_actions, default_attr, { program, ... }, nil) end local function run(...) local pid, err, errno = start(...) if pid == nil then return nil, err, errno end return wait.waitpid(pid) end local function system(arg) return run("/bin/sh", "-c", arg) end return { kill = kill; posix = posix; sigset = sigset; wait = wait; start = start; run = run; system = system; }
spawn/init: Fix error handling in `run`
spawn/init: Fix error handling in `run`
Lua
mit
daurnimator/lua-spawn
18a815527129ea65a709dce6bb41466a2535a79f
src/core/buffer.lua
src/core/buffer.lua
module(...,package.seeall) local ffi = require("ffi") local memory = require("core.memory") local freelist = require("core.freelist") local lib = require("core.lib") local C = ffi.C require("core.packet_h") max = 10e5 allocated = 0 buffersize = 4096 buffers = freelist.new("struct buffer *", max) buffer_t = ffi.typeof("struct buffer") buffer_ptr_t = ffi.typeof("struct buffer *") -- Array of registered virtio devices. -- This is used to return freed buffers to their devices. virtio_devices = {} -- Return a ready-to-use buffer, or nil if none is available. function allocate () return freelist.remove(buffers) or new_buffer() end -- Return a newly created buffer, or nil if none can be created. function new_buffer () assert(allocated < max, "out of buffers") allocated = allocated + 1 local pointer, physical, bytes = memory.dma_alloc(buffersize) local b = lib.malloc("struct buffer") b.pointer, b.physical, b.size = pointer, physical, buffersize return b end -- Free a buffer that is no longer in use. function free (b) if b.origin.type == C.BUFFER_ORIGIN_VIRTIO then virtio_devices[b.origin.info.virtio.device_id]:return_virtio_buffer(b) else freelist.add(buffers, b) end end -- Accessors for important structure elements. function pointer (b) return b.pointer end function physical (b) return b.physical end function size (b) return b.size end -- Create buffers until at least N are ready for use. -- This is a way to pay the cost of allocating buffer memory in advance. function preallocate (n) while freelist.nfree(buffers) < n do free(new_buffer()) end end function add_virtio_device (d) local index = #virtio_devices + 1 virtio_devices[index] = d return index end function delete_virtio_device (index) virtio_devices[index] = nil end
module(...,package.seeall) local ffi = require("ffi") local memory = require("core.memory") local freelist = require("core.freelist") local lib = require("core.lib") local C = ffi.C require("core.packet_h") max = 10e5 allocated = 0 buffersize = 4096 buffers = freelist.new("struct buffer *", max) buffer_t = ffi.typeof("struct buffer") buffer_ptr_t = ffi.typeof("struct buffer *") -- Array of registered virtio devices. -- This is used to return freed buffers to their devices. virtio_devices = {} -- Return a ready-to-use buffer, or nil if none is available. function allocate () return freelist.remove(buffers) or new_buffer() end -- Return a newly created buffer, or nil if none can be created. function new_buffer () assert(allocated < max, "out of buffers") allocated = allocated + 1 local pointer, physical, bytes = memory.dma_alloc(buffersize) local b = lib.malloc("struct buffer") b.pointer, b.physical, b.size = pointer, physical, buffersize b.origin.type = C.BUFFER_ORIGIN_UNKNOWN return b end -- Free a buffer that is no longer in use. function free (b) if b.origin.type == C.BUFFER_ORIGIN_VIRTIO then virtio_devices[b.origin.info.virtio.device_id]:return_virtio_buffer(b) else freelist.add(buffers, b) end end -- Accessors for important structure elements. function pointer (b) return b.pointer end function physical (b) return b.physical end function size (b) return b.size end -- Create buffers until at least N are ready for use. -- This is a way to pay the cost of allocating buffer memory in advance. function preallocate (n) while freelist.nfree(buffers) < n do free(new_buffer()) end end function add_virtio_device (d) local index = #virtio_devices + 1 virtio_devices[index] = d return index end function delete_virtio_device (index) virtio_devices[index] = nil end
Fix initialization bug in buffer.new_buffer()
Fix initialization bug in buffer.new_buffer() The origin.type member of a newly allocated buffer needs to be set explicitely after receiving a memory block with undefined contents from malloc(3).
Lua
apache-2.0
Igalia/snabb,snabbco/snabb,eugeneia/snabbswitch,Igalia/snabb,snabbco/snabb,lukego/snabb,dpino/snabb,lukego/snabbswitch,eugeneia/snabb,virtualopensystems/snabbswitch,lukego/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,pirate/snabbswitch,justincormack/snabbswitch,heryii/snabb,alexandergall/snabbswitch,kellabyte/snabbswitch,aperezdc/snabbswitch,javierguerragiraldez/snabbswitch,dpino/snabb,pavel-odintsov/snabbswitch,wingo/snabbswitch,andywingo/snabbswitch,mixflowtech/logsensor,xdel/snabbswitch,fhanik/snabbswitch,snabbco/snabb,lukego/snabb,kbara/snabb,Igalia/snabb,snabbnfv-goodies/snabbswitch,lukego/snabb,kbara/snabb,xdel/snabbswitch,heryii/snabb,andywingo/snabbswitch,wingo/snabbswitch,justincormack/snabbswitch,Igalia/snabb,virtualopensystems/snabbswitch,dpino/snabbswitch,eugeneia/snabb,kbara/snabb,snabbnfv-goodies/snabbswitch,alexandergall/snabbswitch,aperezdc/snabbswitch,kellabyte/snabbswitch,wingo/snabbswitch,dwdm/snabbswitch,kbara/snabb,aperezdc/snabbswitch,eugeneia/snabb,fhanik/snabbswitch,Igalia/snabb,eugeneia/snabbswitch,Igalia/snabbswitch,wingo/snabb,wingo/snabb,xdel/snabbswitch,Igalia/snabbswitch,pirate/snabbswitch,alexandergall/snabbswitch,dpino/snabb,plajjan/snabbswitch,snabbco/snabb,SnabbCo/snabbswitch,Igalia/snabb,pirate/snabbswitch,kbara/snabb,hb9cwp/snabbswitch,dpino/snabbswitch,snabbco/snabb,wingo/snabbswitch,eugeneia/snabb,dpino/snabb,pavel-odintsov/snabbswitch,kbara/snabb,eugeneia/snabb,pavel-odintsov/snabbswitch,hb9cwp/snabbswitch,plajjan/snabbswitch,kellabyte/snabbswitch,javierguerragiraldez/snabbswitch,heryii/snabb,snabbnfv-goodies/snabbswitch,eugeneia/snabbswitch,Igalia/snabb,dwdm/snabbswitch,eugeneia/snabb,dpino/snabb,wingo/snabb,mixflowtech/logsensor,Igalia/snabb,aperezdc/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,heryii/snabb,hb9cwp/snabbswitch,dpino/snabbswitch,eugeneia/snabbswitch,justincormack/snabbswitch,mixflowtech/logsensor,javierguerragiraldez/snabbswitch,snabbco/snabb,virtualopensystems/snabbswitch,plajjan/snabbswitch,dpino/snabbswitch,fhanik/snabbswitch,heryii/snabb,snabbnfv-goodies/snabbswitch,alexandergall/snabbswitch,justincormack/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,eugeneia/snabb,SnabbCo/snabbswitch,wingo/snabb,snabbco/snabb,wingo/snabb,alexandergall/snabbswitch,andywingo/snabbswitch,hb9cwp/snabbswitch,mixflowtech/logsensor,plajjan/snabbswitch,mixflowtech/logsensor,dpino/snabb,heryii/snabb,dwdm/snabbswitch,wingo/snabb,Igalia/snabbswitch,lukego/snabbswitch,dpino/snabb,alexandergall/snabbswitch,lukego/snabb,SnabbCo/snabbswitch,lukego/snabbswitch,Igalia/snabbswitch,andywingo/snabbswitch
fa2c9156b1de9be58fe8ae8efbc161a24eacb096
src/System.lua
src/System.lua
local P = {} local Log = require 'Log' function P.quote(...) local function quote(arg) return string.format('%q', tostring(arg)) end return table.concat(table.imap({...}, quote), ' ') end function P.mkpath(...) local sep = '/' local path = {} for _, c in ipairs({...}) do table.insert(path, c) end return table.concat(path, sep) end function P.exec(cmdline, ...) local command = string.format(cmdline, ...) Log.debug2(command) local status = os.execute(command) return status == 0, status % 0xFF end function P.popen(cmdline, ...) local prog = string.format(cmdline, ...) Log.debug2(prog) return assert(io.popen(prog)) end function P.pread(format, cmdline, ...) local file = P.popen(cmdline, ...) local out = file:read(format) file:close() return out end function P.getenv(vars) local o = {} for _, v in ipairs(vars) do local value = os.getenv(v) assert(value and #value > 0, string.format("the environment variable '%s' is not set", v)) table.insert(o, value) end return o end function P.rmrf(...) return P.exec('rm -rf %s', P.quote(...)) end function P.mkdir(...) return P.exec('mkdir -p %s', P.quote(...)) end function P.exists(path) return P.exec('test -e "%s"', path) end function P.file_exists(path) return P.exec('test -f "%s"', path) end function P.is_empty(path) return P.pread('*l', 'cd "%s" && echo *', path) == '*' end return P
local P = {} local Log = require 'Log' function P.quote(...) local function quote(arg) return string.format('%q', tostring(arg)) end return table.concat(table.imap({...}, quote), ' ') end function P.expand(...) return P.pread('*a', 'printf "%s" '..P.quote(...), '%s') end function P.mkpath(...) local sep = '/' local path = {} for _, c in ipairs({...}) do table.insert(path, c) end return table.concat(path, sep) end function P.exec(cmdline, ...) Log.debug2(cmdline, ...) local command = string.format(cmdline, ...) local status = os.execute(command) return status == 0, status % 0xFF end function P.popen(cmdline, ...) Log.debug2(cmdline, ...) local prog = string.format(cmdline, ...) return assert(io.popen(prog)) end function P.pread(format, cmdline, ...) local file = P.popen(cmdline, ...) local out = file:read(format) file:close() return out end function P.getenv(vars) local o = {} for _, v in ipairs(vars) do local value = os.getenv(v) assert(value and #value > 0, string.format("the environment variable '%s' is not set", v)) table.insert(o, value) end return o end function P.rmrf(...) return P.exec('rm -rf %s', P.quote(...)) end function P.mkdir(...) return P.exec('mkdir -p %s', P.quote(...)) end function P.exists(path) return P.exec('test -e "%s"', path) end function P.file_exists(path) return P.exec('test -f "%s"', path) end function P.is_empty(path) return P.pread('*l', 'cd "%s" && echo *', path) == '*' end return P
Add System.expand, fix double expansion of command when debug logging
Add System.expand, fix double expansion of command when debug logging
Lua
mit
bazurbat/jagen
7bb0d4215eeb03b771f549979404a21204c3be71
src/Source.lua
src/Source.lua
local system = require 'system' local Source = {} function Source:new(o) local o = o or {} setmetatable(o, self) self.__index = self return o end local GitSource = Source:new() local HgSource = Source:new() local RepoSource = Source:new() -- Source function Source:is_scm() return self.type == 'git' or self.type == 'hg' or self.type == 'repo' end function Source:basename(filename) local name = string.match(filename, '^.*/(.+)') or filename local exts = { '%.git', '%.tar', '%.tgz', '%.txz', '%.tbz2', '%.zip', '%.rar', '' } for _, ext in ipairs(exts) do local match = string.match(name, '^([%w_.-]+)'..ext) if match then return match end end end function Source:create(source) local source = source or {} if source.type == 'git' then source = GitSource:new(source) elseif source.type == 'hg' then source = HgSource:new(source) elseif source.type == 'repo' then source = RepoSource:new(source) elseif source.type == 'dist' then source.location = '$jagen_dist_dir/'..source.location source = Source:new(source) else source = Source:new(source) end if source.location and source.type ~= 'curl' then local dir = source:is_scm() and '$jagen_src_dir' or '$pkg_work_dir' local basename = source:basename(source.location) source.path = system.mkpath(dir, source.path or basename) end return source end -- GitSource function GitSource:new(o) local source = Source.new(GitSource, o) source.branch = source.branch or 'master' return source end function GitSource:exec(...) return system.exec('git', '-C', assert(self.path), ...) end function GitSource:popen(...) return system.popen('git', '-C', assert(self.path), ...):read() end function GitSource:head() return self:popen('rev-parse', 'HEAD') end function GitSource:dirty() return self:popen('status', '--porcelain') end function GitSource:clean() return self:exec('checkout', 'HEAD', '.') and self:exec('clean', '-fxd') end function GitSource:update() local branch = assert(self.branch) local cmd = { 'fetch', '--prune', '--no-tags', 'origin', string.format('+refs/heads/%s:refs/remotes/origin/%s', branch, branch) } return self:exec(unpack(cmd)) end function GitSource:_is_branch(pattern) local branch = self:popen('branch', '-a', '--list', pattern) local exists, active = false, false if branch and #branch > 0 then exists = true active = string.sub(branch, 1, 1) == '*' end return exists, active end function GitSource:_checkout() local branch = assert(self.branch) local exists, active = self:_is_branch(branch) if active then return true elseif exists then return self:exec('checkout', branch) else local start_point = 'origin/'..branch exists = self:_is_branch(start_point) if exists then local add = { 'remote', 'set-branches', 'origin', branch } local checkout = { 'checkout', '-b', branch, start_point } return self:exec(unpack(add)) and self:exec(unpack(checkout)) else jagen.error("could not find branch '%s' in local repository", branch) return false end end end function GitSource:_merge() local branch = assert(self.branch) local cmd = { 'merge', '--ff-only', string.format('origin/%s', branch) } return self:exec(unpack(cmd)) end function GitSource:switch() return self:_checkout() and self:_merge() end function GitSource:clone() return system.exec('git', 'clone', '--branch', assert(self.branch), '--depth', 1, assert(self.location), assert(self.path)) end -- HgSource function HgSource:new(o) local source = Source.new(HgSource, o) source.branch = source.branch or 'default' return source end function HgSource:exec(...) return system.exec('hg', '-R', assert(self.path), ...) end function HgSource:popen(...) return system.popen('hg', '-R', assert(self.path), ...):read() end function HgSource:head() return self:popen('id', '-i') end function HgSource:dirty() return self:popen('status') end function HgSource:clean() return self:exec('update', '-C', assert(self.branch)) and self:exec('purge', '--all') end function HgSource:update() local cmd = { 'pull', '-r', assert(self.branch) } return self:exec(unpack(cmd)) end function HgSource:switch() local cmd = { 'update', '-r', assert(self.branch) } return self:exec(unpack(cmd)) end function HgSource:clone() return system.exec('hg', 'clone', '-r', assert(self.branch), assert(self.location), assert(self.path)) end -- RepoSource function RepoSource:new(o) local source = Source.new(RepoSource, o) source.jobs = jagen.nproc * 2 return source end function RepoSource:exec(...) local cmd = { 'cd', '"'..assert(self.path)..'"', '&&', 'repo', ... } return system.exec(unpack(cmd)) end function RepoSource:popen(...) local cmd = { 'cd', '"'..assert(self.path)..'"', '&&', 'repo', ... } return system.popen(unpack(cmd)) end function RepoSource:head() return self:popen('status', '-j', 1, '--orphans'):read('*all') end function RepoSource:dirty() return false end function RepoSource:_load_projects(...) local o = {} local list = self:popen('list', ...) while true do local line = list:read() if not line then break end local path, name = string.match(line, "(.+)%s:%s(.+)") if name then o[name] = path end end return o end function RepoSource:clean() local projects = self:load_projects() local function is_empty(path) return system.popen('cd', '"'..path..'"', '&&', 'echo', '*'):read() == '*' end for n, p in pairs(projects) do local path = system.mkpath(self.path, p) if not is_empty(path) then if not system.exec('git', '-C', path, 'checkout', 'HEAD', '.') then return false end if not system.exec('git', '-C', path, 'clean', '-fxd') then return false end end end return true end function RepoSource:update() local cmd = { 'sync', '-j', self.jobs, '--current-branch', '--no-tags', '--optimized-fetch' } return self:exec(unpack(cmd)) end function RepoSource:switch() end function RepoSource:clone() local mkdir = { 'mkdir -p "'..self.path..'"' } local init = { 'init', '-u', assert(self.location), '-b', assert(self.branch), '-p', 'linux', '--depth', 1 } return system.exec(unpack(mkdir)) and self:exec(unpack(init)) and self:update() end return Source
local system = require 'system' local Source = {} function Source:new(o) local o = o or {} setmetatable(o, self) self.__index = self return o end local GitSource = Source:new() local HgSource = Source:new() local RepoSource = Source:new() -- Source function Source:is_scm() return self.type == 'git' or self.type == 'hg' or self.type == 'repo' end function Source:basename(filename) local name = string.match(filename, '^.*/(.+)') or filename local exts = { '%.git', '%.tar', '%.tgz', '%.txz', '%.tbz2', '%.zip', '%.rar', '' } for _, ext in ipairs(exts) do local match = string.match(name, '^([%w_.-]+)'..ext) if match then return match end end end function Source:create(source) local source = source or {} if source.type == 'git' then source = GitSource:new(source) elseif source.type == 'hg' then source = HgSource:new(source) elseif source.type == 'repo' then source = RepoSource:new(source) elseif source.type == 'dist' then source.location = '$jagen_dist_dir/'..source.location source = Source:new(source) else source = Source:new(source) end if source.location and source.type ~= 'curl' then local dir = source:is_scm() and '$jagen_src_dir' or '$pkg_work_dir' local basename = source:basename(source.location) source.path = system.mkpath(dir, source.path or basename) end return source end -- GitSource function GitSource:new(o) local source = Source.new(GitSource, o) source.branch = source.branch or 'master' return source end function GitSource:exec(...) return system.exec('git', '-C', assert(self.path), ...) end function GitSource:popen(...) return system.popen('git', '-C', assert(self.path), ...):read() end function GitSource:head() return self:popen('rev-parse', 'HEAD') end function GitSource:dirty() return self:popen('status', '--porcelain') end function GitSource:clean() return self:exec('checkout', 'HEAD', '.') and self:exec('clean', '-fxd') end function GitSource:update() local branch = assert(self.branch) local cmd = { 'fetch', '--prune', '--no-tags', 'origin', string.format('+refs/heads/%s:refs/remotes/origin/%s', branch, branch) } return self:exec(unpack(cmd)) end function GitSource:_is_branch(pattern) local branch = self:popen('branch', '-a', '--list', pattern) local exists, active = false, false if branch and #branch > 0 then exists = true active = string.sub(branch, 1, 1) == '*' end return exists, active end function GitSource:_checkout() local branch = assert(self.branch) local exists, active = self:_is_branch(branch) if active then return true elseif exists then return self:exec('checkout', branch) else local start_point = 'origin/'..branch exists = self:_is_branch(start_point) if exists then local add = { 'remote', 'set-branches', 'origin', branch } local checkout = { 'checkout', '-b', branch, start_point } return self:exec(unpack(add)) and self:exec(unpack(checkout)) else jagen.error("could not find branch '%s' in local repository", branch) return false end end end function GitSource:_merge() local branch = assert(self.branch) local cmd = { 'merge', '--ff-only', string.format('origin/%s', branch) } return self:exec(unpack(cmd)) end function GitSource:switch() return self:_checkout() and self:_merge() end function GitSource:clone() return system.exec('git', 'clone', '--branch', assert(self.branch), '--depth', 1, assert(self.location), assert(self.path)) end -- HgSource function HgSource:new(o) local source = Source.new(HgSource, o) source.branch = source.branch or 'default' return source end function HgSource:exec(...) return system.exec('hg', '-R', assert(self.path), ...) end function HgSource:popen(...) return system.popen('hg', '-R', assert(self.path), ...):read() end function HgSource:head() return self:popen('id', '-i') end function HgSource:dirty() return self:popen('status') end function HgSource:clean() return self:exec('update', '-C', assert(self.branch)) and self:exec('purge', '--all') end function HgSource:update() local cmd = { 'pull', '-r', assert(self.branch) } return self:exec(unpack(cmd)) end function HgSource:switch() local cmd = { 'update', '-r', assert(self.branch) } return self:exec(unpack(cmd)) end function HgSource:clone() return system.exec('hg', 'clone', '-r', assert(self.branch), assert(self.location), assert(self.path)) end -- RepoSource function RepoSource:new(o) local source = Source.new(RepoSource, o) source.jobs = jagen.nproc * 2 return source end function RepoSource:exec(...) local cmd = { 'cd', '"'..assert(self.path)..'"', '&&', 'repo', ... } return system.exec(unpack(cmd)) end function RepoSource:popen(...) local cmd = { 'cd', '"'..assert(self.path)..'"', '&&', 'repo', ... } return system.popen(unpack(cmd)) end function RepoSource:head() return self:popen('status', '-j', 1, '--orphans'):read('*all') end function RepoSource:dirty() return false end function RepoSource:_load_projects(...) local o = {} local list = self:popen('list', ...) while true do local line = list:read() if not line then break end local path, name = string.match(line, "(.+)%s:%s(.+)") if name then o[name] = path end end return o end function RepoSource:clean() local projects = self:_load_projects() local function is_empty(path) return system.popen('cd', '"'..path..'"', '&&', 'echo', '*'):read() == '*' end local function is_dirty(path) local cmd = { 'git', '-C', assert(path), 'status', '--porcelain' } return system.popen(unpack(cmd)):read() ~= nil end for n, p in pairs(projects) do local path = system.mkpath(self.path, p) if not is_empty(path) and is_dirty(path) then if not system.exec('git', '-C', path, 'checkout', 'HEAD', '.') then return false end if not system.exec('git', '-C', path, 'clean', '-fxd') then return false end end end return true end function RepoSource:update() local cmd = { 'sync', '-j', self.jobs, '--current-branch', '--no-tags', '--optimized-fetch' } return self:exec(unpack(cmd)) end function RepoSource:switch() return true -- TODO -- local cmd = { 'checkout', assert(self.branch) } -- return self:exec(unpack(cmd)) end function RepoSource:clone() local mkdir = { 'mkdir -p "'..self.path..'"' } local init = { 'init', '-u', assert(self.location), '-b', assert(self.branch), '-p', 'linux', '--depth', 1 } return system.exec(unpack(mkdir)) and self:exec(unpack(init)) and self:update() end return Source
Fix RepoSource clean command
Fix RepoSource clean command
Lua
mit
bazurbat/jagen
037b74ae662ac6607117e705bd43457b87ee84b9
wyx/ui/TooltipFactory.lua
wyx/ui/TooltipFactory.lua
local Class = require 'lib.hump.class' local Tooltip = getClass 'wyx.ui.Tooltip' local Text = getClass 'wyx.ui.Text' local Bar = getClass 'wyx.ui.Bar' local Frame = getClass 'wyx.ui.Frame' local Style = getClass 'wyx.ui.Style' local property = require 'wyx.component.property' local math_ceil = math.ceil local colors = colors -- some constants local MARGIN = 16 local MINWIDTH = 300 -- Common styles for tooltips local tooltipStyle = Style({ bgcolor = colors.BLACK_A85, bordersize = 4, borderinset = 4, bordercolor = colors.GREY30, }) local header1Style = Style({ font = GameFont.small, fontcolor = colors.WHITE, }) local header2Style = header1Style:clone({ fontcolor = colors.GREY90, }) local textStyle = Style({ font = GameFont.verysmall, fontcolor = colors.GREY80, }) local iconStyle = Style({ bordersize = 2, bordercolor = colors.GREY60, bgcolor = colors.GREY10, fgcolor = colors.WHITE, }) local healthBarStyle = Style({ fgcolor = colors.RED, bgcolor = colors.DARKRED, }) -- TooltipFactory -- local TooltipFactory = Class{name='TooltipFactory', function(self) end } -- destructor function TooltipFactory:destroy() end -- make a tooltip for an entity function TooltipFactory:makeEntityTooltip(entity) local entity = type(id) == 'number' and EntityRegistry:get(id) or id verifyClass('wyx.entity.Entity', entity) local name = entity:getName() local family = entity:getFamily() local kind = entity:getKind() local description = entity:getDescription() local headerW = 0 -- make the icon local icon local image = entity:query(property('TileSet')) if image then local allcoords = entity:query(property('TileCoords')) local coords local coords = allcoords.item or allcoords.front or allcoords.right or allcoords.left if not coords then for k in pairs(allcoords) do coords = allcoords[k]; break end end if coords then local size = entity:query(property('TileSize')) if size then local x, y = (coords[1]-1) * size, (coords[2]-1) * size icon = self:_makeIcon(image, x, y, size, size) else warning('makeEntityTooltip: bad TileSize property in entity %q', name) end else warning('makeEntityTooltip: bad TileCoords property in entity %q', name) end else warning('makeEntityTooltip: bad TileSet property in entity %q', name) end -- make the first header local header1 if name then header1 = self:_makeHeader1(name) headerW = header1:getWidth() else warning('makeEntityTooltip: bad Name for entity %q', tostring(entity)) end -- make the second header local header2 if family and kind then local string = family..' ('..kind..')' header2 = self:_makeHeader2(string) local width = header2:getWidth() headerW = width > headerW and width or headerW else warning('makeEntityTooltip: missing family or kind for entity %q', name) end headerW = icon and headerW + icon:getWidth() + MARGIN or headerW local width = headerW > MINWIDTH and headerW or MINWIDTH -- make the health bar local health = entity:query(property('Health')) local maxHealth = entity:query(property('MaxHealth')) local healthBar if health and maxHealth then healthBar = Bar(0, 0, width, margin) healthBar:setNormalStyle(healthBarStyle) healthBar:setLimits(0, maxHealth) healthBar:setValue(health) end -- make the stats frames -- TODO -- make the description local body if description then body = self:_makeText(description, width) else warning('makeEntityTooltip: missing description for entity %q', name) end -- make the tooltip local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if icon then tooltip:setIcon(icon) end if header1 then tooltip:setHeader1(header1) end if header2 then tooltip:setHeader2(header2) end if healthBar then tooltip:addBar(healthBar) end if stats then for i=1,numStats do local stat = stats[i] tooltip:addText(stat) end end if body then if stats then tooltip:addSpace() end tooltip:addText(body) end return tooltip end -- make a simple generic tooltip with a header and text function TooltipFactory:makeSimpleTooltip(header, text) verify('string', header, text) local header1 = self:_makeHeader1(header) local headerW = header1:getWidth() local width = headerW > MINWIDTH and headerW or MINWIDTH local body = self:_makeText(text, width) local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if header1 then tooltip:setHeader1(header1) end if body then tooltip:addText(body) end return tooltip end -- make an icon frame function TooltipFactory:_makeIcon(image, x, y, w, h) local style = iconStyle:clone({fgimage = image}) style:setFGQuad(x, y, w, h) local icon = Frame(0, 0, w, h) icon:setNormalStyle(style, true) return icon end -- make a header1 Text frame function TooltipFactory:_makeHeader1(text) local font = header1Style:getFont() local fontH = font:getHeight() local width = font:getWidth(text) local header1 = Text(0, 0, width, fontH) header1:setNormalStyle(header1Style) header1:setText(text) return header1 end -- make a header2 Text frame function TooltipFactory:_makeHeader2(text) local font = header2Style:getFont() local fontH = font:getHeight() local width = font:getWidth(text) local header2 = Text(0, 0, width, fontH) header2:setNormalStyle(header2Style) header2:setText(text) return header2 end -- make a generic Text frame function TooltipFactory:_makeText(text, width) local font = textStyle:getFont() local fontH = font:getHeight() local fontW = font:getWidth(text) width = width or fontW local numLines = math_ceil(fontW / width) local line = Text(0, 0, width, numLines * fontH) line:setMaxLines(numLines) line:setNormalStyle(textStyle) line:setText(text) return line end -- the class return TooltipFactory
local Class = require 'lib.hump.class' local Tooltip = getClass 'wyx.ui.Tooltip' local Text = getClass 'wyx.ui.Text' local Bar = getClass 'wyx.ui.Bar' local Frame = getClass 'wyx.ui.Frame' local Style = getClass 'wyx.ui.Style' local property = require 'wyx.component.property' local math_ceil = math.ceil local colors = colors -- some constants local MARGIN = 16 local MINWIDTH = 300 -- Common styles for tooltips local tooltipStyle = Style({ bgcolor = colors.BLACK_A85, bordersize = 4, borderinset = 4, bordercolor = colors.GREY30, }) local header1Style = Style({ font = GameFont.small, fontcolor = colors.WHITE, }) local textStyle = Style({ font = GameFont.verysmall, fontcolor = colors.GREY70, }) local iconStyle = Style({ bordersize = 4, bordercolor = colors.GREY70, bgcolor = colors.GREY10, fgcolor = colors.WHITE, }) local healthBarStyle = Style({ fgcolor = colors.RED, bgcolor = colors.DARKRED, }) -- TooltipFactory -- local TooltipFactory = Class{name='TooltipFactory', function(self) end } -- destructor function TooltipFactory:destroy() end -- make a tooltip for an entity function TooltipFactory:makeEntityTooltip(id) local entity = type(id) == 'string' and EntityRegistry:get(id) or id verifyClass('wyx.entity.Entity', entity) local name = entity:getName() local family = entity:getFamily() local kind = entity:getKind() local description = entity:getDescription() local headerW = 0 -- make the icon local icon local tileset = entity:query(property('TileSet')) if tileset then local image = Image[tileset] local allcoords = entity:query(property('TileCoords')) local coords local coords = allcoords.item or allcoords.front or allcoords.right or allcoords.left if not coords then for k in pairs(allcoords) do coords = allcoords[k]; break end end if coords then local size = entity:query(property('TileSize')) if size then local x, y = (coords[1]-1) * size, (coords[2]-1) * size icon = self:_makeIcon(image, x, y, size, size) else warning('makeEntityTooltip: bad TileSize property in entity %q', name) end else warning('makeEntityTooltip: bad TileCoords property in entity %q', name) end else warning('makeEntityTooltip: bad TileSet property in entity %q', name) end -- make the first header local header1 if name then header1 = self:_makeHeader1(name) headerW = header1:getWidth() else warning('makeEntityTooltip: bad Name for entity %q', tostring(entity)) end headerW = icon and headerW + icon:getWidth() + MARGIN or headerW local width = headerW > MINWIDTH and headerW or MINWIDTH -- make the health bar local health = entity:query(property('Health')) local maxHealth = entity:query(property('MaxHealth')) local healthBar if health and maxHealth then healthBar = Bar(0, 0, width, margin) healthBar:setNormalStyle(healthBarStyle) healthBar:setLimits(0, maxHealth) healthBar:setValue(health) end -- make the family and kind line local famLine if family and kind then local string = family..' ('..kind..')' famLine = self:_makeText(string) local width = famLine:getWidth() else warning('makeEntityTooltip: missing family or kind for entity %q', name) end -- make the stats frames -- TODO -- make the description local body if description then body = self:_makeText(description, width) else warning('makeEntityTooltip: missing description for entity %q', name) end -- make the tooltip local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if icon then tooltip:setIcon(icon) end if header1 then tooltip:setHeader1(header1) end if healthBar then tooltip:addBar(healthBar) end if famLine then tooltip:addText(famLine) end if stats then for i=1,numStats do local stat = stats[i] tooltip:addText(stat) end end if body then if stats then tooltip:addSpace() end tooltip:addText(body) end return tooltip end -- make a simple generic tooltip with text function TooltipFactory:makeVerySimpleTooltip(text) verifyAny(text, 'string', 'function') local body = self:_makeText(text) local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if body then tooltip:addText(body) end return tooltip end -- make a simple generic tooltip with a header and text function TooltipFactory:makeSimpleTooltip(header, text) verify('string', header) verifyAny(text, 'string', 'function') local header1 = self:_makeHeader1(header) local headerW = header1:getWidth() local width = headerW > MINWIDTH and headerW or MINWIDTH local body = self:_makeText(text, width) local tooltip = Tooltip() tooltip:setNormalStyle(tooltipStyle) tooltip:setMargin(MARGIN) if header1 then tooltip:setHeader1(header1) end if body then tooltip:addText(body) end return tooltip end -- make an icon frame function TooltipFactory:_makeIcon(image, x, y, w, h) local style = iconStyle:clone({fgimage = image}) style:setFGQuad(x, y, w, h) local icon = Frame(0, 0, w, h) icon:setNormalStyle(style, true) return icon end -- make a header1 Text frame function TooltipFactory:_makeHeader1(text) local font = header1Style:getFont() local fontH = font:getHeight() local width = font:getWidth(text) local header1 = Text(0, 0, width, fontH) header1:setNormalStyle(header1Style) header1:setText(text) return header1 end -- make a header2 Text frame function TooltipFactory:_makeHeader2(text) local font = header2Style:getFont() local fontH = font:getHeight() local width = font:getWidth(text) local header2 = Text(0, 0, width, fontH) header2:setNormalStyle(header2Style) header2:setText(text) return header2 end -- make a generic Text frame function TooltipFactory:_makeText(text, width) local isString = type(text) == 'string' local font = textStyle:getFont() local fontH = font:getHeight() local fontW = isString and font:getWidth(text) or font:getWidth(text()) width = width or fontW local numLines = math_ceil(fontW / width) local line = Text(0, 0, width, numLines * fontH) line:setMaxLines(numLines) line:setNormalStyle(textStyle) if isString then line:setText(text) else line:watch(text) end return line end -- the class return TooltipFactory
fix tooltip factory
fix tooltip factory
Lua
mit
scottcs/wyx
d25f181682aeebb0d04e44d0ca704686f037542b
src/system.lua
src/system.lua
function table.firstElement(list) for index, value in pairs(list) do return value end end System = class("System") function System:__init() -- Liste aller Entities, die die RequiredComponents dieses Systems haben self.targets = {} self.active = true end function System:requires() return {} end function System:addEntity(entity, category) -- If there are multiple requirement lists, the added entities will -- be added to their respetive list. if category then self.targets[category][entity.id] = entity else -- Otherwise they'll be added to the normal self.targets list self.targets[entity.id] = entity end end function System:removeEntity(entity) if table.firstElement(self.targets) then if table.firstElement(self.targets).__name then self.targets[entity.id] = nil else -- Removing entities from their respective category target list. if self.targets[index] then for index, value in pairs(self:requires()) do self.targets[index][entity.id] = nil end end end end end function System:pickRequiredComponents(entity) local components = {} for i, componentName in pairs(self:requires()) do table.insert(components, entity:get(componentName)) end return unpack(components) end
function table.firstElement(list) for index, value in pairs(list) do return value end end System = class("System") function System:__init() -- Liste aller Entities, die die RequiredComponents dieses Systems haben self.targets = {} self.active = true end function System:requires() return {} end function System:addEntity(entity, category) -- If there are multiple requirement lists, the added entities will -- be added to their respetive list. if category then self.targets[category][entity.id] = entity else -- Otherwise they'll be added to the normal self.targets list self.targets[entity.id] = entity end end function System:removeEntity(entity) if table.firstElement(self.targets) then if table.firstElement(self.targets).__name then self.targets[entity.id] = nil else -- Removing entities from their respective category target list. for index, _ in pairs(self.targets) do self.targets[index][entity.id] = nil end end end end function System:pickRequiredComponents(entity) local components = {} for i, componentName in pairs(self:requires()) do table.insert(components, entity:get(componentName)) end return unpack(components) end
Multiple requirement removing of system fixed
Multiple requirement removing of system fixed
Lua
mit
takaaptech/lovetoys,xpol/lovetoys
d7abb2b7a0bf0a51d7d7da685fe5e63ddede2426
gumbo/serialize/html5lib.lua
gumbo/serialize/html5lib.lua
local util = require "gumbo.serialize.util" local Rope = util.Rope return function(node) local rope = Rope() local indent = " " local level = 0 local function serialize(node) if node.type == "element" then local i1, i2 = indent:rep(level), indent:rep(level+1) if node.tag_namespace then rope:appendf('| %s<%s %s>\n', i1, node.tag_namespace, node.tag) else rope:appendf('| %s<%s>\n', i1, node.tag) end local attr = node.attr if attr then table.sort(attr, function(x, y) return x.name < y.name end) for i = 1, #attr do local a = attr[i] if a.namespace then rope:appendf('| %s%s %s="%s"\n', i2, a.namespace, a.name, a.value) else rope:appendf('| %s%s="%s"\n', i2, a.name, a.value) end end end level = level + 1 for i = 1, #node do serialize(node[i]) end level = level - 1 elseif node.type == "text" then rope:appendf('| %s"%s"\n', indent:rep(level), node.text) elseif node.type == "comment" then rope:appendf('| %s<!-- %s -->\n', indent:rep(level), node.text) elseif node.type == "document" then if node.has_doctype == true then rope:appendf('| <!DOCTYPE %s>\n', node.name) end for i = 1, #node do serialize(node[i]) end end end serialize(node) return rope:concat() end
local util = require "gumbo.serialize.util" local Rope = util.Rope return function(node) local rope = Rope() local indent = " " local level = 0 local function serialize(node) if node.type == "element" then local i1, i2 = indent:rep(level), indent:rep(level+1) if node.tag_namespace then rope:appendf('| %s<%s %s>\n', i1, node.tag_namespace, node.tag) else rope:appendf('| %s<%s>\n', i1, node.tag) end local attr = node.attr if attr then table.sort(attr, function(x, y) return x.name < y.name end) for i = 1, #attr do local a = attr[i] if a.namespace then rope:appendf('| %s%s %s="%s"\n', i2, a.namespace, a.name, a.value) else rope:appendf('| %s%s="%s"\n', i2, a.name, a.value) end end end level = level + 1 for i = 1, #node do serialize(node[i]) end level = level - 1 elseif node.type == "text" then rope:appendf('| %s"%s"\n', indent:rep(level), node.text) elseif node.type == "comment" then rope:appendf('| %s<!-- %s -->\n', indent:rep(level), node.text) elseif node.type == "document" then if node.has_doctype == true then local pubid = node.public_identifier local sysid = node.system_identifier rope:appendf('| <!DOCTYPE %s%s>\n', node.name, (pubid ~= "" or sysid ~= "") and string.format(' "%s" "%s"', pubid, sysid) or "" ) end for i = 1, #node do serialize(node[i]) end end end serialize(node) return rope:concat() end
Fix DOCTYPE serialization in gumbo/serialize/html5lib.lua
Fix DOCTYPE serialization in gumbo/serialize/html5lib.lua
Lua
apache-2.0
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
a2a4c534ed3f1b64a04e3224fb2f0c1d965f1cc5
interface/configenv/flow.lua
interface/configenv/flow.lua
local Flow = {} local _time_units = { [""] = 1, ms = 1 / 1000, s = 1, m = 60, h = 3600 } local _size_units = { [""] = 1, k = 10 ^ 3, ki = 2 ^ 10, m = 10 ^ 6, mi = 2 ^ 20, g = 10 ^ 9, gi = 2 ^ 30 } local _option_list = { rate = { parse = function(self, rate) if type(rate) == "number" then self.cbr = rate return end local num, unit, time = string.match(rate, "^(%d+%.?%d*)(%a*)/?(%a*)$") num, unit, time = tonumber(num), string.lower(unit), _time_units[time] if unit == "" then unit = _size_units.m * 8 elseif string.find(unit, "bit$") then unit = _size_units[string.sub(unit, 1, -4)] elseif string.find(unit, "b$") then unit = _size_units[string.sub(unit, 1, -2)] * 8 elseif string.find(unit, "p$") then unit = _size_units[string.sub(unit, 1, -2)] * self.packet:size() end unit = unit / 10 ^ 6 -- cbr is in mbit/s self.cbr = num * unit / time end, test = function(error, rate) if type(rate) ~= "number" then error:assert(string.match(rate, "^(%d+%.?%d*)(%a*)/?(%a*)$"), 3, "Invalid value for option 'rate.'") end end } } function Flow.new(name, tbl, error) local self = { name = name, packet = tbl[2], parent = tbl.parent } tbl[1], tbl[2], tbl.parent = nil, nil, nil -- TODO figure out actual queue requirements self.tx_txq, self.tx_rxq, self.rx_txq, self.rx_rxq = 1, 1, 1, 1 -- check and copy options for i,v in pairs(tbl) do local opt = _option_list[i] if opt then if (not opt.test) or opt.test(error, v) then self[i] = v end else error(4, "Unknown field %q in flow %q.", i, name) end end if type(self.parent) == "table" then local parent = self.parent self.packet:inherit(parent.packet) -- copy parent options for i in pairs(_option_list) do if not self[i] then self[i] = parent[i] end end end return setmetatable(self, { __index = Flow }) end function Flow:validate(val) self.packet:validate(val) -- validate options for i,opt in pairs(_option_list) do local v = self.options[i] or self[i] if v and opt.validate then opt.validate(val, v) end end end function Flow:prepare() for name, opt in pairs(_option_list) do local v = self.options[name] or self[name] if v then opt.parse(self, v) end end end return Flow
local Flow = {} local _time_units = { [""] = 1, ms = 1 / 1000, s = 1, m = 60, h = 3600 } local _size_units = { [""] = 1, k = 10 ^ 3, ki = 2 ^ 10, m = 10 ^ 6, mi = 2 ^ 20, g = 10 ^ 9, gi = 2 ^ 30 } local _option_list = { rate = { parse = function(self, rate) if type(rate) == "number" then self.cbr = rate return end local num, unit, time = string.match(rate, "^(%d+%.?%d*)(%a*)/?(%a*)$") num, unit, time = tonumber(num), string.lower(unit), _time_units[time] if unit == "" then unit = _size_units.m * 8 elseif string.find(unit, "bit$") then unit = _size_units[string.sub(unit, 1, -4)] elseif string.find(unit, "b$") then unit = _size_units[string.sub(unit, 1, -2)] * 8 elseif string.find(unit, "p$") then unit = _size_units[string.sub(unit, 1, -2)] * self.packet:size() end unit = unit / 10 ^ 6 -- cbr is in mbit/s self.cbr = num * unit / time end, test = function(error, rate) if type(rate) ~= "number" then error:assert(string.match(rate, "^(%d+%.?%d*)(%a*)/?(%a*)$"), 3, "Invalid value for option 'rate.'") end end } } function Flow.new(name, tbl, error) local self = { name = name, packet = tbl[2], parent = tbl.parent } tbl[1], tbl[2], tbl.parent = nil, nil, nil -- TODO figure out actual queue requirements self.tx_txq, self.tx_rxq, self.rx_txq, self.rx_rxq = 1, 1, 1, 1 -- check and copy options for i,v in pairs(tbl) do local opt = _option_list[i] if opt then if (not opt.test) or opt.test(error, v) then self[i] = v end else error(4, "Unknown field %q in flow %q.", i, name) end end if type(self.parent) == "table" then local parent = self.parent self.packet:inherit(parent.packet) -- copy parent options for i in pairs(_option_list) do if not self[i] then self[i] = parent[i] end end end return setmetatable(self, { __index = Flow }) end function Flow:validate(val) self.packet:validate(val) -- validate options for i,opt in pairs(_option_list) do local v = self[i] if v and opt.validate then opt.validate(val, v) end end end -- TODO test dynamic options function Flow:prepare() for name, opt in pairs(_option_list) do local v = self.options[name] or self[name] if v then opt.parse(self, v) end end end return Flow
Fix option validation.
Fix option validation.
Lua
mit
scholzd/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,emmericp/MoonGen
9d432517b71840322ed2f2475547a5524aa6d49d
gjk.lua
gjk.lua
--[[ Copyright (c) 2012 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local _PACKAGE = (...):match("^(.+)%.[^%.]+") local vector = require(_PACKAGE .. '.vector-light') local huge, abs = math.huge, math.abs local function support(shape_a, shape_b, dx, dy) local x,y = shape_a:support(dx,dy) return vector.sub(x,y, shape_b:support(-dx, -dy)) end -- returns closest edge to the origin local function closest_edge(simplex) local e = {dist = huge} local i = #simplex-1 for k = 1,#simplex-1,2 do local ax,ay = simplex[i], simplex[i+1] local bx,by = simplex[k], simplex[k+1] i = k local ex,ey = vector.perpendicular(bx-ax, by-ay) local nx,ny = vector.normalize(ex,ey) local d = vector.dot(ax,ay, nx,ny) if d < e.dist then e.dist = d e.nx, e.ny = nx, ny e.i = k end end return e end local function EPA(shape_a, shape_b, simplex) -- make sure simplex is oriented counter clockwise local cx,cy, bx,by, ax,ay = unpack(simplex) if vector.dot(ax-bx,ay-by, cx-bx,cy-by) < 0 then simplex[1],simplex[2] = ax,ay simplex[5],simplex[6] = cx,cy end -- the expanding polytype algorithm local last_diff_dist = huge while true do local e = closest_edge(simplex) local px,py = support(shape_a, shape_b, e.nx, e.ny) local d = vector.dot(px,py, e.nx, e.ny) local diff_dist = d - e.dist if diff_dist < 1e-6 or abs(last_diff_dist - diff_dist) < 1e-10 then return -d*e.nx, -d*e.ny end last_diff_dist = diff_dist -- simplex = {..., simplex[e.i-1], px, py, simplex[e.i] table.insert(simplex, e.i, py) table.insert(simplex, e.i, px) end end -- : : origin must be in plane between A and B -- B o------o A since A is the furthest point on the MD -- : : in direction of the origin. local function do_line(simplex) local bx,by, ax,ay = unpack(simplex) local abx,aby = bx-ax, by-ay local dx,dy = vector.perpendicular(abx,aby) if vector.dot(dx,dy, -ax,-ay) < 0 then dx,dy = -dx,-dy end return simplex, dx,dy end -- B .' -- o-._ 1 -- | `-. .' The origin can only be in regions 1, 3 or 4: -- | 4 o A 2 A lies on the edge of the MD and we came -- | _.-' '. from left of BC. -- o-' 3 -- C '. local function do_triangle(simplex) local cx,cy, bx,by, ax,ay = unpack(simplex) local aox,aoy = -ax,-ay local abx,aby = bx-ax, by-ay local acx,acy = cx-ax, cy-ay -- test region 1 local dx,dy = vector.perpendicular(abx,aby) if vector.dot(dx,dy, acx,acy) > 0 then dx,dy = -dx,-dy end if vector.dot(dx,dy, aox,aoy) > 0 then -- simplex = {bx,by, ax,ay} simplex[1], simplex[2] = bx,by simplex[3], simplex[4] = ax,ay simplex[5], simplex[6] = nil, nil return simplex, dx,dy end -- test region 3 dx,dy = vector.perpendicular(acx,acy) if vector.dot(dx,dy, abx,aby) > 0 then dx,dy = -dx,-dy end if vector.dot(dx,dy, aox, aoy) > 0 then -- simplex = {cx,cy, ax,ay} simplex[3], simplex[4] = ax,ay simplex[5], simplex[6] = nil, nil return simplex, dx,dy end -- must be in region 4 return simplex end local function GJK(shape_a, shape_b) local ax,ay = support(shape_a, shape_b, 1,0) if ax == 0 and ay == 0 then -- only true if shape_a and shape_b are touching in a vertex, e.g. -- .--- .---. -- | A | .-. | B | support(A, 1,0) = x -- '---x---. or : A :x---' support(B, -1,0) = x -- | B | `-' => support(A,B,1,0) = x - x = 0 -- '---' -- Since CircleShape:support(dx,dy) normalizes dx,dy we have to opt -- out or the algorithm blows up. In accordance to the cases below -- choose to judge this situation as not colliding. return false end local simplex = {ax,ay} local n = 2 local dx,dy = -ax,-ay -- first iteration: line case ax,ay = support(shape_a, shape_b, dx,dy) if vector.dot(ax,ay, dx,dy) <= 0 then return false end simplex[n+1], simplex[n+2] = ax,ay simplex, dx, dy = do_line(simplex, dx, dy) n = 4 -- all other iterations must be the triangle case while true do ax,ay = support(shape_a, shape_b, dx,dy) if vector.dot(ax,ay, dx,dy) <= 0 then return false end simplex[n+1], simplex[n+2] = ax,ay simplex, dx, dy = do_triangle(simplex, dx,dy) n = #simplex if n == 6 then return true, EPA(shape_a, shape_b, simplex) end end end return GJK
--[[ Copyright (c) 2012 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local _PACKAGE = (...):match("^(.+)%.[^%.]+") local vector = require(_PACKAGE .. '.vector-light') local huge, abs = math.huge, math.abs local function support(shape_a, shape_b, dx, dy) local x,y = shape_a:support(dx,dy) return vector.sub(x,y, shape_b:support(-dx, -dy)) end -- returns closest edge to the origin local function closest_edge(simplex) local e = {dist = huge} local i = #simplex-1 for k = 1,#simplex-1,2 do local ax,ay = simplex[i], simplex[i+1] local bx,by = simplex[k], simplex[k+1] i = k local ex,ey = vector.perpendicular(bx-ax, by-ay) local nx,ny = vector.normalize(ex,ey) local d = vector.dot(ax,ay, nx,ny) if d < e.dist then e.dist = d e.nx, e.ny = nx, ny e.i = k end end return e end local function EPA(shape_a, shape_b, simplex) -- make sure simplex is oriented counter clockwise local cx,cy, bx,by, ax,ay = unpack(simplex) if vector.dot(ax-bx,ay-by, cx-bx,cy-by) < 0 then simplex[1],simplex[2] = ax,ay simplex[5],simplex[6] = cx,cy end -- the expanding polytype algorithm local is_either_circle = shape_a._center or shape_b._center local last_diff_dist = huge while true do local e = closest_edge(simplex) local px,py = support(shape_a, shape_b, e.nx, e.ny) local d = vector.dot(px,py, e.nx, e.ny) local diff_dist = d - e.dist if diff_dist < 1e-6 or (is_either_circle and abs(last_diff_dist - diff_dist) < 1e-10) then return -d*e.nx, -d*e.ny end last_diff_dist = diff_dist -- simplex = {..., simplex[e.i-1], px, py, simplex[e.i] table.insert(simplex, e.i, py) table.insert(simplex, e.i, px) end end -- : : origin must be in plane between A and B -- B o------o A since A is the furthest point on the MD -- : : in direction of the origin. local function do_line(simplex) local bx,by, ax,ay = unpack(simplex) local abx,aby = bx-ax, by-ay local dx,dy = vector.perpendicular(abx,aby) if vector.dot(dx,dy, -ax,-ay) < 0 then dx,dy = -dx,-dy end return simplex, dx,dy end -- B .' -- o-._ 1 -- | `-. .' The origin can only be in regions 1, 3 or 4: -- | 4 o A 2 A lies on the edge of the MD and we came -- | _.-' '. from left of BC. -- o-' 3 -- C '. local function do_triangle(simplex) local cx,cy, bx,by, ax,ay = unpack(simplex) local aox,aoy = -ax,-ay local abx,aby = bx-ax, by-ay local acx,acy = cx-ax, cy-ay -- test region 1 local dx,dy = vector.perpendicular(abx,aby) if vector.dot(dx,dy, acx,acy) > 0 then dx,dy = -dx,-dy end if vector.dot(dx,dy, aox,aoy) > 0 then -- simplex = {bx,by, ax,ay} simplex[1], simplex[2] = bx,by simplex[3], simplex[4] = ax,ay simplex[5], simplex[6] = nil, nil return simplex, dx,dy end -- test region 3 dx,dy = vector.perpendicular(acx,acy) if vector.dot(dx,dy, abx,aby) > 0 then dx,dy = -dx,-dy end if vector.dot(dx,dy, aox, aoy) > 0 then -- simplex = {cx,cy, ax,ay} simplex[3], simplex[4] = ax,ay simplex[5], simplex[6] = nil, nil return simplex, dx,dy end -- must be in region 4 return simplex end local function GJK(shape_a, shape_b) local ax,ay = support(shape_a, shape_b, 1,0) if ax == 0 and ay == 0 then -- only true if shape_a and shape_b are touching in a vertex, e.g. -- .--- .---. -- | A | .-. | B | support(A, 1,0) = x -- '---x---. or : A :x---' support(B, -1,0) = x -- | B | `-' => support(A,B,1,0) = x - x = 0 -- '---' -- Since CircleShape:support(dx,dy) normalizes dx,dy we have to opt -- out or the algorithm blows up. In accordance to the cases below -- choose to judge this situation as not colliding. return false end local simplex = {ax,ay} local n = 2 local dx,dy = -ax,-ay -- first iteration: line case ax,ay = support(shape_a, shape_b, dx,dy) if vector.dot(ax,ay, dx,dy) <= 0 then return false end simplex[n+1], simplex[n+2] = ax,ay simplex, dx, dy = do_line(simplex, dx, dy) n = 4 -- all other iterations must be the triangle case while true do ax,ay = support(shape_a, shape_b, dx,dy) if vector.dot(ax,ay, dx,dy) <= 0 then return false end simplex[n+1], simplex[n+2] = ax,ay simplex, dx, dy = do_triangle(simplex, dx,dy) n = #simplex if n == 6 then return true, EPA(shape_a, shape_b, simplex) end end end return GJK
Hackish fix for 97ae2d89 and parent.
Hackish fix for 97ae2d89 and parent. A clean solution needs more investigation, but this will work for now.
Lua
mit
aswyk/botrot
f2b901911268a9f620774d9537f326942f774e8a
src/remy/cgilua.lua
src/remy/cgilua.lua
-- Remy - CGI-Lua compatibility -- Copyright (c) 2014 Felipe Daragon -- License: MIT require "base64" -- TODO: implement all functions from mod_lua's request_rec local request = { -- ENCODING/DECODING FUNCTIONS base64_decode = function(_,...) return base64.decode(...) end, base64_encode = function(_,...) return base64.encode(...) end, escape = function(_,...) return cgilua.urlcode.escape(...) end, unescape = function(_,...) return cgilua.urlcode.unescape(...) end, -- REQUEST PARSING FUNCTIONS parseargs = function(_) return cgilua.QUERY, {} end, parsebody = function(_) return cgilua.POST, {} end, -- REQUEST RESPONSE FUNCTIONS puts = function(_,...) cgilua.put(...) end, write = function(_,...) cgilua.print(...) end } local M = { mode = "cgilua", request = request } function M.init() local r = request local query = cgilua.servervariable("QUERY_STRING") local port = cgilua.servervariable("SERVER_PORT") local server_name = cgilua.servervariable("SERVER_NAME") local path_info = M.getpathinfo() apache2.version = cgilua.servervariable("SERVER_SOFTWARE") r = remy.loadrequestrec(r) r.ap_auth_type = cgilua.servervariable("AUTH_TYPE") if query ~= nil and query ~= '' then r.args = query end r.banner = apache2.version r.canonical_filename = cgilua.script_path r.content_type = "text/html" -- CGILua needs a default content_type r.context_document_root = cgilua.script_pdir r.document_root = cgilua.script_pdir r.filename = cgilua.script_path r.hostname = server_name r.method = cgilua.servervariable("REQUEST_METHOD") r.path_info = path_info if port ~= nil then r.port = tonumber(port) if r.port == 443 then r.is_https = true end end r.protocol = cgilua.servervariable("SERVER_PROTOCOL") r.range = cgilua.servervariable("HTTP_RANGE") r.server_name = server_name r.started = os.time() r.the_request = r.method..' '..M.getunparseduri()..' '..r.protocol r.unparsed_uri = M.getunparseduri() r.uri = path_info r.user = cgilua.servervariable("REMOTE_USER") r.useragent_ip = cgilua.servervariable("REMOTE_ADDR") end function M.getpathinfo() local p = cgilua.servervariable("PATH_INFO") if p == nil then p = cgilua.servervariable("SCRIPT_NAME") end return p end function M.getunparseduri() local uri = M.getpathinfo() local query = cgilua.servervariable("QUERY_STRING") if query ~= nil and query ~= '' then uri = uri..'?'..query end return uri end function M.contentheader(content_type) if content_type == "text/html" then cgilua.htmlheader() else local header_sep = "/" local header_type = remy.splitstring(content_type,header_sep)[1] local header_subtype = remy.splitstring(content_type,header_sep)[2] cgilua.contentheader(header_type,header_subtype) end end -- TODO: handle the return code in CGILua function M.finish(code) end return M
-- Remy - CGI-Lua compatibility -- Copyright (c) 2014 Felipe Daragon -- License: MIT require "base64" -- TODO: implement all functions from mod_lua's request_rec local request = { -- ENCODING/DECODING FUNCTIONS base64_decode = function(_,...) return base64.decode(...) end, base64_encode = function(_,...) return base64.encode(...) end, escape = function(_,...) return cgilua.urlcode.escape(...) end, unescape = function(_,...) return cgilua.urlcode.unescape(...) end, -- REQUEST PARSING FUNCTIONS parseargs = function(_) return cgilua.QUERY, {} end, parsebody = function(_) return cgilua.POST, {} end, -- REQUEST RESPONSE FUNCTIONS puts = function(_,...) cgilua.put(...) end, write = function(_,...) cgilua.print(...) end } local M = { mode = "cgilua", request = request } function M.init() local r = request local query = cgilua.servervariable("QUERY_STRING") local port = cgilua.servervariable("SERVER_PORT") local server_name = cgilua.servervariable("SERVER_NAME") local path_info = M.getpathinfo() apache2.version = cgilua.servervariable("SERVER_SOFTWARE") r = remy.loadrequestrec(r) r.ap_auth_type = cgilua.servervariable("AUTH_TYPE") if query ~= nil and query ~= '' then r.args = query end r.banner = apache2.version r.canonical_filename = cgilua.script_path r.content_type = "text/html" -- CGILua needs a default content_type r.context_document_root = cgilua.script_pdir r.document_root = cgilua.script_pdir r.filename = cgilua.script_path r.hostname = server_name r.method = cgilua.servervariable("REQUEST_METHOD") r.path_info = path_info if port ~= nil then r.port = tonumber(port) if r.port == 443 then r.is_https = true end end r.protocol = cgilua.servervariable("SERVER_PROTOCOL") r.range = cgilua.servervariable("HTTP_RANGE") r.server_name = server_name r.started = os.time() r.the_request = r.method..' '..M.getunparseduri()..' '..r.protocol r.unparsed_uri = M.getunparseduri() r.uri = path_info r.user = cgilua.servervariable("REMOTE_USER") r.useragent_ip = cgilua.servervariable("REMOTE_ADDR") end function M.getpathinfo() local p = cgilua.urlpath if p == nil then p = cgilua.servervariable("SCRIPT_NAME") end return p end function M.getunparseduri() local uri = M.getpathinfo() local query = cgilua.servervariable("QUERY_STRING") if query ~= nil and query ~= '' then uri = uri..'?'..query end return uri end function M.contentheader(content_type) if content_type == "text/html" then cgilua.htmlheader() else local header_sep = "/" local header_type = remy.splitstring(content_type,header_sep)[1] local header_subtype = remy.splitstring(content_type,header_sep)[2] cgilua.contentheader(header_type,header_subtype) end end -- TODO: handle the return code in CGILua function M.finish(code) end return M
Update cgilua.lua
Update cgilua.lua Fixing uri coming from cgilua requests for Xavante compatibility
Lua
mit
noname007/sailor,Etiene/sailor,mpeterv/sailor,ignacio/sailor,felipedaragon/sailor,sailorproject/sailor,mpeterv/sailor,hallison/sailor,ignacio/sailor,felipedaragon/sailor,jeary/sailor,Etiene/sailor
3b4d7ce56d1d53af69a77e3c3101c93113f18548
lgi/override/Gio-DBus.lua
lgi/override/Gio-DBus.lua
------------------------------------------------------------------------------ -- -- lgi Gio DBus override module. -- -- Copyright (c) 2013 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local pairs, ipairs = pairs, ipairs local lgi = require 'lgi' local core = require 'lgi.core' local ffi = require 'lgi.ffi' local ti = ffi.types local Gio = lgi.Gio local GLib = lgi.GLib -- DBus introspection support. -- All introspection structures are boxed, but they lack proper C-side -- introspectable constructors. Work around this limitation by adding -- custom lgi constructors which create allocated variants of these -- records. for _, name in pairs { 'Annotation', 'Arg' , 'Method', 'Signal', 'Property', 'Interface', 'Node', } do name = 'DBus' .. name .. 'Info' local infotype = Gio[name] -- Add constructor which properly creates and initializes info. function infotype:_new(params) -- Create allocated variant of the record, because when -- destroyed by g_boxed_free, Info instances automatically sweep -- away also all fields which belong to them. local struct = core.record.new(self, nil, 1, true) -- Initialize ref_count on the instance. struct.ref_count = 1 -- Assign all constructor parameters. for name, value in pairs(params or {}) do struct[name] = value end return struct end -- Assign proper refsink method. infotype._refsink = core.gi.Gio[name].methods.ref end -- g_dbus_node_gemerate_xml is busted, has incorrect [out] annotation -- of its GString argument (which is in fact [in] one). Fix it by -- redeclaring it. Gio.DBusNodeInfo.generate_xml = core.callable.new { name = 'Gio.DBusNodeInfo.generate_xml', addr = core.gi.Gio.resolve.g_dbus_node_info_generate_xml, ret = ti.void, Gio.DBusNodeInfo, ti.uint, GLib.String, } -- Add simple 'xml' attribute as facade over a bit hard-to-use -- generate_xml() method. Gio.DBusNodeInfo._attribute = {} function Gio.DBusNodeInfo._attribute:xml() local xml = GLib.String('') self:generate_xml(0, xml) return xml.str end
------------------------------------------------------------------------------ -- -- lgi Gio DBus override module. -- -- Copyright (c) 2013 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local pairs, ipairs = pairs, ipairs local lgi = require 'lgi' local core = require 'lgi.core' local ffi = require 'lgi.ffi' local ti = ffi.types local Gio = lgi.Gio local GLib = lgi.GLib -- DBus introspection support. -- All introspection structures are boxed, but they lack proper C-side -- introspectable constructors. Work around this limitation by adding -- custom lgi constructors which create allocated variants of these -- records. for _, name in pairs { 'Annotation', 'Arg' , 'Method', 'Signal', 'Property', 'Interface', 'Node', } do name = 'DBus' .. name .. 'Info' local infotype = Gio[name] -- Add constructor which properly creates and initializes info. function infotype:_new(params) -- Create allocated variant of the record, because when -- destroyed by g_boxed_free, Info instances automatically sweep -- away also all fields which belong to them. local struct = core.record.new(self, nil, 1, true) -- Initialize ref_count on the instance. struct.ref_count = 1 -- Assign all constructor parameters. for name, value in pairs(params or {}) do struct[name] = value end return struct end -- Assign proper refsink method. infotype._refsink = core.gi.Gio[name].methods.ref end -- g_dbus_node_gemerate_xml is busted, has incorrect [out] annotation -- of its GString argument (which is in fact [in] one). Fix it by -- redeclaring it. Gio.DBusNodeInfo.generate_xml = core.callable.new { name = 'Gio.DBusNodeInfo.generate_xml', addr = core.gi.Gio.resolve.g_dbus_node_info_generate_xml, ret = ti.void, Gio.DBusNodeInfo, ti.uint, GLib.String, } -- Add simple 'xml' attribute as facade over a bit hard-to-use -- generate_xml() method. Gio.DBusNodeInfo._attribute = {} function Gio.DBusNodeInfo._attribute:xml() local xml = GLib.String('') self:generate_xml(0, xml) return xml.str end -- g_dbus_proxy_get_interface_info() is documented as "Do not unref the returned -- object", but has transfer=full. Fix this. if core.gi.Gio.DBusProxy.methods.get_interface_info.return_transfer ~= 'none' then Gio.DBusProxy.get_interface_info = core.callable.new { addr = core.gi.Gio.resolve.g_dbus_proxy_get_interface_info, name = 'DBusProxy.get_interface_info', ret = Gio.DBusInterfaceInfo, core.gi.Gio.DBusProxy.methods.new_sync.return_type, } end
Work around incorect annotation on Gio.DBusProxy.get_interface_info
Work around incorect annotation on Gio.DBusProxy.get_interface_info The return value should be "transfer=none", but since it is not annotated as such, it gets "transfer=full". Work around this with a hand-written bindings based on core.callable. This fixes the test added by the previous commit. Signed-off-by: Uli Schlachter <346c0ad49ac8427b61b3b55abbe37dc0ebd524f2@znc.in>
Lua
mit
psychon/lgi,pavouk/lgi
38ec00d9351a61ea0365ac6fd2252b812744ba66
helper/string.lua
helper/string.lua
-- Copyright (C) Dejiang Zhu (doujiang24) local utf8 = require "system.helper.utf8" local find = string.find local sub = string.sub local insert = table.insert local concat = table.concat local type = type local re_gsub = ngx.re.gsub local random = math.random local time = ngx.time local gsub = string.gsub local gmatch = string.gmatch local unescape_uri = ngx.unescape_uri local ok, uuid = pcall(require, "resty.uuid") if not ok then uuid = {} uuid.generate = function () return time() .. random(1000, 9999) end end local charlist = "[\t\n\r\0\11]*" local _M = { _VERSION = '0.01' } -- @param pattern The split pattern (I.e. "%s+" to split text by one or more -- whitespace characters). function _M.split(s, pattern, ret) if not pattern then pattern = "%s+" end if not ret then ret = {} end local pos = 1 local fstart, fend = find(s, pattern, pos) while fstart do insert(ret, sub(s, pos, fstart - 1)) pos = fend + 1 fstart, fend = find(s, pattern, pos) end if pos <= #s then insert(ret, sub(s, pos)) end return ret end -- @param pattern The pattern to strip from the left-most and right-most of the function _M.strip(s, pattern) local p = pattern or "%s*" local sub_start, sub_end -- Find start point local _, f_end = find(s, "^"..p) if f_end then sub_start = f_end + 1 end -- Find end point local f_start = find(s, p.."$") if f_start then sub_end = f_start - 1 end return sub(s, sub_start or 1, sub_end or #s) end -- to do: not sure allowable_tags work perfect function _M.strip_tags(s, allowable_tags) local pattern = "</?[^>]+>" if allowable_tags and type(allowable_tags) == "table" then pattern = "</?+(?!" .. concat(allowable_tags, "|") .. ")([^>]*?)/?>" end return re_gsub(s, pattern, "", "iux") end -- Translate certain characters -- from can be the table { from = to, from1 = to1 } -- s is the utf8 string function _M.strtr(s, from, to) local ret = {} if type(from) ~= "table" then from = { [from] = to } end for c in utf8.iter(s) do if from[c] then insert(ret, from[c]) else insert(ret, c) end end return concat(ret) end function _M.uniqid() local id = uuid.generate() local pref = re_gsub(id, "-[^-]+$", "") local short = re_gsub(pref, "-", "") return short end function _M.rawurldecode(str) return unescape_uri(gsub(str, "+", "%%2B")) end function _M.trim(str) local pref = re_gsub(str, "^" .. charlist, "") or str return re_gsub(pref, charlist .. "$", "") or pref end function _M.str_replace(search, replace, str) if type(search) == "string" then return gsub(str, search, replace) end local rp_type = type(replace) == "string" and true or nil for i = 1, #search do str = gsub(str, search[i], rp_type and replace or replace[i]) end return str end function _M.explode(separator, str) local str = str .. separator local ret, i = {}, 1 for s in gmatch(str, "(.-)" .. separator) do ret[i] = s i = i + 1 end return ret end return _M
-- Copyright (C) Dejiang Zhu (doujiang24) local utf8 = require "system.helper.utf8" local find = string.find local sub = string.sub local insert = table.insert local concat = table.concat local type = type local re_gsub = ngx.re.gsub local random = math.random local time = ngx.time local gsub = string.gsub local gmatch = string.gmatch local unescape_uri = ngx.unescape_uri local ok, uuid = pcall(require, "resty.uuid") if not ok then uuid = {} uuid.generate = function () return time() .. random(1000, 9999) end end -- " " (ASCII 32 (0x20)), an ordinary space. -- "\x0B" (ASCII 11 (0x0B)), a vertical tab. local charlist = "[\t\n\r\32\11]+" local _M = { _VERSION = '0.01' } -- @param pattern The split pattern (I.e. "%s+" to split text by one or more -- whitespace characters). function _M.split(s, pattern, ret) if not pattern then pattern = "%s+" end if not ret then ret = {} end local pos = 1 local fstart, fend = find(s, pattern, pos) while fstart do insert(ret, sub(s, pos, fstart - 1)) pos = fend + 1 fstart, fend = find(s, pattern, pos) end if pos <= #s then insert(ret, sub(s, pos)) end return ret end -- @param pattern The pattern to strip from the left-most and right-most of the function _M.strip(s, pattern) local p = pattern or "%s*" local sub_start, sub_end -- Find start point local _, f_end = find(s, "^"..p) if f_end then sub_start = f_end + 1 end -- Find end point local f_start = find(s, p.."$") if f_start then sub_end = f_start - 1 end return sub(s, sub_start or 1, sub_end or #s) end -- to do: not sure allowable_tags work perfect function _M.strip_tags(s, allowable_tags) local pattern = "</?[^>]+>" if allowable_tags and type(allowable_tags) == "table" then pattern = "</?+(?!" .. concat(allowable_tags, "|") .. ")([^>]*?)/?>" end return re_gsub(s, pattern, "", "iux") end -- Translate certain characters -- from can be the table { from = to, from1 = to1 } -- s is the utf8 string function _M.strtr(s, from, to) local ret = {} if type(from) ~= "table" then from = { [from] = to } end for c in utf8.iter(s) do if from[c] then insert(ret, from[c]) else insert(ret, c) end end return concat(ret) end function _M.uniqid() local id = uuid.generate() local pref = re_gsub(id, "-[^-]+$", "") local short = re_gsub(pref, "-", "") return short end function _M.rawurldecode(str) return unescape_uri(gsub(str, "+", "%%2B")) end function _M.trim(str) local pref = re_gsub(str, "^" .. charlist, "") or str return re_gsub(pref, charlist .. "$", "") or pref end function _M.str_replace(search, replace, str) if type(search) == "string" then return gsub(str, search, replace) end local rp_type = type(replace) == "string" and true or nil for i = 1, #search do str = gsub(str, search[i], rp_type and replace or replace[i]) end return str end function _M.explode(separator, str) local str = str .. separator local ret, i = {}, 1 for s in gmatch(str, "(.-)" .. separator) do ret[i] = s i = i + 1 end return ret end return _M
bugfix: \0 is string ending in c, can not use in pcre; * means any char, + means more instead
bugfix: \0 is string ending in c, can not use in pcre; * means any char, + means more instead
Lua
mit
doujiang24/durap-system
14982f45ae5be42b2ed716278d7bf7f0d4af6b50
quest/rutrus_67_cadomyr_wilderness.lua
quest/rutrus_67_cadomyr_wilderness.lua
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (67, 'quest.rutrus_67_cadomyr_wilderness'); require("base.common") module("quest.rutrus_67_cadomyr_wilderness", package.seeall) GERMAN = Player.german ENGLISH = Player.english -- Insert the quest title here, in both languages Title = {} Title[GERMAN] = "Sternenoase" Title[ENGLISH] = "Oasis of Stars" -- Insert an extensive description of each status here, in both languages -- Make sure that the player knows exactly where to go and what to do Description = {} Description[GERMAN] = {} Description[ENGLISH] = {} Description[GERMAN][1] = "Sammel zehnmal groben Sand und bringe diese Rutrus. Nimm das Beil in die Hand und benutzt es, whrend du vor einem Stein im Sand stehst." Description[ENGLISH][1] = "Collect ten coarse sand and bring them back to Rutrus. Use the shovel in your hand, while standing in front of a stone in the desert." Description[GERMAN][2] = "Geh zu Rutrus in der Sternenoase. Er hat bestimmt noch eine Aufgabe fr dich." Description[ENGLISH][2] = "Go back to Rutrus in the Oasis of Stars, he certainly have another task for you." Description[GERMAN][3] = "Sammel zwanzigmal Quarzsand und bringe diese Rutrus. Siebe groben Sand um Quarzsand herzustelle. Nimm eine Holzkelle in die Hand und benutzt es, whrend du vor einem Sieb." Description[ENGLISH][3] = "Produce twenty quartz sand and bring them back to Rutrus. Sieve coarse sand to produce quartz sand. Use the wooden shovel in your hand, while standing in front of a sieve." Description[GERMAN][4] = "Geh zu Rutrus in der Sternenoase. Er hat bestimmt noch eine Aufgabe fr dich." Description[ENGLISH][4] = "Go back to Rutrus in the Oasis of Stars, he certainly have another task for you." Description[GERMAN][5] = "Sammel fnf ungeschliffene Topaze und bringe diese Rutrus. Du kannst sie entweder beim Hndler kaufen oder in der Mine finden. Nimm hierfr eine Spitzhacke in die Hand und benutzt sie, whrend du vor einem Stein stehst." Description[ENGLISH][5] = "Collect five raw topaz and bring them back to Rutrus. You can buy them from a merchant or find them in a mine. Therefor use the pick-axe in your hand, while standing in front of a stone." Description[GERMAN][6] = "Geh zu Rutrus in der Sternenoase. Er hat bestimmt noch eine Aufgabe fr dich." Description[ENGLISH][6] = "Go back to Rutrus in the Oasis of Stars, he certainly have another task for you." Description[GERMAN][7] = "Besorge zehn Kohleklumpen und bringe sie Rutrus. Du kannst Kohle entweder beim Hndler kaufen oder in der Mine finden. Nimm hierfr eine Spitzhacke in die Hand und benutzt sie, whrend du vor einem Stein stehst." Description[ENGLISH][7] = "Produce ten lumps of coal and bring them to Rutrus. You can buy coal from a merchant or find them in a mine. Therefor use the pick-axe in your hand, while standing in front of a stone." Description[GERMAN][8] = "Du hast alle Aufgaben von Rutrus erfllt." Description[ENGLISH][8] = "You have fulfilled all the tasks for Rutrus." -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there QuestTarget = {} QuestTarget[1] = {position(359, 678, 0), position(352, 678, 0)} -- stone QuestTarget[2] = {position(359, 678, 0)} QuestTarget[3] = {position(359, 678, 0), position(143, 592, 0)} -- sieve QuestTarget[4] = {position(359, 678, 0)} QuestTarget[5] = {position(359, 678, 0), position(133, 589, 0), position(169, 607, 0)} -- hndler mine QuestTarget[6] = {position(359, 678, 0)} QuestTarget[7] = {position(359, 678, 0), position(133, 589, 0), position(143, 689, 0)} -- hndler mine QuestTarget[8] = {position(359, 678, 0)} -- Insert the quest status which is reached at the end of the quest FINAL_QUEST_STATUS = 8 function QuestTitle(user) return base.common.GetNLS(user, Title[GERMAN], Title[ENGLISH]) end function QuestDescription(user, status) local german = Description[GERMAN][status] or "" local english = Description[ENGLISH][status] or "" return base.common.GetNLS(user, german, english) end function QuestTargets(user, status) return QuestTarget[status] end function QuestFinalStatus() return FINAL_QUEST_STATUS end turn FINAL_QUEST_STATUS end
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (67, 'quest.rutrus_67_cadomyr_wilderness'); require("base.common") module("quest.rutrus_67_cadomyr_wilderness", package.seeall) GERMAN = Player.german ENGLISH = Player.english -- Insert the quest title here, in both languages Title = {} Title[GERMAN] = "Sternenoase" Title[ENGLISH] = "Oasis of Stars" -- Insert an extensive description of each status here, in both languages -- Make sure that the player knows exactly where to go and what to do Description = {} Description[GERMAN] = {} Description[ENGLISH] = {} Description[GERMAN][1] = "Sammel zehnmal groben Sand und bringe diese Rutrus. Nimm das Beil in die Hand und benutzt es, whrend du vor einem Stein im Sand stehst." Description[ENGLISH][1] = "Collect ten coarse sand and bring them back to Rutrus. Use the shovel in your hand, while standing in front of a stone in the desert." Description[GERMAN][2] = "Geh zu Rutrus in der Sternenoase. Er hat bestimmt noch eine Aufgabe fr dich." Description[ENGLISH][2] = "Go back to Rutrus in the Oasis of Stars, he certainly have another task for you." Description[GERMAN][3] = "Sammel zwanzigmal Quarzsand und bringe diese Rutrus. Siebe groben Sand um Quarzsand herzustelle. Nimm eine Holzkelle in die Hand und benutzt es, whrend du vor einem Sieb." Description[ENGLISH][3] = "Produce twenty quartz sand and bring them back to Rutrus. Sieve coarse sand to produce quartz sand. Use the wooden shovel in your hand, while standing in front of a sieve." Description[GERMAN][4] = "Geh zu Rutrus in der Sternenoase. Er hat bestimmt noch eine Aufgabe fr dich." Description[ENGLISH][4] = "Go back to Rutrus in the Oasis of Stars, he certainly have another task for you." Description[GERMAN][5] = "Sammel fnf ungeschliffene Topaze und bringe diese Rutrus. Du kannst sie entweder beim Hndler kaufen oder in der Mine finden. Nimm hierfr eine Spitzhacke in die Hand und benutzt sie, whrend du vor einem Stein stehst." Description[ENGLISH][5] = "Collect five raw topaz and bring them back to Rutrus. You can buy them from a merchant or find them in a mine. Therefor use the pick-axe in your hand, while standing in front of a stone." Description[GERMAN][6] = "Geh zu Rutrus in der Sternenoase. Er hat bestimmt noch eine Aufgabe fr dich." Description[ENGLISH][6] = "Go back to Rutrus in the Oasis of Stars, he certainly have another task for you." Description[GERMAN][7] = "Besorge zehn Kohleklumpen und bringe sie Rutrus. Du kannst Kohle entweder beim Hndler kaufen oder in der Mine finden. Nimm hierfr eine Spitzhacke in die Hand und benutzt sie, whrend du vor einem Stein stehst." Description[ENGLISH][7] = "Produce ten lumps of coal and bring them to Rutrus. You can buy coal from a merchant or find them in a mine. Therefor use the pick-axe in your hand, while standing in front of a stone." Description[GERMAN][8] = "Du hast alle Aufgaben von Rutrus erfllt." Description[ENGLISH][8] = "You have fulfilled all the tasks for Rutrus." -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there QuestTarget = {} QuestTarget[1] = {position(359, 678, 0), position(352, 678, 0)} -- stone QuestTarget[2] = {position(359, 678, 0)} QuestTarget[3] = {position(359, 678, 0), position(143, 592, 0)} -- sieve QuestTarget[4] = {position(359, 678, 0)} QuestTarget[5] = {position(359, 678, 0), position(133, 589, 0), position(169, 607, 0)} -- hndler mine QuestTarget[6] = {position(359, 678, 0)} QuestTarget[7] = {position(359, 678, 0), position(133, 589, 0), position(143, 689, 0)} -- hndler mine QuestTarget[8] = {position(359, 678, 0)} -- Insert the quest status which is reached at the end of the quest FINAL_QUEST_STATUS = 8 function QuestTitle(user) return base.common.GetNLS(user, Title[GERMAN], Title[ENGLISH]) end function QuestDescription(user, status) local german = Description[GERMAN][status] or "" local english = Description[ENGLISH][status] or "" return base.common.GetNLS(user, german, english) end function QuestTargets(user, status) return QuestTarget[status] end function QuestFinalStatus() return FINAL_QUEST_STATUS end
Bugfix
Bugfix
Lua
agpl-3.0
vilarion/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content
53e78405d71c9b78d0a60e0d038c472fdb33280a
lib/train/epoch_state.lua
lib/train/epoch_state.lua
require 'torch' --[[ Class for managing the training process by logging and storing the state of the current epoch. ]] local EpochState = torch.class("EpochState") --[[ Initialize for epoch `epoch` and training `status` (current loss)]] function EpochState:__init(epoch, num_iterations, learning_rate, status) self.epoch = epoch self.num_iterations = num_iterations self.learning_rate = learning_rate if status ~= nil then self.status = status else self.status = {} self.status.train_nonzeros = 0 self.status.train_loss = 0 end self.timer = torch.Timer() self.num_words_source = 0 self.num_words_target = 0 self.minFreeMemory = 100000000 print('') end --[[ Update training status. Takes `batch` (described in data.lua) and last losses.]] function EpochState:update(batches, losses) for i = 1,#batches do self.num_words_source = self.num_words_source + batches[i].size * batches[i].source_length self.num_words_target = self.num_words_target + batches[i].size * batches[i].target_length self.status.train_loss = self.status.train_loss + losses[i] self.status.train_nonzeros = self.status.train_nonzeros + batches[i].target_non_zeros end end --[[ Log to status stdout. ]] function EpochState:log(batch_index) local time_taken = self:get_time() local stats = '' local freeMemory = utils.Cuda.freeMemory() if freeMemory < self.minFreeMemory then self.minFreeMemory = freeMemory end stats = stats .. string.format('Epoch %d ; Batch %d/%d ; LR %.4f ; ', self.epoch, batch_index, self.num_iterations, self.learning_rate) stats = stats .. string.format('Throughput %d/%d/%d total/src/targ tokens/sec ; ', (self.num_words_target + self.num_words_source) / time_taken, self.num_words_source / time_taken, self.num_words_target / time_taken) stats = stats .. string.format('PPL %.2f ; Free mem %d', self:get_train_ppl(), freeMemory) print(stats) end function EpochState:get_train_ppl() return math.exp(self.status.train_loss / self.status.train_nonzeros) end function EpochState:get_time() return self.timer:time().real end function EpochState:get_status() return self.status end function EpochState:get_min_freememory() return self.minFreeMemory end return EpochState
require 'torch' --[[ Class for managing the training process by logging and storing the state of the current epoch. ]] local EpochState = torch.class("EpochState") --[[ Initialize for epoch `epoch` and training `status` (current loss)]] function EpochState:__init(epoch, num_iterations, learning_rate, status) self.epoch = epoch self.num_iterations = num_iterations self.learning_rate = learning_rate if status ~= nil then self.status = status else self.status = {} self.status.train_nonzeros = 0 self.status.train_loss = 0 end self.timer = torch.Timer() self.num_words_source = 0 self.num_words_target = 0 self.minFreeMemory = 100000000000 print('') end --[[ Update training status. Takes `batch` (described in data.lua) and last losses.]] function EpochState:update(batches, losses) for i = 1,#batches do self.num_words_source = self.num_words_source + batches[i].size * batches[i].source_length self.num_words_target = self.num_words_target + batches[i].size * batches[i].target_length self.status.train_loss = self.status.train_loss + losses[i] self.status.train_nonzeros = self.status.train_nonzeros + batches[i].target_non_zeros end end --[[ Log to status stdout. ]] function EpochState:log(batch_index) local time_taken = self:get_time() local stats = '' local freeMemory = utils.Cuda.freeMemory() if freeMemory < self.minFreeMemory then self.minFreeMemory = freeMemory end stats = stats .. string.format('Epoch %d ; Batch %d/%d ; Time %.2f ; LR %.4f ; ', self.timer:time().real, self.epoch, batch_index, self.num_iterations, self.learning_rate) stats = stats .. string.format('Throughput %d/%d/%d total/src/targ tokens/sec ; ', (self.num_words_target + self.num_words_source) / time_taken, self.num_words_source / time_taken, self.num_words_target / time_taken) stats = stats .. string.format('PPL %.2f ; Free mem %d', self:get_train_ppl(), freeMemory) print(stats) end function EpochState:get_train_ppl() return math.exp(self.status.train_loss / self.status.train_nonzeros) end function EpochState:get_time() return self.timer:time().real end function EpochState:get_status() return self.status end function EpochState:get_min_freememory() return self.minFreeMemory end return EpochState
fix "infinite" minimal memory value that was too low
fix "infinite" minimal memory value that was too low
Lua
mit
OpenNMT/OpenNMT,jsenellart/OpenNMT,cservan/OpenNMT_scores_0.2.0,jsenellart-systran/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,OpenNMT/OpenNMT,jsenellart/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,srush/OpenNMT,jungikim/OpenNMT,monsieurzhang/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,da03/OpenNMT,monsieurzhang/OpenNMT
3c593e387bc4383e9a1f1060a3c34ff3109b4751
src/lua_libraries/agent.lua
src/lua_libraries/agent.lua
local cjson = require("cjson.safe") local sleep = require("socket") local ldbus = require("ldbus") local agent = { conn = assert(ldbus.bus.get("session")) } assert(assert(ldbus.bus.request_name(agent.conn , "dynamicagent.signal.sink" , {replace_existing = true})) == "primary_owner" , "Not Primary Owner") -- DBus signals to subscribe to -- assert(ldbus.bus.add_match(agent.conn , "type='signal',interface='bus.can.update.can_medium_speed'")) assert(ldbus.bus.add_match(agent.conn , "type='signal',interface='com.jlr.fmradio'")) assert(ldbus.bus.add_match(agent.conn , "type='signal',interface='com.jlr.mediaManager'")) ---------------------------------- agent.conn:flush() local function get_event() while agent.conn:read_write(0) do local msg = agent.conn:pop_message() if not msg then ; elseif msg:get_type () == 'signal' then local iter = ldbus.message.iter.new() if msg:iter_init(iter) then if iter:get_arg_type() == ldbus.types.string then local payload = cjson.decode(iter:get_basic()) if payload == nil then elseif payload['signal_type'] == 'VEHICLE_SIGNAL' then agent.medium_speed_can_table[payload['signal_id']] = payload['value'] return payload elseif payload['signal_type'] == 'HMI_EVENT' then return payload else end end end end end end local function get_signals_table() local msg = assert(ldbus.message.new_method_call("bus.can.medium_speed" , "/bus/can/can_medium_speed/object" , "bus.can.request.can_medium_table" , "request_can_table") , "Message Null") local iter = ldbus.message.iter.new () msg:iter_init_append(iter) local reply = assert(agent.conn:send_with_reply_and_block(msg)) assert(reply:iter_init(iter), "Message has no arguments") return cjson.decode(iter:get_basic()) end local function dbus_connected() return agent.conn:read_write_dispatch() end local function signal_subscribe(sub) assert(ldbus.bus.add_match(agent.conn, "type='signal',interface=" .. "'" .. sub .. "'")) agent.conn:flush() end agent.signal_subscribe = signal_subscribe agent.get_event = get_event -- agent.get_signals_table = get_signals_table agent.dbus_connected = dbus_connected agent.medium_speed_can_table = get_signals_table() return agent
local cjson = require("cjson.safe") local sleep = require("socket") local ldbus = require("ldbus") local agent = { conn = assert(ldbus.bus.get("session")) } local full_path = (arg[0]):match("^.+/(.+)$") if full_path == nil then full_path = arg[0] end assert(assert(ldbus.bus.request_name(agent.conn , "dynamicagent.signal.sink"..full_path , {replace_existing = true})) == "primary_owner" , "Not Primary Owner") -- DBus signals to subscribe to -- assert(ldbus.bus.add_match(agent.conn , "type='signal',interface='bus.can.update.can_medium_speed'")) assert(ldbus.bus.add_match(agent.conn , "type='signal',interface='com.jlr.fmradio'")) assert(ldbus.bus.add_match(agent.conn , "type='signal',interface='com.jlr.mediaManager'")) ---------------------------------- agent.conn:flush() local function get_event() while agent.conn:read_write(0) do local msg = agent.conn:pop_message() if not msg then agent.conn:read_write_dispatch() elseif msg:get_type () == 'signal' then local iter = ldbus.message.iter.new() if msg:iter_init(iter) then if iter:get_arg_type() == ldbus.types.string then local payload = cjson.decode(iter:get_basic()) if payload == nil then elseif payload['signal_type'] == 'VEHICLE_SIGNAL' then agent.medium_speed_can_table[payload['signal_id']] = payload['value'] return payload elseif payload['signal_type'] == 'HMI_EVENT' then return payload else end end end end end end local function get_signals_table() local msg = assert(ldbus.message.new_method_call("bus.can.medium_speed" , "/bus/can/can_medium_speed/object" , "bus.can.request.can_medium_table" , "request_can_table") , "Message Null") local iter = ldbus.message.iter.new () msg:iter_init_append(iter) local reply = assert(agent.conn:send_with_reply_and_block(msg)) assert(reply:iter_init(iter), "Message has no arguments") return cjson.decode(iter:get_basic()) end local function dbus_connected() return agent.conn:read_write_dispatch() end local function signal_subscribe(sub) assert(ldbus.bus.add_match(agent.conn, "type='signal',interface=" .. "'" .. sub .. "'")) agent.conn:flush() end agent.signal_subscribe = signal_subscribe agent.get_event = get_event -- agent.get_signals_table = get_signals_table agent.dbus_connected = dbus_connected agent.medium_speed_can_table = get_signals_table() return agent
Fixed multiple agents collision for getting dbus namespace. Also fixed infinite while loop if no D-Bus signals on initation
Fixed multiple agents collision for getting dbus namespace. Also fixed infinite while loop if no D-Bus signals on initation
Lua
mpl-2.0
PDXostc/rvi_dynamic_agents,PDXostc/rvi_dynamic_agents
bf3fd18cf16928b1f8fcff532c37993fe01d99e9
home/config/nvim/lua/plugins/alpha.lua
home/config/nvim/lua/plugins/alpha.lua
local alpha = require'alpha' local dashboard = require'alpha.themes.dashboard' dashboard.section.header.val = { [[███╗ ██╗ ███████╗ ██████╗ ██╗ ██╗ ██╗ ███╗ ███╗]], [[████╗ ██║ ██╔════╝██╔═══██╗ ██║ ██║ ██║ ████╗ ████║]], [[██╔██╗ ██║ █████╗ ██║ ██║ ██║ ██║ ██║ ██╔████╔██║]], [[██║╚██╗██║ ██╔══╝ ██║ ██║ ╚██╗ ██╔╝ ██║ ██║╚██╔╝██║]], [[██║ ╚████║ ███████╗╚██████╔╝ ╚████╔╝ ██║ ██║ ╚═╝ ██║]], [[╚═╝ ╚═══╝ ╚══════╝ ╚═════╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝]], } dashboard.section.header.opts.hl = 'deviconhtml' local function button(sc, txt, keybind, keybind_opts) local b = dashboard.button(sc, txt, keybind, keybind_opts) b.opts.hl = 'warningmsg' b.opts.hl_shortcut = 'warningmsg' return b end dashboard.section.buttons.val = { button('e', ' New file', ':ene <Bar> startinsert <Cr>'), button('<Leader>ff', ' Find file'), button('<Leader>fg', ' Live grep'), button('q', ' Quit NVIM', ':qa<Cr>'), } local handle = io.popen('fortune') handle:close() dashboard.opts.opts.noautocmd = true dashboard.section.footer.val = 'Soli Deo Gloria' dashboard.section.footer.opts.hl = 'msgarea' alpha.setup(dashboard.opts)
local alpha = require'alpha' local dashboard = require'alpha.themes.dashboard' dashboard.section.header.val = { [[███╗ ██╗ ███████╗ ██████╗ ██╗ ██╗ ██╗ ███╗ ███╗]], [[████╗ ██║ ██╔════╝██╔═══██╗ ██║ ██║ ██║ ████╗ ████║]], [[██╔██╗ ██║ █████╗ ██║ ██║ ██║ ██║ ██║ ██╔████╔██║]], [[██║╚██╗██║ ██╔══╝ ██║ ██║ ╚██╗ ██╔╝ ██║ ██║╚██╔╝██║]], [[██║ ╚████║ ███████╗╚██████╔╝ ╚████╔╝ ██║ ██║ ╚═╝ ██║]], [[╚═╝ ╚═══╝ ╚══════╝ ╚═════╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝]], } dashboard.section.header.opts.hl = 'deviconhtml' local function button(sc, txt, keybind, keybind_opts) local b = dashboard.button(sc, txt, keybind, keybind_opts) b.opts.hl = 'warningmsg' b.opts.hl_shortcut = 'warningmsg' return b end dashboard.section.buttons.val = { button('e', ' New file', ':ene <Bar> startinsert <Cr>'), button('<Leader>ff', ' Find file'), button('<Leader>fg', ' Live grep'), button('q', ' Quit NVIM', ':qa<Cr>'), } dashboard.opts.opts.noautocmd = true dashboard.section.footer.val = 'Soli Deo Gloria' dashboard.section.footer.opts.hl = 'msgarea' alpha.setup(dashboard.opts)
fix(nvim): remove fortune call in alpha.lua
fix(nvim): remove fortune call in alpha.lua
Lua
unlicense
knpwrs/dotfiles
44ebea556a502684a63f4619ac341f50f165df0f
src/rspamadm/fuzzy_stat.lua
src/rspamadm/fuzzy_stat.lua
--Res here is the table of the following args: --workers: { -- pid: { -- data: { -- key_id: { -- matched: -- scanned: -- added: -- removed: -- errors: -- last_ips: { -- ip: { -- matched: -- scanned -- added: -- removed: -- } -- } -- } -- } -- } --} --.USE "getopt" local function add_data(target, src) for k,v in pairs(src) do if k ~= 'ips' then if target[k] then target[k] = target[k] + v else target[k] = v end else target[k] = v end end end local function print_stat(st, tabs) if st['checked'] then print(string.format('%sChecked: %8d', tabs, tonumber(st['checked']))) end if st['matched'] then print(string.format('%sMatched: %8d', tabs, tonumber(st['matched']))) end if st['errors'] then print(string.format('%sErrors: %9d', tabs, tonumber(st['errors']))) end if st['added'] then print(string.format('%sAdded: %10d', tabs, tonumber(st['added']))) end if st['deleted'] then print(string.format('%sAdded: %10d', tabs, tonumber(st['deleted']))) end end -- Sort by checked local function sort_ips(tbl) local res = {} for k,v in pairs(tbl) do table.insert(res, {ip = k, data = v}) end table.sort(res, function(a, b) local n1 = 0 if a['data']['checked'] then n1 = a['data']['checked'] end local n2 = 0 if b['data']['checked'] then n2 = b['data']['checked'] end return n1 > n2 end) return res end return function(args, res) local res_keys = {} local res_ips = {} local wrk = res['workers'] if wrk then for i,pr in pairs(wrk) do -- processes cycle if pr['data'] then for k,elts in pairs(pr['data']) do -- keys cycle if not res_keys[k] then res_keys[k] = {} end add_data(res_keys[k], elts) if elts['ips'] then for ip,v in pairs(elts['ips']) do if not res_ips[ip] then res_ips[ip] = {} end add_data(res_ips[ip], v) end end end end end end print('Keys statistics:') for k,st in pairs(res_keys) do print(string.format('Key id: %s', k)) print_stat(st, '\t') if st['ips'] then print('') print('\tIPs stat:') local sorted_ips = sort_ips(st['ips']) for i,v in ipairs(sorted_ips) do print(string.format('\t%s', v['ip'])) print_stat(v['data'], '\t\t') print('') end end print('') end print('') print('IPs statistics:') local sorted_ips = sort_ips(res_ips) for i, v in ipairs(sorted_ips) do print(string.format('%s', v['ip'])) print_stat(v['data'], '\t') print('') end end
--Res here is the table of the following args: --workers: { -- pid: { -- data: { -- key_id: { -- matched: -- scanned: -- added: -- removed: -- errors: -- last_ips: { -- ip: { -- matched: -- scanned -- added: -- removed: -- } -- } -- } -- } -- } --} --.USE "getopt" local function add_data(target, src) for k,v in pairs(src) do if k ~= 'ips' then if target[k] then target[k] = target[k] + v else target[k] = v end else if not target['ips'] then target['ips'] = {} end -- Iterate over IPs for ip,st in pairs(v) do if not target['ips'][ip] then target['ips'][ip] = {} end add_data(target['ips'][ip], st) end end end end local function print_stat(st, tabs) if st['checked'] then print(string.format('%sChecked: %8d', tabs, tonumber(st['checked']))) end if st['matched'] then print(string.format('%sMatched: %8d', tabs, tonumber(st['matched']))) end if st['errors'] then print(string.format('%sErrors: %9d', tabs, tonumber(st['errors']))) end if st['added'] then print(string.format('%sAdded: %10d', tabs, tonumber(st['added']))) end if st['deleted'] then print(string.format('%sAdded: %10d', tabs, tonumber(st['deleted']))) end end -- Sort by checked local function sort_ips(tbl) local res = {} for k,v in pairs(tbl) do table.insert(res, {ip = k, data = v}) end table.sort(res, function(a, b) local n1 = 0 if a['data']['checked'] then n1 = a['data']['checked'] end local n2 = 0 if b['data']['checked'] then n2 = b['data']['checked'] end return n1 > n2 end) return res end return function(args, res) local res_keys = {} local res_ips = {} local wrk = res['workers'] if wrk then for i,pr in pairs(wrk) do -- processes cycle if pr['data'] then for k,elts in pairs(pr['data']) do -- keys cycle if not res_keys[k] then res_keys[k] = {} end add_data(res_keys[k], elts) if elts['ips'] then for ip,v in pairs(elts['ips']) do if not res_ips[ip] then res_ips[ip] = {} end add_data(res_ips[ip], v) end end end end end end print('Keys statistics:') for k,st in pairs(res_keys) do print(string.format('Key id: %s', k)) print_stat(st, '\t') if st['ips'] then print('') print('\tIPs stat:') local sorted_ips = sort_ips(st['ips']) for i,v in ipairs(sorted_ips) do print(string.format('\t%s', v['ip'])) print_stat(v['data'], '\t\t') print('') end end print('') end print('') print('IPs statistics:') local sorted_ips = sort_ips(res_ips) for i, v in ipairs(sorted_ips) do print(string.format('%s', v['ip'])) print_stat(v['data'], '\t') print('') end end
Fix output
Fix output
Lua
apache-2.0
minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd
d9a8b9a64f055b000b06f0364c7b1fd28528252f
Source/PinnedDownClient/PinnedDownClient/Assets/Text/English.lua
Source/PinnedDownClient/PinnedDownClient/Assets/Text/English.lua
Card_0_0 = "Bridge Hit" Card_0_1 = "Cargo Bay Hit" Card_0_3 = "Direct Hit" Card_0_4 = "Engine Room Hit" Card_0_5 = "Engines Hit" Card_0_6 = "Sickbay Hit" Card_0_7 = "Weapon Systems Hit" Card_0_45 = "Ace In The Hole" Card_0_48 = "Never Say Die" Card_0_54 = "Berlin" Card_0_55 = "London" Card_0_56 = "Moscow" Card_0_57 = "Paris" Card_0_58 = "Washington" Card_0_72 = "Assault Cruiser" Card_0_73 = "Assault Frigate" Card_0_75 = "Behemoth" Card_0_84 = "Swarm Frigate" Card_0_0_Text = " " Card_0_1_Text = " " Card_0_3_Text = " " Card_0_4_Text = " " Card_0_5_Text = " " Card_0_6_Text = " " Card_0_7_Text = " " Card_0_45_Text = "FIGHT: Make a starship power +3." Card_0_48_Text = "FIGHT: Make a starship power +2 (or +4 if that starship is not damaged)." Card_0_54_Text = " " Card_0_55_Text = " " Card_0_56_Text = "Flagship." Card_0_57_Text = " " Card_0_58_Text = " " Card_0_72_Text = " " Card_0_73_Text = " " Card_0_75_Text = " " Card_0_84_Text = " " Card_Property_Power = "Power" Card_Property_Structure = "Structure" Card_Type_Damage = "Damage" Card_Type_Effect = "Effect" Card_Type_Starship = "Starship" Error_AuthenticationRequired = "You must authenticate yourself in order to play Pinned Down." Error_NotAllEnemyShipsAssigned = "You have to assign all of your ships to fight!" Error_NotAllFightsResolved = "You have to resolve all fights first!" Error_UnableToConntect = "Unable to connect to server." GameScreen_Button_EndTurnPhase = "End Turn Phase" GameScreen_Button_Hint = "Help" GameScreen_GameOver_Defeat = "DEFEAT!" GameScreen_GameOver_Victory = "VICTORY!" GameScreen_Hint_Assignment = "Assign your starships to enemy attackers by tapping one of your ships first, and an enemy ship after!" GameScreen_Hint_Attack = "" GameScreen_Hint_Fight = "Play effects to increase the power of your starships by tapping of your effects in hand first, and one of your ships after!\r\nResolve fights in order of your choice by tapping any of your assigned ships!" GameScreen_Hint_Jump = "" GameScreen_Hint_Main = "Tap a starship on your hand to deploy it for battle!\r\nTap and hold any hand card to show its details!\r\n" GameScreen_Info_DistanceCovered = "Distance Covered:" GameScreen_Info_TurnPhase = "Turn Phase:" GameScreen_Info_Threat = "Threat:" GameScreen_TurnPhase_Assignment = "Assignment" GameScreen_TurnPhase_Attack = "Attack" GameScreen_TurnPhase_Fight = "Fight" GameScreen_TurnPhase_Jump = "Jump" GameScreen_TurnPhase_Main = "Main" LoginScreen_Connecting = "Connecting" LoginScreen_Reconnect = "Reconnect" LoginScreen_UnableToConnect = "Connecting"
Card_0_0 = "Bridge Hit" Card_0_1 = "Cargo Bay Hit" Card_0_3 = "Direct Hit" Card_0_4 = "Engine Room Hit" Card_0_5 = "Engines Hit" Card_0_6 = "Sickbay Hit" Card_0_7 = "Weapon Systems Hit" Card_0_45 = "Ace In The Hole" Card_0_48 = "Never Say Die" Card_0_54 = "Berlin" Card_0_55 = "London" Card_0_56 = "Moscow" Card_0_57 = "Paris" Card_0_58 = "Washington" Card_0_72 = "Assault Cruiser" Card_0_73 = "Assault Frigate" Card_0_75 = "Behemoth" Card_0_84 = "Swarm Frigate" Card_0_0_Text = " " Card_0_1_Text = " " Card_0_3_Text = " " Card_0_4_Text = " " Card_0_5_Text = " " Card_0_6_Text = " " Card_0_7_Text = " " Card_0_45_Text = "FIGHT: Make a starship power +3." Card_0_48_Text = "FIGHT: Make a starship power +2 (or +4 if that starship is not damaged)." Card_0_54_Text = " " Card_0_55_Text = " " Card_0_56_Text = "Flagship." Card_0_57_Text = " " Card_0_58_Text = " " Card_0_72_Text = " " Card_0_73_Text = " " Card_0_75_Text = " " Card_0_84_Text = " " Card_Property_Power = "Power" Card_Property_Structure = "Structure" Card_Type_Damage = "Damage" Card_Type_Effect = "Effect" Card_Type_Starship = "Starship" Error_AuthenticationRequired = "You must authenticate yourself in order to play Pinned Down." Error_NotAllEnemyShipsAssigned = "You have to assign all of your ships to fight!" Error_NotAllFightsResolved = "You have to resolve all fights first!" Error_UnableToConntect = "Unable to connect to server.\r\n\r\nCheck http://pinneddown.de/server/ if you're sure you've done everything right!" GameScreen_Button_EndTurnPhase = "End Turn Phase" GameScreen_Button_Hint = "Help" GameScreen_GameOver_Defeat = "DEFEAT!" GameScreen_GameOver_Victory = "VICTORY!" GameScreen_Hint_Assignment = "Assign your starships to enemy attackers by tapping one of your ships first, and an enemy ship after!" GameScreen_Hint_Attack = "" GameScreen_Hint_Fight = "Play effects to increase the power of your starships by tapping of your effects in hand first, and one of your ships after!\r\nResolve fights in order of your choice by tapping any of your assigned ships!" GameScreen_Hint_Jump = "" GameScreen_Hint_Main = "Tap a starship on your hand to deploy it for battle!\r\nTap and hold any hand card to show its details!\r\n" GameScreen_Info_DistanceCovered = "Distance Covered:" GameScreen_Info_TurnPhase = "Turn Phase:" GameScreen_Info_Threat = "Threat:" GameScreen_TurnPhase_Assignment = "Assignment" GameScreen_TurnPhase_Attack = "Attack" GameScreen_TurnPhase_Fight = "Fight" GameScreen_TurnPhase_Jump = "Jump" GameScreen_TurnPhase_Main = "Main" LoginScreen_Connecting = "Connecting" LoginScreen_Reconnect = "Reconnect" LoginScreen_UnableToConnect = "Connecting"
FIXED #40 UI - Show useful links with error messages
FIXED #40 UI - Show useful links with error messages
Lua
mit
npruehs/pinned-down-client-win8,npruehs/pinned-down-client-win8
8797fd5adfea08e23b5515bc087db0f3fc816570
testserver/npc/base/condition/skill.lua
testserver/npc/base/condition/skill.lua
require("base.class") require("npc.base.condition.condition") module("npc.base.condition.skill", package.seeall) skill = base.class.class(npc.base.condition.condition.condition, function(self, name, comp, value) npc.base.condition.condition.condition:init(self); self["value"], self["valuetype"] = npc.base.talk._set_value(value); self["skill"] = name; if (comp == "=") then self["check"] = _skill_helper_equal; elseif (comp == "<>" or comp == "!=" or comp == "~=") then self["check"] = _skill_helper_notequal; elseif (comp == "<=" or comp == "=<") then self["check"] = _skill_helper_lesserequal; elseif (comp == ">=" or comp == "=>") then self["check"] = _skill_helper_greaterequal; elseif (comp == ">") then self["check"] = _skill_helper_greater; elseif (comp == "<") then self["check"] = _skill_helper_lesser; else -- unkonwn comparator end; end); function _skill_helper_equal(self, npcChar, texttype, player) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (value == player:getSkill(self.skill)) end; function _skill_helper_notequal(self, npcChar, texttype, player) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (value ~= player:getSkill(self.skill)) end; function _skill_helper_lesserequal(self, npcChar, texttype, player) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (value <= player:getSkill(self.skill)) end; function _skill_helper_greaterequal(self, npcChar, texttype, player) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (value >= player:getSkill(self.skill)) end; function _skill_helper_lesser(self, npcChar, texttype, player) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (value < player:getSkill(self.skill)) end; function _skill_helper_greater(self, npcChar, texttype, player) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (value > player:getSkill(self.skill)) end;
require("base.class") require("npc.base.condition.condition") module("npc.base.condition.skill", package.seeall) skill = base.class.class(npc.base.condition.condition.condition, function(self, name, comp, value) npc.base.condition.condition.condition:init(self); self["value"], self["valuetype"] = npc.base.talk._set_value(value); self["skill"] = name; if (comp == "=") then self["check"] = _skill_helper_equal; elseif (comp == "<>" or comp == "!=" or comp == "~=") then self["check"] = _skill_helper_notequal; elseif (comp == "<=" or comp == "=<") then self["check"] = _skill_helper_lesserequal; elseif (comp == ">=" or comp == "=>") then self["check"] = _skill_helper_greaterequal; elseif (comp == ">") then self["check"] = _skill_helper_greater; elseif (comp == "<") then self["check"] = _skill_helper_lesser; else -- unkonwn comparator end; end); function _skill_helper_equal(self, npcChar, texttype, player) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (player:getSkill(self.skill) == value) end; function _skill_helper_notequal(self, npcChar, texttype, player) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (player:getSkill(self.skill) ~= value) end; function _skill_helper_lesserequal(self, npcChar, texttype, player) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (player:getSkill(self.skill) <= value) end; function _skill_helper_greaterequal(self, npcChar, texttype, player) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (player:getSkill(self.skill) >= value) end; function _skill_helper_lesser(self, npcChar, texttype, player) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (player:getSkill(self.skill) < value) end; function _skill_helper_greater(self, npcChar, texttype, player) local value = npc.base.talk._get_value(self.npc, self.value, self.valuetype); return (player:getSkill(self.skill) > value) end;
Bug in easyNPC
Bug in easyNPC
Lua
agpl-3.0
KayMD/Illarion-Content,LaFamiglia/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content
419c943b8e72a11a21631c0b63ac60ad5de70f13
src/program/alarms/set_operator_state/set_operator_state.lua
src/program/alarms/set_operator_state/set_operator_state.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local common = require("program.config.common") function show_usage(status, err_msg) if err_msg then print('error: '..err_msg) end print(require("program.alarms.set_operator_state.README_inc")) main.exit(status) end local function fatal() show_usage(1) end local function parse_args (args) if #args < 3 or #args > 4 then fatal() end local alarm_type_id, alarm_type_qualifier = (args[2]):match("([%w]+)/([%w]+)") if not alarm_type_id then alarm_type_id, alarm_type_qualifier = args[2], '' end local ret = { key = { resource = args[1], alarm_type_id = alarm_type_id, alarm_type_qualifier = alarm_type_qualifier, }, state = args[3], text = args[4] or '', } return ret end function run(args) local opts = { command='set-alarm-operator-state', with_path=false, is_config=false, usage = show_usage, failsafe = true } local args, cdr = common.parse_command_line(args, opts) local l_args = parse_args(cdr) local response = common.call_leader( args.instance_id, 'set-alarm-operator-state', { schema = args.schema_name, revision = args.revision_date, resource = l_args.key.resource, alarm_type_id = l_args.key.alarm_type_id, alarm_type_qualifier = l_args.key.alarm_type_qualifier, state = l_args.state, text = l_args.text }) common.print_and_exit(response, "success") end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local common = require("program.config.common") function show_usage(program, status, err_msg) if err_msg then print('error: '..err_msg) end print(require("program.alarms.set_operator_state.README_inc")) main.exit(status) end local function fatal() show_usage('set-operator-state', 1) end local function parse_args (args) if #args < 3 or #args > 4 then fatal() end local alarm_type_id, alarm_type_qualifier = (args[2]):match("([%w]+)/([%w]+)") if not alarm_type_id then alarm_type_id, alarm_type_qualifier = args[2], '' end local ret = { key = { resource = args[1], alarm_type_id = alarm_type_id, alarm_type_qualifier = alarm_type_qualifier, }, state = args[3], text = args[4] or '', } return ret end function run(args) local opts = { command='set-alarm-operator-state', with_path=false, is_config=false, usage=show_usage, failsafe=true } local args, cdr = common.parse_command_line(args, opts) local l_args = parse_args(cdr) local response = common.call_leader( args.instance_id, 'set-alarm-operator-state', { schema = args.schema_name, revision = args.revision_date, resource = l_args.key.resource, alarm_type_id = l_args.key.alarm_type_id, alarm_type_qualifier = l_args.key.alarm_type_qualifier, state = l_args.state, text = l_args.text }) common.print_and_exit(response, "success") end
Fix error message
Fix error message
Lua
apache-2.0
Igalia/snabbswitch,eugeneia/snabbswitch,dpino/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,snabbco/snabb,Igalia/snabb,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabb,eugeneia/snabb,dpino/snabb,eugeneia/snabbswitch,Igalia/snabbswitch,Igalia/snabb,eugeneia/snabb,eugeneia/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,SnabbCo/snabbswitch,dpino/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,Igalia/snabbswitch,dpino/snabb,snabbco/snabb,dpino/snabbswitch,Igalia/snabb,SnabbCo/snabbswitch,dpino/snabbswitch,dpino/snabb,SnabbCo/snabbswitch,alexandergall/snabbswitch,dpino/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,snabbco/snabb,snabbco/snabb,Igalia/snabb,eugeneia/snabb,snabbco/snabb,alexandergall/snabbswitch,dpino/snabb,snabbco/snabb,Igalia/snabb,eugeneia/snabb,dpino/snabb,Igalia/snabb,snabbco/snabb,eugeneia/snabbswitch,snabbco/snabb,dpino/snabbswitch,alexandergall/snabbswitch,eugeneia/snabb
bae982571abb9c109c28cc90aabefe5f7b2c92c8
src/analytics/delrequest.lua
src/analytics/delrequest.lua
-- -- Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. -- local sm = ARGV[1]..":"..ARGV[2]..":"..ARGV[3]..":"..ARGV[4] local ngen_sm = ARGV[1]..":"..ARGV[2]..":"..ARGV[3]..":"..ARGV[6] redis.log(redis.LOG_NOTICE,"DelRequest for "..sm) local db = tonumber(ARGV[5]) redis.call('select',db) local typ = redis.call('smembers',"TYPES:"..sm) local ism = redis.call('sismember', 'NGENERATORS', ngen_sm) if ism == 0 then return false end redis.call('expire', "NGENERATORS", 40) local res = {} for k,v in pairs(typ) do redis.log(redis.LOG_NOTICE, "Read UVES:"..sm..":"..v) local lres = redis.call('zrange',"UVES:"..sm..":"..v, 0, -1, "withscores") redis.call('del', "UVES:"..sm..":"..v) local iter = 1 local citer = 1 redis.log(redis.LOG_NOTICE, "Delete "..sm..":"..v.." [#"..(#lres/2).."]") while iter <= #lres do local deltyp = v local deluve = lres[iter] local delseq = lres[iter+1] local st,en table.insert(res, deluve) table.insert(res, deltyp) st,en = string.find(deluve,":") local deltbl = string.sub(deluve, 1, st-1) local dkey = "DEL:"..deluve..":"..sm..":"..deltyp..":"..delseq local part = redis.call('hget',"KEY2PART:"..sm..":"..deltyp, deluve) if not part then part = "NULL" else redis.call('hdel', "KEY2PART:"..sm..":"..deltyp, deluve) redis.call('srem', "PART2KEY:"..part, sm..":"..deltyp..":"..deluve) end local dval = "VALUES:"..deluve..":"..sm..":"..deltyp local lttt = redis.call('exists', dval) if lttt == 1 then redis.call('rename', dval, dkey) end dval = "ORIGINS:"..deluve if redis.call('srem', dval, sm..":"..deltyp) == 1 then dval = "TABLE:"..deltbl redis.call('srem', dval, deluve..":"..sm..":"..deltyp) else dval = "ALARM_ORIGINS:"..deluve redis.call('srem', dval, sm..":"..deltyp) dval = "ALARM_TABLE:"..deltbl redis.call('srem', dval, deluve..":"..sm..":"..deltyp) end if lttt == 1 then redis.call('lpush',"DELETED", dkey) end iter = iter + 2 if citer > 100 then redis.call('expire', "NGENERATORS", 40) citer = 1 else citer = citer + 2 end end end redis.call('del', "TYPES:"..ARGV[1]..":"..ARGV[2]..":"..ARGV[3]..":"..ARGV[4]) redis.call('srem', "NGENERATORS", ngen_sm) redis.log(redis.LOG_NOTICE,"Delete Request for "..sm.." successful") return res
-- -- Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. -- local sm = ARGV[1]..":"..ARGV[2]..":"..ARGV[3]..":"..ARGV[4] local ngen_sm = ARGV[1]..":"..ARGV[2]..":"..ARGV[3]..":"..ARGV[6] redis.log(redis.LOG_NOTICE,"DelRequest for "..sm) local db = tonumber(ARGV[5]) redis.call('select',db) local typ = redis.call('smembers',"TYPES:"..sm) local ism = redis.call('sismember', 'NGENERATORS', ngen_sm) if ism == 0 then return false end redis.call('expire', "NGENERATORS", 40) local res = {} for k,v in pairs(typ) do redis.log(redis.LOG_NOTICE, "Read UVES:"..sm..":"..v) local lres = redis.call('zrange',"UVES:"..sm..":"..v, 0, -1, "withscores") redis.call('del', "UVES:"..sm..":"..v) local iter = 1 local citer = 1 redis.log(redis.LOG_NOTICE, "Delete "..sm..":"..v.." [#"..(#lres/2).."]") while iter <= #lres do local deltyp = v local deluve = lres[iter] local delseq = lres[iter+1] local st,en table.insert(res, deluve) table.insert(res, deltyp) st,en = string.find(deluve,":") local deltbl = string.sub(deluve, 1, st-1) local part = redis.call('hget',"KEY2PART:"..sm..":"..deltyp, deluve) if not part then part = "NULL" else redis.call('hdel', "KEY2PART:"..sm..":"..deltyp, deluve) redis.call('srem', "PART2KEY:"..part, sm..":"..deltyp..":"..deluve) end local dval = "VALUES:"..deluve..":"..sm..":"..deltyp redis.call('del', dval) dval = "ORIGINS:"..deluve if redis.call('srem', dval, sm..":"..deltyp) == 1 then dval = "TABLE:"..deltbl redis.call('srem', dval, deluve..":"..sm..":"..deltyp) else dval = "ALARM_ORIGINS:"..deluve redis.call('srem', dval, sm..":"..deltyp) dval = "ALARM_TABLE:"..deltbl redis.call('srem', dval, deluve..":"..sm..":"..deltyp) end iter = iter + 2 if citer > 100 then redis.call('expire', "NGENERATORS", 40) citer = 1 else citer = citer + 2 end end end redis.call('del', "TYPES:"..ARGV[1]..":"..ARGV[2]..":"..ARGV[3]..":"..ARGV[4]) redis.call('srem', "NGENERATORS", ngen_sm) redis.log(redis.LOG_NOTICE,"Delete Request for "..sm.." successful") return res
We should not queue UVEs for delete during generator removal. Closes-Bug:1671281
We should not queue UVEs for delete during generator removal. Closes-Bug:1671281 Change-Id: I36d63950c52833388fb072fc97eb66de37c73f58
Lua
apache-2.0
rombie/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,nischalsheth/contrail-controller,rombie/contrail-controller,nischalsheth/contrail-controller,rombie/contrail-controller,nischalsheth/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller,eonpatapon/contrail-controller,nischalsheth/contrail-controller,rombie/contrail-controller,nischalsheth/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller,nischalsheth/contrail-controller,nischalsheth/contrail-controller,eonpatapon/contrail-controller,nischalsheth/contrail-controller
bc28bde4db80c8f5131bc71dd71d04f508618c8b
agents/monitoring/tests/fixtures/protocol/server.lua
agents/monitoring/tests/fixtures/protocol/server.lua
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local tls = require('tls') local timer = require('timer') local lineEmitter = LineEmitter:new() local port = 50041 local send_schedule_changed_initial = 2000 local send_schedule_changed_interval = 60000 local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(client, payload) -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil response.target = payload.source response.source = payload.target response.id = payload.id print("Sending response:") p(response) response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') end local send_schedule_changed = function(client) local request = fixtures['check_schedule.changed.request'] print("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end tls.createServer(options, function (client) client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) print("Got payload:") p(payload) respond(client, payload) end) timer.setTimeout(send_schedule_changed_initial, function() send_schedule_changed(client) end) timer.setInterval(send_schedule_changed_interval, function() send_schedule_changed(client) end) end):listen(port) print("TCP echo server listening on port " .. port)
local net = require('net') local JSON = require('json') local fixtures = require('./') local LineEmitter = require('line-emitter').LineEmitter local tls = require('tls') local timer = require('timer') local string = require('string') local math = require('math') local lineEmitter = LineEmitter:new() local ports = {50041, 50051, 50061} local opts = {} local function set_option(options, name, default) options[name] = process.env[string.upper(name)] or default end set_option(opts, "send_schedule_changed_initial", 2000) set_option(opts, "send_schedule_changed_interval", 60000) set_option(opts, "destroy_connection_jitter", 60000) set_option(opts, "destroy_connection_base", 60000) local keyPem = [[ -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDx3wdzpq2rvwm3Ucun1qAD/ClB+wW+RhR1nVix286QvaNqePAd CAwwLL82NqXcVQRbQ4s95splQnwvjgkFdKVXFTjPKKJI5aV3wSRN61EBVPdYpCre 535yfG/uDysZFCnVQdnCZ1tnXAR8BirxCNjHqbVyIyBGjsNoNCEPb2R35QIDAQAB AoGBAJNem9C4ftrFNGtQ2DB0Udz7uDuucepkErUy4MbFsc947GfENjDKJXr42Kx0 kYx09ImS1vUpeKpH3xiuhwqe7tm4FsCBg4TYqQle14oxxm7TNeBwwGC3OB7hiokb aAjbPZ1hAuNs6ms3Ybvvj6Lmxzx42m8O5DXCG2/f+KMvaNUhAkEA/ekrOsWkNoW9 2n3m+msdVuxeek4B87EoTOtzCXb1dybIZUVv4J48VAiM43hhZHWZck2boD/hhwjC M5NWd4oY6QJBAPPcgBVNdNZSZ8hR4ogI4nzwWrQhl9MRbqqtfOn2TK/tjMv10ALg lPmn3SaPSNRPKD2hoLbFuHFERlcS79pbCZ0CQQChX3PuIna/gDitiJ8oQLOg7xEM wk9TRiDK4kl2lnhjhe6PDpaQN4E4F0cTuwqLAoLHtrNWIcOAQvzKMrYdu1MhAkBm Et3qDMnjDAs05lGT72QeN90/mPAcASf5eTTYGahv21cb6IBxM+AnwAPpqAAsHhYR 9h13Y7uYbaOjvuF23LRhAkBoI9eaSMn+l81WXOVUHnzh3ZwB4GuTyxMXXNOhuiFd 0z4LKAMh99Z4xQmqSoEkXsfM4KPpfhYjF/bwIcP5gOei -----END RSA PRIVATE KEY----- ]] local certPem = [[ -----BEGIN CERTIFICATE----- MIIDXDCCAsWgAwIBAgIJAKL0UG+mRkSPMA0GCSqGSIb3DQEBBQUAMH0xCzAJBgNV BAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEGA1UEBxMKUmh5cyBKb25l czEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVzdCBUTFMgQ2VydGlmaWNh dGUxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0wOTExMTEwOTUyMjJaFw0yOTExMDYw OTUyMjJaMH0xCzAJBgNVBAYTAlVLMRQwEgYDVQQIEwtBY2tuYWNrIEx0ZDETMBEG A1UEBxMKUmh5cyBKb25lczEQMA4GA1UEChMHbm9kZS5qczEdMBsGA1UECxMUVGVz dCBUTFMgQ2VydGlmaWNhdGUxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG 9w0BAQEFAAOBjQAwgYkCgYEA8d8Hc6atq78Jt1HLp9agA/wpQfsFvkYUdZ1YsdvO kL2janjwHQgMMCy/Njal3FUEW0OLPebKZUJ8L44JBXSlVxU4zyiiSOWld8EkTetR AVT3WKQq3ud+cnxv7g8rGRQp1UHZwmdbZ1wEfAYq8QjYx6m1ciMgRo7DaDQhD29k d+UCAwEAAaOB4zCB4DAdBgNVHQ4EFgQUL9miTJn+HKNuTmx/oMWlZP9cd4QwgbAG A1UdIwSBqDCBpYAUL9miTJn+HKNuTmx/oMWlZP9cd4ShgYGkfzB9MQswCQYDVQQG EwJVSzEUMBIGA1UECBMLQWNrbmFjayBMdGQxEzARBgNVBAcTClJoeXMgSm9uZXMx EDAOBgNVBAoTB25vZGUuanMxHTAbBgNVBAsTFFRlc3QgVExTIENlcnRpZmljYXRl MRIwEAYDVQQDEwlsb2NhbGhvc3SCCQCi9FBvpkZEjzAMBgNVHRMEBTADAQH/MA0G CSqGSIb3DQEBBQUAA4GBADRXXA2xSUK5W1i3oLYWW6NEDVWkTQ9RveplyeS9MOkP e7yPcpz0+O0ZDDrxR9chAiZ7fmdBBX1Tr+pIuCrG/Ud49SBqeS5aMJGVwiSd7o1n dhU2Sz3Q60DwJEL1VenQHiVYlWWtqXBThe9ggqRPnCfsCRTP8qifKkjk45zWPcpN -----END CERTIFICATE----- ]] local options = { cert = certPem, key = keyPem } local respond = function(log, client, payload) -- skip responses to requests if payload.method == nil then return end local response_method = payload.method .. '.response' local response = JSON.parse(fixtures[response_method]) local response_out = nil response.target = payload.source response.source = payload.target response.id = payload.id log("Sending response:") p(response) response_out = JSON.stringify(response) response_out:gsub("\n", " ") client:write(response_out .. '\n') end local send_schedule_changed = function(log, client) local request = fixtures['check_schedule.changed.request'] log("Sending request:") p(JSON.parse(request)) client:write(request .. '\n') end local function start_fixture_server(options, port) local log = function(...) print(port .. ": " .. ...) end tls.createServer(options, function (client) client:pipe(lineEmitter) lineEmitter:on('data', function(line) local payload = JSON.parse(line) log("Got payload:") p(payload) respond(log, client, payload) end) timer.setTimeout(opts.send_schedule_changed_initial, function() send_schedule_changed(log, client) end) timer.setInterval(opts.send_schedule_changed_interval, function() send_schedule_changed(log, client) end) -- Disconnect the agent after some random number of seconds -- to exercise reconnect logic local disconnect_time = opts.destroy_connection_base + math.floor(math.random() * opts.destroy_connection_jitter) timer.setTimeout(disconnect_time, function() log("Destroying connection after " .. disconnect_time .. "ms connected") client:destroy() end) end):listen(port) end -- There is no cleanup code for the server here as the process for exiting is -- to just ctrl+c the runner or kill the process. for k, v in pairs(ports) do start_fixture_server(options, v) print("TCP echo server listening on port " .. v) end
monitoring: tests: server: listen on multiple ports
monitoring: tests: server: listen on multiple ports listen on all of the expected ports of the fixtures config file. Then randomly disconnect the agent at random intervals to test the retry logic.
Lua
apache-2.0
cp16net/virgo-base,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,christopherjwang/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base
368693b7a8599941d5bfe3b73f440e16ff115a24
src/lua-factory/sources/grl-pocket.lua
src/lua-factory/sources/grl-pocket.lua
--[[ * Copyright (C) 2015 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] -- Documented at: -- http://getpocket.com/developer/docs/v3/retrieve -- -- We only get videos here because if we didn't filter ahead of time -- we'd need to check whether each URL was supported through -- totem-pl-parser/quvi, which would be too slow POCKET_GET_URL = 'https://getpocket.com/v3/get?consumer_key=%s&access_token=%s&sort=newest&contentType=video&detailType=complete&count=%d&offset=%d' HAS_VIDEO = '1' IS_VIDEO = '2' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-pocket-lua", name = 'Pocket', description = 'A source for browsing Pocket videos', goa_account_provider = 'pocket', goa_account_feature = 'read-later', supported_keys = { 'id', 'thumbnail', 'title', 'url', 'favourite', 'creation-date' }, supported_media = 'video', icon = 'resource:///org/gnome/grilo/plugins/pocket/pocket.svg', tags = { 'net:internet' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) local count = grl.get_options("count") local skip = grl.get_options("skip") local operation_id = grl.get_options('operation-id') local url = string.format(POCKET_GET_URL, grl.goa_consumer_key(), grl.goa_access_token(), count, skip) grl.debug ("Fetching URL: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") grl.fetch(url, "pocket_fetch_cb") end ------------------------ -- Callback functions -- ------------------------ -- Newest first function sort_added_func(itema, itemb) return itema.time_added > itemb.time_added end -- From http://lua-users.org/wiki/StringRecipes function string.starts(String,Start) return string.sub(String,1,string.len(Start))==Start end -- return all the media found function pocket_fetch_cb(results) local count = grl.get_options("count") if not results then grl.callback () return end json = grl.lua.json.string_to_table(results) -- Put the table in an array so we can sort it local array = {} for n, item in pairs(json.list) do table.insert(array, item) end table.sort(array, sort_added_func) for i, item in ipairs(array) do local media = create_media(item) if media then count = count - 1 grl.callback(media, count) end -- Bail out if we've given enough items if count == 0 then return end end grl.callback() end ------------- -- Helpers -- ------------- function create_media(item) local media = {} if not item.has_video or (item.has_video ~= HAS_VIDEO and item.has_video ~= IS_VIDEO) then grl.debug("We filtered for videos, but this isn't one: " .. grl.lua.inspect(item)) return nil end if item.has_video == HAS_VIDEO then if not item.videos then grl.debug('Item has no video, skipping: ' .. grl.lua.inspect(item)) return nil end if #item.videos > 1 then grl.debug('Item has than one video, skipping: ' .. grl.lua.inspect(item)) return nil end end media.type = "video" media.id = item.resolved_id if media.id == '' then media.id = item.item_id end local url = item.resolved_url if url == '' then url = item.given_url end if item.has_video == HAS_VIDEO then url = item.videos['1'].src -- BUG: Pocket puts garbage like: -- src = "//player.vimeo.com/video/75911370" -- FIXME: this should be https instead but then -- quvi doesn't detect it if string.starts(url, '//') then url = 'http:' .. url end end if grl.is_video_site(url) then media.external_url = url else media.url = url end media.title = item.resolved_title if media.title == '' then media.title = item.given_title end if media.title == '' then media.title = media.url end media.favourite = (item.favorite and item.favorite == '1') if item.image then media.thumbnail = item.image.src end media.creation_date = item.time_added media.modification_date = item.time_updated return media end
--[[ * Copyright (C) 2015 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * --]] -- Documented at: -- http://getpocket.com/developer/docs/v3/retrieve -- -- We only get videos here because if we didn't filter ahead of time -- we'd need to check whether each URL was supported through -- totem-pl-parser/quvi, which would be too slow POCKET_GET_URL = 'https://getpocket.com/v3/get?consumer_key=%s&access_token=%s&sort=newest&contentType=video&detailType=complete&count=%d&offset=%d' HAS_VIDEO = '1' IS_VIDEO = '2' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-pocket-lua", name = 'Pocket', description = 'A source for browsing Pocket videos', goa_account_provider = 'pocket', goa_account_feature = 'read-later', supported_keys = { 'id', 'thumbnail', 'title', 'url', 'favourite', 'creation-date' }, supported_media = 'video', icon = 'resource:///org/gnome/grilo/plugins/pocket/pocket.svg', tags = { 'net:internet' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media, options, callback) local count = options.count local skip = options.skip local url = string.format(POCKET_GET_URL, grl.goa_consumer_key(), grl.goa_access_token(), count, skip) grl.debug ("Fetching URL: " .. url .. " (count: " .. count .. " skip: " .. skip .. ")") local userdata = {callback = callback, count = count} grl.fetch(url, pocket_fetch_cb, userdata) end ------------------------ -- Callback functions -- ------------------------ -- Newest first function sort_added_func(itema, itemb) return itema.time_added > itemb.time_added end -- From http://lua-users.org/wiki/StringRecipes function string.starts(String,Start) return string.sub(String,1,string.len(Start))==Start end -- return all the media found function pocket_fetch_cb(results, userdata) local count = userdata.count if not results then userdata.callback() return end json = grl.lua.json.string_to_table(results) -- Put the table in an array so we can sort it local array = {} for n, item in pairs(json.list) do table.insert(array, item) end table.sort(array, sort_added_func) for i, item in ipairs(array) do local media = create_media(item) if media then count = count - 1 userdata.callback(media, count) end -- Bail out if we've given enough items if count == 0 then return end end userdata.callback() end ------------- -- Helpers -- ------------- function create_media(item) local media = {} if not item.has_video or (item.has_video ~= HAS_VIDEO and item.has_video ~= IS_VIDEO) then grl.debug("We filtered for videos, but this isn't one: " .. grl.lua.inspect(item)) return nil end if item.has_video == HAS_VIDEO then if not item.videos then grl.debug('Item has no video, skipping: ' .. grl.lua.inspect(item)) return nil end if #item.videos > 1 then grl.debug('Item has than one video, skipping: ' .. grl.lua.inspect(item)) return nil end end media.type = "video" media.id = item.resolved_id if media.id == '' then media.id = item.item_id end local url = item.resolved_url if url == '' then url = item.given_url end if item.has_video == HAS_VIDEO then url = item.videos['1'].src -- BUG: Pocket puts garbage like: -- src = "//player.vimeo.com/video/75911370" -- FIXME: this should be https instead but then -- quvi doesn't detect it if string.starts(url, '//') then url = 'http:' .. url end end if grl.is_video_site(url) then media.external_url = url else media.url = url end media.title = item.resolved_title if media.title == '' then media.title = item.given_title end if media.title == '' then media.title = media.url end media.favourite = (item.favorite and item.favorite == '1') if item.image then media.thumbnail = item.image.src end media.creation_date = item.time_added media.modification_date = item.time_updated return media end
lua-factory: port grl-pocket.lua to the new lua system
lua-factory: port grl-pocket.lua to the new lua system https://bugzilla.gnome.org/show_bug.cgi?id=753141 Acked-by: Victor Toso <b1c1d8736f20db3fb6c1c66bb1455ed43909f0d8@victortoso.com>
Lua
lgpl-2.1
jasuarez/grilo-plugins,GNOME/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,MikePetullo/grilo-plugins
ae1d5eca726701e37ff1c0b59d25b260efc3c673
CircuitsUI_0.1.0/control.lua
CircuitsUI_0.1.0/control.lua
--control.lua -- Show ALL signals connected to network, and the value of them -- Button in top left to open up list of all UI Combinators -- Condition on UI combinator for when to auto-show the data -- Work in multiplayer -- Configure update interval require "libs.itemselection" require "signal_gui" --We'll keep our own base of belts to not iterate trough all belts everytime local combinatorsToUI = {} local update_interval = 30 --That's a lot I think. --Helper method for my debugging while coding local function out(txt) debug = false if debug then game.print(txt) end end local function txtpos(pos) return "{" .. pos["x"] .. ", " .. pos["y"] .."}" end --Creates a new GUI and returns it's var local function createGUI(entity) local id = #combinatorsToUI local centerpane = game.players[1].gui.left if centerpane["fum_frame"] == nil then centerpane.add({type = "frame", name = "fum_frame"}) centerpane["fum_frame"].add({type = "scroll-pane", name = "fum_panel"}) end while centerpane["fum_frame"]["fum_panel"]["gauge" .. id] do id = id + 1 end local newGui = centerpane["fum_frame"]["fum_panel"].add({type = "scroll-pane", name = "gauge" .. id, direction="horizontal"}) newGui.add({type = "textfield", name = "gauge_label"}) newGui["gauge_label"].text = "ID : " .. id CreateSignalGuiPanel(newGui, nil) return newGui end --We add all the belts in the game to our data local function onInit() if not global.fum_uic then global.fum_uic = {} end combinatorsToUI = global.fum_uic local toRemove = {} for k, v in pairs(combinatorsToUI) do if v[1] then v.entity = v[1] end if v[2] then v.ui = v[2] end if not v.entity or not v.entity.valid then table.insert(toRemove, key) end end for k, v in pairs(toRemove) do destroyCombinator(k) end end --We store which belts are in the world for next time local function onLoad() combinatorsToUI = global.fum_uic end --Destroys a gui and removes from table local function destroyGui(entity) --out("Tries to remove : " .. tostring(entity) .. "at : " .. txtpos(entity.position)) out(#combinatorsToUI) for k, v in pairs(combinatorsToUI) do --out(tostring(v.entity) .. ", " .. tostring(v[2])) local ent = v.entity if ent then out(txtpos(ent.position)) end if not ent or txtpos(ent.position) == txtpos(entity.position) then destroyCombinator(k) end end end function destroyCombinator(key) local v = combinatorsToUI[k] if v then v.ui.destroy() end out("destroy") table.remove(combinatorsToUI, k) local centerpane = game.players[1].gui.left if #centerpane["fum_frame"]["fum_panel"].children == 0 then centerpane["fum_frame"].destroy() end end --When we place a new ui combinator, it's stored. Value is {entity, ui} local function onPlaceEntity(event) if event.created_entity.name == "ui-combinator" then local newUI = createGUI(event.created_entity) local temp = {entity = event.created_entity, ui = newUI} table.insert(combinatorsToUI, temp) --out("Added : ".. tostring(event.created_entity) .. " at : " .. txtpos(event.created_entity.position) ) out("Size : " .. #combinatorsToUI) end end --Entity removed from table when removed from world local function onRemoveEntity(event) if event.entity.name == "ui-combinator" then destroyGui(event.entity) out("Size : " .. #combinatorsToUI) end end --Updates UI based on blocks signals local function updateUICombinator(uicomb) local entity = uicomb.entity local circuit = entity.get_circuit_network(defines.wire_type.red) if not circuit then circuit = entity.get_circuit_network(defines.wire_type.green) end UpdateSignalGuiPanel(uicomb.ui.signals, circuit) end local function onTick() if 0 == game.tick % update_interval then for k, v in pairs(combinatorsToUI) do updateUICombinator(combinatorsToUI[k]) end end end script.on_init(onInit) script.on_configuration_changed(onInit) script.on_load(onLoad) script.on_event(defines.events.on_built_entity, onPlaceEntity) script.on_event(defines.events.on_robot_built_entity, onPlaceEntity) script.on_event(defines.events.on_preplayer_mined_item, onRemoveEntity) script.on_event(defines.events.on_robot_pre_mined, onRemoveEntity) script.on_event(defines.events.on_entity_died, onRemoveEntity) script.on_event(defines.events.on_tick, onTick)
--control.lua -- Show ALL signals connected to network, and the value of them -- Button in top left to open up list of all UI Combinators -- Condition on UI combinator for when to auto-show the data -- Work in multiplayer -- Configure update interval require "libs.itemselection" require "signal_gui" --We'll keep our own base of belts to not iterate trough all belts everytime local combinatorsToUI = {} local update_interval = 30 --That's a lot I think. --Helper method for my debugging while coding local function out(txt) debug = false if debug then game.print(txt) end end local function txtpos(pos) return "{" .. pos["x"] .. ", " .. pos["y"] .."}" end --Creates a new GUI and returns it's var local function createGUI(entity) local id = #combinatorsToUI local centerpane = game.players[1].gui.left if centerpane["fum_frame"] == nil then centerpane.add({type = "frame", name = "fum_frame"}) centerpane["fum_frame"].add({type = "scroll-pane", name = "fum_panel"}) end while centerpane["fum_frame"]["fum_panel"]["gauge" .. id] do id = id + 1 end local newGui = centerpane["fum_frame"]["fum_panel"].add({type = "scroll-pane", name = "gauge" .. id, direction="horizontal"}) newGui.add({type = "textfield", name = "gauge_label"}) newGui["gauge_label"].text = "ID : " .. id CreateSignalGuiPanel(newGui, nil) return newGui end --We add all the belts in the game to our data local function onInit() if not global.fum_uic then global.fum_uic = {} end combinatorsToUI = global.fum_uic local toRemove = {} for k, v in pairs(combinatorsToUI) do if v[1] then v.entity = v[1] end if v[2] then v.ui = v[2] end if not v.entity or not v.entity.valid then table.insert(toRemove, key) end end for k, v in pairs(toRemove) do destroyCombinator(k) end end --We store which belts are in the world for next time local function onLoad() combinatorsToUI = global.fum_uic end --Destroys a gui and removes from table local function destroyGui(entity) --out("Tries to remove : " .. tostring(entity) .. "at : " .. txtpos(entity.position)) out(#combinatorsToUI) for k, v in pairs(combinatorsToUI) do --out(tostring(v.entity) .. ", " .. tostring(v[2])) local ent = v.entity if ent and ent.valid then out(txtpos(ent.position)) end if not ent or not ent.valid then destroyCombinator(k) return end if entity.valid and txtpos(ent.position) == txtpos(entity.position) then destroyCombinator(k) end end end function destroyCombinator(key) local v = combinatorsToUI[key] if v then v.ui.destroy() end out("destroy") table.remove(combinatorsToUI, key) local centerpane = game.players[1].gui.left if #centerpane["fum_frame"]["fum_panel"].children == 0 then centerpane["fum_frame"].destroy() end end --When we place a new ui combinator, it's stored. Value is {entity, ui} local function onPlaceEntity(event) if event.created_entity.name == "ui-combinator" then local newUI = createGUI(event.created_entity) local temp = {entity = event.created_entity, ui = newUI} table.insert(combinatorsToUI, temp) --out("Added : ".. tostring(event.created_entity) .. " at : " .. txtpos(event.created_entity.position) ) out("Size : " .. #combinatorsToUI) end end --Entity removed from table when removed from world local function onRemoveEntity(event) if event.entity.name == "ui-combinator" then destroyGui(event.entity) out("Size : " .. #combinatorsToUI) end end --Updates UI based on blocks signals local function updateUICombinator(uicomb) local entity = uicomb.entity local circuit = entity.get_circuit_network(defines.wire_type.red) if not circuit then circuit = entity.get_circuit_network(defines.wire_type.green) end UpdateSignalGuiPanel(uicomb.ui.signals, circuit) end local function onTick() if 0 == game.tick % update_interval then for k, v in pairs(combinatorsToUI) do updateUICombinator(combinatorsToUI[k]) end end end script.on_init(onInit) script.on_configuration_changed(onInit) script.on_load(onLoad) script.on_event(defines.events.on_built_entity, onPlaceEntity) script.on_event(defines.events.on_robot_built_entity, onPlaceEntity) script.on_event(defines.events.on_preplayer_mined_item, onRemoveEntity) script.on_event(defines.events.on_robot_pre_mined, onRemoveEntity) script.on_event(defines.events.on_entity_died, onRemoveEntity) script.on_event(defines.events.on_tick, onTick)
CircuitsUI: Fix removing
CircuitsUI: Fix removing
Lua
mit
Zomis/FactorioMods
9bb0ad04429498a0f3e232e6b9b85addc4b27ccb
worldedit_commands/mark.lua
worldedit_commands/mark.lua
worldedit.marker1 = {} worldedit.marker2 = {} worldedit.marker_region = {} --marks worldedit region position 1 worldedit.mark_pos1 = function(name) local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if pos1 ~= nil then --make area stay loaded local manip = minetest.get_voxel_manip() manip:read_from_map(pos1, pos1) end if worldedit.marker1[name] ~= nil then --marker already exists worldedit.marker1[name]:remove() --remove marker worldedit.marker1[name] = nil end if pos1 ~= nil then --add marker worldedit.marker1[name] = minetest.add_entity(pos1, "worldedit:pos1") if worldedit.marker1[name] ~= nil then worldedit.marker1[name]:get_luaentity().player_name = name end end worldedit.mark_region(name) end --marks worldedit region position 2 worldedit.mark_pos2 = function(name) local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if pos2 ~= nil then --make area stay loaded local manip = minetest.get_voxel_manip() manip:read_from_map(pos2, pos2) end if worldedit.marker2[name] ~= nil then --marker already exists worldedit.marker2[name]:remove() --remove marker worldedit.marker2[name] = nil end if pos2 ~= nil then --add marker worldedit.marker2[name] = minetest.add_entity(pos2, "worldedit:pos2") if worldedit.marker2[name] ~= nil then worldedit.marker2[name]:get_luaentity().player_name = name end end worldedit.mark_region(name) end worldedit.mark_region = function(name) local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if worldedit.marker_region[name] ~= nil then --marker already exists --wip: make the area stay loaded somehow for _, entity in ipairs(worldedit.marker_region[name]) do entity:remove() end worldedit.marker_region[name] = nil end if pos1 ~= nil and pos2 ~= nil then local pos1, pos2 = worldedit.sort_pos(pos1, pos2) local vec = vector.subtract(pos2, pos1) local maxside = math.max(vec.x, math.max(vec.y, vec.z)) local limit = tonumber(minetest.settings:get("active_object_send_range_blocks")) * 16 if maxside > limit * 1.5 then -- The client likely won't be able to see the plane markers as intended anyway, -- thus don't place them and also don't load the area into memory return end local thickness = 0.2 local sizex, sizey, sizez = (1 + pos2.x - pos1.x) / 2, (1 + pos2.y - pos1.y) / 2, (1 + pos2.z - pos1.z) / 2 --make area stay loaded local manip = minetest.get_voxel_manip() manip:read_from_map(pos1, pos2) local markers = {} --XY plane markers for _, z in ipairs({pos1.z - 0.5, pos2.z + 0.5}) do local marker = minetest.add_entity({x=pos1.x + sizex - 0.5, y=pos1.y + sizey - 0.5, z=z}, "worldedit:region_cube") if marker ~= nil then marker:set_properties({ visual_size={x=sizex * 2, y=sizey * 2}, collisionbox = {-sizex, -sizey, -thickness, sizex, sizey, thickness}, }) marker:get_luaentity().player_name = name table.insert(markers, marker) end end --YZ plane markers for _, x in ipairs({pos1.x - 0.5, pos2.x + 0.5}) do local marker = minetest.add_entity({x=x, y=pos1.y + sizey - 0.5, z=pos1.z + sizez - 0.5}, "worldedit:region_cube") if marker ~= nil then marker:set_properties({ visual_size={x=sizez * 2, y=sizey * 2}, collisionbox = {-thickness, -sizey, -sizez, thickness, sizey, sizez}, }) marker:set_yaw(math.pi / 2) marker:get_luaentity().player_name = name table.insert(markers, marker) end end worldedit.marker_region[name] = markers end end minetest.register_entity(":worldedit:pos1", { initial_properties = { visual = "cube", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png"}, collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55}, physical = false, }, on_step = function(self, dtime) if worldedit.marker1[self.player_name] == nil then self.object:remove() end end, on_punch = function(self, hitter) self.object:remove() worldedit.marker1[self.player_name] = nil end, }) minetest.register_entity(":worldedit:pos2", { initial_properties = { visual = "cube", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png"}, collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55}, physical = false, }, on_step = function(self, dtime) if worldedit.marker2[self.player_name] == nil then self.object:remove() end end, on_punch = function(self, hitter) self.object:remove() worldedit.marker2[self.player_name] = nil end, }) minetest.register_entity(":worldedit:region_cube", { initial_properties = { visual = "upright_sprite", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_cube.png"}, visual_size = {x=10, y=10}, physical = false, }, on_step = function(self, dtime) if worldedit.marker_region[self.player_name] == nil then self.object:remove() return end end, on_punch = function(self, hitter) local markers = worldedit.marker_region[self.player_name] if not markers then return end for _, entity in ipairs(markers) do entity:remove() end worldedit.marker_region[self.player_name] = nil end, })
worldedit.marker1 = {} worldedit.marker2 = {} worldedit.marker_region = {} --marks worldedit region position 1 worldedit.mark_pos1 = function(name) local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if pos1 ~= nil then --make area stay loaded local manip = minetest.get_voxel_manip() manip:read_from_map(pos1, pos1) end if worldedit.marker1[name] ~= nil then --marker already exists worldedit.marker1[name]:remove() --remove marker worldedit.marker1[name] = nil end if pos1 ~= nil then --add marker worldedit.marker1[name] = minetest.add_entity(pos1, "worldedit:pos1") if worldedit.marker1[name] ~= nil then worldedit.marker1[name]:get_luaentity().player_name = name end end worldedit.mark_region(name) end --marks worldedit region position 2 worldedit.mark_pos2 = function(name) local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if pos2 ~= nil then --make area stay loaded local manip = minetest.get_voxel_manip() manip:read_from_map(pos2, pos2) end if worldedit.marker2[name] ~= nil then --marker already exists worldedit.marker2[name]:remove() --remove marker worldedit.marker2[name] = nil end if pos2 ~= nil then --add marker worldedit.marker2[name] = minetest.add_entity(pos2, "worldedit:pos2") if worldedit.marker2[name] ~= nil then worldedit.marker2[name]:get_luaentity().player_name = name end end worldedit.mark_region(name) end worldedit.mark_region = function(name) local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name] if worldedit.marker_region[name] ~= nil then --marker already exists --wip: make the area stay loaded somehow for _, entity in ipairs(worldedit.marker_region[name]) do entity:remove() end worldedit.marker_region[name] = nil end if pos1 ~= nil and pos2 ~= nil then local pos1, pos2 = worldedit.sort_pos(pos1, pos2) local vec = vector.subtract(pos2, pos1) local maxside = math.max(vec.x, math.max(vec.y, vec.z)) local limit = tonumber(minetest.settings:get("active_object_send_range_blocks")) * 16 if maxside > limit * 1.5 then -- The client likely won't be able to see the plane markers as intended anyway, -- thus don't place them and also don't load the area into memory return end local thickness = 0.2 local sizex, sizey, sizez = (1 + pos2.x - pos1.x) / 2, (1 + pos2.y - pos1.y) / 2, (1 + pos2.z - pos1.z) / 2 --make area stay loaded local manip = minetest.get_voxel_manip() manip:read_from_map(pos1, pos2) local markers = {} --XY plane markers for _, z in ipairs({pos1.z - 0.5, pos2.z + 0.5}) do local marker = minetest.add_entity({x=pos1.x + sizex - 0.5, y=pos1.y + sizey - 0.5, z=z}, "worldedit:region_cube") if marker ~= nil then marker:set_properties({ visual_size={x=sizex * 2, y=sizey * 2}, collisionbox = {-sizex, -sizey, -thickness, sizex, sizey, thickness}, }) marker:get_luaentity().player_name = name table.insert(markers, marker) end end --YZ plane markers for _, x in ipairs({pos1.x - 0.5, pos2.x + 0.5}) do local marker = minetest.add_entity({x=x, y=pos1.y + sizey - 0.5, z=pos1.z + sizez - 0.5}, "worldedit:region_cube") if marker ~= nil then marker:set_properties({ visual_size={x=sizez * 2, y=sizey * 2}, collisionbox = {-thickness, -sizey, -sizez, thickness, sizey, sizez}, }) marker:set_yaw(math.pi / 2) marker:get_luaentity().player_name = name table.insert(markers, marker) end end worldedit.marker_region[name] = markers end end minetest.register_entity(":worldedit:pos1", { initial_properties = { visual = "cube", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png", "worldedit_pos1.png"}, collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55}, physical = false, }, on_step = function(self, dtime) if worldedit.marker1[self.player_name] == nil then self.object:remove() end end, on_punch = function(self, hitter) self.object:remove() worldedit.marker1[self.player_name] = nil end, }) minetest.register_entity(":worldedit:pos2", { initial_properties = { visual = "cube", visual_size = {x=1.1, y=1.1}, textures = {"worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png", "worldedit_pos2.png"}, collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55}, physical = false, }, on_step = function(self, dtime) if worldedit.marker2[self.player_name] == nil then self.object:remove() end end, on_punch = function(self, hitter) self.object:remove() worldedit.marker2[self.player_name] = nil end, }) minetest.register_entity(":worldedit:region_cube", { initial_properties = { visual = "upright_sprite", textures = {"worldedit_cube.png"}, visual_size = {x=10, y=10}, physical = false, }, on_step = function(self, dtime) if worldedit.marker_region[self.player_name] == nil then self.object:remove() return end end, on_punch = function(self, hitter) local markers = worldedit.marker_region[self.player_name] if not markers then return end for _, entity in ipairs(markers) do entity:remove() end worldedit.marker_region[self.player_name] = nil end, })
Fix double-definition of visual_size in entity def
Fix double-definition of visual_size in entity def
Lua
agpl-3.0
Uberi/Minetest-WorldEdit
6f671cc17fbd9648de6034a0c9239dabb8b12316
nvim/lua/local/packer.lua
nvim/lua/local/packer.lua
-- https://github.com/wbthomason/packer.nvim#notices -- https://github.com/wbthomason/packer.nvim#bootstrapping -- If you want to automatically install and set up packer.nvim on any machine -- you clone your configuration to, add the following snippet -- (which is due to @Iron-E and @khuedoan) -- somewhere in your config before your first usage of packer: local fn = vim.fn local packer_boostrap = false local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim' if fn.empty(fn.glob(install_path)) > 0 then print("Installing Packer...") packer_bootstrap = fn.system( {'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path} ) end local packer = require('packer').startup(function(use) -- Packer can manage itself use 'wbthomason/packer.nvim' -- Lua utils / lib use 'nvim-lua/plenary.nvim' use 'nvim-lua/popup.nvim' -- For writing prose -- Plug 'junegunn/goyo.vim' -- Formatting use 'axelf4/vim-strip-trailing-whitespace' -- -> Python use 'psf/black' use 'brentyi/isort.vim' -- FZF setup use { 'junegunn/fzf', dir = '~/.fzf', run = { './install --all' }, } use 'junegunn/fzf.vim' -- Telescope https://github.com/nvim-telescope/telescope.nvim use {'nvim-telescope/telescope-fzf-native.nvim', run = 'make' } use { 'nvim-telescope/telescope.nvim', requires = { {'nvim-lua/plenary.nvim'}, {'nvim-telescope/telescope-fzf-native.nvim', run = 'make' } } } -- Iconogrophy use 'junegunn/vim-emoji' use 'kyazdani42/nvim-web-devicons' use 'mortepau/codicons.nvim' -- Status line use { 'nvim-lualine/lualine.nvim', requires = {'kyazdani42/nvim-web-devicons', opt = true} } -- Commenters use 'preservim/nerdcommenter' -- NVim Tree -- Install 'kyazdani42/nvim-web-devicons' for file icons use { 'kyazdani42/nvim-tree.lua', requires = 'kyazdani42/nvim-web-devicons', config = function() require'local/nvim_tree' end } -- Unixy commands for vim -- I don't think I've used this since I've started using plugins like nvim-tree, fzf, etc. -- use 'tpope/vim-eunuch' -- Diff stuff use 'sindrets/diffview.nvim' -- Snippets -- use 'honza/vim-snippets' -- From cmp-nvim-ultisnips: -- UltiSnip was auto-removing tab mappings for select mode, -- that leads to we cannot jump through snippet stops -- We have to disable this by set UltiSnipsRemoveSelectModeMappings = 0 (Credit JoseConseco) use({ "SirVer/ultisnips", requires = "honza/vim-snippets", config = function() vim.g.UltiSnipsRemoveSelectModeMappings = 0 end, }) -- Markdown stuff use 'PratikBhusal/vim-grip' use 'ajorgensen/vim-markdown-toc' -- Git use "https://github.com/tpope/vim-fugitive" use { "lewis6991/gitsigns.nvim", requires = { "nvim-lua/plenary.nvim" }, config = function() require("gitsigns").setup() end } use { "rbong/vim-flog", requires = { "https://github.com/tpope/vim-fugitive" }, } -- Theme / Colors use "ishan9299/nvim-solarized-lua" use "folke/lsp-colors.nvim" -- Tab indicator -- use "lukas-reineke/indent-blankline.nvim" -- LSP and completions use "neovim/nvim-lspconfig" use { "nvim-treesitter/nvim-treesitter", run = ":TSUpdate" } use { "tamago324/cmp-zsh", requires = { "Shougo/deol.nvim" }, } -- Lua use { "folke/trouble.nvim", requires = "kyazdani42/nvim-web-devicons", config = function() require("trouble").setup { -- your configuration comes here -- or leave it empty to use the default settings -- refer to the configuration section below } end } -- -> nvim-cmp use { "hrsh7th/nvim-cmp", requires = { -- https://github.com/quangnguyen30192/cmp-nvim-ultisnips "quangnguyen30192/cmp-nvim-ultisnips", "quangnguyen30192/cmp-nvim-tags", "hrsh7th/cmp-nvim-lsp", "hrsh7th/cmp-buffer", "hrsh7th/cmp-path", "hrsh7th/cmp-calc", "hrsh7th/cmp-nvim-lua", "hrsh7th/cmp-look", 'hrsh7th/cmp-cmdline', "ray-x/cmp-treesitter", "f3fora/cmp-spell", "tamago324/cmp-zsh", }, } use { "tzachar/cmp-tabnine", run="./install.sh", requires = "hrsh7th/nvim-cmp" } if packer_bootstrap then require('packer').sync() end end) -- You can configure Neovim to automatically run :PackerCompile -- whenever plugins.lua is updated with an autocommand: vim.cmd([[ augroup packer_user_config autocmd! autocmd BufWritePost plugins.lua source <afile> | PackerCompile augroup end ]]) return packer
-- https://github.com/wbthomason/packer.nvim#notices -- https://github.com/wbthomason/packer.nvim#bootstrapping -- If you want to automatically install and set up packer.nvim on any machine -- you clone your configuration to, add the following snippet -- (which is due to @Iron-E and @khuedoan) -- somewhere in your config before your first usage of packer: local fn = vim.fn local packer_boostrap = false local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim' if fn.empty(fn.glob(install_path)) > 0 then print("Installing Packer...") packer_bootstrap = fn.system( {'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path} ) end local packer = require('packer').startup(function(use) -- Packer can manage itself use 'wbthomason/packer.nvim' -- Lua utils / lib use 'nvim-lua/plenary.nvim' use 'nvim-lua/popup.nvim' -- For writing prose -- Plug 'junegunn/goyo.vim' -- Formatting use 'axelf4/vim-strip-trailing-whitespace' -- -> Python use 'psf/black' use 'brentyi/isort.vim' -- FZF setup use { 'junegunn/fzf', dir = '~/.fzf', run = { './install --all' }, } use 'junegunn/fzf.vim' -- Telescope https://github.com/nvim-telescope/telescope.nvim use {'nvim-telescope/telescope-fzf-native.nvim', run = 'make' } use { 'nvim-telescope/telescope.nvim', requires = { {'nvim-lua/plenary.nvim'}, {'nvim-telescope/telescope-fzf-native.nvim', run = 'make' } } } -- Iconogrophy use 'junegunn/vim-emoji' use 'kyazdani42/nvim-web-devicons' use 'mortepau/codicons.nvim' -- Status line use { 'nvim-lualine/lualine.nvim', requires = {'kyazdani42/nvim-web-devicons', opt = true} } -- Commenters use 'preservim/nerdcommenter' -- NVim Tree -- Install 'kyazdani42/nvim-web-devicons' for file icons use { 'kyazdani42/nvim-tree.lua', requires = 'kyazdani42/nvim-web-devicons', config = function() require'local/nvim_tree' end } -- Unixy commands for vim -- I don't think I've used this since I've started using plugins like nvim-tree, fzf, etc. -- use 'tpope/vim-eunuch' -- Diff stuff use 'sindrets/diffview.nvim' -- Snippets -- use 'honza/vim-snippets' -- From cmp-nvim-ultisnips: -- UltiSnip was auto-removing tab mappings for select mode, -- that leads to we cannot jump through snippet stops -- We have to disable this by set UltiSnipsRemoveSelectModeMappings = 0 (Credit JoseConseco) use({ "SirVer/ultisnips", requires = "honza/vim-snippets", config = function() vim.g.UltiSnipsRemoveSelectModeMappings = 0 end, }) -- Markdown stuff use 'PratikBhusal/vim-grip' use 'ajorgensen/vim-markdown-toc' -- Git use "tpope/vim-fugitive" use { "lewis6991/gitsigns.nvim", requires = { "nvim-lua/plenary.nvim" }, config = function() require("gitsigns").setup() end } use { "rbong/vim-flog", requires = { "tpope/vim-fugitive" }, } -- Theme / Colors use "ishan9299/nvim-solarized-lua" use "folke/lsp-colors.nvim" -- Tab indicator -- use "lukas-reineke/indent-blankline.nvim" -- LSP and completions use "neovim/nvim-lspconfig" use { "nvim-treesitter/nvim-treesitter", run = ":TSUpdate" } use { "tamago324/cmp-zsh", requires = { "Shougo/deol.nvim" }, } -- Lua use { "folke/trouble.nvim", requires = "kyazdani42/nvim-web-devicons", config = function() require("trouble").setup { -- your configuration comes here -- or leave it empty to use the default settings -- refer to the configuration section below } end } -- -> nvim-cmp use { "hrsh7th/nvim-cmp", requires = { -- https://github.com/quangnguyen30192/cmp-nvim-ultisnips "quangnguyen30192/cmp-nvim-ultisnips", "quangnguyen30192/cmp-nvim-tags", "hrsh7th/cmp-nvim-lsp", "hrsh7th/cmp-buffer", "hrsh7th/cmp-path", "hrsh7th/cmp-calc", "hrsh7th/cmp-nvim-lua", "hrsh7th/cmp-look", 'hrsh7th/cmp-cmdline', "ray-x/cmp-treesitter", "f3fora/cmp-spell", "tamago324/cmp-zsh", }, } use { "tzachar/cmp-tabnine", run="./install.sh", requires = "hrsh7th/nvim-cmp" } if packer_bootstrap then require('packer').sync() end end) -- You can configure Neovim to automatically run :PackerCompile -- whenever plugins.lua is updated with an autocommand: vim.cmd([[ augroup packer_user_config autocmd! autocmd BufWritePost plugins.lua source <afile> | PackerCompile augroup end ]]) return packer
Update the url used in packer to install vim-fugitive, this fixes an issue where it wants to remove and re-install fugitive on every run of packer
Update the url used in packer to install vim-fugitive, this fixes an issue where it wants to remove and re-install fugitive on every run of packer
Lua
mit
jeffbuttars/nvim
c98cf3f776ea6d61cec4071647e04b1a0544a50c
game/mapgen.lua
game/mapgen.lua
-- Implementation of map generation. -- The function returned by this library becomes the Map:generate() method. local function in_bounds(map, x, y, w, h) return x >= 0 and y >= 0 and x+w < map.w and y+h < map.h end local opposite = { n='s'; s='n'; e='w'; w='e'; } local function pushDoor(self, door, x, y) table.insert(self._doors, { x = x+door.x; y = y+door.y; dir = opposite[door.dir] }) end local function pullDoor(self) return table.remove(self._doors, 1) end -- Copy a single cell into place, with checks local function copyTerrain(cell, terrain) if not terrain then return end assertf(not cell[1] or (cell[1] == 'Wall' and terrain == 'Wall'), "error placing terrain %s: %s", terrain, cell[1]) cell[1] = terrain end -- Instantiate and place an object from a room's object table local function placeObject(self, obj, ox, oy) if not obj.x then log.debug("Object has no location! %s", repr(obj)) return end local x,y = obj.x+ox,obj.y+oy local ent = self:create 'TestObject' { name = obj.name or obj.type or obj._type or "???"; render = { face = (obj.type or '?'):sub(1,1); }; position = { x = x; y = y; } } if not self[x][y][1] then log.debug("Object %s at (%d,%d) in void!", ent, x, y) ent.render.colour = { 255, 0, 0 } ent.render.style = 'v' end self:placeAt(ent, x, y) end -- Place an entire room into the map, create and place all of its objects, and -- enqueue all of its doors. local function placeRoom(self, room, ox, oy) log.debug("Placing %s (%dx%d) at (%d,%d)", room.name, room.w, room.h, ox, oy) assertf(in_bounds(self, ox, oy, room.w, room.h), "out of bounds room placement: %s (%dx%d) at (%d,%d)", room.name, room.w, room.h, ox, oy) -- Copy the terrain into the map. for x,y,terrain in room:cells(ox,oy) do local cell = self[x][y] cell.name = room.name copyTerrain(cell, terrain) end -- Copy the objects into the map. for _,obj in ipairs(room.contents) do placeObject(self, obj, ox, oy) end -- Push all doors from that room into the queue. for door in room:doors() do pushDoor(self, door, ox, oy) end end -- Fill in a doorway with wall, since we couldn't create a room there. local function fillDoor(map, door) local x,y = door.x,door.y local mx,my = x,y if door.dir == 'n' or door.dir == 's' then x,mx = x-1,x+1 else y,my = y-1,y+1 end for x=x,mx do for y=y,my do local cell = map[x][y] cell[1] = 'Wall'; -- Temporary addition so that places where doors were filled in stand out. -- For debugging the map generator. cell[2] = game.createSingleton('Wall', 'DoorFiller') { render = { face = '░' }; } end end end local function placeDoor(self, door) local segments = {} local x,y = door.x,door.y if door.dir == 'n' or door.dir == 's' then segments[1] = { x = x-1; y = y; open = '╸'; shut = '╼' } segments[2] = { x = x; y = y; open = ' '; shut = '━' } segments[3] = { x = x+1; y = y; open = '╺'; shut = '╾' } else segments[1] = { x = x; y = y-1; open = '╹'; shut = '╽' } segments[2] = { x = x; y = y; open = ' '; shut = '┃' } segments[3] = { x = x; y = y+1; open = '╻'; shut = '╿' } end for _,segment in ipairs(segments) do self[segment.x][segment.y][1] = 'Floor' local door = self:create 'Door' { door = { face_open = segment.open; face_shut = segment.shut; }; position = { x = segment.x; y = segment.y; z = self.depth; } } self[segment.x][segment.y][2] = door end end local function createTerrain(self) for x,y,cell in self:cells() do if cell[1] then assert(type(cell[1]) == 'string', tostring(cell[1])) cell[1] = game.createSingleton(cell[1], 'terrain:'..cell[1]) {} else cell[1] = nil end end end local function isRoomCompatible(self, door, target) local ox = target.x - door.x local oy = target.y - door.y if not in_bounds(self, ox, oy, door.room.w, door.room.h) then return false end for x,y,cell in door.room:cells(ox, oy) do local mapcell = self[x][y] if mapcell[1] and (mapcell[1] ~= cell or mapcell[1] ~= 'Wall') then -- collision with existing terrain return false end end return true end local function placeRoomAtDoor(self, room, door, target_door) -- calculate offsets based on position of target_door local ox,oy = target_door.x - door.x, target_door.y - door.y placeRoom(self, room, ox, oy) placeDoor(self, target_door) end local function findCompatibleRoom(self, target) for i=1,5 do local door = dredmor.randomDoor(target.dir) if isRoomCompatible(self, door, target) then return door.room,door end end end return function(self, w, h, room) self.w, self.h = w,h for x=0,self.w-1 do self[x] = {} for y=0,self.h-1 do self[x][y] = {} end end self._doors = {} -- place the first room in the middle of the map if room then room = dredmor.room(room) else room = dredmor.randomRoom() end local x = (self.w/2 - room.w/2):floor() local y = (self.h/2 - room.h/2):floor() placeRoom(self, room, x, y) for target_door in pullDoor,self do log.debug('checking door %s', repr(target_door):gsub('%s+', '')) -- find a compatible random room local room,door = findCompatibleRoom(self, target_door) if room then placeRoomAtDoor(self, room, door, target_door) elseif not self[target_door.x][target_door.y][2] then fillDoor(self, target_door) end end createTerrain(self) end
-- Implementation of map generation. -- The function returned by this library becomes the Map:generate() method. local function in_bounds(map, x, y, w, h) return x >= 0 and y >= 0 and x+w < map.w and y+h < map.h end local opposite = { n='s'; s='n'; e='w'; w='e'; } local function pushDoor(self, door, x, y) table.insert(self._doors, { x = x+door.x; y = y+door.y; dir = opposite[door.dir] }) end local function pullDoor(self) return table.remove(self._doors, 1) end -- Copy a single cell into place, with checks local function copyTerrain(cell, terrain) if not terrain then return end assertf(not cell[1] or (cell[1] == 'Wall' and terrain == 'Wall'), "error placing terrain %s: %s", terrain, cell[1]) cell[1] = terrain end -- Instantiate and place an object from a room's object table local function placeObject(self, obj, ox, oy) if not obj.x then log.debug("Object has no location! %s", repr(obj)) return end local x,y = obj.x+ox,obj.y+oy local ent = { name = obj.name or obj.type or obj._type or "???"; render = { face = (obj.type or '?'):sub(1,1); }; position = { x = x; y = y; } } if not self[x][y][1] then log.debug("Object %s at (%d,%d) in void!", ent, x, y) ent.render.colour = { 255, 0, 0 } ent.render.style = 'v' end self:placeAt(self:create('TestObject')(ent), x, y) end -- Place an entire room into the map, create and place all of its objects, and -- enqueue all of its doors. local function placeRoom(self, room, ox, oy) log.debug("Placing %s (%dx%d) at (%d,%d)", room.name, room.w, room.h, ox, oy) assertf(in_bounds(self, ox, oy, room.w, room.h), "out of bounds room placement: %s (%dx%d) at (%d,%d)", room.name, room.w, room.h, ox, oy) -- Copy the terrain into the map. for x,y,terrain in room:cells(ox,oy) do local cell = self[x][y] cell.name = room.name copyTerrain(cell, terrain) end -- Copy the objects into the map. for _,obj in ipairs(room.contents) do placeObject(self, obj, ox, oy) end -- Push all doors from that room into the queue. for door in room:doors() do pushDoor(self, door, ox, oy) end end -- Fill in a doorway with wall, since we couldn't create a room there. local function fillDoor(map, door) local x,y = door.x,door.y local mx,my = x,y if door.dir == 'n' or door.dir == 's' then x,mx = x-1,x+1 else y,my = y-1,y+1 end for x=x,mx do for y=y,my do local cell = map[x][y] cell[1] = 'Wall'; -- Temporary addition so that places where doors were filled in stand out. -- For debugging the map generator. cell[2] = game.createSingleton('Wall', 'DoorFiller') { render = { face = '░' }; } end end end local function placeDoor(self, door) local segments = {} local x,y = door.x,door.y if door.dir == 'n' or door.dir == 's' then segments[1] = { x = x-1; y = y; open = '╸'; shut = '╼' } segments[2] = { x = x; y = y; open = ' '; shut = '━' } segments[3] = { x = x+1; y = y; open = '╺'; shut = '╾' } else segments[1] = { x = x; y = y-1; open = '╹'; shut = '╽' } segments[2] = { x = x; y = y; open = ' '; shut = '┃' } segments[3] = { x = x; y = y+1; open = '╻'; shut = '╿' } end for _,segment in ipairs(segments) do self[segment.x][segment.y][1] = 'Floor' local door = self:create 'Door' { door = { face_open = segment.open; face_shut = segment.shut; }; position = { x = segment.x; y = segment.y; z = self.depth; } } self[segment.x][segment.y][2] = door end end local function createTerrain(self) for x,y,cell in self:cells() do if type(cell[1]) == 'string' then cell[1] = game.createSingleton(cell[1], 'terrain:'..cell[1]) {} elseif cell[1] == false then cell[1] = nil end end end local function isRoomCompatible(self, door, target) local ox = target.x - door.x local oy = target.y - door.y if not in_bounds(self, ox, oy, door.room.w, door.room.h) then return false end for x,y,cell in door.room:cells(ox, oy) do local mapcell = self[x][y] if mapcell[1] and (mapcell[1] ~= cell or mapcell[1] ~= 'Wall') then -- collision with existing terrain return false end end return true end local function placeRoomAtDoor(self, room, door, target_door) -- calculate offsets based on position of target_door local ox,oy = target_door.x - door.x, target_door.y - door.y placeRoom(self, room, ox, oy) placeDoor(self, target_door) end local function findCompatibleRoom(self, target) for i=1,5 do local door = dredmor.randomDoor(target.dir) if isRoomCompatible(self, door, target) then return door.room,door end end end return function(self, w, h, room) self.w, self.h = w,h for x=0,self.w-1 do self[x] = {} for y=0,self.h-1 do self[x][y] = {} end end self._doors = {} -- place the first room in the middle of the map if room then room = dredmor.room(room) else room = dredmor.randomRoom() end local x = (self.w/2 - room.w/2):floor() local y = (self.h/2 - room.h/2):floor() placeRoom(self, room, x, y) for target_door in pullDoor,self do -- find a compatible random room local room,door = findCompatibleRoom(self, target_door) if room then placeRoomAtDoor(self, room, door, target_door) elseif not self[target_door.x][target_door.y][2] then fillDoor(self, target_door) end end createTerrain(self) end
Fix a bug in creation of objects-in-void
Fix a bug in creation of objects-in-void
Lua
mit
ToxicFrog/ttymor
688065673c36823b8c285516cfbc951ba4c0f884
lib/Async.lua
lib/Async.lua
--- -- Execute a query with no result required -- -- @param query -- @param params -- @param func -- @param Transaction transaction -- -- @return coroutine -- function MySQL.Async.execute(query, params, func, transaction) local Command = MySQL.Utils.CreateCommand(query, params, transaction) local executeTask = Command.ExecuteNonQueryAsync(); if func ~= nil then clr.Brouznouf.FiveM.Async.ExecuteCallback(executeTask, LogWrapper( ResultCallback(func), Command.Connection.ServerThread, Command.CommandText )) end return MySQL.Utils.CreateCoroutineFromTask(executeTask, LogWrapper( NoTransform, Command.Connection.ServerThread, Command.CommandText )) end --- -- Execute a query and fetch all results in an async way -- -- @param query -- @param params -- @param func -- @param Transaction transaction -- -- @return coroutine -- function MySQL.Async.fetchAll(query, params, func, transaction) local Command = MySQL.Utils.CreateCommand(query, params, transaction) local executeReaderTask = Command.ExecuteReaderAsync(); if func ~= nil then clr.Brouznouf.FiveM.Async.ExecuteReaderCallback(executeReaderTask, LogWrapper( ResultCallback(func), Command.Connection.ServerThread, Command.CommandText )) end return MySQL.Utils.CreateCoroutineFromTask(executeReaderTask, LogWrapper( MySQL.Utils.ConvertResultToTable, Command.Connection.ServerThread, Command.CommandText )) end --- -- Execute a query and fetch the first column of the first row -- Useful for count function by example -- -- @param query -- @param params -- @param func -- @param Transaction transaction -- -- @return coroutine -- function MySQL.Async.fetchScalar(query, params, func, transaction) local Command = MySQL.Utils.CreateCommand(query, params, transaction) local executeScalarTask = Command.ExecuteScalarAsync(); if func ~= nil then clr.Brouznouf.FiveM.Async.ExecuteScalarCallback(executeScalarTask, LogWrapper( ResultCallback(func), Command.Connection.ServerThread, Command.CommandText )) end return MySQL.Utils.CreateCoroutineFromTask(executeScalarTask, LogWrapper( NoTransform, Command.Connection.ServerThread, Command.CommandText )) end --- -- Create a transaction -- -- @param function func -- -- @return coroutine -- function MySQL.Async.beginTransaction(func) local connection = MySQL:createConnection(); local beginTransactionTask = connection.BeginTransactionAsync(clr.System.Threading.CancellationToken.None); if func ~= nil then clr.Brouznouf.FiveM.Async.BeginTransactionCallback(beginTransactionTask, LogWrapper( NoResultCallback(func), connection.ServerThread, 'BEGIN TRANSACTION' )) end return MySQL.Utils.CreateCoroutineFromTask(beginTransactionTask, LogWrapper( NoTransform, connection.ServerThread, 'BEGIN TRANSACTION' )) end --- -- Commit the transaction -- -- @param Transaction transaction -- @param function func -- function MySQL.Async.commitTransaction(transaction, func) local commitTransactionTrask = transaction.CommitAsync(clr.System.Threading.CancellationToken.None); if func ~= nil then clr.Brouznouf.FiveM.Async.CommitTransactionCallback(commitTransactionTrask, LogWrapper( NoResultCallback(func), transaction.Connection.ServerThread, 'COMMIT' )) end return MySQL.Utils.CreateCoroutineFromTask(commitTransactionTrask, LogWrapper( NoTransform, transaction.Connection.ServerThread, 'COMMIT' )) end --- -- Rollback the transaction -- -- @param Transaction transaction -- @param function func -- function MySQL.Async.rollbackTransaction(transaction, func) local rollbackTransactionTask = transaction.RollbackAsync(clr.System.Threading.CancellationToken.None); if func ~= nil then clr.Brouznouf.FiveM.Async.RollbackTransactionCallback(rollbackTransactionTask, LogWrapper( NoResultCallback(func), transaction.Connection.ServerThread, 'ROLLBACK' )) end return MySQL.Utils.CreateCoroutineFromTask(rollbackTransactionTask, LogWrapper( NoTransform, transaction.Connection.ServerThread, 'ROLLBACK' )) end function NoTransform(Result) return Result end function ResultCallback(next) return function(Result, Error) if Error ~= nil then Logger:Error(Error.ToString()) else next(Result) end end end function NoResultCallback(next) return function(Result, Error) if Error ~= nil then Logger:Error(Error.ToString()) else next() end end end function LogWrapper(next, ServerThread, Message) local Stopwatch = clr.System.Diagnostics.Stopwatch() Stopwatch.Start() return function (Result, Error) Stopwatch.Stop() Logger:Info(string.format('[%d][%dms] %s', ServerThread, Stopwatch.ElapsedMilliseconds, Message)) return next(Result, Error) end end
--- -- Execute a query with no result required -- -- @param query -- @param params -- @param func -- @param Transaction transaction -- -- @return coroutine -- function MySQL.Async.execute(query, params, func, transaction) local Command = MySQL.Utils.CreateCommand(query, params, transaction) local executeTask = Command.ExecuteNonQueryAsync(); if func ~= nil then clr.Brouznouf.FiveM.Async.ExecuteCallback(executeTask, LogWrapper( ResultCallback(func), Command.Connection.ServerThread, Command.CommandText )) end return MySQL.Utils.CreateCoroutineFromTask(executeTask, LogWrapper( NoTransform, Command.Connection.ServerThread, Command.CommandText )) end --- -- Execute a query and fetch all results in an async way -- -- @param query -- @param params -- @param func -- @param Transaction transaction -- -- @return coroutine -- function MySQL.Async.fetchAll(query, params, func, transaction) local Command = MySQL.Utils.CreateCommand(query, params, transaction) local executeReaderTask = Command.ExecuteReaderAsync(); if func ~= nil then clr.Brouznouf.FiveM.Async.ExecuteReaderCallback(executeReaderTask, LogWrapper( ResultCallback(function (Result) return func(MySQL.Utils.ConvertResultToTable(Result)) end), Command.Connection.ServerThread, Command.CommandText )) end return MySQL.Utils.CreateCoroutineFromTask(executeReaderTask, LogWrapper( MySQL.Utils.ConvertResultToTable, Command.Connection.ServerThread, Command.CommandText )) end --- -- Execute a query and fetch the first column of the first row -- Useful for count function by example -- -- @param query -- @param params -- @param func -- @param Transaction transaction -- -- @return coroutine -- function MySQL.Async.fetchScalar(query, params, func, transaction) local Command = MySQL.Utils.CreateCommand(query, params, transaction) local executeScalarTask = Command.ExecuteScalarAsync(); if func ~= nil then clr.Brouznouf.FiveM.Async.ExecuteScalarCallback(executeScalarTask, LogWrapper( ResultCallback(func), Command.Connection.ServerThread, Command.CommandText )) end return MySQL.Utils.CreateCoroutineFromTask(executeScalarTask, LogWrapper( NoTransform, Command.Connection.ServerThread, Command.CommandText )) end --- -- Create a transaction -- -- @param function func -- -- @return coroutine -- function MySQL.Async.beginTransaction(func) local connection = MySQL:createConnection(); local beginTransactionTask = connection.BeginTransactionAsync(clr.System.Threading.CancellationToken.None); if func ~= nil then clr.Brouznouf.FiveM.Async.BeginTransactionCallback(beginTransactionTask, LogWrapper( NoResultCallback(func), connection.ServerThread, 'BEGIN TRANSACTION' )) end return MySQL.Utils.CreateCoroutineFromTask(beginTransactionTask, LogWrapper( NoTransform, connection.ServerThread, 'BEGIN TRANSACTION' )) end --- -- Commit the transaction -- -- @param Transaction transaction -- @param function func -- function MySQL.Async.commitTransaction(transaction, func) local commitTransactionTrask = transaction.CommitAsync(clr.System.Threading.CancellationToken.None); if func ~= nil then clr.Brouznouf.FiveM.Async.CommitTransactionCallback(commitTransactionTrask, LogWrapper( NoResultCallback(func), transaction.Connection.ServerThread, 'COMMIT' )) end return MySQL.Utils.CreateCoroutineFromTask(commitTransactionTrask, LogWrapper( NoTransform, transaction.Connection.ServerThread, 'COMMIT' )) end --- -- Rollback the transaction -- -- @param Transaction transaction -- @param function func -- function MySQL.Async.rollbackTransaction(transaction, func) local rollbackTransactionTask = transaction.RollbackAsync(clr.System.Threading.CancellationToken.None); if func ~= nil then clr.Brouznouf.FiveM.Async.RollbackTransactionCallback(rollbackTransactionTask, LogWrapper( NoResultCallback(func), transaction.Connection.ServerThread, 'ROLLBACK' )) end return MySQL.Utils.CreateCoroutineFromTask(rollbackTransactionTask, LogWrapper( NoTransform, transaction.Connection.ServerThread, 'ROLLBACK' )) end function NoTransform(Result) return Result end function ResultCallback(next) return function(Result, Error) if Error ~= nil then Logger:Error(Error.ToString()) else next(Result) end end end function NoResultCallback(next) return function(Result, Error) if Error ~= nil then Logger:Error(Error.ToString()) else next() end end end function LogWrapper(next, ServerThread, Message) local Stopwatch = clr.System.Diagnostics.Stopwatch() Stopwatch.Start() return function (Result, Error) Stopwatch.Stop() Logger:Info(string.format('[%d][%dms] %s', ServerThread, Stopwatch.ElapsedMilliseconds, Message)) return next(Result, Error) end end
Fix fetchall result transform for callback
Fix fetchall result transform for callback
Lua
mit
brouznouf/fivem-mysql-async,brouznouf/fivem-mysql-async,brouznouf/fivem-mysql-async
4bdef6885b5ff5f86b52c074c9a9d453a68d6fc0
src/plugins/lua/phishing.lua
src/plugins/lua/phishing.lua
--[[ Copyright (c) 2011-2015, Vsevolod Stakhov <vsevolod@highsecure.ru> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- -- Phishing detection interface for selecting phished urls and inserting corresponding symbol -- -- local symbol = 'PHISHED_URL' local domains = nil local strict_domains = {} local redirector_domains = {} local rspamd_logger = require "rspamd_logger" local util = require "rspamd_util" local opts = rspamd_config:get_all_opt('phishing') local function phishing_cb(task) local urls = task:get_urls() if urls then for _,url in ipairs(urls) do if url:is_phished() then local found = false local purl = url:get_phished() local tld = url:get_tld() local ptld = purl:get_tld() if not ptld or not tld then return end local weight = 1.0 local dist = util.levenshtein_distance(tld, ptld) dist = 2 * dist / (#tld + #ptld) if dist > 0.3 and dist <= 1.0 then -- Use distance to penalize the total weight weight = util.tanh(3 * (1 - dist + 0.1)) end rspamd_logger.debugx(task, "distance: %1 -> %2: %3", tld, ptld, dist) if #redirector_domains > 0 then for _,rule in ipairs(redirector_domains) do if rule['map']:get_key(url:get_tld()) then task:insert_result(rule['symbol'], weight, ptld .. '->' .. tld) found = true end end end if not found and #strict_domains > 0 then for _,rule in ipairs(strict_domains) do if rule['map']:get_key(ptld) then task:insert_result(rule['symbol'], 1.0, ptld .. '->' .. tld) found = true end end end if not found then if domains then if domains:get_key(ptld) then task:insert_result(symbol, weight, ptld .. '->' .. tld) end else task:insert_result(symbol, weight, ptld .. '->' .. tld) end end end end end end local function phishing_map(mapname, phishmap) if opts[mapname] then local xd = {} if type(opts[mapname]) == 'table' then xd = opts[mapname] else xd[1] = opts[mapname] end for _,d in ipairs(xd) do local s, _ = string.find(d, ':[^:]+$') if s then local sym = string.sub(d, s + 1, -1) local map = string.sub(d, 1, s - 1) rspamd_config:register_virtual_symbol(sym, 1, id) local rmap = rspamd_config:add_hash_map (map, 'Phishing ' .. mapname .. ' map') if rmap then local rule = {symbol = sym, map = rmap} table.insert(phishmap, rule) else rspamd_logger.infox(rspamd_config, 'cannot add map: ' .. map .. ' for symbol: ' .. sym) end else rspamd_logger.infox(rspamd_config, mapname .. ' option must be in format <map>:<symbol>') end end end end if opts then if opts['symbol'] then symbol = opts['symbol'] -- Register symbol's callback rspamd_config:register_symbol({ name = symbol, callback = phishing_cb }) end if opts['domains'] and type(opt['domains']) == 'string' then domains = rspamd_config:add_hash_map (opts['domains']) end phishing_map('strict_domains', strict_domains) phishing_map('redirector_domains', redirector_domains) end
--[[ Copyright (c) 2011-2015, Vsevolod Stakhov <vsevolod@highsecure.ru> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- -- Phishing detection interface for selecting phished urls and inserting corresponding symbol -- -- local symbol = 'PHISHED_URL' local domains = nil local strict_domains = {} local redirector_domains = {} local rspamd_logger = require "rspamd_logger" local util = require "rspamd_util" local opts = rspamd_config:get_all_opt('phishing') local function phishing_cb(task) local urls = task:get_urls() if urls then for _,url in ipairs(urls) do if url:is_phished() and not url:is_redirected() then local found = false local purl = url:get_phished() local tld = url:get_tld() local ptld = purl:get_tld() if not ptld or not tld then return end local weight = 1.0 local dist = util.levenshtein_distance(tld, ptld, 2) dist = 2 * dist / (#tld + #ptld) if dist > 0.3 and dist <= 1.0 then -- Use distance to penalize the total weight weight = util.tanh(3 * (1 - dist + 0.1)) end rspamd_logger.debugx(task, "distance: %1 -> %2: %3", tld, ptld, dist) if #redirector_domains > 0 then for _,rule in ipairs(redirector_domains) do if rule['map']:get_key(url:get_tld()) then task:insert_result(rule['symbol'], weight, ptld .. '->' .. tld) found = true end end end if not found and #strict_domains > 0 then for _,rule in ipairs(strict_domains) do if rule['map']:get_key(ptld) then task:insert_result(rule['symbol'], 1.0, ptld .. '->' .. tld) found = true end end end if not found then if domains then if domains:get_key(ptld) then task:insert_result(symbol, weight, ptld .. '->' .. tld) end else task:insert_result(symbol, weight, ptld .. '->' .. tld) end end end end end end local function phishing_map(mapname, phishmap) if opts[mapname] then local xd = {} if type(opts[mapname]) == 'table' then xd = opts[mapname] else xd[1] = opts[mapname] end for _,d in ipairs(xd) do local s, _ = string.find(d, ':[^:]+$') if s then local sym = string.sub(d, s + 1, -1) local map = string.sub(d, 1, s - 1) rspamd_config:register_virtual_symbol(sym, 1, id) local rmap = rspamd_config:add_hash_map (map, 'Phishing ' .. mapname .. ' map') if rmap then local rule = {symbol = sym, map = rmap} table.insert(phishmap, rule) else rspamd_logger.infox(rspamd_config, 'cannot add map: ' .. map .. ' for symbol: ' .. sym) end else rspamd_logger.infox(rspamd_config, mapname .. ' option must be in format <map>:<symbol>') end end end end if opts then if opts['symbol'] then symbol = opts['symbol'] -- Register symbol's callback rspamd_config:register_symbol({ name = symbol, callback = phishing_cb }) end if opts['domains'] and type(opt['domains']) == 'string' then domains = rspamd_config:add_hash_map (opts['domains']) end phishing_map('strict_domains', strict_domains) phishing_map('redirector_domains', redirector_domains) end
[Feature] Improve phishing plugin
[Feature] Improve phishing plugin - Ignore redirected URLs - Fix levenshtein distance calculations
Lua
bsd-2-clause
andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd
6b73c1d4e673b74db6b137e125dd7142084eb198
orange/utils/headers.lua
orange/utils/headers.lua
-- -- Created by IntelliJ IDEA. -- User: soul11201 <soul11201@gmail.com> -- Date: 2017/4/26 -- Time: 20:50 -- To change this template use File | Settings | File Templates. -- local handle_util = require("orange.utils.handle") local extractor_util = require("orange.utils.extractor") local _M = {} local function set_header(k,v,overide) local override = overide or false end function _M:set_headers(rule) local extractor,headers_config= rule.extractor,rule.headers if not headers_config or type(headers_config) ~= 'table' then return end local variables = extractor_util.extract_variables(extractor) local req_headers = ngx.req.get_headers(); for _, v in pairs(headers_config) do -- 不存在 || 存在且覆蓋 ngx.log(ngx.ERR,v.name,v.value); if not req_headers[v.name] or v.override == '1' then if v.type == "normal" then ngx.req.set_header(v.name,v.value) ngx.log(ngx.INFO,'[plug header][normal] add headers [',v.name,":",v.value,']') elseif v.type == "extraction" then local value = handle_util.build_uri(extractor.type, v.value, variables) ngx.req.set_header(v.name,value) ngx.log(ngx.INFO,'[plug header][normal] add headers [',v.name,":",value,']') end end end end return _M
-- -- Created by IntelliJ IDEA. -- User: soul11201 <soul11201@gmail.com> -- Date: 2017/4/26 -- Time: 20:50 -- To change this template use File | Settings | File Templates. -- local handle_util = require("orange.utils.handle") local extractor_util = require("orange.utils.extractor") local _M = {} local function set_header(k,v,overide) local override = overide or false end function _M:set_headers(rule) local extractor,headers_config= rule.extractor,rule.headers if not headers_config or type(headers_config) ~= 'table' then return end local variables = extractor_util.extract_variables(extractor) local req_headers = ngx.req.get_headers(); for _, v in pairs(headers_config) do -- 不存在 || 存在且覆蓋 if not req_headers[v.name] or v.override == '1' then if v.type == "normal" then ngx.req.set_header(v.name,v.value) ngx.log(ngx.INFO,'[plug header][normal] add headers [',v.name,":",v.value,']') elseif v.type == "extraction" then local value = handle_util.build_uri(extractor.type, v.value, variables) ngx.req.set_header(v.name,value) ngx.log(ngx.INFO,'[plug header][expression] add headers [',v.name,":",value,']') end end end end return _M
refactor: headers.lua del log && fix info
refactor: headers.lua del log && fix info
Lua
mit
thisverygoodhhhh/orange,thisverygoodhhhh/orange,thisverygoodhhhh/orange
4aa3b704739e3398402fbbef1216ae588ff9be2e
src/plugins/lua/received_rbl.lua
src/plugins/lua/received_rbl.lua
-- This plugin is designed for testing received headers via rbl -- Configuration: -- .module 'received_rbl' { -- rbl = "insecure-bl.rambler.ru"; -- rbl = "xbl.spamhaus.org"; -- symbol = "RECEIVED_RBL"; -- }; local symbol = 'RECEIVED_RBL' local rbls = {} function dns_cb(task, to_resolve, results, err) if results then local _,_,o4,o3,o2,o1,in_rbl = string.find(to_resolve, '(%d+)%.(%d+)%.(%d+)%.(%d+)%.(.+)') local ip = o1 .. '.' .. o2 .. '.' .. o3 .. '.' .. o4 -- Find incoming rbl in rbls list for _,rbl in ipairs(rbls) do if rbl == in_rbl then task:insert_result(symbol, 1, rbl .. ': ' .. ip) else local s, _ = string.find(rbl, in_rbl) if s then s, _ = string.find(rbl, ':') if s then task:insert_result(string.sub(rbl, s + 1, -1), 1, ip) else task:insert_result(symbol, 1, rbl .. ': ' .. ip) end end end end end end function received_cb (task) local recvh = task:get_received_headers() for _,rh in ipairs(recvh) do for k,v in pairs(rh) do if k == 'real_ip' then local _,_,o1,o2,o3,o4 = string.find(v, '(%d+)%.(%d+)%.(%d+)%.(%d+)') for _,rbl in ipairs(rbls) do local rbl_str = '' local rb_s,_ = string.find(rbl, ':') if rb_s then -- We have rbl in form some_rbl:SYMBOL, so get first part local actual_rbl = string.sub(rbl, 1, rb_s - 1) rbl_str = o4 .. '.' .. o3 .. '.' .. o2 .. '.' .. o1 .. '.' .. actual_rbl else rbl_str = o4 .. '.' .. o3 .. '.' .. o2 .. '.' .. o1 .. '.' .. rbl end task:resolve_dns_a(rbl_str, 'dns_cb') end end end end end -- Registration if type(rspamd_config.get_api_version) ~= 'nil' then if rspamd_config:get_api_version() >= 1 then rspamd_config:register_module_option('received_rbl', 'symbol', 'string') rspamd_config:register_module_option('received_rbl', 'rbl', 'string') end end -- Configuration local opts = rspamd_config:get_all_opt('received_rbl') if opts then if opts['symbol'] then symbol = opts['symbol'] if opts['rbl'] then rbls = opts['rbl'] end for _,rbl in ipairs(rbls) do local s, _ = string.find(rbl, ':') if s then if type(rspamd_config.get_api_version) ~= 'nil' then rspamd_config:register_virtual_symbol(string.sub(rbl, s + 1, -1), 1) end end end -- Register symbol's callback rspamd_config:register_symbol(symbol, 1.0, 'received_cb') end -- If no symbol defined, do not register this module end
-- This plugin is designed for testing received headers via rbl -- Configuration: -- .module 'received_rbl' { -- rbl = "insecure-bl.rambler.ru"; -- rbl = "xbl.spamhaus.org"; -- symbol = "RECEIVED_RBL"; -- }; local symbol = 'RECEIVED_RBL' local rbls = {} function dns_cb(task, to_resolve, results, err) if results then local _,_,o4,o3,o2,o1,in_rbl = string.find(to_resolve, '(%d+)%.(%d+)%.(%d+)%.(%d+)%.(.+)') local ip = o1 .. '.' .. o2 .. '.' .. o3 .. '.' .. o4 -- Find incoming rbl in rbls list for _,rbl in ipairs(rbls) do if rbl == in_rbl then task:insert_result(symbol, 1, rbl .. ': ' .. ip) else local s, _ = string.find(rbl, in_rbl) if s then s, _ = string.find(rbl, ':') if s then task:insert_result(string.sub(rbl, s + 1, -1), 1, ip) else task:insert_result(symbol, 1, rbl .. ': ' .. ip) end end end end end end function received_cb (task) local recvh = task:get_received_headers() for _,rh in ipairs(recvh) do for k,v in pairs(rh) do if k == 'real_ip' then local _,_,o1,o2,o3,o4 = string.find(v, '(%d+)%.(%d+)%.(%d+)%.(%d+)') for _,rbl in ipairs(rbls) do local rbl_str = '' local rb_s,_ = string.find(rbl, ':') if rb_s then -- We have rbl in form some_rbl:SYMBOL, so get first part local actual_rbl = string.sub(rbl, 1, rb_s - 1) rbl_str = o4 .. '.' .. o3 .. '.' .. o2 .. '.' .. o1 .. '.' .. actual_rbl else rbl_str = o4 .. '.' .. o3 .. '.' .. o2 .. '.' .. o1 .. '.' .. rbl end task:resolve_dns_a(rbl_str, 'dns_cb') end end end end end -- Registration if type(rspamd_config.get_api_version) ~= 'nil' then if rspamd_config:get_api_version() >= 1 then rspamd_config:register_module_option('received_rbl', 'symbol', 'string') rspamd_config:register_module_option('received_rbl', 'rbl', 'string') end end -- Configuration local opts = rspamd_config:get_all_opt('received_rbl') if opts then if opts['symbol'] then symbol = opts['symbol'] if opts['rbl'] then if type(opts['rbl']) == 'table' then rbls = opts['rbl'] else rbls[1] = opts['rbl'] end end for _,rbl in ipairs(rbls) do local s, _ = string.find(rbl, ':') if s then if type(rspamd_config.get_api_version) ~= 'nil' then rspamd_config:register_virtual_symbol(string.sub(rbl, s + 1, -1), 1) end end end -- Register symbol's callback rspamd_config:register_symbol(symbol, 1.0, 'received_cb') end -- If no symbol defined, do not register this module end
Fix configuration of received_rbl module.
Fix configuration of received_rbl module.
Lua
bsd-2-clause
andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,awhitesong/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,amohanta/rspamd,AlexeySa/rspamd,minaevmike/rspamd,dark-al/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,amohanta/rspamd,amohanta/rspamd,awhitesong/rspamd,AlexeySa/rspamd,awhitesong/rspamd,minaevmike/rspamd,andrejzverev/rspamd,amohanta/rspamd,dark-al/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,dark-al/rspamd,awhitesong/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,minaevmike/rspamd,amohanta/rspamd,dark-al/rspamd,dark-al/rspamd
1259877163f90dfe7f37adac44eeeb5f377dc1da
tests/AceDB-3.0-defaults.lua
tests/AceDB-3.0-defaults.lua
dofile("wow_api.lua") dofile("LibStub.lua") dofile("../CallbackHandler-1.0/CallbackHandler-1.0.lua") dofile("../AceDB-3.0/AceDB-3.0.lua") dofile("serialize.lua") -- Test the defaults system do local defaults = { profile = { singleEntry = "singleEntry", tableEntry = { tableDefault = "tableDefault", }, starTest = { ["*"] = { starDefault = "starDefault", }, sibling = { siblingDefault = "siblingDefault", }, siblingDeriv = { starDefault = "not-so-starDefault", }, }, doubleStarTest = { ["**"] = { doubleStarDefault = "doubleStarDefault", }, sibling = { siblingDefault = "siblingDefault", }, siblingDeriv = { doubleStarDefault = "overruledDefault", } }, starTest2 = { ["*"] = "fun", sibling = "notfun", } }, } local db = LibStub("AceDB-3.0"):New("MyDB", defaults) assert(db.profile.singleEntry == "singleEntry") assert(db.profile.tableEntry.tableDefault == "tableDefault") assert(db.profile.starTest.randomkey.starDefault == "starDefault") assert(db.profile.starTest.sibling.siblingDefault == "siblingDefault") assert(db.profile.starTest.sibling.starDefault == nil) assert(db.profile.doubleStarTest.randomkey.doubleStarDefault == "doubleStarDefault") assert(db.profile.doubleStarTest.sibling.siblingDefault == "siblingDefault") assert(db.profile.doubleStarTest.sibling.doubleStarDefault == "doubleStarDefault") assert(db.profile.doubleStarTest.siblingDeriv.doubleStarDefault == "overruledDefault") assert(db.profile.starTest2.randomkey == "fun") assert(db.profile.starTest2.sibling == "notfun") db.profile.doubleStarTest.siblingDeriv.doubleStarDefault = "doubleStarDefault" db.profile.starTest2.randomkey = "notfun" db.profile.starTest2.randomkey2 = "fun" db.profile.starTest2.sibling = "fun" WoWAPI_FireEvent("PLAYER_LOGOUT") assert(db.profile.singleEntry == nil) assert(db.profile.tableEntry == nil) assert(db.profile.starTest.randomkey.starDefault == nil) assert(db.profile.starTest.sibling == nil) assert(db.profile.doubleStarTest.randomkey.doubleStarDefault == nil) assert(db.profile.doubleStarTest.siblingDeriv.doubleStarDefault == "doubleStarDefault") assert(db.profile.starTest2.randomkey == "notfun") assert(db.profile.starTest2.randomkey2 == nil) assert(db.profile.starTest2.sibling == "fun") end do local AceDB = LibStub("AceDB-3.0") local defaultTest = { profile = { units = { ["**"] = { test = 2 }, ["player"] = { } } } } local bugdb = { ["profileKeys"] = { ["player - Realm Name"] = "player - Realm Name", }, ["profiles"] = { ["player - Realm Name"] = { ["units"] = { ["player"] = { }, ["pet"] = { }, ["focus"] = { }, }, }, }, } local data = LibStub("AceDB-3.0"):New(bugdb, defaultTest) assert(data.profile.units["player"].test == 2) assert(data.profile.units["pet"].test == 2) assert(data.profile.units["focus"].test == 2) end do local AceDB = LibStub("AceDB-3.0") local defaultTest = { profile = { units = { ["*"] = { test = 2 }, ["player"] = { } } } } local bugdb = { ["profileKeys"] = { ["player - Realm Name"] = "player - Realm Name", }, ["profiles"] = { ["player - Realm Name"] = { ["units"] = { ["player"] = { }, ["pet"] = { }, }, }, }, } local data = LibStub("AceDB-3.0"):New(bugdb, defaultTest) assert(data.profile.units["player"].test == nil) assert(data.profile.units["pet"].test == 2) assert(data.profile.units["focus"].test == 2) end
dofile("wow_api.lua") dofile("LibStub.lua") dofile("../CallbackHandler-1.0/CallbackHandler-1.0.lua") dofile("../AceDB-3.0/AceDB-3.0.lua") dofile("serialize.lua") -- Test the defaults system do local defaults = { profile = { singleEntry = "singleEntry", tableEntry = { tableDefault = "tableDefault", }, starTest = { ["*"] = { starDefault = "starDefault", }, sibling = { siblingDefault = "siblingDefault", }, siblingDeriv = { starDefault = "not-so-starDefault", }, }, doubleStarTest = { ["**"] = { doubleStarDefault = "doubleStarDefault", }, sibling = { siblingDefault = "siblingDefault", }, siblingDeriv = { doubleStarDefault = "overruledDefault", } }, starTest2 = { ["*"] = "fun", sibling = "notfun", } }, } local db = LibStub("AceDB-3.0"):New("MyDB", defaults) assert(db.profile.singleEntry == "singleEntry") assert(db.profile.tableEntry.tableDefault == "tableDefault") assert(db.profile.starTest.randomkey.starDefault == "starDefault") assert(db.profile.starTest.sibling.siblingDefault == "siblingDefault") assert(db.profile.starTest.sibling.starDefault == nil) assert(db.profile.doubleStarTest.randomkey.doubleStarDefault == "doubleStarDefault") assert(db.profile.doubleStarTest.sibling.siblingDefault == "siblingDefault") assert(db.profile.doubleStarTest.sibling.doubleStarDefault == "doubleStarDefault") assert(db.profile.doubleStarTest.siblingDeriv.doubleStarDefault == "overruledDefault") assert(db.profile.starTest2.randomkey == "fun") assert(db.profile.starTest2.sibling == "notfun") db.profile.doubleStarTest.siblingDeriv.doubleStarDefault = "doubleStarDefault" db.profile.starTest2.randomkey = "notfun" db.profile.starTest2.randomkey2 = "fun" db.profile.starTest2.sibling = "fun" WoWAPI_FireEvent("PLAYER_LOGOUT") assert(db.profile.singleEntry == nil) assert(db.profile.tableEntry == nil) assert(db.profile.starTest.randomkey.starDefault == nil) assert(db.profile.starTest.sibling == nil) assert(db.profile.doubleStarTest.randomkey.doubleStarDefault == nil) assert(db.profile.doubleStarTest.siblingDeriv.doubleStarDefault == "doubleStarDefault") assert(db.profile.starTest2.randomkey == "notfun") assert(db.profile.starTest2.randomkey2 == nil) assert(db.profile.starTest2.sibling == "fun") end do local defaultTest = { profile = { units = { ["**"] = { test = 2 }, ["player"] = { } } } } local bugdb = { ["profileKeys"] = { ["player - Realm Name"] = "player - Realm Name", }, ["profiles"] = { ["player - Realm Name"] = { ["units"] = { ["player"] = { }, ["pet"] = { }, ["focus"] = { }, }, }, }, } local data = LibStub("AceDB-3.0"):New(bugdb, defaultTest) assert(data.profile.units["player"].test == 2) assert(data.profile.units["pet"].test == 2) assert(data.profile.units["focus"].test == 2) end do local defaultTest = { profile = { units = { ["*"] = { test = 2 }, ["player"] = { } } } } local bugdb = { ["profileKeys"] = { ["player - Realm Name"] = "player - Realm Name", }, ["profiles"] = { ["player - Realm Name"] = { ["units"] = { ["player"] = { }, ["pet"] = { }, }, }, }, } local data = LibStub("AceDB-3.0"):New(bugdb, defaultTest) assert(data.profile.units["player"].test == nil) assert(data.profile.units["pet"].test == 2) assert(data.profile.units["focus"].test == 2) end
Ace3 - fix some tests
Ace3 - fix some tests git-svn-id: 00c2b8bc9b083c53e126de03a83516ee6a3b87d9@275 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
bb5c910b85023842518a06b0eb0439f7b8418858
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(Colors.RGB(255,0,0)) addColor(Colors.RGB(0,255,0)) addColor(Colors.RGB(0,0,255)) addColor(Colors.RGB(255,255,0)) addColor(Colors.RGB(0,255,255)) addColor(Colors.RGB(255,0,255)) addColor(Colors.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 local x = (point.x * scale) - (toolSize) local y = (point.y * scale) - (toolSize) if #drl_tool_colors < tonumber(point.tool.index) then drl_g_drawArc(x, y, toolSize, Colors.RGB(255,255,255)) else drl_g_drawArc(x, y, toolSize, drl_tool_colors[point.tool.index]) end drl_g_drawLine(lastX, lastY, x, y, Colors.RGB(255,255,255)) lastX = x lastY = y 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 = Sys.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 = Sys.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 local x = tonumber(point.x) local y = tonumber(point.y) if x < 100 then x = "0" .. x end if y < 100 then y = "0" .. y end drl_writeLine("X" .. x .. "Y" .. 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) 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, rawFileName, fileEnding) fileName = rawFileName .. "." .. fileEnding drl_lines = {} drl_tools = {} drl_points = {} last = {} last.x = 0 last.y = 0 currentTool = nil multForMinor = 2 drl_fileName = fileName local tbl = string.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() else drl_frame_setVisible(true) drl_frame_update() end end Sys.RegisterConverter("drl", "^[dD][rR][lL]$", "txt")
drl_lines = {} drl_tool_colors = {} function addColor(rgb) drl_tool_colors[#drl_tool_colors + 1] = rgb end addColor(Colors.RGB(255,0,0)) addColor(Colors.RGB(0,255,0)) addColor(Colors.RGB(0,0,255)) addColor(Colors.RGB(255,255,0)) addColor(Colors.RGB(0,255,255)) addColor(Colors.RGB(255,0,255)) addColor(Colors.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 local x = (point.x * scale) - (toolSize) local y = (point.y * scale) - (toolSize) if #drl_tool_colors < tonumber(point.tool.index) then drl_g_drawArc(x, y, toolSize, Colors.RGB(255,255,255)) else drl_g_drawArc(x, y, toolSize, drl_tool_colors[point.tool.index]) end drl_g_drawLine(lastX, lastY, x, y, Colors.RGB(255,255,255)) lastX = x lastY = y 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 = Sys.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 = Sys.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 local x = tonumber(point.x) local y = tonumber(point.y) if x < 100 then x = "0" .. x end if y < 100 then y = "0" .. y end x = "00" .. x y = "00" .. y drl_writeLine("X" .. x .. "Y" .. 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) 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, rawFileName, fileEnding) fileName = rawFileName .. "." .. fileEnding drl_lines = {} drl_tools = {} drl_points = {} last = {} last.x = 0 last.y = 0 currentTool = nil multForMinor = 2 drl_fileName = fileName local tbl = string.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() else drl_frame_setVisible(true) drl_frame_update() end end Sys.RegisterConverter("drl", "^[dD][rR][lL]$", "txt")
Fixed drl bug with scaling.
Fixed drl bug with scaling.
Lua
mit
DeltaCore/FabFileConverter
75445137a0758c578ad07e1c24a85316662eaf3e
init.lua
init.lua
local textadept = require("textadept") local events = require("events") local constants = require("textadept-nim.constants") local icons = require("textadept-nim.icons") local nimsuggest = require("textadept-nim.nimsuggest") local check_executable = require("textadept-nim.utils").check_executable local sessions = require("textadept-nim.sessions") local nim_shutdown_all_sessions = function() sessions:stop_all() end -- Keybinds: -- API Helper key local api_helper_key = "ch" -- GoTo Definition key local goto_definition_key = "cG" local on_buffer_delete = function() -- Checks if any nimsuggest session left without -- binding to buffer. -- All unbound sessions will be closed local to_remove = {} for k, v in pairs(sessions.session_of) do local keep = false for i, b in ipairs(_BUFFERS) do if b.filename ~= nil then if b.filename == k then keep = true end end end if not keep then table.insert(to_remove, k) end end for i, v in pairs(to_remove) do sessions:detach(v) end end local on_file_load = function() -- Called when editor loads file. -- Trying to get information about project and starts nimsuggest if buffer ~= nil and buffer:get_lexer(true) == "nim" then buffer.use_tabs = false buffer.tab_width = 2 nimsuggest.check() end end local function gotoDeclaration(position) -- Puts cursor to declaration local answer = nimsuggest.definition(position) if #answer > 0 then local path = answer[1].file local line = tonumber(answer[1].line) - 1 local col = tonumber(answer[1].column) if path ~= buffer.filename then ui.goto_file(path, false, view) end local pos = buffer:find_column(line, col) buffer:goto_pos(pos) buffer:vertical_centre_caret() buffer:word_right_end_extend() end end -- list of additional actions on symbol encountering -- for further use local actions_on_symbol = { [40] = function(pos) local suggestions = nimsuggest.context(pos) for i, v in pairs(suggestions) do local brackets = v.type:match("%((.*)%)") buffer:call_tip_show(pos, brackets) end end, [46] = function(pos) textadept.editing.autocomplete("nim") end, } local function nim_complete(name) -- Returns a list of suggestions for autocompletion buffer.auto_c_separator = 35 icons:register() local shift = 0 local curline = buffer:get_cur_line() local cur_col = buffer.column[buffer.current_pos] + 1 for i = 1, cur_col do local shifted_col = cur_col - i local c = curline:sub(shifted_col, shifted_col) if c == c:match("([^%w_-])") then shift = i - 1 break end end local suggestions = {} local token_list = nimsuggest.suggest(buffer.current_pos-shift) for i, v in pairs(token_list) do table.insert(suggestions, v.name..": "..v.type.."?"..icons[v.skind]) end if #suggestions == 0 then return textadept.editing.autocompleters.word(name) end return shift, suggestions end local function remove_type_info(text, position) if buffer == nil or buffer:get_lexer(true) ~= "nim" then return end local name = text:match("^([^:]+):.*") if name ~= nil then local pos = buffer.current_pos local to_paste = name:sub(pos-position+1) buffer:insert_text(pos, to_paste) buffer:word_right_end() end buffer:auto_c_cancel() end if check_executable(constants.nimsuggest_exe) then events.connect(events.FILE_AFTER_SAVE, on_file_load) events.connect(events.QUIT, nim_shutdown_all_sessions) events.connect(events.RESET_BEFORE, nim_shutdown_all_sessions) events.connect(events.FILE_OPENED, on_file_load) events.connect(events.BUFFER_DELETED, on_buffer_delete) events.connect(events.AUTO_C_SELECTION, remove_type_info) events.connect(events.CHAR_ADDED, function(ch) if buffer:get_lexer() ~= "nim" or ch > 90 or actions_on_symbol[ch] == nil then return end actions_on_symbol[ch](buffer.current_pos) end) keys.nim = { -- Documentation loader on Ctrl-H [api_helper_key] = function() if buffer:get_lexer() == "nim" then if textadept.editing.api_files.nim == nil then textadept.editing.api_files.nim = {} end local answer = nimsuggest.definition(buffer.current_pos) if #answer > 0 then buffer:call_tip_show(buffer.current_pos, answer[1].skind:match("sk(.*)").." "..answer[1].name..": ".. answer[1].type.."\n"..answer[1].comment) end end end, -- Goto definition on Ctrl-Shift-G [goto_definition_key] = function() gotoDeclaration(buffer.current_pos) end, } textadept.editing.autocompleters.nim = nim_complete end if check_executable(constants.nim_compiler_exe) then textadept.run.compile_commands.nim = function () return nim_compiler.." ".. sessions.active[sessions.session_of(buffer.filename)].project.backend.. " %p" end textadept.run.run_commands.nim = function () return nim_compiler.." ".. sessions.active[sessions.session_of(buffer.filename)].project.backend.. " --run %p" end end
local textadept = require("textadept") local events = require("events") local constants = require("textadept-nim.constants") local icons = require("textadept-nim.icons") local nimsuggest = require("textadept-nim.nimsuggest") local check_executable = require("textadept-nim.utils").check_executable local sessions = require("textadept-nim.sessions") local nim_shutdown_all_sessions = function() sessions:stop_all() end -- Keybinds: -- API Helper key local api_helper_key = "ch" -- GoTo Definition key local goto_definition_key = "cG" local on_buffer_delete = function() -- Checks if any nimsuggest session left without -- binding to buffer. -- All unbound sessions will be closed local to_remove = {} for k, v in pairs(sessions.session_of) do local keep = false for i, b in ipairs(_BUFFERS) do if b.filename ~= nil then if b.filename == k then keep = true end end end if not keep then table.insert(to_remove, k) end end for i, v in pairs(to_remove) do sessions:detach(v) end end local on_file_load = function() -- Called when editor loads file. -- Trying to get information about project and starts nimsuggest if buffer ~= nil and buffer:get_lexer(true) == "nim" then buffer.use_tabs = false buffer.tab_width = 2 nimsuggest.check() end end local function gotoDeclaration(position) -- Puts cursor to declaration local answer = nimsuggest.definition(position) if #answer > 0 then local path = answer[1].file local line = tonumber(answer[1].line) - 1 local col = tonumber(answer[1].column) if path ~= buffer.filename then ui.goto_file(path, false, view) end local pos = buffer:find_column(line, col) buffer:goto_pos(pos) buffer:vertical_centre_caret() buffer:word_right_end_extend() end end -- list of additional actions on symbol encountering -- for further use local actions_on_symbol = { [40] = function(pos) local suggestions = nimsuggest.context(pos) for i, v in pairs(suggestions) do local brackets = v.type:match("%((.*)%)") buffer:call_tip_show(pos, brackets) end end, [46] = function(pos) textadept.editing.autocomplete("nim") end, } local function remove_type_info(text, position) if buffer == nil or buffer:get_lexer(true) ~= "nim" then return end local name = text:match("^([^:]+):.*") if name ~= nil then local pos = buffer.current_pos local to_paste = name:sub(pos-position+1) buffer:insert_text(pos, to_paste) buffer:word_right_end() buffer:auto_c_cancel() end end local function nim_complete(name) -- Returns a list of suggestions for autocompletion buffer.auto_c_separator = 35 icons:register() local shift = 0 local curline = buffer:get_cur_line() local cur_col = buffer.column[buffer.current_pos] + 1 for i = 1, cur_col do local shifted_col = cur_col - i local c = curline:sub(shifted_col, shifted_col) if c == c:match("([^%w_-])") then shift = i - 1 break end end local suggestions = {} local token_list = nimsuggest.suggest(buffer.current_pos-shift) for i, v in pairs(token_list) do table.insert(suggestions, v.name..": "..v.type.."?"..icons[v.skind]) end if #suggestions == 0 then return textadept.editing.autocompleters.word(name) end if #suggestions == 1 then remove_type_info(suggestions[1], buffer.current_pos - shift) return end return shift, suggestions end if check_executable(constants.nimsuggest_exe) then events.connect(events.FILE_AFTER_SAVE, on_file_load) events.connect(events.QUIT, nim_shutdown_all_sessions) events.connect(events.RESET_BEFORE, nim_shutdown_all_sessions) events.connect(events.FILE_OPENED, on_file_load) events.connect(events.BUFFER_DELETED, on_buffer_delete) events.connect(events.AUTO_C_SELECTION, remove_type_info) events.connect(events.CHAR_ADDED, function(ch) if buffer:get_lexer() ~= "nim" or ch > 90 or actions_on_symbol[ch] == nil then return end actions_on_symbol[ch](buffer.current_pos) end) keys.nim = { -- Documentation loader on Ctrl-H [api_helper_key] = function() if buffer:get_lexer() == "nim" then if textadept.editing.api_files.nim == nil then textadept.editing.api_files.nim = {} end local answer = nimsuggest.definition(buffer.current_pos) if #answer > 0 then buffer:call_tip_show(buffer.current_pos, answer[1].skind:match("sk(.*)").." "..answer[1].name..": ".. answer[1].type.."\n"..answer[1].comment) end end end, -- Goto definition on Ctrl-Shift-G [goto_definition_key] = function() gotoDeclaration(buffer.current_pos) end, } textadept.editing.autocompleters.nim = nim_complete end if check_executable(constants.nim_compiler_exe) then textadept.run.compile_commands.nim = function () return nim_compiler.." ".. sessions.active[sessions.session_of(buffer.filename)].project.backend.. " %p" end textadept.run.run_commands.nim = function () return nim_compiler.." ".. sessions.active[sessions.session_of(buffer.filename)].project.backend.. " --run %p" end end
Fixed incorrect suggestion pasting when only one suggestion availible
Fixed incorrect suggestion pasting when only one suggestion availible
Lua
mit
xomachine/textadept-nim
88d7dec24a82d47f706a80e5382915bb8e7aaa5d
nyagos.d/trash.lua
nyagos.d/trash.lua
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end nyagos.alias.trash = function(args) if #args <= 0 then nyagos.writerr("Move files or directories to Windows Trashbox\n") nyagos.writerr("Usage: trash file(s)...\n") return end local fsObj = nyagos.create_object("Scripting.FileSystemObject") local shellApp = nyagos.create_object("Shell.Application") local ten = 10 if _VERSION == "Lua 5.3" then ten = math.tointeger(10) end local trashBox = shellApp:NameSpace(ten) args = nyagos.glob((table.unpack or unpack)(args)) for i=1,#args do if fsObj:FileExists(args[i]) or fsObj:FolderExists(args[i]) then trashBox:MoveHere(fsObj:GetAbsolutePathName(args[i])) else nyagos.writerr(args[i]..": such a file or directory not found.\n") end end end
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end nyagos.alias.trash = function(args) if #args <= 0 then nyagos.writerr("Move files or directories to Windows Trashbox\n") nyagos.writerr("Usage: trash file(s)...\n") return end local fsObj = nyagos.create_object("Scripting.FileSystemObject") local shellApp = nyagos.create_object("Shell.Application") local trashBox = shellApp:NameSpace(nyagos.to_ole_integer(10)) args = nyagos.glob((table.unpack or unpack)(args)) for i=1,#args do if fsObj:FileExists(args[i]) or fsObj:FolderExists(args[i]) then trashBox:MoveHere(fsObj:GetAbsolutePathName(args[i])) else nyagos.writerr(args[i]..": such a file or directory not found.\n") end end end
The command `trash` did not work because lua.LNumber used as float64. It is fixed by nyagos.to_ole_integer
The command `trash` did not work because lua.LNumber used as float64. It is fixed by nyagos.to_ole_integer
Lua
bsd-3-clause
tsuyoshicho/nyagos,nocd5/nyagos,zetamatta/nyagos
5c5f715e9862af59609eb48491ea730763d4c1bc
spec/demos/form_spec.lua
spec/demos/form_spec.lua
local request = require 'http.functional.request' local writer = require 'http.functional.response' local describe, it, assert = describe, it, assert local function test_cases(app) assert.not_nil(app) it('responds with bad request status cod and errors', function() local w, req = writer.new(), request.new {method = 'POST'} app(w, req) assert.same({ status_code = 400, headers = {['Content-Type'] = 'application/json'}, buffer = { '{"message":"Required field cannot be left blank.",' .. '"author":"Required field cannot be left blank."}' } }, w) end) it('accepts a valid input', function() local w = writer.new() local req = request.new { method = 'POST', form = { author = 'jack', message = 'hello' } } app(w, req) assert.is_nil(w.status_code) end) end describe('demos.http.form', function() test_cases(require 'demos.http.form') end) describe('demos.web.form', function() test_cases(require 'demos.web.form') end)
local request = require 'http.functional.request' local writer = require 'http.functional.response' local json = require 'core.encoding.json' local describe, it, assert = describe, it, assert local function test_cases(app) assert.not_nil(app) it('responds with bad request status cod and errors', function() local w, req = writer.new(), request.new {method = 'POST'} app(w, req) assert.equals(400, w.status_code) assert.same({['Content-Type'] = 'application/json'}, w.headers) assert(json.decode(table.concat(w.buffer))) end) it('accepts a valid input', function() local w = writer.new() local req = request.new { method = 'POST', form = { author = 'jack', message = 'hello' } } app(w, req) assert.is_nil(w.status_code) end) end describe('demos.http.form', function() test_cases(require 'demos.http.form') end) describe('demos.web.form', function() test_cases(require 'demos.web.form') end)
Fixed issue with lua 5.2.
Fixed issue with lua 5.2.
Lua
mit
akornatskyy/lucid
45ad4796648a33c1c526fde43e5c763d6101575d
Modules/Gui/Markdown/MarkdownParser.lua
Modules/Gui/Markdown/MarkdownParser.lua
--- Parses text into markdown -- @classmod MarkdownParser local MarkdownParser = {} MarkdownParser.__index = MarkdownParser MarkdownParser.ClassName = "MarkdownParser" function MarkdownParser.new(text) local self = setmetatable({}, MarkdownParser) self._text = text or error("No text") return self end function MarkdownParser:GetLines() local lines = {} for line in self._text:gmatch("([^\r\n]*)[\r\n]") do table.insert(lines, line) end return lines end function MarkdownParser:ParseList(oldLines) local lines = {} local currentList for _, line in pairs(oldLines) do local space, bullet, text if type(line) == "string" then space, bullet, text = line:match("^([ \t]*)([%-%*])%s*(.+)%s*$") end if space and bullet and text then space = space:gsub(" ", "X") space = space:gsub(" ", "") space = space:gsub("\t", "X") local Level = #space + 1 if currentList and currentList.Level ~= Level then table.insert(lines, currentList) currentList = nil end if currentList then table.insert(currentList, text) else currentList = {} currentList.Level = Level currentList.Type = "List" table.insert(currentList, text) end else if currentList then table.insert(lines, currentList) currentList = nil end table.insert(lines, line) end end if currentList then table.insert(lines, currentList) end return lines end function MarkdownParser:ParseHeaders(oldLines) local lines = {} for _, line in pairs(oldLines) do local poundSymbols, text if type(line) == "string" then poundSymbols, text = line:match("^%s*([#]+)%s*(.+)%s*$") end local level = poundSymbols and #poundSymbols if text and level and level >= 1 and level <= 5 then table.insert(lines, { Type = "Header"; Level = level; Text = text; }) else table.insert(lines, line) end end return lines end function MarkdownParser:ParseParagraphs(oldLines) local lines = {} local currentParagraph for _, line in pairs(oldLines) do if type(line) == "table" then table.insert(lines, line) else if line:match("[^%s]") then if currentParagraph then currentParagraph = currentParagraph .. " " .. line else currentParagraph = line end else if currentParagraph then table.insert(lines, currentParagraph) currentParagraph = nil end end end end if currentParagraph then table.insert(lines, currentParagraph) end return lines end --- Parses the given text into a list of lines function MarkdownParser:Parse() local lines = self:GetLines() lines = self:ParseList(lines) lines = self:ParseHeaders(lines) lines = self:ParseParagraphs(lines) -- do this last return lines end return MarkdownParser
--- Parses text into markdown -- @classmod MarkdownParser local MarkdownParser = {} MarkdownParser.__index = MarkdownParser MarkdownParser.ClassName = "MarkdownParser" function MarkdownParser.new(text) local self = setmetatable({}, MarkdownParser) self._text = text or error("No text") return self end function MarkdownParser:GetLines() local lines = {} local text = self._text .. "\n" -- append extra line to force ending match for line in text:gmatch("([^\r\n]*)[\r\n]") do table.insert(lines, line) end return lines end function MarkdownParser:ParseList(oldLines) local lines = {} local currentList for _, line in pairs(oldLines) do local space, bullet, text if type(line) == "string" then space, bullet, text = line:match("^([ \t]*)([%-%*])%s*(.+)%s*$") end if space and bullet and text then space = space:gsub(" ", "X") space = space:gsub(" ", "") space = space:gsub("\t", "X") local Level = #space + 1 if currentList and currentList.Level ~= Level then table.insert(lines, currentList) currentList = nil end if currentList then table.insert(currentList, text) else currentList = {} currentList.Level = Level currentList.Type = "List" table.insert(currentList, text) end else if currentList then table.insert(lines, currentList) currentList = nil end table.insert(lines, line) end end if currentList then table.insert(lines, currentList) end return lines end function MarkdownParser:ParseHeaders(oldLines) local lines = {} for _, line in pairs(oldLines) do local poundSymbols, text if type(line) == "string" then poundSymbols, text = line:match("^%s*([#]+)%s*(.+)%s*$") end local level = poundSymbols and #poundSymbols if text and level and level >= 1 and level <= 5 then table.insert(lines, { Type = "Header"; Level = level; Text = text; }) else table.insert(lines, line) end end return lines end function MarkdownParser:ParseParagraphs(oldLines) local lines = {} local currentParagraph for _, line in pairs(oldLines) do if type(line) == "table" then table.insert(lines, line) else if line:match("[^%s]") then if currentParagraph then currentParagraph = currentParagraph .. " " .. line else currentParagraph = line end else if currentParagraph then table.insert(lines, currentParagraph) currentParagraph = nil end end end end if currentParagraph then table.insert(lines, currentParagraph) end return lines end --- Parses the given text into a list of lines function MarkdownParser:Parse() local lines = self:GetLines() lines = self:ParseList(lines) lines = self:ParseHeaders(lines) lines = self:ParseParagraphs(lines) -- do this last return lines end return MarkdownParser
Fix single line markdown instances
Fix single line markdown instances
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
0b8e96e8cbc93a56deda4f815762e6d00005c7ea
ardivink.lua
ardivink.lua
bootstrap = require("bootstrap") bootstrap.init() ci = require("ci") --godi = require("godi") oasis = require("oasis") git = require("git") ci.init() -- godi.init() git.init() oasis.init() --godi.bootstrap("3.12") --godi.update() --godi.upgrade() --godi.build_many( -- {"godi-findlib", -- "godi-ocaml-fileutils", -- "godi-ocaml-data-notation", -- "godi-ocaml-expect", -- "godi-ounit", -- "apps-ocamlmod", -- "apps-ocamlify"}) oasis.std_process("--enable-tests") git.create_tag(oasis.package_version())
ci = require("ci") --godi = require("godi") oasis = require("oasis") git = require("git") ci.init() -- godi.init() git.init() oasis.init() --godi.bootstrap("3.12") --godi.update() --godi.upgrade() --godi.build_many( -- {"godi-findlib", -- "godi-ocaml-fileutils", -- "godi-ocaml-data-notation", -- "godi-ocaml-expect", -- "godi-ounit", -- "apps-ocamlmod", -- "apps-ocamlify"}) oasis.std_process("--enable-tests") git.create_tag(oasis.package_version())
Fix missing bootstrap.lua.
Fix missing bootstrap.lua.
Lua
lgpl-2.1
Chris00/oasis,Chris00/oasis,RadicalZephyr/oasis,jpdeplaix/oasis,jpdeplaix/oasis,gerdstolpmann/oasis,gerdstolpmann/oasis,madroach/oasis,madroach/oasis,RadicalZephyr/oasis,Chris00/oasis,gerdstolpmann/oasis,diml/oasis,diml/oasis,jpdeplaix/oasis
9d13e7d111da9544d416df772540a54845bfb2d8
gateway/src/apicast/policy_loader.lua
gateway/src/apicast/policy_loader.lua
--- Policy loader -- This module loads a policy defined by its name and version. -- It uses sandboxed require to isolate dependencies and not mutate global state. -- That allows for loading several versions of the same policy with different dependencies. -- And even loading several independent copies of the same policy with no shared state. -- Each object returned by the loader is new table and shares only shared APIcast code. local sandbox = require('resty.sandbox') local cjson = require('cjson') local format = string.format local ipairs = ipairs local pairs = pairs local insert = table.insert local setmetatable = setmetatable local pcall = pcall local _M = {} local resty_env = require('resty.env') local re = require('ngx.re') do local function apicast_dir() return resty_env.value('APICAST_DIR') or '.' end local function policy_load_path() return resty_env.value('APICAST_POLICY_LOAD_PATH') or format('%s/policies', apicast_dir()) end function _M.policy_load_paths() return re.split(policy_load_path(), ':', 'oj') end function _M.builtin_policy_load_path() return resty_env.value('APICAST_BUILTIN_POLICY_LOAD_PATH') or format('%s/src/apicast/policy', apicast_dir()) end end -- Returns true if config validation has been enabled via ENV or if we are -- running Test::Nginx integration tests. We know that the framework always -- sets TEST_NGINX_BINARY so we can use it to detect whether we are running the -- tests. local function policy_config_validation_is_enabled() return resty_env.enabled('APICAST_VALIDATE_POLICY_CONFIGS') or resty_env.value('TEST_NGINX_BINARY') end local policy_config_validator = { validate_config = function() return true end } if policy_config_validation_is_enabled() then policy_config_validator = require('apicast.policy_config_validator') end local function read_manifest(path) local handle = io.open(format('%s/%s', path, 'apicast-policy.json')) if handle then local contents = handle:read('*a') handle:close() return cjson.decode(contents) end end local function lua_load_path(load_path) return format('%s/?.lua', load_path) end local function load_manifest(name, version, path) local manifest = read_manifest(path) if manifest then if manifest.version ~= version then ngx.log(ngx.ERR, 'Not loading policy: ', name, ' path: ', path, ' version: ', version, '~= ', manifest.version) return end return manifest, lua_load_path(path) end return nil, lua_load_path(path) end local function with_config_validator(policy, policy_config_schema) local original_new = policy.new local new_with_validator = function(config) local is_valid, err = policy_config_validator.validate_config( config, policy_config_schema) if not is_valid then error(format('Invalid config for policy: %s', err)) end return original_new(config) end return setmetatable( { new = new_with_validator }, { __index = policy } ) end function _M:load_path(name, version, paths) local failures = {} for _, path in ipairs(paths or self.policy_load_paths()) do local manifest, load_path = load_manifest(name, version, format('%s/%s/%s', path, name, version) ) if manifest then return load_path, manifest.configuration else insert(failures, load_path) end end if version == 'builtin' then local manifest, load_path = load_manifest(name, version, format('%s/%s', self.builtin_policy_load_path(), name) ) if manifest then return load_path, manifest.configuration else insert(failures, load_path) end end return nil, nil, failures end local package_cache = setmetatable({}, { __index = function(t, k) local n = { }; t[k] = n; return n end }) function _M:call(name, version, dir) local v = version or 'builtin' local load_path, policy_config_schema, invalid_paths = self:load_path(name, v, dir) local cache = package_cache[table.concat({name, v, dir}, '-')] local loader = sandbox.new(load_path and { load_path } or invalid_paths, cache) ngx.log(ngx.DEBUG, 'loading policy: ', name, ' version: ', v) -- passing the "exclusive" flag for the require so it does not fallback to native require -- it should load only policies and not other code and fail if there is no such policy local res = loader('init', true) if policy_config_validation_is_enabled() then return with_config_validator(res, policy_config_schema) else return res end end function _M:pcall(name, version, dir) local ok, ret = pcall(self.call, self, name, version, dir) if ok then return ret else return nil, ret end end -- Returns all the policy modules function _M:get_all() local policy_modules = {} local policy_manifests_loader = require('apicast.policy_manifests_loader') local manifests = policy_manifests_loader.get_all() for policy_name, policy_manifests in pairs(manifests) do for _, manifest in ipairs(policy_manifests) do local policy = self:call(policy_name, manifest.version) insert(policy_modules, policy) end end return policy_modules end return setmetatable(_M, { __call = _M.call })
--- Policy loader -- This module loads a policy defined by its name and version. -- It uses sandboxed require to isolate dependencies and not mutate global state. -- That allows for loading several versions of the same policy with different dependencies. -- And even loading several independent copies of the same policy with no shared state. -- Each object returned by the loader is new table and shares only shared APIcast code. local sandbox = require('resty.sandbox') local cjson = require('cjson') local format = string.format local ipairs = ipairs local pairs = pairs local insert = table.insert local concat = table.concat local setmetatable = setmetatable local pcall = pcall local _M = {} local resty_env = require('resty.env') local re = require('ngx.re') do local function apicast_dir() return resty_env.value('APICAST_DIR') or '.' end local function policy_load_path() return resty_env.value('APICAST_POLICY_LOAD_PATH') or format('%s/policies', apicast_dir()) end function _M.policy_load_paths() return re.split(policy_load_path(), ':', 'oj') end function _M.builtin_policy_load_path() return resty_env.value('APICAST_BUILTIN_POLICY_LOAD_PATH') or format('%s/src/apicast/policy', apicast_dir()) end end -- Returns true if config validation has been enabled via ENV or if we are -- running Test::Nginx integration tests. We know that the framework always -- sets TEST_NGINX_BINARY so we can use it to detect whether we are running the -- tests. local function policy_config_validation_is_enabled() return resty_env.enabled('APICAST_VALIDATE_POLICY_CONFIGS') or resty_env.value('TEST_NGINX_BINARY') end local policy_config_validator = { validate_config = function() return true end } if policy_config_validation_is_enabled() then policy_config_validator = require('apicast.policy_config_validator') end local function read_manifest(path) local handle = io.open(format('%s/%s', path, 'apicast-policy.json')) if handle then local contents = handle:read('*a') handle:close() return cjson.decode(contents) end end local function lua_load_path(load_path) return format('%s/?.lua', load_path) end local function load_manifest(name, version, path) local manifest = read_manifest(path) if manifest then if manifest.version ~= version then ngx.log(ngx.ERR, 'Not loading policy: ', name, ' path: ', path, ' version: ', version, '~= ', manifest.version) return end return manifest, lua_load_path(path) end return nil, lua_load_path(path) end local function with_config_validator(policy, policy_config_schema) local original_new = policy.new local new_with_validator = function(config) local is_valid, err = policy_config_validator.validate_config( config, policy_config_schema) if not is_valid then error(format('Invalid config for policy: %s', err)) end return original_new(config) end return setmetatable( { new = new_with_validator }, { __index = policy } ) end function _M:load_path(name, version, paths) local failures = {} for _, path in ipairs(paths or self.policy_load_paths()) do local manifest, load_path = load_manifest(name, version, format('%s/%s/%s', path, name, version) ) if manifest then return load_path, manifest.configuration else insert(failures, load_path) end end if version == 'builtin' then local manifest, load_path = load_manifest(name, version, format('%s/%s', self.builtin_policy_load_path(), name) ) if manifest then return load_path, manifest.configuration else insert(failures, load_path) end end return nil, nil, failures end local package_cache = setmetatable({}, { __index = function(t, k) local n = { }; t[k] = n; return n end }) function _M:call(name, version, dir) local v = version or 'builtin' local load_path, policy_config_schema, invalid_paths = self:load_path(name, v, dir) local cache_key = concat({name, v, dir and concat(dir, ',') or '' }, '-') local cache = package_cache[cache_key] local loader = sandbox.new(load_path and { load_path } or invalid_paths, cache) ngx.log(ngx.DEBUG, 'loading policy: ', name, ' version: ', v) -- passing the "exclusive" flag for the require so it does not fallback to native require -- it should load only policies and not other code and fail if there is no such policy local res = loader('init', true) if policy_config_validation_is_enabled() then return with_config_validator(res, policy_config_schema) else return res end end function _M:pcall(name, version, dir) local ok, ret = pcall(self.call, self, name, version, dir) if ok then return ret else return nil, ret end end -- Returns all the policy modules function _M:get_all() local policy_modules = {} local policy_manifests_loader = require('apicast.policy_manifests_loader') local manifests = policy_manifests_loader.get_all() for policy_name, policy_manifests in pairs(manifests) do for _, manifest in ipairs(policy_manifests) do local policy = self:call(policy_name, manifest.version) insert(policy_modules, policy) end end return policy_modules end return setmetatable(_M, { __call = _M.call })
policy_loader: fix building of the cache key in call()
policy_loader: fix building of the cache key in call() The code was not taking into account that 'dir' is a table.
Lua
mit
3scale/docker-gateway,3scale/apicast,3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/apicast
88e16001e37eab28f5d6f4c242f65b8a4c2a1e33
src/luarocks/download.lua
src/luarocks/download.lua
--- Module implementing the luarocks "download" command. -- Download a rock from the repository. --module("luarocks.download", package.seeall) local download = {} package.loaded["luarocks.download"] = download local util = require("luarocks.util") local path = require("luarocks.path") local fetch = require("luarocks.fetch") local search = require("luarocks.search") local fs = require("luarocks.fs") local dir = require("luarocks.dir") download.help_summary = "Download a specific rock file from a rocks server." download.help_arguments = "[--all] [--arch=<arch> | --source | --rockspec] [<name> [<version>]]" download.help = [[ --all Download all files if there are multiple matches. --source Download .src.rock if available. --rockspec Download .rockspec if available. --arch=<arch> Download rock for a specific architecture. ]] local function get_file(filename) local protocol, pathname = dir.split_url(filename) if protocol == "file" then local ok, err = fs.copy(pathname, fs.current_dir()) if ok then return pathname else return nil, err end else return fetch.fetch_url(filename) end end function download.download(arch, name, version, all) local query = search.make_query(name, version) if arch then query.arch = arch end if all then if name == "" then query.exact_name = false end local results = search.search_repos(query) if next(results) then local all_ok = true local any_err = "" for name, result in pairs(results) do for version, items in pairs(result) do for _, item in ipairs(items) do local url = path.make_url(item.repo, name, version, item.arch) local ok, err = get_file(url) if not ok then all_ok = false any_err = any_err .. "\n" .. err end end end end return all_ok, any_err end else local url = search.find_suitable_rock(query) if url then return get_file(url) end end return nil, "Could not find a result named "..name..(version and " "..version or "").."." end --- Driver function for the "download" command. -- @param name string: a rock name. -- @param version string or nil: if the name of a package is given, a -- version may also be passed. -- @return boolean or (nil, string): true if successful or nil followed -- by an error message. function download.run(...) local flags, name, version = util.parse_flags(...) assert(type(version) == "string" or not version) if type(name) ~= "string" and not flags["all"] then return nil, "Argument missing, see help." end if not name then name, version = "", "" end local arch if flags["source"] then arch = "src" elseif flags["rockspec"] then arch = "rockspec" elseif flags["arch"] then arch = flags["arch"] end local dl, err = download.download(arch, name, version, flags["all"]) return dl and true, err end return download
--- Module implementing the luarocks "download" command. -- Download a rock from the repository. --module("luarocks.download", package.seeall) local download = {} package.loaded["luarocks.download"] = download local util = require("luarocks.util") local path = require("luarocks.path") local fetch = require("luarocks.fetch") local search = require("luarocks.search") local fs = require("luarocks.fs") local dir = require("luarocks.dir") download.help_summary = "Download a specific rock file from a rocks server." download.help_arguments = "[--all] [--arch=<arch> | --source | --rockspec] [<name> [<version>]]" download.help = [[ --all Download all files if there are multiple matches. --source Download .src.rock if available. --rockspec Download .rockspec if available. --arch=<arch> Download rock for a specific architecture. ]] local function get_file(filename) local protocol, pathname = dir.split_url(filename) if protocol == "file" then local ok, err = fs.copy(pathname, fs.current_dir()) if ok then return pathname else return nil, err end else return fetch.fetch_url(filename) end end function download.download(arch, name, version, all) local query = search.make_query(name, version) if arch then query.arch = arch end if all then if name == "" then query.exact_name = false end local results = search.search_repos(query) local has_result = false local all_ok = true local any_err = "" for name, result in pairs(results) do for version, items in pairs(result) do for _, item in ipairs(items) do -- Ignore provided rocks. if item.arch ~= "installed" then has_result = true local filename = path.make_url(item.repo, name, version, item.arch) local ok, err = get_file(filename) if not ok then all_ok = false any_err = any_err .. "\n" .. err end end end end end if has_result then return all_ok, any_err end else local url = search.find_suitable_rock(query) if url then return get_file(url) end end return nil, "Could not find a result named "..name..(version and " "..version or "").."." end --- Driver function for the "download" command. -- @param name string: a rock name. -- @param version string or nil: if the name of a package is given, a -- version may also be passed. -- @return boolean or (nil, string): true if successful or nil followed -- by an error message. function download.run(...) local flags, name, version = util.parse_flags(...) assert(type(version) == "string" or not version) if type(name) ~= "string" and not flags["all"] then return nil, "Argument missing, see help." end if not name then name, version = "", "" end local arch if flags["source"] then arch = "src" elseif flags["rockspec"] then arch = "rockspec" elseif flags["arch"] then arch = flags["arch"] end local dl, err = download.download(arch, name, version, flags["all"]) return dl and true, err end return download
Fix stat error on `luarocks download <provided rock> --all`
Fix stat error on `luarocks download <provided rock> --all`
Lua
mit
xpol/luavm,xpol/luavm,robooo/luarocks,tarantool/luarocks,xpol/luarocks,xpol/luarocks,tarantool/luarocks,keplerproject/luarocks,xpol/luarocks,xpol/luainstaller,keplerproject/luarocks,xpol/luarocks,xpol/luainstaller,xpol/luainstaller,xpol/luavm,luarocks/luarocks,tarantool/luarocks,robooo/luarocks,xpol/luainstaller,xpol/luavm,robooo/luarocks,keplerproject/luarocks,luarocks/luarocks,luarocks/luarocks,robooo/luarocks,xpol/luavm,keplerproject/luarocks
f2e0d829b43011cce87568118a5b8b0b469ade1e
tests/build.lua
tests/build.lua
-- main entry function main(argv) -- generic? os.exec("xmake m -b") os.exec("xmake f -c") os.exec("xmake") if os.host() ~= "windows" then os.exec("sudo xmake install") os.exec("sudo xmake uninstall") end os.exec("xmake p") os.exec("xmake c") os.exec("xmake f -m release") os.exec("xmake -r -a -v --backtrace") if os.host() ~= "windows" then os.exec("sudo xmake install --all -v --backtrace") os.exec("sudo xmake uninstall -v --backtrace") end os.exec("xmake f --mode=debug --verbose --backtrace") os.exec("xmake --rebuild --all --verbose --backtrace") if os.host() ~= "windows" then os.exec("xmake install -o /tmp -a --verbose --backtrace") os.exec("xmake uninstall --installdir=/tmp --verbose --backtrace") end os.exec("xmake p --verbose --backtrace") os.exec("xmake c --verbose --backtrace") os.exec("xmake m -e buildtest") os.exec("xmake m -l") os.exec("xmake f --cc=gcc --cxx=g++") os.exec("xmake m buildtest") os.exec("xmake f --cc=clang --cxx=clang++ --ld=clang++ --verbose --backtrace") os.exec("xmake m buildtest") os.exec("xmake m -d buildtest") -- test iphoneos? if argv and argv.iphoneos then if os.host() == "macosx" then os.exec("xmake m package -p iphoneos") end end end
-- main entry function main(argv) -- generic? os.exec("$(xmake) m -b") os.exec("$(xmake) f -c") os.exec("$(xmake)") if os.host() ~= "windows" then os.exec("sudo $(xmake) install") os.exec("sudo $(xmake) uninstall") end os.exec("$(xmake) p") os.exec("$(xmake) c") os.exec("$(xmake) f -m release") os.exec("$(xmake) -r -a -v --backtrace") if os.host() ~= "windows" then os.exec("sudo $(xmake) install --all -v --backtrace") os.exec("sudo $(xmake) uninstall -v --backtrace") end os.exec("$(xmake) f --mode=debug --verbose --backtrace") os.exec("$(xmake) --rebuild --all --verbose --backtrace") if os.host() ~= "windows" then os.exec("$(xmake) install -o /tmp -a --verbose --backtrace") os.exec("$(xmake) uninstall --installdir=/tmp --verbose --backtrace") end os.exec("$(xmake) p --verbose --backtrace") os.exec("$(xmake) c --verbose --backtrace") os.exec("$(xmake) m -e buildtest") os.exec("$(xmake) m -l") os.exec("$(xmake) f --cc=gcc --cxx=g++") os.exec("$(xmake) m buildtest") os.exec("$(xmake) f --cc=clang --cxx=clang++ --ld=clang++ --verbose --backtrace") os.exec("$(xmake) m buildtest") os.exec("$(xmake) m -d buildtest") -- test iphoneos? if argv and argv.iphoneos then if os.host() == "macosx" then os.exec("$(xmake) m package -p iphoneos") end end end
use $(xmake) instead of xmake to fix cnf
use $(xmake) instead of xmake to fix cnf
Lua
apache-2.0
waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake
5915d7cd26e9b85b63e5dad6a29229d1a63a027d
libs/sgi-uhttpd/luasrc/sgi/uhttpd.lua
libs/sgi-uhttpd/luasrc/sgi/uhttpd.lua
--[[ LuCI - Server Gateway Interface for the uHTTPd server Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. ]]-- require "nixio.util" require "luci.http" require "luci.sys" require "luci.dispatcher" require "luci.ltn12" function handle_request(env) exectime = os.clock() local renv = { CONTENT_LENGTH = env.CONTENT_LENGTH, CONTENT_TYPE = env.CONTENT_TYPE, REQUEST_METHOD = env.REQUEST_METHOD, REQUEST_URI = env.REQUEST_URI, PATH_INFO = env.PATH_INFO, SCRIPT_NAME = env.SCRIPT_NAME:gsub("/+$", ""), SCRIPT_FILENAME = env.SCRIPT_NAME, SERVER_PROTOCOL = env.SERVER_PROTOCOL, QUERY_STRING = env.QUERY_STRING } local k, v for k, v in pairs(env.headers) do k = k:upper():gsub("%-", "_") renv["HTTP_" .. k] = v end local len = tonumber(env.CONTENT_LENGTH) or 0 local function recv() if len > 0 then local rlen, rbuf = uhttpd.recv(4096) if rlen >= 0 then len = len - rlen return rbuf end end return nil end local function send(...) return uhttpd.send(...) end local function sendc(...) if env.HTTP_VERSION > 1.0 then return uhttpd.sendc(...) else return uhttpd.send(...) end end local req = luci.http.Request( renv, recv, luci.ltn12.sink.file(io.stderr) ) local x = coroutine.create(luci.dispatcher.httpdispatch) local hcache = { } local active = true if env.HTTP_VERSION > 1.0 then hcache["Transfer-Encoding"] = "chunked" end while coroutine.status(x) ~= "dead" do local res, id, data1, data2 = coroutine.resume(x, req) if not res then send(env.SERVER_PROTOCOL) send(" 500 Internal Server Error\r\n") send("Content-Type: text/plain\r\n\r\n") send(tostring(id)) break end if active then if id == 1 then send(env.SERVER_PROTOCOL) send(" ") send(tostring(data1)) send(" ") send(tostring(data2)) send("\r\n") elseif id == 2 then hcache[data1] = data2 elseif id == 3 then for k, v in pairs(hcache) do send(tostring(k)) send(": ") send(tostring(v)) send("\r\n") end send("\r\n") elseif id == 4 then sendc(tostring(data1 or "")) elseif id == 5 then active = false elseif id == 6 then data1:copyz(nixio.stdout, data2) end end end end
--[[ LuCI - Server Gateway Interface for the uHTTPd server Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. ]]-- require "nixio.util" require "luci.http" require "luci.sys" require "luci.dispatcher" require "luci.ltn12" function handle_request(env) exectime = os.clock() local renv = { CONTENT_LENGTH = env.CONTENT_LENGTH, CONTENT_TYPE = env.CONTENT_TYPE, REQUEST_METHOD = env.REQUEST_METHOD, REQUEST_URI = env.REQUEST_URI, PATH_INFO = env.PATH_INFO, SCRIPT_NAME = env.SCRIPT_NAME:gsub("/+$", ""), SCRIPT_FILENAME = env.SCRIPT_NAME, SERVER_PROTOCOL = env.SERVER_PROTOCOL, QUERY_STRING = env.QUERY_STRING } local k, v for k, v in pairs(env.headers) do k = k:upper():gsub("%-", "_") renv["HTTP_" .. k] = v end local len = tonumber(env.CONTENT_LENGTH) or 0 local function recv() if len > 0 then local rlen, rbuf = uhttpd.recv(4096) if rlen >= 0 then len = len - rlen return rbuf end end return nil end local send = uhttpd.send local req = luci.http.Request( renv, recv, luci.ltn12.sink.file(io.stderr) ) local x = coroutine.create(luci.dispatcher.httpdispatch) local hcache = { } local active = true while coroutine.status(x) ~= "dead" do local res, id, data1, data2 = coroutine.resume(x, req) if not res then send("Status: 500 Internal Server Error\r\n") send("Content-Type: text/plain\r\n\r\n") send(tostring(id)) break end if active then if id == 1 then send("Status: ") send(tostring(data1)) send(" ") send(tostring(data2)) send("\r\n") elseif id == 2 then hcache[data1] = data2 elseif id == 3 then for k, v in pairs(hcache) do send(tostring(k)) send(": ") send(tostring(v)) send("\r\n") end send("\r\n") elseif id == 4 then send(tostring(data1 or "")) elseif id == 5 then active = false elseif id == 6 then data1:copyz(nixio.stdout, data2) end end end end
libs/sgi-uhttpd: fix binding to properly work with current uhttpd2 implementation
libs/sgi-uhttpd: fix binding to properly work with current uhttpd2 implementation Signed-off-by: Jo-Philipp Wich <jow@openwrt.org> git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@9963 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
gwlim/luci,ch3n2k/luci,ch3n2k/luci,yeewang/openwrt-luci,phi-psi/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,ch3n2k/luci,8devices/carambola2-luci,phi-psi/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,ch3n2k/luci,gwlim/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,8devices/carambola2-luci,phi-psi/luci,phi-psi/luci,yeewang/openwrt-luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,8devices/carambola2-luci,zwhfly/openwrt-luci,gwlim/luci,yeewang/openwrt-luci,gwlim/luci,eugenesan/openwrt-luci,gwlim/luci,ThingMesh/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,zwhfly/openwrt-luci,gwlim/luci,8devices/carambola2-luci,eugenesan/openwrt-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,phi-psi/luci,gwlim/luci,eugenesan/openwrt-luci,phi-psi/luci,yeewang/openwrt-luci,phi-psi/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci
e50a194d178d747f9a9bad3a3b324620d6acc3fa
l2l/main.lua
l2l/main.lua
local compiler = require("l2l.compiler") local version = "0.0.2-pre" local paired_options = {eval=true, load=true, compile=true} local single_options = {repl=true, help=true, version=true} local aliases = {r="repl", e="eval", l="load", c="compile", v="version", h="help", ["?"]="help"} local lookup_alias = function(arg) return aliases[arg] or arg end local trace, err local handler = function(e) trace, err = debug.traceback(2), e end local function repl(partial) if(partial) then io.write("... ") else io.write("> ") end local input = io.read() if(not input) then if(not partial) then return else return repl() end end input = (partial or "") .. input local compiled_ok, src_or_err = pcall(compiler.compile, input, "*repl*") if(compiled_ok) then local vals = {xpcall(loadstring(src_or_err), handler)} if(table.remove(vals, 1)) then for _,val in ipairs(vals) do -- TODO: pretty-print regular tables print(val) end else print(err) print(trace) end else if(src_or_err:find("no bytes$")) then return repl(input) -- partial input else print("Compiler error:", src_or_err) end return repl() end return repl() end local run = function(...) local args, options, next_in = {...}, {} for i,a in ipairs(args) do if(a:sub(1, 1) == "-") then local option_name = lookup_alias(a:gsub("%-", "")) next_in = false if(paired_options[option_name]) then next_in = option_name elseif(single_options[option_name]) then options[option_name] = true else error("Unknown argument: " .. a) end elseif(next_in) then table.insert(options, {how=next_in, val=a}) elseif(i ~= #args) then error("Unknown argument: " .. a) else -- last arg is assumed to be a file table.insert(options, {how="load", val=a}) end end if(#args == 0 or options.help) then print("Welcome to l2l.") print("Usage: l2l [<option> ...] <argument>") print("Options:") print(" -r / --repl open a repl session") print(" -e / --eval FORM evaluate and print a given FORM") print(" -l / --load FILE load a given FILE") print(" -c / --compile FILE print compiled lua for a given FILE") print(" -h / --help print this message and exit") print(" -v / --version print version information and exit") os.exit(0) elseif(options.version) then print("l2l version " .. version) os.exit(0) end for _,to_load in ipairs(options) do if(to_load.how == "eval") then local src = compiler.compile(to_load.val, "*eval*") print(loadstring(src)()) elseif(to_load.how == "load") then local f = assert(io.open(to_load.val), "File not found: " .. to_load.val) local lisp_source = f:read("*all") f:close() local src = compiler.compile(lisp_source, to_load.val) loadstring(src)() elseif(to_load.how == "compile") then local f = assert(io.open(to_load.val), "File not found: " .. to_load.val) local lisp_source = f:read("*all") f:close() print(compiler.compile(lisp_source, to_load.val)) end end if(options.repl) then repl() end end return { run = run, repl = repl, version = version, }
local compiler = require("l2l.compiler") local version = "0.0.2-pre" local loadstring = _G["loadstring"] or _G["load"] local paired_options = {eval=true, load=true, compile=true} local single_options = {repl=true, help=true, version=true} local aliases = {r="repl", e="eval", l="load", c="compile", v="version", h="help", ["?"]="help"} local lookup_alias = function(arg) return aliases[arg] or arg end local trace, err local handler = function(e) trace, err = debug.traceback(2), e end local function repl(partial) if(partial) then io.write("... ") else io.write("> ") end local input = io.read() if(not input) then if(not partial) then return else return repl() end end input = (partial or "") .. input local compiled_ok, src_or_err = pcall(compiler.compile, input, "*repl*") if(compiled_ok) then local vals = {xpcall(loadstring(src_or_err), handler)} if(table.remove(vals, 1)) then for _,val in ipairs(vals) do -- TODO: pretty-print regular tables print(val) end else print(err) print(trace) end else if(src_or_err:find("no bytes$")) then return repl(input) -- partial input else print("Compiler error:", src_or_err) end return repl() end return repl() end local run = function(...) local args, options, next_in = {...}, {} for i,a in ipairs(args) do if(a:sub(1, 1) == "-") then local option_name = lookup_alias(a:gsub("%-", "")) next_in = false if(paired_options[option_name]) then next_in = option_name elseif(single_options[option_name]) then options[option_name] = true else error("Unknown argument: " .. a) end elseif(next_in) then table.insert(options, {how=next_in, val=a}) elseif(i ~= #args) then error("Unknown argument: " .. a) else -- last arg is assumed to be a file table.insert(options, {how="load", val=a}) end end if(#args == 0 or options.help) then print("Welcome to l2l.") print("Usage: l2l [<option> ...] <argument>") print("Options:") print(" -r / --repl open a repl session") print(" -e / --eval FORM evaluate and print a given FORM") print(" -l / --load FILE load a given FILE") print(" -c / --compile FILE print compiled lua for a given FILE") print(" -h / --help print this message and exit") print(" -v / --version print version information and exit") os.exit(0) elseif(options.version) then print("l2l version " .. version) os.exit(0) end for _,to_load in ipairs(options) do if(to_load.how == "eval") then local src = compiler.compile(to_load.val, "*eval*") print(loadstring(src)()) elseif(to_load.how == "load") then local f = assert(io.open(to_load.val), "File not found: " .. to_load.val) local lisp_source = f:read("*all") f:close() local src = compiler.compile(lisp_source, to_load.val) loadstring(src)() elseif(to_load.how == "compile") then local f = assert(io.open(to_load.val), "File not found: " .. to_load.val) local lisp_source = f:read("*all") f:close() print(compiler.compile(lisp_source, to_load.val)) end end if(options.repl) then repl() end end return { run = run, repl = repl, version = version, }
Fix main.lua for 5.2 and 5.3
Fix main.lua for 5.2 and 5.3
Lua
bsd-2-clause
carloscm/l2l,meric/l2l
ca6f28d2a2f1fa2d565a48c5bea435fd8ed654db
mods/eventobjects/init.lua
mods/eventobjects/init.lua
minetest.register_tool("eventobjects:spleef_shovel", { description = "Golden Spleef Shovel", inventory_image = "eventobjects_spleef_shovel.png", wield_image = "eventobjects_spleef_shovel.png^[transformR90", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ unbreakable={times={[1]=0, [2]=0, [3]=0}, uses=0, maxlevel=3}, crumbly = {times={[1]=1.20, [2]=0.60, [3]=0.40}, uses=0, maxlevel=3}, }, damage_groups = {fleshy=4}, }, }) minetest.register_node("eventobjects:surprise_node", { description = "'?' block", inventory_image = minetest.inventorycube("eventobjects_surprise_node.png"), tiles = { "eventobjects_surprise_node_top.png", "eventobjects_surprise_node_top.png", {name = "eventobjects_surprise_node_animated.png", animation={type = "vertical_frames", aspect_w= 16, aspect_h = 16, length = 1.5}} }, special_tiles = { { image = "blocmario.png", backface_culling=false, animation={type = "vertical_frames", aspect_w= 16, aspect_h = 16, length = 0.6} }, { image = "blocmario.png", backface_culling=true, animation={type = "vertical_frames", aspect_w= 16, aspect_h = 16, length = 0.6} } }, groups = {oddly_breakable_by_hand = 2}, on_construct = function(pos) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() meta:set_string("infotext","?") meta:set_string("formspec", "size[11,12]" .. "list[current_name;main;0.45,0.45;10,7;]" .. "list[current_player;main;1.45,8;8,4;]" ) inv:set_size("main",70) end, allow_metadata_inventory_put = function(pos, to_list, to_index, stack, player) if player and minetest.check_player_privs(player:get_player_name(),{server=true}) then return stack:get_count() else return 0 end end, allow_metadata_inventory_take = function(pos, from_list, from_index, stack, player) print(from_list) print(from_index) if player and minetest.check_player_privs(player:get_player_name(),{server=true}) then return stack:get_count() else return 0 end end, on_rightclick = function(pos, node, clicker, itemstack, pointed_thing) end, on_punch = function(pos, node, puncher, pointed_things) -- Spawn betweek 5 and 20 random nodes local meta = minetest.get_meta(pos) local inv = meta:get_inventory() if inv:is_empty("main") then minetest.chat_send_player(puncher:get_player_name(),"Cannot spread items, inventory empty") return end for cnt = 1,70 do local stack = inv:get_stack("main",cnt) if stack:get_name() ~= "" then local obj = minetest.spawn_item({x=pos.x, y = pos.y + 1,z=pos.z},stack) inv:remove_item("main",stack) if obj then obj:setvelocity({x = math.random(-0.4,0.4), y = math.random(2,9), z = math.random(-0.4,0.4)}) end end end minetest.remove_node(pos) end, })
minetest.register_tool("eventobjects:spleef_shovel", { description = "Golden Spleef Shovel", inventory_image = "eventobjects_spleef_shovel.png", wield_image = "eventobjects_spleef_shovel.png^[transformR90", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ unbreakable={times={[1]=0, [2]=0, [3]=0}, uses=0, maxlevel=3}, crumbly = {times={[1]=1.20, [2]=0.60, [3]=0.40}, uses=0, maxlevel=3}, }, damage_groups = {fleshy=4}, }, }) minetest.register_node("eventobjects:surprise_node", { description = "'?' block", inventory_image = minetest.inventorycube("eventobjects_surprise_node.png"), tiles = { "eventobjects_surprise_node_top.png", "eventobjects_surprise_node_top.png", {name = "eventobjects_surprise_node_animated.png", animation={type = "vertical_frames", aspect_w= 16, aspect_h = 16, length = 1.5}} }, special_tiles = { { image = "eventobjects_surprise_node_top.png", backface_culling=false, animation={type = "vertical_frames", aspect_w= 16, aspect_h = 16, length = 0.6} }, { image = "eventobjects_surprise_node_top.png", backface_culling=true, animation={type = "vertical_frames", aspect_w= 16, aspect_h = 16, length = 0.6} } }, groups = {oddly_breakable_by_hand = 2}, on_construct = function(pos) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() meta:set_string("infotext","?") meta:set_string("formspec", "size[11,12]" .. "list[current_name;main;0.45,0.45;10,7;]" .. "list[current_player;main;1.45,8;8,4;]" ) inv:set_size("main",70) end, allow_metadata_inventory_put = function(pos, to_list, to_index, stack, player) if player and minetest.check_player_privs(player:get_player_name(),{server=true}) then return stack:get_count() else return 0 end end, allow_metadata_inventory_take = function(pos, from_list, from_index, stack, player) print(from_list) print(from_index) if player and minetest.check_player_privs(player:get_player_name(),{server=true}) then return stack:get_count() else return 0 end end, on_rightclick = function(pos, node, clicker, itemstack, pointed_thing) end, on_punch = function(pos, node, puncher, pointed_things) -- Spawn betweek 5 and 20 random nodes local meta = minetest.get_meta(pos) local inv = meta:get_inventory() if inv:is_empty("main") then minetest.chat_send_player(puncher:get_player_name(),"Cannot spread items, inventory empty") return end for cnt = 1,70 do local stack = inv:get_stack("main",cnt) if stack:get_name() ~= "" then local obj = minetest.spawn_item({x=pos.x, y = pos.y + 1,z=pos.z},stack) inv:remove_item("main",stack) if obj then obj:setvelocity({x = math.random(-0.4,0.4), y = math.random(2,9), z = math.random(-0.4,0.4)}) end end end minetest.remove_node(pos) end, })
fix wrong name
fix wrong name
Lua
unlicense
LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server
e688a9523f005c340d4d9ed62a93fcc918307e5e
pud/kit/Rect.lua
pud/kit/Rect.lua
local Class = require 'lib.hump.class' local math_floor, math_ceil = math.floor, math.ceil local round = function(x) return math_floor(x + 0.5) end local format = string.format -- Rect -- provides position and size of a rectangle -- Note: coordinates are not floored or rounded and may be floats local Rect = Class{name='Rect', function(self, x, y, w, h) x = x or 0 y = y or 0 w = w or 0 h = h or 0 self:setSize(w, h) self:setPosition(x, y) end } -- destructor function Rect:destroy() self._x = nil self._y = nil self._w = nil self._h = nil end -- get and set position function Rect:getX() return self._x end function Rect:setX(x) verify('number', x) self._x = x end function Rect:getY() return self._y end function Rect:setY(y) verify('number', y) self._y = y end function Rect:getPosition() return self._x, self._y end function Rect:setPosition(x, y) self:setX(x) self:setY(y) end -- valid center adjusment flags local _adjust = { round = function(x) return math_floor(x+0.5) end, floor = function(x) return math_floor(x) end, ceil = function(x) return math_ceil(x) end, default = function(x) return x end, } local _getAdjust = function(flag) flag = flag or 'default' assert(nil ~= _adjust[flag], 'unknown flag for center adjustment (%s)', flag) return _adjust[flag] end -- get and set center coords, rounding to nearest number if requested function Rect:getCenter(flag) local adjust = _getAdjust(flag) local w, h = self:getInnerSize() return self._x + adjust(w/2), self._y + adjust(h/2) end function Rect:setCenter(x, y, flag) local adjust = _getAdjust(flag) local w, h = self:getInnerSize() self:setPosition(x - adjust(w/2), h - adjust(h/2)) end -- get (no set) bounding box coordinates function Rect:getBBox() local w, h = self:getInnerSize() return self._x, self._y, self._x + w, self._y + h end -- check if a point falls within the Rect's bounding box function Rect:containsPoint(x, y) local x1, y1 = self._x, self._y local x2, y2 = x1 + self._w, y1 + self._h return x >= x1 and x <= x2 and y >= y1 and y <= y2 end -- get and set size function Rect:getWidth() return self._w end function Rect:setWidth(w) verify('number', w) self._w = w end function Rect:getHeight() return self._h end function Rect:setHeight(h) verify('number', h) self._h = h end function Rect:getSize() return self._w, self._h end function Rect:setSize(w, h) self:setWidth(w) self:setHeight(h) end -- get the size of the rect for use in center calculations function Rect:getInnerSize() return self:getWidth() - 1, self:getHeight() - 1 end -- clone this rect function Rect:clone() return Rect(self._x, self._y, self._w, self._h) end -- tostring function Rect:__tostring() local x, y = self:getPosition() local w, h = self:getSize() return format('(%f,%f) %fx%f', x,y, w,h) end -- the class return Rect
local Class = require 'lib.hump.class' local math_floor, math_ceil = math.floor, math.ceil local round = function(x) return math_floor(x + 0.5) end local format = string.format -- Rect -- provides position and size of a rectangle -- Note: coordinates are not floored or rounded and may be floats local Rect = Class{name='Rect', function(self, x, y, w, h) x = x or 0 y = y or 0 w = w or 0 h = h or 0 self:setSize(w, h) self:setPosition(x, y) end } -- destructor function Rect:destroy() self._x = nil self._y = nil self._w = nil self._h = nil end -- get and set position function Rect:getX() return self._x end function Rect:setX(x) verify('number', x) self._x = x end function Rect:getY() return self._y end function Rect:setY(y) verify('number', y) self._y = y end function Rect:getPosition() return self._x, self._y end function Rect:setPosition(x, y) self:setX(x) self:setY(y) end -- valid center adjusment flags local _adjust = { round = function(x) return math_floor(x+0.5) end, floor = function(x) return math_floor(x) end, ceil = function(x) return math_ceil(x) end, default = function(x) return x end, } local _getAdjust = function(flag) flag = flag or 'default' assert(nil ~= _adjust[flag], 'unknown flag for center adjustment (%s)', flag) return _adjust[flag] end -- get and set center coords, rounding to nearest number if requested function Rect:getCenter(flag) local adjust = _getAdjust(flag) local w, h = self:getSize() return self._x + adjust((w-1)/2), self._y + adjust((h-1)/2) end function Rect:setCenter(x, y, flag) local adjust = _getAdjust(flag) local w, h = self:getSize() self:setPosition(x - adjust((w-1)/2), y - adjust((h-1)/2)) end -- get (no set) bounding box coordinates function Rect:getBBox() local w, h = self:getSize() return self._x, self._y, self._x + (w-1), self._y + (h-1) end -- check if a point falls within the Rect's bounding box function Rect:containsPoint(x, y) local x1, y1 = self._x, self._y local x2, y2 = x1 + self._w, y1 + self._h return x >= x1 and x <= x2 and y >= y1 and y <= y2 end -- get and set size function Rect:getWidth() return self._w end function Rect:setWidth(w) verify('number', w) self._w = w end function Rect:getHeight() return self._h end function Rect:setHeight(h) verify('number', h) self._h = h end function Rect:getSize() return self._w, self._h end function Rect:setSize(w, h) self:setWidth(w) self:setHeight(h) end -- clone this rect function Rect:clone() return Rect(self._x, self._y, self._w, self._h) end -- tostring function Rect:__tostring() local x, y = self:getPosition() local w, h = self:getSize() return format('(%f,%f) %fx%f', x,y, w,h) end -- the class return Rect
fix rect setCenter
fix rect setCenter
Lua
mit
scottcs/wyx
992d2ee4898106bfa17bb1fb05454fa844e4e953
test/test_record_udf.lua
test/test_record_udf.lua
--[[UDF which performs arithmetic operation on bin containing integer value. --]] function bin_udf_operation_integer(record, bin_name, x, y) record[bin_name] = (record[bin_name] + x) + y if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end return record[bin_name] end --[[UDF which performs concatenation operation on bin containing string. --]] function bin_udf_operation_string(record, bin_name, str) if (type(record[bin_name]) == "string" or type(record[bin_name]) == "number") and (type(str) == "string" or type(str) == "number") then record[bin_name] = record[bin_name] .. str end if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end return record[bin_name] end function bin_udf_operation_bool(record , bin_name) return record[bin_name] end --[[UDF which modifies element of list.--]] function list_iterate(record, bin, index_of_ele) local get_list = record[bin] list.append(get_list, 58) get_list[index_of_ele] = 222; record[bin] = get_list; if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end end --[[UDF which modifies list and returns a list.--]] function list_iterate_returns_list(record, bin, index_of_ele) local get_list = record[bin] list.append(get_list, 58) get_list[index_of_ele] = 222; record[bin] = get_list; if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end return record[bin] end --[[UDF which sets value of each key in the map by set_value which is given by user.--]] function map_iterate(record, bin, set_value) local put_map = record[bin] for key,value in map.pairs(put_map) do put_map[key] = set_value; end record[bin] = put_map; if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end end --[[UDF which sets value of each key in the map by set_value which is given by user, And returns map--]] function map_iterate_returns_map(record, bin, set_value) local put_map = record[bin] for key,value in map.pairs(put_map) do put_map[key] = set_value; end record[bin] = put_map; if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end return record[bin] end --[[UDF which returns a whole record--]] function udf_returns_record(record) return record end --[[UDF which accepts nothing and returns nothing--]] function udf_without_arg_and_return(record) end --[[UDF which will put bytes array in DB.--]] function udf_put_bytes(record, bin) local put_bytes = bytes(18) put_bytes[1] = 10 put_bytes[2] = 85 record[bin] = put_bytes if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end end
--[[UDF which performs arithmetic operation on bin containing integer value. --]] function bin_udf_operation_integer(record, bin_name, x, y) record[bin_name] = (record[bin_name] + x) + y if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end return record[bin_name] end --[[UDF which performs concatenation operation on bin containing string. --]] function bin_udf_operation_string(record, bin_name, str) if (type(record[bin_name]) == "string" or type(record[bin_name]) == "number") and (type(str) == "string" or type(str) == "number") then record[bin_name] = record[bin_name] .. str end if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end return record[bin_name] end function bin_udf_operation_bool(record , bin_name) return record[bin_name] end --[[UDF which modifies element of list.--]] function list_iterate(record, bin, index_of_ele) local get_list = record[bin] list.append(get_list, 58) get_list[index_of_ele] = 222; record[bin] = get_list; if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end end --[[UDF which modifies list and returns a list.--]] function list_iterate_returns_list(record, bin, index_of_ele) local get_list = record[bin] list.append(get_list, 58) get_list[index_of_ele] = 222; record[bin] = get_list; if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end return record[bin] end --[[UDF which sets value of each key in the map by set_value which is given by user.--]] function map_iterate(record, bin, set_value) local put_map = record[bin] for key,value in map.pairs(put_map) do put_map[key] = set_value; end record[bin] = put_map; if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end end --[[UDF which sets value of each key in the map by set_value which is given by user, And returns map--]] function map_iterate_returns_map(record, bin, set_value) local put_map = record[bin] for key,value in map.pairs(put_map) do put_map[key] = set_value; end record[bin] = put_map; if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end return record[bin] end --[[UDF which returns a whole record--]] function udf_returns_record(rec) local mapped = map() for i, bin_name in ipairs(record.bin_names(rec)) do mapped[bin_name] = rec[bin_name]; end return mapped end --[[UDF which accepts nothing and returns nothing--]] function udf_without_arg_and_return(record) end --[[UDF which will put bytes array in DB.--]] function udf_put_bytes(record, bin) local put_bytes = bytes(18) put_bytes[1] = 10 put_bytes[2] = 85 record[bin] = put_bytes if aerospike:exists(record) then aerospike:update(record) else aerospike:create(record) end end
Fixed lua record UDF for test
Fixed lua record UDF for test
Lua
apache-2.0
aerospike/aerospike-client-python,trupty/aerospike-client-python,arthurprs/aerospike-client-python,aerospike/aerospike-client-python,arthurprs/aerospike-client-python,aerospike/aerospike-client-python,arthurprs/aerospike-client-python,trupty/aerospike-client-python,trupty/aerospike-client-python
9270d3e282510ab0841f1f4c43eb53beb2202122
core/hostmanager.lua
core/hostmanager.lua
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local hosts = hosts; local configmanager = require "core.configmanager"; local eventmanager = require "core.eventmanager"; local events_new = require "util.events".new; local log = require "util.logger".init("hostmanager"); local pairs = pairs; module "hostmanager" local hosts_loaded_once; local function load_enabled_hosts(config) local defined_hosts = config or configmanager.getconfig(); for host, host_config in pairs(defined_hosts) do if host ~= "*" and (host_config.core.enabled == nil or host_config.core.enabled) and not host_config.core.component_module then activate(host, host_config); end end eventmanager.fire_event("hosts-activated", defined_hosts); hosts_loaded_once = true; end eventmanager.add_event_hook("server-starting", load_enabled_hosts); function activate(host, host_config) hosts[host] = {type = "local", connected = true, sessions = {}, host = host, s2sout = {}, events = events_new(), disallow_s2s = configmanager.get(host, "core", "disallow_s2s") or (configmanager.get(host, "core", "anonymous_login") and (configmanager.get(host, "core", "disallow_s2s") ~= false)) }; for option_name in pairs(host_config.core) do if option_name:match("_ports$") then log("warn", "%s: Option '%s' has no effect for virtual hosts - put it in global Host \"*\" instead", host, option_name); end end log((hosts_loaded_once and "info") or "debug", "Activated host: %s", host); eventmanager.fire_event("host-activated", host, host_config); end function deactivate(host) local host_session = hosts[host]; log("info", "Deactivating host: %s", host); eventmanager.fire_event("host-deactivating", host, host_session); -- Disconnect local users, s2s connections for user, session_list in pairs(host_session.sessions) do for resource, session in pairs(session_list) do session:close("host-gone"); end end -- Components? hosts[host] = nil; eventmanager.fire_event("host-deactivated", host); log("info", "Deactivated host: %s", host); end function getconfig(name) end
-- Prosody IM -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local ssl = ssl local hosts = hosts; local configmanager = require "core.configmanager"; local eventmanager = require "core.eventmanager"; local events_new = require "util.events".new; -- These are the defaults if not overridden in the config local default_ssl_ctx = { mode = "client", protocol = "sslv23", capath = "/etc/ssl/certs", verify = "none"; }; local log = require "util.logger".init("hostmanager"); local pairs, setmetatable = pairs, setmetatable; module "hostmanager" local hosts_loaded_once; local function load_enabled_hosts(config) local defined_hosts = config or configmanager.getconfig(); for host, host_config in pairs(defined_hosts) do if host ~= "*" and (host_config.core.enabled == nil or host_config.core.enabled) and not host_config.core.component_module then activate(host, host_config); end end eventmanager.fire_event("hosts-activated", defined_hosts); hosts_loaded_once = true; end eventmanager.add_event_hook("server-starting", load_enabled_hosts); function activate(host, host_config) hosts[host] = {type = "local", connected = true, sessions = {}, host = host, s2sout = {}, events = events_new(), disallow_s2s = configmanager.get(host, "core", "disallow_s2s") or (configmanager.get(host, "core", "anonymous_login") and (configmanager.get(host, "core", "disallow_s2s") ~= false)) }; for option_name in pairs(host_config.core) do if option_name:match("_ports$") then log("warn", "%s: Option '%s' has no effect for virtual hosts - put it in global Host \"*\" instead", host, option_name); end end local ssl_config = host_config.core.ssl or configmanager.get("*", "core", "ssl"); if ssl_config then hosts[host].ssl_ctx = ssl.newcontext(setmetatable(ssl_config, { __index = default_ssl_ctx })); end log((hosts_loaded_once and "info") or "debug", "Activated host: %s", host); eventmanager.fire_event("host-activated", host, host_config); end function deactivate(host) local host_session = hosts[host]; log("info", "Deactivating host: %s", host); eventmanager.fire_event("host-deactivating", host, host_session); -- Disconnect local users, s2s connections for user, session_list in pairs(host_session.sessions) do for resource, session in pairs(session_list) do session:close("host-gone"); end end -- Components? hosts[host] = nil; eventmanager.fire_event("host-deactivated", host); log("info", "Deactivated host: %s", host); end function getconfig(name) end
hostmanager: Create ssl context for each host (fixes #30 for outgoing s2s connections)
hostmanager: Create ssl context for each host (fixes #30 for outgoing s2s connections)
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
65425fdf70732a8e1dec071f478099a69f04a66b
lib/luvit/module.lua
lib/luvit/module.lua
--[[ Copyright 2012 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 fs = require('fs') local path = require('path') local table = require('table') local module = {} -- This is the built-in require from lua. module.oldRequire = require local global_meta = {__index=_G} local function partialRealpath(filepath) -- Do some minimal realpathing local link link = fs.lstatSync(filepath).is_symbolic_link and fs.readlinkSync(filepath) while link do filepath = path.resolve(path.dirname(filepath), link) link = fs.lstatSync(filepath).is_symbolic_link and fs.readlinkSync(filepath) end return path.normalize(filepath) end local function myloadfile(filepath) if not fs.existsSync(filepath) then return end filepath = partialRealpath(filepath) if package.loaded[filepath] then return function () return package.loaded[filepath] end end local code = fs.readFileSync(filepath) -- TODO: find out why inlining assert here breaks the require test local fn, err = loadstring(code, '@' .. filepath) assert(fn, err) local dirname = path.dirname(filepath) local realRequire = require setfenv(fn, setmetatable({ __filename = filepath, __dirname = dirname, require = function (filepath) return realRequire(filepath, dirname) end, }, global_meta)) local module = fn() package.loaded[filepath] = module return function() return module end end module.myloadfile = myloadfile local function myloadlib(filepath) if not fs.existsSync(filepath) then return end filepath = partialRealpath(filepath) if package.loaded[filepath] then return function () return package.loaded[filepath] end end local name = path.basename(filepath) if name == "init.luvit" then name = path.basename(path.dirname(filepath)) end local base_name = name:sub(1, #name - 6) package.loaded[filepath] = base_name -- Hook to allow C modules to find their path local fn, error_message = package.loadlib(filepath, "luaopen_" .. base_name) if fn then local module = fn() package.loaded[filepath] = module return function() return module end end error(error_message) end -- tries to load a module at a specified absolute path local function loadModule(filepath, verbose) -- First, look for exact file match if the extension is given local extension = path.extname(filepath) if extension == ".lua" then return myloadfile(filepath) end if extension == ".luvit" then return myloadlib(filepath) end -- Then, look for module/package.lua config file if fs.existsSync(filepath .. "/package.lua") then local metadata = loadModule(filepath .. "/package.lua")() if metadata.main then return loadModule(path.join(filepath, metadata.main)) end end -- Try to load as either lua script or binary extension local fn = myloadfile(filepath .. ".lua") or myloadfile(filepath .. "/init.lua") or myloadlib(filepath .. ".luvit") or myloadlib(filepath .. "/init.luvit") if fn then return fn end return "\n\tCannot find module " .. filepath end -- Remove the cwd based loaders, we don't want them local builtinLoader = package.loaders[1] local base_path = process.cwd() local libpath = process.execPath:match('^(.*)' .. path.sep .. '[^' ..path.sep.. ']+' ..path.sep.. '[^' ..path.sep.. ']+$') ..path.sep.. 'lib' ..path.sep.. 'luvit' ..path.sep function module.require(filepath, dirname) if not dirname then dirname = base_path end -- Absolute and relative required modules local first = filepath:sub(1, 2) local absolute_path if first == "c:" then absolute_path = path.normalize(filepath) elseif first == "." then absolute_path = path.join(dirname, filepath) end if absolute_path then local loader = loadModule(absolute_path) if type(loader) == "function" then return loader() else error("Failed to find module '" .. filepath .."'") end end local errors = {} -- Builtin modules local module = package.loaded[filepath] if module then return module end if filepath:find("^[a-z_]+$") then local loader = builtinLoader(filepath) if type(loader) == "function" then module = loader() package.loaded[filepath] = module return module else errors[#errors + 1] = loader end end -- Library modules local loader = loadModule(libpath .. filepath) if type(loader) == "function" then return loader() else errors[#errors + 1] = loader end -- Bundled path modules local dir = dirname .. path.sep repeat dir = path.dirname(dir) local full_path = path.join(dir, modules, filepath) local loader = loadModule(full_path) if type(loader) == "function" then return loader() else errors[#errors + 1] = loader end until dir == "." error("Failed to find module '" .. filepath .."'" .. table.concat(errors, "")) end package.loaders = nil package.path = nil package.cpath = nil package.searchpath = nil package.seeall = nil package.config = nil _G.module = nil return module
--[[ Copyright 2012 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 fs = require('fs') local path = require('path') local table = require('table') local module = {} -- This is the built-in require from lua. module.oldRequire = require local global_meta = {__index=_G} local function partialRealpath(filepath) -- Do some minimal realpathing local link link = fs.lstatSync(filepath).is_symbolic_link and fs.readlinkSync(filepath) while link do filepath = path.resolve(path.dirname(filepath), link) link = fs.lstatSync(filepath).is_symbolic_link and fs.readlinkSync(filepath) end return path.normalize(filepath) end local function myloadfile(filepath) if not fs.existsSync(filepath) then return end filepath = partialRealpath(filepath) if package.loaded[filepath] then return function () return package.loaded[filepath] end end local code = fs.readFileSync(filepath) -- TODO: find out why inlining assert here breaks the require test local fn, err = loadstring(code, '@' .. filepath) assert(fn, err) local dirname = path.dirname(filepath) local realRequire = require setfenv(fn, setmetatable({ __filename = filepath, __dirname = dirname, require = function (filepath) return realRequire(filepath, dirname) end, }, global_meta)) local module = fn() package.loaded[filepath] = module return function() return module end end module.myloadfile = myloadfile local function myloadlib(filepath) if not fs.existsSync(filepath) then return end filepath = partialRealpath(filepath) if package.loaded[filepath] then return function () return package.loaded[filepath] end end local name = path.basename(filepath) if name == "init.luvit" then name = path.basename(path.dirname(filepath)) end local base_name = name:sub(1, #name - 6) package.loaded[filepath] = base_name -- Hook to allow C modules to find their path local fn, error_message = package.loadlib(filepath, "luaopen_" .. base_name) if fn then local module = fn() package.loaded[filepath] = module return function() return module end end error(error_message) end -- tries to load a module at a specified absolute path local function loadModule(filepath, verbose) -- First, look for exact file match if the extension is given local extension = path.extname(filepath) if extension == ".lua" then return myloadfile(filepath) end if extension == ".luvit" then return myloadlib(filepath) end -- Then, look for module/package.lua config file if fs.existsSync(filepath .. "/package.lua") then local metadata = loadModule(filepath .. "/package.lua")() if metadata.main then return loadModule(path.join(filepath, metadata.main)) end end -- Try to load as either lua script or binary extension local fn = myloadfile(filepath .. ".lua") or myloadfile(filepath .. "/init.lua") or myloadlib(filepath .. ".luvit") or myloadlib(filepath .. "/init.luvit") if fn then return fn end return "\n\tCannot find module " .. filepath end -- Remove the cwd based loaders, we don't want them local builtinLoader = package.loaders[1] local base_path = process.cwd() local libpath = process.execPath:match('^(.*)' .. path.sep .. '[^' ..path.sep.. ']+' ..path.sep.. '[^' ..path.sep.. ']+$') ..path.sep.. 'lib' ..path.sep.. 'luvit' ..path.sep function module.require(filepath, dirname) if not dirname then dirname = base_path end -- Absolute and relative required modules local absolute_path if filepath:sub(1, path.root:len()) == path.root then absolute_path = path.normalize(filepath) elseif filepath:sub(1, 1) == "." then absolute_path = path.join(dirname, filepath) end if absolute_path then local loader = loadModule(absolute_path) if type(loader) == "function" then return loader() else error("Failed to find module '" .. filepath .."'") end end local errors = {} -- Builtin modules local module = package.loaded[filepath] if module then return module end if filepath:find("^[a-z_]+$") then local loader = builtinLoader(filepath) if type(loader) == "function" then module = loader() package.loaded[filepath] = module return module else errors[#errors + 1] = loader end end -- Library modules local loader = loadModule(libpath .. filepath) if type(loader) == "function" then return loader() else errors[#errors + 1] = loader end -- Bundled path modules local dir = dirname .. path.sep repeat dir = path.dirname(dir) local full_path = path.join(dir, modules, filepath) local loader = loadModule(full_path) if type(loader) == "function" then return loader() else errors[#errors + 1] = loader end until dir == "." error("Failed to find module '" .. filepath .."'" .. table.concat(errors, "")) end package.loaders = nil package.path = nil package.cpath = nil package.searchpath = nil package.seeall = nil package.config = nil _G.module = nil return module
FIxup for linux
FIxup for linux
Lua
apache-2.0
kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,boundary/luvit,AndrewTsao/luvit,sousoux/luvit,rjeli/luvit,kaustavha/luvit,sousoux/luvit,sousoux/luvit,luvit/luvit,AndrewTsao/luvit,DBarney/luvit,AndrewTsao/luvit,boundary/luvit,boundary/luvit,zhaozg/luvit,bsn069/luvit,bsn069/luvit,luvit/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,connectFree/lev,sousoux/luvit,connectFree/lev,bsn069/luvit,boundary/luvit,boundary/luvit,rjeli/luvit,GabrielNicolasAvellaneda/luvit-upstream,DBarney/luvit,rjeli/luvit,sousoux/luvit,rjeli/luvit,kaustavha/luvit,DBarney/luvit,GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,zhaozg/luvit
6071fbc74c22ddcf72e0134ed41147ac4467e46c
.vim/lua/pluginconfig/nvim-treesitter.lua
.vim/lua/pluginconfig/nvim-treesitter.lua
require'nvim-treesitter.configs'.setup { ensure_installed = 'all', -- one of 'all', 'language', or a list of languages highlight = { enable = true, -- false will disable the whole extension disable = { }, -- list of language that will be disabled custom_captures = { -- mapping of user defined captures to highlight groups -- ["foo.bar"] = "Identifier" -- highlight own capture @foo.bar with highlight group "Identifier", see :h nvim-treesitter-query-extensions }, }, incremental_selection = { enable = true, disable = { 'cpp', 'lua' }, keymaps = { -- mappings for incremental selection (visual mappings) init_selection = 'gnn', -- maps in normal mode to init the node/scope selection node_incremental = "grn", -- increment to the upper named parent scope_incremental = "grc", -- increment to the upper scope (as defined in locals.scm) node_decremental = "grm", -- decrement to the previous node } }, refactor = { highlight_definitions = { enable = true }, highlight_current_scope = { enable = false }, smart_rename = { enable = true, keymaps = { smart_rename = "grr" -- mapping to rename reference under cursor } }, navigation = { enable = true, keymaps = { goto_definition = "gnd", -- mapping to go to definition of symbol under cursor list_definitions = "gnD" -- mapping to list all definitions in current file } } }, textobjects = { -- syntax-aware textobjects select = { enable = true, disable = {}, keymaps = { ["af"] = "@function.outer", ["if"] = "@function.inner", ["ac"] = "@class.outer", ["ic"] = "@class.inner", ["ib"] = "@block.inner", ["ab"] = "@block.outer", -- ["i"] = "@call.inner", -- ["a"] = "@call.outer", -- ["a"] = "@comment.outer", ["iC"] = "@conditional.inner", ["aC"] = "@conditional.outer", ["iL"] = "@loop.inner", ["aL"] = "@loop.outer", ["iP"] = "@parameter.inner", ["aP"] = "@parameter.outer", ["as"] = "@statement.outer", ["iF"] = { python = "(function_definition) @function", cpp = "(function_definition) @function", c = "(function_definition) @function", java = "(method_declaration) @function", }, }, }, swap = { enable = true, swap_next = { ["<leader>a"] = "@parameter.inner", }, swap_previous = { ["<leader>A"] = "@parameter.inner", }, }, move = { enable = true, goto_next_start = { ["]m"] = "@function.outer", ["]]"] = "@class.outer", }, goto_next_end = { ["]M"] = "@function.outer", ["]["] = "@class.outer", }, goto_previous_start = { ["[m"] = "@function.outer", ["[["] = "@class.outer", }, goto_previous_end = { ["[M"] = "@function.outer", ["[]"] = "@class.outer", }, }, }, rainbow = { enable = true, disable = {'lua', 'bash'} -- please disable lua and bash for now }, }
require'nvim-treesitter.configs'.setup { ensure_installed = 'all', -- one of 'all', 'language', or a list of languages highlight = { enable = true, -- false will disable the whole extension disable = {}, -- list of language that will be disabled custom_captures = { -- mapping of user defined captures to highlight groups -- ["foo.bar"] = "Identifier" -- highlight own capture @foo.bar with highlight group "Identifier", see :h nvim-treesitter-query-extensions } }, incremental_selection = { enable = true, disable = {'cpp', 'lua'}, keymaps = { -- mappings for incremental selection (visual mappings) init_selection = 'gnn', -- maps in normal mode to init the node/scope selection node_incremental = "grn", -- increment to the upper named parent scope_incremental = "grc", -- increment to the upper scope (as defined in locals.scm) node_decremental = "grm" -- decrement to the previous node } }, refactor = { highlight_definitions = {enable = true}, highlight_current_scope = {enable = false}, smart_rename = { enable = true, keymaps = { smart_rename = "grr" -- mapping to rename reference under cursor } }, navigation = { enable = true, keymaps = { goto_definition = "gnd", -- mapping to go to definition of symbol under cursor list_definitions = "gnD" -- mapping to list all definitions in current file } } }, textobjects = { -- syntax-aware textobjects select = { enable = true, disable = {}, keymaps = { ["af"] = "@function.outer", ["if"] = "@function.inner", ["ac"] = "@class.outer", ["ic"] = "@class.inner", ["ib"] = "@block.inner", ["ab"] = "@block.outer", -- ["i"] = "@call.inner", -- ["a"] = "@call.outer", -- ["a"] = "@comment.outer", ["iC"] = "@conditional.inner", ["aC"] = "@conditional.outer", ["iL"] = "@loop.inner", ["aL"] = "@loop.outer", ["iP"] = "@parameter.inner", ["aP"] = "@parameter.outer", ["as"] = "@statement.outer", ["iF"] = { python = "(function_definition) @function", cpp = "(function_definition) @function", c = "(function_definition) @function", java = "(method_declaration) @function" } } }, swap = { enable = true, swap_next = {["<leader>a"] = "@parameter.inner"}, swap_previous = {["<leader>A"] = "@parameter.inner"} }, move = { enable = true, goto_next_start = {["]m"] = "@function.outer", ["]]"] = "@class.outer"}, goto_next_end = {["]M"] = "@function.outer", ["]["] = "@class.outer"}, goto_previous_start = { ["[m"] = "@function.outer", ["[["] = "@class.outer" }, goto_previous_end = {["[M"] = "@function.outer", ["[]"] = "@class.outer"} } }, rainbow = { enable = true, disable = {'lua', 'bash'} -- please disable lua and bash for now } }
vim: Fix format
vim: Fix format
Lua
mit
yutakatay/dotfiles,yutakatay/dotfiles
c1d415c7c06a2cacf4d52a1af1b92016893cb1f3
libs/base64.lua
libs/base64.lua
--------------------------------------------------------- --- base64 library in pure lua --- credits go to the original creator --------------------------------------------------------- -- Luvit libraries local string = require('string') --------------------------------------------------------- --- START ORIGINAL --------------------------------------------------------- -- Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss <alexthkloss@web.de> -- licensed under the terms of the LGPL2 local base64 = {} -- character table string local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -- encoding base64.encode = function(data) return ((data:gsub('.', function(x) local r,b='',x:byte() for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end return r; end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x) if (#x < 6) then return '' end local c=0 for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end return b:sub(c+1,c+1) end)..({ '', '==', '=' })[#data%3+1]) end -- decoding base64.decode = function(data) data = string.gsub(data, '[^'..b..'=]', '') return (data:gsub('.', function(x) if (x == '=') then return '' end local r,f='',(b:find(x)-1) for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end return r; end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x) if (#x ~= 8) then return '' end local c=0 for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end return string.char(c) end)) end --------------------------------------------------------- --- END ORIGINAL --------------------------------------------------------- local tableStuff = function(direction) local f = function(t) local newt = {} if type(t) == "table" then for k,v in pairs(t) do if type(v) == "string" or type(v) == "number" or type(v) == "bool" then newt[base64[direction](tostring(k))] = base64[direction](tostring(v)) elseif type(v) == "table" then newt[base64[direction](tostring(k))] = f(v) end end end return newt end return f end exports.encodeTable = tableStuff("encode") exports.decodeTable = tableStuff("decode") exports.encode = base64.encode exports.decode = base64.decode exports.name = "base64" exports.version = "v3.0" exports.author = "Alex Kloss"
--------------------------------------------------------- --- base64 library in pure lua --- credits go to the original creator --------------------------------------------------------- -- Luvit libraries local string = require('string') --------------------------------------------------------- --- START ORIGINAL --------------------------------------------------------- -- Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss <alexthkloss@web.de> -- licensed under the terms of the LGPL2 local base64 = {} -- character table string local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -- encoding base64.encode = function(data) return ((data:gsub('.', function(x) local r,b='',x:byte() for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end return r; end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x) if (#x < 6) then return '' end local c=0 for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end return b:sub(c+1,c+1) end)..({ '', '==', '=' })[#data%3+1]) end -- decoding base64.decode = function(data) data = string.gsub(data, '[^'..b..'=]', '') return (data:gsub('.', function(x) if (x == '=') then return '' end local r,f='',(b:find(x)-1) for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end return r; end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x) if (#x ~= 8) then return '' end local c=0 for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end return string.char(c) end)) end --------------------------------------------------------- --- END ORIGINAL --------------------------------------------------------- local funcs = {} local tableStuff = function(direction) funcs[direction] = function(t) local newt = {} if type(t) == "table" then for k,v in pairs(t) do if type(v) == "string" or type(v) == "number" or type(v) == "bool" then newt[base64[direction](tostring(k))] = base64[direction](tostring(v)) elseif type(v) == "table" then newt[base64[direction](tostring(k))] = funcs[direction](v) end end end return newt end return funcs[direction] end exports.encodeTable = tableStuff("encode") exports.decodeTable = tableStuff("decode") exports.encode = base64.encode exports.decode = base64.decode exports.name = "base64" exports.version = "v3.0" exports.author = "Alex Kloss"
Fixed recursion in curried function.
Fixed recursion in curried function.
Lua
mit
b42nk/LuvSocks,b42nk/LuvSocks
2e46ee9c63350049422e0f855b3d978d23cd7f59
lua/autorun/sbep_global.lua
lua/autorun/sbep_global.lua
-- -- Created by IntelliJ IDEA. -- User: Sam Elmer (Selekton99) -- Date: 27/11/12 -- Time: 11:08 AM -- Last Updated : -- if SERVER then CreateConVar("sv_sbep_debug", 0, FCVAR_SERVER_CAN_EXECUTE, "Enable Debug Messages for the Server") elseif CLIENT then CreateClientConVar("cl_sbep_debug", 0, true, false ) end function DebugMessage( Message ) if CLIENT then if (GetConVar( "cl_sbep_debug" ):GetInt() == 1 ) then print("SBEP Debug (CL): "..Message.."\n") end elseif SERVER then if (GetConVar( "sv_sbep_debug" ):GetInt() == 1) then print("SBEP Debug (SV): "..Message.."\n") --Send Umsg containing errors to SuperAdmins, Admins and Sam Elmer (SteamID) end end end
-- -- Created by IntelliJ IDEA. -- User: Sam Elmer (Selekton99) -- Date: 27/11/12 -- Time: 11:08 AM -- Last Updated : -- SBEP = SBEP or {} --Version: SBEP.Version = "\"1.0.1\"" if SERVER then CreateConVar("sv_sbep_debug", 0, FCVAR_SERVER_CAN_EXECUTE, "Enable Debug Messages for the Server") elseif CLIENT then CreateClientConVar("cl_sbep_debug", 0, true, false ) end function DebugMessage( Message ) if CLIENT then if (GetConVar( "cl_sbep_debug" ):GetInt() == 1 ) then print("SBEP Debug (CL): "..Message.."\n") end elseif SERVER then if (GetConVar( "sv_sbep_debug" ):GetInt() == 1) then print("SBEP Debug (SV): "..Message.."\n") --Send Umsg containing errors to SuperAdmins, Admins and Sam Elmer (SteamID) end end end
Fixed Versioning System. Not going to bother with a new version number considering they weren't working til now.
Fixed Versioning System. Not going to bother with a new version number considering they weren't working til now.
Lua
apache-2.0
SnakeSVx/sbep
ec7791b5ec5a63644d4028841c376c763b4c34d1
lunamark/parser/generic.lua
lunamark/parser/generic.lua
module(..., package.seeall) local lpeg = require "lpeg" local util = require "lunamark.util" local c = lpeg.C local _ = lpeg.V local p = lpeg.P local r = lpeg.R spacechar = lpeg.S("\t ") newline = p"\r"^-1 * p"\n" nonspacechar = p(1) - (spacechar + newline) sp = spacechar^0 space = spacechar^1 eof = -p(1) nonindentspace = (p" ")^-3 blankline = sp * c(newline) skipblanklines = (sp * newline)^0 linechar = p(1 - newline) indent = p" " + (nonindentspace * p"\t") / "" indentedline = indent * c(linechar^1 * (newline + eof)) optionallyindentedline = indent^-1 * c(linechar^1 * (newline + eof)) spnl = sp * (newline * sp)^-1 specialchar = lpeg.S("*_`*&[]<!\\") normalchar = p(1) - (specialchar + spacechar + newline) alphanumeric = lpeg.R("AZ","az","09") line = c((p(1) - newline)^0 * newline) + c(p(1)^1 * eof) nonemptyline = (p(1) - newline)^1 * newline quoted = function(open, close) return (p(open) * c((p(1) - (blankline + p(close)))^0) * p(close)) end htmlattributevalue = (quoted("'","'") + quoted("\"","\"")) + (p(1) - lpeg.S("\t >"))^1 htmlattribute = (alphanumeric + lpeg.S("_-"))^1 * spnl * (p"=" * spnl * htmlattributevalue)^-1 * spnl htmlcomment = p"<!--" * (p(1) - p"-->")^0 * p"-->" htmltag = p"<" * spnl * p"/"^-1 * alphanumeric^1 * spnl * htmlattribute^0 * p"/"^-1 * spnl * p">" lineof = function(c) return (nonindentspace * (p(c) * sp)^3 * newline * blankline^1) end bullet = nonindentspace * (p"+" + (p"*" - lineof"*") + (p"-" - lineof"-")) * space enumerator = nonindentspace * r"09"^1 * p"." * space openticks = lpeg.Cg(p"`"^1, "ticks") closeticks = sp * lpeg.Cmt(c(p"`"^1) * lpeg.Cb("ticks"), function(s,i,a,b) return string.len(a) == string.len(b) and i end) inticks = openticks * sp * c((p(1) - (blankline + closeticks))^1) * closeticks blocktags = { address = true, blockquote = true, center = true, dir = true, div = true, dl = true, fieldset = true, form = true, h1 = true, h2 = true, h3 = true, h4 = true, h5 = true, h6 = true, hr = true, isindex = true, menu = true, noframes = true, noscript = true, ol = true, p = true, pre = true, table = true, ul = true, dd = true, ht = true, frameset = true, li = true, tbody = true, td = true, tfoot = true, th = true, thead = true, tr = true, script = true } blocktag = lpeg.Cmt(c(alphanumeric^1), function(s,i,a) return blocktags[string.lower(a)] and i, a end) openblocktag = p"<" * spnl * lpeg.Cg(blocktag, "opentag") * spnl * htmlattribute^0 * p">" closeblocktag = p"<" * spnl * p"/" * lpeg.Cmt(c(alphanumeric^1) * lpeg.Cb("opentag"), function(s,i,a,b) return string.lower(a) == string.lower(b) and i end) * spnl * p">" selfclosingblocktag = p"<" * spnl * p"/"^-1 * blocktag * spnl * htmlattribute^0 * p"/" * spnl * p">" choice = function(parsers) local res = lpeg.S""; for k,p in pairs(parsers) do res = res + p end; return res end -- yields a blank line unless we're at the beginning of the document interblockspace = lpeg.Cmt(blankline^0, function(s,i) if i == 1 then return i, "" else return i, "\n" end end)
module(..., package.seeall) local lpeg = require "lpeg" local util = require "lunamark.util" local c = lpeg.C local _ = lpeg.V local p = lpeg.P local r = lpeg.R spacechar = lpeg.S("\t ") newline = p"\r"^-1 * p"\n" nonspacechar = p(1) - (spacechar + newline) sp = spacechar^0 space = spacechar^1 eof = -p(1) nonindentspace = (p" ")^-3 blankline = sp * c(newline) skipblanklines = (sp * newline)^0 linechar = p(1 - newline) indent = p" " + (nonindentspace * p"\t") / "" indentedline = indent * c(linechar^1 * (newline + eof)) optionallyindentedline = indent^-1 * c(linechar^1 * (newline + eof)) spnl = sp * (newline * sp)^-1 specialchar = lpeg.S("*_`*&[]<!\\") normalchar = p(1) - (specialchar + spacechar + newline) alphanumeric = lpeg.R("AZ","az","09") line = c((p(1) - newline)^0 * newline) + c(p(1)^1 * eof) nonemptyline = (p(1) - newline)^1 * newline quoted = function(open, close) return (p(open) * c((p(1) - (blankline + p(close)))^0) * p(close)) end htmlattributevalue = (quoted("'","'") + quoted("\"","\"")) + (p(1) - lpeg.S("\t >"))^1 htmlattribute = (alphanumeric + lpeg.S("_-"))^1 * spnl * (p"=" * spnl * htmlattributevalue)^-1 * spnl htmlcomment = p"<!--" * (p(1) - p"-->")^0 * p"-->" htmltag = p"<" * spnl * p"/"^-1 * alphanumeric^1 * spnl * htmlattribute^0 * p"/"^-1 * spnl * p">" lineof = function(c) return (nonindentspace * (p(c) * sp)^3 * newline * blankline^1) end bullet = nonindentspace * (p"+" + (p"*" - lineof"*") + (p"-" - lineof"-")) * space enumerator = nonindentspace * r"09"^1 * p"." * space openticks = lpeg.Cg(p"`"^1, "ticks") closeticks = p" "^-1 * lpeg.Cmt(c(p"`"^1) * lpeg.Cb("ticks"), function(s,i,a,b) return string.len(a) == string.len(b) and i end) intickschar = (p(1) - lpeg.S(" \n\r`")) + (newline * -blankline) + (p" " - closeticks) + (p("`")^1 - closeticks) inticks = openticks * p(" ")^-1 * c(intickschar^1) * closeticks blocktags = { address = true, blockquote = true, center = true, dir = true, div = true, dl = true, fieldset = true, form = true, h1 = true, h2 = true, h3 = true, h4 = true, h5 = true, h6 = true, hr = true, isindex = true, menu = true, noframes = true, noscript = true, ol = true, p = true, pre = true, table = true, ul = true, dd = true, ht = true, frameset = true, li = true, tbody = true, td = true, tfoot = true, th = true, thead = true, tr = true, script = true } blocktag = lpeg.Cmt(c(alphanumeric^1), function(s,i,a) return blocktags[string.lower(a)] and i, a end) openblocktag = p"<" * spnl * lpeg.Cg(blocktag, "opentag") * spnl * htmlattribute^0 * p">" closeblocktag = p"<" * spnl * p"/" * lpeg.Cmt(c(alphanumeric^1) * lpeg.Cb("opentag"), function(s,i,a,b) return string.lower(a) == string.lower(b) and i end) * spnl * p">" selfclosingblocktag = p"<" * spnl * p"/"^-1 * blocktag * spnl * htmlattribute^0 * p"/" * spnl * p">" choice = function(parsers) local res = lpeg.S""; for k,p in pairs(parsers) do res = res + p end; return res end -- yields a blank line unless we're at the beginning of the document interblockspace = lpeg.Cmt(blankline^0, function(s,i) if i == 1 then return i, "" else return i, "\n" end end)
Fixed bug in inline code spans.
Fixed bug in inline code spans. Test case: ``hi ``` there``.
Lua
mit
simoncozens/lunamark,simoncozens/lunamark,jgm/lunamark,jgm/lunamark,simoncozens/lunamark,jgm/lunamark,tst2005/lunamark,tst2005/lunamark,tst2005/lunamark
6d3e45a67a7d596a7ee26a7572e5c6b428085d3c
shared/file.lua
shared/file.lua
local IsWindows = false os.fs.name = {} if iguana.workingDir():find('\\') then IsWindows = true end function os.fs.dirExists(Path) Path = os.fs.name.toNative(Path) return os.fs.access(Path,'r') end function os.fs.addDir(Dir) if Dir:sub(#Dir) ~= '/' then return Dir..'/' end return Dir end function os.isWindows() return IsWindows end function os.fs.dirSep() return DirSep end function string.addDir(S) return os.fs.addDir(S) end function os.fs.name.toNative(Path) local FilePath = os.fs.abspath(Path) if os.isWindows() then FilePath = FilePath:gsub("/", "\\") end return FilePath end function os.fs.name.fromNative(Path) return Path:gsub("\\", "/") end local FileOpen = io.open function io.open(FileName, Mode) FileName = os.fs.name.toNative(FileName) local Success, Result, ErrMessage = pcall(FileOpen, FileName, Mode) if Success then return Result, ErrMessage else error(Result, 1) end end function os.fs.tempDir() local Name = os.getenv('TEMP') if not Name then Name = os.getenv('TMPDIR') end return os.fs.name.fromNative(Name):addDir() end function os.fs.writeFile(Name, Content) Name = os.fs.abspath(Name) local Parts = Name:split('/') local Dir = '' for i = 1, #Parts-1 do Dir = Dir..Parts[i]..'/' trace(Dir) if not os.fs.dirExists(Dir) then os.fs.mkdir(Dir) end end os.fs.access(Name, 'w') local F, Err = io.open(Name, "wb+") if not F then error("Unable to write to "..Err) end F:write(Content) F:close() end function os.fs.readFile(Name) local F = io.open(Name, "rb") local Content = F:read('*a') F:close(); return Content; end function os.fs.cleanDir(Dir, List) if not os.fs.dirExists(Dir) then return false end local LocalList = {} for Name,Info in os.fs.glob(os.fs.name.toNative(Dir:addDir())..'*') do trace(Name,Info) LocalList[Name] = Info if (Info.isdir) then os.fs.cleanDir(Name) end end trace(LocalList) for K, V in pairs(LocalList) do if V.isdir then os.fs.rmdir(K) else os.remove(K) end end end local function ConvertProcessLine(T) local Dir = os.fs.name.toNative(T.dir) local Command = T.command local Args = T.arguments local CmdString = '' if os.isWindows() then if iguana.workingDir():sub(1,2) ~= Dir:sub(1,2) then CmdString = Dir:sub(1,2).." && " end end CmdString = CmdString..'cd '..Dir..' && '..Command..' '..Args return CmdString end local OsExecute = os.execute function os.execute(T) local CmdString = ConvertProcessLine(T) return OsExecute(CmdString) end local POpen = io.popen function io.popen(T) local CmdLine = ConvertProcessLine(T) return POpen(CmdLine, T.mode), CmdLine end local WorkingDir=iguana.workingDir():gsub('\\', '/') function iguana.workingDir() return WorkingDir end local AbsPath = os.fs.abspath function os.fs.abspath(Path) return AbsPath(Path):gsub('\\','/') end local Access = os.fs.access function os.fs.access(Path) if os.isWindows() then Path = Path:gsub('/', '\\') end return Access(Path) end Glob = os.fs.glob function os.fs.glob(Path) Path = os.fs.name.toNative(Path) local GlobFunction = Glob(Path) return function(K,V) local A, B; A, B = GlobFunction(K,V); if (A) then return os.fs.name.fromNative(A), B else return nil end end end
local IsWindows = false os.fs.name = {} if iguana.workingDir():find('\\') then IsWindows = true end function os.fs.dirExists(Path) Path = os.fs.name.toNative(Path) return os.fs.access(Path,'r') end function os.fs.addDir(Dir) if Dir:sub(#Dir) ~= '/' then return Dir..'/' end return Dir end function os.isWindows() return IsWindows end function os.fs.dirSep() return DirSep end function string.addDir(S) return os.fs.addDir(S) end function os.fs.name.toNative(Path) local FilePath = os.fs.abspath(Path) if os.isWindows() then FilePath = FilePath:gsub("/", "\\") end return FilePath end function os.fs.name.fromNative(Path) return Path:gsub("\\", "/") end local FileOpen = io.open function io.open(FileName, Mode) FileName = os.fs.name.toNative(FileName) local Success, Result, ErrMessage = pcall(FileOpen, FileName, Mode) if Success then return Result, ErrMessage else error(Result, 1) end end function os.fs.tempDir() local Name = os.getenv('TEMP') if not Name then Name = os.getenv('TMPDIR') end return os.fs.name.fromNative(Name):addDir() end function os.fs.writeFile(Name, Content) Name = os.fs.abspath(Name) local Parts = Name:split('/') local Dir = '' for i = 1, #Parts-1 do Dir = Dir..Parts[i]..'/' trace(Dir) if not os.fs.dirExists(Dir) then os.fs.mkdir(Dir) end end os.fs.access(Name, 'w') local F, Err = io.open(Name, "wb+") if not F then error("Unable to write to "..Err) end F:write(Content) F:close() end function os.fs.readFile(Name) local F = io.open(Name, "rb") local Content = F:read('*a') F:close(); return Content; end function os.fs.cleanDir(Dir, List) if not os.fs.dirExists(Dir) then return false end local LocalList = {} for Name,Info in os.fs.glob(os.fs.name.toNative(Dir:addDir())..'*') do trace(Name,Info) LocalList[Name] = Info if (Info.isdir) then os.fs.cleanDir(Name) end end trace(LocalList) for K, V in pairs(LocalList) do if V.isdir then os.fs.rmdir(K) else os.remove(K) end end end local function ConvertProcessLine(T) local Dir = os.fs.name.toNative(T.dir) local Command = T.command local Args = T.arguments local CmdString = '' if os.isWindows() then if iguana.workingDir():sub(1,2) ~= Dir:sub(1,2) then CmdString = Dir:sub(1,2).." && " end end CmdString = CmdString..'cd '..Dir..' && '..Command..' '..Args return CmdString end local OsExecute = os.execute function os.execute(T) local CmdString = ConvertProcessLine(T) return OsExecute(CmdString) end local POpen = io.popen function io.popen(T) local CmdLine = ConvertProcessLine(T) return POpen(CmdLine, T.mode), CmdLine end local WorkingDir=iguana.workingDir():gsub('\\', '/') function iguana.workingDir() return WorkingDir end local AbsPath = os.fs.abspath function os.fs.abspath(Path) return AbsPath(Path):gsub('\\','/') end local Access = os.fs.access function os.fs.access(Path) Path = os.fs.name.toNative(Path) return Access(Path) end Glob = os.fs.glob function os.fs.glob(Path) Path = os.fs.name.toNative(Path) local GlobFunction = Glob(Path) return function(K,V) local A, B; A, B = GlobFunction(K,V); if (A) then return os.fs.name.fromNative(A), B else return nil end end end Chmod = os.fs.chmod function os.fs.chmod(Path, Permission) Path = os.fs.name.toNative(Path) Chmod(Path, Permission) end
Added os.fs.chmod to non native file abstraction.
Added os.fs.chmod to non native file abstraction. Fixed non existent problem with os.fs.access - I think the png files were in fact damaged.
Lua
mit
interfaceware/iguana-web-apps,interfaceware/iguana-web-apps
7c9a6bdb7ed491168bf4e444ff7c7e7ea011e274
src/plugins/finalcutpro/midi/controls/colorwheels.lua
src/plugins/finalcutpro/midi/controls/colorwheels.lua
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- M I D I C O N T R O L S -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === plugins.finalcutpro.midi.controls.colorwheels === --- --- Final Cut Pro MIDI Color Controls. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Logger: -------------------------------------------------------------------------------- local log = require("hs.logger").new("colorMIDI") -------------------------------------------------------------------------------- -- Hammerspoon Extensions: -------------------------------------------------------------------------------- local eventtap = require("hs.eventtap") local inspect = require("hs.inspect") -------------------------------------------------------------------------------- -- CommandPost Extensions: -------------------------------------------------------------------------------- local fcp = require("cp.apple.finalcutpro") local tools = require("cp.tools") -------------------------------------------------------------------------------- -- Local Lua Functions: -------------------------------------------------------------------------------- local round = tools.round local upper, format = string.upper, string.format -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} -- shiftPressed() -> boolean -- Function -- Is the Shift Key being pressed? -- -- Parameters: -- * None -- -- Returns: -- * `true` if the shift key is being pressed, otherwise `false`. local function shiftPressed() -------------------------------------------------------------------------------- -- Check for keyboard modifiers: -------------------------------------------------------------------------------- local mods = eventtap.checkKeyboardModifiers() local result = false if mods['shift'] and not mods['cmd'] and not mods['alt'] and not mods['ctrl'] and not mods['capslock'] and not mods['fn'] then result = true end return result end -------------------------------------------------------------------------------- -- MIDI Controller Value (7bit): 0 to 127 -- MIDI Controller Value (14bit): 0 to 16383 -- -- Percentage Slider: -100 to 100 -- Angle Slider: 0 to 360 (359 in Final Cut Pro 10.4) -- -- Wheel Color Orientation -1 to 1 -------------------------------------------------------------------------------- local ZERO_14BIT = 16383/2 -- < THIS IS MAYBE WRONG? local UNSHIFTED_14BIT = 16383*200-100 -- < THIS IS WRONG local ZERO_7BIT = 127/2 -- < THIS IS MAYBE WRONG? local SHIFTED_7BIT = 128*202-100 -- < THIS IS WRONG local UNSHIFTED_7BIT = 128*128-(128/2) -- < THIS IS WRONG -- makeWheelHandler(puckFinderFn) -> function -- Function -- Creates a 'handler' for wheel controls, applying them to the puck returned by the `puckFinderFn` -- -- Parameters: -- * puckFinderFn - a function that will return the `ColorPuck` to apply the percentage value to. -- -- Returns: -- * a function that will receive the MIDI control metadata table and process it. local function makeWheelHandler(wheelFinderFn, vertical) return function(metadata) --log.df("Doing stuff: %s", hs.inspect(metadata)) log.df("-----------------------") local midiValue, value local wheel = wheelFinderFn() if metadata.fourteenBitCommand or metadata.pitchChange then -------------------------------------------------------------------------------- -- 14bit: -------------------------------------------------------------------------------- log.df("14bit") midiValue = metadata.pitchChange or metadata.fourteenBitValue if type(midiValue) == "number" then value = midiValue == ZERO_14BIT and 0 or round(midiValue / UNSHIFTED_14BIT) end else -------------------------------------------------------------------------------- -- 7bit: -------------------------------------------------------------------------------- log.df("7bit") midiValue = metadata.controllerValue if type(midiValue) == "number" then value = midiValue == ZERO_7BIT and 0 or midiValue / (shiftPressed() and SHIFTED_7BIT or UNSHIFTED_7BIT) end end if value == nil then log.ef("Unexpected MIDI value of type '%s': %s", type(midiValue), inspect(midiValue)) end log.df("value: %s", value) local current = wheel:colorOrientation() if current then if vertical then log.df("vertical: %s", wheel:colorOrientation()) wheel:colorOrientation({right=current.right,up=value}) else log.df("horizontal") wheel:colorOrientation({right=value,up=current.up}) end end end end --- plugins.finalcutpro.midi.controls.colorwheels.init() -> nil --- Function --- Initialise the module. --- --- Parameters: --- * None --- --- Returns: --- * None function mod.init(deps) deps.manager.controls:new("masterHorizontal", { group = "fcpx", text = "Color Wheel: Master (Horizontal)", subText = "Controls the Final Cut Pro Color Wheel via a MIDI Knob or Slider", fn = makeWheelHandler(function() return fcp:inspector():color():colorWheels():master() end, false), }) return mod end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "finalcutpro.midi.controls.colorwheels", group = "finalcutpro", dependencies = { ["core.midi.manager"] = "manager", } } -------------------------------------------------------------------------------- -- INITIALISE PLUGIN: -------------------------------------------------------------------------------- function plugin.init(deps) return mod.init(deps) end return plugin
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- M I D I C O N T R O L S -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === plugins.finalcutpro.midi.controls.colorwheels === --- --- Final Cut Pro MIDI Color Controls. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Logger: -------------------------------------------------------------------------------- local log = require("hs.logger").new("colorMIDI") -------------------------------------------------------------------------------- -- Hammerspoon Extensions: -------------------------------------------------------------------------------- local eventtap = require("hs.eventtap") local inspect = require("hs.inspect") -------------------------------------------------------------------------------- -- CommandPost Extensions: -------------------------------------------------------------------------------- local fcp = require("cp.apple.finalcutpro") local tools = require("cp.tools") -------------------------------------------------------------------------------- -- Local Lua Functions: -------------------------------------------------------------------------------- local round = tools.round local upper, format = string.upper, string.format -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} -- shiftPressed() -> boolean -- Function -- Is the Shift Key being pressed? -- -- Parameters: -- * None -- -- Returns: -- * `true` if the shift key is being pressed, otherwise `false`. local function shiftPressed() -------------------------------------------------------------------------------- -- Check for keyboard modifiers: -------------------------------------------------------------------------------- local mods = eventtap.checkKeyboardModifiers() local result = false if mods['shift'] and not mods['cmd'] and not mods['alt'] and not mods['ctrl'] and not mods['capslock'] and not mods['fn'] then result = true end return result end -------------------------------------------------------------------------------- -- MIDI Controller Value (7bit): 0 to 127 -- MIDI Controller Value (14bit): 0 to 16383 -- -- Percentage Slider: -100 to 100 -- Angle Slider: 0 to 360 (359 in Final Cut Pro 10.4) -- -- Wheel Color Orientation -1 to 1 -------------------------------------------------------------------------------- local MAX_14BIT = 0x3FFF -- 16383 local MAX_7BIT = 0x7F -- 127 -- makeWheelHandler(puckFinderFn) -> function -- Function -- Creates a 'handler' for wheel controls, applying them to the puck returned by the `puckFinderFn` -- -- Parameters: -- * puckFinderFn - a function that will return the `ColorPuck` to apply the percentage value to. -- -- Returns: -- * a function that will receive the MIDI control metadata table and process it. local function makeWheelHandler(wheelFinderFn, vertical) return function(metadata) --log.df("Doing stuff: %s", hs.inspect(metadata)) log.df("-----------------------") local midiValue, value local wheel = wheelFinderFn() if metadata.fourteenBitCommand or metadata.pitchChange then -------------------------------------------------------------------------------- -- 14bit: -------------------------------------------------------------------------------- log.df("14bit") midiValue = metadata.pitchChange or metadata.fourteenBitValue if type(midiValue) == "number" then value = (midiValue / MAX_14BIT) * 2 - 1 end else -------------------------------------------------------------------------------- -- 7bit: -------------------------------------------------------------------------------- log.df("7bit") midiValue = metadata.controllerValue if type(midiValue) == "number" then local pct = (midiValue / MAX_7BIT) if shiftPressed() then value = pct * 2 - 1 else value = pct - 0.5 -- picked a scale of 50% end end end if value == nil then log.ef("Unexpected MIDI value of type '%s': %s", type(midiValue), inspect(midiValue)) end log.df("value: %s", value) local current = wheel:colorOrientation() if current then if vertical then log.df("vertical: %s", wheel:colorOrientation()) wheel:colorOrientation({right=current.right,up=value}) else log.df("horizontal") wheel:colorOrientation({right=value,up=current.up}) end end end end --- plugins.finalcutpro.midi.controls.colorwheels.init() -> nil --- Function --- Initialise the module. --- --- Parameters: --- * None --- --- Returns: --- * None function mod.init(deps) deps.manager.controls:new("masterHorizontal", { group = "fcpx", text = "Color Wheel: Master (Horizontal)", subText = "Controls the Final Cut Pro Color Wheel via a MIDI Knob or Slider", fn = makeWheelHandler(function() return fcp:inspector():color():colorWheels():master() end, false), }) return mod end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "finalcutpro.midi.controls.colorwheels", group = "finalcutpro", dependencies = { ["core.midi.manager"] = "manager", } } -------------------------------------------------------------------------------- -- INITIALISE PLUGIN: -------------------------------------------------------------------------------- function plugin.init(deps) return mod.init(deps) end return plugin
#1050 * Attempted fix for scaling MIDI values on Color Wheels.
#1050 * Attempted fix for scaling MIDI values on Color Wheels.
Lua
mit
fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost
9b005e98631fc351b455854508151fa7b72fd430
src_trunk/resources/camera-system/s_camera_system.lua
src_trunk/resources/camera-system/s_camera_system.lua
-- STRIP CAMERA 1 stripCamera1 = nil stripCamera1Col = nil stripCamera1ColWarn = nil stripCamera1Speed = nil function resourceStart(res) -- STRIP CAMERA 1 stripCamera1 = createObject(1293, 1342.5859375, -1471.4306640625, 12.939081573486, 0, 0, 347.48364257813) exports.pool:allocateElement(stripCamera1) stripCamera1Col = createColTube(1342.5859375, -1471.4306640625, 5, 80, 9) exports.pool:allocateElement(stripCamera1Col) stripCamera1ColWarn = createColTube(1342.5859375, -1471.4306640625, 5, 150, 10) exports.pool:allocateElement(stripCamera1ColWarn) stripCamera1Speed = 65 addEventHandler("onColShapeHit", stripCamera1ColWarn, sendWarning) addEventHandler("onColShapeHit", stripCamera1Col, monitorSpeed) addEventHandler("onColShapeLeave", stripCamera1Col, stopMonitorSpeed) end addEventHandler("onResourceStart", getResourceRootElement(), resourceStart) -- dynamic stuff function monitorSpeed(element, matchingDimension) if (matchingDimension) and (getElementType(element)=="vehicle")then local thePlayer = getVehicleOccupant(element) local timer = setTimer(checkSpeed, 200, 40, element, thePlayer, source) setElementData(thePlayer, "cameratimer", timer, false) end end function stopMonitorSpeed(element, matchingDimension) if (matchingDimension) and (getElementType(element)=="vehicle") then local thePlayer = getVehicleOccupant(element) local timer = getElementData(thePlayer, "cameratimer") end end function checkSpeed(vehicle, player, colshape) speedx, speedy, speedz = getElementVelocity(vehicle) if (speedx) and (speedy) and (speedz) then speed = ((speedx^2 + speedy^2 + speedz^2)^(0.5)*100) if (colshape==stripCamera1Col) then -- strip camera 1 if (speed>stripCamera1Speed) then local x, y, z = getElementPosition(player) local timer = getElementData(player, "cameratimer") if timer then killTimer(timer) removeElementData(player, "cameratimer") end setTimer(sendWarningToCops, 1000, 1, vehicle, player, colshape, x, y, z, speed) end end end end lawVehicles = { [416]=true, [433]=true, [427]=true, [490]=true, [528]=true, [407]=true, [544]=true, [523]=true, [470]=true, [598]=true, [596]=true, [597]=true, [599]=true, [432]=true, [601]=true } function sendWarningToCops(vehicle, player, colshape, x, y, z, speed) local direction = "in an unknown direction" local areaname = getZoneName(x, y, z) local nx, ny, nz = getElementPosition(player) local vehname = getVehicleName(vehicle) local vehid = getElementModel(vehicle) if not (lawVehicles[vehid]) then if (ny>y) then -- north direction = "northbound" elseif (ny<y) then -- south direction = "southbound" elseif (nx>x) then -- east direction = "eastbound" elseif (nx<x) then -- west direction = "westbound" end exports.global:givePlayerAchievement(player, 13) triggerClientEvent(player, "cameraEffect", player) local theTeam = getTeamFromName("Los Santos Police Department") local teamPlayers = getPlayersInTeam(theTeam) for key, value in ipairs(teamPlayers) do local duty = tonumber(getElementData(value, "duty")) if (duty>0) then outputChatBox("DISPATCH: All units we have a traffic violation at " .. areaname .. ". ((" .. getPlayerName(player) .. "))", value, 255, 194, 14) outputChatBox("DISPATCH: Vehicle was a " .. vehname .. " travelling at " .. tostring(math.ceil(speed)) .. " Mph.", value, 255, 194, 14) outputChatBox("DISPATCH: Vehicle was last seen heading " .. direction .. ".", value, 255, 194, 14) end end end end function sendWarning(element, matchingDimension) if (matchingDimension) and (getElementType(element)=="vehicle")then local thePlayer = getVehicleOccupant(element) if (isElement(thePlayer) and (thePlayer~=getRootElement())) then outputChatBox("You are entering a speed control area. The speed limit is 60Kph (40Mph). Watch your speed.", thePlayer) outputChatBox("Courtesy of the Los Santos Police Department.", thePlayer) end end end function showspeed(thePlayer) local veh = getPedOccupiedVehicle(thePlayer) speedx, speedy, speedz = getElementVelocity (veh) actualspeed = ((speedx^2 + speedy^2 + speedz^2)^(0.5)*100) outputChatBox("SPEED: " .. actualspeed .. "(" .. getTrainSpeed(veh) .. ")") setVehicleEngineState(veh, true) end
-- STRIP CAMERA 1 stripCamera1 = nil stripCamera1Col = nil stripCamera1ColWarn = nil stripCamera1Speed = nil function resourceStart(res) -- STRIP CAMERA 1 stripCamera1 = createObject(1293, 1342.5859375, -1471.4306640625, 12.939081573486, 0, 0, 347.48364257813) exports.pool:allocateElement(stripCamera1) stripCamera1Col = createColTube(1342.5859375, -1471.4306640625, 5, 80, 9) exports.pool:allocateElement(stripCamera1Col) stripCamera1ColWarn = createColTube(1342.5859375, -1471.4306640625, 5, 150, 10) exports.pool:allocateElement(stripCamera1ColWarn) stripCamera1Speed = 65 addEventHandler("onColShapeHit", stripCamera1ColWarn, sendWarning) addEventHandler("onColShapeHit", stripCamera1Col, monitorSpeed) addEventHandler("onColShapeLeave", stripCamera1Col, stopMonitorSpeed) end addEventHandler("onResourceStart", getResourceRootElement(), resourceStart) -- dynamic stuff function monitorSpeed(element, matchingDimension) if (matchingDimension) and (getElementType(element)=="vehicle")then local thePlayer = getVehicleOccupant(element) local timer = setTimer(checkSpeed, 200, 40, element, thePlayer, source) setElementData(thePlayer, "cameratimer", timer, false) end end function stopMonitorSpeed(element, matchingDimension) if (matchingDimension) and (getElementType(element)=="vehicle") then local thePlayer = getVehicleOccupant(element) local timer = getElementData(thePlayer, "cameratimer") end end function checkSpeed(vehicle, player, colshape) speedx, speedy, speedz = getElementVelocity(vehicle) if (speedx) and (speedy) and (speedz) then speed = ((speedx^2 + speedy^2 + speedz^2)^(0.5)*100) if (colshape==stripCamera1Col) then -- strip camera 1 if (speed>stripCamera1Speed) then local x, y, z = getElementPosition(player) local timer = getElementData(player, "cameratimer") if timer then killTimer(timer) removeElementData(player, "cameratimer") end setTimer(sendWarningToCops, 1000, 1, vehicle, player, colshape, x, y, z, speed) end end end end lawVehicles = { [416]=true, [433]=true, [427]=true, [490]=true, [528]=true, [407]=true, [544]=true, [523]=true, [470]=true, [598]=true, [596]=true, [597]=true, [599]=true, [432]=true, [601]=true } function sendWarningToCops(vehicle, player, colshape, x, y, z, speed) local direction = "in an unknown direction" local areaname = getZoneName(x, y, z) local nx, ny, nz = getElementPosition(player) local vehname = getVehicleName(vehicle) local vehid = getElementModel(vehicle) if not (lawVehicles[vehid]) then local dx = nx - x local dy = ny - y outputChatBox(dx.." "..dy) if dy > math.abs(dx) then direction = "northbound" elseif dy < -math.abs(dx) then direction = "southbound" elseif dx > math.abs(dy) then direction = "eastbound" elseif dx < -math.abs(dy) then direction = "westbound" end exports.global:givePlayerAchievement(player, 13) triggerClientEvent(player, "cameraEffect", player) local theTeam = getTeamFromName("Los Santos Police Department") local teamPlayers = getPlayersInTeam(theTeam) for key, value in ipairs(teamPlayers) do local duty = tonumber(getElementData(value, "duty")) if (duty>0) then outputChatBox("DISPATCH: All units we have a traffic violation at " .. areaname .. ". ((" .. getPlayerName(player) .. "))", value, 255, 194, 14) outputChatBox("DISPATCH: Vehicle was a " .. vehname .. " travelling at " .. tostring(math.ceil(speed)) .. " Mph.", value, 255, 194, 14) outputChatBox("DISPATCH: Vehicle was last seen heading " .. direction .. ".", value, 255, 194, 14) end end end end function sendWarning(element, matchingDimension) if (matchingDimension) and (getElementType(element)=="vehicle")then local thePlayer = getVehicleOccupant(element) if (isElement(thePlayer) and (thePlayer~=getRootElement())) then outputChatBox("You are entering a speed control area. The speed limit is 60Kph (40Mph). Watch your speed.", thePlayer) outputChatBox("Courtesy of the Los Santos Police Department.", thePlayer) end end end function showspeed(thePlayer) local veh = getPedOccupiedVehicle(thePlayer) speedx, speedy, speedz = getElementVelocity (veh) actualspeed = ((speedx^2 + speedy^2 + speedz^2)^(0.5)*100) outputChatBox("SPEED: " .. actualspeed .. "(" .. getTrainSpeed(veh) .. ")") setVehicleEngineState(veh, true) end
fixed speedcam direction detection
fixed speedcam direction detection git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1234 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
8eead7e3ca1d150569e9f0c540ad980c91b87bec
nvim/lua/user/treesitter.lua
nvim/lua/user/treesitter.lua
local status_ok, configs = pcall(require, "nvim-treesitter.configs") if not status_ok then return end configs.setup { ensure_installed = { "bash", "comment", "css", "dockerfile", "eex", "elixir", "erlang", "graphql", "heex", "html", "javascript", "jsdoc", "json", "make", "markdown", "ruby", "rust", "toml", "typescript", "yaml", "zig", }, sync_install = false, -- install languages synchronously (only applied to `ensure_installed`) ignore_install = { "" }, -- List of parsers to ignore installing autopairs = { enable = true, }, highlight = { enable = true, -- false will disable the whole extension disable = { "" }, -- list of language that will be disabled additional_vim_regex_highlighting = true, }, indent = { enable = true, disable = { "yaml" } }, context_commentstring = { enable = true, enable_autocmd = false, }, rainbow = { enable = true, extended_mode = true, max_file_lines = nil, }, }
local status_ok, configs = pcall(require, "nvim-treesitter.configs") if not status_ok then return end configs.setup { ensure_installed = { "bash", -- "comment", "css", "dockerfile", "eex", "elixir", "erlang", "graphql", "heex", "html", "javascript", "jsdoc", "json", "make", "markdown", "ruby", "rust", "toml", "typescript", "yaml", "zig", }, sync_install = false, -- install languages synchronously (only applied to `ensure_installed`) ignore_install = { "" }, -- List of parsers to ignore installing autopairs = { enable = true, }, highlight = { enable = true, -- false will disable the whole extension disable = { "" }, -- list of language that will be disabled additional_vim_regex_highlighting = true, }, indent = { enable = true, disable = { "yaml" } }, context_commentstring = { enable = true, enable_autocmd = false, config = { elixir = { __default = '# %s', }, heex = { __default = '<!-- %s -->', } } }, rainbow = { enable = true, extended_mode = true, max_file_lines = nil, }, }
nvim: fix commenting code in elixir and heex
nvim: fix commenting code in elixir and heex
Lua
mit
sax/dotfiles,sax/dotfiles
c4532ebfc34d20bbc2dafc4bf99583a4f1b81e07
item/id_917_cursedshield.lua
item/id_917_cursedshield.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 common SET com_script = 'item.id_917_cursedshield' WHERE com_itemid = 917; require("base.common") require("item.general.metal") require("base.lookat") require("item.general.checks") module("item.id_917_cursedshield", package.seeall, package.seeall(item.general.metal)) function MoveItemBeforeMove(User,SourceItem,TargetItem) if TargetItem:getType() == 4 then --inventory, not belt return item.general.checks.checkLevel(User,SourceItem); else return true; end return true; --just in case end function MoveItemBeforeMove( User, SourceItem, TargetItem ) if TargetItem:getType() == 4 then --inventory, not belt return item.general.checks.checkLevel(User,SourceItem); else -- if shield was purified, then no possibility of curse if ( tonumber(SourceItem:getData("cursedShield")) == 1 ) then return true; end; -- if the shield is cursed, make it impossible to unequip if ( tonumber(SourceItem:getData("cursedShield")) == 2 ) and ( ( SourceItem.itempos == 5 ) or ( SourceItem.itempos == 6 ) ) then -- if successfully removed if ( math.random( 2000 ) <= User:increaseAttrib( "willpower", 0 ) * 4 ) then base.common.InformNLS( User, "Mit deinem starken Willen und Ausdauer schaffst du es, das verfluchte Schild von deiner Hand zu lsen.", "With a strong will and perseverance, you manage to detach the cursed shield from your hand." ) return true; end; -- else unable to remove shield base.common.InformNLS( User, "Eine dunkle Energie scheint dich daran zu hindern das Schild loszulassen.", "Some kind of dark energy seems to prohibit you from releasing the shield." ); return false; end; end; return true; end; function MoveItemAfterMove( User, SourceItem, TargetItem ) -- if shield equipped in hands if ( TargetItem.itempos == 5 ) or ( TargetItem.pos == 6 )then -- if curse gets in effect local curseChance = math.random( 5 + User:increaseAttrib( "essence", 0 ) + math.floor( User:getSkill(Character.magicResistance) / 5 ) ); -- if shield curse had already been effected, but user managed to remove it if ( tonumber(SourceItem:getData("cursedShield")) == 2 ) then curseChance = 1; end; if ( curseChance == 1 ) then TargetItem:setData("cursedShield",2); world:changeItem( TargetItem ); base.common.InformNLS( User, "Eine pltzliche dunkle Energie strmt aus dem Schild und scheint deine Hand zu packen.", "A sudden dark energy emenates from the shield and seems to clutch to your hand." ); return true; end; end; return true; end; function LookAtItem(User,Item) item.general.metal.LookAtItem(User,Item) 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/>. ]] -- UPDATE common SET com_script = 'item.id_917_cursedshield' WHERE com_itemid = 917; require("base.common") require("item.general.metal") require("base.lookat") require("item.general.checks") module("item.id_917_cursedshield", package.seeall, package.seeall(item.general.metal)) function MoveItemBeforeMove( User, SourceItem, TargetItem ) if TargetItem:getType() == 4 then --inventory, not belt return item.general.checks.checkLevel(User,SourceItem); else -- if shield was purified, then no possibility of curse if ( tonumber(SourceItem:getData("cursedShield")) == 1 ) then return true; end; -- if the shield is cursed, make it impossible to unequip if ( tonumber(SourceItem:getData("cursedShield")) == 2 ) and ( ( SourceItem.itempos == 5 ) or ( SourceItem.itempos == 6 ) ) then -- if successfully removed if ( math.random( 2000 ) <= User:increaseAttrib( "willpower", 0 ) * 4 ) then base.common.InformNLS( User, "Mit deinem starken Willen und Ausdauer schaffst du es, das verfluchte Schild von deiner Hand zu lsen.", "With a strong will and perseverance, you manage to detach the cursed shield from your hand." ) return true; end; -- else unable to remove shield base.common.InformNLS( User, "Eine dunkle Energie scheint dich daran zu hindern das Schild loszulassen.", "Some kind of dark energy seems to prohibit you from releasing the shield." ); return false; end; end; return true; end; function MoveItemAfterMove( User, SourceItem, TargetItem ) -- if shield equipped in hands if ( TargetItem.itempos == 5 ) or ( TargetItem.pos == 6 )then -- if curse gets in effect local curseChance = math.random( 5 + User:increaseAttrib( "essence", 0 ) + math.floor( User:getSkill(Character.magicResistance) / 5 ) ); -- if shield curse had already been effected, but user managed to remove it if ( tonumber(SourceItem:getData("cursedShield")) == 2 ) then curseChance = 1; end; if ( curseChance == 1 ) then TargetItem:setData("cursedShield",2); world:changeItem( TargetItem ); base.common.InformNLS( User, "Eine pltzliche dunkle Energie strmt aus dem Schild und scheint deine Hand zu packen.", "A sudden dark energy emenates from the shield and seems to clutch to your hand." ); return true; end; end; return true; end; function LookAtItem(User,Item) return item.general.metal.LookAtItem(User,Item) end
remove a doubled function and fix lookat
remove a doubled function and fix lookat
Lua
agpl-3.0
Illarion-eV/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content
3548da6bcd9ce3b1ad46f1fb005b6d6ba51c47f4
plugins/warn.lua
plugins/warn.lua
local warn = {} local mattata = require('mattata') local redis = require('mattata-redis') local JSON = require('dkjson') function warn:init(configuration) warn.arguments = 'warn' warn.commands = mattata.commands(self.info.username, configuration.commandPrefix):c('warn').table warn.help = configuration.commandPrefix .. 'warn - Warn the replied-to user.' end function warn:onCallback(callback, message, configuration) if message.chat.type ~= 'private' then if mattata.isGroupAdmin(message.chat.id, callback.from.id) then if string.match(callback.data, '^resetWarnings') then redis:hdel('chat:' .. message.chat.id .. ':warnings', callback.data:gsub('resetWarnings', '')) mattata.editMessageText(message.chat.id, message.message_id, 'Warnings reset by ' .. callback.from.first_name, nil, true) return end if string.match(callback.data, '^removeWarning') then local user = callback.data:gsub('removeWarning', '') local amount = redis:hincrby('chat:' .. message.chat.id .. ':warnings', user, -1) local text, maximum, difference if tonumber(amount) < 0 then text = 'The number of warnings received by this user is already zero!' redis:hincrby('chat:' .. message.chat.id .. ':warnings', user, 1) else maximum = 3 difference = maximum - amount text = 'Warning removed! (%d/%d)' text = text:format(tonumber(amount), tonumber(maximum)) end mattata.editMessageText(message.chat.id, message.message_id, text, nil, true) return end end end end function warn:onMessage(message, configuration) if message.chat.type ~= 'private' then if mattata.isGroupAdmin(message.chat.id, message.from.id) then if (not message.reply_to_message) or mattata.isGroupAdmin(message.chat.id, message.reply_to_message.from.id) then mattata.sendMessage(message.chat.id, 'Either the targeted user is a group administrator, or you haven\'t send this message as a reply.', nil, true, false, message.message_id) return end local name = message.reply_to_message.from.first_name local hash = 'chat:' .. message.chat.id .. ':warnings' local amount = redis:hincrby(hash, message.reply_to_message.from.id, 1) local maximum = 3 local text, res amount, maximum = tonumber(amount), tonumber(maximum) if amount >= maximum then text = message.reply_to_message.from.first_name .. ' was banned for reaching the maximum number of allowed warnings (' .. maximum .. ').' res = mattata.kickChatMember(message.chat.id, message.reply_to_message.from.id) if not res then mattata.sendMessage(message.chat.id, 'I couldn\'t ban that user. Please ensure that I\'m an administrator and that the targeted user isn\'t.', nil, true, false, message.message_id) return end redis:hdel('chat:' .. message.chat.id .. ':warnings', message.reply_to_message.from.id) mattata.sendMessage(message.chat.id, text, nil, true, false, message.message_id) return end local difference = maximum - amount text = '*%s* has been warned `[`%d/%d`]`' if message.text_lower ~= configuration.commandPrefix .. 'warn' then text = text .. '\n*Reason:* ' .. mattata.markdownEscape(message.text_lower:gsub('^' .. configuration.commandPrefix .. 'warn ', '')) end text = text:format(mattata.markdownEscape(name), amount, maximum) local keyboard = {} keyboard.inline_keyboard = { { { { text = 'Remove Warning', callback_data = 'removeWarning' .. message.reply_to_message.from.id }, { text = 'Reset Warnings', callback_data = 'resetWarnings' .. message.reply_to_message.from.id } } } } mattata.sendMessage(message.chat.id, text, 'Markdown', true, false, message.message_id, JSON.encode(keyboard)) return end end end return warn
local warn = {} local mattata = require('mattata') local redis = require('mattata-redis') local JSON = require('dkjson') function warn:init(configuration) warn.arguments = 'warn' warn.commands = mattata.commands(self.info.username, configuration.commandPrefix):c('warn').table warn.help = configuration.commandPrefix .. 'warn - Warn the replied-to user.' end function warn:onCallbackQuery(callback_query, message, configuration) if message.chat.type ~= 'private' then if mattata.isGroupAdmin(message.chat.id, callback_query.from.id) then if string.match(callback_query.data, '^resetWarnings') then redis:hdel('chat:' .. message.chat.id .. ':warnings', callback_query.data:gsub('resetWarnings', '')) mattata.editMessageText(message.chat.id, message.message_id, 'Warnings reset by ' .. callback_query.from.first_name, nil, true) return end if string.match(callback_query.data, '^removeWarning') then local user = callback_query.data:gsub('removeWarning', '') local amount = redis:hincrby('chat:' .. message.chat.id .. ':warnings', user, -1) local text, maximum, difference if tonumber(amount) < 0 then text = 'The number of warnings received by this user is already zero!' redis:hincrby('chat:' .. message.chat.id .. ':warnings', user, 1) else maximum = 3 difference = maximum - amount text = 'Warning removed! (%d/%d)' text = text:format(tonumber(amount), tonumber(maximum)) end mattata.editMessageText(message.chat.id, message.message_id, text, nil, true) return end end end end function warn:onMessage(message, configuration) if message.chat.type ~= 'private' then if mattata.isGroupAdmin(message.chat.id, message.from.id) then if (not message.reply_to_message) or mattata.isGroupAdmin(message.chat.id, message.reply_to_message.from.id) then mattata.sendMessage(message.chat.id, 'Either the targeted user is a group administrator, or you haven\'t send this message as a reply.', nil, true, false, message.message_id) return end local name = message.reply_to_message.from.first_name local hash = 'chat:' .. message.chat.id .. ':warnings' local amount = redis:hincrby(hash, message.reply_to_message.from.id, 1) local maximum = 3 local text, res amount, maximum = tonumber(amount), tonumber(maximum) if amount >= maximum then text = message.reply_to_message.from.first_name .. ' was banned for reaching the maximum number of allowed warnings (' .. maximum .. ').' res = mattata.kickChatMember(message.chat.id, message.reply_to_message.from.id) if not res then mattata.sendMessage(message.chat.id, 'I couldn\'t ban that user. Please ensure that I\'m an administrator and that the targeted user isn\'t.', nil, true, false, message.message_id) return end redis:hdel('chat:' .. message.chat.id .. ':warnings', message.reply_to_message.from.id) mattata.sendMessage(message.chat.id, text, nil, true, false, message.message_id) return end local difference = maximum - amount text = '*%s* has been warned `[`%d/%d`]`' if message.text_lower ~= configuration.commandPrefix .. 'warn' then text = text .. '\n*Reason:* ' .. mattata.markdownEscape(message.text_lower:gsub('^' .. configuration.commandPrefix .. 'warn ', '')) end text = text:format(mattata.markdownEscape(name), amount, maximum) local keyboard = {} keyboard.inline_keyboard = { { { text = 'Remove Warning', callback_data = 'removeWarning' .. message.reply_to_message.from.id }, { text = 'Reset Warnings', callback_data = 'resetWarnings' .. message.reply_to_message.from.id } } } mattata.sendMessage(message.chat.id, text, 'Markdown', true, false, message.message_id, JSON.encode(keyboard)) return end end end return warn
[v5.2] Fixed a JSON-related bug with warn.lua
[v5.2] Fixed a JSON-related bug with warn.lua
Lua
mit
barreeeiroo/BarrePolice
498e66fea2c3451f68bebfcf91d32f9512b15561
mod_mam/rsm.lib.lua
mod_mam/rsm.lib.lua
local stanza = require"util.stanza".stanza; local tostring, tonumber = tostring, tonumber; local type = type; local pairs = pairs; local xmlns_rsm = 'http://jabber.org/protocol/rsm'; local element_parsers; do local function xs_int(st) return tonumber((st:get_text())); end local function xs_string(st) return st:get_text(); end element_parsers = { after = xs_string; before = function(st) return st:get_text() or true; end; max = xs_int; index = xs_int; first = function(st) return { index = tonumber(st.attr.index); st:get_text() }; end; last = xs_string; count = xs_int; } end local element_generators = setmetatable({ first = function(st, data) if type(data) == "table" then st:tag("first", { index = data.index }):text(data[1]):up(); else st:tag("first"):text(tostring(data)):up(); end end; }, { __index = function(_, name) return function(st, data) st:tag(name):text(tostring(data)):up(); end end; }); local function parse(stanza) local rs = {}; for tag in stanza:childtags() do local name = tag.name; local parser = name and element_parsers[name]; if parser then rs[name] = parser(tag); end end return rs; end local function generate(t) local st = stanza("set", { xmlns = xmlns_rsm }); for k,v in pairs(t) do if element_parsers[k] then element_generators[k](st, v); end end return st; end local function get(st) local set = st:get_child("set", xmlns_rsm); if set and #set.tags > 0 then return parse(set); end end return { parse = parse, generate = generate, get = get };
local stanza = require"util.stanza".stanza; local tostring, tonumber = tostring, tonumber; local type = type; local pairs = pairs; local xmlns_rsm = 'http://jabber.org/protocol/rsm'; local element_parsers; do local function xs_int(st) return tonumber((st:get_text())); end local function xs_string(st) return st:get_text(); end element_parsers = { after = xs_string; before = function(st) return st:get_text() or true; end; max = xs_int; index = xs_int; first = function(st) return { index = tonumber(st.attr.index); st:get_text() }; end; last = xs_string; count = xs_int; } end local element_generators = setmetatable({ first = function(st, data) if type(data) == "table" then st:tag("first", { index = data.index }):text(data[1]):up(); else st:tag("first"):text(tostring(data)):up(); end end; before = function(st, data) if data == true then st:tag("before"):up(); else st:tag("before"):text(tostring(data)):up(); end end }, { __index = function(_, name) return function(st, data) st:tag(name):text(tostring(data)):up(); end end; }); local function parse(stanza) local rs = {}; for tag in stanza:childtags() do local name = tag.name; local parser = name and element_parsers[name]; if parser then rs[name] = parser(tag); end end return rs; end local function generate(t) local st = stanza("set", { xmlns = xmlns_rsm }); for k,v in pairs(t) do if element_parsers[k] then element_generators[k](st, v); end end return st; end local function get(st) local set = st:get_child("set", xmlns_rsm); if set and #set.tags > 0 then return parse(set); end end return { parse = parse, generate = generate, get = get };
mod_mam/rsm.lib: Fix serialization of before = true
mod_mam/rsm.lib: Fix serialization of before = true
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
deeb65ba9ca514d7628e7cb2618d3894e3760e47
mod_xrandr/cfg_xrandr.lua
mod_xrandr/cfg_xrandr.lua
-- map workspace name to list of initial outputs for that workspace initialScreens = {} function screenmanagedchanged(tab) if tab.mode == 'add' and initialScreens[tab.sub:name()] == nil then outputs = mod_xrandr.get_outputs(tab.reg) outputKeys = {} for k,v in pairs(outputs) do table.insert(outputKeys, k) end initialScreens[tab.sub:name()] = outputKeys end end screen_managed_changed_hook = notioncore.get_hook('screen_managed_changed_hook') if screen_managed_changed_hook ~= nil then screen_managed_changed_hook:add(screenmanagedchanged) end function add_safe(t, key, value) if t[key] == nil then t[key] = {} end table.insert(t[key], value) end -- parameter: list of output names -- returns: map from screen name to screen function candidate_screens_for_output(outputname) local retval = {} function addIfContainsOutput(screen) local outputs_within_screen = mod_xrandr.get_outputs_within(screen) if outputs_within_screen[outputname] ~= nil then retval[screen:name()] = screen end return true end notioncore.region_i(addIfContainsOutput, "WScreen") return retval end -- parameter: list of output names -- returns: map from screen name to screen function candidate_screens_for_outputs(outputnames) local result = {} if outputnames == nil then return result end for i,outputname in pairs(outputnames) do local screens = candidate_screens_for_output(outputname) for k,screen in pairs(screens) do result[k] = screen; end end return result; end function firstValue(t) local key, value = next(t) return value end function firstKey(t) local key, value = next(t) return key end function empty(t) return next(t) == nil end function singleton(t) local first = next(t) return first ~= nil and next(t,first) == nil end function move_if_needed(workspace, screen_id) local screen = notioncore.find_screen_id(screen_id) if workspace:screen_of() ~= screen then screen:attach(workspace) end end function mod_xrandr.rearrangeworkspaces() -- for each screen id, which workspaces should be on that screen new_mapping = {} -- workspaces that want to be on an output that's currently not on any screen orphans = {} -- workspaces that want to be on multiple available outputs wanderers = {} -- round one: divide workspaces in directly assignable, -- orphans and wanderers function roundone(workspace) local screens = candidate_screens_for_outputs(initialScreens[workspace:name()]) if (screens == nil) or empty(screens) then table.insert(orphans, workspace) elseif singleton(screens) then local name, screen = next(screens) add_safe(new_mapping, screen:id(), workspace) else add_safe(wanderers, workspace, screens) end return true end notioncore.region_i(roundone, "WGroupWS") for workspace,screens in pairs(wanderers) do -- print('Wanderer', workspace:name()) -- TODO add to screen with least # of workspaces instead of just the -- first one that applies add_safe(new_mapping, screens[0]:id(), workspace) end for i,workspace in pairs(orphans) do -- print('Orphan', workspace:name()) -- TODO add to screen with least # of workspaces instead of just the first one add_safe(new_mapping, 0, workspace) end for screen_id,workspaces in pairs(new_mapping) do -- move workspace to that for i,workspace in pairs(workspaces) do move_if_needed(workspace, screen_id) end end end -- refresh xinerama and rearrange workspaces on screen layout updates function screenlayoutupdated() mod_xinerama.refresh() mod_xrandr.rearrangeworkspaces() end randr_screen_change_notify_hook = notioncore.get_hook('randr_screen_change_notify') if randr_screen_change_notify_hook ~= nil then randr_screen_change_notify_hook:add(screenlayoutupdated) end
-- map workspace name to list of initial outputs for that workspace initialScreens = {} function screenmanagedchanged(tab) if tab.mode == 'add' and initialScreens[tab.sub:name()] == nil then outputs = mod_xrandr.get_outputs(tab.reg) outputKeys = {} for k,v in pairs(outputs) do table.insert(outputKeys, k) end initialScreens[tab.sub:name()] = outputKeys end end screen_managed_changed_hook = notioncore.get_hook('screen_managed_changed_hook') if screen_managed_changed_hook ~= nil then screen_managed_changed_hook:add(screenmanagedchanged) end function add_safe(t, key, value) if t[key] == nil then t[key] = {} end table.insert(t[key], value) end -- parameter: list of output names -- returns: map from screen name to screen function candidate_screens_for_output(outputname) local retval = {} function addIfContainsOutput(screen) local outputs_within_screen = mod_xrandr.get_outputs_within(screen) if outputs_within_screen[outputname] ~= nil then retval[screen:name()] = screen end return true end notioncore.region_i(addIfContainsOutput, "WScreen") return retval end -- parameter: list of output names -- returns: map from screen name to screen function candidate_screens_for_outputs(outputnames) local result = {} if outputnames == nil then return result end for i,outputname in pairs(outputnames) do local screens = candidate_screens_for_output(outputname) for k,screen in pairs(screens) do result[k] = screen; end end return result; end function firstValue(t) local key, value = next(t) return value end function firstKey(t) local key, value = next(t) return key end function empty(t) return next(t) == nil end function singleton(t) local first = next(t) return first ~= nil and next(t,first) == nil end function move_if_needed(workspace, screen_id) local screen = notioncore.find_screen_id(screen_id) if workspace:screen_of() ~= screen then screen:attach(workspace) end end function mod_xrandr.rearrangeworkspaces() -- for each screen id, which workspaces should be on that screen new_mapping = {} -- workspaces that want to be on an output that's currently not on any screen orphans = {} -- workspaces that want to be on multiple available outputs wanderers = {} -- round one: divide workspaces in directly assignable, -- orphans and wanderers function roundone(workspace) local screens = candidate_screens_for_outputs(initialScreens[workspace:name()]) if not screens or empty(screens) then table.insert(orphans, workspace) elseif singleton(screens) then add_safe(new_mapping, firstValue(screens):id(), workspace) else add_safe(wanderers, workspace, screens) end return true end notioncore.region_i(roundone, "WGroupWS") for workspace,screens in pairs(wanderers) do -- print('Wanderer', workspace:name()) -- TODO add to screen with least # of workspaces instead of just the -- first one that applies add_safe(new_mapping, firstValue(screens):id(), workspace) end for i,workspace in pairs(orphans) do -- print('Orphan', workspace:name()) -- TODO add to screen with least # of workspaces instead of just the first one add_safe(new_mapping, 0, workspace) end for screen_id,workspaces in pairs(new_mapping) do -- move workspace to that for i,workspace in pairs(workspaces) do move_if_needed(workspace, screen_id) end end end -- refresh xinerama and rearrange workspaces on screen layout updates function screenlayoutupdated() mod_xinerama.refresh() mod_xrandr.rearrangeworkspaces() end randr_screen_change_notify_hook = notioncore.get_hook('randr_screen_change_notify') if randr_screen_change_notify_hook ~= nil then randr_screen_change_notify_hook:add(screenlayoutupdated) end
Fix bug when handling wanderers
Fix bug when handling wanderers
Lua
lgpl-2.1
anoduck/notion,dkogan/notion,anoduck/notion,knixeur/notion,knixeur/notion,dkogan/notion,p5n/notion,anoduck/notion,neg-serg/notion,raboof/notion,knixeur/notion,dkogan/notion,neg-serg/notion,dkogan/notion.xfttest,knixeur/notion,dkogan/notion.xfttest,knixeur/notion,neg-serg/notion,anoduck/notion,p5n/notion,neg-serg/notion,dkogan/notion,p5n/notion,p5n/notion,anoduck/notion,p5n/notion,raboof/notion,dkogan/notion,dkogan/notion.xfttest,raboof/notion,dkogan/notion.xfttest,raboof/notion
5b093f33a9bc21f0a6a09a367e540b01a2e7a3aa
HexChat/mymsg.lua
HexChat/mymsg.lua
hexchat.register('MyMessage', '1', 'Properly show your own messages in ZNC playback') hexchat.hook_print('Capability List', function (args) if args[2]:find('znc.in/self-message') then hexchat.command('CAP REQ znc.in/self-message') end end) hexchat.hook_server_attrs('PRIVMSG', function (word, word_eol, attrs) -- Only want private messages if word[3].sub(0, 1) == '#' then return end local mynick = hexchat.get_info('nick') local sender = word[1]:match('^([^!])!.*') local recipient = word[3] local network = hexchat.get_info('network') local message = word_eol[3] if message[0] == ':' then message = message:sub(1) end if hexchat.nickcmp(sender, mynick) == 0 and hexchat.nickcmp(recipient, mynick) ~= 0 then hexchat.command('query -nofocus ' .. recipient) local ctx = hexchat.find_context(network, recipient) if message:sub(0, 7) == '\001ACTION' then local action = message:sub(8, #message-1) ctx:emit_print_attrs(attrs, 'Your Action', mynick, action) else ctx:emit_print_attrs(attrs, 'Your Message', mynick, message) end return hexchat.EAT_ALL end end)
hexchat.register('MyMessage', '1', 'Properly show your own messages in ZNC playback') hexchat.hook_print('Capability List', function (args) if args[2]:find('znc.in/self%-message') then hexchat.command('CAP REQ znc.in/self-message') end end) hexchat.hook_server_attrs('PRIVMSG', function (word, word_eol, attrs) -- Only want private messages if word[3]:sub(1, 1) == '#' then return -- TODO: More robust check end local mynick = hexchat.get_info('nick') local sender = word[1]:match('^:([^!]+)') local recipient = word[3] local network = hexchat.get_info('network') local message = word_eol[4] if message:sub(1, 1) == ':' then message = message:sub(2) end if hexchat.nickcmp(sender, mynick) == 0 and hexchat.nickcmp(recipient, mynick) ~= 0 then hexchat.command('query -nofocus ' .. recipient) local ctx = hexchat.find_context(network, recipient) if message:sub(1, 7) == '\001ACTION' then local action = message:sub(8, #message-1) ctx:emit_print_attrs(attrs, 'Your Action', mynick, action) else ctx:emit_print_attrs(attrs, 'Your Message', mynick, message) end return hexchat.EAT_ALL end end)
mymsg.lua: Fixup
mymsg.lua: Fixup
Lua
mit
TingPing/plugins,TingPing/plugins
f2cac00849bd370df72a7e13eac1d339c01c9789
game/scripts/vscripts/heroes/structures/healer_bottle_filling.lua
game/scripts/vscripts/heroes/structures/healer_bottle_filling.lua
LinkLuaModifier("modifier_healer_bottle_filling", "heroes/structures/healer_bottle_filling.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_healer_bottle_filling_delay", "heroes/structures/healer_bottle_filling.lua", LUA_MODIFIER_MOTION_NONE) healer_bottle_filling = class({ GetIntrinsicModifierName = function() return "modifier_healer_bottle_filling" end, }) modifier_healer_bottle_filling = class({ IsPurgable = function() return false end, IsHidden = function() return true end, }) if IsServer() then function modifier_healer_bottle_filling:OnCreated() self:StartIntervalThink(1) self:OnIntervalThink() end function modifier_healer_bottle_filling:OnIntervalThink() local caster = self:GetCaster() local ability = self:GetAbility() local modifier = "modifier_healer_bottle_filling_delay" local radius = ability:GetSpecialValueFor("aura_radius") local delay_duration = ability:GetSpecialValueFor('bottle_refill_cooldown') for _,v in ipairs(FindUnitsInRadius(caster:GetTeamNumber(), caster:GetAbsOrigin(), nil, radius, DOTA_UNIT_TARGET_TEAM_FRIENDLY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do if v:HasModifier("modifier_healer_bottle_filling_delay") then return end for i = 0, 11 do local item = v:GetItemInSlot(i) if item and item:GetAbilityName() == "item_bottle_arena" then item:SetCurrentCharges(item:GetCurrentCharges()+1) v:EmitSound("DOTA_Item.MagicWand.Activate") if item:GetCurrentCharges() == 3 then v:AddNewModifier(ability:GetCaster(), ability, "modifier_healer_bottle_filling_delay", {duration = delay_duration}) end end end end end end modifier_healer_bottle_filling_delay = class({ IsDebuff = function() return true end, IsPurgable = function() return false end, })
LinkLuaModifier("modifier_healer_bottle_filling", "heroes/structures/healer_bottle_filling.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_healer_bottle_filling_delay", "heroes/structures/healer_bottle_filling.lua", LUA_MODIFIER_MOTION_NONE) healer_bottle_filling = class({ GetIntrinsicModifierName = function() return "modifier_healer_bottle_filling" end, }) modifier_healer_bottle_filling = class({ IsPurgable = function() return false end, IsHidden = function() return true end, }) if IsServer() then function modifier_healer_bottle_filling:OnCreated() self:StartIntervalThink(1) self:OnIntervalThink() end function modifier_healer_bottle_filling:OnIntervalThink() local caster = self:GetCaster() local ability = self:GetAbility() local radius = ability:GetSpecialValueFor("aura_radius") local delay_duration = ability:GetSpecialValueFor('bottle_refill_cooldown') for _,v in ipairs(FindUnitsInRadius(caster:GetTeamNumber(), caster:GetAbsOrigin(), nil, radius, DOTA_UNIT_TARGET_TEAM_FRIENDLY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do if not v:HasModifier("modifier_healer_bottle_filling_delay") then for i = 0, 11 do local item = v:GetItemInSlot(i) if item and item:GetAbilityName() == "item_bottle_arena" then item:SetCurrentCharges(item:GetCurrentCharges()+1) v:EmitSound("DOTA_Item.MagicWand.Activate") if item:GetCurrentCharges() == 3 then v:AddNewModifier(ability:GetCaster(), ability, "modifier_healer_bottle_filling_delay", {duration = delay_duration}) end end end end end end end modifier_healer_bottle_filling_delay = class({ IsDebuff = function() return true end, IsPurgable = function() return false end, })
fix(abilities) Shrine bottle filling ability had wrong modifier verify.
fix(abilities) Shrine bottle filling ability had wrong modifier verify. This commit supresses c8f5658.
Lua
mit
ark120202/aabs
b811416e0512ebf6a12e0288bad252956d0c9ac7
lua/entities/gmod_wire_button/cl_init.lua
lua/entities/gmod_wire_button/cl_init.lua
include('shared.lua') ENT.Spawnable = false ENT.AdminSpawnable = false ENT.RenderGroup = RENDERGROUP_OPAQUE local halo_ent, halo_blur function ENT:Initialize() self.PosePosition = 0.0 end function ENT:Draw() baseclass.Get("gmod_button").UpdateLever(self) self:DoNormalDraw(true,false) if LocalPlayer():GetEyeTrace().Entity == self and EyePos():Distance( self:GetPos() ) < 512 then if self:GetOn() then halo_ent = self halo_blur = 4 + math.sin(CurTime()*20)*2 else self:DrawEntityOutline() end end Wire_Render(self) end hook.Add("PreDrawHalos", "Wiremod_button_overlay_halos", function() if halo_ent then halo.Add({halo_ent}, Color(255,100,100), halo_blur, halo_blur, 1, true, true) halo_ent = nil end end)
include('shared.lua') ENT.Spawnable = false ENT.AdminSpawnable = false ENT.RenderGroup = RENDERGROUP_OPAQUE local halo_ent, halo_blur function ENT:Initialize() self.PosePosition = 0.0 end function ENT:Think() baseclass.Get("gmod_button").UpdateLever(self) end function ENT:Draw() self:DoNormalDraw(true,false) if LocalPlayer():GetEyeTrace().Entity == self and EyePos():Distance( self:GetPos() ) < 512 then if self:GetOn() then halo_ent = self halo_blur = 4 + math.sin(CurTime()*20)*2 else self:DrawEntityOutline() end end Wire_Render(self) end hook.Add("PreDrawHalos", "Wiremod_button_overlay_halos", function() if halo_ent then halo.Add({halo_ent}, Color(255,100,100), halo_blur, halo_blur, 1, true, true) halo_ent = nil end end)
gmod_wire_button: Call UpdateLever() in the right way. Fixes a bug where the lever would move faster if you were hovering over it.
gmod_wire_button: Call UpdateLever() in the right way. Fixes a bug where the lever would move faster if you were hovering over it.
Lua
apache-2.0
mms92/wire,plinkopenguin/wiremod,rafradek/wire,sammyt291/wire,dvdvideo1234/wire,immibis/wiremod,CaptainPRICE/wire,thegrb93/wire,notcake/wire,garrysmodlua/wire,Python1320/wire,Grocel/wire,mitterdoo/wire,NezzKryptic/Wire,bigdogmat/wire,wiremod/wire
7ed68c0d2b1f006071a2a6fc2600eab76c4d7128
lib/lux/oo/class.lua
lib/lux/oo/class.lua
--[[ -- -- Copyright (c) 2013-2014 Wilson Kazuo Mizutani -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -- --]] --- LUX's object-oriented feature module. -- This module provides some basic functionalities for object-oriented -- programming in Lua. It is divided in two parts, which you can @{require} -- separately. -- -- <h2><code>lux.oo.prototype</code></h2> -- -- This part provides a prototype-based implementation. It returns the root -- prototype object, with which you can create new objects using -- @{prototype:new}. Objects created this way automatically inherit fields and -- methods from their parent, but may override them. It is not possible to -- inherit from multiple objects. For usage instructions, refer to -- @{prototype}. -- -- <h2><code>lux.oo.class</code></h2> -- -- This part provides a class-based implementation. It returns a special table -- @{class} through which you can define classes. As of the current version of -- LUX, there is no support for inheritance. -- -- @module lux.oo --- A special table for defining classes through a simple package system. -- -- In order to use it in any way, call the <code>class.package</code> function -- to get a package (all classes belong in package). Then, by defining a named -- method in it, a new class is created. It uses the given method to create its -- instances. Once defined, the class can be retrieved by using accessing the -- package table with its name. If it is not defined, the package tries to -- <code>require</code> using its name concatenated with the class' name. -- -- Since the fields are declared in a scope of -- their own, local variables are kept their closures. Thus, it is -- possible to have private members. Public member can be created by not using -- the <code>local</code> keyword or explicitly referring to <code>self</code> -- within the class definition. -- -- Inheritance is possible through the <code>my_class:inherit()</code> method. -- You use it inside the class definition passing self as the first parameter. -- -- @feature class -- @usage -- local class = require 'lux.oo.class' -- local pack = class.package 'pack' -- function pack:MyClass() -- local a_number = 42 -- function show () -- print(a_number) -- end -- end -- function pack:MyChildClass() -- pack.MyClass:inherit(self) -- local a_string = "foo" -- function show_twice () -- show() -- show() -- end -- end -- local class = {} local lambda = require 'lux.functional' local packages = {} local obj_metatable = {} local no_op = function () end local function makeEmptyObject (the_class) return { __inherit = class, __class = the_class, __meta = {}, } end local function construct (the_class, obj, ...) assert(the_class.definition) (obj, ...) return obj end local function createAndConstruct (the_class, ...) local obj = makeEmptyObject(the_class) construct(the_class, obj, ...) return setmetatable(obj, obj.__meta); end local redef_err = "Redefinition of class '%s' in package '%s'" local function define (pack, name, definition) assert(not rawget(pack, name), redef_err:format(name, current_package)) local new_class = { name = name, definition = definition, inherit = construct } setmetatable(new_class, { __call = createAndConstruct }) rawset(pack, name, new_class) end local function import (pack, name) local result = rawget(pack, name) return result or require(pack.__name.."."..name) end local package_mttab = { __index = import, __newindex = define } --- Loads a class package -- Tries to provide a previously registered package with the given name. If it -- is not found, it is created, registered and returned. -- @param name The package name function class.package (name) local pack = packages[name] if not pack then pack = setmetatable({ __name = name }, package_mttab) packages[name] = pack end return pack end class:package 'std' return class
--[[ -- -- Copyright (c) 2013-2014 Wilson Kazuo Mizutani -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -- --]] --- LUX's object-oriented feature module. -- This module provides some basic functionalities for object-oriented -- programming in Lua. It is divided in two parts, which you can @{require} -- separately. -- -- <h2><code>lux.oo.prototype</code></h2> -- -- This part provides a prototype-based implementation. It returns the root -- prototype object, with which you can create new objects using -- @{prototype:new}. Objects created this way automatically inherit fields and -- methods from their parent, but may override them. It is not possible to -- inherit from multiple objects. For usage instructions, refer to -- @{prototype}. -- -- <h2><code>lux.oo.class</code></h2> -- -- This part provides a class-based implementation. It returns a special table -- @{class} through which you can define classes. As of the current version of -- LUX, there is no support for inheritance. -- -- @module lux.oo --- A special table for defining classes through a simple package system. -- -- In order to use it in any way, call the <code>class.package</code> function -- to get a package (all classes belong in package). Then, by defining a named -- method in it, a new class is created. It uses the given method to create its -- instances. Once defined, the class can be retrieved by using accessing the -- package table with its name. If it is not defined, the package tries to -- <code>require</code> using its name concatenated with the class' name. -- -- Since the fields are declared in a scope of -- their own, local variables are kept their closures. Thus, it is -- possible to have private members. Public member can be created by not using -- the <code>local</code> keyword or explicitly referring to <code>self</code> -- within the class definition. -- -- Inheritance is possible through the <code>my_class:inherit()</code> method. -- You use it inside the class definition passing self as the first parameter. -- -- @feature class -- @usage -- local class = require 'lux.oo.class' -- local pack = class.package 'pack' -- function pack:MyClass() -- local a_number = 42 -- function show () -- print(a_number) -- end -- end -- function pack:MyChildClass() -- pack.MyClass:inherit(self) -- local a_string = "foo" -- function show_twice () -- show() -- show() -- end -- end -- local class = {} local lambda = require 'lux.functional' local packages = {} local obj_metatable = {} local no_op = function () end local function makeEmptyObject (the_class) return { __inherit = class, __class = the_class, __meta = {}, } end local function construct (the_class, obj, ...) assert(the_class.definition) (obj, ...) return obj end local function createAndConstruct (the_class, ...) local obj = makeEmptyObject(the_class) construct(the_class, obj, ...) return setmetatable(obj, obj.__meta); end local redef_err = "Redefinition of class '%s' in package '%s'" local function define (pack, name, definition) assert(not rawget(pack, name), redef_err:format(name, current_package)) local new_class = { name = name, definition = definition, inherit = construct } setmetatable(new_class, { __call = createAndConstruct }) rawset(pack, name, new_class) end local function import (pack, name) local result = rawget(pack, name) if not result then result = require(pack.__name.."."..name) or rawget(pack, name) end return result end local package_mttab = { __index = import, __newindex = define } --- Loads a class package -- Tries to provide a previously registered package with the given name. If it -- is not found, it is created, registered and returned. -- @param name The package name function class.package (name) local pack = packages[name] if not pack then pack = setmetatable({ __name = name }, package_mttab) packages[name] = pack end return pack end class:package 'std' return class
[class] Package.import fixed
[class] Package.import fixed Require heuristic was poor
Lua
mit
Kazuo256/luxproject
0b1a13d9c0f2dd008d3a6b6ce7c755ea2e757937
tools/export_model.lua
tools/export_model.lua
-- adapted from https://github.com/marcan/cl-waifu2x require 'pl' local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)() package.path = path.join(path.dirname(__FILE__), "..", "lib", "?.lua;") .. package.path require 'w2nn' local cjson = require "cjson" local function meta_data(model) local meta = {} for k, v in pairs(model) do if k:match("w2nn_") then meta[k:gsub("w2nn_", "")] = v end end return meta end local function includes(s, a) for i = 1, #a do if s == a[i] then return true end end return false end local function get_bias(mod) if mod.bias then return mod.bias:float() else -- no bias return torch.FloatTensor(mod.nOutputPlane):zero() end end local function export_weight(jmodules, seq) local targets = {"nn.SpatialConvolutionMM", "cudnn.SpatialConvolution", "nn.SpatialFullConvolution", "cudnn.SpatialFullConvolution" } for k = 1, #seq.modules do local mod = seq.modules[k] local name = torch.typename(mod) if name == "nn.Sequential" or name == "nn.ConcatTable" then export_weight(jmodules, mod) elseif includes(name, targets) then local weight = mod.weight:float() if name:match("FullConvolution") then weight = torch.totable(weight:reshape(mod.nInputPlane, mod.nOutputPlane, mod.kH, mod.kW)) else weight = torch.totable(weight:reshape(mod.nOutputPlane, mod.nInputPlane, mod.kH, mod.kW)) end local jmod = { class_name = name, kW = mod.kW, kH = mod.kH, dH = mod.dH, dW = mod.dW, padW = mod.padW, padH = mod.padH, nInputPlane = mod.nInputPlane, nOutputPlane = mod.nOutputPlane, bias = torch.totable(get_bias(mod)), weight = weight } if first_layer then first_layer = false jmod.model_config = model_config end table.insert(jmodules, jmod) end end end local function export(model, output) local jmodules = {} local model_config = meta_data(model) local first_layer = true export_weight(jmodules, model) local fp = io.open(output, "w") if not fp then error("IO Error: " .. output) end fp:write(cjson.encode(jmodules)) fp:close() end local cmd = torch.CmdLine() cmd:text() cmd:text("waifu2x export model") cmd:text("Options:") cmd:option("-i", "input.t7", 'Specify the input torch model') cmd:option("-o", "output.json", 'Specify the output json file') cmd:option("-iformat", "ascii", 'Specify the input format (ascii|binary)') local opt = cmd:parse(arg) if not path.isfile(opt.i) then cmd:help() os.exit(-1) end local model = torch.load(opt.i, opt.iformat) export(model, opt.o)
-- adapted from https://github.com/marcan/cl-waifu2x require 'pl' local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)() package.path = path.join(path.dirname(__FILE__), "..", "lib", "?.lua;") .. package.path require 'w2nn' local cjson = require "cjson" local function meta_data(model, model_path) local meta = {} for k, v in pairs(model) do if k:match("w2nn_") then meta[k:gsub("w2nn_", "")] = v end end modtime = file.modified_time(model_path) utc_date = Date('utc') utc_date:set(modtime) meta["created_at"] = tostring(utc_date) return meta end local function includes(s, a) for i = 1, #a do if s == a[i] then return true end end return false end local function get_bias(mod) if mod.bias then return mod.bias:float() else -- no bias return torch.FloatTensor(mod.nOutputPlane):zero() end end local function export_weight(jmodules, seq) local targets = {"nn.SpatialConvolutionMM", "cudnn.SpatialConvolution", "cudnn.SpatialDilatedConvolution", "nn.SpatialFullConvolution", "nn.SpatialDilatedConvolution", "cudnn.SpatialFullConvolution" } for k = 1, #seq.modules do local mod = seq.modules[k] local name = torch.typename(mod) if name == "nn.Sequential" or name == "nn.ConcatTable" then export_weight(jmodules, mod) elseif includes(name, targets) then local weight = mod.weight:float() if name:match("FullConvolution") then weight = torch.totable(weight:reshape(mod.nInputPlane, mod.nOutputPlane, mod.kH, mod.kW)) else weight = torch.totable(weight:reshape(mod.nOutputPlane, mod.nInputPlane, mod.kH, mod.kW)) end local jmod = { class_name = name, kW = mod.kW, kH = mod.kH, dH = mod.dH, dW = mod.dW, padW = mod.padW, padH = mod.padH, dilationW = mod.dilationW, dilationH = mod.dilationH, nInputPlane = mod.nInputPlane, nOutputPlane = mod.nOutputPlane, bias = torch.totable(get_bias(mod)), weight = weight } table.insert(jmodules, jmod) end end end local function export(model, model_path, output) local jmodules = {} local model_config = meta_data(model, model_path) local first_layer = true print(model_config) print(model) export_weight(jmodules, model) jmodules[1]["model_config"] = model_config local fp = io.open(output, "w") if not fp then error("IO Error: " .. output) end fp:write(cjson.encode(jmodules)) fp:close() end local cmd = torch.CmdLine() cmd:text() cmd:text("waifu2x export model") cmd:text("Options:") cmd:option("-i", "input.t7", 'Specify the input torch model') cmd:option("-o", "output.json", 'Specify the output json file') cmd:option("-iformat", "ascii", 'Specify the input format (ascii|binary)') local opt = cmd:parse(arg) if not path.isfile(opt.i) then cmd:help() os.exit(-1) end local model = torch.load(opt.i, opt.iformat) export(model, opt.i, opt.o)
Add to json formt model; Fix json format;
Add to json formt model; Fix json format;
Lua
mit
nagadomi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x
9e7d41d1296edc0b06b533bbc10b4e1b6702391e
frontend/ui/reader/readertoc.lua
frontend/ui/reader/readertoc.lua
ReaderToc = InputContainer:new{ toc_menu_title = "Table of contents", } function ReaderToc:init() if not Device:hasNoKeyboard() then self.key_events = { ShowToc = { { "T" }, doc = "show Table of Content menu" }, } end self.ui.menu:registerToMainMenu(self) end function ReaderToc:cleanUpTocTitle(title) return (title:gsub("\13", "")) end function ReaderToc:onSetDimensions(dimen) self.dimen = dimen end --function ReaderToc:fillToc() --self.toc = self.doc:getToc() --end -- getTocTitleByPage wrapper, so specific reader -- can tranform pageno according its need function ReaderToc:getTocTitleByPage(pageno) return self:_getTocTitleByPage(pageno) end function ReaderToc:_getTocTitleByPage(pageno) if not self.toc then -- build toc when needed. self:fillToc() end -- no table of content if #self.toc == 0 then return "" end local pre_entry = self.toc[1] for _k,_v in ipairs(self.toc) do if _v.page > pageno then break end pre_entry = _v end return self:cleanUpTocTitle(pre_entry.title) end function ReaderToc:getTocTitleOfCurrentPage() return self:getTocTitleByPage(self.pageno) end function ReaderToc:onShowToc() local items = self.ui.document:getToc() -- build menu items for _,v in ipairs(items) do v.text = (" "):rep(v.depth-1)..self:cleanUpTocTitle(v.title) end local toc_menu = Menu:new{ title = "Table of Contents", item_table = items, ui = self.ui, width = Screen:getWidth()-20, height = Screen:getHeight(), } function toc_menu:onMenuChoice(item) self.ui:handleEvent(Event:new("PageUpdate", item.page)) end local menu_container = CenterContainer:new{ dimen = Screen:getSize(), toc_menu, } toc_menu.close_callback = function() UIManager:close(menu_container) end UIManager:show(menu_container) end function ReaderToc:addToMainMenu(item_table) -- insert table to main reader menu table.insert(item_table, { text = self.toc_menu_title, callback = function() self:onShowToc() end, }) end
ReaderToc = InputContainer:new{ toc_menu_title = "Table of contents", } function ReaderToc:init() if not Device:hasNoKeyboard() then self.key_events = { ShowToc = { { "T" }, doc = "show Table of Content menu" }, } end self.ui.menu:registerToMainMenu(self) end function ReaderToc:cleanUpTocTitle(title) return (title:gsub("\13", "")) end function ReaderToc:onSetDimensions(dimen) self.dimen = dimen end function ReaderToc:fillToc() self.toc = self.ui.document:getToc() end -- _getTocTitleByPage wrapper, so specific reader -- can tranform pageno according its need function ReaderToc:getTocTitleByPage(pn_or_xp) local page = pn_or_xp if type(pn_or_xp) == "string" then page = self.ui.document:getPageFromXPointer(pn_or_xp) end return self:_getTocTitleByPage(page) end function ReaderToc:_getTocTitleByPage(pageno) if not self.toc then -- build toc when needed. self:fillToc() end -- no table of content if #self.toc == 0 then return "" end local pre_entry = self.toc[1] for _k,_v in ipairs(self.toc) do if _v.page > pageno then break end pre_entry = _v end return self:cleanUpTocTitle(pre_entry.title) end function ReaderToc:getTocTitleOfCurrentPage() return self:getTocTitleByPage(self.pageno) end function ReaderToc:onShowToc() local items = self.ui.document:getToc() -- build menu items for _,v in ipairs(items) do v.text = (" "):rep(v.depth-1)..self:cleanUpTocTitle(v.title) end local toc_menu = Menu:new{ title = "Table of Contents", item_table = items, ui = self.ui, width = Screen:getWidth()-20, height = Screen:getHeight(), } function toc_menu:onMenuChoice(item) self.ui:handleEvent(Event:new("PageUpdate", item.page)) end local menu_container = CenterContainer:new{ dimen = Screen:getSize(), toc_menu, } toc_menu.close_callback = function() UIManager:close(menu_container) end UIManager:show(menu_container) return true end function ReaderToc:addToMainMenu(item_table) -- insert table to main reader menu table.insert(item_table, { text = self.toc_menu_title, callback = function() self:onShowToc() end, }) end
bug fix in readertoc
bug fix in readertoc * typo in fillToc method * handle xpointer in getTocTitleByPage * return true in onShowToc
Lua
agpl-3.0
houqp/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,Frenzie/koreader-base,frankyifei/koreader-base,apletnev/koreader,ashang/koreader,ashhher3/koreader,mwoz123/koreader,chrox/koreader,pazos/koreader,poire-z/koreader,Hzj-jie/koreader-base,frankyifei/koreader-base,koreader/koreader,Frenzie/koreader-base,Frenzie/koreader,frankyifei/koreader-base,Hzj-jie/koreader-base,koreader/koreader-base,NiLuJe/koreader,houqp/koreader-base,chihyang/koreader,koreader/koreader-base,Hzj-jie/koreader-base,Markismus/koreader,apletnev/koreader-base,apletnev/koreader-base,koreader/koreader-base,Frenzie/koreader-base,poire-z/koreader,lgeek/koreader,houqp/koreader-base,houqp/koreader,NiLuJe/koreader,koreader/koreader,Frenzie/koreader,houqp/koreader-base,Hzj-jie/koreader,frankyifei/koreader-base,frankyifei/koreader,Hzj-jie/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,noname007/koreader,NiLuJe/koreader-base,mihailim/koreader,Frenzie/koreader-base,NickSavage/koreader,apletnev/koreader-base,robert00s/koreader
c8df1035ff97aa42d2881586ccc02a69183037c1
KataAnimalQuiz.lua
KataAnimalQuiz.lua
#! /usr/bin/lua -- utils function yes() local resp repeat resp = io.read() until (resp == 'y') or (resp == 'n') return (resp == 'y') end -- returns 'a' or 'an' function article(noun) if (type(noun) == 'table') then noun = noun.value or noun.name end if (string.find(noun, '^[aeiouAEIOU]')) then return 'an' end return 'a' end -- Animal --------------------- local Animal = {} Animal.__index = Animal function Animal.create(name) local a = {} setmetatable(a, Animal) a.name = name a.is_a = 'Animal' return a end ------------------------------- -- Question ------------------- local Question = {} Question.__index = Question function Question.create(s, y_resp, n_resp) local q = {} setmetatable(q, Question) q.string = s q.y_resp = y_resp q.n_resp = n_resp q.is_a = 'Question' return q end function Question:ask() print(self.string .. ' (y/n) ') if yes() then return self.y_resp end return self.n_resp end ------------------------------- -- Node ----------------------- local Node = {} Node.__index = Node function Node.create(value) local n = {} setmetatable(n, Node) n.value = value return n end -- change current value into a question function Node:make_question(q_string, y_resp, n_resp) self.value = Question.create(q_string, y_resp, n_resp) end ------------------------------- -- Quiz ----------------------- local Quiz = {} Quiz.__index = Quiz function Quiz.create(root) local q = {} local n setmetatable(q, Quiz) if (type(root) == 'string') then n = Node.create(Animal.create(root)) else if (type(root_node) == 'table') then n = Node.create(root) else return nil end end q.root = n q.current_node = n return q end function Quiz.create_animal(name) return Animal.create(name) end function Quiz.create_question(q_string, y_resp, n_resp) return Question.create(q_string, y_resp, n_resp) end function Quiz:ask() return Question.ask(self.current_node.value) end function Quiz:answer() print("It's a " .. self.current_node.value.name .. ".") print("Am I right? (y/n) ") if not yes() then local old_value = self.current_node.value.name print("You win. What were you thinking of? ") local good_value = io.read() print("Give me a question to distinguish " .. article(good_value) .. " " .. good_value .. " from " .. article(old_value) .. " " .. old_value .. ".") local q_s = io.read() print("For " .. article(good_value) .. " " .. good_value .. ", what is the answer to your question") if (yes()) then Node.make_question(self.current_node, Node.create(Animal.create(good_value)), Node.create(Animal.create(old_value))) else Node.make_question(self.current_node, Node.create(Animal.create(old_value)), Node.create(Animal.create(good_value))) end end print("Play again? (y/n) ") if yes() then Quiz.start(self) end return self.current_node.value.name end function Quiz:next() if (self.current_node.value.is_a == 'Animal') then return Quiz.answer(self) else -- if self.current_node.value.is_a == 'Question' self.current_node = Quiz.ask(self) end end function Quiz:init() self.current_node = self.root end function Quiz:start() Quiz.init(self) print("Think of an animal…\n") return Quiz.next(self) end ------------------------------- --[[ TODO: - add a .load() and .dump() functions to load/dump "database" (animals) into a file (just for fun) - use a tree structure to store animals, e.g.: Q1 y/ \n A1 Q2 y/ \n A2 A3 with Qx = questions, Ax = animals (y: yes, n: no) ]] return Quiz
#! /usr/bin/lua -- utils function yes() local resp repeat resp = io.read() until (resp == 'y') or (resp == 'n') return (resp == 'y') end -- returns 'a' or 'an' function article(noun) if (type(noun) == 'table') then noun = noun.value or noun.name end if (string.find(noun, '^[aeiouAEIOU]')) then return 'an' end return 'a' end -- Animal --------------------- local Animal = {} Animal.__index = Animal function Animal.create(name) local a = {} setmetatable(a, Animal) a.name = name a.is_a = 'Animal' return a end ------------------------------- -- Question ------------------- local Question = {} Question.__index = Question function Question.create(s, y_resp, n_resp) local q = {} setmetatable(q, Question) q.string = s q.y_resp = y_resp q.n_resp = n_resp q.is_a = 'Question' return q end function Question:ask() print(self.string .. ' (y/n) ') if yes() then return self.y_resp end return self.n_resp end ------------------------------- -- Node ----------------------- local Node = {} Node.__index = Node function Node.create(value) local n = {} setmetatable(n, Node) n.value = value return n end -- change current value into a question function Node:make_question(q_string, y_resp, n_resp) self.value = Question.create(q_string, y_resp, n_resp) end ------------------------------- -- Quiz ----------------------- local Quiz = {} Quiz.__index = Quiz function Quiz.create(root) local q = {} local n setmetatable(q, Quiz) if (type(root) == 'string') then n = Node.create(Animal.create(root)) else if (type(root_node) == 'table') then n = Node.create(root) else return nil end end q.root = n q.current_node = n return q end function Quiz.create_question(q_string, y_resp, n_resp) return Question.create(q_string, y_resp, n_resp) end function Quiz:ask() return Question.ask(self.current_node.value) end function Quiz:answer() print("It's a " .. self.current_node.value.name .. ".") print("Am I right? (y/n) ") local right = yes() if not right then local old_value = self.current_node.value.name print("You win. What were you thinking of? ") local good_value = io.read() print("Give me a question to distinguish " .. article(good_value) .. " " .. good_value .. " from " .. article(old_value) .. " " .. old_value .. ".") local q_s = io.read() print("For " .. article(good_value) .. " " .. good_value .. ", what is the answer to your question") if (yes()) then Node.make_question(self.current_node, q_s, Node.create(Animal.create(good_value)), Node.create(Animal.create(old_value))) else Node.make_question(self.current_node, q_s, Node.create(Animal.create(old_value)), Node.create(Animal.create(good_value))) end end print("Play again? (y/n) ") if yes() then Quiz.start(self) end return self.current_node.value.name or right end function Quiz:next() if (self.current_node.value.is_a == 'Animal') then return Quiz.answer(self) else -- if self.current_node.value.is_a == 'Question' self.current_node = Quiz.ask(self) return Quiz.next(self) end end function Quiz:init() self.current_node = self.root end function Quiz:start() Quiz.init(self) print("Think of an animal…\n") return Quiz.next(self) end ------------------------------- --[[ TODO: - add a .load() and .dump() functions to load/dump "database" (animals) into a file (just for fun) ]] return Quiz
Quiz:next() fixed, Quiz:answer() returns the animal's name if it guess it, false if not.
Quiz:next() fixed, Quiz:answer() returns the animal's name if it guess it, false if not.
Lua
mit
bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas,bfontaine/Katas
0729a1bec2441c935490a5003df844b3480bd829
classes/plain.lua
classes/plain.lua
plain = SILE.baseClass { id = "plain" } plain:declareFrame("content", {left = "5%", right = "95%", top = "5%", bottom = "90%" }); plain:declareFrame("folio", {left = "5%", right = "95%", top = "92%", bottom = "97%" }); plain.pageTemplate.firstContentFrame = plain.pageTemplate.frames["content"]; plain:loadPackage("folio"); plain.endPage = function(self) plain:outputFolio() return SILE.baseClass.endPage(self) end local options = {} plain.declareOption = function (self, name, default) options[name] = default self.options[name] = function (g) if g then options[name] = g end return options[name] end end SILE.registerCommand("noindent", function ( options, content ) SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) SILE.process(content) end, "Do not add an indent to the start of this paragraph") SILE.registerCommand("indent", function ( options, content ) SILE.settings.set("current.parindent", SILE.settings.get("document.parindent")) SILE.process(content) end, "Do add an indent to the start of this paragraph, even if previously told otherwise") local skips = { small= "3pt plus 1pt minus 1pt", med = "6pt plus 2pt minus 2pt", big = "12pt plus 4pt minus 4pt"} for k,v in pairs(skips) do SILE.settings.declare({ name = "plain."..k.."skipamount", type="VGlue", default = SILE.nodefactory.newVglue(v), help = "The amount of a \\"..k.."skip"}) SILE.registerCommand(k.."skip", function ( options, content ) SILE.typesetter:leaveHmode(); SILE.typesetter:pushExplicitVglue(SILE.settings.get("plain."..k.."skipamount")) end, "Skip vertically by a "..k.." amount") end SILE.registerCommand("hfill", function(o,c) SILE.typesetter:pushGlue(SILE.nodefactory.hfillGlue) end, "Add a huge horizontal glue") SILE.registerCommand("vfill", function(o,c) SILE.typesetter:leaveHmode() SILE.typesetter:pushExplicitVglue(SILE.nodefactory.vfillGlue) end, "Add huge vertical glue") SILE.registerCommand("hss", function(o,c) SILE.typesetter:initline() SILE.typesetter:pushGlue(SILE.nodefactory.hssGlue) table.insert(SILE.typesetter.state.nodes, SILE.nodefactory.zeroHbox) end, "Add glue which stretches and shrinks horizontally (good for centering)") SILE.registerCommand("vss", function(o,c) SILE.typesetter:pushVglue(SILE.nodefactory.vssGlue) end, "Add glue which stretches and shrinks vertically") plain.registerCommands = function() SILE.baseClass.registerCommands() SILE.doTexlike([[\define[command=thinspace]{\glue[width=0.16667em]}% \define[command=negthinspace]{\glue[width=-0.16667em]}% \define[command=enspace]{\glue[width=0.5em]}% \define[command=relax]{}% \define[command=enskip]{\enspace}% \define[command=quad]{\glue[width=1em]}% \define[command=qquad]{\glue[width=2em]}% \define[command=slash]{/\penalty[penalty=50]}% \define[command=break]{\penalty[penalty=-10000]}% \define[command=framebreak]{\break}% \define[command=pagebreak]{\penalty[penalty=-20000]}% \define[command=nobreak]{\penalty[penalty=10000]}% \define[command=novbreak]{\penalty[penalty=10000,vertical=1]}% \define[command=allowbreak]{\penalty[penalty=0]}% \define[command=filbreak]{\vfill\penalty[penalty=-200]}% \define[command=goodbreak]{\penalty[penalty=-500]}% \define[command=eject]{\par\break}% \define[command=supereject]{\par\penalty[penalty=-20000]}% \define[command=justified]{\set[parameter=document.rskip]\set[parameter=document.spaceskip]}% \define[command=rightalign]{\raggedleft{\process\par}}% \define[command=em]{\font[style=italic]{\process}}% \define[command=nohyphenation]{\font[language=xx]{\process}}% \define[command=raggedright]{\ragged[right=true]{\process}}% \define[command=raggedleft]{\ragged[left=true]{\process}}% \define[command=center]{\ragged[left=true,right=true]{\process}}% \define[command=quote]{\smallskip\par\set[parameter=document.lskip,value=2.5em]\set[parameter=document.rskip,value=2.5em]\font[size=1.2em]{\noindent\process}\par\set[parameter=document.lskip]\set[parameter="document.rskip"]\smallskip}% \define[command=listitem]{\medskip{}• \process\medskip}% ]]) end SILE.registerCommand("{", function (o,c) SILE.typesetter:typeset("{") end) SILE.registerCommand("}", function (o,c) SILE.typesetter:typeset("}") end) SILE.registerCommand("%", function (o,c) SILE.typesetter:typeset("%") end) SILE.registerCommand("\\", function (o,c) SILE.typesetter:typeset("\\") end) SILE.registerCommand("ragged", function(options,c) SILE.settings.temporarily(function() if options.left then SILE.settings.set("document.lskip", SILE.nodefactory.hfillGlue) end if options.right then SILE.settings.set("document.rskip", SILE.nodefactory.hfillGlue) end SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) SILE.settings.set("document.parindent", SILE.nodefactory.zeroGlue) SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) SILE.settings.set("document.spaceskip", SILE.length.new({ length = SILE.shaper:measureDim(" ") })) SILE.process(c) SILE.call("par") end) end) SILE.registerCommand("hbox", function (o,c) local index = #(SILE.typesetter.state.nodes)+1 local recentContribution = {} SILE.process(c) local l = SILE.length.new() local h,d = 0,0 for i = index, #(SILE.typesetter.state.nodes) do local node = SILE.typesetter.state.nodes[i] if node:isUnshaped() then table.append(recentContribution, node:shape()) else recentContribution[#recentContribution+1] = node end l = l + node:lineContribution() h = node.height > h and node.height or h d = node.depth > d and node.depth or d SILE.typesetter.state.nodes[i] = nil end local hbox = SILE.nodefactory.newHbox({ height = h, width = l, depth = d, value = recentContribution, outputYourself = function (self, typesetter, line) SILE.outputter.moveTo(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY) for i = 1, #(self.value) do local node = self.value[i] node:outputYourself(typesetter, line) end end }) table.insert(SILE.typesetter.state.nodes, hbox) return hbox end, "Compiles all the enclosed horizontal-mode material into a single hbox") SILE.registerCommand("vbox", function (options,c) local vbox SILE.settings.temporarily(function() if (options.width) then SILE.settings.set("typesetter.breakwidth", options.width) end SILE.typesetter:pushState() SILE.process(c) SILE.typesetter:leaveHmode(1) vbox = SILE.pagebuilder.collateVboxes(SILE.typesetter.state.outputQueue) SILE.typesetter:popState() end) return vbox end, "Compiles all the enclosed horizontal-mode material into a single hbox") SILE.require("packages/bidi") return plain;
plain = SILE.baseClass { id = "plain" } plain:declareFrame("content", {left = "5%", right = "95%", top = "5%", bottom = "90%" }); plain:declareFrame("folio", {left = "5%", right = "95%", top = "92%", bottom = "97%" }); plain.pageTemplate.firstContentFrame = plain.pageTemplate.frames["content"]; plain:loadPackage("folio"); plain.endPage = function(self) plain:outputFolio() return SILE.baseClass.endPage(self) end local options = {} plain.declareOption = function (self, name, default) options[name] = default self.options[name] = function (g) if g then options[name] = g end return options[name] end end SILE.registerCommand("noindent", function ( options, content ) SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) SILE.process(content) end, "Do not add an indent to the start of this paragraph") SILE.registerCommand("indent", function ( options, content ) SILE.settings.set("current.parindent", SILE.settings.get("document.parindent")) SILE.process(content) end, "Do add an indent to the start of this paragraph, even if previously told otherwise") local skips = { small= "3pt plus 1pt minus 1pt", med = "6pt plus 2pt minus 2pt", big = "12pt plus 4pt minus 4pt"} for k,v in pairs(skips) do SILE.settings.declare({ name = "plain."..k.."skipamount", type="VGlue", default = SILE.nodefactory.newVglue(v), help = "The amount of a \\"..k.."skip"}) SILE.registerCommand(k.."skip", function ( options, content ) SILE.typesetter:leaveHmode(); SILE.typesetter:pushExplicitVglue(SILE.settings.get("plain."..k.."skipamount")) end, "Skip vertically by a "..k.." amount") end SILE.registerCommand("hfill", function(o,c) SILE.typesetter:pushGlue(SILE.nodefactory.hfillGlue) end, "Add a huge horizontal glue") SILE.registerCommand("vfill", function(o,c) SILE.typesetter:leaveHmode() SILE.typesetter:pushExplicitVglue(SILE.nodefactory.vfillGlue) end, "Add huge vertical glue") SILE.registerCommand("hss", function(o,c) SILE.typesetter:initline() SILE.typesetter:pushGlue(SILE.nodefactory.hssGlue) table.insert(SILE.typesetter.state.nodes, SILE.nodefactory.zeroHbox) end, "Add glue which stretches and shrinks horizontally (good for centering)") SILE.registerCommand("vss", function(o,c) SILE.typesetter:pushVglue(SILE.nodefactory.vssGlue) end, "Add glue which stretches and shrinks vertically") plain.registerCommands = function() SILE.baseClass.registerCommands() SILE.doTexlike([[\define[command=thinspace]{\glue[width=0.16667em]}% \define[command=negthinspace]{\glue[width=-0.16667em]}% \define[command=enspace]{\glue[width=0.5em]}% \define[command=relax]{}% \define[command=enskip]{\enspace}% \define[command=quad]{\glue[width=1em]}% \define[command=qquad]{\glue[width=2em]}% \define[command=slash]{/\penalty[penalty=50]}% \define[command=break]{\penalty[penalty=-10000]}% \define[command=framebreak]{\break}% \define[command=pagebreak]{\penalty[penalty=-20000]}% \define[command=nobreak]{\penalty[penalty=10000]}% \define[command=novbreak]{\penalty[penalty=10000,vertical=1]}% \define[command=allowbreak]{\penalty[penalty=0]}% \define[command=filbreak]{\vfill\penalty[penalty=-200]}% \define[command=goodbreak]{\penalty[penalty=-500]}% \define[command=eject]{\par\break}% \define[command=supereject]{\par\penalty[penalty=-20000]}% \define[command=justified]{\set[parameter=document.rskip]\set[parameter=document.spaceskip]}% \define[command=rightalign]{\raggedleft{\process\par}}% \define[command=em]{\font[style=italic]{\process}}% \define[command=nohyphenation]{\font[language=xx]{\process}}% \define[command=raggedright]{\ragged[right=true]{\process}}% \define[command=raggedleft]{\ragged[left=true]{\process}}% \define[command=center]{\ragged[left=true,right=true]{\process}}% \define[command=quote]{\smallskip\par\set[parameter=document.lskip,value=2.5em]\set[parameter=document.rskip,value=2.5em]\font[size=1.2em]{\noindent\process}\par\set[parameter=document.lskip]\set[parameter="document.rskip"]\smallskip}% \define[command=listitem]{\medskip{}• \process\medskip}% ]]) end SILE.registerCommand("{", function (o,c) SILE.typesetter:typeset("{") end) SILE.registerCommand("}", function (o,c) SILE.typesetter:typeset("}") end) SILE.registerCommand("%", function (o,c) SILE.typesetter:typeset("%") end) SILE.registerCommand("\\", function (o,c) SILE.typesetter:typeset("\\") end) SILE.registerCommand("ragged", function(options,c) SILE.settings.temporarily(function() if options.left then SILE.settings.set("document.lskip", SILE.nodefactory.hfillGlue) end if options.right then SILE.settings.set("document.rskip", SILE.nodefactory.hfillGlue) end SILE.settings.set("typesetter.parfillskip", SILE.nodefactory.zeroGlue) SILE.settings.set("document.parindent", SILE.nodefactory.zeroGlue) SILE.settings.set("current.parindent", SILE.nodefactory.zeroGlue) SILE.settings.set("document.spaceskip", SILE.length.new({ length = SILE.shaper:measureDim(" ") })) SILE.process(c) SILE.call("par") end) end) SILE.registerCommand("hbox", function (o,c) local index = #(SILE.typesetter.state.nodes)+1 local recentContribution = {} SILE.process(c) local l = SILE.length.new() local h,d = 0,0 for i = index, #(SILE.typesetter.state.nodes) do local node = SILE.typesetter.state.nodes[i] if node:isUnshaped() then local s = node:shape() for i = 1, #s do recentContribution[#recentContribution+1] = s[i] l = l + s[i]:lineContribution() end else recentContribution[#recentContribution+1] = node l = l + node:lineContribution() end h = node.height > h and node.height or h d = node.depth > d and node.depth or d SILE.typesetter.state.nodes[i] = nil end local hbox = SILE.nodefactory.newHbox({ height = h, width = l, depth = d, value = recentContribution, outputYourself = function (self, typesetter, line) SILE.outputter.moveTo(typesetter.frame.state.cursorX, typesetter.frame.state.cursorY) for i = 1, #(self.value) do local node = self.value[i] node:outputYourself(typesetter, line) end end }) table.insert(SILE.typesetter.state.nodes, hbox) return hbox end, "Compiles all the enclosed horizontal-mode material into a single hbox") SILE.registerCommand("vbox", function (options,c) local vbox SILE.settings.temporarily(function() if (options.width) then SILE.settings.set("typesetter.breakwidth", options.width) end SILE.typesetter:pushState() SILE.process(c) SILE.typesetter:leaveHmode(1) vbox = SILE.pagebuilder.collateVboxes(SILE.typesetter.state.outputQueue) SILE.typesetter:popState() end) return vbox end, "Compiles all the enclosed horizontal-mode material into a single hbox") SILE.require("packages/bidi") return plain;
Fix \hbox’ing of unshaped nodes.
Fix \hbox’ing of unshaped nodes.
Lua
mit
alerque/sile,alerque/sile,neofob/sile,neofob/sile,simoncozens/sile,neofob/sile,simoncozens/sile,neofob/sile,alerque/sile,simoncozens/sile,simoncozens/sile,alerque/sile
7aae88044fda5701823421bd1f342cf78590d3cc
spec/01-unit/14-dns_spec.lua
spec/01-unit/14-dns_spec.lua
local mocker = require "spec.fixtures.mocker" local balancer = require "kong.runloop.balancer" local utils = require "kong.tools.utils" local ws_id = utils.uuid() local function setup_it_block() local cache_table = {} local function mock_cache(cache_table, limit) return { safe_set = function(self, k, v) if limit then local n = 0 for _, _ in pairs(cache_table) do n = n + 1 end if n >= limit then return nil, "no memory" end end cache_table[k] = v return true end, get = function(self, k, _, fn, arg) if cache_table[k] == nil then cache_table[k] = fn(arg) end return cache_table[k] end, } end mocker.setup(finally, { kong = { configuration = { worker_consistency = "strict", }, core_cache = mock_cache(cache_table), }, ngx = { ctx = { workspace = ws_id, } } }) balancer.init() end -- simple debug function local function dump(...) print(require("pl.pretty").write({...})) end describe("DNS", function() local resolver, query_func, old_new local mock_records, singletons, client lazy_setup(function() stub(ngx, "log") singletons = require "kong.singletons" singletons.core_cache = { get = function() return {} end } --[[ singletons.db = {} singletons.db.upstreams = { find_all = function(self) return {} end } --]] singletons.origins = {} resolver = require "resty.dns.resolver" client = require "kong.resty.dns.client" end) lazy_teardown(function() if type(ngx.log) == "table" then ngx.log:revert() -- luacheck: ignore end end) before_each(function() mock_records = {} -- you can replace this `query_func` upvalue to spy on resolver query calls. -- This default will look for a mock-record and if not found call the -- original resolver query_func = function(self, original_query_func, name, options) if mock_records[name .. ":" .. options.qtype] then return mock_records[name .. ":" .. options.qtype] end print("now looking for: ", name .. ":" .. options.qtype) return original_query_func(self, name, options) end -- patch the resolver lib, such that any new resolver created will query -- using the `query_func` upvalue defined above old_new = resolver.new resolver.new = function(...) local r = old_new(...) local original_query_func = r.query r.query = function(self, ...) if not query_func then print(debug.traceback("WARNING: query_func is not set")) dump(self, ...) return end return query_func(self, original_query_func, ...) end return r end client.init { hosts = {}, resolvConf = {}, nameservers = { "8.8.8.8" }, enable_ipv6 = true, order = { "LAST", "SRV", "A", "CNAME" }, } end) after_each(function() resolver.new = old_new end) it("returns an error and 503 on a Name Error (3)", function() setup_it_block() mock_records = { ["konghq.com:" .. resolver.TYPE_A] = { errcode = 3, errstr = "name error" }, ["konghq.com:" .. resolver.TYPE_AAAA] = { errcode = 3, errstr = "name error" }, ["konghq.com:" .. resolver.TYPE_CNAME] = { errcode = 3, errstr = "name error" }, ["konghq.com:" .. resolver.TYPE_SRV] = { errcode = 3, errstr = "name error" }, } local ip, port, code = balancer.execute({ type = "name", port = nil, host = "konghq.com", try_count = 0, }) assert.is_nil(ip) assert.equals("name resolution failed", port) assert.equals(503, code) end) for _, consistency in ipairs({"strict", "eventual"}) do it("returns an error and 503 on an empty record", function() setup_it_block(consistency) mock_records = { ["konghq.com:" .. resolver.TYPE_A] = {}, ["konghq.com:" .. resolver.TYPE_AAAA] = {}, ["konghq.com:" .. resolver.TYPE_CNAME] = {}, ["konghq.com:" .. resolver.TYPE_SRV] = {}, } local ip, port, code = balancer.execute({ type = "name", port = nil, host = "konghq.com", try_count = 0, }) assert.is_nil(ip) assert.equals("name resolution failed", port) assert.equals(503, code) end) end end)
local mocker = require "spec.fixtures.mocker" local balancer = require "kong.runloop.balancer" local utils = require "kong.tools.utils" local ws_id = utils.uuid() local function setup_it_block() local client = require "kong.resty.dns.client" local cache_table = {} local function mock_cache(cache_table, limit) return { safe_set = function(self, k, v) if limit then local n = 0 for _, _ in pairs(cache_table) do n = n + 1 end if n >= limit then return nil, "no memory" end end cache_table[k] = v return true end, get = function(self, k, _, fn, arg) if cache_table[k] == nil then cache_table[k] = fn(arg) end return cache_table[k] end, } end mocker.setup(finally, { kong = { configuration = { worker_consistency = "strict", }, core_cache = mock_cache(cache_table), }, ngx = { ctx = { workspace = ws_id, } } }) balancer.init() client.init { hosts = {}, resolvConf = {}, nameservers = { "8.8.8.8" }, enable_ipv6 = true, order = { "LAST", "SRV", "A", "CNAME" }, } end -- simple debug function local function dump(...) print(require("pl.pretty").write({...})) end describe("DNS", function() local resolver, query_func, old_new local mock_records, singletons lazy_setup(function() stub(ngx, "log") singletons = require "kong.singletons" singletons.core_cache = { get = function() return {} end } --[[ singletons.db = {} singletons.db.upstreams = { find_all = function(self) return {} end } --]] singletons.origins = {} resolver = require "resty.dns.resolver" end) lazy_teardown(function() if type(ngx.log) == "table" then ngx.log:revert() -- luacheck: ignore end end) before_each(function() mock_records = {} -- you can replace this `query_func` upvalue to spy on resolver query calls. -- This default will look for a mock-record and if not found call the -- original resolver query_func = function(self, original_query_func, name, options) if mock_records[name .. ":" .. options.qtype] then return mock_records[name .. ":" .. options.qtype] end print("now looking for: ", name .. ":" .. options.qtype) return original_query_func(self, name, options) end -- patch the resolver lib, such that any new resolver created will query -- using the `query_func` upvalue defined above old_new = resolver.new resolver.new = function(...) local r = old_new(...) local original_query_func = r.query r.query = function(self, ...) if not query_func then print(debug.traceback("WARNING: query_func is not set")) dump(self, ...) return end return query_func(self, original_query_func, ...) end return r end end) after_each(function() resolver.new = old_new end) it("returns an error and 503 on a Name Error (3)", function() setup_it_block() mock_records = { ["konghq.com:" .. resolver.TYPE_A] = { errcode = 3, errstr = "name error" }, ["konghq.com:" .. resolver.TYPE_AAAA] = { errcode = 3, errstr = "name error" }, ["konghq.com:" .. resolver.TYPE_CNAME] = { errcode = 3, errstr = "name error" }, ["konghq.com:" .. resolver.TYPE_SRV] = { errcode = 3, errstr = "name error" }, } local ip, port, code = balancer.execute({ type = "name", port = nil, host = "konghq.com", try_count = 0, }) assert.is_nil(ip) assert.equals("name resolution failed", port) assert.equals(503, code) end) for _, consistency in ipairs({"strict", "eventual"}) do it("returns an error and 503 on an empty record", function() setup_it_block(consistency) mock_records = { ["konghq.com:" .. resolver.TYPE_A] = {}, ["konghq.com:" .. resolver.TYPE_AAAA] = {}, ["konghq.com:" .. resolver.TYPE_CNAME] = {}, ["konghq.com:" .. resolver.TYPE_SRV] = {}, } local ip, port, code = balancer.execute({ type = "name", port = nil, host = "konghq.com", try_count = 0, }) assert.is_nil(ip) assert.equals("name resolution failed", port) assert.equals(503, code) end) end end)
tests(dns) fix dns resolve in 14-dns_spec.lua (#8300)
tests(dns) fix dns resolve in 14-dns_spec.lua (#8300) * fix dns resolve in 14-dns_spec.lu * style fix for 14-dns_spec.lua
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
74b579e28a98d0e417044224ae161575bec6653d
src/extensions/cp/apple/finalcutpro/browser/Columns.lua
src/extensions/cp/apple/finalcutpro/browser/Columns.lua
--- === cp.apple.finalcutpro.browser.Columns === --- --- Final Cut Pro Browser List View Columns local require = require --local log = require("hs.logger").new("Columns") local ax = require("hs._asm.axuielement") local geometry = require("hs.geometry") local axutils = require("cp.ui.axutils") local tools = require("cp.tools") local Element = require("cp.ui.Element") local Menu = require("cp.ui.Menu") local systemElementAtPosition = ax.systemElementAtPosition local childWithRole = axutils.childWithRole -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local Columns = Element:subclass("cp.apple.finalcutpro.browser.Columns") --- cp.apple.finalcutpro.browser.Columns(parent) -> Columns --- Constructor --- Constructs a new Columns object. --- --- Parameters: --- * parent - The parent object --- --- Returns: --- * The new `Columns` instance. function Columns:initialize(parent) local UI = parent.UI:mutate(function(original) return childWithRole(original(), "AXScrollArea") end) Element.initialize(self, parent, UI) end --- cp.apple.finalcutpro.browser.Columns:show() -> self --- Method --- Shows the Browser List View columns menu popup. --- --- Parameters: --- * None --- --- Returns: --- * Self function Columns:show() local ui = self:UI() if ui then local scrollAreaFrame = ui:attributeValue("AXFrame") local outlineUI = childWithRole(ui, "AXOutline") local scrollbarUI = childWithRole(ui, "AXScrollBar") local scrollbarFrame = scrollbarUI and scrollbarUI:attributeValue("AXFrame") local scrollbarHeight = scrollbarFrame and scrollbarFrame.h local outlineFrame = outlineUI and outlineUI:attributeValue("AXFrame") if scrollAreaFrame and outlineFrame and scrollbarHeight then local headerHeight = (scrollAreaFrame.h - scrollbarHeight) / 2 local point = geometry.point(scrollAreaFrame.x+headerHeight, scrollAreaFrame.y+headerHeight) local element = point and systemElementAtPosition(point) --cp.dev.highlightPoint(point) if element and element:attributeValue("AXParent"):attributeValue("AXParent") == outlineUI then tools.ninjaRightMouseClick(point) end end end return self end --- cp.apple.finalcutpro.browser.Columns:isMenuShowing() -> boolean --- Method --- Is the Columns menu popup showing? --- --- Parameters: --- * None --- --- Returns: --- * `true` if the columns menu popup is showing, otherwise `false` function Columns:isMenuShowing() return self:menu():isShowing() end --- cp.apple.finalcutpro.browser.Columns:menu() -> cp.ui.Menu --- Method --- Gets the Columns menu object. --- --- Parameters: --- * None --- --- Returns: --- * A `Menu` object. function Columns.lazy.method:menu() return Menu(self, self.UI:mutate(function(original) return childWithRole(childWithRole(childWithRole(original(), "AXOutline"), "AXGroup"), "AXMenu") end)) end return Columns
--- === cp.apple.finalcutpro.browser.Columns === --- --- Final Cut Pro Browser List View Columns local require = require --local log = require("hs.logger").new("Columns") local ax = require("hs._asm.axuielement") local geometry = require("hs.geometry") local axutils = require("cp.ui.axutils") local tools = require("cp.tools") local Element = require("cp.ui.Element") local Menu = require("cp.ui.Menu") local systemElementAtPosition = ax.systemElementAtPosition local childWithRole = axutils.childWithRole -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local Columns = Element:subclass("cp.apple.finalcutpro.browser.Columns") --- cp.apple.finalcutpro.browser.Columns(parent) -> Columns --- Constructor --- Constructs a new Columns object. --- --- Parameters: --- * parent - The parent object --- --- Returns: --- * The new `Columns` instance. function Columns:initialize(parent) local UI = parent.UI:mutate(function(original) return childWithRole(original(), "AXScrollArea") end) Element.initialize(self, parent, UI) end --- cp.apple.finalcutpro.browser.Columns:show() -> self --- Method --- Shows the Browser List View columns menu popup. --- --- Parameters: --- * None --- --- Returns: --- * Self function Columns:show() local ui = self:UI() if ui then local scrollAreaFrame = ui:attributeValue("AXFrame") local outlineUI = childWithRole(ui, "AXOutline") local outlineFrame = outlineUI and outlineUI:attributeValue("AXFrame") local groupUI = outlineUI and childWithRole(outlineUI, "AXGroup") local buttonUI = groupUI and groupUI[1] local buttonSize = buttonUI and buttonUI:attributeValue("AXSize") local headerHeight = buttonSize and (buttonSize.h / 2) if headerHeight then local point = geometry.point(scrollAreaFrame.x+headerHeight, scrollAreaFrame.y+headerHeight) local element = point and systemElementAtPosition(point) --cp.dev.highlightPoint(point) if element and element:attributeValue("AXParent"):attributeValue("AXParent") == outlineUI then tools.ninjaRightMouseClick(point) end end end return self end --- cp.apple.finalcutpro.browser.Columns:isMenuShowing() -> boolean --- Method --- Is the Columns menu popup showing? --- --- Parameters: --- * None --- --- Returns: --- * `true` if the columns menu popup is showing, otherwise `false` function Columns:isMenuShowing() return self:menu():isShowing() end --- cp.apple.finalcutpro.browser.Columns:menu() -> cp.ui.Menu --- Method --- Gets the Columns menu object. --- --- Parameters: --- * None --- --- Returns: --- * A `Menu` object. function Columns.lazy.method:menu() return Menu(self, self.UI:mutate(function(original) return childWithRole(childWithRole(childWithRole(original(), "AXOutline"), "AXGroup"), "AXMenu") end)) end return Columns
#1701
#1701 - Fixes a bug that still exists in `cp.apple.finalcutpro.browser.Columns:show()` - Closes #1701
Lua
mit
CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost
fd2e20440acd5c83b58cfbdf4bfee9ebed83731d
src_trunk/resources/social-system/c_player_rightclick.lua
src_trunk/resources/social-system/c_player_rightclick.lua
wRightClick = nil bAddAsFriend, bFrisk, bRestrain, bCloseMenu = nil sent = false ax, ay = nil player = nil gotClick = false function clickPlayer(button, state, absX, absY, wx, wy, wz, element) if (element) and (getElementType(element)=="player") and (button=="right") and (state=="down") and (sent==false) and (element==getLocalPlayer()) then if (wRightClick) then hidePlayerMenu() end showCursor(true) ax = absX ay = absY player = element sent = true triggerServerEvent("sendPlayerInfo", getLocalPlayer(), element) elseif not (element) then if (wRightClick) then hidePlayerMenu() end end end addEventHandler("onClientClick", getRootElement(), clickPlayer, false) function showPlayerMenu(targetPlayer, friends, description) wRightClick = guiCreateWindow(ax, ay, 150, 200, string.gsub(getPlayerName(targetPlayer), "_", " "), false) local targetid = tonumber(getElementData(targetPlayer, "gameaccountid")) local found = false for key, value in ipairs(friends) do if (friends[key]==targetid) then found = true end end if (found==false) then bAddAsFriend = guiCreateButton(0.05, 0.13, 0.87, 0.1, "Add as friend", true, wRightClick) addEventHandler("onClientGUIClick", bAddAsFriend, caddFriend, false) else bAddAsFriend = guiCreateButton(0.05, 0.13, 0.87, 0.1, "Remove friend", true, wRightClick) addEventHandler("onClientGUIClick", bAddAsFriend, cremoveFriend, false) end bCloseMenu = guiCreateButton(0.05, 0.45, 0.87, 0.1, "Close Menu", true, wRightClick) addEventHandler("onClientGUIClick", bCloseMenu, hidePlayerMenu, false) sent = false -- FRISK --bFrisk = guiCreateButton(0.05, 0.25, 0.87, 0.1, "Frisk", true, wRightClick) --addEventHandler("onClientGUIClick", bFrisk, cfriskPlayer, false) end addEvent("displayPlayerMenu", true) addEventHandler("displayPlayerMenu", getRootElement(), showPlayerMenu) -------------------- -- FRISKING -- -------------------- wFriskItems, bFriskTakeItem, bFriskClose, gFriskItems, FriskColName = nil function cfriskPlayer(button, state, x, y) if not (wFriskItems) then local width, height = 300, 200 local scrWidth, scrHeight = guiGetScreenSize() wFriskItems = guiCreateWindow(x, y, width, height, "Frisk: " .. getPlayerName(player), false) guiWindowSetSizable(wFriskItems, false) gFriskItems = guiCreateGridList(0.05, 0.1, 0.9, 0.7, true, wFriskItems) FriskColName = guiGridListAddColumn(gFriskItems, "Name", 0.9) local items = getElementData(player, "items") for i = 1, 10 do local itemID = tonumber(gettok(items, i, string.byte(','))) if (itemID~=nil) then local itemName = exports.global:cgetItemName(itemID) outputChatBox(tostring(itemName)) local row = guiGridListAddRow(gFriskItems) guiGridListSetItemText(gFriskItems, row, FriskColName, tostring(itemName), false, false) end end bFriskTakeItem = guiCreateButton(0.05, 0.85, 0.45, 0.1, "Take Item", true, wFriskItems) bFriskClose = guiCreateButton(0.5, 0.85, 0.45, 0.1, "Close", true, wFriskItems) addEventHandler("onClientGUIClick", bFrisk, hidePlayerMenu, false) else guiBringToFront(wFriskItems, true) end end -------------------- -- END FRISKING -- -------------------- function caddFriend() triggerServerEvent("addFriend", getLocalPlayer(), player) hidePlayerMenu() end function cremoveFriend() local id = tonumber(getElementData(player, "gameaccountid")) local username = getPlayerName(player) triggerServerEvent("removeFriend", getLocalPlayer(), id, username, true) hidePlayerMenu() end function hidePlayerMenu() destroyElement(bAddAsFriend) bAddAsFriend = nil destroyElement(wRightClick) wRightClick = nil ax = nil ay = nil player = nil showCursor(false) end
wRightClick = nil bAddAsFriend, bFrisk, bRestrain, bCloseMenu = nil sent = false ax, ay = nil player = nil gotClick = false closing = false function clickPlayer(button, state, absX, absY, wx, wy, wz, element) if (element) and (getElementType(element)=="player") and (button=="right") and (state=="down") and (sent==false) and (element==getLocalPlayer()) then if (wRightClick) then hidePlayerMenu() end showCursor(true) ax = absX ay = absY player = element sent = true closing = false triggerServerEvent("sendPlayerInfo", getLocalPlayer(), element) end end addEventHandler("onClientClick", getRootElement(), clickPlayer, true) function showPlayerMenu(targetPlayer, friends, description) wRightClick = guiCreateWindow(ax, ay, 150, 200, string.gsub(getPlayerName(targetPlayer), "_", " "), false) local targetid = tonumber(getElementData(targetPlayer, "gameaccountid")) local found = false for key, value in ipairs(friends) do if (friends[key]==targetid) then found = true end end if (found==false) then bAddAsFriend = guiCreateButton(0.05, 0.13, 0.87, 0.1, "Add as friend", true, wRightClick) addEventHandler("onClientGUIClick", bAddAsFriend, caddFriend, false) else bAddAsFriend = guiCreateButton(0.05, 0.13, 0.87, 0.1, "Remove friend", true, wRightClick) addEventHandler("onClientGUIClick", bAddAsFriend, cremoveFriend, false) end bCloseMenu = guiCreateButton(0.05, 0.25, 0.87, 0.1, "Close Menu", true, wRightClick) addEventHandler("onClientGUIClick", bCloseMenu, hidePlayerMenu, false) sent = false -- FRISK --bFrisk = guiCreateButton(0.05, 0.25, 0.87, 0.1, "Frisk", true, wRightClick) --addEventHandler("onClientGUIClick", bFrisk, cfriskPlayer, false) end addEvent("displayPlayerMenu", true) addEventHandler("displayPlayerMenu", getRootElement(), showPlayerMenu) -------------------- -- FRISKING -- -------------------- wFriskItems, bFriskTakeItem, bFriskClose, gFriskItems, FriskColName = nil function cfriskPlayer(button, state, x, y) if not (wFriskItems) then local width, height = 300, 200 local scrWidth, scrHeight = guiGetScreenSize() wFriskItems = guiCreateWindow(x, y, width, height, "Frisk: " .. getPlayerName(player), false) guiWindowSetSizable(wFriskItems, false) gFriskItems = guiCreateGridList(0.05, 0.1, 0.9, 0.7, true, wFriskItems) FriskColName = guiGridListAddColumn(gFriskItems, "Name", 0.9) local items = getElementData(player, "items") for i = 1, 10 do local itemID = tonumber(gettok(items, i, string.byte(','))) if (itemID~=nil) then local itemName = exports.global:cgetItemName(itemID) outputChatBox(tostring(itemName)) local row = guiGridListAddRow(gFriskItems) guiGridListSetItemText(gFriskItems, row, FriskColName, tostring(itemName), false, false) end end bFriskTakeItem = guiCreateButton(0.05, 0.85, 0.45, 0.1, "Take Item", true, wFriskItems) bFriskClose = guiCreateButton(0.5, 0.85, 0.45, 0.1, "Close", true, wFriskItems) addEventHandler("onClientGUIClick", bFrisk, hidePlayerMenu, false) else guiBringToFront(wFriskItems, true) end end -------------------- -- END FRISKING -- -------------------- function caddFriend() triggerServerEvent("addFriend", getLocalPlayer(), player) hidePlayerMenu() end function cremoveFriend() local id = tonumber(getElementData(player, "gameaccountid")) local username = getPlayerName(player) triggerServerEvent("removeFriend", getLocalPlayer(), id, username, true) hidePlayerMenu() end function hidePlayerMenu() destroyElement(bAddAsFriend) bAddAsFriend = nil destroyElement(bCloseMenu) bCloseMenu = nil destroyElement(wRightClick) wRightClick = nil ax = nil ay = nil player = nil sent = false showCursor(false) end
Crash fix for right click of player
Crash fix for right click of player git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@253 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
e8eef4bce44ed2fa0649cd29b1299df1b709a291
lib/xjob.lua
lib/xjob.lua
--- SCP commands function uploadFile(conf, localfile, remotefile) if (not remotefile) then remotefile = "./" end local scpcmd = 'scp -i '.. conf.sshkey .. ' ' .. localfile .. ' ' .. conf.user ..'@'.. conf.server .. ':' .. remotefile; --print('CMD>' .. scpcmd) local handle = io.popen(scpcmd) local result = handle:read("*a") --print('OUT>' .. result) handle:close() return result end function downloadFile(conf, remotefile, localfile) if (not localfile) then localfile = "./" end local scpcmd = 'scp -i '.. conf.sshkey .. ' ' .. conf.user ..'@'.. conf.server .. ':' .. remotefile .. ' ' .. localfile; --print('CMD>' .. scpcmd) local handle = io.popen(scpcmd) local result = handle:read("*a") --print('OUT>' .. result) handle:close() return result end --- Remote(ssh) commands local function sshCmd(user, server, key, cmd, disableErr) local sshcmd = 'ssh -i '.. key .. ' ' .. user ..'@'.. server .. ' "' .. cmd ..'"' .. (disableErr and ' 2>/dev/null' or '') --print('CMD>' .. sshcmd) local handle = io.popen(sshcmd) local result = handle:read("*a") --print('OUT>' .. result) handle:close() return result end function remoteExtractFile(conf, filepath, varbose) local option = verbose and 'xvf' or 'xf' local cmd = 'tar ' .. option .. ' ' .. filepath return sshCmd(conf.user, conf.server, conf.sshkey, cmd) end function remoteCompressFile(conf, srcfile, tarfile, verbose) local option = verbose and 'czvf' or 'czf' local cmd = 'tar ' .. option .. ' ' .. tarfile .. ' ' .. srcfile return sshCmd(conf.user, conf.server, conf.sshkey, cmd) end function remoteDeleteFile(conf, filename) -- TODO print('not implemented yet!') end function remoteMoveFile(conf, fromFile, toFile) -- TODO print('not implemented yet!') end function remoteCopyFile(conf, fromFile, toFile) -- TODO print('not implemented yet!') end function remoteMakeDir(conf, dirpath) -- TODO print('not implemented yet!') end function remoteDeleteDir(conf, dirname) -- TODO print('not implemented yet!') end local function split(str, delim) local result,pat,lastPos = {},"(.-)" .. delim .. "()",1 for part, pos in string.gmatch(str, pat) do --print(pos, part) table.insert(result, part); lastPos = pos end table.insert(result, string.sub(str, lastPos)) return result end local function statSplit(res) local t = split(res, '\n') local statTable = {} for i,v in pairs(t) do local ss = string.gmatch(v,"[^%s]+") local statColumn = {} for k in ss do statColumn[#statColumn + 1] = k; end statTable[#statTable+1] = statColumn end return statTable end local function parseJobID(conf, cmdret) local t = split(cmdret, ' ') return t[conf.submitIDRow] end local function parseJobStat(conf, cmdret, jobid) local t = statSplit(cmdret) --[[ print('===============') for i,j in pairs(t) do io.write(i .. ',') for k,w in pairs(j) do io.write(k .. ': ' .. w .. ' ') end io.write('\n') end print('===============') --]] if (t[1][1] == 'Invalid' and t[1][2] == 'job') then -- END return 'END' end if (#t >= conf.statStateColumn and #(t[conf.statStateColumn]) >= conf.statStateRow) then return t[conf.statStateColumn][conf.statStateRow]; else return 'END' -- not found job end end function remoteJobSubmit(conf, jobdata) local cmdTarget = 'cd ' .. jobdata.targetpath ..';' local cmdSubmit = cmdTarget .. conf.submitCmd .. ' ' .. jobdata.job --print(cmdSubmit) local cmdret = sshCmd(conf.user, conf.server, conf.sshkey, cmdSubmit, true) local jobid = parseJobID(conf, cmdret) jobdata.id = jobid --print('JOB ID = '.. jobid) return jobid end function remoteJobDel(conf, jobdata) if (not jobdata.id) then print('[Error] job id is invalid') return end local cmdDel = conf.delCmd .. ' ' .. jobdata.id --print(cmdDel) local cmdret = sshCmd(conf.user, conf.server, conf.sshkey, cmdDel, true) end function remoteJobStat(conf, jobdata) local cmdStat = conf.statCmd .. ' ' .. (jobdata.id and jobdata.id or '') --print(cmdStat) local cmdret = sshCmd(conf.user, conf.server, conf.sshkey, cmdStat, true) local jobstat = parseJobStat(conf, cmdret, jobdata.id) --print('JOB ST = ' .. jobstat) return jobstat end
--- SCP commands function uploadFile(conf, localfile, remotefile) if (not remotefile) then remotefile = "./" end local scpcmd = 'scp -i '.. conf.sshkey .. ' ' .. localfile .. ' ' .. conf.user ..'@'.. conf.server .. ':' .. remotefile; --print('CMD>' .. scpcmd) local handle = io.popen(scpcmd) local result = handle:read("*a") --print('OUT>' .. result) handle:close() return result end function downloadFile(conf, remotefile, localfile) if (not localfile) then localfile = "./" end local scpcmd = 'scp -i '.. conf.sshkey .. ' ' .. conf.user ..'@'.. conf.server .. ':' .. remotefile .. ' ' .. localfile; --print('CMD>' .. scpcmd) local handle = io.popen(scpcmd) local result = handle:read("*a") --print('OUT>' .. result) handle:close() return result end --- Remote(ssh) commands local function sshCmd(user, server, key, cmd, disableErr) local nullDev = '/dev/null' if (getPlatform() == 'Windows') then disableErr = false end local sshcmd = 'ssh -i '.. key .. ' ' .. user ..'@'.. server .. ' "' .. cmd ..'"' .. (disableErr and (' 2>'..nullDev) or '') --print('CMD>' .. sshcmd) local handle = io.popen(sshcmd) local result = handle:read("*a") --print('OUT>' .. result) handle:close() return result end function remoteExtractFile(conf, filepath, varbose) local option = verbose and 'xvf' or 'xf' local cmd = 'tar ' .. option .. ' ' .. filepath return sshCmd(conf.user, conf.server, conf.sshkey, cmd) end function remoteCompressFile(conf, srcfile, tarfile, verbose) local option = verbose and 'czvf' or 'czf' local cmd = 'tar ' .. option .. ' ' .. tarfile .. ' ' .. srcfile return sshCmd(conf.user, conf.server, conf.sshkey, cmd) end function remoteDeleteFile(conf, filename) -- TODO print('not implemented yet!') end function remoteMoveFile(conf, fromFile, toFile) -- TODO print('not implemented yet!') end function remoteCopyFile(conf, fromFile, toFile) -- TODO print('not implemented yet!') end function remoteMakeDir(conf, dirpath) -- TODO print('not implemented yet!') end function remoteDeleteDir(conf, dirname) -- TODO print('not implemented yet!') end local function split(str, delim) local result,pat,lastPos = {},"(.-)" .. delim .. "()",1 for part, pos in string.gmatch(str, pat) do --print(pos, part) table.insert(result, part); lastPos = pos end table.insert(result, string.sub(str, lastPos)) return result end local function statSplit(res) local t = split(res, '\n') local statTable = {} for i,v in pairs(t) do local ss = string.gmatch(v,"[^%s]+") local statColumn = {} for k in ss do statColumn[#statColumn + 1] = k; end statTable[#statTable+1] = statColumn end return statTable end local function parseJobID(conf, cmdret) local t = split(cmdret, ' ') return t[conf.submitIDRow] end local function parseJobStat(conf, cmdret, jobid) local t = statSplit(cmdret) --[[ print('===============') for i,j in pairs(t) do io.write(i .. ',') for k,w in pairs(j) do io.write(k .. ': ' .. w .. ' ') end io.write('\n') end print('===============') --]] if (t[1][1] == 'Invalid' and t[1][2] == 'job') then -- END return 'END' end if (#t >= conf.statStateColumn and #(t[conf.statStateColumn]) >= conf.statStateRow) then return t[conf.statStateColumn][conf.statStateRow]; else return 'END' -- not found job end end function remoteJobSubmit(conf, jobdata) local cmdTarget = 'cd ' .. jobdata.targetpath ..';' local cmdSubmit = cmdTarget .. conf.submitCmd .. ' ' .. jobdata.job --print(cmdSubmit) local cmdret = sshCmd(conf.user, conf.server, conf.sshkey, cmdSubmit, true) local jobid = parseJobID(conf, cmdret) jobdata.id = jobid --print('JOB ID = '.. jobid) return jobid end function remoteJobDel(conf, jobdata) if (not jobdata.id) then print('[Error] job id is invalid') return end local cmdDel = conf.delCmd .. ' ' .. jobdata.id --print(cmdDel) local cmdret = sshCmd(conf.user, conf.server, conf.sshkey, cmdDel, true) end function remoteJobStat(conf, jobdata) local cmdStat = conf.statCmd .. ' ' .. (jobdata.id and jobdata.id or '') --print(cmdStat) local cmdret = sshCmd(conf.user, conf.server, conf.sshkey, cmdStat, true) local jobstat = parseJobStat(conf, cmdret, jobdata.id) --print('JOB ST = ' .. jobstat) return jobstat end
fixed for windows
fixed for windows
Lua
bsd-2-clause
avr-aics-riken/hpcpfGUI,avr-aics-riken/hpcpfGUI,digirea/hpcpfGUI,digirea/hpcpfGUI,avr-aics-riken/hpcpfGUI,digirea/hpcpfGUI
f0a98f01ffeeb1adb852eb658b887e0f47794c76
lua/mp_menu/sidebar_tabs.lua
lua/mp_menu/sidebar_tabs.lua
local math = math local ceil = math.ceil local clamp = math.Clamp local surface = surface local color_white = color_white local PANEL = {} PANEL.TabHeight = 43 function PANEL:Init() self:SetShowIcons( false ) self:SetFadeTime( 0 ) self:SetPadding( 0 ) self.animFade = Derma_Anim( "Fade", self, self.CrossFade ) self.Items = {} end function PANEL:Paint( w, h ) end function PANEL:AddSheet( label, panel, material, NoStretchX, NoStretchY, Tooltip ) if not IsValid( panel ) then return end local Sheet = {} Sheet.Name = label Sheet.Tab = vgui.Create( "MP.SidebarTab", self ) Sheet.Tab:SetTooltip( Tooltip ) Sheet.Tab:Setup( label, self, panel, material ) Sheet.Panel = panel Sheet.Panel.NoStretchX = NoStretchX Sheet.Panel.NoStretchY = NoStretchY Sheet.Panel:SetPos( self:GetPadding(), self.TabHeight + self:GetPadding() ) Sheet.Panel:SetVisible( false ) panel:SetParent( self ) table.insert( self.Items, Sheet ) if not self:GetActiveTab() then self:SetActiveTab( Sheet.Tab ) Sheet.Panel:SetVisible( true ) end -- self.tabScroller:AddPanel( Sheet.Tab ) return Sheet end function PANEL:PerformLayout() local ActiveTab = self:GetActiveTab() local Padding = self:GetPadding() if not ActiveTab then return end -- Update size now, so the height is definitiely right. ActiveTab:InvalidateLayout( true ) local ActivePanel = ActiveTab:GetPanel() local numItems = #self.Items local tabWidth = ceil(self:GetWide() / numItems) local tab for k, v in pairs( self.Items ) do tab = v.Tab tab:SetSize( tabWidth, self.TabHeight ) tab:SetPos( (k-1) * tabWidth ) -- Handle tab panel visibility if tab:GetPanel() == ActivePanel then tab:GetPanel():SetVisible( true ) tab:SetZPos( 100 ) else tab:GetPanel():SetVisible( false ) tab:SetZPos( 1 ) end tab:ApplySchemeSettings() end ActivePanel:SetWide( self:GetWide() - Padding * 2 ) ActivePanel:SetTall( (self:GetTall() - ActiveTab:GetTall() ) - Padding ) ActivePanel:InvalidateLayout() -- Give the animation a chance self.animFade:Run() end derma.DefineControl( "MP.SidebarTabs", "", PANEL, "DPropertySheet" ) local SIDEBAR_TAB = {} surface.CreateFont( "MP.TabTitle", { font = "Roboto Regular", size = 16, weight = 400 } ) SIDEBAR_TAB.BgColor = Color( 28, 100, 157 ) SIDEBAR_TAB.SelectedBorderColor = color_white SIDEBAR_TAB.SelectedBorderHeight = 2 function SIDEBAR_TAB:Init() self.BaseClass.Init( self ) self:SetFont( "MP.TabTitle" ) self:SetContentAlignment( 5 ) self:SetTextInset( 0, 0 ) end function SIDEBAR_TAB:Paint( w, h ) surface.SetDrawColor( self.BgColor ) surface.DrawRect( 0, 0, w, h ) if self:IsActive() then surface.SetDrawColor( self.SelectedBorderColor ) surface.DrawRect( 0, h - self.SelectedBorderHeight, w, self.SelectedBorderHeight ) end end function SIDEBAR_TAB:ApplySchemeSettings() self:SetTextInset( 0, 0 ) DLabel.ApplySchemeSettings( self ) end derma.DefineControl( "MP.SidebarTab", "", SIDEBAR_TAB, "DTab" ) local CURRENTLY_PLAYING_TAB = {} AccessorFunc( CURRENTLY_PLAYING_TAB, "MediaPlayerId", "MediaPlayerId" ) CURRENTLY_PLAYING_TAB.BgColor = Color( 7, 21, 33 ) function CURRENTLY_PLAYING_TAB:Init() self.QueuePanel = vgui.Create( "MP.Queue", self ) self.QueuePanel:Dock( FILL ) self.QueuePanel:DockMargin( 0, -4, 0, 0 ) -- fix offset due to seekbar self.PlaybackPanel = vgui.Create( "MP.Playback", self ) self.PlaybackPanel:Dock( TOP ) hook.Add( MP.EVENTS.UI.MEDIA_PLAYER_CHANGED, self, self.OnMediaPlayerChanged ) end function CURRENTLY_PLAYING_TAB:OnMediaPlayerChanged( mp ) self:SetMediaPlayerId( mp:GetId() ) if not self.MediaChangedHandle then -- set current media self.PlaybackPanel:OnMediaChanged( mp:GetMedia() ) -- listen for any future media changes self.MediaChangedHandle = function(...) if ValidPanel(self.PlaybackPanel) then self.PlaybackPanel:OnMediaChanged(...) end end mp:on( MP.EVENTS.MEDIA_CHANGED, self.MediaChangedHandle ) end if not self.QueueChangedHandle then -- set current queue self.QueuePanel:OnQueueChanged( mp:GetMediaQueue() ) -- listen for any future media changes self.QueueChangedHandle = function(...) if ValidPanel(self.QueuePanel) then self.QueuePanel:OnQueueChanged(...) end end mp:on( MP.EVENTS.QUEUE_CHANGED, self.QueueChangedHandle ) end if not self.PlayerStateChangeHandle then -- set current player state self.PlaybackPanel:OnPlayerStateChanged( mp:GetPlayerState() ) -- listen for any future player state changes self.PlayerStateChangeHandle = function(...) if ValidPanel(self.PlaybackPanel) then self.PlaybackPanel:OnPlayerStateChanged(...) end end mp:on( MP.EVENTS.PLAYER_STATE_CHANGED, self.PlayerStateChangeHandle ) end end function CURRENTLY_PLAYING_TAB:OnRemove() hook.Remove( MP.EVENTS.UI.MEDIA_PLAYER_CHANGED, self ) local mpId = self:GetMediaPlayerId() local mp = MediaPlayer.GetById( mpId ) if mp then mp:removeListener( MP.EVENTS.MEDIA_CHANGED, self.MediaChangedHandle ) mp:removeListener( MP.EVENTS.QUEUE_CHANGED, self.QueueChangedHandle ) mp:removeListener( MP.EVENTS.PLAYER_STATE_CHANGED, self.PlayerStateChangeHandle ) end end function CURRENTLY_PLAYING_TAB:Paint( w, h ) surface.SetDrawColor( self.BgColor ) surface.DrawRect( 0, 0, w, h ) end derma.DefineControl( "MP.CurrentlyPlayingTab", "", CURRENTLY_PLAYING_TAB, "Panel" )
local math = math local ceil = math.ceil local clamp = math.Clamp local surface = surface local color_white = color_white local PANEL = {} PANEL.TabHeight = 43 function PANEL:Init() self:SetShowIcons( false ) self:SetFadeTime( 0 ) self:SetPadding( 0 ) self.animFade = Derma_Anim( "Fade", self, self.CrossFade ) self.Items = {} end function PANEL:Paint( w, h ) end function PANEL:AddSheet( label, panel, material, NoStretchX, NoStretchY, Tooltip ) if not IsValid( panel ) then return end local Sheet = {} Sheet.Name = label Sheet.Tab = vgui.Create( "MP.SidebarTab", self ) Sheet.Tab:SetTooltip( Tooltip ) Sheet.Tab:Setup( label, self, panel, material ) Sheet.Panel = panel Sheet.Panel.NoStretchX = NoStretchX Sheet.Panel.NoStretchY = NoStretchY Sheet.Panel:SetPos( self:GetPadding(), self.TabHeight + self:GetPadding() ) Sheet.Panel:SetVisible( false ) panel:SetParent( self ) table.insert( self.Items, Sheet ) if not self:GetActiveTab() then self:SetActiveTab( Sheet.Tab ) Sheet.Panel:SetVisible( true ) end -- self.tabScroller:AddPanel( Sheet.Tab ) return Sheet end function PANEL:PerformLayout() local ActiveTab = self:GetActiveTab() local Padding = self:GetPadding() if not ActiveTab then return end -- Update size now, so the height is definitiely right. ActiveTab:InvalidateLayout( true ) local ActivePanel = ActiveTab:GetPanel() local numItems = #self.Items local tabWidth = ceil(self:GetWide() / numItems) local tab for k, v in pairs( self.Items ) do tab = v.Tab tab:SetSize( tabWidth, self.TabHeight ) tab:SetPos( (k-1) * tabWidth ) -- Handle tab panel visibility if tab:GetPanel() == ActivePanel then tab:GetPanel():SetVisible( true ) tab:SetZPos( 100 ) else tab:GetPanel():SetVisible( false ) tab:SetZPos( 1 ) end tab:ApplySchemeSettings() end ActivePanel:SetWide( self:GetWide() - Padding * 2 ) ActivePanel:SetTall( (self:GetTall() - ActiveTab:GetTall() ) - Padding ) ActivePanel:InvalidateLayout() -- Give the animation a chance self.animFade:Run() end derma.DefineControl( "MP.SidebarTabs", "", PANEL, "DPropertySheet" ) local SIDEBAR_TAB = {} surface.CreateFont( "MP.TabTitle", { font = "Roboto Regular", size = 16, weight = 400 } ) SIDEBAR_TAB.BgColor = Color( 28, 100, 157 ) SIDEBAR_TAB.SelectedBorderColor = color_white SIDEBAR_TAB.SelectedBorderHeight = 2 function SIDEBAR_TAB:Init() self.BaseClass.Init( self ) self:SetFont( "MP.TabTitle" ) self:SetContentAlignment( 5 ) self:SetTextInset( 0, 0 ) end function SIDEBAR_TAB:Paint( w, h ) surface.SetDrawColor( self.BgColor ) surface.DrawRect( 0, 0, w, h ) if self:IsActive() then surface.SetDrawColor( self.SelectedBorderColor ) surface.DrawRect( 0, h - self.SelectedBorderHeight, w, self.SelectedBorderHeight ) end end function SIDEBAR_TAB:ApplySchemeSettings() self:SetTextInset( 0, 0 ) -- TODO: this errors as of version 2015.03.09 -- DLabel.ApplySchemeSettings( self ) end derma.DefineControl( "MP.SidebarTab", "", SIDEBAR_TAB, "DTab" ) local CURRENTLY_PLAYING_TAB = {} AccessorFunc( CURRENTLY_PLAYING_TAB, "MediaPlayerId", "MediaPlayerId" ) CURRENTLY_PLAYING_TAB.BgColor = Color( 7, 21, 33 ) function CURRENTLY_PLAYING_TAB:Init() self.QueuePanel = vgui.Create( "MP.Queue", self ) self.QueuePanel:Dock( FILL ) self.QueuePanel:DockMargin( 0, -4, 0, 0 ) -- fix offset due to seekbar self.PlaybackPanel = vgui.Create( "MP.Playback", self ) self.PlaybackPanel:Dock( TOP ) hook.Add( MP.EVENTS.UI.MEDIA_PLAYER_CHANGED, self, self.OnMediaPlayerChanged ) end function CURRENTLY_PLAYING_TAB:OnMediaPlayerChanged( mp ) self:SetMediaPlayerId( mp:GetId() ) if not self.MediaChangedHandle then -- set current media self.PlaybackPanel:OnMediaChanged( mp:GetMedia() ) -- listen for any future media changes self.MediaChangedHandle = function(...) if ValidPanel(self.PlaybackPanel) then self.PlaybackPanel:OnMediaChanged(...) end end mp:on( MP.EVENTS.MEDIA_CHANGED, self.MediaChangedHandle ) end if not self.QueueChangedHandle then -- set current queue self.QueuePanel:OnQueueChanged( mp:GetMediaQueue() ) -- listen for any future media changes self.QueueChangedHandle = function(...) if ValidPanel(self.QueuePanel) then self.QueuePanel:OnQueueChanged(...) end end mp:on( MP.EVENTS.QUEUE_CHANGED, self.QueueChangedHandle ) end if not self.PlayerStateChangeHandle then -- set current player state self.PlaybackPanel:OnPlayerStateChanged( mp:GetPlayerState() ) -- listen for any future player state changes self.PlayerStateChangeHandle = function(...) if ValidPanel(self.PlaybackPanel) then self.PlaybackPanel:OnPlayerStateChanged(...) end end mp:on( MP.EVENTS.PLAYER_STATE_CHANGED, self.PlayerStateChangeHandle ) end end function CURRENTLY_PLAYING_TAB:OnRemove() hook.Remove( MP.EVENTS.UI.MEDIA_PLAYER_CHANGED, self ) local mpId = self:GetMediaPlayerId() local mp = MediaPlayer.GetById( mpId ) if mp then mp:removeListener( MP.EVENTS.MEDIA_CHANGED, self.MediaChangedHandle ) mp:removeListener( MP.EVENTS.QUEUE_CHANGED, self.QueueChangedHandle ) mp:removeListener( MP.EVENTS.PLAYER_STATE_CHANGED, self.PlayerStateChangeHandle ) end end function CURRENTLY_PLAYING_TAB:Paint( w, h ) surface.SetDrawColor( self.BgColor ) surface.DrawRect( 0, 0, w, h ) end derma.DefineControl( "MP.CurrentlyPlayingTab", "", CURRENTLY_PLAYING_TAB, "Panel" )
Fixed vgui Lua error.
Fixed vgui Lua error.
Lua
mit
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
5ae92b4dc494d27fc8c94cab50000c95fa2a4d0c
premake4.lua
premake4.lua
solution "alloy" configurations { "Debug", "Release" } -- get data from shell LLVM_OPTIONS = "--system-libs --libs " LLVM_CONFIG = "core analysis executionengine jit interpreter native " LLVM_CFLAGS = "$(" .. "llvm-config --cflags " .. LLVM_OPTIONS .. LLVM_CONFIG .. ")" LLVM_LFLAGS = "$(" .. "llvm-config --ldflags " .. LLVM_OPTIONS .. LLVM_CONFIG .. ")" -- common settings defines { "_GNU_SOURCE", "__STDC_LIMIT_MACROS", "__STDC_CONSTANT_MACROS" } buildoptions { LLVM_CFLAGS, "-pthread", "-xc" } includedirs { "includes" } links { "dl", "ncurses", "z" } linkoptions { LLVM_LFLAGS, "-pthread", "-Wl,--as-needed -ltinfo" } configuration "Debug" flags { "Symbols", "ExtraWarnings", "FatalWarnings" } configuration "Release" buildoptions { "-march=native", "-O2" } -- compiler project "alloyc" kind "ConsoleApp" language "C++" -- because LLVM is a bitchling files { "src/*.c", "src/*.h" }
solution "alloy" configurations { "Debug", "Release" } -- missing function if not os.outputof then function os.outputof(cmd) local pipe = io.popen(cmd) local result = pipe:read('*a') pipe:close() result = result:gsub ("\n", " ") return result end end -- get data from shell LLVM_OPTIONS = "--system-libs --libs " LLVM_CFLAGS = os.outputof ("llvm-config --cflags ") LLVM_LFLAGS = os.outputof ("llvm-config --ldflags " .. LLVM_OPTIONS .. "all") -- sanitize inputs -- LLVM_CFLAGS = string.gsub (LLVM_CFLAGS, "\n", " ") -- LLVM_LFLAGS = string.gsub (LLVM_LFLAGS, "\n", " ") -- common settings defines { "_GNU_SOURCE", "__STDC_LIMIT_MACROS", "__STDC_CONSTANT_MACROS" } buildoptions { LLVM_CFLAGS, "-pthread", "-xc", "-O0" } includedirs { "includes" } links { "dl" } linkoptions { LLVM_LFLAGS, "-pthread" } if os.is ("linux") then linkoptions { "-Wl,--as-needed -ltinfo" } end configuration "Debug" flags { "Symbols", "ExtraWarnings" } configuration "Release" buildoptions { "-march=native", "-O2" } -- compiler project "alloyc" kind "ConsoleApp" language "C++" -- because LLVM is a bitchling files { "src/*.c", "src/*.h" }
fix various premake/makefile/LLVM errors
fix various premake/makefile/LLVM errors
Lua
mit
dansawkins/ark,dansawkins/ark,naegelejd/ark,8l/ark-c,8l/ark-c,8l/ark-c,naegelejd/ark,naegelejd/ark
050752a4ae302384e5008943a7417593e0597b91
applications/luci-app-ddns/luasrc/model/cbi/ddns/hints.lua
applications/luci-app-ddns/luasrc/model/cbi/ddns/hints.lua
-- Copyright 2014-2016 Christian Schoenebeck <christian dot schoenebeck at gmail dot com> -- Licensed to the public under the Apache License 2.0. local DISP = require "luci.dispatcher" local SYS = require "luci.sys" local CTRL = require "luci.controller.ddns" -- this application's controller local DDNS = require "luci.tools.ddns" -- ddns multiused functions -- html constants font_red = [[<font color="red">]] font_off = [[</font>]] bold_on = [[<strong>]] bold_off = [[</strong>]] -- cbi-map definition -- ####################################################### m = Map("ddns") m.title = CTRL.app_title_back() m.description = CTRL.app_description() m.redirect = DISP.build_url("admin", "services", "ddns") -- SimpleSection definition -- ################################################# -- show Hints to optimize installation and script usage s = m:section( SimpleSection, translate("Hints"), translate("Below a list of configuration tips for your system to run Dynamic DNS updates without limitations") ) -- ddns-scripts needs to be updated for full functionality if not CTRL.service_ok() then local so = s:option(DummyValue, "_update_needed") so.titleref = DISP.build_url("admin", "system", "packages") so.rawhtml = true so.title = font_red .. bold_on .. translate("Software update required") .. bold_off .. font_off so.value = translate("The currently installed 'ddns-scripts' package did not support all available settings.") .. "<br />" .. translate("Please update to the current version!") end -- DDNS Service disabled if not SYS.init.enabled("ddns") then local se = s:option(DummyValue, "_not_enabled") se.titleref = DISP.build_url("admin", "system", "startup") se.rawhtml = true se.title = bold_on .. translate("DDNS Autostart disabled") .. bold_off se.value = translate("Currently DDNS updates are not started at boot or on interface events." .. "<br />" .. "This is the default if you run DDNS scripts by yourself (i.e. via cron with force_interval set to '0')" ) end -- No IPv6 support if not DDNS.env_info("has_ipv6") then local v6 = s:option(DummyValue, "_no_ipv6") v6.titleref = 'http://www.openwrt.org" target="_blank' v6.rawhtml = true v6.title = bold_on .. translate("IPv6 not supported") .. bold_off v6.value = translate("IPv6 is currently not (fully) supported by this system" .. "<br />" .. "Please follow the instructions on OpenWrt's homepage to enable IPv6 support" .. "<br />" .. "or update your system to the latest OpenWrt Release") end -- No HTTPS support if not DDNS.env_info("has_ssl") then local sl = s:option(DummyValue, "_no_https") sl.titleref = DISP.build_url("admin", "system", "packages") sl.rawhtml = true sl.title = bold_on .. translate("HTTPS not supported") .. bold_off sl.value = translate("Neither GNU Wget with SSL nor cURL installed to support secure updates via HTTPS protocol.") .. "<br />- " .. translate("You should install 'wget' or 'curl' or 'uclient-fetch' with 'libustream-*ssl' package.") .. "<br />- " .. translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.") end -- No bind_network if not DDNS.env_info("has_bindnet") then local bn = s:option(DummyValue, "_no_bind_network") bn.titleref = DISP.build_url("admin", "system", "packages") bn.rawhtml = true bn.title = bold_on .. translate("Binding to a specific network not supported") .. bold_off bn.value = translate("Neither GNU Wget with SSL nor cURL installed to select a network to use for communication.") .. "<br />- " .. translate("You should install 'wget' or 'curl' package.") .. "<br />- " .. translate("GNU Wget will use the IP of given network, cURL will use the physical interface.") .. "<br />- " .. translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.") end -- currently only cURL possibly without proxy support if not DDNS.env_info("has_proxy") then local px = s:option(DummyValue, "_no_proxy") px.titleref = DISP.build_url("admin", "system", "packages") px.rawhtml = true px.title = bold_on .. translate("cURL without Proxy Support") .. bold_off px.value = translate("cURL is installed, but libcurl was compiled without proxy support.") .. "<br />- " .. translate("You should install 'wget' or 'uclient-fetch' package or replace libcurl.") .. "<br />- " .. translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.") end -- "Force IP Version not supported" if not DDNS.env_info("has_forceip") then local fi = s:option(DummyValue, "_no_force_ip") fi.titleref = DISP.build_url("admin", "system", "packages") fi.rawhtml = true fi.title = bold_on .. translate("Force IP Version not supported") .. bold_off local value = translate("BusyBox's nslookup and Wget do not support to specify " .. "the IP version to use for communication with DDNS Provider!") if not (DDNS.env_info("has_wgetssl") or DDNS.env_info("has_curl") or DDNS.env_info("has_fetch")) then value = value .. "<br />- " .. translate("You should install 'wget' or 'curl' or 'uclient-fetch' package.") end if not DDNS.env_info("has_bindhost") then value = value .. "<br />- " .. translate("You should install 'bind-host' or 'knot-host' or 'drill' package for DNS requests.") end fi.value = value end -- "DNS requests via TCP not supported" if not DDNS.env_info("has_bindhost") then local dt = s:option(DummyValue, "_no_dnstcp") dt.titleref = DISP.build_url("admin", "system", "packages") dt.rawhtml = true dt.title = bold_on .. translate("DNS requests via TCP not supported") .. bold_off dt.value = translate("BusyBox's nslookup and hostip do not support to specify to use TCP " .. "instead of default UDP when requesting DNS server!") .. "<br />- " .. translate("You should install 'bind-host' or 'knot-host' or 'drill' package for DNS requests.") end -- nslookup compiled with musl produce problems when using if not DDNS.env_info("has_dnsserver") then local ds = s:option(DummyValue, "_no_dnsserver") ds.titleref = DISP.build_url("admin", "system", "packages") ds.rawhtml = true ds.title = bold_on .. translate("Using specific DNS Server not supported") .. bold_off ds.value = translate("BusyBox's nslookup in the current compiled version " .. "does not handle given DNS Servers correctly!") .. "<br />- " .. translate("You should install 'bind-host' or 'knot-host' or 'drill' or 'hostip' package, " .. "if you need to specify a DNS server to detect your registered IP.") end -- certificates installed if DDNS.env_info("has_ssl") and not DDNS.env_info("has_cacerts") then local ca = s:option(DummyValue, "_no_certs") ca.titleref = DISP.build_url("admin", "system", "packages") ca.rawhtml = true ca.title = bold_on .. translate("No certificates found") .. bold_off ca.value = translate("If using secure communication you should verify server certificates!") .. "<br />- " .. translate("Install 'ca-certificates' package or needed certificates " .. "by hand into /etc/ssl/certs default directory") end return m
-- Copyright 2014-2016 Christian Schoenebeck <christian dot schoenebeck at gmail dot com> -- Licensed to the public under the Apache License 2.0. local DISP = require "luci.dispatcher" local SYS = require "luci.sys" local CTRL = require "luci.controller.ddns" -- this application's controller local DDNS = require "luci.tools.ddns" -- ddns multiused functions -- html constants font_red = [[<font color="red">]] font_off = [[</font>]] bold_on = [[<strong>]] bold_off = [[</strong>]] -- cbi-map definition -- ####################################################### m = Map("ddns") m.title = CTRL.app_title_back() m.description = CTRL.app_description() m.redirect = DISP.build_url("admin", "services", "ddns") -- SimpleSection definition -- ################################################# -- show Hints to optimize installation and script usage s = m:section( SimpleSection, translate("Hints"), translate("Below a list of configuration tips for your system to run Dynamic DNS updates without limitations") ) -- ddns-scripts needs to be updated for full functionality if not CTRL.service_ok() then local so = s:option(DummyValue, "_update_needed") so.titleref = DISP.build_url("admin", "system", "opkg") so.rawhtml = true so.title = font_red .. bold_on .. translate("Software update required") .. bold_off .. font_off so.value = translate("The currently installed 'ddns-scripts' package did not support all available settings.") .. "<br />" .. translate("Please update to the current version!") end -- DDNS Service disabled if not SYS.init.enabled("ddns") then local se = s:option(DummyValue, "_not_enabled") se.titleref = DISP.build_url("admin", "system", "startup") se.rawhtml = true se.title = bold_on .. translate("DDNS Autostart disabled") .. bold_off se.value = translate("Currently DDNS updates are not started at boot or on interface events." .. "<br />" .. "This is the default if you run DDNS scripts by yourself (i.e. via cron with force_interval set to '0')" ) end -- No IPv6 support if not DDNS.env_info("has_ipv6") then local v6 = s:option(DummyValue, "_no_ipv6") v6.titleref = 'http://www.openwrt.org" target="_blank' v6.rawhtml = true v6.title = bold_on .. translate("IPv6 not supported") .. bold_off v6.value = translate("IPv6 is currently not (fully) supported by this system" .. "<br />" .. "Please follow the instructions on OpenWrt's homepage to enable IPv6 support" .. "<br />" .. "or update your system to the latest OpenWrt Release") end -- No HTTPS support if not DDNS.env_info("has_ssl") then local sl = s:option(DummyValue, "_no_https") sl.titleref = DISP.build_url("admin", "system", "opkg") sl.rawhtml = true sl.title = bold_on .. translate("HTTPS not supported") .. bold_off sl.value = translate("Neither GNU Wget with SSL nor cURL installed to support secure updates via HTTPS protocol.") .. "<br />- " .. translate("You should install 'wget' or 'curl' or 'uclient-fetch' with 'libustream-*ssl' package.") .. "<br />- " .. translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.") end -- No bind_network if not DDNS.env_info("has_bindnet") then local bn = s:option(DummyValue, "_no_bind_network") bn.titleref = DISP.build_url("admin", "system", "opkg") bn.rawhtml = true bn.title = bold_on .. translate("Binding to a specific network not supported") .. bold_off bn.value = translate("Neither GNU Wget with SSL nor cURL installed to select a network to use for communication.") .. "<br />- " .. translate("You should install 'wget' or 'curl' package.") .. "<br />- " .. translate("GNU Wget will use the IP of given network, cURL will use the physical interface.") .. "<br />- " .. translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.") end -- currently only cURL possibly without proxy support if not DDNS.env_info("has_proxy") then local px = s:option(DummyValue, "_no_proxy") px.titleref = DISP.build_url("admin", "system", "opkg") px.rawhtml = true px.title = bold_on .. translate("cURL without Proxy Support") .. bold_off px.value = translate("cURL is installed, but libcurl was compiled without proxy support.") .. "<br />- " .. translate("You should install 'wget' or 'uclient-fetch' package or replace libcurl.") .. "<br />- " .. translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.") end -- "Force IP Version not supported" if not DDNS.env_info("has_forceip") then local fi = s:option(DummyValue, "_no_force_ip") fi.titleref = DISP.build_url("admin", "system", "opkg") fi.rawhtml = true fi.title = bold_on .. translate("Force IP Version not supported") .. bold_off local value = translate("BusyBox's nslookup and Wget do not support to specify " .. "the IP version to use for communication with DDNS Provider!") if not (DDNS.env_info("has_wgetssl") or DDNS.env_info("has_curl") or DDNS.env_info("has_fetch")) then value = value .. "<br />- " .. translate("You should install 'wget' or 'curl' or 'uclient-fetch' package.") end if not DDNS.env_info("has_bindhost") then value = value .. "<br />- " .. translate("You should install 'bind-host' or 'knot-host' or 'drill' package for DNS requests.") end fi.value = value end -- "DNS requests via TCP not supported" if not DDNS.env_info("has_bindhost") then local dt = s:option(DummyValue, "_no_dnstcp") dt.titleref = DISP.build_url("admin", "system", "opkg") dt.rawhtml = true dt.title = bold_on .. translate("DNS requests via TCP not supported") .. bold_off dt.value = translate("BusyBox's nslookup and hostip do not support to specify to use TCP " .. "instead of default UDP when requesting DNS server!") .. "<br />- " .. translate("You should install 'bind-host' or 'knot-host' or 'drill' package for DNS requests.") end -- nslookup compiled with musl produce problems when using if not DDNS.env_info("has_dnsserver") then local ds = s:option(DummyValue, "_no_dnsserver") ds.titleref = DISP.build_url("admin", "system", "opkg") ds.rawhtml = true ds.title = bold_on .. translate("Using specific DNS Server not supported") .. bold_off ds.value = translate("BusyBox's nslookup in the current compiled version " .. "does not handle given DNS Servers correctly!") .. "<br />- " .. translate("You should install 'bind-host' or 'knot-host' or 'drill' or 'hostip' package, " .. "if you need to specify a DNS server to detect your registered IP.") end -- certificates installed if DDNS.env_info("has_ssl") and not DDNS.env_info("has_cacerts") then local ca = s:option(DummyValue, "_no_certs") ca.titleref = DISP.build_url("admin", "system", "opkg") ca.rawhtml = true ca.title = bold_on .. translate("No certificates found") .. bold_off ca.value = translate("If using secure communication you should verify server certificates!") .. "<br />- " .. translate("Install 'ca-certificates' package or needed certificates " .. "by hand into /etc/ssl/certs default directory") end return m
luci-app-ddns: fix package installation link
luci-app-ddns: fix package installation link Signed-off-by: Florian Eckert <ee3e4af9c48a69f5a5c47153eb4a777754bfbe6f@dev.tdt.de>
Lua
apache-2.0
nmav/luci,nmav/luci,Noltari/luci,openwrt-es/openwrt-luci,hnyman/luci,openwrt-es/openwrt-luci,rogerpueyo/luci,tobiaswaldvogel/luci,artynet/luci,hnyman/luci,hnyman/luci,rogerpueyo/luci,openwrt/luci,openwrt-es/openwrt-luci,nmav/luci,nmav/luci,hnyman/luci,nmav/luci,nmav/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,nmav/luci,tobiaswaldvogel/luci,rogerpueyo/luci,Noltari/luci,rogerpueyo/luci,tobiaswaldvogel/luci,Noltari/luci,openwrt-es/openwrt-luci,artynet/luci,openwrt/luci,artynet/luci,Noltari/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,Noltari/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,openwrt/luci,hnyman/luci,hnyman/luci,openwrt/luci,artynet/luci,openwrt-es/openwrt-luci,Noltari/luci,artynet/luci,artynet/luci,hnyman/luci,Noltari/luci,tobiaswaldvogel/luci,artynet/luci,artynet/luci,rogerpueyo/luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,openwrt/luci,openwrt/luci,lbthomsen/openwrt-luci,Noltari/luci,artynet/luci,openwrt/luci,Noltari/luci,lbthomsen/openwrt-luci,openwrt-es/openwrt-luci,rogerpueyo/luci,lbthomsen/openwrt-luci,nmav/luci,rogerpueyo/luci,openwrt/luci,rogerpueyo/luci,hnyman/luci,lbthomsen/openwrt-luci,nmav/luci
e55f2e12a8b87db8e2da4819f0d828819b687914
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local is_mini = (luci.dispatcher.context.path[1] == "mini") m = Map("ddns", translate("Dynamic DNS"), translate("Dynamic DNS allows that your router can be reached with " .. "a fixed hostname while having a dynamically changing " .. "IP address.")) s = m:section(TypedSection, "service", "") s.addremove = true s.anonymous = false s:option(Flag, "enabled", translate("Enable")) svc = s:option(ListValue, "service_name", translate("Service")) svc.rmempty = true local services = { } local fd = io.open("/usr/lib/ddns/services", "r") if fd then local ln repeat ln = fd:read("*l") local s = ln and ln:match('^%s*"([^"]+)"') if s then services[#services+1] = s end until not ln fd:close() end local v for _, v in luci.util.vspairs(services) do svc:value(v) end svc:value("", "-- "..translate("custom").." --") url = s:option(Value, "update_url", translate("Custom update-URL")) url:depends("service_name", "") url.rmempty = true s:option(Value, "domain", translate("Hostname")).rmempty = true s:option(Value, "username", translate("Username")).rmempty = true pw = s:option(Value, "password", translate("Password")) pw.rmempty = true pw.password = true if is_mini then s.defaults.ip_source = "network" s.defaults.ip_network = "wan" else require("luci.tools.webadmin") src = s:option(ListValue, "ip_source", translate("Source of IP address")) src:value("network", translate("network")) src:value("interface", translate("interface")) src:value("web", translate("URL")) iface = s:option(ListValue, "ip_network", translate("Network")) iface:depends("ip_source", "network") iface.rmempty = true luci.tools.webadmin.cbi_add_networks(iface) iface = s:option(ListValue, "ip_interface", translate("Interface")) iface:depends("ip_source", "interface") iface.rmempty = true for k, v in pairs(luci.sys.net.devices()) do iface:value(v) end web = s:option(Value, "ip_url", translate("URL")) web:depends("ip_source", "web") web.rmempty = true end s:option(Value, "check_interval", translate("Check for changed IP every")).default = 10 unit = s:option(ListValue, "check_unit", translate("Check-time unit")) unit.default = "minutes" unit:value("minutes", translate("min")) unit:value("hours", translate("h")) s:option(Value, "force_interval", translate("Force update every")).default = 72 unit = s:option(ListValue, "force_unit", translate("Force-time unit")) unit.default = "hours" unit:value("minutes", translate("min")) unit:value("hours", translate("h")) return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local is_mini = (luci.dispatcher.context.path[1] == "mini") m = Map("ddns", translate("Dynamic DNS"), translate("Dynamic DNS allows that your router can be reached with " .. "a fixed hostname while having a dynamically changing " .. "IP address.")) s = m:section(TypedSection, "service", "") s.addremove = true s.anonymous = false s:option(Flag, "enabled", translate("Enable")) svc = s:option(ListValue, "service_name", translate("Service")) svc.rmempty = false local services = { } local fd = io.open("/usr/lib/ddns/services", "r") if fd then local ln repeat ln = fd:read("*l") local s = ln and ln:match('^%s*"([^"]+)"') if s then services[#services+1] = s end until not ln fd:close() end local v for _, v in luci.util.vspairs(services) do svc:value(v) end function svc.cfgvalue(...) local v = Value.cfgvalue(...) if not v or #v == 0 then return "-" else return v end end function svc.write(self, section, value) if value == "-" then m.uci:delete("ddns", section, self.option) else Value.write(self, section, value) end end svc:value("-", "-- "..translate("custom").." --") url = s:option(Value, "update_url", translate("Custom update-URL")) url:depends("service_name", "-") url.rmempty = true s:option(Value, "domain", translate("Hostname")).rmempty = true s:option(Value, "username", translate("Username")).rmempty = true pw = s:option(Value, "password", translate("Password")) pw.rmempty = true pw.password = true if is_mini then s.defaults.ip_source = "network" s.defaults.ip_network = "wan" else require("luci.tools.webadmin") src = s:option(ListValue, "ip_source", translate("Source of IP address")) src:value("network", translate("network")) src:value("interface", translate("interface")) src:value("web", translate("URL")) iface = s:option(ListValue, "ip_network", translate("Network")) iface:depends("ip_source", "network") iface.rmempty = true luci.tools.webadmin.cbi_add_networks(iface) iface = s:option(ListValue, "ip_interface", translate("Interface")) iface:depends("ip_source", "interface") iface.rmempty = true for k, v in pairs(luci.sys.net.devices()) do iface:value(v) end web = s:option(Value, "ip_url", translate("URL")) web:depends("ip_source", "web") web.rmempty = true end s:option(Value, "check_interval", translate("Check for changed IP every")).default = 10 unit = s:option(ListValue, "check_unit", translate("Check-time unit")) unit.default = "minutes" unit:value("minutes", translate("min")) unit:value("hours", translate("h")) s:option(Value, "force_interval", translate("Force update every")).default = 72 unit = s:option(ListValue, "force_unit", translate("Force-time unit")) unit.default = "hours" unit:value("minutes", translate("min")) unit:value("hours", translate("h")) return m
applications/luci-ddns: fix selection of custom update_url
applications/luci-ddns: fix selection of custom update_url
Lua
apache-2.0
MinFu/luci,bright-things/ionic-luci,kuoruan/luci,schidler/ionic-luci,mumuqz/luci,david-xiao/luci,cshore-firmware/openwrt-luci,remakeelectric/luci,thess/OpenWrt-luci,rogerpueyo/luci,jchuang1977/luci-1,NeoRaider/luci,oyido/luci,LuttyYang/luci,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,florian-shellfire/luci,artynet/luci,thesabbir/luci,taiha/luci,ff94315/luci-1,oyido/luci,lbthomsen/openwrt-luci,teslamint/luci,db260179/openwrt-bpi-r1-luci,jlopenwrtluci/luci,ollie27/openwrt_luci,Sakura-Winkey/LuCI,deepak78/new-luci,tobiaswaldvogel/luci,Kyklas/luci-proto-hso,lbthomsen/openwrt-luci,jorgifumi/luci,male-puppies/luci,chris5560/openwrt-luci,981213/luci-1,tcatm/luci,harveyhu2012/luci,slayerrensky/luci,daofeng2015/luci,shangjiyu/luci-with-extra,nwf/openwrt-luci,lbthomsen/openwrt-luci,Kyklas/luci-proto-hso,nwf/openwrt-luci,maxrio/luci981213,keyidadi/luci,schidler/ionic-luci,jchuang1977/luci-1,keyidadi/luci,maxrio/luci981213,zhaoxx063/luci,taiha/luci,thesabbir/luci,palmettos/cnLuCI,palmettos/cnLuCI,NeoRaider/luci,harveyhu2012/luci,Noltari/luci,jorgifumi/luci,male-puppies/luci,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,joaofvieira/luci,artynet/luci,cshore/luci,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,oneru/luci,kuoruan/luci,deepak78/new-luci,forward619/luci,kuoruan/luci,jchuang1977/luci-1,tcatm/luci,thess/OpenWrt-luci,Noltari/luci,tobiaswaldvogel/luci,Hostle/luci,tobiaswaldvogel/luci,LuttyYang/luci,teslamint/luci,dwmw2/luci,ff94315/luci-1,maxrio/luci981213,RedSnake64/openwrt-luci-packages,obsy/luci,tcatm/luci,schidler/ionic-luci,slayerrensky/luci,cshore-firmware/openwrt-luci,keyidadi/luci,dwmw2/luci,cappiewu/luci,shangjiyu/luci-with-extra,cappiewu/luci,bright-things/ionic-luci,oyido/luci,RedSnake64/openwrt-luci-packages,openwrt/luci,Kyklas/luci-proto-hso,Wedmer/luci,ff94315/luci-1,MinFu/luci,urueedi/luci,lcf258/openwrtcn,urueedi/luci,jchuang1977/luci-1,aircross/OpenWrt-Firefly-LuCI,david-xiao/luci,joaofvieira/luci,artynet/luci,openwrt/luci,chris5560/openwrt-luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,hnyman/luci,chris5560/openwrt-luci,chris5560/openwrt-luci,obsy/luci,Noltari/luci,joaofvieira/luci,remakeelectric/luci,kuoruan/lede-luci,981213/luci-1,zhaoxx063/luci,deepak78/new-luci,chris5560/openwrt-luci,Hostle/luci,openwrt-es/openwrt-luci,db260179/openwrt-bpi-r1-luci,david-xiao/luci,cappiewu/luci,marcel-sch/luci,openwrt-es/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,jlopenwrtluci/luci,dwmw2/luci,kuoruan/lede-luci,slayerrensky/luci,rogerpueyo/luci,sujeet14108/luci,forward619/luci,cappiewu/luci,florian-shellfire/luci,981213/luci-1,schidler/ionic-luci,opentechinstitute/luci,981213/luci-1,wongsyrone/luci-1,teslamint/luci,keyidadi/luci,fkooman/luci,lcf258/openwrtcn,palmettos/cnLuCI,marcel-sch/luci,jchuang1977/luci-1,zhaoxx063/luci,aircross/OpenWrt-Firefly-LuCI,fkooman/luci,openwrt-es/openwrt-luci,NeoRaider/luci,palmettos/cnLuCI,NeoRaider/luci,sujeet14108/luci,ollie27/openwrt_luci,MinFu/luci,dwmw2/luci,Wedmer/luci,Hostle/openwrt-luci-multi-user,LuttyYang/luci,wongsyrone/luci-1,wongsyrone/luci-1,tcatm/luci,thess/OpenWrt-luci,kuoruan/luci,urueedi/luci,palmettos/test,thesabbir/luci,nwf/openwrt-luci,artynet/luci,remakeelectric/luci,joaofvieira/luci,Sakura-Winkey/LuCI,Kyklas/luci-proto-hso,nwf/openwrt-luci,harveyhu2012/luci,ollie27/openwrt_luci,hnyman/luci,opentechinstitute/luci,RuiChen1113/luci,ff94315/luci-1,kuoruan/luci,RuiChen1113/luci,aa65535/luci,thess/OpenWrt-luci,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,bittorf/luci,bright-things/ionic-luci,RuiChen1113/luci,Hostle/luci,ff94315/luci-1,taiha/luci,daofeng2015/luci,oneru/luci,zhaoxx063/luci,LuttyYang/luci,LazyZhu/openwrt-luci-trunk-mod,male-puppies/luci,LazyZhu/openwrt-luci-trunk-mod,Kyklas/luci-proto-hso,dismantl/luci-0.12,harveyhu2012/luci,aircross/OpenWrt-Firefly-LuCI,Noltari/luci,Wedmer/luci,taiha/luci,palmettos/test,thesabbir/luci,slayerrensky/luci,cshore/luci,urueedi/luci,bright-things/ionic-luci,RuiChen1113/luci,florian-shellfire/luci,chris5560/openwrt-luci,artynet/luci,Hostle/luci,hnyman/luci,ff94315/luci-1,Hostle/luci,openwrt/luci,981213/luci-1,MinFu/luci,mumuqz/luci,dwmw2/luci,maxrio/luci981213,wongsyrone/luci-1,bittorf/luci,marcel-sch/luci,palmettos/test,cappiewu/luci,oneru/luci,obsy/luci,db260179/openwrt-bpi-r1-luci,jchuang1977/luci-1,dismantl/luci-0.12,thesabbir/luci,zhaoxx063/luci,Hostle/openwrt-luci-multi-user,lcf258/openwrtcn,slayerrensky/luci,oyido/luci,mumuqz/luci,maxrio/luci981213,artynet/luci,jlopenwrtluci/luci,lcf258/openwrtcn,openwrt-es/openwrt-luci,urueedi/luci,oyido/luci,Hostle/openwrt-luci-multi-user,schidler/ionic-luci,harveyhu2012/luci,LazyZhu/openwrt-luci-trunk-mod,nwf/openwrt-luci,oneru/luci,zhaoxx063/luci,daofeng2015/luci,LazyZhu/openwrt-luci-trunk-mod,NeoRaider/luci,Wedmer/luci,openwrt/luci,kuoruan/lede-luci,aircross/OpenWrt-Firefly-LuCI,ReclaimYourPrivacy/cloak-luci,deepak78/new-luci,Hostle/luci,lbthomsen/openwrt-luci,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,shangjiyu/luci-with-extra,openwrt/luci,joaofvieira/luci,RuiChen1113/luci,LazyZhu/openwrt-luci-trunk-mod,NeoRaider/luci,opentechinstitute/luci,forward619/luci,kuoruan/luci,RuiChen1113/luci,kuoruan/lede-luci,slayerrensky/luci,tobiaswaldvogel/luci,shangjiyu/luci-with-extra,jlopenwrtluci/luci,florian-shellfire/luci,kuoruan/lede-luci,nmav/luci,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,nmav/luci,ff94315/luci-1,cshore/luci,openwrt/luci,mumuqz/luci,hnyman/luci,Noltari/luci,openwrt-es/openwrt-luci,florian-shellfire/luci,Noltari/luci,hnyman/luci,oneru/luci,shangjiyu/luci-with-extra,MinFu/luci,jorgifumi/luci,wongsyrone/luci-1,keyidadi/luci,lbthomsen/openwrt-luci,deepak78/new-luci,LuttyYang/luci,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,db260179/openwrt-bpi-r1-luci,keyidadi/luci,jchuang1977/luci-1,aa65535/luci,david-xiao/luci,rogerpueyo/luci,NeoRaider/luci,mumuqz/luci,forward619/luci,slayerrensky/luci,marcel-sch/luci,david-xiao/luci,schidler/ionic-luci,RedSnake64/openwrt-luci-packages,ollie27/openwrt_luci,tcatm/luci,jlopenwrtluci/luci,sujeet14108/luci,teslamint/luci,bittorf/luci,fkooman/luci,cshore/luci,oneru/luci,fkooman/luci,joaofvieira/luci,fkooman/luci,Sakura-Winkey/LuCI,oyido/luci,opentechinstitute/luci,rogerpueyo/luci,openwrt-es/openwrt-luci,male-puppies/luci,fkooman/luci,artynet/luci,cshore/luci,aircross/OpenWrt-Firefly-LuCI,ReclaimYourPrivacy/cloak-luci,palmettos/test,bright-things/ionic-luci,kuoruan/lede-luci,maxrio/luci981213,nmav/luci,lcf258/openwrtcn,aa65535/luci,remakeelectric/luci,harveyhu2012/luci,marcel-sch/luci,maxrio/luci981213,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,marcel-sch/luci,david-xiao/luci,oneru/luci,artynet/luci,forward619/luci,cshore-firmware/openwrt-luci,oyido/luci,zhaoxx063/luci,LuttyYang/luci,cshore/luci,jorgifumi/luci,obsy/luci,wongsyrone/luci-1,palmettos/cnLuCI,hnyman/luci,dwmw2/luci,cappiewu/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,artynet/luci,LuttyYang/luci,NeoRaider/luci,ReclaimYourPrivacy/cloak-luci,joaofvieira/luci,tcatm/luci,db260179/openwrt-bpi-r1-luci,mumuqz/luci,Noltari/luci,male-puppies/luci,male-puppies/luci,ReclaimYourPrivacy/cloak-luci,obsy/luci,ReclaimYourPrivacy/cloak-luci,daofeng2015/luci,forward619/luci,nwf/openwrt-luci,bittorf/luci,jlopenwrtluci/luci,aircross/OpenWrt-Firefly-LuCI,dismantl/luci-0.12,nmav/luci,oyido/luci,mumuqz/luci,taiha/luci,kuoruan/luci,remakeelectric/luci,mumuqz/luci,ff94315/luci-1,daofeng2015/luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,lcf258/openwrtcn,cshore/luci,shangjiyu/luci-with-extra,bright-things/ionic-luci,981213/luci-1,dwmw2/luci,lcf258/openwrtcn,nmav/luci,sujeet14108/luci,ReclaimYourPrivacy/cloak-luci,dismantl/luci-0.12,Wedmer/luci,urueedi/luci,thess/OpenWrt-luci,aa65535/luci,florian-shellfire/luci,male-puppies/luci,nmav/luci,lbthomsen/openwrt-luci,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,ReclaimYourPrivacy/cloak-luci,deepak78/new-luci,slayerrensky/luci,hnyman/luci,cappiewu/luci,sujeet14108/luci,rogerpueyo/luci,cshore-firmware/openwrt-luci,maxrio/luci981213,aa65535/luci,Hostle/openwrt-luci-multi-user,bittorf/luci,981213/luci-1,RuiChen1113/luci,teslamint/luci,remakeelectric/luci,Hostle/openwrt-luci-multi-user,palmettos/test,lcf258/openwrtcn,jlopenwrtluci/luci,palmettos/test,palmettos/cnLuCI,dismantl/luci-0.12,obsy/luci,bright-things/ionic-luci,jchuang1977/luci-1,fkooman/luci,RedSnake64/openwrt-luci-packages,lbthomsen/openwrt-luci,db260179/openwrt-bpi-r1-luci,rogerpueyo/luci,aa65535/luci,jorgifumi/luci,zhaoxx063/luci,marcel-sch/luci,tcatm/luci,bittorf/luci,dismantl/luci-0.12,forward619/luci,sujeet14108/luci,ollie27/openwrt_luci,urueedi/luci,jorgifumi/luci,deepak78/new-luci,lcf258/openwrtcn,obsy/luci,florian-shellfire/luci,daofeng2015/luci,teslamint/luci,RedSnake64/openwrt-luci-packages,urueedi/luci,Kyklas/luci-proto-hso,thess/OpenWrt-luci,LuttyYang/luci,openwrt/luci,Wedmer/luci,david-xiao/luci,MinFu/luci,Sakura-Winkey/LuCI,cshore-firmware/openwrt-luci,sujeet14108/luci,Sakura-Winkey/LuCI,keyidadi/luci,remakeelectric/luci,ollie27/openwrt_luci,taiha/luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,joaofvieira/luci,taiha/luci,forward619/luci,chris5560/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,Sakura-Winkey/LuCI,Hostle/luci,opentechinstitute/luci,nmav/luci,david-xiao/luci,deepak78/new-luci,thess/OpenWrt-luci,rogerpueyo/luci,Sakura-Winkey/LuCI,Hostle/luci,remakeelectric/luci,palmettos/test,Noltari/luci,marcel-sch/luci,obsy/luci,harveyhu2012/luci,Noltari/luci,MinFu/luci,Kyklas/luci-proto-hso,palmettos/cnLuCI,opentechinstitute/luci,teslamint/luci,RedSnake64/openwrt-luci-packages,bittorf/luci,Wedmer/luci,bright-things/ionic-luci,aa65535/luci,taiha/luci,schidler/ionic-luci,fkooman/luci,ollie27/openwrt_luci,chris5560/openwrt-luci,nmav/luci,RuiChen1113/luci,teslamint/luci,cshore/luci,tobiaswaldvogel/luci,bittorf/luci,cappiewu/luci,thess/OpenWrt-luci,palmettos/test,jorgifumi/luci,kuoruan/luci,hnyman/luci,MinFu/luci,nmav/luci,dwmw2/luci,dismantl/luci-0.12,ReclaimYourPrivacy/cloak-luci,aa65535/luci,wongsyrone/luci-1,florian-shellfire/luci,wongsyrone/luci-1,rogerpueyo/luci,daofeng2015/luci,oneru/luci,nwf/openwrt-luci,opentechinstitute/luci,jorgifumi/luci,palmettos/cnLuCI,male-puppies/luci,openwrt/luci,Wedmer/luci,keyidadi/luci,Hostle/openwrt-luci-multi-user,daofeng2015/luci,thesabbir/luci,cshore-firmware/openwrt-luci,thesabbir/luci,tobiaswaldvogel/luci,thesabbir/luci
6ca3a55505272869d2fac0fc0ca1ee2bdbb69c82
oracle/xplan.lua
oracle/xplan.lua
local db,cfg=env.getdb(),env.set local xplan={} local default_fmt,e10053,prof="ALLSTATS ALL -PROJECTION OUTLINE REMOTE" function xplan.explain(fmt,sql) local ora,sqltext=db.C.ora env.checkhelp(fmt) if fmt:sub(1,1)=='-' then if not sql then return end fmt=fmt:sub(2) if fmt=='10053' then e10053,fmt=true,default_fmt fmt=default_fmt elseif fmt:lower()=="prof" then prof,fmt=true,default_fmt end else sql=fmt..(not sql and "" or " "..sql) fmt=default_fmt end sql=env.END_MARKS.match(sql) if not sql:gsub("[\n\r]",""):match('(%s)') then sql=sql:gsub("[\n\r]","") sqltext=db:get_value([[SELECT * FROM(SELECT sql_text from dba_hist_sqltext WHERE sql_id=:1 AND ROWNUM<2 UNION ALL SELECT sql_fulltext from gv$sqlarea WHERE sql_id=:1 AND ROWNUM<2) WHERE ROWNUM<2]],{sql}) env.checkerr(sqltext,"Cannot find target SQL ID %s",sql) sql=sqltext else sqltext=sql end local args={} sql=sql:gsub("(:[%w_$]+)",function(s) args[s:sub(2)]=""; return s end) local feed=cfg.get("feed") cfg.set("feed","off",true) cfg.set("printsize",9999,true) --db:internal_call("alter session set statistics_level=all") db:rollback() if e10053 then db:internal_call("ALTER SESSION SET EVENTS='10053 trace name context forever, level 1'") end db:internal_call("delete plan_table"); db:internal_call("Explain PLAN /*INTERNAL_DBCLI_CMD*/ FOR "..sql,args) sql=[[ WITH /*INTERNAL_DBCLI_CMD*/ sql_plan_data AS (SELECT * FROM (SELECT id, parent_id, plan_id, dense_rank() OVER(ORDER BY plan_id DESC) seq FROM plan_table) WHERE seq = 1 ORDER BY id), qry AS (SELECT DISTINCT PLAN_id FROM sql_plan_data), hierarchy_data AS (SELECT id, parent_id FROM sql_plan_data START WITH id = 0 CONNECT BY PRIOR id = parent_id ORDER SIBLINGS BY id DESC), ordered_hierarchy_data AS (SELECT id, parent_id AS pid, row_number() over(ORDER BY rownum DESC) AS OID, MAX(id) over() AS maxid FROM hierarchy_data), xplan_data AS (SELECT /*+ ordered use_nl(o) */ rownum AS r, x.plan_table_output AS plan_table_output, o.id, o.pid, o.oid, o.maxid, COUNT(*) over() AS rc FROM (SELECT * FROM qry, TABLE(dbms_xplan.display('PLAN_TABLE', NULL, '@fmt@', 'plan_id=' || qry.plan_id))) x LEFT OUTER JOIN ordered_hierarchy_data o ON (o.id = CASE WHEN regexp_like(x.plan_table_output, '^\|[\* 0-9]+\|') THEN to_number(regexp_substr(x.plan_table_output, '[0-9]+')) END)) select plan_table_output from xplan_data model dimension by (rownum as r) measures (plan_table_output, id, maxid, pid, oid, rc, greatest(max(length(maxid)) over () + 3, 6) as csize, cast(null as varchar2(128)) as inject) rules sequential order ( inject[r] = case when id[cv()+1] = 0 or id[cv()+3] = 0 or id[cv()-1] = maxid[cv()-1] then rpad('-', csize[cv()]*2, '-') when id[cv()+2] = 0 then '|' || lpad('Pid |', csize[cv()]) || lpad('Ord |', csize[cv()]) when id[cv()] is not null then '|' || lpad(pid[cv()] || ' |', csize[cv()]) || lpad(oid[cv()] || ' |', csize[cv()]) end, plan_table_output[r] = case when inject[cv()] like '---%' then inject[cv()] || plan_table_output[cv()] when inject[cv()] is not null then regexp_replace(plan_table_output[cv()], '\|', inject[cv()], 1, 2) else plan_table_output[cv()] END ) order by r]] sql=sql:gsub('@fmt@',fmt) db:query(sql) --db:rollback() if e10053==true then db:internal_call("ALTER SESSION SET EVENTS '10053 trace name context off'") oracle.C.tracefile.get_trace('default') elseif prof==true then oracle.C.sqlprof.extract_profile(nil,'plan',sqltext) end cfg.set("feed",feed,true) end function xplan.onload() local help=[[ Explain SQL execution plan. Usage: @@NAME {[-<format>|-10053|-prof] <SQL statement|SQL ID>} Options: -<format>: Refer to the 'format' field in the document of 'dbms_xplan'. Default is ']]..default_fmt..[[' -10053 : Generate the 10053 trace file after displaying the execution plan -prof : Generate the SQL profile script after displaying the execution plan Parameters: <SQL Statement>: SELECT/DELETE/UPDATE/MERGE/etc that can produce the execution plan <SQL ID> : The SQL ID that can be found in SQL area or AWR history ]] env.set_command(nil,{"XPLAIN","XPLAN"},help,xplan.explain,'__SMART_PARSE__',3,true) end return xplan
local db,cfg=env.getdb(),env.set local xplan={} local default_fmt,e10053,prof="ALLSTATS ALL -PROJECTION OUTLINE REMOTE" function xplan.explain(fmt,sql) local ora,sqltext=db.C.ora env.checkhelp(fmt) if fmt:sub(1,1)=='-' then if not sql then return end fmt=fmt:sub(2) if fmt=='10053' then e10053,fmt=true,default_fmt fmt=default_fmt elseif fmt:lower()=="prof" then prof,fmt=true,default_fmt end else sql=fmt..(not sql and "" or " "..sql) fmt=default_fmt end sql=env.END_MARKS.match(sql) if not sql:gsub("[\n\r]",""):match('(%s)') then sql=sql:gsub("[\n\r]","") sqltext=db:get_value([[SELECT * FROM(SELECT sql_text from dba_hist_sqltext WHERE sql_id=:1 AND ROWNUM<2 UNION ALL SELECT sql_fulltext from gv$sqlarea WHERE sql_id=:1 AND ROWNUM<2) WHERE ROWNUM<2]],{sql}) env.checkerr(sqltext,"Cannot find target SQL ID %s",sql) sql=sqltext else sqltext=sql end local args={} sql=sql:gsub("(:[%w_$]+)",function(s) args[s:sub(2)]=""; return s end) local feed=cfg.get("feed") cfg.set("feed","off",true) cfg.set("printsize",9999,true) --db:internal_call("alter session set statistics_level=all") db:rollback() if e10053 then db:internal_call("ALTER SESSION SET EVENTS='10053 trace name context forever, level 1'") end db:internal_call("Explain PLAN SET STATEMENT_ID='INTERNAL_DBCLI_CMD' FOR "..sql,args) sql=[[ WITH /*INTERNAL_DBCLI_CMD*/ sql_plan_data AS (SELECT * FROM (SELECT id, parent_id, plan_id, dense_rank() OVER(ORDER BY plan_id DESC) seq FROM plan_table WHERE STATEMENT_ID='INTERNAL_DBCLI_CMD') WHERE seq = 1 ORDER BY id), qry AS (SELECT DISTINCT PLAN_id FROM sql_plan_data), hierarchy_data AS (SELECT id, parent_id FROM sql_plan_data START WITH id = 0 CONNECT BY PRIOR id = parent_id ORDER SIBLINGS BY id DESC), ordered_hierarchy_data AS (SELECT id, parent_id AS pid, row_number() over(ORDER BY rownum DESC) AS OID, MAX(id) over() AS maxid FROM hierarchy_data), xplan_data AS (SELECT /*+ ordered use_nl(o) */ rownum AS r, x.plan_table_output AS plan_table_output, o.id, o.pid, o.oid, o.maxid, COUNT(*) over() AS rc FROM (SELECT * FROM qry, TABLE(dbms_xplan.display('PLAN_TABLE', NULL, '@fmt@', 'plan_id=' || qry.plan_id))) x LEFT OUTER JOIN ordered_hierarchy_data o ON (o.id = CASE WHEN regexp_like(x.plan_table_output, '^\|[\* 0-9]+\|') THEN to_number(regexp_substr(x.plan_table_output, '[0-9]+')) END)) select plan_table_output from xplan_data model dimension by (rownum as r) measures (plan_table_output, id, maxid, pid, oid, rc, greatest(max(length(maxid)) over () + 3, 6) as csize, cast(null as varchar2(128)) as inject) rules sequential order ( inject[r] = case when id[cv()+1] = 0 or id[cv()+3] = 0 or id[cv()-1] = maxid[cv()-1] then rpad('-', csize[cv()]*2, '-') when id[cv()+2] = 0 then '|' || lpad('Pid |', csize[cv()]) || lpad('Ord |', csize[cv()]) when id[cv()] is not null then '|' || lpad(pid[cv()] || ' |', csize[cv()]) || lpad(oid[cv()] || ' |', csize[cv()]) end, plan_table_output[r] = case when inject[cv()] like '---%' then inject[cv()] || plan_table_output[cv()] when inject[cv()] is not null then regexp_replace(plan_table_output[cv()], '\|', inject[cv()], 1, 2) else plan_table_output[cv()] END ) order by r]] sql=sql:gsub('@fmt@',fmt) db:query(sql) --db:rollback() if e10053==true then db:internal_call("ALTER SESSION SET EVENTS '10053 trace name context off'") oracle.C.tracefile.get_trace('default') elseif prof==true then oracle.C.sqlprof.extract_profile(nil,'plan',sqltext) end cfg.set("feed",feed,true) end function xplan.onload() local help=[[ Explain SQL execution plan. Usage: @@NAME {[-<format>|-10053|-prof] <SQL statement|SQL ID>} Options: -<format>: Refer to the 'format' field in the document of 'dbms_xplan'. Default is ']]..default_fmt..[[' -10053 : Generate the 10053 trace file after displaying the execution plan -prof : Generate the SQL profile script after displaying the execution plan Parameters: <SQL Statement>: SELECT/DELETE/UPDATE/MERGE/etc that can produce the execution plan <SQL ID> : The SQL ID that can be found in SQL area or AWR history ]] env.set_command(nil,{"XPLAIN","XPLAN"},help,xplan.explain,'__SMART_PARSE__',3,true) end return xplan
fix incorrect xplan result;
fix incorrect xplan result;
Lua
mit
hyee/dbcli,hyee/dbcli,hyee/dbcli,hyee/dbcli
b710e9f8a58ef212d12ed14b4dc0e3bb8896efce
nvim/lua/config/lspconfig.lua
nvim/lua/config/lspconfig.lua
-- NOTE: see https://github.com/neovim/nvim-lspconfig/blob/master/CONFIG.md -- see also https://github.com/williamboman/nvim-lsp-installer -- keymaps local on_attach = function(client, bufnr) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end require('lsp_signature').on_attach() buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') -- Mappings. local opts = { noremap = true, silent = true } buf_set_keymap('n', 'gD', '<Cmd>lua vim.lsp.buf.declaration()<CR>', opts) buf_set_keymap('n', 'gd', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts) buf_set_keymap('n', 'gk', '<Cmd>lua vim.lsp.buf.hover()<CR>', opts) buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts) buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts) buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts) buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts) buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts) buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts) buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts) buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts) buf_set_keymap('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts) buf_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts) buf_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts) buf_set_keymap('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts) -- Set some keybinds conditional on server capabilities if client.resolved_capabilities.document_formatting then buf_set_keymap('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts) elseif client.resolved_capabilities.document_range_formatting then buf_set_keymap('n', '<space>f', '<cmd>lua vim.lsp.buf.range_formatting()<CR>', opts) end -- Set autocommands conditional on server_capabilities if client.resolved_capabilities.document_highlight then vim.api.nvim_exec( [[ augroup lsp_document_highlight autocmd! * <buffer> autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() augroup END ]], false ) end end -- config that activates keymaps and enables snippet support local function make_config() local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true return { -- enable snippet support capabilities = capabilities, -- map buffer local keybindings when the language server attaches on_attach = on_attach, } end local lsp_installer = require('nvim-lsp-installer') lsp_installer.on_server_ready(function(server) local opts = make_config() -- (optional) Customize the options passed to the server if server.name == 'eslint' then opts.on_attach = function(client, bufnr) -- neovim's LSP client does not currently support dynamic capabilities registration, so we need to set -- the resolved capabilities of the eslint server ourselves! client.resolved_capabilities.document_formatting = true on_attach(client, bufnr) end opts.settings = { format = { enable = true }, -- this will enable formatting } end -- This setup() function is exactly the same as lspconfig's setup function (:help lspconfig-quickstart) server:setup(opts) vim.cmd([[ do User LspAttachBuffers ]]) end)
-- NOTE: see https://github.com/neovim/nvim-lspconfig/blob/master/CONFIG.md -- see also https://github.com/williamboman/nvim-lsp-installer -- keymaps local on_attach = function(client, bufnr) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end require('lsp_signature').on_attach() buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') -- Mappings. local opts = { noremap = true, silent = true } buf_set_keymap('n', 'gD', '<Cmd>lua vim.lsp.buf.declaration()<CR>', opts) buf_set_keymap('n', 'gd', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts) buf_set_keymap('n', 'gk', '<Cmd>lua vim.lsp.buf.hover()<CR>', opts) buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts) buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts) buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts) buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts) buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts) buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts) buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts) buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts) buf_set_keymap('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts) buf_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts) buf_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts) buf_set_keymap('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts) -- Set some keybinds conditional on server capabilities if client.resolved_capabilities.document_formatting then buf_set_keymap('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts) elseif client.resolved_capabilities.document_range_formatting then buf_set_keymap('n', '<space>f', '<cmd>lua vim.lsp.buf.range_formatting()<CR>', opts) end -- Set autocommands conditional on server_capabilities if client.resolved_capabilities.document_highlight then vim.api.nvim_exec( [[ augroup lsp_document_highlight autocmd! * <buffer> autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() augroup END ]], false ) end end -- config that activates keymaps and enables snippet support local function make_config() local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true return { -- enable snippet support capabilities = capabilities, -- map buffer local keybindings when the language server attaches on_attach = on_attach, } end local lsp_installer = require('nvim-lsp-installer') lsp_installer.on_server_ready(function(server) local opts = make_config() -- (optional) Customize the options passed to the server if server.name == 'eslint' or server.name == 'tsserver' or server.name == 'stylelint_lsp' then -- this is to avoid LSP formatting conflicts with null-ls... see https://github.com/jose-elias-alvarez/null-ls.nvim/wiki/Avoiding-LSP-formatting-conflicts opts.on_attach = function(client) client.resolved_capabilities.document_formatting = false client.resolved_capabilities.document_range_formatting = false end end -- This setup() function is exactly the same as lspconfig's setup function (:help lspconfig-quickstart) server:setup(opts) vim.cmd([[ do User LspAttachBuffers ]]) end)
fix: avoid LSP formatting conflicts
fix: avoid LSP formatting conflicts See https://github.com/jose-elias-alvarez/null-ls.nvim/wiki/Avoiding-LSP-formatting-conflicts I had tsserver, eslint and stylelint_lsp set up... so... lots of options.
Lua
mit
drmohundro/dotfiles
d5375b5e4a24ac66c9321f7f23fe8b72c535b304
src/logfactory/LogCreator.lua
src/logfactory/LogCreator.lua
local LogCreator = {}; -- ------------------------------------------------ -- Constants -- ------------------------------------------------ local GIT_COMMAND = 'git -C "' local LOG_COMMAND = '" log --reverse --numstat --pretty=format:"info: %an|%ae|%ct" --name-status --no-merges'; local FIRST_COMMIT_COMMAND = '" log --pretty=format:%ct|tail -1'; local LATEST_COMMIT_COMMAND = '" log --pretty=format:%ct|head -1'; local TOTAL_COMMITS_COMMAND = '" rev-list HEAD --count'; local LOG_FOLDER = 'logs/'; local LOG_FILE = '/log.txt'; local INFO_FILE = '/info.lua'; -- ------------------------------------------------ -- Public Functions -- ------------------------------------------------ --- -- Creates a git log if git is available and no log has been -- created in the target folder yet. -- @param projectname -- @param path -- function LogCreator.createGitLog(projectname, path, force) if not force and love.filesystem.isFile(LOG_FOLDER .. projectname .. LOG_FILE) then io.write('Git log for ' .. projectname .. ' already exists!\r\n'); else io.write('Writing log for ' .. projectname .. '.\r\n'); love.filesystem.createDirectory(LOG_FOLDER .. projectname); local cmd = GIT_COMMAND .. path .. LOG_COMMAND; local handle = io.popen(cmd); love.filesystem.write(LOG_FOLDER .. projectname .. LOG_FILE, handle:read('*all')); handle:close(); io.write('Done!\r\n'); end end function LogCreator.createInfoFile(projectname, path, force) if not force and love.filesystem.isFile(LOG_FOLDER .. projectname .. INFO_FILE) then io.write('Info file for ' .. projectname .. ' already exists!\r\n'); elseif love.system.getOS() ~= 'Windows' then local fileContent = ''; fileContent = fileContent .. 'return {\r\n'; -- Project name. fileContent = fileContent .. ' name = "' .. projectname .. '",\r\n'; -- First commit. local handle = io.popen(GIT_COMMAND .. path .. FIRST_COMMIT_COMMAND); fileContent = fileContent .. ' firstCommit = ' .. handle:read('*a'):gsub('[%s]+', '') .. ',\r\n'; handle:close(); -- Latest commit. local handle = io.popen(GIT_COMMAND .. path .. LATEST_COMMIT_COMMAND); fileContent = fileContent .. ' latestCommit = ' .. handle:read('*a'):gsub('[%s]+', '') .. ',\r\n'; handle:close(); -- Number of commits. local handle = io.popen(GIT_COMMAND .. path .. TOTAL_COMMITS_COMMAND); fileContent = fileContent .. ' totalCommits = ' .. handle:read('*a'):gsub('[%s]+', '') .. '\r\n'; handle:close(); fileContent = fileContent .. '};\r\n'; love.filesystem.write(LOG_FOLDER .. projectname .. INFO_FILE, fileContent); end end -- ------------------------------------------------ -- Getters -- ------------------------------------------------ --- -- Checks if git is available on the system. -- function LogCreator.isGitAvailable() return os.execute('git version') == 0; end return LogCreator;
local LogCreator = {}; -- ------------------------------------------------ -- Constants -- ------------------------------------------------ local GIT_COMMAND = 'git -C "' local LOG_COMMAND = '" log --reverse --numstat --pretty=format:"info: %an|%ae|%ct" --name-status --no-merges'; local FIRST_COMMIT_COMMAND = '" log --pretty=format:%ct|tail -1'; local LATEST_COMMIT_COMMAND = '" log --pretty=format:%ct|head -1'; local TOTAL_COMMITS_COMMAND = '" rev-list HEAD --count'; local LOG_FOLDER = 'logs/'; local LOG_FILE = '/log.txt'; local INFO_FILE = '/info.lua'; -- ------------------------------------------------ -- Public Functions -- ------------------------------------------------ --- -- Creates a git log if git is available and no log has been -- created in the target folder yet. -- @param projectname -- @param path -- function LogCreator.createGitLog(projectname, path, force) if not force and love.filesystem.isFile(LOG_FOLDER .. projectname .. LOG_FILE) then io.write('Git log for ' .. projectname .. ' already exists!\r\n'); else io.write('Writing log for ' .. projectname .. '.\r\n'); love.filesystem.createDirectory(LOG_FOLDER .. projectname); local cmd = GIT_COMMAND .. path .. LOG_COMMAND; local handle = io.popen(cmd); love.filesystem.write(LOG_FOLDER .. projectname .. LOG_FILE, handle:read('*all')); handle:close(); io.write('Done!\r\n'); end end function LogCreator.createInfoFile(projectname, path, force) if not force and love.filesystem.isFile(LOG_FOLDER .. projectname .. INFO_FILE) then io.write('Info file for ' .. projectname .. ' already exists!\r\n'); elseif love.system.getOS() ~= 'Windows' then local fileContent = ''; fileContent = fileContent .. 'return {\r\n'; -- Project name. fileContent = fileContent .. ' name = "' .. projectname .. '",\r\n'; -- First commit. local handle = io.popen(GIT_COMMAND .. path .. FIRST_COMMIT_COMMAND); fileContent = fileContent .. ' firstCommit = ' .. handle:read('*a'):gsub('[%s]+', '') .. ',\r\n'; handle:close(); -- Latest commit. local handle = io.popen(GIT_COMMAND .. path .. LATEST_COMMIT_COMMAND); fileContent = fileContent .. ' latestCommit = ' .. handle:read('*a'):gsub('[%s]+', '') .. ',\r\n'; handle:close(); -- Number of commits. local handle = io.popen(GIT_COMMAND .. path .. TOTAL_COMMITS_COMMAND); fileContent = fileContent .. ' totalCommits = ' .. handle:read('*a'):gsub('[%s]+', '') .. '\r\n'; handle:close(); fileContent = fileContent .. '};\r\n'; love.filesystem.write(LOG_FOLDER .. projectname .. INFO_FILE, fileContent); end end -- ------------------------------------------------ -- Getters -- ------------------------------------------------ --- -- Checks if git is available on the system. -- function LogCreator.isGitAvailable() local handle = io.popen('git version'); local result = handle:read('*a'); print(result); handle:close(); return result:find('git version'); end return LogCreator;
Fix #24 - Use io.popen instead of os.execute to check for git
Fix #24 - Use io.popen instead of os.execute to check for git Had to replace os.execute as it produced garbled output on Windows. Apparently this is an issue within LOVE / LuaJIT itself. (see https://bitbucket.org/rude/love/issue/940)
Lua
mit
rm-code/logivi