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
1519ad9cc0a5cf12d849cb7306d73f5df9a97eef
state/main_menu.lua
state/main_menu.lua
local o = {} local startx = W.getWidth() * 0.5 - 176 * 0.5 local starty = 160 o.imgLogo = love.graphics.newImage("resources/sprites/ui/logo.png") o.imgBackground = love.graphics.newImage("resources/sprites/ui/menu_background.png") o.imgMiddleground = love.graphics.newImage("resources/sprites/ui/menu_middleground.png") o.imgScreen = love.graphics.newImage("gfx/screen00.png") o.fontMenu = G.newFont(32) o.fontVersion = G.newFont(16) o.version = "0.0.0" o.effectTimer = 0 o.chromaticEffect = 0 o.guiMenu = love.gui.newGui() o.btnStart = o.guiMenu.newButton(startx, starty + 80 * 0, 176, 48, "Start") o.btnConfigure = o.guiMenu.newButton(startx, starty + 80 * 1, 176, 48, "Settings") o.btnCredits = o.guiMenu.newButton(startx, starty + 80 * 2, 176, 48, "Credits") o.btnQuit = o.guiMenu.newButton(startx, starty + 80 * 3, 176, 48, "Quit") o.reset = function() o.guiMenu.flushMouse() end o.update = function(dt) o.effectTimer = o.effectTimer + dt o.chromaticEffect = o.chromaticEffect + dt o.guiMenu.update(dt) if o.btnStart.isHit() then love.sounds.playSound("sounds/button_pressed.wav") love.setgamestate(1) end if o.btnConfigure.isHit() then love.sounds.playSound("sounds/button_pressed.wav") love.setgamestate(6) o.guiMenu.flushMouse() end if o.btnCredits.isHit() then love.sounds.playSound("sounds/button_pressed.wav") love.setgamestate(5) end if o.btnQuit.isHit() then love.sounds.playSound("sounds/button_pressed.wav") love.event.quit() end end o.draw = function() G.setFont(o.fontMenu) G.setBlendMode("alpha") G.setColor(255, 255, 255) G.draw(o.imgScreen) G.setColor(255, 255, 255, 223) G.draw(o.imgBackground) G.setColor(95 + math.sin(o.effectTimer * 0.1) * 63, 191 + math.cos(o.effectTimer) * 31, 223 + math.sin(o.effectTimer) * 31, 255) G.setBlendMode("additive") G.draw(o.imgMiddleground,(W.getWidth()-o.imgMiddleground:getWidth())*0.5,0) G.setColor(255, 255, 255) G.setBlendMode("alpha") G.draw(o.imgLogo, W.getWidth() * 0.5, o.imgLogo:getHeight() * 0.5, math.sin(o.effectTimer * 4) * 0.05 * math.max(0, 2 - o.effectTimer ^ 0.5), 1, 1, o.imgLogo:getWidth() * 0.5, o.imgLogo:getHeight() * 0.5) o.guiMenu.draw() G.setFont(o.fontVersion) G.setColor(95 + math.sin(o.effectTimer * 0.1) * 63, 191 + math.cos(o.effectTimer) * 31, 223 + math.sin(o.effectTimer) * 31, 255) G.print(o.version, W.getWidth() - 64, W.getHeight() - 32) if math.random(0, love.timer.getFPS() * 5) == 0 then o.chromaticEffect = math.random(0, 5) * 0.1 end if o.chromaticEffect < 1.0 then local colorAberration1 = math.sin(love.timer.getTime() * 10.0) * (1.0 - o.chromaticEffect) * 2.0 local colorAberration2 = math.cos(love.timer.getTime() * 10.0) * (1.0 - o.chromaticEffect) * 2.0 love.postshader.addEffect("chromatic", colorAberration1, colorAberration2, colorAberration2, -colorAberration1, colorAberration1, -colorAberration2) end end o.setVersion = function(version) o.version = version end return o
local o = {} local startx = W.getWidth() * 0.5 - 176 * 0.5 local starty = 160 o.imgLogo = love.graphics.newImage("resources/sprites/ui/logo.png") o.imgBackground = love.graphics.newImage("resources/sprites/ui/menu_background.png") o.imgMiddleground = love.graphics.newImage("resources/sprites/ui/menu_middleground.png") o.imgScreen = love.graphics.newImage("gfx/screen00.png") o.fontMenu = G.newFont(32) o.fontVersion = G.newFont(16) o.version = "0.0.0" o.effectTimer = 0 o.chromaticEffect = 0 o.guiMenu = love.gui.newGui() o.btnStart = o.guiMenu.newButton(startx, starty + 80 * 0, 176, 48, "Start") o.btnConfigure = o.guiMenu.newButton(startx, starty + 80 * 1, 176, 48, "Settings") o.btnCredits = o.guiMenu.newButton(startx, starty + 80 * 2, 176, 48, "Credits") o.btnQuit = o.guiMenu.newButton(startx, starty + 80 * 3, 176, 48, "Quit") o.reset = function() o.guiMenu.flushMouse() end o.update = function(dt) o.effectTimer = o.effectTimer + dt o.chromaticEffect = o.chromaticEffect + dt o.guiMenu.update(dt) if o.btnStart.isHit() then love.sounds.playSound("sounds/button_pressed.wav") love.setgamestate(1) o.guiMenu.flushMouse() end if o.btnConfigure.isHit() then love.sounds.playSound("sounds/button_pressed.wav") love.setgamestate(6) o.guiMenu.flushMouse() end if o.btnCredits.isHit() then love.sounds.playSound("sounds/button_pressed.wav") love.setgamestate(5) o.guiMenu.flushMouse() end if o.btnQuit.isHit() then love.sounds.playSound("sounds/button_pressed.wav") love.event.quit() end end o.draw = function() G.setFont(o.fontMenu) G.setBlendMode("alpha") G.setColor(255, 255, 255) G.draw(o.imgScreen) G.setColor(255, 255, 255, 223) G.draw(o.imgBackground) G.setColor(95 + math.sin(o.effectTimer * 0.1) * 63, 191 + math.cos(o.effectTimer) * 31, 223 + math.sin(o.effectTimer) * 31, 255) G.setBlendMode("additive") G.draw(o.imgMiddleground,(W.getWidth()-o.imgMiddleground:getWidth())*0.5,0) G.setColor(255, 255, 255) G.setBlendMode("alpha") G.draw(o.imgLogo, W.getWidth() * 0.5, o.imgLogo:getHeight() * 0.5, math.sin(o.effectTimer * 4) * 0.05 * math.max(0, 2 - o.effectTimer ^ 0.5), 1, 1, o.imgLogo:getWidth() * 0.5, o.imgLogo:getHeight() * 0.5) o.guiMenu.draw() G.setFont(o.fontVersion) G.setColor(95 + math.sin(o.effectTimer * 0.1) * 63, 191 + math.cos(o.effectTimer) * 31, 223 + math.sin(o.effectTimer) * 31, 255) G.print(o.version, W.getWidth() - 64, W.getHeight() - 32) if math.random(0, love.timer.getFPS() * 5) == 0 then o.chromaticEffect = math.random(0, 5) * 0.1 end if o.chromaticEffect < 1.0 then local colorAberration1 = math.sin(love.timer.getTime() * 10.0) * (1.0 - o.chromaticEffect) * 2.0 local colorAberration2 = math.cos(love.timer.getTime() * 10.0) * (1.0 - o.chromaticEffect) * 2.0 love.postshader.addEffect("chromatic", colorAberration1, colorAberration2, colorAberration2, -colorAberration1, colorAberration1, -colorAberration2) end end o.setVersion = function(version) o.version = version end return o
menu fix
menu fix
Lua
mit
sam1i/Turres-Monacorum,sam1i/Turres-Monacorum
06f75dc18bf152d9d6bbe8749db69052506200f5
triggerfield/lakeoflife_teleport.lua
triggerfield/lakeoflife_teleport.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/>. ]] --Teleporters in the Lake of Life dungeon --Evie Pryler local common = require("base.common") local M = {} function M.MoveToField( User ) if User:getType() ~= Character.player then return end if User.pos == position(789, 295, -9) then --To the boss area. world:gfx(41,User.pos); world:makeSound(13,User.pos); User:warp(position(559, 260, 0)); world:gfx(41,User.pos); world:makeSound(13,User.pos); elseif User.pos == position(559,258,0) then -- back down to Lake of Life Main Dungeon world:gfx(41,User.pos); world:makeSound(13,User.pos); User:warp(position(797, 295 -9)); world:gfx(41,User.pos); world:makeSound(13,User.pos); elseif User.pos == position(727, 324, -9) then -- Boat to Island of Zenia. common.InformNLS(User,"Als du in das Boot steigst, setzt es sich in Bewegung, bevor du dich hinsitzen kannst, um dich zu einer entfernten Insel zu tragen.","As you step into the boat, it starts moving before youhave a chance tosit down, transporting you to a distant island."); --sending a message world:gfx(11,User.pos); world:makeSound(9,User.pos); User:warp(position(756, 341, -9)); world:gfx(11,User.pos); world:makeSound(9,User.pos); elseif User.pos == position(756, 351, -9) then -- Boat back to the dock common.InformNLS(User,"Als du in das Boot steigst, setzt es sich in Bewegung, bevor du dich hinsitzen kannst, um dich zurck zur Anlegestelle zu tragen.","As you step into the boat, it starts moving before youhave a chance tosit down, transporting you back to the dock."); --sending a message world:gfx(11,User.pos); world:makeSound(9,User.pos); User:warp(position(734, 323, -9)); world:gfx(11,User.pos); world:makeSound(9,User.pos); end end return M
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO triggerfields VALUES (789, 295, -9,'triggerfield.lakeoflife_teleport'); -- INSERT INTO triggerfields VALUES (559, 258, 0,'triggerfield.lakeoflife_teleport'); -- INSERT INTO triggerfields VALUES (727, 324, -9,'triggerfield.lakeoflife_teleport'); -- INSERT INTO triggerfields VALUES (756, 351, -9,'triggerfield.lakeoflife_teleport'); --Teleporters in the Lake of Life dungeon --Evie Pryler local common = require("base.common") local M = {} function M.MoveToField( User ) if User:getType() ~= Character.player then return end if User.pos == position(789, 295, -9) then -- to the boss area world:gfx(41, User.pos) world:makeSound(13,User.pos) User:warp(position(559, 260, 0)) world:gfx(41, User.pos) world:makeSound(13, User.pos) elseif User.pos == position(559, 258, 0) then -- back down to Lake of Life Main Dungeon world:gfx(41, User.pos) world:makeSound(13, User.pos) User:warp(position(797, 295 -9)) world:gfx(41, User.pos) world:makeSound(13,User.pos) elseif User.pos == position(727, 324, -9) then -- Boat to Island of Zenia common.InformNLS(User,"Als du in das Boot steigst, setzt es sich in Bewegung, bevor du dich hinsetzen kannst, um dich zu einer entfernten Insel zu tragen.","As you step into the boat, it starts moving before youhave a chance tosit down, transporting you to a distant island.") world:gfx(11, User.pos) world:makeSound(9, User.pos) User:warp(position(756, 341, -9)) world:gfx(11,User.pos) world:makeSound(9, User.pos) elseif User.pos == position(756, 351, -9) then -- Boat back to the dock common.InformNLS(User,"Als du in das Boot steigst, setzt es sich in Bewegung, bevor du dich hinsetzen kannst, um dich zurck zur Anlegestelle zu tragen.","As you step into the boat, it starts moving before youhave a chance tosit down, transporting you back to the dock.") world:gfx(11, User.pos) world:makeSound(9, User.pos) User:warp(position(734, 323, -9)) world:gfx(11, User.pos) world:makeSound(9, User.pos) end end return M
add sql lines, fix a typo in german text, style fixes
add sql lines, fix a typo in german text, style fixes
Lua
agpl-3.0
LaFamiglia/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content
092a7fcb01de7fbe2497cc37578be547f0189bb1
item/id_90_flute.lua
item/id_90_flute.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/>. ]] -- I_90 Floete spielen -- UPDATE common SET com_script='item.id_90_flute' WHERE com_itemid=90; require("item.base.music") require("item.general.wood") module("item.id_90_flute", package.seeall) skill = Character.flute item.base.music.addTalkText("#me produces some squeaking sounds on the flute.","#me macht einige quietschende Gerusche auf der Flte.", skill); item.base.music.addTalkText("#me plays a horribly out of tune melody.","#me spielt eine frchterlich verstimmte Melodie auf der Flte.", skill); item.base.music.addTalkText("#me plays an out of tune melody.","#me spielt eine verstimmte Melodie auf der Flte.", skill); item.base.music.addTalkText("#me plays an airy tune on the flute.","#me spielt eine leichte Melodie auf der Flte.", skill); item.base.music.addTalkText("#me plays a wild tune on the flute.","#me spielt eine wilde Melodie auf der Flte.", skill); function UseItem(User, SourceItem) --Testing fireball, only activates if flute's data key name is used. Does not affect normal flute -Dyluck local targetPos local targetChar local extraPos local graphicNum local xoff local yoff local mylist local last local isChar local totalDmg local testDmg graphicNum = tonumber(SourceItem:getData("spell")); if ( graphicNum ~= nil ) then if (User:increaseAttrib("intelligence", 0) < 10) then User:talk(Character.say, "INT would be too low. You have "..User:increaseAttrib("intelligence", 0)); end if (User:increaseAttrib("mana", 0) < 50) then User:talk(Character.say, "Mana would be too low. You have "..User:increaseAttrib("mana", 0)); end User:talk(Character.say, "#me casts Fireball "); --User facing direction to determine offset numbers for target area if ( User:getFaceTo() == 0) then --north xoff = 0; yoff = -1; elseif ( User:getFaceTo() == 1) then --northeast xoff = 1; yoff = -1; elseif ( User:getFaceTo() == 2) then --east xoff = 1; yoff = 0; elseif ( User:getFaceTo() == 3) then --southeast xoff = 1; yoff = 1; elseif ( User:getFaceTo() == 4) then --south xoff = 0; yoff = 1; elseif ( User:getFaceTo() == 5) then --southwest xoff = -1; yoff = 1; elseif ( User:getFaceTo() == 6) then --west xoff = -1; yoff = 0; elseif ( User:getFaceTo() == 7) then --northwest xoff = -1; yoff = -1; end --Set max range and check for line of sight targetPos = position(User.pos.x + 5 * xoff, User.pos.y + 5 * yoff, User.pos.z); mylist = world:LoS(User.pos, targetPos); last = table.getn(mylist); if (mylist[1] == nil) then --hit max range world:gfx(graphicNum, targetPos); world:makeSound(5, targetPos); if world:isCharacterOnField(targetPos) then --hit char at max range isChar = true; targetChar = world:getCharacterOnField(targetPos); end else --hit obstacle --[[ for key, listEntry in pairs(mylist) do User:inform("Item with the ID: "..listEntry.OBJECT.id); end User:inform("Array size is: "..last); ]]-- targetPos = mylist[last].OBJECT.pos; world:gfx(graphicNum, mylist[last].OBJECT.pos); world:makeSound(5, mylist[last].OBJECT.pos); if (mylist[last].TYPE == "CHARACTER") then --obstacle is a char isChar = true; targetChar = mylist[last].OBJECT; end end --Calculate numbers and damage char if ( (isChar == true) and (targetChar:increaseAttrib("hitpoints", 0) > 0) ) then world:makeSound(1, targetPos); totalDmg = -( (21 + User:increaseAttrib("intelligence", 0) - targetChar:increaseAttrib("essence", 0) ) * 50) testDmg = -2000; targetChar:increaseAttrib("hitpoints", testDmg); if (User:increaseAttrib("mana", 0) >= 50) then User:increaseAttrib("mana", - 50); end User:talk(Character.say, "Damage is -2000, but would've been "..totalDmg); User:talk(Character.say, "Because your INT was "..User:increaseAttrib("intelligence", 0)); end --User:talk(Character.say, "Mana is now "..User:increaseAttrib("mana", 0)); --[[ for i = 0, 2, 1 do for j = 0, 2, 1 do extraPos = position(targetPos.x -1 +i, targetPos.y -1 +j, targetPos.z); if (graphicNum ~= nil) then world:gfx(graphicNum, extraPos); else User:talk(Character.say, "No graphic for this number"); end if world:isCharacterOnField(extraPos) then --if there's a target char on target position targetChar = world:getCharacterOnField(extraPos); --find the char targetChar:increaseAttrib("hitpoints", -2000); world:makeSound(1, extraPos); end end end]]-- end --End Test -Dyluck end LookAtItem = item.general.wood.LookAtItem
--[[ 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/>. ]] -- I_90 Floete spielen -- UPDATE common SET com_script='item.id_90_flute' WHERE com_itemid=90; require("item.base.music") require("item.general.wood") module("item.id_90_flute", package.seeall) skill = Character.flute item.base.music.addTalkText("#me produces some squeaking sounds on the flute.","#me macht einige quietschende Gerusche auf der Flte.", skill); item.base.music.addTalkText("#me plays a horribly out of tune melody.","#me spielt eine frchterlich verstimmte Melodie auf der Flte.", skill); item.base.music.addTalkText("#me plays an out of tune melody.","#me spielt eine verstimmte Melodie auf der Flte.", skill); item.base.music.addTalkText("#me plays an airy tune on the flute.","#me spielt eine leichte Melodie auf der Flte.", skill); item.base.music.addTalkText("#me plays a wild tune on the flute.","#me spielt eine wilde Melodie auf der Flte.", skill); function UseItem(User, SourceItem) item.base.music.PlayInstrument(User,SourceItem,skill); end LookAtItem = item.general.wood.LookAtItem
fix flute, and remove test code
fix flute, and remove test code
Lua
agpl-3.0
KayMD/Illarion-Content,LaFamiglia/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content
1965434c9b73a3245c30815f888ba83224af29f6
travis-test-tracer/premake4.lua
travis-test-tracer/premake4.lua
-- hdf5 linking is different in windows and ubuntu hdf5_link = "hdf5" thread_link = "pthread" -- Check current linux distro, (on windows returns mingw) local handle = io.popen('uname -a') local result = handle:read("*a") handle:close() if string.find(result, 'Debian') then print(result) hdf5_link="hdf5_serial" end -- ugly hack to use gcc-4.8 premake.gcc.cc = 'gcc-4.8' premake.gcc.cxx = 'g++-4.8' -- A solution contains projects, and defines the available configurations solution "MyApplication" configurations { "Debug", "Release", "Debug_verbose", "ReleaseNoRays" } -- A project defines one build target project "tracer" kind "ConsoleApp" language "C++" files { "**.h", "**.cpp", "Tracer/**.cpp", "raytracer_src/**.cpp", "raytracer_src/**.cpp", } kind "ConsoleApp" language "C++" files { "**.h", "**.cpp", "raytracer_src/**.cpp", "raytracer_src/**.cpp", } includedirs {"raytracer_src/**", "/usr/include/hdf5/serial"} includedirs {"raytracer_src/**", "arma/usr/", "arma/usr/include/", "arma/usr/include/armadillo_bits", "arma/usr/share/Armadillo/CMake", "/usr/include/hdf5/serial"} libdirs { "arma/usr/lib/" } excludes{ "raytracer_src/Detectors/IrradianceDetector**", "Tests/IrradianceDetectorTest**"} configuration "Debug_verbose" defines { "DEBUG", "ARMA_DONT_PRINT_ERRORS", "DEBUG_SOLIDPROPAGATION", "DEBUG_VERBOSE", " DEBUG_RAYINTERSECT", "SAVERAYS" } links { "armadillo", hdf5_link, thread_link} flags { "Symbols" } -- Enables some additional warnings. buildoptions { "-Wall" , '-W', "-std=c++11"} configuration "Debug" defines { "DEBUG", "ARMA_DONT_PRINT_ERRORS" , "SAVERAYS"} links { "armadillo", hdf5_link, thread_link} flags { "Symbols" } -- Enables some additional warnings. buildoptions { "-Wall" , '-W', "-std=c++11"} configuration "Release" defines { "NDEBUG", "ARMA_DONT_PRINT_ERRORS", "ARMA_NO_DEBUG" , "SAVERAYS"} links { "armadillo", hdf5_link, thread_link} flags { "OptimizeSpeed", "EnableSSE", "EnableSSE2"} buildoptions {"-std=c++11"} configuration "ReleaseNoRays" defines { "NDEBUG", "ARMA_DONT_PRINT_ERRORS", "ARMA_NO_DEBUG"} links { "armadillo", hdf5_link, thread_link} flags { "OptimizeSpeed", "EnableSSE", "EnableSSE2"} buildoptions {"-std=c++11"} targetname ("tracer-no-ray-save") -- -- Rename gmake action into _gmake -- assert(premake.action.list.gmake, "Your Premake does not have gmake action!") premake.action.list.gmake, premake.action.list._gmake = nil, premake.action.list.gmake premake.action.list._gmake.trigger = "_gmake" -- -- Add new gmake action -- newaction { trigger = "gmake", description = premake.action.get("_gmake").description, shortname = premake.action.get("_gmake").shortname, valid_kinds = premake.action.get("_gmake").valid_kinds, valid_languages = premake.action.get("_gmake").valid_languages, valid_tools = premake.action.get("_gmake").valid_tools, onproject = function(prj) -- Your code end, execute = function() -- Your code premake.action.call("_gmake") -- Opens a file in append mode file = io.open("Makefile", "a") io.output(file) io.write("\n") io.write("INSTALL = install -c\n") io.write("prefix = /usr/local\n") io.write("binprefix = \n") io.write("# The directory to install tar in.\n") io.write("bindir = $(prefix)/bin\n") io.write("install:\n") io.write("ifeq ($(config),releasenorays)\n") io.write("\t$(INSTALL) tracer-no-ray-save $(DESTDIR)$(bindir)/$(binprefix)tracer-no-ray-save\n") io.write("else\n") io.write("\t$(INSTALL) tracer $(DESTDIR)$(bindir)/$(binprefix)tracer\n") io.write("endif\n") io.write("\n") -- closes the open file io.close(file) end }
-- hdf5 linking is different in windows and ubuntu hdf5_link = "hdf5" thread_link = "pthread" -- Check current linux distro, (on windows returns mingw) local handle = io.popen('uname -a') local result = handle:read("*a") handle:close() if string.find(result, 'Debian') then print(result) hdf5_link="hdf5_serial" end -- ugly hack to use gcc-4.8 premake.gcc.cc = 'gcc-4.8' premake.gcc.cxx = 'g++-4.8' -- A solution contains projects, and defines the available configurations solution "MyApplication" configurations { "Debug", "Release", "Debug_verbose", "ReleaseNoRays" } -- A project defines one build target project "tracer" kind "ConsoleApp" language "C++" files { "**.h", "**.cpp", "../**.cpp", "../raytracer_src/**.cpp", "../raytracer_src/**.cpp", } includedirs {"../raytracer_src/**", "/usr/include/hdf5/serial"} includedirs {"../raytracer_src/**", "../arma/usr/", "../arma/usr/include/", "../arma/usr/include/armadillo_bits", "../arma/usr/share/Armadillo/CMake", "/usr/include/hdf5/serial"} libdirs { "../arma/usr/lib/" } excludes{ "../raytracer_src/Detectors/IrradianceDetector**", "../Tests/IrradianceDetectorTest**"} configuration "Debug_verbose" defines { "DEBUG", "ARMA_DONT_PRINT_ERRORS", "DEBUG_SOLIDPROPAGATION", "DEBUG_VERBOSE", " DEBUG_RAYINTERSECT", "SAVERAYS" } links { "armadillo", hdf5_link, thread_link} flags { "Symbols" } -- Enables some additional warnings. buildoptions { "-Wall" , '-W', "-std=c++11"} configuration "Debug" defines { "DEBUG", "ARMA_DONT_PRINT_ERRORS" , "SAVERAYS"} links { "armadillo", hdf5_link, thread_link} flags { "Symbols" } -- Enables some additional warnings. buildoptions { "-Wall" , '-W', "-std=c++11"} configuration "Release" defines { "NDEBUG", "ARMA_DONT_PRINT_ERRORS", "ARMA_NO_DEBUG" , "SAVERAYS"} links { "armadillo", hdf5_link, thread_link} flags { "OptimizeSpeed", "EnableSSE", "EnableSSE2"} buildoptions {"-std=c++11"} configuration "ReleaseNoRays" defines { "NDEBUG", "ARMA_DONT_PRINT_ERRORS", "ARMA_NO_DEBUG"} links { "armadillo", hdf5_link, thread_link} flags { "OptimizeSpeed", "EnableSSE", "EnableSSE2"} buildoptions {"-std=c++11"} targetname ("tracer-no-ray-save") -- -- Rename gmake action into _gmake -- assert(premake.action.list.gmake, "Your Premake does not have gmake action!") premake.action.list.gmake, premake.action.list._gmake = nil, premake.action.list.gmake premake.action.list._gmake.trigger = "_gmake" -- -- Add new gmake action -- newaction { trigger = "gmake", description = premake.action.get("_gmake").description, shortname = premake.action.get("_gmake").shortname, valid_kinds = premake.action.get("_gmake").valid_kinds, valid_languages = premake.action.get("_gmake").valid_languages, valid_tools = premake.action.get("_gmake").valid_tools, onproject = function(prj) -- Your code end, execute = function() -- Your code premake.action.call("_gmake") -- Opens a file in append mode file = io.open("Makefile", "a") io.output(file) io.write("\n") io.write("INSTALL = install -c\n") io.write("prefix = /usr/local\n") io.write("binprefix = \n") io.write("# The directory to install tar in.\n") io.write("bindir = $(prefix)/bin\n") io.write("install:\n") io.write("ifeq ($(config),releasenorays)\n") io.write("\t$(INSTALL) tracer-no-ray-save $(DESTDIR)$(bindir)/$(binprefix)tracer-no-ray-save\n") io.write("else\n") io.write("\t$(INSTALL) tracer $(DESTDIR)$(bindir)/$(binprefix)tracer\n") io.write("endif\n") io.write("\n") -- closes the open file io.close(file) end }
Travis fix
Travis fix
Lua
apache-2.0
ollitapa/VTT-Raytracer,ollitapa/VTT-Raytracer
b5746390cd24c1df6fcc0ac06c8108fcf16dfb5e
share/lua/playlist/lelombrik.lua
share/lua/playlist/lelombrik.lua
--[[ French humor site: http://lelombrik.net $Id$ Copyright © 2007 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "lelombrik.net/videos" ) end -- Parse function. function parse() while true do line = vlc.readline() if not line then vlc.msg.err("Couldn't extract the video URL from lelombrik") return { } end if string.match( line, "id=\"nom_fichier\">" ) then title = string.gsub( line, ".*\"nom_fichier\">([^<]*).*", "%1" ) elseif string.match( line, "'file'" ) then _,_,path = string.find( line, "'file', *'([^']*)") elseif string.match( line, "flashvars=" ) then path = string.gsub( line, "flashvars=.*&file=([^&]*).*", "%1" ) arturl = string.gsub( line, "flashvars=.*&image=([^&]*).*", "%1" ) elseif string.match( line, "'image'" ) then _,_,arturl = string.find( line, "'image', *'([^']*)") end if path and arturl and title then return { { path = path; arturl = arturl; title = title } } end end end
--[[ French humor site: http://lelombrik.net $Id$ Copyright © 2007 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "lelombrik.net/videos" ) end -- Parse function. function parse() while true do line = vlc.readline() if not line then vlc.msg.err("Couldn't extract the video URL from lelombrik") return { } end if string.match( line, "id=\"nom_fichier\">" ) then title = string.gsub( line, ".*\"nom_fichier\">([^<]*).*", "%1" ) if title then title = vlc.strings.iconv( "UTF8", "ISO_8859-1", title ) end elseif string.match( line, "'file'" ) then _,_,path = string.find( line, "'file', *'([^']*)") elseif string.match( line, "flashvars=" ) then path = string.gsub( line, "flashvars=.*&file=([^&]*).*", "%1" ) arturl = string.gsub( line, "flashvars=.*&image=([^&]*).*", "%1" ) elseif string.match( line, "'image'" ) then _,_,arturl = string.find( line, "'image', *'([^']*)") end if path and arturl and title then return { { path = path; arturl = arturl; title = title } } end end end
lelombrik: fix title encoding.
lelombrik: fix title encoding.
Lua
lgpl-2.1
krichter722/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,xkfz007/vlc,krichter722/vlc,xkfz007/vlc,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc,shyamalschandra/vlc,shyamalschandra/vlc,vlc-mirror/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.2
7a7f63586f6445217b474bdb79e260977d4c6ec1
modules/client_serverlist/serverlist.lua
modules/client_serverlist/serverlist.lua
ServerList = {} -- private variables local serverListWindow = nil local serverTextList = nil local removeWindow = nil local servers = {} -- public functions function ServerList.init() serverListWindow = g_ui.displayUI('serverlist') serverTextList = serverListWindow:getChildById('serverList') local serverSettings = g_settings.getNode('ServerList') if serverSettings then ServerList.load(serverSettings) end end function ServerList.terminate() ServerList.destroy() g_settings.setNode('ServerList', servers) ServerList = nil end function ServerList.load(serverSettings) for host, server in pairs(serverSettings) do ServerList.add(host, server.port, server.protocol, true) end end function ServerList.select() local selected = serverTextList:getFocusedChild() if selected then local server = servers[selected:getId()] if server then EnterGame.setDefaultServer(selected:getId(), server.port, server.protocol) EnterGame.setAccountName(server.account) EnterGame.setPassword(server.password) ServerList.hide() end end end function ServerList.add(host, port, protocol, load) if not host or not port or not protocol then return false, 'Failed to load settings' elseif not load and servers[host] then return false, 'Server already exists' elseif host == '' or port == '' then return false, 'Required fields are missing' end local widget = g_ui.createWidget('ServerWidget', serverTextList) widget:setId(host) if not load then servers[host] = { port = port, protocol = protocol, account = '', password = '' } end local details = widget:getChildById('details') details:setText(host..':'..port) local proto = widget:getChildById('protocol') proto:setText(protocol) connect(widget, { onDoubleClick = function () ServerList.select() return true end } ) return true end function ServerList.remove(widget) local host = widget:getId() if removeWindow then return end local yesCallback = function() widget:destroy() servers[host] = nil removeWindow:destroy() removeWindow=nil end local noCallback = function() removeWindow:destroy() removeWindow=nil end removeWindow = displayGeneralBox(tr('Remove'), tr('Remove '..host..'?'), { { text=tr('Yes'), callback=yesCallback }, { text=tr('No'), callback=noCallback }, anchor=AnchorHorizontalCenter}, yesCallback, noCallback) end function ServerList.destroy() if serverListWindow then serverTextList = nil serverListWindow:destroy() serverListWindow = nil end end function ServerList.show() if g_game.isOnline() then return end serverListWindow:show() serverListWindow:raise() serverListWindow:focus() end function ServerList.hide() serverListWindow:hide() end function ServerList.setServerAccount(host, account) if servers[host] then servers[host].account = account end end function ServerList.setServerPassword(host, password) if servers[host] then servers[host].password = password end end
ServerList = {} -- private variables local serverListWindow = nil local serverTextList = nil local removeWindow = nil local servers = {} -- public functions function ServerList.init() serverListWindow = g_ui.displayUI('serverlist') serverTextList = serverListWindow:getChildById('serverList') servers = g_settings.getNode('ServerList') or {} if servers then ServerList.load() end end function ServerList.terminate() ServerList.destroy() g_settings.setNode('ServerList', servers) ServerList = nil end function ServerList.load() for host, server in pairs(servers) do ServerList.add(host, server.port, server.protocol, true) end end function ServerList.select() local selected = serverTextList:getFocusedChild() if selected then local server = servers[selected:getId()] if server then EnterGame.setDefaultServer(selected:getId(), server.port, server.protocol) EnterGame.setAccountName(server.account) EnterGame.setPassword(server.password) ServerList.hide() end end end function ServerList.add(host, port, protocol, load) if not host or not port or not protocol then return false, 'Failed to load settings' elseif not load and servers[host] then return false, 'Server already exists' elseif host == '' or port == '' then return false, 'Required fields are missing' end local widget = g_ui.createWidget('ServerWidget', serverTextList) widget:setId(host) if not load then servers[host] = { port = port, protocol = protocol, account = '', password = '' } end local details = widget:getChildById('details') details:setText(host..':'..port) local proto = widget:getChildById('protocol') proto:setText(protocol) connect(widget, { onDoubleClick = function () ServerList.select() return true end } ) return true end function ServerList.remove(widget) local host = widget:getId() if removeWindow then return end local yesCallback = function() widget:destroy() servers[host] = nil removeWindow:destroy() removeWindow=nil end local noCallback = function() removeWindow:destroy() removeWindow=nil end removeWindow = displayGeneralBox(tr('Remove'), tr('Remove '..host..'?'), { { text=tr('Yes'), callback=yesCallback }, { text=tr('No'), callback=noCallback }, anchor=AnchorHorizontalCenter}, yesCallback, noCallback) end function ServerList.destroy() if serverListWindow then serverTextList = nil serverListWindow:destroy() serverListWindow = nil end end function ServerList.show() if g_game.isOnline() then return end serverListWindow:show() serverListWindow:raise() serverListWindow:focus() end function ServerList.hide() serverListWindow:hide() end function ServerList.setServerAccount(host, account) if servers[host] then servers[host].account = account end end function ServerList.setServerPassword(host, password) if servers[host] then servers[host].password = password end end
Fix serverlist issues from previous commit.
Fix serverlist issues from previous commit. Was referencing a 'global' variable so a simple check will do.
Lua
mit
dreamsxin/otclient,dreamsxin/otclient,Radseq/otclient,dreamsxin/otclient,Radseq/otclient
e0a0c427f97677c905e74cd16733ac745f7a64a3
UCDwanted/server.lua
UCDwanted/server.lua
local wantedPoints = {} addEventHandler("onResourceStart", resourceRoot, function () for _, plr in ipairs(Element.getAllByType("player")) do if (not plr.account.guest) then setWantedPoints(plr, exports.UCDaccounts:GAD(plr, "wp")) end end end ) addEventHandler("onResourceStop", resourceRoot, function () for _, plr in ipairs(Element.getAllByType("player")) do if (not plr.account.guest) then exports.UCDaccounts:SAD(plr, "wp", getWantedPoints(plr)) end end end ) function addWantedPoints(plr, wp) if (plr and wp and not plr.account.guest and tonumber(wp)) then wp = tonumber(wp) local a = plr.account.name if (not wantedPoints[a]) then wantedPoints[a] = 0 end setWantedPoints(plr, wantedPoints[a] + wp) exports.UCDstats:setPlayerAccountStat(plr, "lifetimeWanted", exports.UCDstats:getPlayerAccountStat(plr, "lifetimeWanted") + wp) return true end end function getWantedPoints(plr) if (plr and not plr.account.guest) then local a = plr.account.name if (not wantedPoints[a]) then wantedPoints[a] = 0 end return wantedPoints[a] end end function setWantedPoints(plr, wp) if (plr and wp and not plr.account.guest and tonumber(wp)) then wp = tonumber(wp) local a = plr.account.name if (not wantedPoints[a]) then wantedPoints[a] = wp return true end wantedPoints[a] = wp plr:setData("w", wantedPoints[a]) triggerEvent("onPlayerWPChange", plr, wantedPoints[a]) return true end end function onPlayerWPChange(wp) -- Stars if (wp > 0 and wp <= 10) then source.wantedLevel = 1 elseif (wp > 10 and wp <= 20) then source.wantedLevel = 2 elseif (wp > 20 and wp <= 30) then source.wantedLevel = 3 elseif (wp > 30 and wp <= 40) then source.wantedLevel = 4 elseif (wp > 40 and wp <= 50) then source.wantedLevel = 5 elseif (wp > 50) then --if (source.wantedLevel ~= 60) then source.wantedLevel = 6 --end else source.wantedLevel = 0 end -- Nametag if (wp > 0) then source.nametagText = "["..tostring(source.wantedLevel).."] "..tostring(source.name) else source.nametagText = source.name end if (wp > 0) then if (source.team.name == "Law") then exports.UCDjobs:setPlayerJob(source, "Criminal") end end end addEvent("onPlayerWPChange") addEventHandler("onPlayerWPChange", root, onPlayerWPChange)
local wantedPoints = {} addEventHandler("onResourceStart", resourceRoot, function () for _, plr in ipairs(Element.getAllByType("player")) do if (not plr.account.guest) then setWantedPoints(plr, exports.UCDaccounts:GAD(plr, "wp")) end end end ) addEventHandler("onResourceStop", resourceRoot, function () for _, plr in ipairs(Element.getAllByType("player")) do if (not plr.account.guest) then exports.UCDaccounts:SAD(plr, "wp", getWantedPoints(plr)) end end end ) function addWantedPoints(plr, wp) if (plr and wp and not plr.account.guest and tonumber(wp)) then wp = tonumber(wp) local a = plr.account.name if (not wantedPoints[a]) then wantedPoints[a] = 0 end setWantedPoints(plr, wantedPoints[a] + wp) exports.UCDstats:setPlayerAccountStat(plr, "lifetimeWanted", exports.UCDstats:getPlayerAccountStat(plr, "lifetimeWanted") + wp) return true end end function getWantedPoints(plr) if (plr and not plr.account.guest) then local a = plr.account.name if (not wantedPoints[a]) then wantedPoints[a] = exports.UCDaccounts:GAD(plr, "wp") or 0 end return wantedPoints[a] end end function setWantedPoints(plr, wp) if (plr and wp and not plr.account.guest and tonumber(wp)) then wp = tonumber(wp) local a = plr.account.name if (not wantedPoints[a]) then wantedPoints[a] = wp return true end wantedPoints[a] = wp plr:setData("w", wantedPoints[a]) triggerEvent("onPlayerWPChange", plr, wantedPoints[a]) return true end end function onPlayerWPChange(wp) -- Stars if (wp > 0 and wp <= 10) then source.wantedLevel = 1 elseif (wp > 10 and wp <= 20) then source.wantedLevel = 2 elseif (wp > 20 and wp <= 30) then source.wantedLevel = 3 elseif (wp > 30 and wp <= 40) then source.wantedLevel = 4 elseif (wp > 40 and wp <= 50) then source.wantedLevel = 5 elseif (wp > 50) then --if (source.wantedLevel ~= 60) then source.wantedLevel = 6 --end else source.wantedLevel = 0 end -- Nametag if (wp > 0) then source.nametagText = "["..tostring(source.wantedLevel).."] "..tostring(source.name) else source.nametagText = source.name end if (wp > 0) then if (source.team.name == "Law") then exports.UCDjobs:setPlayerJob(source, "Criminal") end end end addEvent("onPlayerWPChange") addEventHandler("onPlayerWPChange", root, onPlayerWPChange)
UCDwanted
UCDwanted - Fixed a case where wanted points would return as false or nil when logged in
Lua
mit
nokizorque/ucd,nokizorque/ucd
887823f1a3bfabbd75a84640a5c8d5a992426179
xmake/platforms/checker.lua
xmake/platforms/checker.lua
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file checker.lua -- -- imports import("core.base.option") import("detect.sdks.find_xcode_dir") import("detect.sdks.find_xcode_sdkvers") import("lib.detect.find_tool") -- find the given tool function _toolchain_check(config, toolkind, toolinfo) -- get the program local program = config.get(toolkind) if not program then -- get name and attempt to get `$(env XX)` local name = vformat(toolinfo.name) if #name == 0 then return end -- get cross local cross = toolinfo.cross or "" -- attempt to check it if not program then local tool = find_tool(name, {program = cross .. name, pathes = config.get("toolchains"), check = toolinfo.check}) if tool then program = tool.program end end -- check ok? if program then config.set(toolkind, program) end -- trace if option.get("verbose") then if program then cprint("checking for %s (%s) ... ${green}%s", toolinfo.description, toolkind, path.filename(program)) else cprint("checking for %s (%s: ${red}%s${clear}) ... ${red}no", toolinfo.description, toolkind, name) end end end -- ok? return program end -- check all for the given config kind function check(kind, checkers) -- init config name local confignames = {config = "core.project.config", global = "core.base.global"} -- import config module local config = import(confignames[kind]) -- check all for _, checker in ipairs(checkers[kind]) do -- has arguments? local args = {} if type(checker) == "table" then for idx, arg in ipairs(checker) do if idx == 1 then checker = arg else table.insert(args, arg) end end end -- check it checker(config, unpack(args)) end end -- check the architecture function check_arch(config, default) -- get the architecture local arch = config.get("arch") if not arch then -- init the default architecture config.set("arch", default or os.arch()) -- trace cprint("checking for the architecture ... ${green}%s", config.get("arch")) end end -- check the xcode application directory function check_xcode_dir(config) -- get the xcode directory local xcode_dir = config.get("xcode_dir") if not xcode_dir then -- check ok? update it xcode_dir = find_xcode_dir() if xcode_dir then -- save it config.set("xcode_dir", xcode_dir) -- trace cprint("checking for the Xcode application directory ... ${green}%s", xcode_dir) else -- failed cprint("checking for the Xcode application directory ... ${red}no") cprint("${bright red}please run:") cprint("${red} - xmake config --xcode_dir=xxx") cprint("${red}or - xmake global --xcode_dir=xxx") raise() end end end -- check the xcode sdk version function check_xcode_sdkver(config) -- get the xcode sdk version local xcode_sdkver = config.get("xcode_sdkver") if not xcode_sdkver then -- check ok? update it xcode_sdkver = find_xcode_sdkvers({xcode_dir = config.get("xcode_dir"), plat = config.get("plat"), arch = config.get("arch")})[1] if xcode_sdkver then -- save it config.set("xcode_sdkver", xcode_sdkver) -- trace cprint("checking for the Xcode SDK version for %s ... ${green}%s", config.get("plat"), xcode_sdkver) else -- failed cprint("checking for the Xcode SDK version for %s ... ${red}no", config.get("plat")) cprint("${bright red}please run:") cprint("${red} - xmake config --xcode_sdkver=xxx") cprint("${red}or - xmake global --xcode_sdkver=xxx") raise() end end -- get target minver local target_minver = config.get("target_minver") if not target_minver then config.set("target_minver", xcode_sdkver) end end -- insert toolchain function toolchain_insert(toolchains, toolkind, cross, name, description, check) -- insert to the given toolchain toolchains[toolkind] = toolchains[toolkind] or {} table.insert(toolchains[toolkind], {cross = cross, name = name, description = description, check = check}) end -- check the toolchain function toolchain_check(kind, toolkind, toolchains) -- init config name local confignames = {config = "core.project.config", global = "core.base.global"} -- import config module local config = import(confignames[kind]) -- load toolchains if be function if type(toolchains) == "function" then toolchains = toolchains(config) end -- check this toolchain for _, toolinfo in ipairs(toolchains[toolkind]) do if _toolchain_check(config, toolkind, toolinfo) then break end end -- save config config.save() end
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file checker.lua -- -- imports import("core.base.option") import("detect.sdks.find_xcode_dir") import("detect.sdks.find_xcode_sdkvers") import("lib.detect.find_tool") -- find the given tool function _toolchain_check(config, toolkind, toolinfo) -- get the program local program = config.get(toolkind) if not program then -- get name and attempt to get `$(env XX)` local name = vformat(toolinfo.name) if #name == 0 then return end -- get cross local cross = toolinfo.cross or "" -- attempt to check it if not program then local tool = find_tool(name, {program = cross .. name, pathes = config.get("toolchains"), check = toolinfo.check}) if tool then program = tool.program end end -- check ok? if program then config.set(toolkind, program) end -- trace if option.get("verbose") then if program then cprint("checking for %s (%s) ... ${green}%s", toolinfo.description, toolkind, path.filename(program)) else cprint("checking for %s (%s: ${red}%s${clear}) ... ${red}no", toolinfo.description, toolkind, name) end end end -- ok? return program end -- check all for the given config kind function check(kind, checkers) -- init config name local confignames = {config = "core.project.config", global = "core.base.global"} -- import config module local config = import(confignames[kind]) -- check all for _, checker in ipairs(checkers[kind]) do -- has arguments? local args = {} if type(checker) == "table" then for idx, arg in ipairs(checker) do if idx == 1 then checker = arg else table.insert(args, arg) end end end -- check it checker(config, unpack(args)) end end -- check the architecture function check_arch(config, default) -- get the architecture local arch = config.get("arch") if not arch then -- init the default architecture config.set("arch", default or os.arch()) -- trace cprint("checking for the architecture ... ${green}%s", config.get("arch")) end end -- check the xcode application directory function check_xcode_dir(config) -- get the xcode directory local xcode_dir = config.get("xcode_dir") if not xcode_dir then -- check ok? update it xcode_dir = find_xcode_dir() if xcode_dir then -- save it config.set("xcode_dir", xcode_dir) -- trace cprint("checking for the Xcode application directory ... ${green}%s", xcode_dir) else -- failed cprint("checking for the Xcode application directory ... ${red}no") cprint("${bright red}please run:") cprint("${red} - xmake config --xcode_dir=xxx") cprint("${red}or - xmake global --xcode_dir=xxx") raise() end end end -- check the xcode sdk version function check_xcode_sdkver(config) -- get the xcode sdk version local xcode_sdkver = config.get("xcode_sdkver") if not xcode_sdkver then -- check ok? update it xcode_sdkver = find_xcode_sdkvers({xcode_dir = config.get("xcode_dir"), plat = config.get("plat"), arch = config.get("arch")})[1] if xcode_sdkver then -- save it config.set("xcode_sdkver", xcode_sdkver) -- trace cprint("checking for the Xcode SDK version for %s ... ${green}%s", config.get("plat"), xcode_sdkver) else -- failed cprint("checking for the Xcode SDK version for %s ... ${red}no", config.get("plat")) cprint("${bright red}please run:") cprint("${red} - xmake config --xcode_sdkver=xxx") cprint("${red}or - xmake global --xcode_sdkver=xxx") raise() end end -- get target minver local target_minver = config.get("target_minver") if not target_minver then config.set("target_minver", xcode_sdkver) end end -- insert toolchain function toolchain_insert(toolchains, toolkind, cross, name, description, check) -- insert to the given toolchain toolchains[toolkind] = toolchains[toolkind] or {} table.insert(toolchains[toolkind], {cross = cross, name = name, description = description, check = check}) end -- check the toolchain function toolchain_check(config_or_kind, toolkind, toolchains) -- init config name local confignames = {config = "core.project.config", global = "core.base.global"} -- import config module local config = config_or_kind if type(config_or_kind) == "string" then config = import(confignames[config_or_kind]) end -- load toolchains if be function if type(toolchains) == "function" then toolchains = toolchains(config) end -- check this toolchain for _, toolinfo in ipairs(toolchains[toolkind]) do if _toolchain_check(config, toolkind, toolinfo) then break end end -- save config config.save() end
fix check toolchain for android platform
fix check toolchain for android platform
Lua
apache-2.0
waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake
5635fb0365eec5a02d9037c1c2b0070b10eecae5
protocol_memcached/test_client_ascii.lua
protocol_memcached/test_client_ascii.lua
require('protocol_memcached/test_base') require('protocol_memcached/client') client = memcached_client_ascii ------------------------------------------ location = arg[1] or '127.0.0.1:11211' host, port, c = connect(location) c:settimeout(nil) ------------------------------------------ p("connected", host, port, c) fresh() assert(client.flush_all(c, got) == "OK") expected("OK") fresh() assert(client.get(c, got, {keys = {"a", "b", "c"}}) == "END") expected() fresh() assert(client.set(c, got, {key = "a", data = "hello"}) == "STORED") expected("STORED") fresh() assert(client.get(c, got, {keys = {"a"}}) == "END") expected({"VALUE a", {data = "hello"}}) fresh() assert(client.get(c, got, {keys = {"a", "b", "c"}}) == "END") expected({"VALUE a", {data = "hello"}}) fresh() assert(client.set(c, got, {key = "b", flag = 0, expire = 0, data = "world"}) == "STORED") expected("STORED") fresh() assert(client.get(c, got, {keys = {"a", "b", "c"}}) == "END") expected({"VALUE a", {data = "hello"}}, {"VALUE b", {data = "world"}}) fresh() assert(client.get(c, got, {keys = {"a", "b", "c", "a", "b", "c"}}) == "END") expected({"VALUE a", {data = "hello"}}, {"VALUE b", {data = "world"}}, {"VALUE a", {data = "hello"}}, {"VALUE b", {data = "world"}}) fresh() assert(client.delete(c, got, {key = "b"}) == "DELETED") expected("DELETED") fresh() assert(client.get(c, got, {keys = {"a", "b", "c"}}) == "END") expected({"VALUE a", {data = "hello"}}) fresh() assert(client.flush_all(c, got) == "OK") expected("OK") fresh() assert(client.get(c, got, {keys = {"a", "b", "c"}}) == "END") expected() fresh() assert(client.delete(c, got, {key = "a"}) == "DELETED") expected("DELETED") --fresh() --assert(client.set(c, got, {key = "a", -- data = "1"}) == "STORED") --expected("STORED") -- --fresh() --assert(client.incr(c, got, {key = "a", -- data = "1"}) == "2") --expected("2") -- --fresh() --assert(client.incr(c, got, {key = "a", -- data = "10"}) == "12") --expected("12") -- --fresh() --assert(client.decr(c, got, {key = "a", -- data = "1"}) == "11") --expected("11") -- --fresh() --assert(client.decr(c, got, {key = "a", -- data = "10"}) == "1") --expected("1") -- --fresh() --assert(client.incr(c, got, {key = "a" }) == "2") --expected("2") -- --fresh() --assert(client.decr(c, got, {key = "a" }) == "1") --expected("1") -- --p("done!")
require('protocol_memcached/test_base') require('protocol_memcached/client') client = memcached_client_ascii ------------------------------------------ location = arg[1] or '127.0.0.1:11211' host, port, c = connect(location) c:settimeout(nil) ------------------------------------------ p("connected", host, port, c) fresh() assert(client.flush_all(c, got) == "OK") expected("OK") fresh() assert(client.get(c, got, {keys = {"a", "b", "c"}}) == "END") expected() fresh() assert(client.set(c, got, {key = "a", data = "hello"}) == "STORED") expected("STORED") fresh() assert(client.get(c, got, {keys = {"a"}}) == "END") expected({"VALUE a", {data = "hello"}}) fresh() assert(client.get(c, got, {keys = {"a", "b", "c"}}) == "END") expected({"VALUE a", {data = "hello"}}) fresh() assert(client.set(c, got, {key = "b", flag = 0, expire = 0, data = "world"}) == "STORED") expected("STORED") fresh() assert(client.get(c, got, {keys = {"a", "b", "c"}}) == "END") expected({"VALUE a", {data = "hello"}}, {"VALUE b", {data = "world"}}) fresh() assert(client.get(c, got, {keys = {"a", "b", "c", "a", "b", "c"}}) == "END") expected({"VALUE a", {data = "hello"}}, {"VALUE b", {data = "world"}}, {"VALUE a", {data = "hello"}}, {"VALUE b", {data = "world"}}) fresh() assert(client.delete(c, got, {key = "b"}) == "DELETED") expected("DELETED") fresh() assert(client.get(c, got, {keys = {"a", "b", "c"}}) == "END") expected({"VALUE a", {data = "hello"}}) fresh() assert(client.flush_all(c, got) == "OK") expected("OK") fresh() assert(client.get(c, got, {keys = {"a", "b", "c"}}) == "END") expected() fresh() assert(client.set(c, got, {key = "a", data = "1"}) == "STORED") expected("STORED") fresh() assert(client.incr(c, got, {key = "a", amount = "1"}) == "2") expected("2") fresh() assert(client.incr(c, got, {key = "a", amount = "10"}) == "12") expected("12") fresh() assert(client.decr(c, got, {key = "a", amount = "1"}) == "11") expected("11") fresh() assert(client.decr(c, got, {key = "a", amount = "10"}) == "1") expected("1") fresh() assert(client.incr(c, got, {key = "a" , amount = "1"}) == "2") expected("2") fresh() assert(client.decr(c, got, {key = "a" , amount = "1"}) == "1") expected("1") p("done!")
Fixes to the client test. Need to figure out how to not pass 'amount' without it failing. How does one make an argument optional in lua?
Fixes to the client test. Need to figure out how to not pass 'amount' without it failing. How does one make an argument optional in lua?
Lua
apache-2.0
steveyen/moxilua
17db9b1860b555ef67cdb81f3400856ffe849f5b
lua/types.lua
lua/types.lua
local utils = require('utils') local M = {} -- type functions function M._sequential_Q(obj) return M._list_Q(obj) or M._vector_Q(obj) end function M._equal_Q(a,b) if M._symbol_Q(a) and M._symbol_Q(b) then return a.val == b.val elseif M._sequential_Q(a) and M._sequential_Q(b) then if #a ~= #b then return false end for i, v in ipairs(a) do if not M._equal_Q(v,b[i]) then return false end end return true else return a == b end end function M.copy(obj) if type(obj) == "function" then return M.FunctionRef:new(obj) end if type(obj) ~= "table" then return obj end -- copy object data local new_obj = {} for k,v in pairs(obj) do new_obj[k] = v end -- copy metatable and link to original local old_mt = getmetatable(obj) if old_mt ~= nil then local new_mt = {} for k,v in pairs(old_mt) do new_mt[k] = v end setmetatable(new_mt, old_mt) setmetatable(new_obj, new_mt) end return new_obj end function M.slice(lst, start, last) if last == nil then last = #lst end local new_lst = {} if start <= last then for i = start, last do new_lst[#new_lst+1] = lst[i] end end return new_lst end -- Error/exceptions M.MalException = {} function M.MalException:new(val) local newObj = {val = val} self.__index = self return setmetatable(newObj, self) end function M._malexception_Q(obj) return utils.instanceOf(obj, M.MalException) end function M.throw(val) error(M.MalException:new(val)) end -- Nil local NilType = {} function NilType:new(val) local newObj = {} self.__index = self return setmetatable(newObj, self) end M.Nil = NilType:new() function M._nil_Q(obj) return obj == Nil end -- Strings function M._string_Q(obj) return type(obj) == "string" end -- Symbols M.Symbol = {} function M.Symbol:new(val) local newObj = {val = val} self.__index = self return setmetatable(newObj, self) end function M._symbol_Q(obj) return utils.instanceOf(obj, M.Symbol) end -- Keywords function M._keyword_Q(obj) return M._string_Q(obj) and "\177" == string.sub(obj,1,1) end -- Lists M.List = {} function M.List:new(lst) local newObj = lst and lst or {} self.__index = self return setmetatable(newObj, self) end function M._list_Q(obj) return utils.instanceOf(obj, M.List) end function M.List:slice(start,last) return M.List:new(M.slice(self,start,last)) end -- Vectors M.Vector = {} function M.Vector:new(lst) local newObj = lst and lst or {} self.__index = self return setmetatable(newObj, self) end function M._vector_Q(obj) return utils.instanceOf(obj, M.Vector) end function M.Vector:slice(start,last) return M.Vector:new(M.slice(self,start,last)) end -- Hash Maps -- M.HashMap = {} function M.HashMap:new(val) local newObj = val and val or {} self.__index = self return setmetatable(newObj, self) end function M.hash_map(...) return M._assoc_BANG(M.HashMap:new(), unpack(arg)) end function M._hash_map_Q(obj) return utils.instanceOf(obj, M.HashMap) end function M._assoc_BANG(hm, ...) for i = 1, #arg, 2 do hm[arg[i]] = arg[i+1] end return hm end function M._dissoc_BANG(hm, ...) for i = 1, #arg do hm[arg[i]] = nil end return hm end -- Functions M.MalFunc = {} function M.MalFunc:new(fn, ast, env, params) local newObj = {fn = fn, ast = ast, env = env, params = params, ismacro = false} self.__index = self return setmetatable(newObj, self) end function M._malfunc_Q(obj) return utils.instanceOf(obj, M.MalFunc) end -- Atoms M.Atom = {} function M.Atom:new(val) local newObj = {val = val} self.__index = self return setmetatable(newObj, self) end function M._atom_Q(obj) return utils.instanceOf(obj, M.Atom) end -- FunctionRefs M.FunctionRef = {} function M.FunctionRef:new(fn) local newObj = {fn = fn} return setmetatable(newObj, self) end function M._functionref_Q(obj) return utils.instanceOf(obj, M.FunctionRef) end function M.FunctionRef:__call(...) return self.fn(...) end return M
local utils = require('utils') local M = {} -- type functions function M._sequential_Q(obj) return M._list_Q(obj) or M._vector_Q(obj) end function M._equal_Q(a,b) if M._symbol_Q(a) and M._symbol_Q(b) then return a.val == b.val elseif M._sequential_Q(a) and M._sequential_Q(b) then if #a ~= #b then return false end for i, v in ipairs(a) do if not M._equal_Q(v,b[i]) then return false end end return true elseif M._hash_map_Q(a) and M._hash_map_Q(b) then if #a ~= #b then return false end for k, v in pairs(a) do if not M._equal_Q(v,b[k]) then return false end end return true else return a == b end end function M.copy(obj) if type(obj) == "function" then return M.FunctionRef:new(obj) end if type(obj) ~= "table" then return obj end -- copy object data local new_obj = {} for k,v in pairs(obj) do new_obj[k] = v end -- copy metatable and link to original local old_mt = getmetatable(obj) if old_mt ~= nil then local new_mt = {} for k,v in pairs(old_mt) do new_mt[k] = v end setmetatable(new_mt, old_mt) setmetatable(new_obj, new_mt) end return new_obj end function M.slice(lst, start, last) if last == nil then last = #lst end local new_lst = {} if start <= last then for i = start, last do new_lst[#new_lst+1] = lst[i] end end return new_lst end -- Error/exceptions M.MalException = {} function M.MalException:new(val) local newObj = {val = val} self.__index = self return setmetatable(newObj, self) end function M._malexception_Q(obj) return utils.instanceOf(obj, M.MalException) end function M.throw(val) error(M.MalException:new(val)) end -- Nil local NilType = {} function NilType:new(val) local newObj = {} self.__index = self return setmetatable(newObj, self) end M.Nil = NilType:new() function M._nil_Q(obj) return obj == Nil end -- Strings function M._string_Q(obj) return type(obj) == "string" end -- Symbols M.Symbol = {} function M.Symbol:new(val) local newObj = {val = val} self.__index = self return setmetatable(newObj, self) end function M._symbol_Q(obj) return utils.instanceOf(obj, M.Symbol) end -- Keywords function M._keyword_Q(obj) return M._string_Q(obj) and "\177" == string.sub(obj,1,1) end -- Lists M.List = {} function M.List:new(lst) local newObj = lst and lst or {} self.__index = self return setmetatable(newObj, self) end function M._list_Q(obj) return utils.instanceOf(obj, M.List) end function M.List:slice(start,last) return M.List:new(M.slice(self,start,last)) end -- Vectors M.Vector = {} function M.Vector:new(lst) local newObj = lst and lst or {} self.__index = self return setmetatable(newObj, self) end function M._vector_Q(obj) return utils.instanceOf(obj, M.Vector) end function M.Vector:slice(start,last) return M.Vector:new(M.slice(self,start,last)) end -- Hash Maps -- M.HashMap = {} function M.HashMap:new(val) local newObj = val and val or {} self.__index = self return setmetatable(newObj, self) end function M.hash_map(...) return M._assoc_BANG(M.HashMap:new(), unpack(arg)) end function M._hash_map_Q(obj) return utils.instanceOf(obj, M.HashMap) end function M._assoc_BANG(hm, ...) for i = 1, #arg, 2 do hm[arg[i]] = arg[i+1] end return hm end function M._dissoc_BANG(hm, ...) for i = 1, #arg do hm[arg[i]] = nil end return hm end -- Functions M.MalFunc = {} function M.MalFunc:new(fn, ast, env, params) local newObj = {fn = fn, ast = ast, env = env, params = params, ismacro = false} self.__index = self return setmetatable(newObj, self) end function M._malfunc_Q(obj) return utils.instanceOf(obj, M.MalFunc) end -- Atoms M.Atom = {} function M.Atom:new(val) local newObj = {val = val} self.__index = self return setmetatable(newObj, self) end function M._atom_Q(obj) return utils.instanceOf(obj, M.Atom) end -- FunctionRefs M.FunctionRef = {} function M.FunctionRef:new(fn) local newObj = {fn = fn} return setmetatable(newObj, self) end function M._functionref_Q(obj) return utils.instanceOf(obj, M.FunctionRef) end function M.FunctionRef:__call(...) return self.fn(...) end return M
lua: fix hash-map equality
lua: fix hash-map equality
Lua
mpl-2.0
0gajun/mal,jwalsh/mal,sleep/mal,hterkelsen/mal,jwalsh/mal,sleexyz/mal,0gajun/mal,tompko/mal,sleexyz/mal,h3rald/mal,SawyerHood/mal,sleexyz/mal,alantsev/mal,DomBlack/mal,sleexyz/mal,jwalsh/mal,alantsev/mal,foresterre/mal,0gajun/mal,alantsev/mal,h3rald/mal,h3rald/mal,sleep/mal,jwalsh/mal,tompko/mal,sleexyz/mal,h3rald/mal,0gajun/mal,tompko/mal,SawyerHood/mal,SawyerHood/mal,alantsev/mal,DomBlack/mal,tompko/mal,hterkelsen/mal,h3rald/mal,sleexyz/mal,foresterre/mal,jwalsh/mal,martinlschumann/mal,sleep/mal,alantsev/mal,SawyerHood/mal,SawyerHood/mal,sleexyz/mal,sleexyz/mal,hterkelsen/mal,h3rald/mal,martinlschumann/mal,sleep/mal,hterkelsen/mal,h3rald/mal,mpwillson/mal,0gajun/mal,alantsev/mal,martinlschumann/mal,DomBlack/mal,martinlschumann/mal,DomBlack/mal,martinlschumann/mal,0gajun/mal,mpwillson/mal,0gajun/mal,SawyerHood/mal,foresterre/mal,alantsev/mal,DomBlack/mal,alantsev/mal,DomBlack/mal,sleep/mal,alantsev/mal,hterkelsen/mal,foresterre/mal,SawyerHood/mal,hterkelsen/mal,joncol/mal,sleexyz/mal,0gajun/mal,jwalsh/mal,hterkelsen/mal,0gajun/mal,DomBlack/mal,martinlschumann/mal,hterkelsen/mal,hterkelsen/mal,sleep/mal,DomBlack/mal,0gajun/mal,DomBlack/mal,0gajun/mal,mpwillson/mal,tompko/mal,mpwillson/mal,martinlschumann/mal,SawyerHood/mal,0gajun/mal,tompko/mal,hterkelsen/mal,jwalsh/mal,h3rald/mal,martinlschumann/mal,jwalsh/mal,hterkelsen/mal,0gajun/mal,martinlschumann/mal,0gajun/mal,SawyerHood/mal,mpwillson/mal,SawyerHood/mal,foresterre/mal,martinlschumann/mal,hterkelsen/mal,martinlschumann/mal,DomBlack/mal,hterkelsen/mal,mpwillson/mal,sleep/mal,h3rald/mal,alantsev/mal,hterkelsen/mal,foresterre/mal,SawyerHood/mal,mpwillson/mal,DomBlack/mal,jwalsh/mal,mpwillson/mal,h3rald/mal,sleexyz/mal,DomBlack/mal,alantsev/mal,sleep/mal,martinlschumann/mal,alantsev/mal,sleexyz/mal,alantsev/mal,DomBlack/mal,hterkelsen/mal,tompko/mal,DomBlack/mal,foresterre/mal,foresterre/mal,tompko/mal,h3rald/mal,0gajun/mal,martinlschumann/mal,sleep/mal,martinlschumann/mal,SawyerHood/mal,jwalsh/mal,sleexyz/mal,SawyerHood/mal,h3rald/mal,martinlschumann/mal,foresterre/mal,mpwillson/mal,martinlschumann/mal,martinlschumann/mal,foresterre/mal,foresterre/mal,sleexyz/mal,tompko/mal,hterkelsen/mal,DomBlack/mal,sleexyz/mal,hterkelsen/mal,jwalsh/mal,SawyerHood/mal,h3rald/mal,foresterre/mal,tompko/mal,jwalsh/mal,0gajun/mal,tompko/mal,mpwillson/mal,joncol/mal,mpwillson/mal,0gajun/mal,h3rald/mal,h3rald/mal,sleep/mal,hterkelsen/mal,foresterre/mal,DomBlack/mal,sleep/mal,mpwillson/mal,0gajun/mal,sleep/mal,0gajun/mal,sleexyz/mal,tompko/mal,0gajun/mal,hterkelsen/mal,DomBlack/mal,alantsev/mal,tompko/mal,foresterre/mal,alantsev/mal,DomBlack/mal,joncol/mal,SawyerHood/mal,jwalsh/mal,foresterre/mal,tompko/mal,sleep/mal,SawyerHood/mal,SawyerHood/mal,DomBlack/mal,sleexyz/mal,alantsev/mal,mpwillson/mal,sleexyz/mal,sleep/mal,jwalsh/mal,DomBlack/mal,sleep/mal,foresterre/mal,jwalsh/mal,mpwillson/mal,tompko/mal,alantsev/mal,h3rald/mal,jwalsh/mal,sleep/mal,sleep/mal,SawyerHood/mal,DomBlack/mal,h3rald/mal,jwalsh/mal,tompko/mal,foresterre/mal,tompko/mal
4aff968116e15e8531d6f33aed5080aec1bf5f0b
tools/lua/epbin.lua
tools/lua/epbin.lua
local bit32 = require "bit32" local ppm = require "ppm" local epconv = require "epconv" local lzma = require "lzma" local pvr = require "pvr" local ktx = require "ktx" local model, filename, compress = ... local max_id = 0 local export = 0 local pic = {} local ani = {} local tex = 0 local memfile = { result = {} } function memfile:write(str) table.insert(self.result, str) end local function picture(tbl) table.insert(pic, tbl) end local function animation(tbl) table.insert(ani, tbl) end local function texture(n) tex = n end f = assert(loadfile (filename , "t", { picture = picture , animation = animation , texture = texture })) f() local ANIMATION = 0 local PICTURE = 1 local CLIPUI = 2 local TEXTURE4 = 0 local TEXTURE8 = 1 local DATA = 2 local PVRTC = 3 local KTX = 4 local COMPONENT = 0 local SWITCH = 1 local LABEL = 2 local MOUNT = 3 local FID = 0 local FCOLOR = 1 local FMAT = 2 local FCLIP = 4 local function wstring(f,s) if s == nil then f:write(string.char(255)) else assert (#s < 255) f:write(string.char(#s)) f:write(s) end end local function wchar(f,c) f:write(string.char(c)) end local function wshort(f,c) assert(c> -0x8000 and c < 0x8000) f:write(string.char(bit32.extract(c,0,8),bit32.extract(c,8,8))) end local function wlong(f,c) f:write(string.char(bit32.extract(c,0,8),bit32.extract(c,8,8),bit32.extract(c,16,8),bit32.extract(c,24,8))) end local function wpicture(f, t) wchar(f,PICTURE) wshort(f,t.id) wshort(f,#t) for _,v in ipairs(t) do wchar(f,v.tex) for _,v in ipairs(v.src) do wshort(f,v) end for _,v in ipairs(v.screen) do wlong(f,v) end end end local function wmat(f,mat) for _,v in ipairs(mat) do wlong(f, v) end end local function waction(f,ani,t) local ncomp = #ani.component local ani_id = assert(ani.id) wstring(f, t.action) wshort(f, #t) for _,frame in ipairs(t) do wshort(f,#frame) for _,v in ipairs(frame) do if type(v) == "number" then assert(0 <= v and (v % 1) == 0 and v < ncomp, ani_id) wchar(f, FID) wshort(f, v) else local i = v.index assert(0 <= i and (i % 1) == 0 and i < ncomp, ani_id) if v.mat then assert(not (v.scale or v.trans)) elseif v.scale or v.trans then local m = {1024,0,0,1024,0,0} if v.scale then local sx, sy = v.scale[1], v.scale[2] m[1] = m[1] * sx m[2] = m[2] * sy m[3] = m[3] * sx m[4] = m[4] * sy m[5] = m[5] * sx m[6] = m[6] * sy end if v.trans then local tx, ty = v.trans[1], v.trans[2] m[5] = m[5] + tx m[6] = m[6] + ty end v.mat = m end local type = FID if v.clip then type = type + FCLIP end if v.color then type = type + FCOLOR end if v.mat then type = type + FMAT end wchar(f, type) wshort(f, i) if v.color then wlong(f, v.color) wlong(f, v.add) end if v.mat then wmat(f, v.mat) end end end end end local function wlabel(f,v) wstring(f,v.name) wstring(f,v.font) wlong(f, v.color) wchar(f, v.size) wchar(f, v.align) wshort(f, v.width) wshort(f, v.height) end local function wanimation(f,t) assert(t.id) if #t.component == 0 then print(t.export , t.id, "is empty") end if t.clipbox then wchar(f, CLIPUI) wshort(f,t.id) wlong(f, t.clipbox[1]) wlong(f, t.clipbox[2]) wlong(f, t.clipbox[3]) wlong(f, t.clipbox[4]) else wchar(f, ANIMATION) wshort(f,t.id) end wstring(f,t.export) -- component wshort(f,#t.component) for _,v in ipairs(t.component) do if v.id == nil then if v.font then wchar(f,LABEL) wlabel(f,v) elseif v.name then wchar(f, MOUNT) wstring(f, v.name) end elseif v.name then wchar(f,SWITCH) wshort(f, v.id) wstring(f, v.name) else wchar(f, COMPONENT) wshort(f, v.id) end end -- action wshort(f,#t) for _,v in ipairs(t) do waction(f,t,v) end end local function check_id(v) if v.id > max_id then max_id = v.id end if v.export then export = export + 1 end end --- detail local function detail() memfile.result = {} local f = memfile for _,v in pairs(pic) do check_id(v) wpicture(f, v) end for _,v in pairs(ani) do check_id(v) wanimation(f,v); end wshort(f,max_id) wshort(f,export) local data = table.concat(f.result) local sz = epconv(data) f.result = {} wchar(f,DATA) wlong(f,sz) table.insert(f.result, data) return table.concat(f.result) end local function load_pvr(filename) memfile.result = {} local w,h,internal_format,data_table = pvr.load(filename..".pvr") print("Gen pvr image",w,h,internal_format) wchar(memfile, PVRTC) assert(internal_format == 4 or internal_format == 2) wchar(memfile, internal_format) wshort(memfile, w) wshort(memfile, h) for i=1,#data_table do wlong(memfile, string.len(data_table[i])) table.insert(memfile.result, data_table[i]) end return table.concat(memfile.result) end local function load_ktx(filename) print("load_ktx :" .. filename..".ktx") memfile.reault = {} local w,h,data = ktx.read(filename..".ktx") print("Gen ktx image",w,h) wchar(memfile, KTX) wchar(memfile, w) wchar(memfile, h) table.insert(memfile.result, data) return table.concat(memfile.result) end local function _load(filename, func) memfile.result = {} local w,h,depth,data = func(filename) print("Gen image",w,h,depth) if depth == 15 then wchar(memfile, TEXTURE4) elseif depth == 255 then wchar(memfile, TEXTURE8) else error("Unsupport depth", depth) end wshort(memfile, w) wshort(memfile, h) table.insert(memfile.result, data) return table.concat(memfile.result) end local function load_png(filename) local png = require "png" return _load(filename..".png", function (name) return png.read(name, model) end) end local function load_ppm(filename) return _load(filename, ppm) end local write_block if compress == "0" then function write_block(f, t) wlong(f, -#t) f:write(t) end else function write_block(f, t) local c = lzma.compress(t) wlong(f, #c) f:write(c) end end filename = string.match(filename, "(.*)%..*$") local f = io.open(filename .. ".ep", "wb") local gm_filename, gm_load = nil, nil if model == "-ppm" then gm_load = load_ppm gm_filename = filename.."." elseif model =="-png8" or model=="-png4" then gm_load = load_png gm_filename = filename elseif model =="-pvr" then gm_load = load_pvr gm_filename = filename elseif model == "-ktx" then gm_load = load_ktx gm_filename = filename else error("not match ppm or png model.") end for i = 1,tex do local t = gm_load(gm_filename..tostring(i)) write_block(f, t) end write_block(f, detail()) f:close()
local bit32 = require "bit32" local ppm = require "ppm" local epconv = require "epconv" local lzma = require "lzma" local pvr = require "pvr" local ktx = require "ktx" local model, filename, compress = ... local max_id = 0 local export = 0 local pic = {} local ani = {} local tex = 0 local memfile = { result = {} } function memfile:write(str) table.insert(self.result, str) end local function picture(tbl) table.insert(pic, tbl) end local function animation(tbl) table.insert(ani, tbl) end local function texture(n) tex = n end f = assert(loadfile (filename , "t", { picture = picture , animation = animation , texture = texture })) f() local ANIMATION = 0 local PICTURE = 1 local CLIPUI = 2 local TEXTURE4 = 0 local TEXTURE8 = 1 local DATA = 2 local PVRTC = 3 local KTX = 4 local COMPONENT = 0 local SWITCH = 1 local LABEL = 2 local MOUNT = 3 local FID = 0 local FCOLOR = 1 local FMAT = 2 local FCLIP = 4 local function wstring(f,s) if s == nil then f:write(string.char(255)) else assert (#s < 255) f:write(string.char(#s)) f:write(s) end end local function wchar(f,c) f:write(string.char(c)) end local function wshort(f,c) assert(c> -0x8000 and c < 0x8000) f:write(string.char(bit32.extract(c,0,8),bit32.extract(c,8,8))) end local function wlong(f,c) f:write(string.char(bit32.extract(c,0,8),bit32.extract(c,8,8),bit32.extract(c,16,8),bit32.extract(c,24,8))) end local function wpicture(f, t) wchar(f,PICTURE) wshort(f,t.id) wshort(f,#t) for _,v in ipairs(t) do wchar(f,v.tex) for _,v in ipairs(v.src) do wshort(f,v) end for _,v in ipairs(v.screen) do wlong(f,v) end end end local function wmat(f,mat) for _,v in ipairs(mat) do wlong(f, v) end end local function waction(f,ani,t) local ncomp = #ani.component local ani_id = assert(ani.id) wstring(f, t.action) wshort(f, #t) for _,frame in ipairs(t) do wshort(f,#frame) for _,v in ipairs(frame) do if type(v) == "number" then assert(0 <= v and (v % 1) == 0 and v < ncomp, ani_id) wchar(f, FID) wshort(f, v) else local i = v.index assert(0 <= i and (i % 1) == 0 and i < ncomp, ani_id) if v.mat then assert(not (v.scale or v.trans)) elseif v.scale or v.trans then local m = {1024,0,0,1024,0,0} if v.scale then local sx, sy = v.scale[1], v.scale[2] m[1] = m[1] * sx m[2] = m[2] * sy m[3] = m[3] * sx m[4] = m[4] * sy m[5] = m[5] * sx m[6] = m[6] * sy end if v.trans then local tx, ty = v.trans[1], v.trans[2] m[5] = m[5] + tx m[6] = m[6] + ty end v.mat = m end local type = FID if v.clip then type = type + FCLIP end if v.color then type = type + FCOLOR end if v.mat then type = type + FMAT end wchar(f, type) wshort(f, i) if v.color then wlong(f, v.color) wlong(f, v.add) end if v.mat then wmat(f, v.mat) end end end end end local function wlabel(f,v) wstring(f,v.name) wstring(f,v.font) wlong(f, v.color) wchar(f, v.size) wchar(f, v.align) wshort(f, v.width) wshort(f, v.height) end local function wanimation(f,t) assert(t.id) if #t.component == 0 then print(t.export , t.id, "is empty") end if t.clipbox then wchar(f, CLIPUI) wshort(f,t.id) wlong(f, t.clipbox[1]) wlong(f, t.clipbox[2]) wlong(f, t.clipbox[3]) wlong(f, t.clipbox[4]) else wchar(f, ANIMATION) wshort(f,t.id) end wstring(f,t.export) -- component wshort(f,#t.component) for _,v in ipairs(t.component) do if v.id == nil then if v.font then wchar(f,LABEL) wlabel(f,v) elseif v.name then wchar(f, MOUNT) wstring(f, v.name) end elseif v.name then wchar(f,SWITCH) wshort(f, v.id) wstring(f, v.name) else wchar(f, COMPONENT) wshort(f, v.id) end end -- action wshort(f,#t) for _,v in ipairs(t) do waction(f,t,v) end end local function check_id(v) if v.id > max_id then max_id = v.id end if v.export then export = export + 1 end end --- detail local function detail() memfile.result = {} local f = memfile for _,v in pairs(pic) do check_id(v) wpicture(f, v) end for _,v in pairs(ani) do check_id(v) wanimation(f,v); end wshort(f,max_id) wshort(f,export) local data = table.concat(f.result) local sz = epconv(data) f.result = {} wchar(f,DATA) wlong(f,sz) table.insert(f.result, data) return table.concat(f.result) end local function load_pvr(filename) memfile.result = {} local w,h,internal_format,data_table = pvr.load(filename..".pvr") print("Gen pvr image",w,h,internal_format) wchar(memfile, PVRTC) assert(internal_format == 4 or internal_format == 2) wchar(memfile, internal_format) wshort(memfile, w) wshort(memfile, h) for i=1,#data_table do wlong(memfile, string.len(data_table[i])) table.insert(memfile.result, data_table[i]) end return table.concat(memfile.result) end local function load_ktx(filename) memfile.result = {} local w,h,size,data = ktx.read(filename..".ktx") print("Gen ktx image",w,h,filename) wchar(memfile, KTX) wshort(memfile, w) wshort(memfile, h) wlong(memfile, size) table.insert(memfile.result, data) return table.concat(memfile.result) end local function _load(filename, func) memfile.result = {} local w,h,depth,data = func(filename) print("Gen image",w,h,depth) if depth == 15 then wchar(memfile, TEXTURE4) elseif depth == 255 then wchar(memfile, TEXTURE8) else error("Unsupport depth", depth) end wshort(memfile, w) wshort(memfile, h) table.insert(memfile.result, data) return table.concat(memfile.result) end local function load_png(filename) local png = require "png" return _load(filename..".png", function (name) return png.read(name, model) end) end local function load_ppm(filename) return _load(filename, ppm) end local write_block if compress == "0" then function write_block(f, t) wlong(f, -#t) f:write(t) end else function write_block(f, t) local c = lzma.compress(t) wlong(f, #c) f:write(c) end end filename = string.match(filename, "(.*)%..*$") local f = io.open(filename .. ".ep", "wb") local gm_filename, gm_load = nil, nil if model == "-ppm" then gm_load = load_ppm gm_filename = filename.."." elseif model =="-png8" or model=="-png4" then gm_load = load_png gm_filename = filename elseif model =="-pvr" then gm_load = load_pvr gm_filename = filename elseif model == "-ktx" then gm_load = load_ktx gm_filename = filename else error("not match ppm or png model.") end for i = 1,tex do local t = gm_load(gm_filename..tostring(i)) write_block(f, t) end write_block(f, detail()) f:close()
fix epbin
fix epbin
Lua
mit
xzrunner/easyeditor,xzrunner/easyeditor
4b277f0f41638e4ab1aa6b1021b1e637f4d9e8f2
packages/pirania/files/usr/lib/lua/voucher/hooks.lua
packages/pirania/files/usr/lib/lua/voucher/hooks.lua
#!/usr/bin/lua local config = require('voucher.config') local fs = require("nixio.fs") local hooks = function(action) local hookPath = config.hooksDir..action..'/' local files = fs.dir(hookPath) or pairs({}) for file in files do os.execute(hookPath..file) end end if debug.getinfo(2).name == nil then arguments = { ... } if (arguments ~= nil and arguments[1] ~= nil) then hooks(arguments[1]) end end return hooks
#!/usr/bin/lua local config = require('voucher.config') local fs = require("nixio.fs") local hooks = function(action) local hookPath = config.hooksDir..action..'/' local files = fs.dir(hookPath) or pairs({}) for file in files do os.execute("(( sh "..hookPath..file.." 0<&- &>/dev/null &) &)") end end if debug.getinfo(2).name == nil then arguments = { ... } if (arguments ~= nil and arguments[1] ~= nil) then hooks(arguments[1]) end end return hooks
fix ubus timeout
fix ubus timeout
Lua
agpl-3.0
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
2d89391cd624d543e4caafb48a6fb56f59f0995a
Sassilization/gamemode/server/game.lua
Sassilization/gamemode/server/game.lua
-------------------- -- Sassilization -- By Sassafrass / Spacetech / LuaPineapple -------------------- util.AddNetworkString( "SetWinners" ) function GM:StartGame() if(self.Started) then return end self.Started = true self.StartTime = tostring(os.time()) --for k,v in pairs(self.Players) do -- v = true --end --PrintTable(self.Players) for k,v in pairs(player.GetAll()) do v:UnLock() v:Spawn() end timer.Create("UpdateResources", 10, 0, function() self:UpdateResources() end ) if(SA.DEV) then return end --timer.Create("UpdateMinimapBuildings", 20, 0, self.UpdateMinimapBuildings, self) --timer.Create("UpdateMinimapUnits", 20, 0, self.UpdateMinimapUnits, self) end function GM:UpdateResources() for _, empire in pairs(empire.GetAll()) do if(empire:GetCities() > 0 or empire:GetFarms() > 0 or (empire:GetCities() == 0 and empire:GetFood() < 50)) then empire:AddFood( empire:GetFoodIncome() ) end if(empire:GetCities() > 0 or empire:GetMines() > 0 or (empire:GetCities() == 0 and empire:GetIron() < 50)) then empire:AddIron( empire:GetIronIncome() ) end empire:AddGold( empire:GetGoldIncome() ) if( IsValid( empire:GetPlayer() ) ) then empire:GetPlayer():SetFrags( empire:GetGold() ) end end self:CheckGame() end function GM:CheckGame() if(SA.DEV) then return end for _, empire1 in pairs(empire.GetAll()) do local Amount = empire1:GetGold() if(Amount >= SA.WIN_LIMIT) then self:EndGame(empire1) return elseif(Amount >= SA.WIN_GOAL_MIN) then local CanWin = true for _, otherEmpire in pairs(empire.GetAll()) do if(empire1 ~= otherEmpire and empire1:GetPlayer() and empire1:GetPlayer().Alliance and otherEmpire:GetPlayer() and otherEmpire:GetPlayer().Alliance and !Allied(empire1, otherEmpire)) then if(Amount - otherEmpire:GetGold() < SA.WIN_LEAD) then CanWin = false break end end end if(CanWin) then self:EndGame( empire1 ) return end end end end function GM:EndGame( empire ) if !gameOver then local randTitle = math.random(1, #Titles) for k,v in pairs(Titles) do if k == randTitle then if empire:GetPlayer() and empire:GetPlayer().Alliance then if #empire:GetPlayer().Alliance == 0 then randTitle = v[1] else randTitle = v[2] end else randTitle = v[1] end end end local randDesc = math.random(1, #Description) for k,v in pairs(Description) do if k == randDesc then if empire:GetPlayer() and empire:GetPlayer().Alliance then if #empire:GetPlayer().Alliance == 0 then randDesc = v[1] else randDesc = v[2] end else randTitle = v[1] end end end local allyTable = {} empire.win = true if empire:GetPlayer() then if empire:GetPlayer().Alliance then allyTable = empire:GetPlayer().Alliance end end for _, pl in pairs( player.GetAll() ) do net.Start("SetWinners") net.WriteString(empire:Nick()) net.WriteTable(allyTable) net.WriteString(randTitle) net.WriteString(randDesc) net.Send(pl) end for k,v in pairs(allyTable) do v:GetEmpire().win = true end gameOver = true self.EndTime = tostring(os.time()) DB_Query("INSERT INTO rts_matches (playerCount, startTimestamp, endTimestamp) VALUES ('"..tostring(#empire.GetAll()).."','"..self.StartTime.."','"..self.EndTime.."')", function(data) DB_Query("SELECT ID FROM rts_matches WHERE endTimestamp='"..self.EndTime.."'", function(data) local gameID = data[1].ID for k,v in pairs(empire.GetAll()) do DB_Query("SELECT ID FROM users WHERE steamId='"..string.sub(v.SteamID, 7).."'", function(data) local playerID = data[1].ID if v.win then DB_Query("INSERT INTO rts_match_players (rtsMatchId, userId, wonMatch) VALUES ('"..tostring(gameID).."','"..tostring(playerID).."','"..tostring(1).."')") else DB_Query("INSERT INTO rts_match_players (rtsMatchId, userId, wonMatch) VALUES ('"..tostring(gameID).."','"..tostring(playerID).."','"..tostring(0).."')") end for i,d in pairs(v.spawns) do DB_Query("INSERT INTO rts_constructions (rtsMatchId, rtsMatchPlayerId, constructionTypeId, amountBuilt) VALUES ('"..tostring(gameID).."','"..tostring(playerID).."','"..tostring(i).."','"..tostring(d).."')") end end) end end) end) timer.Simple(SA.INTERMISSION, function() self:RestartGame(MAPS.GetNextMap()) end) end end util.AddNetworkString("sa.connectlobby") function GM:RestartGame(NextMap) if(SA.DEV) then return end for k,v in pairs(player.GetAll()) do net.Start("sa.connectlobby") net.Send(v) end timer.Simple(5, function() game.ConsoleCommand( "changelevel "..NextMap.."\n" ) end) /* gatekeeper.DropAllClients("Join Lobby to Play Again") local Info = [[RETURNINGPLAYERS:]]..SERVERID..[[|TICKETS = {]] for k,v in pairs(player.GetAll()) do local tid = 0 for _, ticket in pairs( TICKETS ) do if ticket.ip == pl:IPAddress() then tid = ticket.team end end info = info..[[{]] info = info..[[name = "]]..tmysql.escape(string.gsub( pl:GetName(), "|", "" ))..[[",]] info = info..[[ip = "]]..pl:IPAddress()..[[",]] info = info..[[team = ]]..tid if _ == #player.GetAll() then info = info..[[}]] else info = info..[[},]] end v:SendLua("LocalPlayer():ConCommand('connect "..LOBBYIP..":"..LOBBYPORT.."')") end info = info..[[}]] tcpSend(LOBBYIP,DATAPORT,info.."\n") ResetPassword() if not NEXTMAP then NEXTMAP = MAPS.GetNextMap() end if not (NEXTMAP and NEXTMAP ~= "") then NEXTMAP = game.GetMap() end timer.Simple( 1, function( level ) for _, pl in pairs( player.GetAll() ) do game.ConsoleCommand( "kickid "..pl:UserID() ) game.ConsoleCommand( "kickid "..pl:UserID() ) end game.ConsoleCommand( "changelevel "..level.."\n" ) end, NEXTMAP ) */ end
-------------------- -- Sassilization -- By Sassafrass / Spacetech / LuaPineapple -------------------- util.AddNetworkString( "SetWinners" ) function GM:StartGame() if(self.Started) then return end self.Started = true self.StartTime = tostring(os.time()) --for k,v in pairs(self.Players) do -- v = true --end --PrintTable(self.Players) for k,v in pairs(player.GetAll()) do v:UnLock() v:Spawn() end timer.Create("UpdateResources", 10, 0, function() self:UpdateResources() end ) if(SA.DEV) then return end --timer.Create("UpdateMinimapBuildings", 20, 0, self.UpdateMinimapBuildings, self) --timer.Create("UpdateMinimapUnits", 20, 0, self.UpdateMinimapUnits, self) end function GM:UpdateResources() for _, empire in pairs(empire.GetAll()) do if(empire:GetCities() > 0 or empire:GetFarms() > 0 or (empire:GetCities() == 0 and empire:GetFood() < 50)) then empire:AddFood( empire:GetFoodIncome() ) end if(empire:GetCities() > 0 or empire:GetMines() > 0 or (empire:GetCities() == 0 and empire:GetIron() < 50)) then empire:AddIron( empire:GetIronIncome() ) end empire:AddGold( empire:GetGoldIncome() ) if( IsValid( empire:GetPlayer() ) ) then empire:GetPlayer():SetFrags( empire:GetGold() ) end end self:CheckGame() end function GM:CheckGame() if(SA.DEV) then return end for _, empire1 in pairs(empire.GetAll()) do local Amount = empire1:GetGold() if(Amount >= SA.WIN_LIMIT) then self:EndGame(empire1) return elseif(Amount >= SA.WIN_GOAL_MIN) then local CanWin = true for _, otherEmpire in pairs(empire.GetAll()) do if(empire1 ~= otherEmpire and empire1:GetPlayer() and empire1:GetPlayer().Alliance and otherEmpire:GetPlayer() and otherEmpire:GetPlayer().Alliance and !Allied(empire1, otherEmpire)) then if(Amount - otherEmpire:GetGold() < SA.WIN_LEAD) then CanWin = false break end end end if(CanWin) then self:EndGame( empire1 ) return end end end end function GM:EndGame( empireWin ) if !gameOver then local randTitle = math.random(1, #Titles) for k,v in pairs(Titles) do if k == randTitle then if empireWin:GetPlayer() and empireWin:GetPlayer().Alliance then if #empireWin:GetPlayer().Alliance == 0 then randTitle = v[1] else randTitle = v[2] end else randTitle = v[1] end end end local randDesc = math.random(1, #Description) for k,v in pairs(Description) do if k == randDesc then if empireWin:GetPlayer() and empireWin:GetPlayer().Alliance then if #empireWin:GetPlayer().Alliance == 0 then randDesc = v[1] else randDesc = v[2] end else randTitle = v[1] end end end local allyTable = {} empireWin.win = true if empireWin:GetPlayer() then if empireWin:GetPlayer().Alliance then allyTable = empireWin:GetPlayer().Alliance end end for _, pl in pairs( player.GetAll() ) do net.Start("SetWinners") net.WriteString(empireWin:Nick()) net.WriteTable(allyTable) net.WriteString(randTitle) net.WriteString(randDesc) net.Send(pl) end for k,v in pairs(allyTable) do v:GetEmpire().win = true end gameOver = true self.EndTime = tostring(os.time()) DB_Query("INSERT INTO rts_matches (playerCount, startTimestamp, endTimestamp) VALUES ('"..tostring(#empire.GetAll()).."','"..self.StartTime.."','"..self.EndTime.."')", function(data) DB_Query("SELECT ID FROM rts_matches WHERE endTimestamp='"..self.EndTime.."'", function(data) local gameID = data[1].ID for k,v in pairs(empire.GetAll()) do DB_Query("SELECT ID FROM users WHERE steamId='"..string.sub(v.SteamID, 7).."'", function(data) local playerID = data[1].ID if v.win then DB_Query("INSERT INTO rts_match_players (rtsMatchId, userId, wonMatch) VALUES ('"..tostring(gameID).."','"..tostring(playerID).."','"..tostring(1).."')") else DB_Query("INSERT INTO rts_match_players (rtsMatchId, userId, wonMatch) VALUES ('"..tostring(gameID).."','"..tostring(playerID).."','"..tostring(0).."')") end for i,d in pairs(v.spawns) do DB_Query("INSERT INTO rts_constructions (rtsMatchId, rtsMatchPlayerId, constructionTypeId, amountBuilt) VALUES ('"..tostring(gameID).."','"..tostring(playerID).."','"..tostring(i).."','"..tostring(d).."')") end end) end end) end) timer.Simple(SA.INTERMISSION, function() self:RestartGame(MAPS.GetNextMap()) end) end end util.AddNetworkString("sa.connectlobby") function GM:RestartGame(NextMap) if(SA.DEV) then return end for k,v in pairs(player.GetAll()) do net.Start("sa.connectlobby") net.Send(v) end timer.Simple(5, function() game.ConsoleCommand( "changelevel "..NextMap.."\n" ) end) /* gatekeeper.DropAllClients("Join Lobby to Play Again") local Info = [[RETURNINGPLAYERS:]]..SERVERID..[[|TICKETS = {]] for k,v in pairs(player.GetAll()) do local tid = 0 for _, ticket in pairs( TICKETS ) do if ticket.ip == pl:IPAddress() then tid = ticket.team end end info = info..[[{]] info = info..[[name = "]]..tmysql.escape(string.gsub( pl:GetName(), "|", "" ))..[[",]] info = info..[[ip = "]]..pl:IPAddress()..[[",]] info = info..[[team = ]]..tid if _ == #player.GetAll() then info = info..[[}]] else info = info..[[},]] end v:SendLua("LocalPlayer():ConCommand('connect "..LOBBYIP..":"..LOBBYPORT.."')") end info = info..[[}]] tcpSend(LOBBYIP,DATAPORT,info.."\n") ResetPassword() if not NEXTMAP then NEXTMAP = MAPS.GetNextMap() end if not (NEXTMAP and NEXTMAP ~= "") then NEXTMAP = game.GetMap() end timer.Simple( 1, function( level ) for _, pl in pairs( player.GetAll() ) do game.ConsoleCommand( "kickid "..pl:UserID() ) game.ConsoleCommand( "kickid "..pl:UserID() ) end game.ConsoleCommand( "changelevel "..level.."\n" ) end, NEXTMAP ) */ end
Fixed lua error on game end.
Fixed lua error on game end.
Lua
bsd-3-clause
T3hArco/skeyler-gamemodes
93507acfb1105a85e403679304066151b577e063
busted/outputHandlers/base.lua
busted/outputHandlers/base.lua
return function(busted) local handler = { successes = {}, successesCount = 0, pendings = {}, pendingsCount = 0, failures = {}, failuresCount = 0, errors = {}, errorsCount = 0, inProgress = {} } handler.cancelOnPending = function(element, parent, status) return not ((element.descriptor == 'pending' or status == 'pending') and handler.options.suppressPending) end handler.subscribe = function(handler, options) require('busted.languages.en') handler.options = options if options.language ~= 'en' then require('busted.languages.' .. options.language) end busted.subscribe({ 'suite', 'start' }, handler.baseSuiteStart) busted.subscribe({ 'suite', 'end' }, handler.baseSuiteEnd) busted.subscribe({ 'test', 'start' }, handler.baseTestStart, { predicate = handler.cancelOnPending }) busted.subscribe({ 'test', 'end' }, handler.baseTestEnd, { predicate = handler.cancelOnPending }) busted.subscribe({ 'pending' }, handler.basePending, { predicate = handler.cancelOnPending }) busted.subscribe({ 'failure' }, handler.baseError) busted.subscribe({ 'error' }, handler.baseError) end handler.getFullName = function(context) local parent = busted.context.parent(context) local names = { (context.name or context.descriptor) } while parent and (parent.name or parent.descriptor) and parent.descriptor ~= 'file' do table.insert(names, 1, parent.name or parent.descriptor) parent = busted.context.parent(parent) end return table.concat(names, ' ') end handler.format = function(element, parent, message, debug, isError) local formatted = { trace = debug or element.trace, element = element, name = handler.getFullName(element), message = message, isError = isError } formatted.element.trace = element.trace or debug return formatted end handler.getDuration = function() if not handler.endTime or not handler.startTime then return 0 end return handler.endTime - handler.startTime end handler.baseSuiteStart = function() handler.startTime = os.clock() return nil, true end handler.baseSuiteEnd = function() handler.endTime = os.clock() return nil, true end handler.baseTestStart = function(element, parent) handler.inProgress[tostring(element)] = {} return nil, true end handler.baseTestEnd = function(element, parent, status, debug) local isError local insertTable local id = tostring(element) if status == 'success' then insertTable = handler.successes handler.successesCount = handler.successesCount + 1 elseif status == 'pending' then insertTable = handler.pendings handler.pendingsCount = handler.pendingsCount + 1 elseif status == 'failure' then insertTable = handler.failures handler.failuresCount = handler.failuresCount + 1 elseif status == 'error' then insertTable = handler.errors handler.errorsCount = handler.errorsCount + 1 isError = true end insertTable[id] = handler.format(element, parent, element.message, debug, isError) if handler.inProgress[id] then for k, v in pairs(handler.inProgress[id]) do insertTable[id][k] = v end handler.inProgress[id] = nil end return nil, true end handler.basePending = function(element, parent, message, debug) if element.descriptor == 'it' then local id = tostring(element) handler.inProgress[id].message = message handler.inProgress[id].trace = debug end return nil, true end handler.baseError = function(element, parent, message, debug) if element.descriptor == 'it' then if parent.randomseed then message = 'Random Seed: ' .. parent.randomseed .. '\n' .. message end local id = tostring(element) handler.inProgress[id].message = message handler.inProgress[id].trace = debug else handler.errorsCount = handler.errorsCount + 1 table.insert(handler.errors, handler.format(element, parent, message, debug, true)) end return nil, true end return handler end
return function(busted) local handler = { successes = {}, successesCount = 0, pendings = {}, pendingsCount = 0, failures = {}, failuresCount = 0, errors = {}, errorsCount = 0, inProgress = {} } handler.cancelOnPending = function(element, parent, status) return not ((element.descriptor == 'pending' or status == 'pending') and handler.options.suppressPending) end handler.subscribe = function(handler, options) require('busted.languages.en') handler.options = options if options.language ~= 'en' then require('busted.languages.' .. options.language) end busted.subscribe({ 'suite', 'start' }, handler.baseSuiteStart, { priority = 1 }) busted.subscribe({ 'suite', 'end' }, handler.baseSuiteEnd, { priority = 1 }) busted.subscribe({ 'test', 'start' }, handler.baseTestStart, { predicate = handler.cancelOnPending }) busted.subscribe({ 'test', 'end' }, handler.baseTestEnd, { predicate = handler.cancelOnPending }) busted.subscribe({ 'pending' }, handler.basePending, { predicate = handler.cancelOnPending }) busted.subscribe({ 'failure' }, handler.baseError) busted.subscribe({ 'error' }, handler.baseError) end handler.getFullName = function(context) local parent = busted.context.parent(context) local names = { (context.name or context.descriptor) } while parent and (parent.name or parent.descriptor) and parent.descriptor ~= 'file' do table.insert(names, 1, parent.name or parent.descriptor) parent = busted.context.parent(parent) end return table.concat(names, ' ') end handler.format = function(element, parent, message, debug, isError) local formatted = { trace = debug or element.trace, element = element, name = handler.getFullName(element), message = message, isError = isError } formatted.element.trace = element.trace or debug return formatted end handler.getDuration = function() if not handler.endTime or not handler.startTime then return 0 end return handler.endTime - handler.startTime end handler.baseSuiteStart = function() handler.startTime = os.clock() return nil, true end handler.baseSuiteEnd = function() handler.endTime = os.clock() return nil, true end handler.baseTestStart = function(element, parent) handler.inProgress[tostring(element)] = {} return nil, true end handler.baseTestEnd = function(element, parent, status, debug) local isError local insertTable local id = tostring(element) if status == 'success' then insertTable = handler.successes handler.successesCount = handler.successesCount + 1 elseif status == 'pending' then insertTable = handler.pendings handler.pendingsCount = handler.pendingsCount + 1 elseif status == 'failure' then insertTable = handler.failures handler.failuresCount = handler.failuresCount + 1 elseif status == 'error' then insertTable = handler.errors handler.errorsCount = handler.errorsCount + 1 isError = true end insertTable[id] = handler.format(element, parent, element.message, debug, isError) if handler.inProgress[id] then for k, v in pairs(handler.inProgress[id]) do insertTable[id][k] = v end handler.inProgress[id] = nil end return nil, true end handler.basePending = function(element, parent, message, debug) if element.descriptor == 'it' then local id = tostring(element) handler.inProgress[id].message = message handler.inProgress[id].trace = debug end return nil, true end handler.baseError = function(element, parent, message, debug) if element.descriptor == 'it' then if parent.randomseed then message = 'Random Seed: ' .. parent.randomseed .. '\n' .. message end local id = tostring(element) handler.inProgress[id].message = message handler.inProgress[id].trace = debug else handler.errorsCount = handler.errorsCount + 1 table.insert(handler.errors, handler.format(element, parent, message, debug, true)) end return nil, true end return handler end
Fix issue #283 Run duration is always 0.0 seconds
Fix issue #283 Run duration is always 0.0 seconds The reported run duration is always 0.0 seconds. This occurs because the terminal output handlers rely on the base output handler to record the start and end times of the suite. However, when the terminal output handler's suiteEnd() function runs, the base output handler's baseSuiteEnd() function has yet to record the end time. Thus, the suite end time is still 'nil' when the terminal output handlers are trying to get the run duration, resulting in a 0 duration. The solution is to ensure that the base output handler subscribes at the highest priority so that the suite end time will be recorded before it is needed by any other output handlers.
Lua
mit
xyliuke/busted,sobrinho/busted,nehz/busted,o-lim/busted,ryanplusplus/busted,mpeterv/busted,leafo/busted,istr/busted,DorianGray/busted,Olivine-Labs/busted
d1516c850def5b064c2b4be931957668de62d6d8
packages/lime-system/files/usr/lib/lua/lime/network.lua
packages/lime-system/files/usr/lib/lua/lime/network.lua
#!/usr/bin/lua network = {} local bit = require "nixio".bit local function split(string, sep) local ret = {} for token in string.gmatch(string, "[^"..sep.."]+") do table.insert(ret, token) end return ret end function network.eui64(mac) local function hex(x) return string.format("%02x", x) end local function flip_7th_bit(x) return hex(bit.bxor(tonumber(x, 16), 2)) end local t = split(mac, ":") t[1] = flip_7th_bit(t[1]) return string.format("%s%s:%sff:fe%s:%s%s", t[1], t[2], t[3], t[4], t[5], t[6]) end function network.generate_address(p, n) local id = n local r1, r2, r3 = node_id() local n1, n2, n3 = network_id() local ipv4_template = assert(x:get("lime", "network", "ipv4_net")) local ipv6_template = assert(x:get("lime", "network", "ipv6_net")) local function hex(x) return string.format("%02x", x) end ipv6_template = ipv6_template:gsub("N1", hex(n1)):gsub("N2", hex(n2)):gsub("N3", hex(n3)) ipv4_template = ipv4_template:gsub("N1", n1):gsub("N2", n2):gsub("N3", n3) return ipv4_template:gsub("R1", r1):gsub("R2", r2):gsub("R3", r3 + id), ipv6_template:gsub("R1", hex(r1)):gsub("R2", hex(r2)):gsub("R3", hex(r3 + id)) end function network.setup_lan(v4, v6) x:set("network", "lan", "ip6addr", v6) x:set("network", "lan", "ipaddr", v4:match("^([^/]+)")) x:set("network", "lan", "netmask", "255.255.255.0") x:set("network", "lan", "ifname", "eth0 bat0") x:save("network") end function network.setup_anygw(v4, v6) local n1, n2, n3 = network_id() -- anygw macvlan interface print("Ugly overwrite of /etc/rc.local to make it add macvlan interface...") local anygw_mac = string.format("aa:aa:aa:%02x:%02x:%02x", n1, n2, n3) local v6prefix = v6:match("^([^:]+:[^:]+:[^:]+:[^:]+):") local v4prefix = v4:match("^([^.]+.[^.]+.[^.]+).") local anygw_ipv6 = string.format(v6prefix .. "::1/64") local anygw_ipv4 = string.format(v4prefix .. ".1/24") local content = { } table.insert(content, "ip link add link br-lan anygw address " .. anygw_mac .. " type macvlan") table.insert(content, "ip address add dev anygw " .. anygw_ipv6) table.insert(content, "ip address add dev anygw " .. anygw_ipv4) table.insert(content, "ip link set anygw up") table.insert(content, "ebtables -A FORWARD -j DROP -d " .. anygw_mac) table.insert(content, "ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac) table.insert(content, "exit 0") fs.writefile("/etc/rc.local", table.concat(content, "\n").."\n") -- IPv6 router advertisement for anygw interface print("Enabling RA in dnsmasq...") local content = { } table.insert(content, "enable-ra") table.insert(content, string.format("dhcp-range=tag:anygw,%s::, ra-names", v6prefix)) table.insert(content, "dhcp-option=tag:anygw,option6:domain-search, lan") table.insert(content, string.format("address=/anygw/%s::1", v6prefix)) table.insert(content, string.format("dhcp-option=tag:anygw,option:router,%s.1", v4prefix)) table.insert(content, string.format("dhcp-option=tag:anygw,option:dns-server,%s.1", v4prefix)) table.insert(content, "no-dhcp-interface=br-lan") fs.writefile("/etc/dnsmasq.conf", table.concat(content, "\n").."\n") -- and disable 6relayd print("Disabling 6relayd...") fs.writefile("/etc/config/6relayd", "") end function network.clean() print("Clearing network config...") x:foreach("network", "interface", function(s) if s[".name"]:match("^lm_") then x:delete("network", s[".name"]) end end) end function network.init() -- TODO end function network.configure() local protocols = assert(x:get("lime", "network", "protos")) local vlans = assert(x:get("lime", "network", "vlans")) local n1, n2, n3 = network_id() local r1, r2, r3 = node_id() local v4, v6 = network.generate_address(1, 0) -- for br-lan network.clean() network.setup_lan(v4, v6) network.setup_anygw(v4, v6) -- For layer2 use a vlan based off network_id, between 16 and 255, if uci doesn't specify a vlan if not vlans[2] then vlans[2] = math.floor(16 + ((tonumber(n1) / 255) * (255 - 16))) end -- TODO: -- for each net ; if protocols = wan or lan ; setup_network_interface_lan -- elsif protocols = bmx6 or batadv ; setup_network_interface_ .. protocol -- FIXME: currently adds vlan interfaces on top of ethernet, for each proto (batadv or bmx6). -- Eg. lm_eth_batadv local n for n = 1, #protocols do local interface = "lm_eth_" .. protocols[n] local ifname = string.format("eth1.%d", vlans[n]) local v4, v6 = network.generate_address(n, 0) local proto = require("lime.proto." .. protocols[n]) proto.setup_interface(interface, ifname, v4, v6) end end function network.apply() -- TODO (i.e. /etc/init.d/network restart) end return network
#!/usr/bin/lua network = {} local bit = require "nixio".bit local ip = require "luci.ip" local function hex(x) return string.format("%02x", x) end local function split(string, sep) local ret = {} for token in string.gmatch(string, "[^"..sep.."]+") do table.insert(ret, token) end return ret end function network.eui64(mac) local function flip_7th_bit(x) return hex(bit.bxor(tonumber(x, 16), 2)) end local t = split(mac, ":") t[1] = flip_7th_bit(t[1]) return string.format("%s%s:%sff:fe%s:%s%s", t[1], t[2], t[3], t[4], t[5], t[6]) end function network.generate_host(ipprefix, hexsuffix) -- use only the 8 rightmost nibbles for IPv4, or 32 nibbles for IPv6 hexsuffix = hexsuffix:sub((ipprefix[1] == 4) and -8 or -32) -- convert hexsuffix into a cidr instance, using same prefix and family of ipprefix local ipsuffix = ip.Hex(hexsuffix, ipprefix:prefix(), ipprefix[1]) local ipaddress = ipprefix -- if it's a network prefix, fill in host bits with ipsuffix if ipprefix:equal(ipprefix:network()) then for i in ipairs(ipprefix[2]) do -- reset ipsuffix netmask bits to 0 ipsuffix[2][i] = bit.bxor(ipsuffix[2][i],ipsuffix:network()[2][i]) -- fill in ipaddress host part, with ipsuffix bits ipaddress[2][i] = bit.bor(ipaddress[2][i],ipsuffix[2][i]) end end return ipaddress end function network.generate_address(p, n) local id = n local r1, r2, r3 = node_id() local n1, n2, n3 = network_id() local ipv4_template = assert(x:get("lime", "network", "ipv4_net")) local ipv6_template = assert(x:get("lime", "network", "ipv6_net")) ipv6_template = ipv6_template:gsub("N1", hex(n1)):gsub("N2", hex(n2)):gsub("N3", hex(n3)) ipv4_template = ipv4_template:gsub("N1", n1):gsub("N2", n2):gsub("N3", n3) hexsuffix = hex((r1 * 256*256 + r2 * 256 + r3) + id) return network.generate_host(ip.IPv4(ipv4_template), hexsuffix):string(), network.generate_host(ip.IPv6(ipv6_template), hexsuffix):string() end function network.setup_lan(v4, v6) x:set("network", "lan", "ip6addr", v6) x:set("network", "lan", "ipaddr", v4:match("^([^/]+)")) x:set("network", "lan", "netmask", "255.255.255.0") x:set("network", "lan", "ifname", "eth0 bat0") x:save("network") end function network.setup_anygw(v4, v6) local n1, n2, n3 = network_id() -- anygw macvlan interface print("Ugly overwrite of /etc/rc.local to make it add macvlan interface...") local anygw_mac = string.format("aa:aa:aa:%02x:%02x:%02x", n1, n2, n3) local v6prefix = v6:match("^([^:]+:[^:]+:[^:]+:[^:]+):") local v4prefix = v4:match("^([^.]+.[^.]+.[^.]+).") local anygw_ipv6 = string.format(v6prefix .. "::1/64") local anygw_ipv4 = string.format(v4prefix .. ".1/24") local content = { } table.insert(content, "ip link add link br-lan anygw address " .. anygw_mac .. " type macvlan") table.insert(content, "ip address add dev anygw " .. anygw_ipv6) table.insert(content, "ip address add dev anygw " .. anygw_ipv4) table.insert(content, "ip link set anygw up") table.insert(content, "ebtables -A FORWARD -j DROP -d " .. anygw_mac) table.insert(content, "ebtables -t nat -A POSTROUTING -o bat0 -j DROP -s " .. anygw_mac) table.insert(content, "exit 0") fs.writefile("/etc/rc.local", table.concat(content, "\n").."\n") -- IPv6 router advertisement for anygw interface print("Enabling RA in dnsmasq...") local content = { } table.insert(content, "enable-ra") table.insert(content, string.format("dhcp-range=tag:anygw,%s::, ra-names", v6prefix)) table.insert(content, "dhcp-option=tag:anygw,option6:domain-search, lan") table.insert(content, string.format("address=/anygw/%s::1", v6prefix)) table.insert(content, string.format("dhcp-option=tag:anygw,option:router,%s.1", v4prefix)) table.insert(content, string.format("dhcp-option=tag:anygw,option:dns-server,%s.1", v4prefix)) table.insert(content, "no-dhcp-interface=br-lan") fs.writefile("/etc/dnsmasq.conf", table.concat(content, "\n").."\n") -- and disable 6relayd print("Disabling 6relayd...") fs.writefile("/etc/config/6relayd", "") end function network.clean() print("Clearing network config...") x:foreach("network", "interface", function(s) if s[".name"]:match("^lm_") then x:delete("network", s[".name"]) end end) end function network.init() -- TODO end function network.configure() local protocols = assert(x:get("lime", "network", "protos")) local vlans = assert(x:get("lime", "network", "vlans")) local n1, n2, n3 = network_id() local r1, r2, r3 = node_id() local v4, v6 = network.generate_address(1, 0) -- for br-lan network.clean() network.setup_lan(v4, v6) network.setup_anygw(v4, v6) -- For layer2 use a vlan based off network_id, between 16 and 255, if uci doesn't specify a vlan if not vlans[2] then vlans[2] = math.floor(16 + ((tonumber(n1) / 255) * (255 - 16))) end -- TODO: -- for each net ; if protocols = wan or lan ; setup_network_interface_lan -- elsif protocols = bmx6 or batadv ; setup_network_interface_ .. protocol -- FIXME: currently adds vlan interfaces on top of ethernet, for each proto (batadv or bmx6). -- Eg. lm_eth_batadv local n for n = 1, #protocols do local interface = "lm_eth_" .. protocols[n] local ifname = string.format("eth1.%d", vlans[n]) local v4, v6 = network.generate_address(n, 0) local proto = require("lime.proto." .. protocols[n]) proto.setup_interface(interface, ifname, v4, v6) end end function network.apply() -- TODO (i.e. /etc/init.d/network restart) end return network
implement a generate_host() function using luci.ip lib, that fills necessary host bits on an address, using a hexsuffix
implement a generate_host() function using luci.ip lib, that fills necessary host bits on an address, using a hexsuffix
Lua
agpl-3.0
p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages
36340a2a13fc76abb365ad7cdf8fabfdacbf0142
.config/mpv/scripts/playback_logger.lua
.config/mpv/scripts/playback_logger.lua
mputils = require 'mp.utils' require 'os' -- from shell.lua, by Peter Odding local function escape(...) local command = type(...) == 'table' and ... or { ... } for i, s in ipairs(command) do s = (tostring(s) or ''):gsub('"', '\\"') if s:find '[^A-Za-z0-9_."/-]' then s = '"' .. s .. '"' elseif s == '' then s = '""' end command[i] = s end return table.concat(command, ' ') end function trim(path) return string.match(path, '^%s*(.-)%s*$') end function run(t) return trim(mputils.subprocess(t).stdout) end function on_path_change(_, new_path) last_file_path = new_path end function on_time_change(_, new_time) last_remaining_time = new_time end function playback_finished(event) if last_remaining_time > minimum_remaining_time then mp.log('info', string.format( 'Too much remaining time (%.02f > %.02f), skipping', last_remaining_time, minimum_remaining_time)) else json = mputils.format_json({ date=os.date('%c'), host=hostname, path=last_file_path }) json = run({ args={ 'sh', '-c', 'echo ' .. escape(json) .. '|' .. 'python -c "import json,sys;print(json.dumps(json.load(sys.stdin),sort_keys=True))"'}, cancellable=false}) mp.log('info', 'Sending JSON: ' .. json) output = run({ args={ 'ssh', remote_host, 'echo', escape(json), '>>', escape(remote_log_path)}, cancellable=false}) end end ---------- minimum_remaining_time = 120 --seconds remote_host = 'burza' remote_log_path = '/srv/www/tmp.sakuya.pl/public_html/mal/watched.lst' hostname = run({args={'hostname'}, cancellable=false}) mp.observe_property('path', 'string', on_path_change) mp.observe_property('time-remaining', 'native', on_time_change) mp.register_event('end-file', playback_finished)
mputils = require 'mp.utils' require 'os' -- from shell.lua, by Peter Odding local function escape(...) local command = type(...) == 'table' and ... or { ... } for i, s in ipairs(command) do s = (tostring(s) or ''):gsub('"', '\\"') if s:find '[^A-Za-z0-9_."/-]' then s = '"' .. s .. '"' elseif s == '' then s = '""' end command[i] = s end return table.concat(command, ' ') end function trim(path) return string.match(path, '^%s*(.-)%s*$') end function run(t) return trim(mputils.subprocess(t).stdout) end function on_path_change(_, new_path) last_file_path = new_path end function on_time_change(_, new_time) last_remaining_time = new_time end function playback_finished(event) if last_remaining_time == null then mp.log('info', 'No information on remaining time, skipping') elseif last_remaining_time > minimum_remaining_time then mp.log('info', string.format( 'Too much remaining time (%.02f > %.02f), skipping', last_remaining_time, minimum_remaining_time)) else json = mputils.format_json({ date=os.date('%c'), host=hostname, path=last_file_path }) json = run({ args={ 'sh', '-c', 'echo ' .. escape(json) .. '|' .. 'python -c "import json,sys;print(json.dumps(json.load(sys.stdin),sort_keys=True))"'}, cancellable=false}) mp.log('info', 'Sending JSON: ' .. json) output = run({ args={ 'ssh', remote_host, 'echo', escape(json), '>>', escape(remote_log_path)}, cancellable=false}) end end ---------- minimum_remaining_time = 120 --seconds remote_host = 'burza' remote_log_path = '/srv/www/tmp.sakuya.pl/public_html/mal/watched.lst' hostname = run({args={'hostname'}, cancellable=false}) mp.observe_property('path', 'string', on_path_change) mp.observe_property('time-remaining', 'native', on_time_change) mp.register_event('end-file', playback_finished)
Fixed mpv errors when playing audio files
Fixed mpv errors when playing audio files
Lua
mit
rr-/dotfiles,rr-/dotfiles,rr-/dotfiles
016e56f13d2577c64769826d6679bdabc77f47a0
openwrt/package/linkmeter/luasrc/luci/controller/linkmeter/api.lua
openwrt/package/linkmeter/luasrc/luci/controller/linkmeter/api.lua
local _M = {} local API_VERSION = 1 function _M.index() local API_READ_ONLY = "api_read" local API_WRITE_ONLY = "api_write" local API_READ_WRITE = { "api_read", "api_write" } local node node = entry({"lm", "api"}, alias({"lm", "api", "version"})) node.sysauth = API_READ_ONLY -- Set the authenticator for all pages below /lm/api -- This needs to be done inline so it is included in the luci-indexcache node.sysauth_authenticator = function(checkpasswd, accs, def) local http = require("luci.http") local uci = require("uci"):cursor() -- If API is disabled, both read and write is disabled if uci:get("linkmeter", "api", "disabled") == "1" then http.status(403, "Forbidden") http.prepare_content("text/plain") http.write("API disabled") return nil end if uci:get("linkmeter", "api", "allowcors") == "1" then http.header("Access-Control-Allow-Origin", "*") end -- Case 1: sysauth = api_read if def == API_READ_ONLY then -- Return read only user and a blank session so one isn't created return API_READ_ONLY, {} end -- Case 2: sysauth = { api_read, api_write } and this is *not* a POST (write) if http.getenv("REQUEST_METHOD") ~= "POST" and def == false then -- Return read only user and a blank session so one isn't created return API_READ_ONLY, {} end -- Case 3: sysauth = api_write or { api_read, api_write } require a POST if http.getenv("REQUEST_METHOD") ~= "POST" then http.status(405, "Method Not Allowed") http.header("Allow", "POST") return nil end -- and check the supplied API key local key = http.formvalue("apikey") local apikey = uci:get("linkmeter", "api", "key") if apikey and apikey ~= "" and key and key:lower() == apikey:lower() then -- Hokey workaround because luci doesn't set the authuser if it -- isn't the code that creates the session luci.dispatcher.context.authuser = API_WRITE_ONLY -- Return write user and a blank session so one isn't created return API_WRITE_ONLY, {} else http.status(403, "Forbidden") http.prepare_content("text/plain") http.write("Invalid or missing apikey") end end -- end sysauth entry({"lm", "api", "version"}, call("action_api_version")) entry({"lm", "api", "status"}, call("action_api_status")).leaf = true node = entry({"lm", "api", "config"}, call("action_api_config")) node.sysauth = API_READ_WRITE node.leaf = true node = entry({"lm", "api", "fw"}, call("action_api_fw")) node.sysauth = API_READ_WRITE node.leaf = true end local function is_write() return luci.http.getenv("REQUEST_METHOD") == "POST" end local function quick_json(t) local http = require("luci.http") http.prepare_content("application/json") http.write('{') local c = "" for k,v in pairs(t) do if type(v) == "string" then if v == "null" then http.write(c .. '"' .. k .. '":null') else http.write(c .. '"' .. k .. '":"' .. v .. '"') end else http.write(c .. '"' .. k .. '":' .. v) end c = "," end http.write('}') end local function api_lmquery(query, tablefmt) lmclient = require("lmclient") local result, err = LmClient:query(query) result = result or "{}" -- Return the result in a parsed table instead of string if tablefmt then local jsonc = require("luci.jsonc") local o = jsonc.parse(result) return o, err end return result, err end function _M.action_api_version() local conf = api_lmquery("$LMCF", true) quick_json({api = API_VERSION, ucid = conf.ucid or "null"}) end function _M.action_api_status() local ctx = luci.dispatcher.context local param = ctx.requestargs and #ctx.requestargs > 0 local status = api_lmquery("$LMSU", param) local http = require("luci.http") if param then for _,k in ipairs(ctx.requestargs) do -- if k is an integer, use it as an index local kn = tonumber(k) if kn and kn == math.floor(kn) then k = kn+1 end status = status and status[k] end end if type(status) == "table" then http.prepare_content("application/json") http.write(luci.jsonc.stringify(status)) elseif type(status) == "string" and status:sub(1,1) == "{" then http.prepare_content("application/json") http.write(status) else http.prepare_content("text/plain") http.write(tostring(status or "null")) -- content must be a string end end function _M.action_api_config() -- See if just one parameter is specified, or this is a parent call local param, value local ctx = luci.dispatcher.context if ctx.requestargs and #ctx.requestargs > 0 then param = ctx.requestargs[1] if #ctx.requestargs > 1 then value = ctx.requestargs[2] end end local http = require("luci.http") if is_write() then local lmadmin = require("luci.controller.linkmeter.lmadmin") if param then local vals = {} vals[param] = http.formvalue(param) or http.formvalue("value") return lmadmin.api_set(vals) else return lmadmin.api_set(http.formvalue()) end else local result = api_lmquery("$LMCF", param) if param then http.prepare_content("text/plain") http.write(result[param] or "null") else http.prepare_content("application/json") http.write(result) end end -- isRead end function _M.action_api_fw() if not luci.http.formvalue("hexfile") then luci.http.status(400, "Bad Request") luci.http.prepare_content("text/plain") luci.http.write("Missing hexfile POST parameter") return end local lmadmin = require("luci.controller.linkmeter.lmadmin") lmadmin.api_file_handler("/tmp/hm.hex") return lmadmin.api_post_fw("/tmp/hm.hex") end return _M
local _M = {} local API_VERSION = 1 function _M.index() entry({"lm", "api"}, alias({"lm", "api", "version"})) entry({"lm", "api", "version"}, call("action_api_version")) entry({"lm", "api", "status"}, call("action_api_status")).leaf = true entry({"lm", "api", "config"}, call("action_api_config")).leaf = true entry({"lm", "api", "fw"}, call("action_api_fw")).leaf = true end local function is_write() return luci.http.getenv("REQUEST_METHOD") == "POST" end local function auth(write_access) local http = require("luci.http") local uci = require("uci"):cursor() -- If API is disabled, both read and write is disabled if uci:get("linkmeter", "api", "disabled") == "1" then http.status(403, "Forbidden") http.prepare_content("text/plain") http.write("API disabled") return nil end if uci:get("linkmeter", "api", "allowcors") == "1" then http.header("Access-Control-Allow-Origin", "*") end -- Case 1: sysauth = api_read if not write_access then return true end -- Case 2: sysauth = api_write or { api_read, api_write } require a POST if write_access and http.getenv("REQUEST_METHOD") ~= "POST" then http.status(405, "Method Not Allowed") http.header("Allow", "POST") return nil end -- and check the supplied API key local key = http.formvalue("apikey") local apikey = uci:get("linkmeter", "api", "key") if apikey and apikey ~= "" and key and key:lower() == apikey:lower() then luci.dispatcher.context.authuser = "api_write" return true else http.status(403, "Forbidden") http.prepare_content("text/plain") http.write("Invalid or missing apikey") return nil end end local function quick_json(t) local http = require("luci.http") http.prepare_content("application/json") http.write('{') local c = "" for k,v in pairs(t) do if type(v) == "string" then if v == "null" then http.write(c .. '"' .. k .. '":null') else http.write(c .. '"' .. k .. '":"' .. v .. '"') end else http.write(c .. '"' .. k .. '":' .. v) end c = "," end http.write('}') end local function api_lmquery(query, tablefmt) lmclient = require("lmclient") local result, err = LmClient:query(query) result = result or "{}" -- Return the result in a parsed table instead of string if tablefmt then local jsonc = require("luci.jsonc") local o = jsonc.parse(result) return o, err end return result, err end function _M.action_api_version() if not auth() then return end local conf = api_lmquery("$LMCF", true) quick_json({api = API_VERSION, ucid = conf.ucid or "null"}) end function _M.action_api_status() if not auth() then return end local ctx = luci.dispatcher.context local param = ctx.requestargs and #ctx.requestargs > 0 local status = api_lmquery("$LMSU", param) local http = require("luci.http") if param then for _,k in ipairs(ctx.requestargs) do -- if k is an integer, use it as an index local kn = tonumber(k) if kn and kn == math.floor(kn) then k = kn+1 end status = status and status[k] end end if type(status) == "table" then http.prepare_content("application/json") http.write(luci.jsonc.stringify(status)) elseif type(status) == "string" and status:sub(1,1) == "{" then http.prepare_content("application/json") http.write(status) else http.prepare_content("text/plain") http.write(tostring(status or "null")) -- content must be a string end end function _M.action_api_config() if not auth(is_write()) then return end -- See if just one parameter is specified, or this is a parent call local param, value local ctx = luci.dispatcher.context if ctx.requestargs and #ctx.requestargs > 0 then param = ctx.requestargs[1] if #ctx.requestargs > 1 then value = ctx.requestargs[2] end end local http = require("luci.http") if is_write() then local lmadmin = require("luci.controller.linkmeter.lmadmin") if param then local vals = {} vals[param] = http.formvalue(param) or http.formvalue("value") return lmadmin.api_set(vals) else return lmadmin.api_set(http.formvalue()) end else local result = api_lmquery("$LMCF", param) if param then http.prepare_content("text/plain") http.write(result[param] or "null") else http.prepare_content("application/json") http.write(result) end end -- isRead end function _M.action_api_fw() if not auth(true) then return end if not luci.http.formvalue("hexfile") then luci.http.status(400, "Bad Request") luci.http.prepare_content("text/plain") luci.http.write("Missing hexfile POST parameter") return end local lmadmin = require("luci.controller.linkmeter.lmadmin") lmadmin.api_file_handler("/tmp/hm.hex") return lmadmin.api_post_fw("/tmp/hm.hex") end return _M
[lm] Fix API access not working at all since LuCI changes
[lm] Fix API access not working at all since LuCI changes
Lua
mit
shmick/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter
b0f2725e081f652f8ba582b886e7ce5efa3b48c7
core/debug-output.lua
core/debug-output.lua
if (not SILE.outputters) then SILE.outputters = {} end local cursorX = 0 local cursorY = 0 local lastFont local outfile local writeline = function (...) local args = table.pack(...) for i = 1, #args do outfile:write(args[i]) if i < #args then outfile:write("\t") end end outfile:write("\n") end local _deprecationCheck = function (caller) if type(caller) ~= "table" or type(caller.debugHbox) ~= "function" then SU.deprecated("SILE.outputter.*", "SILE.outputter:*", "0.10.9", "0.10.10") end end local function _round (input) -- LuaJIT 2.1 betas (and inheritors such as OpenResty and Moonjit) are biased -- towards rounding 0.5 up to 1, all other Lua interpreters are biased -- towards rounding such floating point numbers down. This hack shaves off -- just enough to fix the bias so our test suite works across interpreters. -- Note that even a true rounding function here will fail because the bias is -- inherent to the floating point type. Also note we are erroring in favor of -- the *less* common option beacuse the LuaJIT VMS are hopelessly broken -- whereas normal LUA VMs can be cooerced. if input > 0 then input = input + .00000000000001 end if input < 0 then input = input - .00000000000001 end return string.format("%.4f", input) end SILE.outputters.debug = { init = function (self) _deprecationCheck(self) outfile = io.open(SILE.outputFilename, "w+") writeline("Set paper size ", SILE.documentState.paperSize[1], SILE.documentState.paperSize[2]) writeline("Begin page") end, newPage = function (self) _deprecationCheck(self) writeline("New page") end, finish = function (self) _deprecationCheck(self) if SILE.status.unsupported then writeline("UNSUPPORTED") end writeline("End page") writeline("Finish") outfile:close() end, cursor = function (_) SU.deprecated("SILE.outputter:cursor", "SILE.outputter:getCursor", "0.10.10", "0.11.0") end, getCursor = function (self) _deprecationCheck(self) return cursorX, cursorY end, moveTo = function (_, _, _) SU.deprecated("SILE.outputter:moveTo", "SILE.outputter:setCursor", "0.10.10", "0.11.0") end, setCursor = function (self, x, y, relative) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) local oldx, oldy = self:getCursor() local offset = relative and { x = cursorX, y = cursorY } or { x = 0, y = 0 } cursorX = offset.x + x cursorY = offset.y - y if _round(oldx) ~= _round(cursorX) then writeline("Mx ", _round(x)) end if _round(oldy) ~= _round(cursorY) then writeline("My ", _round(y)) end end, setColor = function (self, color) _deprecationCheck(self) writeline("Set color", color.r, color.g, color.b) end, pushColor = function (self, color) _deprecationCheck(self) if color.r then writeline("Push color", _round(color.r), _round(color.g), _round(color.b)) elseif color.c then writeline("Push color (CMYK)", _round(color.c), _round(color.m), _round(color.y), _round(color.k)) elseif color.l then writeline("Push color (grayscale)", _round(color.l)) end end, popColor = function (self) _deprecationCheck(self) writeline("Pop color") end, outputHbox = function (_, _, _) SU.deprecated("SILE.outputter:outputHbox", "SILE.outputter:drawHbox", "0.10.10", "0.11.0") end, drawHbox = function (self, value, width) _deprecationCheck(self) if not value.glyphString then return end width = SU.cast("number", width) local buf if value.complex then local cluster = {} for i = 1, #value.items do local item = value.items[i] cluster[#cluster+1] = item.gid -- For the sake of terseness we're only dumping non-zero values if item.glyphAdvance ~= 0 then cluster[#cluster+1] = "a=".._round(item.glyphAdvance) end if item.x_offset then cluster[#cluster+1] = "x=".._round(item.x_offset) end if item.y_offset then cluster[#cluster+1] = "y=".._round(item.y_offset) end self:setCursor(item.width, 0, true) end buf = table.concat(cluster, " ") else buf = table.concat(value.glyphString, " ") .. " w=" .. _round(width) end writeline("T", buf, "(" .. tostring(value.text) .. ")") end, setFont = function (self, options) _deprecationCheck(self) local font = SILE.font._key(options) if lastFont ~= font then writeline("Set font ", font) lastFont = font end end, drawImage = function (self, src, x, y, width, height) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) height = SU.cast("number", height) writeline("Draw image", src, _round(x), _round(y), _round(width), _round(height)) end, imageSize = function (_, _) SU.deprecated("SILE.outputter:imageSize", "SILE.outputter:getImageSize", "0.10.10", "0.11.0") end, getImageSize = function (self, src) _deprecationCheck(self) local pdf = require("justenoughlibtexpdf") local llx, lly, urx, ury = pdf.imagebbox(src) return (urx-llx), (ury-lly) end, drawSVG = function (self, figure, _, x, y, width, height, scalefactor) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) height = SU.cast("number", height) writeline("Draw SVG", _round(x), _round(y), _round(width), _round(height), figure, scalefactor) end, rule = function (_, _, _, _, _) SU.deprecated("SILE.outputter:rule", "SILE.outputter:drawRule", "0.10.10", "0.11.0") end, drawRule = function (self, x, y, width, depth) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) depth = SU.cast("number", depth) writeline("Draw line", _round(x), _round(y), _round(width), _round(depth)) end, debugFrame = function (self, _, _) _deprecationCheck(self) end, debugHbox = function (self, _, _, _) _deprecationCheck(self) end } SILE.outputter = SILE.outputters.debug if not SILE.outputFilename and SILE.masterFilename then SILE.outputFilename = SILE.masterFilename..".debug" end
if (not SILE.outputters) then SILE.outputters = {} end local cursorX = 0 local cursorY = 0 local lastFont local outfile local writeline = function (...) local args = table.pack(...) for i = 1, #args do outfile:write(args[i]) if i < #args then outfile:write("\t") end end outfile:write("\n") end local _deprecationCheck = function (caller) if type(caller) ~= "table" or type(caller.debugHbox) ~= "function" then SU.deprecated("SILE.outputter.*", "SILE.outputter:*", "0.10.9", "0.10.10") end end local function _round (input) -- LuaJIT 2.1 betas (and inheritors such as OpenResty and Moonjit) are biased -- towards rounding 0.5 up to 1, all other Lua interpreters are biased -- towards rounding such floating point numbers down. This hack shaves off -- just enough to fix the bias so our test suite works across interpreters. -- Note that even a true rounding function here will fail because the bias is -- inherent to the floating point type. Also note we are erroring in favor of -- the *less* common option beacuse the LuaJIT VMS are hopelessly broken -- whereas normal LUA VMs can be cooerced. if input > 0 then input = input + .00000000000001 end if input < 0 then input = input - .00000000000001 end return string.format("%.4f", input) end SILE.outputters.debug = { init = function (self) _deprecationCheck(self) outfile = io.open(SILE.outputFilename, "w+") writeline("Set paper size ", SILE.documentState.paperSize[1], SILE.documentState.paperSize[2]) writeline("Begin page") end, newPage = function (self) _deprecationCheck(self) writeline("New page") end, finish = function (self) _deprecationCheck(self) if SILE.status.unsupported then writeline("UNSUPPORTED") end writeline("End page") writeline("Finish") outfile:close() end, cursor = function (_) SU.deprecated("SILE.outputter:cursor", "SILE.outputter:getCursor", "0.10.10", "0.11.0") end, getCursor = function (self) _deprecationCheck(self) return cursorX, cursorY end, moveTo = function (_, _, _) SU.deprecated("SILE.outputter:moveTo", "SILE.outputter:setCursor", "0.10.10", "0.11.0") end, setCursor = function (self, x, y, relative) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) local oldx, oldy = self:getCursor() local offset = relative and { x = cursorX, y = cursorY } or { x = 0, y = 0 } cursorX = offset.x + x cursorY = offset.y - y if _round(oldx) ~= _round(cursorX) then writeline("Mx ", _round(x)) end if _round(oldy) ~= _round(cursorY) then writeline("My ", _round(y)) end end, setColor = function (self, color) _deprecationCheck(self) if color.r then writeline("Set color", _round(color.r), _round(color.g), _round(color.b)) elseif color.c then writeline("Set color (CMYK)", _round(color.c), _round(color.m), _round(color.y), _round(color.k)) elseif color.l then writeline("Set color (grayscale)", _round(color.l)) end end, pushColor = function (self, color) _deprecationCheck(self) if color.r then writeline("Push color", _round(color.r), _round(color.g), _round(color.b)) elseif color.c then writeline("Push color (CMYK)", _round(color.c), _round(color.m), _round(color.y), _round(color.k)) elseif color.l then writeline("Push color (grayscale)", _round(color.l)) end end, popColor = function (self) _deprecationCheck(self) writeline("Pop color") end, outputHbox = function (_, _, _) SU.deprecated("SILE.outputter:outputHbox", "SILE.outputter:drawHbox", "0.10.10", "0.11.0") end, drawHbox = function (self, value, width) _deprecationCheck(self) if not value.glyphString then return end width = SU.cast("number", width) local buf if value.complex then local cluster = {} for i = 1, #value.items do local item = value.items[i] cluster[#cluster+1] = item.gid -- For the sake of terseness we're only dumping non-zero values if item.glyphAdvance ~= 0 then cluster[#cluster+1] = "a=".._round(item.glyphAdvance) end if item.x_offset then cluster[#cluster+1] = "x=".._round(item.x_offset) end if item.y_offset then cluster[#cluster+1] = "y=".._round(item.y_offset) end self:setCursor(item.width, 0, true) end buf = table.concat(cluster, " ") else buf = table.concat(value.glyphString, " ") .. " w=" .. _round(width) end writeline("T", buf, "(" .. tostring(value.text) .. ")") end, setFont = function (self, options) _deprecationCheck(self) local font = SILE.font._key(options) if lastFont ~= font then writeline("Set font ", font) lastFont = font end end, drawImage = function (self, src, x, y, width, height) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) height = SU.cast("number", height) writeline("Draw image", src, _round(x), _round(y), _round(width), _round(height)) end, imageSize = function (_, _) SU.deprecated("SILE.outputter:imageSize", "SILE.outputter:getImageSize", "0.10.10", "0.11.0") end, getImageSize = function (self, src) _deprecationCheck(self) local pdf = require("justenoughlibtexpdf") local llx, lly, urx, ury = pdf.imagebbox(src) return (urx-llx), (ury-lly) end, drawSVG = function (self, figure, _, x, y, width, height, scalefactor) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) height = SU.cast("number", height) writeline("Draw SVG", _round(x), _round(y), _round(width), _round(height), figure, scalefactor) end, rule = function (_, _, _, _, _) SU.deprecated("SILE.outputter:rule", "SILE.outputter:drawRule", "0.10.10", "0.11.0") end, drawRule = function (self, x, y, width, depth) _deprecationCheck(self) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) depth = SU.cast("number", depth) writeline("Draw line", _round(x), _round(y), _round(width), _round(depth)) end, debugFrame = function (self, _, _) _deprecationCheck(self) end, debugHbox = function (self, _, _, _) _deprecationCheck(self) end } SILE.outputter = SILE.outputters.debug if not SILE.outputFilename and SILE.masterFilename then SILE.outputFilename = SILE.masterFilename..".debug" end
chore(outputter): Fixup debug outputter for non-RGB
chore(outputter): Fixup debug outputter for non-RGB
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
7ba7e06f684ebf874832721645982ce85dde2586
Client/Assets/Lua/main.lua
Client/Assets/Lua/main.lua
------------------------------------------------ -- Copyright © 2015-2016 Hugula: Arpg game Engine -- 检查资源 -- author pu ------------------------------------------------ require("core.loader") json = require "lib.json" local Hugula = Hugula local RuntimePlatform= UnityEngine.RuntimePlatform local Application= UnityEngine.Application local WWW = UnityEngine.WWW local GameObject = UnityEngine.GameObject local Request=LRequest local CUtils= Hugula.Utils.CUtils local LuaHelper=Hugula.Utils.LuaHelper local FileHelper=Hugula.Utils.FileHelper local PLua = Hugula.PLua local Download = Hugula.Update.Download local Loader = Loader ResVersion = 0 local _progressbar_txt; local FRIST_VIEW = "Logo" local VERSION_FILE_NAME = "crc32_ver.u3d" local VERSION_TEMP_FILE_NAME = "crc32_ver.tmp" local UPDATED_LIST_NAME = "crc32_file.u3d" local UPDATED_TEMP_LIST_NAME = "crc32_file.tmp" local DOWANLOAD_TEMP_FILE = "downloaded.tmp" local host = {"http://192.168.100.14/"..CUtils.GetAssetPath("").."/","http://192.168.100.114/"..CUtils.GetAssetPath("").."/"} --更新列表 --local fristView local all,loaded = 0,0 local local_file,server_file,loaded_file local function set_progress_txt(text) if _progressbar_txt then _progressbar_txt.text = text end end local function enterGame(need_reload) local function to_begin( ... ) require("begin") end local function load_manifest( ... ) Loader:refresh_assetbundle_manifest(to_begin) end if need_reload == true then set_progress_txt("刷新脚本") PLua.instance:LoadBundle(load_manifest) else set_progress_txt("进入游戏") load_manifest() end end local function save_loaded_file(loaded_list) local context = json.encode(loaded_list) local old_list_context = FileHelper.SavePersistentFile(context,DOWANLOAD_TEMP_FILE) --读取上次加载未完成列表 end local function save_loaded_file_one(url ) local key = CUtils.GetKeyURLFileName(url) key = "m_"..key local crc = server_file[key] loaded_file[key] = crc save_loaded_file(loaded_file) end local function one_file_dow(url,bol) -- print(url," is down ",bol) if bol == false then print(url," download error ") else loaded = loaded + 1 set_progress_txt(string.format("网络资源加载中(消耗流量) %d/%d",loaded,all)) save_loaded_file_one(url) end end local function all_file_down(isdown) -- print("all file is down") FileHelper.ChangePersistentFileName(CUtils.GetFileName(UPDATED_TEMP_LIST_NAME),CUtils.GetFileName(UPDATED_LIST_NAME)) print("更新版本号!") FileHelper.ChangePersistentFileName(CUtils.GetFileName(VERSION_TEMP_FILE_NAME),CUtils.GetFileName(VERSION_FILE_NAME)) print("更新文件列表!") FileHelper.DeletePersistentFile(DOWANLOAD_TEMP_FILE)--删除零时文件 enterGame(true) print("all_file_down") Download.Dispose() end local function load_update_files(urls) local download = Download.instance -- print("host",host[1]) loaded_file = {} save_loaded_file(loaded_file) download:Init(host,2,one_file_dow,all_file_down) local file for k,v in pairs(urls) do file = v[1].."?"..v[2] download:Load(file,v[1]) end end local function load_server_file_list() --版本差异化对比 set_progress_txt("更新列表对比") local function on_server_comp(req) local bytes = req.data FileHelper.SavePersistentFile(bytes,CUtils.GetFileName(UPDATED_TEMP_LIST_NAME)) --保存server端临时文件 local ab = LuaHelper.LoadFromMemory(bytes) local text_asset = ab:LoadAsset(req.assetName) PLua.instance:SetRequire("file1",text_asset) -- Loader:clear(req.key) server_file=require("file1") local old_list_context = FileHelper.ReadPersistentFile(DOWANLOAD_TEMP_FILE) --读取上次加载未完成列表 local old_list = {} if old_list_context ~= nil then old_list = json.decode(old_list_context) end local item_url,crc_path local urls = {} for k,v in pairs(server_file) do if v~=local_file[k] then item_url =string.sub(k,3)..".u3d" local crc = old_list[k] --FileHelper.ComputeCrc32(crc_path) -- this is expensive if crc~=v then table.insert(urls,{item_url,v}) end end end all = #urls print("need update file count ",all) set_progress_txt(string.format("初始化网络 ")) if all>0 then load_update_files(urls) else enterGame() end end local function on_server_err(req) enterGame() end local function load_server( ... ) Loader:get_resource(UPDATED_LIST_NAME,nil,"System.Byte[]",on_server_comp,on_server_err,nil,host) end local function on_local_comp(req) local bytes = req.data.bytes PLua.instance:SetRequire("file",req.data) Loader:clear(req.key) local_file = require("file") load_server() end local function on_local_err(req) enterGame() end Loader:get_resource(UPDATED_LIST_NAME,nil,"UnityEngine.TextAsset",on_local_comp,on_local_err) end local function load_server_verion() --加载服务器版本号 local function on_err( req ) print("check_res on erro"..req.key,req.udKey,req.url,req.assetName,req.assetBundleName) enterGame() end local function on_comp( req ) -- print(req.url,"is onComplete") local server_ver = req.data[1] FileHelper.SavePersistentFile(tostring(server_ver),CUtils.GetFileName(VERSION_TEMP_FILE_NAME)) --临时文件 print(server_ver,ResVersion,VERSION_TEMP_FILE_NAME) if tonumber(server_ver) ~= ResVersion then load_server_file_list() else enterGame() end end Loader:get_resource(VERSION_FILE_NAME,nil,"System.String",on_comp,on_err,nil,host) end local function load_local_version() --加载本地版本号 local function onURLComp(req ) ResVersion=tonumber(req.data[1]) print("local ",ResVersion) load_server_verion() end local function onURLErComp(req ) -- load_server_verion() enterGame() end set_progress_txt("版本号对比中") Loader:get_resource(VERSION_FILE_NAME,nil,"System.String",onURLComp,onURLErComp) end local function init_frist() local ui_logo = LuaHelper.Find(FRIST_VIEW) _progressbar_txt = LuaHelper.GetComponentInChildren(ui_logo,"UnityEngine.UI.Text") set_progress_txt("初始化...") if Application.platform == RuntimePlatform.OSXEditor or Application.platform == RuntimePlatform.WindowsEditor then enterGame() else load_local_version() end end init_frist()
------------------------------------------------ -- Copyright © 2015-2016 Hugula: Arpg game Engine -- 检查资源 -- author pu ------------------------------------------------ require("core.loader") json = require "lib.json" local Hugula = Hugula local RuntimePlatform= UnityEngine.RuntimePlatform local Application= UnityEngine.Application local WWW = UnityEngine.WWW local GameObject = UnityEngine.GameObject local Request=LRequest local CUtils= Hugula.Utils.CUtils local LuaHelper=Hugula.Utils.LuaHelper local FileHelper=Hugula.Utils.FileHelper local PLua = Hugula.PLua local Download = Hugula.Update.Download local Loader = Loader ResVersion = 0 local _progressbar_txt; local FRIST_VIEW = "Logo" local VERSION_FILE_NAME = "crc32_ver.u3d" local VERSION_TEMP_FILE_NAME = "crc32_ver.tmp" local UPDATED_LIST_NAME = "crc32_file.u3d" local UPDATED_TEMP_LIST_NAME = "crc32_file.tmp" local DOWANLOAD_TEMP_FILE = "downloaded.tmp" local host = {"http://192.168.100.14/"..CUtils.GetAssetPath("").."/","http://192.168.100.114/"..CUtils.GetAssetPath("").."/"} --更新列表 --local fristView local all,loaded = 0,0 local local_file,server_file,loaded_file local function set_progress_txt(text) if _progressbar_txt then _progressbar_txt.text = text end end local function enterGame(need_reload) local function to_begin( ... ) require("begin") end local function load_manifest( ... ) Loader:refresh_assetbundle_manifest(to_begin) end if need_reload == true then set_progress_txt("刷新脚本") PLua.instance:LoadBundle(load_manifest) else set_progress_txt("进入游戏") load_manifest() end end local function save_loaded_file(loaded_list) local context = json.encode(loaded_list) local old_list_context = FileHelper.SavePersistentFile(context,DOWANLOAD_TEMP_FILE) --读取上次加载未完成列表 end local function save_loaded_file_one(url ) local key = CUtils.GetKeyURLFileName(url) key = "m_"..key local crc = server_file[key] loaded_file[key] = crc save_loaded_file(loaded_file) end local function one_file_dow(url,bol) -- print(url," is down ",bol) if bol == false then print(url," download error ") else loaded = loaded + 1 set_progress_txt(string.format("网络资源加载中(消耗流量) %d/%d",loaded,all)) save_loaded_file_one(url) end end local function all_file_down(isdown) -- print("all file is down") FileHelper.DeletePersistentFile(CUtils.GetFileName(UPDATED_LIST_NAME)) --删除旧文件 FileHelper.DeletePersistentFile(CUtils.GetFileName(VERSION_FILE_NAME)) --删除旧文件 FileHelper.ChangePersistentFileName(CUtils.GetFileName(UPDATED_TEMP_LIST_NAME),CUtils.GetFileName(UPDATED_LIST_NAME)) print("更新版本号!") FileHelper.ChangePersistentFileName(CUtils.GetFileName(VERSION_TEMP_FILE_NAME),CUtils.GetFileName(VERSION_FILE_NAME)) print("更新文件列表!") FileHelper.DeletePersistentFile(DOWANLOAD_TEMP_FILE)--删除零时文件 enterGame(true) print("all_file_down") Download.Dispose() end local function load_update_files(urls) local download = Download.instance -- print("host",host[1]) loaded_file = {} save_loaded_file(loaded_file) download:Init(host,2,one_file_dow,all_file_down) local file for k,v in pairs(urls) do file = v[1].."?"..v[2] print(file) download:Load(file,v[1]) end end local function load_server_file_list() --版本差异化对比 set_progress_txt("更新列表对比") local function on_server_comp(req) local bytes = req.data FileHelper.SavePersistentFile(bytes,CUtils.GetFileName(UPDATED_TEMP_LIST_NAME)) --保存server端临时文件 local ab = LuaHelper.LoadFromMemory(bytes) local text_asset = ab:LoadAsset(req.assetName) PLua.instance:SetRequire("file1",text_asset) -- Loader:clear(req.key) server_file=require("file1") local old_list_context = FileHelper.ReadPersistentFile(DOWANLOAD_TEMP_FILE) --读取上次加载未完成列表 local old_list = {} if old_list_context ~= nil then old_list = json.decode(old_list_context) end local item_url,crc_path local urls = {} for k,v in pairs(server_file) do if v~=local_file[k] then item_url =string.sub(k,3)..".u3d" local crc = old_list[k] --FileHelper.ComputeCrc32(crc_path) -- this is expensive if crc~=v then table.insert(urls,{item_url,v}) end end end all = #urls print("need update file count ",all) set_progress_txt(string.format("初始化网络 ")) if all>0 then load_update_files(urls) else enterGame() end end local function on_server_err(req) enterGame() end local function load_server( ... ) Loader:get_resource(UPDATED_LIST_NAME,nil,"System.Byte[]",on_server_comp,on_server_err,nil,host) end local function on_local_comp(req) local bytes = req.data.bytes PLua.instance:SetRequire("file",req.data) Loader:clear(req.key) local_file = require("file") load_server() end local function on_local_err(req) enterGame() end Loader:get_resource(UPDATED_LIST_NAME,nil,"UnityEngine.TextAsset",on_local_comp,on_local_err) end local function load_server_verion() --加载服务器版本号 local function on_err( req ) print("check_res on erro"..req.key,req.udKey,req.url,req.assetName,req.assetBundleName) enterGame() end local function on_comp( req ) -- print(req.url,"is onComplete") local server_ver = req.data[1] FileHelper.SavePersistentFile(tostring(server_ver),CUtils.GetFileName(VERSION_TEMP_FILE_NAME)) --临时文件 print(server_ver,ResVersion,VERSION_TEMP_FILE_NAME) if tonumber(server_ver) ~= ResVersion then load_server_file_list() else enterGame() end end Loader:get_resource(VERSION_FILE_NAME,nil,"System.String",on_comp,on_err,nil,host) end local function load_local_version() --加载本地版本号 local function onURLComp(req ) ResVersion=tonumber(req.data[1]) load_server_verion() end local function onURLErComp(req ) -- load_server_verion() enterGame() end set_progress_txt("版本号对比中") Loader:get_resource(VERSION_FILE_NAME,nil,"System.String",onURLComp,onURLErComp) end local function init_frist() local ui_logo = LuaHelper.Find(FRIST_VIEW) _progressbar_txt = LuaHelper.GetComponentInChildren(ui_logo,"UnityEngine.UI.Text") set_progress_txt("初始化...") if Application.platform == RuntimePlatform.OSXEditor or Application.platform == RuntimePlatform.WindowsEditor then enterGame() else load_local_version() end end init_frist()
改名时候重名bug修复。
改名时候重名bug修复。
Lua
mit
tenvick/hugula,tenvick/hugula,tenvick/hugula,tenvick/hugula,tenvick/hugula,tenvick/hugula,tenvick/hugula
27cc59360dca2f456c4200d0a753fc2c41d05258
deps/childprocess.lua
deps/childprocess.lua
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] exports.name = "luvit/childprocess" exports.version = "1.0.5-1" exports.dependencies = { "luvit/[email protected]", "luvit/[email protected]", "luvit/[email protected]", } exports.license = "Apache 2" exports.homepage = "https://github.com/luvit/luvit/blob/master/deps/childprocess.lua" exports.description = "A port of node.js's childprocess module for luvit." exports.tags = {"luvit", "spawn", "process"} local core = require('core') local net = require('net') local timer = require('timer') local uv = require('uv') local Error = core.Error local Process = core.Emitter:extend() function Process:initialize(stdin, stdout, stderr) self.stdout = stdout self.stdin = stdin self.stderr = stderr end function Process:setHandle(handle) self.handle = handle end function Process:setPid(pid) self.pid = pid end function Process:kill(signal) if self.handle and not uv.is_closing(self.handle) then uv.process_kill(self.handle, signal or 'sigterm') end self:close(Error:new('killed')) end function Process:close(err) if self.handle and not uv.is_closing(self.handle) then uv.close(self.handle) end self:destroy(err) end function Process:destroy(err) self:_cleanup(err) if err then timer.setImmediate(function() self:emit('error', err) end) end end function Process:_cleanup(err) if self.stdout then if err then self.stdout:destroy(err) else self.stdout:once('end', function() self.stdout:destroy(err) end) self.stdout:resume() end end if self.stderr then self.stderr:destroy(err) end if self.stdin then self.stdin:destroy(err) end end local function spawn(command, args, options) local envPairs = {} local em, onExit, handle, pid local stdout, stdin, stderr, stdio args = args or {} options = options or {} options.detached = options.detached or false if options.env then for k, v in pairs(options.env) do table.insert(envPairs, k .. '=' .. v) end end if options.stdio then stdio = {} stdin = options.stdio[1] stdout = options.stdio[2] stderr = options.stdio[3] stdio[1] = options.stdio[1] and options.stdio[1]._handle stdio[2] = options.stdio[2] and options.stdio[2]._handle stdio[3] = options.stdio[3] and options.stdio[3]._handle else stdin = net.Socket:new({ handle = uv.new_pipe(false) }) stdout = net.Socket:new({ handle = uv.new_pipe(false) }) stderr = net.Socket:new({ handle = uv.new_pipe(false) }) stdio = { stdin._handle, stdout._handle, stderr._handle} end function onExit(code, signal) if signal then em.signal = signal else em.exitCode = code end em:emit('exit', code, signal) em:close() end handle, pid = uv.spawn(command, { cwd = options.cwd or nil, stdio = stdio, args = args, env = envPairs, detached = options.detached, uid = options.uid, gid = options.gid }, onExit) em = Process:new(stdin, stdout, stderr) em:setHandle(handle) em:setPid(pid) if em.handle == nil then timer.setImmediate(function() em:emit('exit', -127) em:destroy(Error:new(pid)) end) end return em end exports.spawn = spawn
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] exports.name = "luvit/childprocess" exports.version = "1.0.5-1" exports.dependencies = { "luvit/[email protected]", "luvit/[email protected]", "luvit/[email protected]", } exports.license = "Apache 2" exports.homepage = "https://github.com/luvit/luvit/blob/master/deps/childprocess.lua" exports.description = "A port of node.js's childprocess module for luvit." exports.tags = {"luvit", "spawn", "process"} local core = require('core') local net = require('net') local timer = require('timer') local uv = require('uv') local Error = core.Error local Process = core.Emitter:extend() function Process:initialize(stdin, stdout, stderr) self.stdout = stdout self.stdin = stdin self.stderr = stderr end function Process:setHandle(handle) self.handle = handle end function Process:setPid(pid) self.pid = pid end function Process:kill(signal) if self.handle and not uv.is_closing(self.handle) then uv.process_kill(self.handle, signal or 'sigterm') end end function Process:close(err) if self.handle and not uv.is_closing(self.handle) then uv.close(self.handle) end self:destroy(err) end function Process:destroy(err) self:_cleanup(err) if err then timer.setImmediate(function() self:emit('error', err) end) end end function Process:_cleanup(err) if self.stdout then if err then self.stdout:destroy(err) else self.stdout:once('end', function() self.stdout:destroy(err) end) self.stdout:resume() end end if self.stderr then self.stderr:destroy(err) end if self.stdin then self.stdin:destroy(err) end end local function spawn(command, args, options) local envPairs = {} local em, onExit, handle, pid local stdout, stdin, stderr, stdio args = args or {} options = options or {} options.detached = options.detached or false if options.env then for k, v in pairs(options.env) do table.insert(envPairs, k .. '=' .. v) end end if options.stdio then stdio = {} stdin = options.stdio[1] stdout = options.stdio[2] stderr = options.stdio[3] stdio[1] = options.stdio[1] and options.stdio[1]._handle stdio[2] = options.stdio[2] and options.stdio[2]._handle stdio[3] = options.stdio[3] and options.stdio[3]._handle else stdin = net.Socket:new({ handle = uv.new_pipe(false) }) stdout = net.Socket:new({ handle = uv.new_pipe(false) }) stderr = net.Socket:new({ handle = uv.new_pipe(false) }) stdio = { stdin._handle, stdout._handle, stderr._handle} end function onExit(code, signal) if signal then em.signal = signal else em.exitCode = code end em:emit('exit', code, signal) em:close() end handle, pid = uv.spawn(command, { cwd = options.cwd or nil, stdio = stdio, args = args, env = envPairs, detached = options.detached, uid = options.uid, gid = options.gid }, onExit) em = Process:new(stdin, stdout, stderr) em:setHandle(handle) em:setPid(pid) if em.handle == nil then timer.setImmediate(function() em:emit('exit', -127) em:destroy(Error:new(pid)) end) end return em end exports.spawn = spawn
fix(childprocess): do not prematurely close the handle
fix(childprocess): do not prematurely close the handle
Lua
apache-2.0
bsn069/luvit,zhaozg/luvit,bsn069/luvit,bsn069/luvit,kaustavha/luvit,kaustavha/luvit,luvit/luvit,kaustavha/luvit,luvit/luvit,zhaozg/luvit
835d644aebb532cdcabff3b98b2d2e2735b44845
jam_bo_ree.lua
jam_bo_ree.lua
if os.getenv('IS_DEV') require 'pl.strict' local setmetatable = setmetatable local print = print local stringx = require 'pl.stringx' local sip = require 'pl.sip' local pl_utils = require 'pl.utils' local _ = require 'underscore' local M = {} local meta = {} local WHITE = "%s+"; -- ================================================================ -- ================== Helpers ===================================== -- ================================================================ local function canon_name(str) return string.gsub(stringx.strip(string.upper(str)), WHITE, " ") end -- ----------------------------------------- -- Clear globals. -------------------------- -- ----------------------------------------- setfenv(1, {}) -- ----------------------------------------- -- ================================================================ -- ================== Jam Bo Ree ================================== -- ================================================================ meta = { on = function (self, raw_name, func) local name = canon_name(raw_name) if not self.events[name] then self.events[name] = {} end local list = self.events[name] list[#list+1] = func return self end, events_for = function (self, raw_name) name = canon_name(raw_name) return self.events[name]; end, run = function (self, ...) -- get all funcs we need local funcs = _.map({...}, function (v) if pl_utils.is_type(v, 'string') then return self:events_for(v) else -- let's assume it's a func return v end end) _.each(_.flatten(funcs), function (f) f(); end); return self end, list = function (self, raw_name, create_if_needed) local o = self; local name = canon_name(raw_name); if (not o.funcs[name]) and create_if_needed then o.funcs[name] = {}; end return o.funcs[name] || []; end, entire_list_for = function (self, name) local arr = { self:list_with_includes('before ' + name), self:list_with_includes(name), self:list_with_includes('after ' + name) } return _.flatten(arr); end, list_with_includes = function (self, raw_name) local me = self; local arr = {}; _.push(arr, _.map(me.includes, function (t) if (t == me) then return t:list(raw_name) else return t:list_with_includes(raw_name) end end)); return _.flatten(arr); end, run_error = function (self, ...) local args = {...} local tasks = {} if (#self:entire_list_for(args[1]) == 0) then throw new Error("Error handlers not found for: " + args[1]) end return self:run(unpack(args)) end, on = function (self, ...) local args = {...} local func = _.pop(args) _.each(args, function (name) _.push(self:list(name, true), func); end); return me; end, run = function (self, ...) local args = {...} local funcs = _.select(args, function (u) return _.isString(u) or _.isFunction(u) end) local str_funcs = _.select(funcs, function (u) return _.isString(u) end); local parent = _.detect(args, function (u) return u && u.is_task_env end); local non_data = _.flatten({funcs, parent}); -- === grab and merge data objects === local data = nil _.each(args, function (u) if (_.isObject(u) && _.indexOf(non_data, u) < 1 && !u.is_task_env) then if not data then data = u else _.extend(data, u) end end end); --[[ // if non string names, only funcs: // Example: // .run(parent, {}, func1, func2); // .run(parent, func1, func2); // ]]-- if (str_funcs.length === 0) then local t = M.new() local name = 'one-off' _.each(funcs, function (f) t:on(name, f); end); return t:run(unpack(_.compact({parent, name, data}))); end -- ==== if Run.new(self, parent, (data || {}), funcs):run() return self end -- .run ----------------------- } function M.new(...) local new = {} setmetatable(new, {__index = meta}); new.events = {}; new.includes = {new}; local args = {...} if (#args > 0) then _.each(_.flatten(_.reverse(args), function (v) _.unshift(t.includes, v) end)) t.includes = _.uniq(t.includes) end return new end -- ================================================================ -- ================== Run (private) =============================== -- ================================================================ local Run = {} function Run.do_next(self, ...) local args = {...} if (#args == 1) self.val = args[1]; self.last = args[1]; local _next = _.shift(me.tasks) if _next then _next(Task_Env.new(self), self.last); else self.is_done = true if self.parent then return self.parent:finish(last) end end return me; end function Run.run(self) if (self.tasks) then throw new Error("Already running."); end self.tasks = {} if (!self.parent) then _.push( self.tasks, self.tally:list('parent run') ) end _.each(self.proc_list, function (name) if (_.isFunction(name)) then return _.push(self.tasks, name); end _.push(self.tasks, self.tally:entire_list_for(name)); end) self.tasks = _.flatten(self.tasks); self:do_next(); return end function Run.new(tally, parent, init_data, arr) local r = { tally = tally, parent = parent data = init_data } setmetatable(r, {__index = Run}) r.proc_list = _.map(arr, function (n) if (_.isString(n)) then return canon_name(n) end return n end); return r; end -- ================================================================ -- ================== Task_Env (private) ========================== -- ================================================================ local Task_Env = {} Task_Env.new = function (run) local t = {} setmetatable(t, {__index = Task_Env}) t.run = run t.data = run.data t.last = run.last t.val = run.val t.is_task_env = true return t end function Task_Env.finish (self, ...) local args = {...} local name_or_val = select(1, ...) local err = select(2, err) if (self.is_done || self.run.is_done) then throw new Error(".finish called more than once.") end self.is_done = true -- if .finish(name, err); if (#args > 1) then -- error if (self.run.parent) then return self.run.parent:finish(name_or_val, err) else return self.run.tally:run_error(name_or_val, self.data, {error: err}) end end return self.run:do_next(unpack(args)) end function Task_Env.detour (self, ...) local args = {...} _.unshift( args, self ) _.unshift( args, self.data ) return self.run.tally:run(unpack(args)); end -- ==================================================== M.canon_name = canon_name; return M -- ====================================================
local setmetatable = setmetatable local print = print local stringx = require 'pl.stringx' local sip = require 'pl.sip' local pl_utils = require 'pl.utils' local _ = require 'underscore' local M = {} local meta = {} local WHITE = "%s+"; -- ================================================================ -- ================== Helpers ===================================== -- ================================================================ local function canon_name(str) return string.gsub(stringx.strip(string.upper(str)), WHITE, " ") end -- ----------------------------------------- -- Clear globals. -------------------------- -- ----------------------------------------- setfenv(1, {}) -- ----------------------------------------- -- ================================================================ -- ================== Jam Bo Ree ================================== -- ================================================================ meta = { on = function (self, raw_name, func) local name = canon_name(raw_name) if not self.events[name] then self.events[name] = {} end local list = self.events[name] list[#list+1] = func return self end, events_for = function (self, raw_name) name = canon_name(raw_name) return self.events[name]; end, run = function (self, ...) -- get all funcs we need local funcs = _.map({...}, function (v) if pl_utils.is_type(v, 'string') then return self:events_for(v) else -- let's assume it's a func return v end end) _.each(_.flatten(funcs), function (f) f(); end); return self end, list = function (self, raw_name, create_if_needed) local o = self; local name = canon_name(raw_name); if (not o.events[name]) and create_if_needed then o.events[name] = {}; end return o.events[name] or {} end, entire_list_for = function (self, name) local arr = { self:list_with_includes('before ' + name), self:list_with_includes(name), self:list_with_includes('after ' + name) } return _.flatten(arr); end, list_with_includes = function (self, raw_name) local me = self; local arr = {}; _.push(arr, _.map(me.includes, function (t) if (t == me) then return t:list(raw_name) else return t:list_with_includes(raw_name) end end)); return _.flatten(arr); end, run_error = function (self, ...) local args = {...} local tasks = {} if (#self:entire_list_for(args[1]) == 0) then error("Error handlers not found for: " + args[1]) end return self:run(unpack(args)) end, on = function (self, ...) local args = {...} local func = _.pop(args) _.each(args, function (name) _.push(self:list(name, true), func); end); return me; end, run = function (self, ...) local args = {...} local funcs = _.select(args, function (u) return _.isString(u) or _.isFunction(u) end) local str_funcs = _.select(funcs, function (u) return _.isString(u) end); local parent = _.detect(args, function (u) return u and u.is_task_env end); local non_data = _.flatten({funcs, parent}); -- === grab and merge data objects === local data = nil _.each(args, function (u) if (_.isObject(u) and _.indexOf(non_data, u) < 1 and not u.is_task_env) then if not data then data = u else _.extend(data, u) end end end); --[[ // if non string names, only funcs: // Example: // .run(parent, {}, func1, func2); // .run(parent, func1, func2); // ]]-- if (str_funcs.length == 0) then local t = M.new() local name = 'one-off' _.each(funcs, function (f) t:on(name, f); end); return t:run(unpack(_.compact({parent, name, data}))); end -- ==== if Run.new(self, parent, (data or {}), funcs):run() return self end -- .run ----------------------- } function M.new(...) local new = {} setmetatable(new, {__index = meta}); new.events = {}; new.includes = {new}; local args = {...} if (#args > 0) then _.each(_.flatten(_.reverse(args), function (v) _.unshift(t.includes, v) end)) t.includes = _.uniq(t.includes) end return new end -- ================================================================ -- ================== Run (private) =============================== -- ================================================================ local Run = {} function Run.do_next(self, ...) local args = {...} if (#args == 1) then self.val = args[1] end self.last = args[1]; local _next = _.shift(me.tasks) if _next then _next(Task_Env.new(self), self.last); else self.is_done = true if self.parent then return self.parent:finish(last) end end return me; end function Run.run(self) if (self.tasks) then error("Already running."); end self.tasks = {} if not self.parent then _.push( self.tasks, self.tally:list('parent run') ) end _.each(self.proc_list, function (name) if (_.isFunction(name)) then return _.push(self.tasks, name); end _.push(self.tasks, self.tally:entire_list_for(name)); end) self.tasks = _.flatten(self.tasks); self:do_next(); return end function Run.new(tally, parent, init_data, arr) local r = { tally = tally, parent = parent, data = init_data } setmetatable(r, {__index = Run}) r.proc_list = _.map(arr, function (n) if (_.isString(n)) then return canon_name(n) end return n end); return r; end -- ================================================================ -- ================== Task_Env (private) ========================== -- ================================================================ local Task_Env = {} Task_Env.new = function (run) local t = {} setmetatable(t, {__index = Task_Env}) t.run = run t.data = run.data t.last = run.last t.val = run.val t.is_task_env = true return t end function Task_Env.finish (self, ...) local args = {...} local name_or_val = select(1, ...) local err = select(2, err) if (self.is_done or self.run.is_done) then error(".finish called more than once.") end self.is_done = true -- if .finish(name, err); if (#args > 1) then -- error if (self.run.parent) then return self.run.parent:finish(name_or_val, err) else return self.run.tally:run_error(name_or_val, self.data, {error=err}) end end return self.run:do_next(unpack(args)) end function Task_Env.detour (self, ...) local args = {...} _.unshift( args, self ) _.unshift( args, self.data ) return self.run.tally:run(unpack(args)); end -- ==================================================== M.canon_name = canon_name; return M -- ====================================================
Various fixes.
Various fixes.
Lua
mit
da99/jam_bo_ree
50a5f4f08d3cba6fea8a215baff82b5231585853
libs/rules.lua
libs/rules.lua
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local ffi = require('ffi') local log = require('log').log local pathJoin = require('luvi').path.join local modes = require('git').modes local quotepattern = '['..("%^$().[]*+-?"):gsub("(.)", "%%%1")..']' -- When importing into the db to publish, we want to include binaries for all -- platforms, but when installing to disk or zip app bundle, we want native only. local patterns = { -- Rough translation of (Linux|Windows|OSX|BSD) and (x86|x64|arm) -- This is more liberal than it needs to be, but works mostly in practice. all = {"[LWOB][iS][nXD][uxdows]*", "[xa][86r][64m]"}, native = {ffi.os, ffi.arch}, } function exports.compileFilter(path, rules, nativeOnly) assert(#rules > 0, "Empty files rule list not allowed") local os, arch = unpack(patterns[nativeOnly and "native" or "all"]) for i = 1, #rules do local skip, pattern = rules[i]:match("(!*)(.*)") local parts = {} for glob, text in pattern:gmatch("(%**)([^%*]*)") do if #glob == 1 then parts[#parts + 1] = "[^\\/]*" elseif #glob > 1 then parts[#parts + 1] = ".*" end if #text > 0 then parts[#parts + 1] = text:gsub(quotepattern, "%%%1"):gsub("/", "[/\\]") end end pattern = table.concat(parts):gsub("%%%$OS", os):gsub("%%%$ARCH", arch) rules[i] = { allowed = #skip == 0, pattern = "^" .. pattern .. "$" } end local default = not rules[1].allowed if default then log("compiling filter", path .. "/** includes by default (first rule is negative)") else log("compiling filter", path .. "/** excludes by default (first rule is positive)") end return { default = default, prefix = "^" .. pathJoin(path:gsub(quotepattern, "%%%1"), '(.*)'), match = function (path) local allowed for i = 1, #rules do local rule = rules[i] if path:match(rule.pattern) then allowed = rule.allowed end end return allowed, path end } end local compileFilter = exports.compileFilter function exports.isAllowed(path, entry, filters) -- Ignore all hidden files and folders always. local allow, subPath, default default = true for i = 1, #filters do local filter = filters[i] local newPath = path:match(filter.prefix) if newPath then default = filter.default local newAllow = filter.match(newPath) if newAllow ~= nil then subPath = newPath allow = newAllow end end end local isTree = entry.type == "directory" or entry.mode == modes.tree if allow == nil then -- If nothing matched, fall back to defaults if entry.name:match("^%.") then -- Skip hidden files. allow = false elseif isTree then -- Walk all trees except deps allow = entry.name ~= "deps" else allow = default end end if subPath then if not isTree then log("including", subPath) elseif not allow then log("skipping", subPath) end end return allow, default, subPath end local isAllowed = exports.isAllowed function exports.filterTree(db, path, hash, rules, nativeOnly) --> hash local filters = {} if rules and #rules > 0 then filters[#filters + 1] = compileFilter(path, rules, nativeOnly) end local function copyTree(path, hash) local tree = db.loadAs("tree", hash) local meta for i = 1, #tree do local entry = tree[i] if entry.name == "package.lua" then if modes.isFile(entry.mode) then local lua = db.loadAs("blob", entry.hash) meta = assert(loadstring(lua, pathJoin(path, "package.lua")))() end break end end if meta and meta.files then filters[#filters + 1] = compileFilter(path, meta.files, nativeOnly) end local changed = false for i = #tree, 1, -1 do local entry = tree[i] local fullPath = pathJoin(path, entry.name) if isAllowed(fullPath, entry, filters) then if entry.mode == modes.tree then local newHash = copyTree(fullPath, entry.hash) if newHash ~= entry.hash then if newHash then entry.hash = newHash else table.remove(tree, i) end changed = true end end else changed = true table.remove(tree, i) end end return not changed and hash or #tree > 0 and db.saveAs("tree", tree) end return copyTree(path, hash) end
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local ffi = require('ffi') local log = require('log').log local pathJoin = require('luvi').path.join local modes = require('git').modes local quotepattern = '['..("%^$().[]*+-?"):gsub("(.)", "%%%1")..']' -- When importing into the db to publish, we want to include binaries for all -- platforms, but when installing to disk or zip app bundle, we want native only. local patterns = { -- Rough translation of (Linux|Windows|OSX|BSD) and (x86|x64|arm) -- This is more liberal than it needs to be, but works mostly in practice. all = {"[LWOB][iS][nXD][uxdows]*", "[xa][86r][64m]"}, native = {ffi.os, ffi.arch}, } function exports.compileFilter(path, rules, nativeOnly) assert(#rules > 0, "Empty files rule list not allowed") local os, arch = unpack(patterns[nativeOnly and "native" or "all"]) for i = 1, #rules do local skip, pattern = rules[i]:match("(!*)(.*)") local parts = {} for glob, text in pattern:gmatch("(%**)([^%*]*)") do if #glob == 1 then parts[#parts + 1] = "[^\\/]*" elseif #glob > 1 then parts[#parts + 1] = ".*" end if #text > 0 then parts[#parts + 1] = text:gsub(quotepattern, "%%%1"):gsub("/", "[/\\]") end end pattern = table.concat(parts):gsub("%%%$OS", os):gsub("%%%$ARCH", arch) rules[i] = { allowed = #skip == 0, pattern = "^" .. pattern .. "$" } end local default = not rules[1].allowed if default then log("compiling filter", path .. "/** includes by default (first rule is negative)") else log("compiling filter", path .. "/** excludes by default (first rule is positive)") end return { default = default, prefix = "^" .. pathJoin(path:gsub(quotepattern, "%%%1"), '(.*)'), match = function (path) local allowed for i = 1, #rules do local rule = rules[i] if path:match(rule.pattern) then allowed = rule.allowed end end return allowed, path end } end local compileFilter = exports.compileFilter function exports.isAllowed(path, entry, filters) -- Ignore all hidden files and folders always. local allow, matchesFilter, default, relativePath default = true for i = 1, #filters do local filter = filters[i] relativePath = path:match(filter.prefix) if relativePath then default = filter.default local newAllow = filter.match(relativePath) if newAllow ~= nil then matchesFilter = true allow = newAllow end end end local isTree = entry.type == "directory" or entry.mode == modes.tree if allow == nil then -- If nothing matched, fall back to defaults if entry.name:match("^%.") then -- Skip hidden files. allow = false elseif isTree then -- Walk all trees except deps allow = entry.name ~= "deps" else allow = default end end if allow and not isTree then log("including", relativePath) elseif not allow and matchesFilter then log("skipping", relativePath) end return allow, default, matchesFilter and relativePath end local isAllowed = exports.isAllowed function exports.filterTree(db, path, hash, rules, nativeOnly) --> hash local filters = {} if rules and #rules > 0 then filters[#filters + 1] = compileFilter(path, rules, nativeOnly) end local function copyTree(path, hash) local tree = db.loadAs("tree", hash) local meta for i = 1, #tree do local entry = tree[i] if entry.name == "package.lua" then if modes.isFile(entry.mode) then local lua = db.loadAs("blob", entry.hash) meta = assert(loadstring(lua, pathJoin(path, "package.lua")))() end break end end if meta and meta.files then filters[#filters + 1] = compileFilter(path, meta.files, nativeOnly) end local changed = false for i = #tree, 1, -1 do local entry = tree[i] local fullPath = pathJoin(path, entry.name) if isAllowed(fullPath, entry, filters) then if entry.mode == modes.tree then local newHash = copyTree(fullPath, entry.hash) if newHash ~= entry.hash then if newHash then entry.hash = newHash else table.remove(tree, i) end changed = true end end else changed = true table.remove(tree, i) end end return not changed and hash or #tree > 0 and db.saveAs("tree", tree) end return copyTree(path, hash) end
Fix files included by default not showing up in the log * Closes #111
Fix files included by default not showing up in the log * Closes #111
Lua
apache-2.0
zhaozg/lit,luvit/lit,squeek502/lit,1yvT0s/lit,kidaa/lit,james2doyle/lit
0d46ef4d45a39f5c5f0d8d7a5b340990d51badab
src/game/StarterPlayer/StarterCharacterScripts/TriggerListening.lua
src/game/StarterPlayer/StarterCharacterScripts/TriggerListening.lua
-- ClassName: LocalScript --[[ Handles user interaction with triggers. The server code explains what a trigger is, you can find it in: game.ServerScriptService.TriggerHandling This script connects all of the triggers to events that then allow the player to "interact" with the game world by the user of ContextActionService. Each trigger has a "TriggerData" module inside of it, which currently is only used to define a `firedEvent` property. This is the name of a RemoteEvent that gets fired when the user interacts. From there the server takes care of what happens next. For example, if you're in the trigger right outside the Wave Station, the server will teleport you to the Sky Wave. --]] local players = game:GetService("Players") local contextAction = game:GetService("ContextActionService") local replicatedStorage = game:GetService("ReplicatedStorage") local ACTION_NAME = "Interact" local ACTION_KEY = Enum.KeyCode.E local remotes = require(replicatedStorage.Events.Remotes) local getTriggers = remotes.getFunction("GetInteractionTriggers") local triggerAdded = remotes.getEvent("TriggerAdded") local triggerRemoved = remotes.getEvent("TriggerRemoved") local player = players.LocalPlayer -- Checks if `part` is the clients HumanoidRootPart. -- -- This is used when checking what touched the trigger so that we only have to -- worry about a single part and none of the other limbs/hats. local function isClientsRootPart(part) return part == player.Character.HumanoidRootPart end -- Fires the event that was set for `trigger`. local function runTriggerEvent(trigger) local triggerData = require(trigger.TriggerData) local event = remotes.getEvent(triggerData.firedEvent) event:FireServer() end -- Fired when the trigger is touched. -- -- This is what sets up the interaction code so the player can actually interact -- with the triggers. local function onTriggerTouched(trigger, otherPart) if isClientsRootPart(otherPart) then local function action(_, inputState) if inputState == Enum.UserInputState.End then return end runTriggerEvent(trigger) end contextAction:BindAction(ACTION_NAME, action, true, ACTION_KEY) end end -- Fired when the player leaves the trigger. -- -- Simply unbinds the event so the player can't interact anymore. -- -- BUG: If the player is teleported out of the trigger, this will not fire. So -- currently we have a pretty big problem of the player being able to -- continuously interact even when they're on the Sky Wave, thus teleporting -- them back to the teleport pad. -- -- This will be removed or reworked to function properly in the future. Right -- now its being kept because it /kinda/ works, and we just need to get all -- these interaction changes commited. local function onTriggerTouchEnded(_, otherPart) if isClientsRootPart(otherPart) then contextAction:UnbindAction(ACTION_NAME) end end -- Hooks up all the events for a trigger. -- -- We have to pass in an anonymous function because we need the trigger later -- on down the line when we get to user itneraction. local function connectTriggerEvents(trigger) trigger.Touched:connect(function(...) onTriggerTouched(trigger, ...) end) trigger.TouchEnded:connect(function(...) onTriggerTouchEnded(trigger, ...) end) end -- Simple loop to connect all of the existing triggers. local function connectExistingTriggers() local triggers = getTriggers:InvokeServer() for _, trigger in ipairs(triggers) do connectTriggerEvents(trigger) end end -- Connects any new triggers that get added. local function connectNewTriggers() triggerAdded.OnClientEvent:connect(function(addedTrigger) connectTriggerEvents(addedTrigger) end) end connectExistingTriggers() connectNewTriggers()
-- ClassName: LocalScript --[[ Handles user interaction with triggers. The server code explains what a trigger is, you can find it in: game.ServerScriptService.TriggerHandling This script connects all of the triggers to events that then allow the player to "interact" with the game world by the user of ContextActionService. Each trigger has a "TriggerData" module inside of it, which currently is only used to define a `firedEvent` property. This is the name of a RemoteEvent that gets fired when the user interacts. From there the server takes care of what happens next. For example, if you're in the trigger right outside the Wave Station, the server will teleport you to the Sky Wave. --]] local players = game:GetService("Players") local contextAction = game:GetService("ContextActionService") local replicatedStorage = game:GetService("ReplicatedStorage") local run = game:GetService("RunService") local ACTION_NAME = "Interact" local ACTION_KEY = Enum.KeyCode.E local remotes = require(replicatedStorage.Events.Remotes) local Region = require(replicatedStorage.Regions.Region) local getTriggers = remotes.getFunction("GetInteractionTriggers") local triggerAdded = remotes.getEvent("TriggerAdded") local triggerRemoved = remotes.getEvent("TriggerRemoved") local player = players.LocalPlayer local character = player.Character local rootPart = character:FindFirstChild("HumanoidRootPart") -- Checks if `part` is the clients HumanoidRootPart. -- -- This is used when checking what touched the trigger so that we only have to -- worry about a single part and none of the other limbs/hats. local function isClientsRootPart(part) return part == rootPart end -- Checks if the player is within the given region. local function playerIsInRegion(region) return region:CastPart(rootPart) end -- Fires the event that was set for `trigger`. local function runTriggerEvent(trigger) local triggerData = require(trigger.TriggerData) local event = remotes.getEvent(triggerData.firedEvent) event:FireServer() end -- Unbinds the interaction action if the player is outside of `region`. -- -- This is used to make sure the player is still inside of the trigger. Once -- they're not we need to unbind the action so they can't interact from across -- the map. -- -- Previously we were using the TouchEnded event instead of a region loop. This -- almost satisfied our needs, but it had a very big problem where if you -- teleport the user outside of the trigger, TouchEnded wouldn't fire. -- -- This left the interact action still bound, so the client could teleport to -- the Wave Road from any location. We're now using a region check to be -- absolutely sure if the player is still inside the trigger or not. local function unbindIfOutOfRegion(region) local conn conn = run.Heartbeat:connect(function() if not playerIsInRegion(region) then contextAction:UnbindAction(ACTION_NAME) conn:disconnect() end end) end -- Hooks up all the events for a trigger. -- -- We have to pass in an anonymous function because we need the trigger later -- on down the line when we get to user itneraction. local function connectTriggerEvents(trigger) local region = Region.FromPart(trigger) local function action(_, inputState) if inputState == Enum.UserInputState.End then return end runTriggerEvent(trigger) end trigger.Touched:connect(function(otherPart) if isClientsRootPart(otherPart) then contextAction:BindAction(ACTION_NAME, action, true, ACTION_KEY) unbindIfOutOfRegion(region) end end) end -- Simple loop to connect all of the existing triggers. local function connectExistingTriggers() local triggers = getTriggers:InvokeServer() for _, trigger in ipairs(triggers) do connectTriggerEvents(trigger) end end -- Connects any new triggers that get added. local function connectNewTriggers() triggerAdded.OnClientEvent:connect(function(addedTrigger) connectTriggerEvents(addedTrigger) end) end connectExistingTriggers() connectNewTriggers()
Fix the interact action still being bound after teleporting
Fix the interact action still being bound after teleporting This issue was talked about in commit 1882b20 in "known bugs".
Lua
mit
VoxelDavid/echo-ridge
82c052ceecb59e2023c4b6f336e0db9423529a02
batteryarc-widget/batteryarc.lua
batteryarc-widget/batteryarc.lua
------------------------------------------------- -- Battery Arc Widget for Awesome Window Manager -- Shows the battery level of the laptop -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/batteryarc-widget -- @author Pavel Makhov -- @copyright 2019 Pavel Makhov ------------------------------------------------- local awful = require("awful") local beautiful = require("beautiful") local naughty = require("naughty") local wibox = require("wibox") local watch = require("awful.widget.watch") local HOME = os.getenv("HOME") local text = wibox.widget { id = "txt", font = "Play 6", widget = wibox.widget.textbox } local text_with_background = wibox.container.background(text) local batteryarc = wibox.widget { text_with_background, max_value = 1, rounded_edge = true, thickness = 2, start_angle = 4.71238898, -- 2pi*3/4 forced_height = 18, forced_width = 18, bg = "#ffffff11", paddings = 2, widget = wibox.container.arcchart, set_value = function(self, value) self.value = value end, } local last_battery_check = os.time() watch("acpi -i", 10, function(widget, stdout) local batteryType local battery_info = {} local capacities = {} for s in stdout:gmatch("[^\r\n]+") do local status, charge_str, time = string.match(s, '.+: (%a+), (%d?%d?%d)%%,?.*') if string.match(s, 'rate information') then -- ignore such line elseif status ~= nil then table.insert(battery_info, {status = status, charge = tonumber(charge_str)}) else local cap_str = string.match(s, '.+:.+last full capacity (%d+)') table.insert(capacities, tonumber(cap_str)) end end local capacity = 0 for i, cap in ipairs(capacities) do capacity = capacity + cap end local charge = 0 local status for i, batt in ipairs(battery_info) do if batt.charge >= charge then status = batt.status -- use most charged battery status -- this is arbitrary, and maybe another metric should be used end charge = charge + batt.charge * capacities[i] end charge = charge / capacity widget.value = charge / 100 if status == 'Charging' then text_with_background.bg = beautiful.widget_green text_with_background.fg = beautiful.widget_black else text_with_background.bg = beautiful.widget_transparent text_with_background.fg = beautiful.widget_main_color end text.text = string.format('%d', charge) if charge < 15 then batteryarc.colors = { beautiful.widget_red } if status ~= 'Charging' and os.difftime(os.time(), last_battery_check) > 300 then -- if 5 minutes have elapsed since the last warning last_battery_check = time() show_battery_warning() end elseif charge > 15 and charge < 40 then batteryarc.colors = { beautiful.widget_yellow } else batteryarc.colors = { beautiful.widget_main_color } end end, batteryarc) -- Popup with battery info -- One way of creating a pop-up notification - naughty.notify local notification function show_battery_status() awful.spawn.easy_async([[bash -c 'acpi']], function(stdout, _, _, _) notification = naughty.notify { text = stdout, title = "Battery status", timeout = 5, hover_timeout = 0.5, width = 200, } end) end batteryarc:connect_signal("mouse::enter", function() show_battery_status() end) batteryarc:connect_signal("mouse::leave", function() naughty.destroy(notification) end) -- Alternative to naughty.notify - tooltip. You can compare both and choose the preferred one --battery_popup = awful.tooltip({objects = {battery_widget}}) -- To use colors from beautiful theme put -- following lines in rc.lua before require("battery"): -- beautiful.tooltip_fg = beautiful.fg_normal -- beautiful.tooltip_bg = beautiful.bg_normal --[[ Show warning notification ]] function show_battery_warning() naughty.notify { icon = HOME .. "/.config/awesome/nichosi.png", icon_size = 100, text = "Huston, we have a problem", title = "Battery is dying", timeout = 5, hover_timeout = 0.5, position = "bottom_right", bg = "#F06060", fg = "#EEE9EF", width = 300, } end return batteryarc
------------------------------------------------- -- Battery Arc Widget for Awesome Window Manager -- Shows the battery level of the laptop -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/batteryarc-widget -- @author Pavel Makhov -- @copyright 2019 Pavel Makhov ------------------------------------------------- local awful = require("awful") local beautiful = require("beautiful") local naughty = require("naughty") local wibox = require("wibox") local watch = require("awful.widget.watch") local HOME = os.getenv("HOME") local text = wibox.widget { id = "txt", font = "Play 6", widget = wibox.widget.textbox } local text_with_background = wibox.container.background(text) local batteryarc = wibox.widget { text_with_background, max_value = 1, rounded_edge = true, thickness = 2, start_angle = 4.71238898, -- 2pi*3/4 forced_height = 18, forced_width = 18, bg = "#ffffff11", paddings = 2, widget = wibox.container.arcchart, set_value = function(self, value) self.value = value end, } local last_battery_check = os.time() watch("acpi -i", 10, function(widget, stdout) local batteryType local battery_info = {} local capacities = {} for s in stdout:gmatch("[^\r\n]+") do local status, charge_str, time = string.match(s, '.+: (%a+), (%d?%d?%d)%%,?.*') if string.match(s, 'rate information') then -- ignore such line elseif status ~= nil then table.insert(battery_info, {status = status, charge = tonumber(charge_str)}) else local cap_str = string.match(s, '.+:.+last full capacity (%d+)') table.insert(capacities, tonumber(cap_str)) end end local capacity = 0 for i, cap in ipairs(capacities) do capacity = capacity + cap end local charge = 0 local status for i, batt in ipairs(battery_info) do if batt.charge >= charge then status = batt.status -- use most charged battery status -- this is arbitrary, and maybe another metric should be used end charge = charge + batt.charge * capacities[i] end if capacity > 0 then charge = charge / capacity end widget.value = charge / 100 if status == 'Charging' then text_with_background.bg = beautiful.widget_green text_with_background.fg = beautiful.widget_black else text_with_background.bg = beautiful.widget_transparent text_with_background.fg = beautiful.widget_main_color end text.text = string.format('%d', charge) if charge < 15 then batteryarc.colors = { beautiful.widget_red } if status ~= 'Charging' and os.difftime(os.time(), last_battery_check) > 300 then -- if 5 minutes have elapsed since the last warning last_battery_check = time() show_battery_warning() end elseif charge > 15 and charge < 40 then batteryarc.colors = { beautiful.widget_yellow } else batteryarc.colors = { beautiful.widget_main_color } end end, batteryarc) -- Popup with battery info -- One way of creating a pop-up notification - naughty.notify local notification function show_battery_status() awful.spawn.easy_async([[bash -c 'acpi']], function(stdout, _, _, _) notification = naughty.notify { text = stdout, title = "Battery status", timeout = 5, hover_timeout = 0.5, width = 200, } end) end batteryarc:connect_signal("mouse::enter", function() show_battery_status() end) batteryarc:connect_signal("mouse::leave", function() naughty.destroy(notification) end) -- Alternative to naughty.notify - tooltip. You can compare both and choose the preferred one --battery_popup = awful.tooltip({objects = {battery_widget}}) -- To use colors from beautiful theme put -- following lines in rc.lua before require("battery"): -- beautiful.tooltip_fg = beautiful.fg_normal -- beautiful.tooltip_bg = beautiful.bg_normal --[[ Show warning notification ]] function show_battery_warning() naughty.notify { icon = HOME .. "/.config/awesome/nichosi.png", icon_size = 100, text = "Huston, we have a problem", title = "Battery is dying", timeout = 5, hover_timeout = 0.5, position = "bottom_right", bg = "#F06060", fg = "#EEE9EF", width = 300, } end return batteryarc
batteryarc-widget: fix crash when battery is not available
batteryarc-widget: fix crash when battery is not available It was crashing awesome window manager when starting with battery removed from the laptop.
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets,streetturtle/AwesomeWM
2bc86a889419476c60a784542c7d181e6a0deb01
quest/alberto_dicker_674_runewick.lua
quest/alberto_dicker_674_runewick.lua
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (674, 'quest.alberto_dicker_674_runewick'); require("base.common") module("quest.alberto_dicker_674_runewick", package.seeall) GERMAN = Player.german ENGLISH = Player.english -- Insert the quest title here, in both languages Title = {} Title[GERMAN] = "Die Bilder Alberto Dickers" Title[ENGLISH] = "The Pictures Alberto Dickers" -- 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 -- 1: say what's wrong with the picture -- 2: talk to Raban -- 3: talk to Numilia -- 4: talk to Halfhung Brian -- 5: talk to Numilia -- 100: find 5 pictures -- 105: talk to Numilia -- 201: talk to Miggs (Galmair only) -- 202: talk to Anthar (Cadomyr only) -- 203: End Description = {} Description[GERMAN] = {} Description[ENGLISH] = {} -- Quests Description[GERMAN][1] = "Schau dir das Bild des Hahnes genau an. Sage Numila Irunnleh was nicht stimmt. Du kannst in der Bcherei ber den Maler nachlesen, dort findest du die Antwort." Description[ENGLISH][1] = "See over the picture of the rooster. Tell Numila Irunnleh what is maybe not right. You find in the library a book about the painter. It contains hints for your answer." Description[GERMAN][2] = "Gehe zu Rabans Hain im Nordwald und sprich mit Raban." Description[ENGLISH][2] = "Go to Rabans Hain in the northern forest and talk to Raban." Description[GERMAN][3] = "Kehre zu Numila Irunnleh zurck und sprich mit ihr." Description[ENGLISH][3] = "Go back to Numila Irunnleh zurck and talk to her." Description[GERMAN][4] = "Befrage den Besitzer der Taverne zur Hanfschlinge nach dem Verbleib des Bildes 'Oldras Altar'." Description[ENGLISH][4] = "Interview the owner of the Hempty Neckty Inn whereabout the pichture 'Oldras Shrine'." Description[GERMAN][5] = "Kehre zu Numila Irunnleh zurck und sprich mit ihr." Description[ENGLISH][5] = "Go back to Numila Irunnleh zurck and talk to her." Description[GERMAN][100] = "Finde 5 weitere Bilder des Malers. Zwei in Cadomyr, eins in Galmair und zwei in Runewick." Description[ENGLISH][100] = "Find 5 more pictures of the painter. Two in Cadomyr, one in Galmair and two in Runewick." Description[GERMAN][105] = "Du hast alle Bilder gefunden. Kehre zu Numila Irunnleh zurck." Description[ENGLISH][105] = "You found all pictures. Go back to Numila Irunnleh." Description[GERMAN][201] = "Gehe zu Miggs und berichte ihm von dem kopierten Bild." Description[ENGLISH][201] = "Go to Miggs and report about the copied picture." Description[GERMAN][202] = "Gehe zu Anthar Vilicon und berichte ihm von dem kopierten Bild." Description[ENGLISH][202] = "Go to Anthar Vilicon and report about the copied picture." -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there -- noch machen! -- QuestTarget = {} QuestTarget[1] = {970, 787, 1} -- Numilia QuestTarget[2] = {819, 104, 0} -- Raban QuestTarget[3] = {970, 787, 1} -- Numilia QuestTarget[4] = {696, 317, 0} -- Halfhung Brian QuestTarget[5] = {970, 787, 1} -- Numilia QuestTarget[105] = {970, 787, 1} -- Numilia QuestTarget[201] = {374, 216, 0} -- Miggs QuestTarget[202] = {117, 528, 0} -- Anthar -- Insert the quest status which is reached at the end of the quest FINAL_QUEST_STATUS = 203 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
--[[ 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/>. ]] -- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (674, 'quest.alberto_dicker_674_runewick'); require("base.common") module("quest.alberto_dicker_674_runewick", package.seeall) GERMAN = Player.german ENGLISH = Player.english -- Insert the quest title here, in both languages Title = {} Title[GERMAN] = "Die Bilder Alberto Dickers" Title[ENGLISH] = "The Pictures Alberto Dickers" -- 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 -- 1: say what's wrong with the picture -- 2: talk to Raban -- 3: talk to Numilia -- 4: talk to Halfhung Brian -- 5: talk to Numilia -- 100: find 5 pictures -- 105: talk to Numilia -- 201: talk to Miggs (Galmair only) -- 202: talk to Anthar (Cadomyr only) -- 203: End Description = {} Description[GERMAN] = {} Description[ENGLISH] = {} -- Quests Description[GERMAN][1] = "Schau dir das Bild des Hahnes genau an. Sage Numila Irunnleh was nicht stimmt. Du kannst in der Bcherei ber den Maler nachlesen, dort findest du die Antwort." Description[ENGLISH][1] = "See over the picture of the rooster. Tell Numila Irunnleh what is maybe not right. You find in the library a book about the painter. It contains hints for your answer." Description[GERMAN][2] = "Gehe zu Rabans Hain im Nordwald und sprich mit Raban." Description[ENGLISH][2] = "Go to Rabans Hain in the northern forest and talk to Raban." Description[GERMAN][3] = "Kehre zu Numila Irunnleh zurck und sprich mit ihr." Description[ENGLISH][3] = "Go back to Numila Irunnleh zurck and talk to her." Description[GERMAN][4] = "Befrage den Besitzer der Taverne zur Hanfschlinge nach dem Verbleib des Bildes 'Oldras Altar'." Description[ENGLISH][4] = "Interview the owner of the Hempty Neckty Inn whereabout the pichture 'Oldras Shrine'." Description[GERMAN][5] = "Kehre zu Numila Irunnleh zurck und sprich mit ihr." Description[ENGLISH][5] = "Go back to Numila Irunnleh zurck and talk to her." Description[GERMAN][100] = "Finde 5 weitere Bilder des Malers. Zwei in Cadomyr, eins in Galmair und zwei in Runewick." Description[ENGLISH][100] = "Find 5 more pictures of the painter. Two in Cadomyr, one in Galmair and two in Runewick." Description[GERMAN][105] = "Du hast alle Bilder gefunden. Kehre zu Numila Irunnleh zurck." Description[ENGLISH][105] = "You found all pictures. Go back to Numila Irunnleh." Description[GERMAN][201] = "Gehe zu Miggs und berichte ihm von dem kopierten Bild." Description[ENGLISH][201] = "Go to Miggs and report about the copied picture." Description[GERMAN][202] = "Gehe zu Anthar Vilicon und berichte ihm von dem kopierten Bild." Description[ENGLISH][202] = "Go to Anthar Vilicon and report about the copied picture." -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there -- noch machen! -- QuestTarget = {} QuestTarget[1] = {970, 787, 1} -- Numilia QuestTarget[2] = {819, 104, 0} -- Raban QuestTarget[3] = {970, 787, 1} -- Numilia QuestTarget[4] = {696, 317, 0} -- Halfhung Brian QuestTarget[5] = {970, 787, 1} -- Numilia QuestTarget[105] = {970, 787, 1} -- Numilia QuestTarget[201] = {374, 216, 0} -- Miggs QuestTarget[202] = {117, 528, 0} -- Anthar -- Insert the quest status which is reached at the end of the quest FINAL_QUEST_STATUS = 203 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
Fix NPC
Fix NPC
Lua
agpl-3.0
Illarion-eV/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content
c51c4208029f4024631aa9d381ed0409bff7775f
modules/http/http.lua
modules/http/http.lua
module("http", package.seeall) local function str(char) return string.char(char) end local function getchar(stream) local char while true do char = stream:getchar() if char == -1 then coroutine.yield() else break end end return char end local function read_line(stream) local line = "" local char local sp = "\r\n" local read = 0 while true do char = getchar(stream) read = read+1 char = str(char) local tmp = "" for i = 1, #sp do local c = sp:sub(i,i) if char ~= c then line = line .. tmp break end if i == #sp then return line, read end tmp = tmp .. c char = getchar(stream) read = read+1 char = str(char) end line = line .. char end end local function dump(t, indent) for n, v in pairs(t) do if type(v) == "table" then print(indent, n) dump(v, indent .. " ") else print(indent, n, "=", v) end end end local function parse_request(stream, http) local len, total_len total_len = 0 local line, len = read_line(stream) total_len = total_len + len http.method, http.uri, http.version = line:match("(%g+) (%g+) (.+)") if not http.method then http.valid = false return end -- Headers http.headers = {} http.headers_order = {} line, len = read_line(stream) total_len = total_len + len while #line > 0 do local name, value = line:match("(%g+): (.+)") if not name then http.valid = false return end http.headers[name] = value table.insert(http.headers_order, name) line, len = read_line(stream) total_len = total_len + len end http.data = stream http.length = total_len http.dump = function (self) dump(self, "") end http.valid = true return true end local function parse_response(stream, http) local len, total_len total_len = 0 local line, len = read_line(stream) total_len = total_len + len http.version, http.status, http.reason = line:match("(%g+) (%g+) (.+)") if not http.version then http.valid = false return end -- Headers http.headers = {} http.headers_order = {} line, len = read_line(stream) total_len = total_len + len while #line > 0 do local name, value = line:match("(%g+): (.+)") if not name then http.valid = false return end http.headers[name] = value table.insert(http.headers_order, name) line, len = read_line(stream) total_len = total_len + len end http.data = stream http.length = total_len http.dump = function (self) dump(self, "") end http.valid = true return true end local function build_headers(stream, headers, headers_order) local copy = headers for _, name in pairs(headers_order) do local value = copy[name] if value then copy[name] = nil stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end for name, value in pairs(copy) do if value then stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end end local function forge(http) local tcp = http.tcp_stream if tcp then if http.state == 2 and tcp.direction then http.state = 3 tcp.stream:seek(http.request.mark, true) http.request.mark = nil tcp.stream:erase(http.request.length) tcp.stream:insert(http.request.method) tcp.stream:insert(" ") tcp.stream:insert(http.request.uri) tcp.stream:insert(" ") tcp.stream:insert(http.request.version) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.request.headers, http.request.headers_order) tcp.stream:insert("\r\n") elseif http.state == 5 and not tcp.direction then http.state = 0 tcp.stream:seek(http.response.mark, true) http.response.mark = nil tcp.stream:erase(http.response.length) tcp.stream:insert(http.response.version) tcp.stream:insert(" ") tcp.stream:insert(http.response.status) tcp.stream:insert(" ") tcp.stream:insert(http.response.reason) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.response.headers, http.response.headers_order) tcp.stream:insert("\r\n") end http.tcp_stream = nil end return tcp end local function parse(http, context, f, name, next_state) if not context.co then context.mark = http.tcp_stream.stream:mark() context.co = coroutine.create(function () f(http.tcp_stream.stream, context) end) end coroutine.resume(context.co) if coroutine.status(context.co) == "dead" then if context.valid then http.state = next_state if haka.rule_hook("http-".. name, http) then return nil end context.next_dissector = http.next_dissector else haka.log.error("http", "invalid " .. name) http.tcp_stream:drop() return nil end end end haka.dissector { name = "http", dissect = function (stream) if not stream.connection.data.http then local http = {} http.dissector = "http" http.next_dissector = nil http.valid = function (self) return self.tcp_stream:valid() end http.drop = function (self) return self.tcp_stream:drop() end http.forge = forge http.state = 0 stream.connection.data.http = http end local http = stream.connection.data.http http.tcp_stream = stream if stream.direction then if http.state == 0 or http.state == 1 then if stream.stream:available() > 0 then if http.state == 0 then http.request = {} http.response = nil http.state = 1 end parse(http, http.request, parse_request, "request", 2) end elseif http.request then http.next_dissector = http.request.next_dissector end else if http.state == 3 or http.state == 4 then if stream.stream:available() > 0 then if http.state == 3 then http.response = {} http.state = 4 end parse(http, http.response, parse_response, "response", 5) end elseif http.response then http.next_dissector = http.response.next_dissector end end return http end }
module("http", package.seeall) local function str(char) return string.char(char) end local function getchar(stream) local char while true do char = stream:getchar() if char == -1 then coroutine.yield() else break end end return char end local function read_line(stream) local line = "" local char, c local read = 0 while true do c = getchar(stream) read = read+1 char = str(c) print(c) if c == 0xd then c = getchar(stream) print(c) read = read+1 if c == 0xa then return line, read else line = line .. char char = str(c) end elseif c == 0xa then return line, read end line = line .. char print(line) end end local function dump(t, indent) for n, v in pairs(t) do if type(v) == "table" then print(indent, n) dump(v, indent .. " ") else print(indent, n, "=", v) end end end local function parse_request(stream, http) local len, total_len total_len = 0 local line, len = read_line(stream) total_len = total_len + len http.method, http.uri, http.version = line:match("(%g+) (%g+) (.+)") if not http.method then http.valid = false return end -- Headers http.headers = {} http.headers_order = {} line, len = read_line(stream) total_len = total_len + len while #line > 0 do local name, value = line:match("(%g+): (.+)") if not name then http.valid = false return end http.headers[name] = value table.insert(http.headers_order, name) line, len = read_line(stream) total_len = total_len + len end http.data = stream http.length = total_len http.dump = function (self) dump(self, "") end http.valid = true return true end local function parse_response(stream, http) local len, total_len total_len = 0 local line, len = read_line(stream) total_len = total_len + len http.version, http.status, http.reason = line:match("(%g+) (%g+) (.+)") if not http.version then http.valid = false return end -- Headers http.headers = {} http.headers_order = {} line, len = read_line(stream) total_len = total_len + len while #line > 0 do local name, value = line:match("(%g+): (.+)") if not name then http.valid = false return end http.headers[name] = value table.insert(http.headers_order, name) line, len = read_line(stream) total_len = total_len + len end http.data = stream http.length = total_len http.dump = function (self) dump(self, "") end http.valid = true return true end local function build_headers(stream, headers, headers_order) local copy = headers for _, name in pairs(headers_order) do local value = copy[name] if value then copy[name] = nil stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end for name, value in pairs(copy) do if value then stream:insert(name) stream:insert(": ") stream:insert(value) stream:insert("\r\n") end end end local function forge(http) local tcp = http.tcp_stream if tcp then if http.state == 2 and tcp.direction then http.state = 3 tcp.stream:seek(http.request.mark, true) http.request.mark = nil tcp.stream:erase(http.request.length) tcp.stream:insert(http.request.method) tcp.stream:insert(" ") tcp.stream:insert(http.request.uri) tcp.stream:insert(" ") tcp.stream:insert(http.request.version) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.request.headers, http.request.headers_order) tcp.stream:insert("\r\n") elseif http.state == 5 and not tcp.direction then http.state = 0 tcp.stream:seek(http.response.mark, true) http.response.mark = nil tcp.stream:erase(http.response.length) tcp.stream:insert(http.response.version) tcp.stream:insert(" ") tcp.stream:insert(http.response.status) tcp.stream:insert(" ") tcp.stream:insert(http.response.reason) tcp.stream:insert("\r\n") build_headers(tcp.stream, http.response.headers, http.response.headers_order) tcp.stream:insert("\r\n") end http.tcp_stream = nil end return tcp end local function parse(http, context, f, name, next_state) if not context.co then context.mark = http.tcp_stream.stream:mark() context.co = coroutine.create(function () f(http.tcp_stream.stream, context) end) end coroutine.resume(context.co) if coroutine.status(context.co) == "dead" then if context.valid then http.state = next_state if haka.rule_hook("http-".. name, http) then return nil end context.next_dissector = http.next_dissector else haka.log.error("http", "invalid " .. name) http.tcp_stream:drop() return nil end end end haka.dissector { name = "http", dissect = function (stream) if not stream.connection.data.http then local http = {} http.dissector = "http" http.next_dissector = nil http.valid = function (self) return self.tcp_stream:valid() end http.drop = function (self) return self.tcp_stream:drop() end http.forge = forge http.state = 0 stream.connection.data.http = http end local http = stream.connection.data.http http.tcp_stream = stream if stream.direction then if http.state == 0 or http.state == 1 then if stream.stream:available() > 0 then if http.state == 0 then http.request = {} http.response = nil http.state = 1 end parse(http, http.request, parse_request, "request", 2) end elseif http.request then http.next_dissector = http.request.next_dissector end else if http.state == 3 or http.state == 4 then if stream.stream:available() > 0 then if http.state == 3 then http.response = {} http.state = 4 end parse(http, http.response, parse_response, "response", 5) end elseif http.response then http.next_dissector = http.response.next_dissector end end return http end }
Fix HTTP parser to handle /n
Fix HTTP parser to handle /n The end of line should be /r/n according to the rfc, but /n seams to be usable. Modified the parser to handle /n as line separator.
Lua
mpl-2.0
LubyRuffy/haka,lcheylus/haka,lcheylus/haka,Wingless-Archangel/haka,nabilbendafi/haka,nabilbendafi/haka,lcheylus/haka,haka-security/haka,nabilbendafi/haka,haka-security/haka,LubyRuffy/haka,Wingless-Archangel/haka,haka-security/haka
21f114c48ca614214bb1733526a1891baf02fbfe
scen_edit/state/abstract_heightmap_editing_state.lua
scen_edit/state/abstract_heightmap_editing_state.lua
SCEN_EDIT.Include("scen_edit/state/abstract_map_editing_state.lua") AbstractHeightmapEditingState = AbstractMapEditingState:extends{} function AbstractHeightmapEditingState:init(editorView) AbstractMapEditingState.init(self, editorView) self.paintTexture = self.editorView.paintTexture self.strength = self.editorView.fields["strength"].value self.height = self.editorView.fields["height"].value self.applyDelay = 0.03 self.initialDelay = 0.3 end function AbstractHeightmapEditingState:leaveState() self.editorView:StoppedEditing() end function AbstractHeightmapEditingState:enterState() self.editorView:Set("size", self.size) self.editorView:StartedEditing() end function AbstractHeightmapEditingState:KeyPress(key, mods, isRepeat, label, unicode) -- FIXME: cannot use "super" here in the current version of LCS and the new version is broken if AbstractMapEditingState.KeyPress(self, key, mods, isRepeat, label, unicode) then return true end if key == 49 then -- 1 local newState = TerrainShapeModifyState(self.editorView) if self.size then newState.size = self.size end SCEN_EDIT.stateManager:SetState(newState) elseif key == 50 then -- 2 local newState = TerrainSetState(self.editorView) if self.size then newState.size = self.size end SCEN_EDIT.stateManager:SetState(newState) elseif key == 51 then -- 3 local newState = TerrainSmoothState(self.editorView) if self.size then newState.size = self.size end SCEN_EDIT.stateManager:SetState(newState) -- elseif key == 52 then -- 4 -- local newState = TerrainChangeHeightRectState(self.editorView) -- SCEN_EDIT.stateManager:SetState(newState) -- elseif key == 53 then -- 5 -- local newState = TerrainShapeModifyState(self.editorView) -- SCEN_EDIT.stateManager:SetState(newState) else return false end return false end function AbstractHeightmapEditingState:GetApplyParams(x, z, button) local strength = self.strength if button == 3 and strength ~= nil then strength = -strength end return x, z, strength end function AbstractHeightmapEditingState:Apply(x, z, strength) if SCEN_EDIT.model.terrainManager:getShape(self.paintTexture) == nil then SCEN_EDIT.model.terrainManager:generateShape(self.paintTexture) end local cmd = self:GetCommand(x, z, strength) SCEN_EDIT.commandManager:execute(cmd) return true end function AbstractHeightmapEditingState:DrawWorld() x, y = Spring.GetMouseState() local result, coords = Spring.TraceScreenRay(x, y, true) if result == "ground" then local x, z = coords[1], coords[3] if not self.paintTexture then return end local shape = SCEN_EDIT.model.textureManager:GetTexture(self.paintTexture) self:DrawShape(shape, x, z) end end
SCEN_EDIT.Include("scen_edit/state/abstract_map_editing_state.lua") AbstractHeightmapEditingState = AbstractMapEditingState:extends{} function AbstractHeightmapEditingState:init(editorView) AbstractMapEditingState.init(self, editorView) self.paintTexture = self.editorView.paintTexture self.strength = self.editorView.fields["strength"].value self.height = self.editorView.fields["height"].value self.applyDelay = 0.03 self.initialDelay = 0.3 end function AbstractHeightmapEditingState:leaveState() self.editorView:StoppedEditing() end function AbstractHeightmapEditingState:enterState() self.editorView:Set("size", self.size) self.editorView:StartedEditing() end function AbstractHeightmapEditingState:KeyPress(key, mods, isRepeat, label, unicode) -- FIXME: cannot use "super" here in the current version of LCS and the new version is broken if AbstractMapEditingState.KeyPress(self, key, mods, isRepeat, label, unicode) then return true end if key == 49 then -- 1 local newState = TerrainShapeModifyState(self.editorView) if self.size then newState.size = self.size end SCEN_EDIT.stateManager:SetState(newState) elseif key == 50 then -- 2 local newState = TerrainSetState(self.editorView) if self.size then newState.size = self.size end SCEN_EDIT.stateManager:SetState(newState) elseif key == 51 then -- 3 local newState = TerrainSmoothState(self.editorView) if self.size then newState.size = self.size end SCEN_EDIT.stateManager:SetState(newState) -- elseif key == 52 then -- 4 -- local newState = TerrainChangeHeightRectState(self.editorView) -- SCEN_EDIT.stateManager:SetState(newState) -- elseif key == 53 then -- 5 -- local newState = TerrainShapeModifyState(self.editorView) -- SCEN_EDIT.stateManager:SetState(newState) else return false end return false end function AbstractHeightmapEditingState:GetApplyParams(x, z, button) local strength = self.strength if button == 3 and strength ~= nil then strength = -strength end return x, z, strength end function AbstractHeightmapEditingState:Apply(x, z, strength) if not self.paintTexture then return false end if SCEN_EDIT.model.terrainManager:getShape(self.paintTexture) == nil then SCEN_EDIT.model.terrainManager:generateShape(self.paintTexture) end local cmd = self:GetCommand(x, z, strength) SCEN_EDIT.commandManager:execute(cmd) return true end function AbstractHeightmapEditingState:DrawWorld() x, y = Spring.GetMouseState() local result, coords = Spring.TraceScreenRay(x, y, true) if result == "ground" then local x, z = coords[1], coords[3] if not self.paintTexture then return end local shape = SCEN_EDIT.model.textureManager:GetTexture(self.paintTexture) self:DrawShape(shape, x, z) end end
fix terrain editing errors when no paint texture is selected
fix terrain editing errors when no paint texture is selected
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
876f2f9027697fef4bc934f3f38f90c8d21c062f
.hammerspoon/init.lua
.hammerspoon/init.lua
-- [[ -- Other stuff -- ]] -- Automatically reload config when init is saved function reloadConfig(files) doReload = false for _, file in pairs(files) do if file:sub(-4) == ".lua" then doReload = true end end if doReload then hs.reload() end end hs.hotkey.bind({"cmd", "ctrl"}, "R", function() hs.reload() end) -- hs.pathwatcher.new(os.getenv("HOME") .. "/.dotfiles/.hammerspoon/", reloadConfig):start() hs.alert.show("Config loaded") -- [[ -- Options -- ]] -- Shorten the animation duration, less jerky hs.window.animationDuration = 0.01 -- Don't show window titles in hints hs.hints.showTitleThresh = 0 -- Set up window hints characters to be in this order -- right hand center row -- left hand center row -- right hand top row -- left hand top row -- center bottom row hs.hints.hintChars = { "H", "J", "K", "L", "A", "S", "D", "F", "G", "Y", "U", "I", "O", "P", "Q", "W", "E", "R", "T", "C", "V", "B", "N" } -- [[ -- Window Control -- -- ]] function alertShowCannotMoveWindow() hs.alert.show("Can't move window") end -- Move current window to full screen hs.hotkey.bind({"shift", "ctrl"}, "K", function () local win = hs.window.focusedWindow() if not win then alertShowCannotMoveWindow() return end local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w f.h = max.h win:setFrame(f) end) -- Move current window to left half of screen hs.hotkey.bind({"cmd", "ctrl"}, "H", function () local win = hs.window.focusedWindow() if not win then alertShowCannotMoveWindow() return end local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end) -- Move current window to right half of screen hs.hotkey.bind({"cmd", "ctrl"}, "L", function () local win = hs.window.focusedWindow() if not win then alertShowCannotMoveWindow() return end local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h win:setFrame(f) end) -- Move current window to bottom half of screen hs.hotkey.bind({"cmd", "ctrl"}, "J", function () local win = hs.window.focusedWindow() if not win then alertShowCannotMoveWindow() return end local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y + (max.h / 2) f.w = max.w f.h = max.h / 2 win:setFrame(f) end) -- Move current window to top half of screen hs.hotkey.bind({"cmd", "ctrl"}, "K", function () local win = hs.window.focusedWindow() if not win then alertShowCannotMoveWindow() return end local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w f.h = max.h / 2 win:setFrame(f) end) -- Window Hints like slate -- I used Karabiner to change cmd+tab to emmit F19 hs.hotkey.bind({""}, "F19", function () hs.hints.windowHints(nil, nil, true) end) -- [[ -- Spotify Hotkeys -- ]] hs.hotkey.bind({"ctrl", "shift"}, "P", function() hs.spotify.playpause() end)
-- [[ -- Other stuff -- ]] -- Automatically reload config when init is saved function reloadConfig(files) doReload = false for _, file in pairs(files) do if file:sub(-4) == ".lua" then doReload = true end end if doReload then hs.reload() end end hs.hotkey.bind({"cmd", "ctrl"}, "R", function() hs.reload() end) -- hs.pathwatcher.new(os.getenv("HOME") .. "/.dotfiles/.hammerspoon/", reloadConfig):start() hs.alert.show("Config loaded") -- [[ -- Options -- ]] -- Shorten the animation duration, less jerky hs.window.animationDuration = 0.01 -- Don't show window titles in hints hs.hints.showTitleThresh = 0 -- Set up window hints characters to be in this order -- right hand center row -- left hand center row -- right hand top row -- left hand top row -- center bottom row hs.hints.hintChars = { "H", "J", "K", "L", "A", "S", "D", "F", "G", "Y", "U", "I", "O", "P", "Q", "W", "E", "R", "T", "C", "V", "B", "N" } -- [[ -- Window Control -- -- ]] function alertShowCannotMoveWindow() hs.alert.show("Can't move window") end function withModifiers(app_name, frame) if app_name == 'iTerm2' then frame.w = frame.w + 5 end return frame end -- Move current window to full screen hs.hotkey.bind({"shift", "ctrl"}, "K", function () local win = hs.window.focusedWindow() if not win then alertShowCannotMoveWindow() return end local f = win:frame() local screen = win:screen() local max = screen:frame() f.x = max.x f.y = max.y f.w = max.w f.h = max.h win:setFrame(f) end) -- Move current window to left half of screen hs.hotkey.bind({"cmd", "ctrl"}, "H", function () local win = hs.window.focusedWindow() if not win then alertShowCannotMoveWindow() return end local app_name = win:application():title() local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x f.y = max.y f.w = max.w / 2 f.h = max.h f = withModifiers(app_name, f) win:setFrame(f) end) -- Move current window to right half of screen hs.hotkey.bind({"cmd", "ctrl"}, "L", function () local win = hs.window.focusedWindow() if not win then alertShowCannotMoveWindow() return end local app_name = win:application():title() local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x + (max.w / 2) f.y = max.y f.w = max.w / 2 f.h = max.h f = withModifiers(app_name, f) win:setFrame(f) end) -- Move current window to bottom half of screen hs.hotkey.bind({"cmd", "ctrl"}, "J", function () local win = hs.window.focusedWindow() if not win then alertShowCannotMoveWindow() return end local app_name = win:application():title() local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x f.y = max.y + (max.h / 2) f.w = max.w f.h = max.h / 2 f = withModifiers(app_name, f) win:setFrame(f) end) -- Move current window to top half of screen hs.hotkey.bind({"cmd", "ctrl"}, "K", function () local win = hs.window.focusedWindow() if not win then alertShowCannotMoveWindow() return end local app_name = win:application():title() local f = win:frame() local screen = win:screen() local max = screen:fullFrame() f.x = max.x f.y = max.y f.w = max.w f.h = max.h / 2 f = withModifiers(app_name, f) win:setFrame(f) end) -- Window Hints like slate -- I used Karabiner to change cmd+tab to emmit F19 hs.hotkey.bind({""}, "F19", function () hs.hints.windowHints(nil, nil, true) end) -- [[ -- Spotify Hotkeys -- ]] hs.hotkey.bind({"ctrl", "shift"}, "P", function() hs.spotify.playpause() end)
Fix: iTerm width resizing working better
Fix: iTerm width resizing working better
Lua
mit
tscheffe/dotfiles,tscheffe/dotfiles,tscheffe/dotfiles
3ad46c10236802bfae4689405ebcb23fb7555bd7
lib/out.lua
lib/out.lua
--[=============================================================================[ The MIT License (MIT) Copyright (c) 2014 RepeatPan excluding parts that were written by Radiant Entertainment Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]=============================================================================] local stdout = radiant.log.create_logger('out') -- Note: Most/all of these functions are global too, because they are "too vital" -- TODO: Make globalisation optional. local out = {} do -- Overwrites `io.output' to our log file(s) io.output('jelly_stdout' .. (radiant.is_server and '_server' or '') .. '.log') local function print_plain(to_logger, ...) local t = { ... } local argc = select('#', ...) io.write('[') io.write(os.date()) io.write('] ') for i = 1, argc do t[i] = tostring(t[i]) io.write(t[i]) t[i] = t[i]:gsub('%%', '%%%%') if i < argc then io.write("\t") end end io.write("\n") io.flush() if to_logger then stdout:write(0, table.concat(t, '\t')) end end function print(...) print_plain(true, ...) end function printf(str, ...) print_plain(false, string.format(str, ...)) stdout:write(0, str, ...) end out.print, out.printf = print, printf end return out
--[=============================================================================[ The MIT License (MIT) Copyright (c) 2014 RepeatPan excluding parts that were written by Radiant Entertainment 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. ]=============================================================================] -- Note: Most/all of these functions are global too, because they are "too vital" -- TODO: Make globalisation optional. local out = {} do -- Overwrites `io.output' to our log file(s) io.output('jelly_stdout' .. (radiant.is_server and '_server' or '') .. '.log') local function print_plain(to_logger, ...) local t = { ... } local argc = select('#', ...) io.write('[') io.write(os.date()) io.write('] ') for i = 1, argc do t[i] = tostring(t[i]) io.write(t[i]) t[i] = t[i]:gsub('%%', '%%%%') if i < argc then io.write("\t") end end io.write("\n") io.flush() if to_logger then radiant.log.write('stdout', 0, table.concat(t, '\t')) end end function print(...) print_plain(true, ...) end function printf(str, ...) print_plain(false, string.format(str, ...)) radiant.log.write('stdout', 0, str, ...) end out.print, out.printf = print, printf end return out
Improved/Fixed console output
Improved/Fixed console output
Lua
mit
Quit/jelly
f053df6674269663818df1d3cbbb85546113645e
scen_edit/view/file_dialog.lua
scen_edit/view/file_dialog.lua
FileDialog = Observable:extends{} function FileDialog:init(dir, caption, fileTypes) self.dir = dir or nil self.caption = caption or "File dialog" self.confirmDialogCallback = nil self.fileTypes = fileTypes local buttonPanel = MakeComponentPanel() self.fileEditBox = EditBox:New { y = 1, x = 75, right = 0, height = "100%", } local okButton = Button:New { height = SCEN_EDIT.conf.B_HEIGHT, bottom = 5, width = "20%", right = "22%", caption = "OK", } local cancelButton = Button:New { height = SCEN_EDIT.conf.B_HEIGHT, bottom = 5, width = "20%", right = 10, caption = "Cancel", } self.filePanel = FilePanel:New { x = 10, y = 10, width = "100%", height = "100%", dir = self.dir, multiselect = false, OnDblClickItem = { function() self:confirmDialog(); self.window:Dispose() end }, } self.filePanel.OnSelectItem = { function (obj, itemIdx, selected) --FIXME: loading from complex paths is broken, uncomment this when they get fixed if selected then -- and itemIdx > self.filePanel._dirsNum+1 then local fullPath = tostring(obj.items[itemIdx]) local fileName = Path.ExtractFileName(fullPath) self.fileEditBox:SetText(fileName) end end } self.window = Window:New { x = 500, y = 200, width = 600, height = 600, parent = screen0, caption = self.caption, children = { ScrollPanel:New { width = "100%", y = 10, bottom = 90 + SCEN_EDIT.conf.B_HEIGHT + 10, children = { self.filePanel, }, }, Control:New { x = 1, width = "100%", height = SCEN_EDIT.conf.B_HEIGHT, bottom = SCEN_EDIT.conf.B_HEIGHT + 20, padding = {0, 0, 0, 0}, children = { Label:New { x = 1, y = 4, valign = "center", width = 65, caption = "File name: ", align = "left", }, self.fileEditBox, }, }, okButton, cancelButton, }, OnDispose = { function() SCEN_EDIT.stateManager:GetCurrentState():SetGlobalKeyListener() end } } if self.fileTypes then self.cmbFileTypes = ComboBox:New { items = self.fileTypes, width = 100, height = SCEN_EDIT.conf.B_HEIGHT + 10, x = 75, right = 0, } local ctrl = Control:New { x = 1, width = "100%", height = SCEN_EDIT.conf.B_HEIGHT + 10, bottom = 2 * SCEN_EDIT.conf.B_HEIGHT + 30, padding = {0, 0, 0, 0}, children = { Label:New { x = 1, y = 4, valign = "center", width = 65, caption = "File type: ", align = "left", }, self.cmbFileTypes, }, } self.window:AddChild(ctrl) end okButton.OnClick = { function() self:confirmDialog() self.window:Dispose() end } cancelButton.OnClick = { function() self.window:Dispose() end } local function keyListener(key) if key == Spring.GetKeyCode("esc") then self.window:Dispose() return true elseif key == Spring.GetKeyCode("enter") or key == Spring.GetKeyCode("numpad_enter") then self:confirmDialog() self.window:Dispose() return true end end SCEN_EDIT.stateManager:GetCurrentState():SetGlobalKeyListener(keyListener) -- self:SetDir(self.dir) end function FileDialog:setConfirmDialogCallback(func) self.confirmDialogCallback = func end function FileDialog:getSelectedFilePath() local path = self.filePanel.dir .. self.fileEditBox.text return path end function FileDialog:getSelectedFileType() if self.cmbFileTypes == nil then return nil end return self.cmbFileTypes.items[self.cmbFileTypes.selected] end function FileDialog:confirmDialog() local path = self:getSelectedFilePath() if self.confirmDialogCallback then self.confirmDialogCallback(path) end end
FileDialog = Observable:extends{} function FileDialog:init(dir, caption, fileTypes) self.dir = dir or nil self.caption = caption or "File dialog" self.confirmDialogCallback = nil self.fileTypes = fileTypes local buttonPanel = MakeComponentPanel() self.fileEditBox = EditBox:New { y = 1, x = 75, right = 0, height = "100%", } local okButton = Button:New { height = SCEN_EDIT.conf.B_HEIGHT, bottom = 5, width = "20%", right = "22%", caption = "OK", } local cancelButton = Button:New { height = SCEN_EDIT.conf.B_HEIGHT, bottom = 5, width = "20%", right = 10, caption = "Cancel", } self.filePanel = FilePanel:New { x = 10, y = 10, width = "100%", height = "100%", dir = self.dir, multiselect = false, OnDblClickItem = { function() self:confirmDialog(); self.window:Dispose() end }, } self.filePanel.OnSelectItem = { function (obj, itemIdx, selected) --FIXME: loading from complex paths is broken, uncomment this when they get fixed if selected then -- and itemIdx > self.filePanel._dirsNum+1 then local fullPath = tostring(obj.items[itemIdx]) local fileName = Path.ExtractFileName(fullPath) self.fileEditBox:SetText(fileName) end end } self.window = Window:New { x = 500, y = 200, width = 600, height = 600, parent = screen0, caption = self.caption, children = { ScrollPanel:New { width = "100%", y = 10, bottom = 90 + SCEN_EDIT.conf.B_HEIGHT + 10, children = { self.filePanel, }, }, Control:New { x = 1, width = "100%", height = SCEN_EDIT.conf.B_HEIGHT, bottom = SCEN_EDIT.conf.B_HEIGHT + 20, padding = {0, 0, 0, 0}, children = { Label:New { x = 1, y = 4, valign = "center", width = 65, caption = "File name: ", align = "left", }, self.fileEditBox, }, }, okButton, cancelButton, }, OnDispose = { function() SCEN_EDIT.stateManager:GetCurrentState():SetGlobalKeyListener() end } } if self.fileTypes then self.cmbFileTypes = ComboBox:New { items = self.fileTypes, width = 100, height = SCEN_EDIT.conf.B_HEIGHT + 10, x = 75, right = 0, } local ctrl = Control:New { x = 1, width = "100%", height = SCEN_EDIT.conf.B_HEIGHT + 10, bottom = 2 * SCEN_EDIT.conf.B_HEIGHT + 30, padding = {0, 0, 0, 0}, children = { Label:New { x = 1, y = 4, valign = "center", width = 65, caption = "File type: ", align = "left", }, self.cmbFileTypes, }, } self.window:AddChild(ctrl) end okButton.OnClick = { function() self:confirmDialog() self.window:Dispose() end } cancelButton.OnClick = { function() self.window:Dispose() end } local function keyListener(key) if key == Spring.GetKeyCode("esc") then self.window:Dispose() return true elseif key == Spring.GetKeyCode("enter") or key == Spring.GetKeyCode("numpad_enter") then self:confirmDialog() self.window:Dispose() return true end end SCEN_EDIT.stateManager:GetCurrentState():SetGlobalKeyListener(keyListener) screen0:FocusControl(self.fileEditBox) -- self:SetDir(self.dir) end function FileDialog:setConfirmDialogCallback(func) self.confirmDialogCallback = func end function FileDialog:getSelectedFilePath() local path = self.filePanel.dir .. self.fileEditBox.text return path end function FileDialog:getSelectedFileType() if self.cmbFileTypes == nil then return nil end return self.cmbFileTypes.items[self.cmbFileTypes.selected] end function FileDialog:confirmDialog() local path = self:getSelectedFilePath() if self.confirmDialogCallback then self.confirmDialogCallback(path) end end
focus editbox in file dialog (fix #137)
focus editbox in file dialog (fix #137)
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
2b3c7e696c3696a28bbdfb6e56bfde317f6d196c
lua/mini-stl/single_list.lua
lua/mini-stl/single_list.lua
-- Copyright (c) 2013 ASMlover. All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- * Redistributions of source code must retain the above copyright -- notice, this list ofconditions and the following disclaimer. -- -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in -- the documentation and/or other materialsprovided with the -- distribution. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -- FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -- COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. require 'object' SingleList = {} function SingleList.new() local obj = { front_ = nil, rear_ = nil, size_ = 0 } obj = newObject(obj, SingleList) return obj end function SingleList:clear() while self.front_ ~= nil do local node = self.front_ self.front_ = self.front_.next node = nil end self.front_ = nil self.rear_ = nil self.size_ = 0 end function SingleList:empty() return self.front_ == nil end function SingleList:size() return self.size_ end function SingleList:push_back(x) local node = { next = nil, data = x } if self.front_ == nil then self.front_ = node self.rear_ = self.front_ else self.rear_.next = node self.rear_ = node end self.size_ = self.size_ + 1 end function SingleList:push_front(x) local node = { next = self.front_, data = x } self.front_ = node self.size_ = self.size_ + 1 end function SingleList:pop_front() if self.front_ == nil then return end local node = self.front_ self.front_ = self.front_.next node = nil self.size_ = self.size_ - 1 end function SingleList:front() if self.front_ == nil then return nil end return self.front_.data end function SingleList:back() if self.rear_ == nil then return nil end return self.rear_.data end function SingleList:pairs() local node = self.front_ return function() if node ~= nil then local data = node.data node = node.next return data end end end
-- Copyright (c) 2013 ASMlover. All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- * Redistributions of source code must retain the above copyright -- notice, this list ofconditions and the following disclaimer. -- -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in -- the documentation and/or other materialsprovided with the -- distribution. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -- FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -- COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. require 'object' SingleList = {} function SingleList.new() local obj = { front_ = nil, rear_ = nil, size_ = 0 } obj = newObject(obj, SingleList) return obj end function SingleList:clear() while self.front_ ~= nil do local node = self.front_ self.front_ = self.front_.next node = nil end self.front_ = nil self.rear_ = nil self.size_ = 0 end function SingleList:empty() return self.front_ == nil end function SingleList:size() return self.size_ end function SingleList:push_back(x) local node = { next = nil, data = x } if self.front_ == nil then self.front_ = node self.rear_ = self.front_ else self.rear_.next = node self.rear_ = node end self.size_ = self.size_ + 1 end function SingleList:push_front(x) local node = { next = self.front_, data = x } self.front_ = node if self.rear_ == nil then self.rear_ = node end self.size_ = self.size_ + 1 end function SingleList:pop_front() if self.front_ == nil then return end local node = self.front_ self.front_ = self.front_.next node = nil self.size_ = self.size_ - 1 end function SingleList:front() if self.front_ == nil then return nil end return self.front_.data end function SingleList:back() if self.rear_ == nil then return nil end return self.rear_.data end function SingleList:pairs() local node = self.front_ return function() if node ~= nil then local data = node.data node = node.next return data end end end
fix bug of single_list push_front
fix bug of single_list push_front
Lua
bsd-2-clause
ASMlover/study,ASMlover/study,ASMlover/study,ASMlover/study,ASMlover/study,ASMlover/study,ASMlover/study,ASMlover/study,ASMlover/study
ed96af39601a84b9ea1a6919283696820070d474
src/cosy/server/middleware/perform.lua
src/cosy/server/middleware/perform.lua
local resource = require "cosy.server.resource" local Perform = {} function Perform.request (context) local request = context.request local response = context.response local r = resource (context) for _, k in ipairs (request.resource) do r = r [k] if r == nil then error { code = 404, message = "Not Found", } end end local method = r [request.method] if not method then error { code = 405, message = "Method Not Allowed", } end response.body = method (r, context) if not response.code then response.code = 200 response.message = "OK" end end return Perform
local Resource = require "cosy.server.resource" local Perform = {} function Perform.request (context) local request = context.request local response = context.response local r = Resource.root (context) for _, k in ipairs (request.resource) do r = r / k if not Resource.exists (r) then error { code = 404, message = "Not Found", } end end local method = r [request.method] if not method then error { code = 405, message = "Method Not Allowed", } end response.body = method (r, context) if not response.code then response.code = 200 response.message = "OK" end end return Perform
Fix perform middleware.
Fix perform middleware.
Lua
mit
CosyVerif/data-server,CosyVerif/data-server
06f1192f56b01552a3219aef228bfaed49588dca
cleanup.lua
cleanup.lua
local util = require("util") local smartmove = require("smartmove") local robot = require("robot") local shell = require("shell") local objectStore = require("objectStore") local NEEDS_CHARGE_THRESHOLD = 0.1 local FULL_CHARGE_THRESHOLD = 0.95 local Cleanup = { } function Cleanup:ok() --luacheck: no unused args if util.needsCharging(NEEDS_CHARGE_THRESHOLD, self.move:distanceFromStart()) then print("charge level is low!") return false end return true end function Cleanup:_cleanHere(isPickup) if not self:ok() then return false end if isPickup then robot.swingDown() else local _, blockType = robot.detectDown() if blockType == "liquid" then local result = robot.placeDown() if not result then print("could not place a cleanup block") return false end end end return true end function Cleanup:backToStart() if not self.move:moveToXZY(0, 0, 0) then print("could not get back to 0,0,0 for some reason.") return false end self.move:faceDirection(1) -- charge if needed, accounting for the distance to the very end of the Cleanup since -- that might be how far it will need to travel if util.needsCharging(NEEDS_CHARGE_THRESHOLD, math.abs(self.options.width) + math.abs(self.options.height) + math.abs(self.options.depth)) then if not util.waitUntilCharge(FULL_CHARGE_THRESHOLD, 300) then print("waited a long time and I didn't get charged enough :(") return false end end return true end function Cleanup:iterate() self.stepsHeight = 1 -- cleanup block is always slot 1 robot.select(1) if not self.move:forward() then print("could not enter Cleanup area.") self:backToStart() return false end local firstLevel = true repeat -- no need to move down on the first level, robot starts on that level already if not firstLevel then -- return to the (1,0,_) point for the level we're currently on local result = self.move:moveToXZ(1, 0) if not result then print("failed to return to starting point to begin the next Cleanup level") return self:backToStart() end result = self.move:down() if not result then print("failed to move down to the next level") return self:backToStart() end self.stepsHeight = self.stepsHeight + 1 self.move:faceDirection(1) end firstLevel = false local laneNum = 1 while laneNum <= self.options.width do if laneNum ~= 1 then -- turn corner local orient = self.move.orient if orient == 1 then self.move:turnLeft() else self.move:turnRight() end if not self.move:forward() then print("could not turn the corner") return false end if orient == 1 then self.move:turnLeft() else self.move:turnRight() end end -- go down lane for d=1,self.options.depth-1 do -- luacheck: no unused args if not self:_cleanHere() then print("could not clean here") return self:backToStart() end if not self.move:forward() then print("couldn't step forward") return self:backToStart(); end end if not self:_cleanHere() then print("could not clean here") return self:backToStart() end -- pick up dirt from the previous lane if laneNum > 1 then self.move:turnLeft() if not self.move:forward() then print("couldn't get back to the previous lane") return self:backToStart(); end self.move:turnLeft() for d=1,self.options.depth-1 do -- luacheck: no unused args if not self:_cleanHere(true) then print("could not pick up dirt") return self:backToStart() end if not self.move:forward() then print("couldn't step forward") return self:backToStart(); end end if not self:_cleanHere(true) then print("could not clean here") return self:backToStart() end -- now back to where we were self.move:turnLeft() if not self.move:forward() then print("couldn't get back start the next lane") return self:backToStart(); end self.move:turnRight() end laneNum = laneNum + 1 end -- we need to pick up the last lane -- just turn around and go back down self.move:turnLeft() self.move:turnLeft() for d=1,self.options.depth-1 do -- luacheck: no unused args if not self:_cleanHere(true) then print("could not pick up dirt") return self:backToStart() end if not self.move:forward() then print("couldn't step forward") return self:backToStart(); end end if not self:_cleanHere(true) then print("could not clean here") return self:backToStart() end until self.stepsHeight >= self.options.height local returnedToStart = self:backToStart() return returnedToStart, true end function Cleanup:start() local result local isDone result, isDone = self:iterate() while (result and not isDone) do print("headed out again!") result, isDone = self:iterate() end if isDone then print("Cleanup complete.") elseif not result then print("Halting.") end return isDone or false end function Cleanup:saveState() return objectStore.saveObject("cleanup", self.options) end function Cleanup:loadState() local result = objectStore.loadObject("cleanup") if result ~= nil then self.options = result return true end return false end function Cleanup.new(o) o = o or {} setmetatable(o, { __index = Cleanup }) o.move = o.move or smartmove.new() o.options = o.options or {} o.options.width = tonumber(o.options.width or "10") o.options.depth = tonumber(o.options.depth or "10") o.options.height = tonumber(o.options.height or "1") return o end local args, options = shell.parse( ... ) if args[1] == 'start' then if (args[2] == 'help') then print("usage: cleanup start --width=25 --depth=25 --height=9") else local q = Cleanup.new({options = options}) q:saveState() q:start() end elseif args[1] == 'resume' then local q = Cleanup.new() if q:loadState() then q:start() else print("Cannot resume. Make sure the robot has a writable hard drive to save state in.") end end return Cleanup
local util = require("util") local smartmove = require("smartmove") local robot = require("robot") local shell = require("shell") local objectStore = require("objectStore") local NEEDS_CHARGE_THRESHOLD = 0.1 local FULL_CHARGE_THRESHOLD = 0.95 local Cleanup = { } function Cleanup:ok() --luacheck: no unused args if util.needsCharging(NEEDS_CHARGE_THRESHOLD, self.move:distanceFromStart()) then print("charge level is low!") return false end return true end function Cleanup:_cleanHere(isPickup) if not self:ok() then return false end if isPickup then robot.swingDown() else local _, blockType = robot.detectDown() if blockType == "liquid" then local result = robot.placeDown() if not result then print("could not place a cleanup block") return false end end end return true end function Cleanup:backToStart() if not self.move:moveToXZY(0, 0, 0) then print("could not get back to 0,0,0 for some reason.") return false end self.move:faceDirection(1) -- charge if needed, accounting for the distance to the very end of the Cleanup since -- that might be how far it will need to travel if util.needsCharging(NEEDS_CHARGE_THRESHOLD, math.abs(self.options.width) + math.abs(self.options.height) + math.abs(self.options.depth)) then if not util.waitUntilCharge(FULL_CHARGE_THRESHOLD, 300) then print("waited a long time and I didn't get charged enough :(") return false end end return true end function Cleanup:iterate() self.stepsHeight = 1 -- cleanup block is always slot 1 robot.select(1) if not self.move:forward() then print("could not enter Cleanup area.") self:backToStart() return false end local firstLevel = true repeat -- no need to move down on the first level, robot starts on that level already if not firstLevel then -- return to the (1,0,_) point for the level we're currently on local result = self.move:moveToXZ(1, 0) if not result then print("failed to return to starting point to begin the next Cleanup level") return self:backToStart() end result = self.move:down() if not result then print("failed to move down to the next level") return self:backToStart() end self.stepsHeight = self.stepsHeight + 1 self.move:faceDirection(1) end firstLevel = false local laneNum = 1 while laneNum <= self.options.width do if laneNum ~= 1 then -- turn corner local orient = self.move.orient if orient == 1 then self.move:turnLeft() else self.move:turnRight() end if not self.move:forward() then print("could not turn the corner") return false end if orient == 1 then self.move:turnLeft() else self.move:turnRight() end end -- go down lane for d=1,self.options.depth-1 do -- luacheck: no unused args if not self:_cleanHere() then print("could not clean here") return self:backToStart() end if not self.move:forward() then print("couldn't step forward") return self:backToStart(); end end if not self:_cleanHere() then print("could not clean here") return self:backToStart() end -- pick up dirt from the previous lane if laneNum > 1 then local orient = self.move.orient if orient == 1 then self.move:turnRight() else self.move:turnLeft() end if not self.move:forward() then print("couldn't get back to the previous lane") return self:backToStart(); end self.move:turnLeft() for d=1,self.options.depth-1 do -- luacheck: no unused args if not self:_cleanHere(true) then print("could not pick up dirt") return self:backToStart() end if not self.move:forward() then print("couldn't step forward") return self:backToStart(); end end if not self:_cleanHere(true) then print("could not clean here") return self:backToStart() end -- now back to where we were local orient = self.move.orient if orient == 1 then self.move:turnRight() else self.move:turnLeft() end if not self.move:forward() then print("couldn't get back start the next lane") return self:backToStart(); end self.move:turnRight() end laneNum = laneNum + 1 end -- we need to pick up the last lane -- just turn around and go back down self.move:turnLeft() self.move:turnLeft() for d=1,self.options.depth-1 do -- luacheck: no unused args if not self:_cleanHere(true) then print("could not pick up dirt") return self:backToStart() end if not self.move:forward() then print("couldn't step forward") return self:backToStart(); end end if not self:_cleanHere(true) then print("could not clean here") return self:backToStart() end until self.stepsHeight >= self.options.height local returnedToStart = self:backToStart() return returnedToStart, true end function Cleanup:start() local result local isDone result, isDone = self:iterate() while (result and not isDone) do print("headed out again!") result, isDone = self:iterate() end if isDone then print("Cleanup complete.") elseif not result then print("Halting.") end return isDone or false end function Cleanup:saveState() return objectStore.saveObject("cleanup", self.options) end function Cleanup:loadState() local result = objectStore.loadObject("cleanup") if result ~= nil then self.options = result return true end return false end function Cleanup.new(o) o = o or {} setmetatable(o, { __index = Cleanup }) o.move = o.move or smartmove.new() o.options = o.options or {} o.options.width = tonumber(o.options.width or "10") o.options.depth = tonumber(o.options.depth or "10") o.options.height = tonumber(o.options.height or "1") return o end local args, options = shell.parse( ... ) if args[1] == 'start' then if (args[2] == 'help') then print("usage: cleanup start --width=25 --depth=25 --height=9") else local q = Cleanup.new({options = options}) q:saveState() q:start() end elseif args[1] == 'resume' then local q = Cleanup.new() if q:loadState() then q:start() else print("Cannot resume. Make sure the robot has a writable hard drive to save state in.") end end return Cleanup
fixes looping bug
fixes looping bug
Lua
apache-2.0
InfinitiesLoop/oclib
600b0cce1d3e5ebf19b1a45477f9dcfdcd368319
lua/kni.lua
lua/kni.lua
local ffi = require "ffi" local dpdkc = require "dpdkc" local dpdk = require "dpdk" require "utils" local mod = {} local mg_kni = {} mod.mg_kni = mg_kni mg_kni.__index = mg_kni ffi.cdef[[ struct rte_kni; struct rte_kni * mg_create_kni(uint8_t port_id, uint8_t core_id, void* mempool_ptr, const char name[]); unsigned rte_kni_tx_burst ( struct rte_kni * kni, struct rte_mbuf ** mbufs, unsigned num ); unsigned rte_kni_rx_burst ( struct rte_kni * kni, struct rte_mbuf ** mbufs, unsigned num ); int rte_kni_handle_request ( struct rte_kni * kni ); unsigned mg_kni_tx_single(struct rte_kni * kni, struct rte_mbuf * mbuf); void rte_kni_close ( void ); int rte_kni_release ( struct rte_kni * kni ); void rte_kni_init(unsigned int max_kni_ifaces); ]] function mod.createKNI(core, device, mempool, name) --printf("kni C pointer print:") --printPtr(mempool) core = core or 0 --printf("port id %d", device.id) --printf("in KNI ptr memp %p", mempool) --printPtr(mempool) local kni = ffi.C.mg_create_kni(device.id, core, mempool, name) --printPtr(mempool) --printf("KNI should be nil = %p ,, mempool = %p", kni, mempool) --if(kni == nil)then -- printf("KNI == NIL !!!") --else -- printf("KNI not nil") --end return setmetatable({ kni = kni, core = core, device = device }, mg_kni) end function mg_kni:rxBurst(bufs, nmax) return ffi.C.rte_kni_rx_burst(self.kni, bufs.array, nmax) end function mg_kni:txSingle(mbuf) ffi.C.mg_kni_tx_single(self.kni, mbuf) end function mg_kni:handleRequest() ffi.C.rte_kni_handle_request(self.kni) end function mg_kni:release() return ffi.C.rte_kni_release(self.kni) end function mod.init(num) return ffi.C.rte_kni_init(num) end function mod.close() ffi.C.rte_kni_close() end return mod
local ffi = require "ffi" local dpdkc = require "dpdkc" local dpdk = require "dpdk" require "utils" local mod = {} local mg_kni = {} mod.mg_kni = mg_kni mg_kni.__index = mg_kni ffi.cdef[[ struct rte_kni; struct rte_kni * mg_create_kni(uint8_t port_id, uint8_t core_id, void* mempool_ptr, const char name[]); unsigned mg_kni_tx_burst ( struct rte_kni * kni, struct rte_mbuf ** mbufs, unsigned num ); unsigned rte_kni_rx_burst ( struct rte_kni * kni, struct rte_mbuf ** mbufs, unsigned num ); int rte_kni_handle_request ( struct rte_kni * kni ); unsigned mg_kni_tx_single(struct rte_kni * kni, struct rte_mbuf * mbuf); void rte_kni_close ( void ); int rte_kni_release ( struct rte_kni * kni ); void rte_kni_init(unsigned int max_kni_ifaces); ]] -- only works with "insmod deps/dpdk/x86_64-native-linuxapp-gcc/kmod/rte_kni.ko" function mod.createKni(core, device, mempool, name) core = core or 0 local kni = ffi.C.mg_create_kni(device.id, core, mempool, name) return setmetatable({ kni = kni, core = core, device = device, name = name }, mg_kni) end -- not blocking recv function mg_kni:recv(bufs, nmax) return ffi.C.rte_kni_rx_burst(self.kni, bufs.array, nmax) end function mg_kni:sendN(bufs, nmax) return ffi.C.mg_kni_tx_burst(self.kni, bufs.array, nmax) end function mg_kni:send(bufs) return ffi.C.mg_kni_tx_burst(self.kni, bufs.array, bufs.size) end function mg_kni:sendSingle(mbuf) ffi.C.mg_kni_tx_single(self.kni, mbuf) end function mg_kni:handleRequest() ffi.C.rte_kni_handle_request(self.kni) end function mg_kni:setIP(ip, net) ip = ip or "192.168.1.1" net = net or 24 -- TODO make this nicer io.popen("/sbin/ifconfig " .. self.name .. " " .. ip .. "/" .. net) self:handleRequest() dpdk.sleepMillisIdle(1) end function mg_kni:release() return ffi.C.rte_kni_release(self.kni) end function mod.init(num) return ffi.C.rte_kni_init(num) end function mod.close() ffi.C.rte_kni_close() end return mod
[kni] Many updates, fixes and improvements
[kni] Many updates, fixes and improvements
Lua
mit
libmoon/libmoon,scholzd/libmoon,emmericp/libmoon,libmoon/libmoon,libmoon/libmoon,emmericp/libmoon,emmericp/libmoon,scholzd/libmoon,scholzd/libmoon
6aa9553b1df04718a9ea826f85e9b5339f371621
home/.hammerspoon/jira.lua
home/.hammerspoon/jira.lua
local utils = require('utils') local jiraAccount = require ('jiraAccount') local log = hs.logger.new('init.lua', 'debug') -- Public part local jira = {} -- Returns a Jira URL to browse the given issue Key function jira.getBrowseUrl(key) return string.format("%s%s%s", jiraAccount.getBaseUrl(), "browse/", key) end -- Returns a Jira URL to log work onto given issue id function jira.getLogWorkUrl(id) return string.format("%s%s%s", jiraAccount.getBaseUrl(), "secure/CreateWorklog!default.jspa?id=", id) end -- Type JIRA issue browsing base url function jira.typeBrowseUrl() local url = jira.getBrowseUrl(utils.getTrimmedSelectedText()) hs.eventtap.keyStrokes(url) end -- Type a JIRA bug template function jira.typeBugTemplate() local source=[[ # *Steps to reproduce* ## ## # *Expected result* ## ## # *Actual* ## ## # *Extra information* ## ## ]] hs.eventtap.keyStrokes(source) end -- Search the highlighted selection in Request.jira.com function jira.search() local url = string.format("%s%s%s%s", jiraAccount.getBaseUrl(), "issues/?jql=text%20~%20%22", utils.getTrimmedSelectedText(), "%22") log.f("Searching '%s'", url) -- TODO: if empty, pop-up a chooser utils.browseUrl(url) end -- Browse the issue key currently highlighted selection, or pop up a chooser function jira.browseIssue() local key = utils.getTrimmedSelectedText() if key == "" then log.f("browseIssue: no selection: invoking graphical chooser") lookupJiraIssue() else -- Does the key starts with only a digit ? local c1 = string.sub(key, 1,1) if string.match(c1, "^%d") ~= nil then -- Yes: add the default project prefix ! log.f("browseIssue: first char '%s' is a digit, adding prefix '%s'", c1, jiraAccount.getDefaultProjectPrefix()) key = jiraAccount.getDefaultProjectPrefix() .. key end log.f("browseIssue: browse issue '%s'", key) utils.browseUrl(jira.getBrowseUrl(key)) end end -- Log work for given issue id in browser function jira.logWork(id) utils.browseUrl(jira.getLogWorkUrl(id)) end -- Private part -- Below from https://github.com/CasperKoning/dothammerspoon/blob/master/jira.lua -- Jira viewer: (also see https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-version-2-tutorial) function createAuthorisationRequestBody() return string.format('{ "username": "%s", "password": "%s" }', jiraAccount.getUsername(), jiraAccount.getPassword()) end function getSession() log.f("getSession(): entering") data = createAuthorisationRequestBody() headers = {["Content-Type"] = "application/json"} status, body, returnedHeaders = hs.http.post(jiraAccount.getBaseUrl() .. 'rest/auth/latest/session', data, headers) log.f("getSession(): received status %s, body '%s', headers '%s'", status, body, headers) if status == 200 then result = hs.json.decode(body) session = result["session"] return session["name"], session["value"] else return nil, nil end end function lookupJiraIssue() sessionName, sessionValue = getSession() if (sessionName ~= nil and sessionValue ~= nil) then log.f("lookupJiraIssue(): got a valid session.") local cookieHeaders = {["cookie"] = sessionName .. "=" .. sessionValue, ["Content-Type"] = "application/json"} local picker = hs.chooser.new(function(userInput) if userInput ~= nil then log.f("chooser: user chose '%s'",userInput) if userInput["key"] ~= Nil then local url = jira.getBrowseUrl(userInput["key"]) log.f("chooser: user chose '%s', browsing to '%s'", userInput["key"], url) hs.execute("open " .. url) end end end) picker:query(jiraAccount.getDefaultIssueSearch()) picker:queryChangedCallback( function(query) log.f("queryChangedCallback(): query is '%s'", query) if string.len(query) > 3 then log.f("queryChangedCallback(): query '%s' could be a valid JIRA issue key", query) hs.http.asyncGet( getJiraQueryUrl(query), cookieHeaders, function(status, body, headers) log.f("queryChangedCallback(): received status %s, body '%s', headers '%s'", status, body, headers) if status == 200 then searchResult = hs.json.decode(body) if searchResult["fields"] ~= nil then local results = {} local key = searchResult["key"] local summary = searchResult["fields"]["summary"] table.insert(results, {text = key, subText = summary, key = key}) picker:choices(results) end end end ) else log.f("queryChangedCallback(): query '%s' cannot be a valid JIRA issue key", query) end end ) picker:rows(1) picker:show() else log.f("lookupJiraIssue(): could not get a valid session.") notify = hs.notify.new() notify:title("Jira") notify:informativeText("Could not get authorization") notify:send() end end function getJiraQueryUrl(query) local url = string.format("%s%s%s", jiraAccount.getBaseUrl(), "rest/api/latest/issue/", query) log.f("jiraQuey(): return url '%s'", url) return url end return jira
local utils = require('utils') local jiraAccount = require ('jiraAccount') local log = hs.logger.new('init.lua', 'debug') -- Public part local jira = {} -- Returns a Jira URL to browse the given issue Key function jira.getBrowseUrl(key) return string.format("%s%s%s", jiraAccount.getBaseUrl(), "browse/", key) end -- Returns a Jira URL to log work onto given issue id function jira.getLogWorkUrl(id) return string.format("%s%s%s", jiraAccount.getBaseUrl(), "secure/CreateWorklog!default.jspa?id=", id) end -- Type JIRA issue browsing base url function jira.typeBrowseUrl() local url = jira.getBrowseUrl(utils.getTrimmedSelectedText()) hs.eventtap.keyStrokes(url) end -- Type a JIRA bug template function jira.typeBugTemplate() local source=[[ # *Steps to reproduce* ## ## # *Expected result* ## ## # *Actual* ## ## # *Reproducibility* ## 100% # *Traces* ## File attached foobar.log ## {code}Or traces captured directly pasted here, between "code" tag elements, maybe multi lines. {code} ## !Foobar Sreenshot.png|thumbnail! # *Extra Information* ## ## ]] hs.eventtap.keyStrokes(source) end -- Search the highlighted selection in Request.jira.com function jira.search() local url = string.format("%s%s%s%s", jiraAccount.getBaseUrl(), "issues/?jql=text%20~%20%22", utils.getTrimmedSelectedText(), "%22") log.f("Searching '%s'", url) -- TODO: if empty, pop-up a chooser utils.browseUrl(url) end -- Browse the issue key currently highlighted selection, or pop up a chooser function jira.browseIssue() local key = utils.getTrimmedSelectedText() if key == "" then log.f("browseIssue: no selection: invoking graphical chooser") lookupJiraIssue() else -- Does the key starts with only a digit ? local c1 = string.sub(key, 1,1) if string.match(c1, "^%d") ~= nil then -- Yes: add the default project prefix ! log.f("browseIssue: first char '%s' is a digit, adding prefix '%s'", c1, jiraAccount.getDefaultProjectPrefix()) key = jiraAccount.getDefaultProjectPrefix() .. key end log.f("browseIssue: browse issue '%s'", key) utils.browseUrl(jira.getBrowseUrl(key)) end end -- Log work for given issue id in browser function jira.logWork(id) utils.browseUrl(jira.getLogWorkUrl(id)) end -- Private part -- Below from https://github.com/CasperKoning/dothammerspoon/blob/master/jira.lua -- Jira viewer: (also see https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-version-2-tutorial) function createAuthorisationRequestBody() return string.format('{ "username": "%s", "password": "%s" }', jiraAccount.getUsername(), jiraAccount.getPassword()) end function getSession() log.f("getSession(): entering") data = createAuthorisationRequestBody() headers = {["Content-Type"] = "application/json"} status, body, returnedHeaders = hs.http.post(jiraAccount.getBaseUrl() .. 'rest/auth/latest/session', data, headers) log.f("getSession(): received status %s, body '%s', headers '%s'", status, body, headers) if status == 200 then result = hs.json.decode(body) session = result["session"] return session["name"], session["value"] else return nil, nil end end function lookupJiraIssue() sessionName, sessionValue = getSession() if (sessionName ~= nil and sessionValue ~= nil) then log.f("lookupJiraIssue(): got a valid session.") local cookieHeaders = {["cookie"] = sessionName .. "=" .. sessionValue, ["Content-Type"] = "application/json"} local picker = hs.chooser.new(function(userInput) if userInput ~= nil then log.f("chooser: user chose '%s'",userInput) if userInput["key"] ~= Nil then local url = jira.getBrowseUrl(userInput["key"]) log.f("chooser: user chose '%s', browsing to '%s'", userInput["key"], url) hs.execute("open " .. url) end end end) picker:query(jiraAccount.getDefaultIssueSearch()) picker:queryChangedCallback( function(query) log.f("queryChangedCallback(): query is '%s'", query) if string.len(query) > 3 then log.f("queryChangedCallback(): query '%s' could be a valid JIRA issue key", query) hs.http.asyncGet( getJiraQueryUrl(query), cookieHeaders, function(status, body, headers) log.f("queryChangedCallback(): received status %s, body '%s', headers '%s'", status, body, headers) if status == 200 then searchResult = hs.json.decode(body) if searchResult["fields"] ~= nil then local results = {} local key = searchResult["key"] local summary = searchResult["fields"]["summary"] table.insert(results, {text = key, subText = summary, key = key}) picker:choices(results) end end end ) else log.f("queryChangedCallback(): query '%s' cannot be a valid JIRA issue key", query) end end ) picker:rows(1) picker:show() else log.f("lookupJiraIssue(): could not get a valid session.") notify = hs.notify.new() notify:title("Jira") notify:informativeText("Could not get authorization") notify:send() end end function getJiraQueryUrl(query) local url = string.format("%s%s%s", jiraAccount.getBaseUrl(), "rest/api/latest/issue/", query) log.f("jiraQuey(): return url '%s'", url) return url end return jira
Updated JIRA bug template
Updated JIRA bug template
Lua
mit
maanuair/dotfiles_tmp,maanuair/dotfiles
55c3fdbdc2efdbe73be79f752f9387a461eeeed2
spec/request_spec.lua
spec/request_spec.lua
describe('lift.request', function() local req = require 'lift.request' local stream = require 'lift.stream' local su = require 'spec.util' it("can fetch an HTML page", su.async(function() local sb = {} -- string buffer containing the page req('www.google.com/invalid_url'):pipe(stream.to_array(sb)):wait_finish() assert.match('404 Not Found', table.concat(sb)) end)) local function try_get(url) return function() local rs = req(url) repeat local data = rs:read() until data == nil assert(not rs.read_error) end end it("pushes errors onto the stream", su.async(function() assert.no_error(try_get('www.google.com/invalid_url')) assert.error_matches(try_get('-s www.google.com'), 'malformed URL') assert.error_matches(try_get('invalid.url'), 't resolve host') assert.error_matches(try_get('weird://protocol.com'), 'Protocol "weird" not supported or disabled in libcurl') end)) it("can fetch a PNG image (Google's logo)", su.async(function() local sb = {} -- string buffer containing the page req('www.google.com'):pipe(stream.to_array(sb)):wait_finish() local html = table.concat(sb) assert.equal('</html>', html:sub(-7)) -- parse Google's logo URL local logo_path = html:match('background:url%(([^)]-googlelogo[^)]*)%)') -- download the PNG local sb2 = {} req('www.google.com'..logo_path):pipe(stream.to_array(sb2)):wait_finish() local content = table.concat(sb2) assert.equal(5482, #content) -- size of the PNG end)) end)
describe('lift.request', function() local req = require 'lift.request' local stream = require 'lift.stream' local su = require 'spec.util' it("can fetch an HTML page", su.async(function() local sb = {} -- string buffer containing the page req('www.google.com/invalid_url'):pipe(stream.to_array(sb)):wait_finish() assert.match('404 Not Found', table.concat(sb)) end)) local function try_get(url) return function() local rs = req(url) repeat local data = rs:read() until data == nil assert(not rs.read_error) end end it("pushes errors onto the stream", su.async(function() assert.no_error(try_get('www.google.com/invalid_url')) assert.error_matches(try_get('-s www.google.com'), 'malformed URL') assert.error_matches(try_get('invalid.url'), 't resolve host') assert.error_matches(try_get('weird://protocol.com'), 'Protocol .- not supported') end)) it("can fetch a PNG image (Google's logo)", su.async(function() local sb = {} -- string buffer containing the page req('www.google.com'):pipe(stream.to_array(sb)):wait_finish() local html = table.concat(sb) assert.equal('</html>', html:sub(-7)) -- parse Google's logo URL local logo_path = html:match('background:url%(([^)]-googlelogo[^)]*)%)') -- download the PNG local sb2 = {} req('www.google.com'..logo_path):pipe(stream.to_array(sb2)):wait_finish() local content = table.concat(sb2) assert.equal(5482, #content) -- size of the PNG end)) end)
Fix dependency on specific version of curl
Fix dependency on specific version of curl
Lua
mit
tbastos/lift
8758b3b634abbb32c91f7a3c3072f48aa451956d
item/bottles.lua
item/bottles.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.bottles' WHERE itm_id IN (2500, 2496, 2497, 2501, 2499); local common = require("base.common") local lookat = require("base.lookat") local evilrock = require("triggerfield.evilrock") local M = {} function InitDrinks() if ( drinkList == nil) then -- nameDE, nameEN, leftover item, { {empty target container, filled target container}, ...} drinkList={}; drinkList[2500] = { "Weinflasche", "bottle of wine", 2498, {{1858, 1860}, {224, 1857}, {2055, 2057}, {1840, 1842}, {2185, 2187}} }; -- Kelch, Goldkelch, Glas, Kupferkelch, Holzbecher drinkList[2496] = { "Wasserflasche", "bottle of water", 2498, { {1858, 1855}, {224, 1854}, {2055, 2058},{1840, 1841}, {2185, 2186} } }; drinkList[2497] = { "Metflasche", "bottle of mead", 2498, { {1858, 1853}, {224, 1856}, {2055, 2056},{1840, 1843}, {2185, 2188} } }; drinkList[2501] = { "Bierflasche", "bottle of dark beer", 2498, { {1908, 1909} } }; -- Krug drinkList[2499] = { "Ciderflasche", "bottle of cider", 2498, { {1858, 1859}, {224, 1861},{2055, 2059},{1840, 1844}, {2185, 2189} } }; -- init descriptions BottleQualDe={"Randvolle ","Volle ","Halbvolle ","Fast leere "}; BottleQualEn={"Brimfull ", "Full ","Half full ","Almost empty "}; BottleQualLm={8,6,3,1}; end end function M.UseItem(User, SourceItem) if firstcall==nil then InitDrinks(); firstcall=1; end local progress = User:getQuestProgress(1); local food = drinkList[ SourceItem.id ]; if (food ~= nil ) then Evilrockentrance(User, SourceItem, ltstate) local TargetItem = common.GetTargetItem(User, SourceItem); if( TargetItem ) then for i, combo in pairs(food[4]) do if combo[1] == TargetItem.id then -- fill drink if (TargetItem.number > 1) then world:erase( TargetItem, 1 ); User:createItem( combo[2], 1, 333,nil); else TargetItem.id = combo[2]; world:changeItem(TargetItem); end world:makeSound(10,User.pos) -- create leftovers if( SourceItem.quality > 199 ) then -- reduce one portion world:changeQuality( SourceItem, -100 ); else if( math.random( 50 ) <= 1 ) then common.InformNLS( User, "Die leere Flasche ist angeschlagen und unbrauchbar.", "The empty bottle is broken and no longer usable."); else local dataCopy = {descriptionDe=SourceItem:getData("descriptionDe"), descriptionEn=SourceItem:getData("descriptionEn")}; local notCreated = User:createItem( food[3], 1, 333, dataCopy); -- create the remnant item if ( notCreated > 0 ) then -- too many items -> character can't carry anymore world:createItemFromId(food[3], notCreated, User.pos, true, 333, dataCopy); common.HighInformNLS(User, "Du kannst nichts mehr halten.", "You can't carry any more."); end end world:erase(SourceItem,1); end -- cancel after one found item break; end -- found item end -- search loop else common.InformNLS( User, "Nimm die Flasche und ein Trinkgef in deine Hnde.", "Take the bottle and a drinking vessel in your hands."); end else --User:inform("unkown bottle item "); end end function M.LookAtItem(User, Item) local lookAt = lookat.GenerateLookAt(User, Item) if firstcall==nil then InitDrinks(); firstcall=1; end local food = drinkList[ Item.id ]; if food == nil then return lookAt end -- decode item quality, extract duration local itemDura=math.fmod(Item.quality,100); local itemQual=(Item.quality-itemDura)/100; --User:inform("portions "..itemQual); -- build description local DisplayText=""; -- build quality text for i,qualLimit in pairs(BottleQualLm) do if (itemQual>=qualLimit ) then DisplayText = common.GetNLS( User, BottleQualDe[i], BottleQualEn[i] ); break; end end DisplayText = DisplayText..common.GetNLS( User, food[1], food[2] ); if lookAt.description ~= nil then -- append the label DisplayText = DisplayText..". "..lookAt.description; end lookAt.description = DisplayText return lookAt end function Evilrockentrance(User, SourceItem, ltstate) local checkBucket = world:getItemOnField(position(997,199,2)) if checkBucket.id == 51 and SourceItem.id == 2496 then local foundSource -- check for empty bucket TargetItem = common.GetItemInArea(User.pos, 51); if (TargetItem ~= nil) then common.TurnTo( User, position(997,199,2) ); -- turn if necessary foundSource=true end if not foundSource then -- nothing found to fill the bucket. common.InformNLS(User,"Du solltest schon einen anderen Eimer zum Umfllen haben.","You should have another container to transfer the water."); return end if ( ltstate == Action.none ) then User:startAction( 20, 21, 5, 10, 25); User:talk(Character.say, "#me beginnt den Eimer zu befllen.", "#me starts to fill bucket.") return end world:swap(checkBucket,52,999) --[[ local checkFullBucket = world:getItemOnField(position(997,199,3)) if checkFullBucket.id == 52 then checkFullBucket.wear=255 world:changeItem(checkFullBucket) end ]] evilrock.RemoveEntranceTrap(User) local notCreated = User:createItem( 2498, 1, 999, nil ); -- create the new produced items if SourceItem.number == 1 then world:erase(SourceItem,1) return end end end return M
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.bottles' WHERE itm_id IN (2500, 2496, 2497, 2501, 2499); local common = require("base.common") local lookat = require("base.lookat") local evilrock = require("triggerfield.evilrock") local M = {} -- nameDE, nameEN, leftover item, { {empty target container, filled target container}, ...} local drinkList = {} drinkList[2500] = { "Weinflasche", "bottle of wine", 2498, {{1858, 1860}, {224, 1857}, {2055, 2057}, {1840, 1842}, {2185, 2187}} } -- Kelch, Goldkelch, Glas, Kupferkelch, Holzbecher drinkList[2496] = { "Wasserflasche", "bottle of water", 2498, { {1858, 1855}, {224, 1854}, {2055, 2058},{1840, 1841}, {2185, 2186} } } drinkList[2497] = { "Metflasche", "bottle of mead", 2498, { {1858, 1853}, {224, 1856}, {2055, 2056},{1840, 1843}, {2185, 2188} } } drinkList[2501] = { "Bierflasche", "bottle of dark beer", 2498, { {1908, 1909} } } -- Krug drinkList[2499] = { "Ciderflasche", "bottle of cider", 2498, { {1858, 1859}, {224, 1861},{2055, 2059},{1840, 1844}, {2185, 2189} } } local BottleQualDe = {"Randvolle ", "Volle ", "Halbvolle ", "Fast leere "} local BottleQualEn = {"Brimfull ", "Full ", "Half full ", "Almost empty "} local BottleQualLm = {8, 6, 3, 1} local function Evilrockentrance(User, SourceItem, ltstate) local checkBucket = world:getItemOnField(position(997,199,2)) if checkBucket.id == 51 and SourceItem.id == 2496 then local foundSource -- check for empty bucket TargetItem = common.GetItemInArea(User.pos, 51); if (TargetItem ~= nil) then common.TurnTo( User, position(997,199,2) ); -- turn if necessary foundSource=true end if not foundSource then -- nothing found to fill the bucket. common.InformNLS(User,"Du solltest schon einen anderen Eimer zum Umfllen haben.","You should have another container to transfer the water."); return end if ( ltstate == Action.none ) then User:startAction( 20, 21, 5, 10, 25); User:talk(Character.say, "#me beginnt den Eimer zu befllen.", "#me starts to fill bucket.") return end world:swap(checkBucket,52,999) --[[ local checkFullBucket = world:getItemOnField(position(997,199,3)) if checkFullBucket.id == 52 then checkFullBucket.wear=255 world:changeItem(checkFullBucket) end ]] evilrock.RemoveEntranceTrap(User) local notCreated = User:createItem( 2498, 1, 999, nil ); -- create the new produced items if SourceItem.number == 1 then world:erase(SourceItem,1) return end end end function M.UseItem(User, SourceItem) local progress = User:getQuestProgress(1); local food = drinkList[ SourceItem.id ]; if (food ~= nil ) then Evilrockentrance(User, SourceItem, ltstate) local TargetItem = common.GetTargetItem(User, SourceItem); if( TargetItem ) then for i, combo in pairs(food[4]) do if combo[1] == TargetItem.id then -- fill drink if (TargetItem.number > 1) then world:erase( TargetItem, 1 ); User:createItem( combo[2], 1, 333,nil); else TargetItem.id = combo[2]; world:changeItem(TargetItem); end world:makeSound(10,User.pos) -- create leftovers if( SourceItem.quality > 199 ) then -- reduce one portion world:changeQuality( SourceItem, -100 ); else if( math.random( 50 ) <= 1 ) then common.InformNLS( User, "Die leere Flasche ist angeschlagen und unbrauchbar.", "The empty bottle is broken and no longer usable."); else local dataCopy = {descriptionDe=SourceItem:getData("descriptionDe"), descriptionEn=SourceItem:getData("descriptionEn")}; local notCreated = User:createItem( food[3], 1, 333, dataCopy); -- create the remnant item if ( notCreated > 0 ) then -- too many items -> character can't carry anymore world:createItemFromId(food[3], notCreated, User.pos, true, 333, dataCopy); common.HighInformNLS(User, "Du kannst nichts mehr halten.", "You can't carry any more."); end end world:erase(SourceItem,1); end -- cancel after one found item break; end -- found item end -- search loop else common.InformNLS( User, "Nimm die Flasche und ein Trinkgef in deine Hnde.", "Take the bottle and a drinking vessel in your hands."); end else --User:inform("unkown bottle item "); end end function M.LookAtItem(User, Item) local lookAt = lookat.GenerateLookAt(User, Item) local food = drinkList[ Item.id ]; if food == nil then return lookAt end -- decode item quality, extract duration local itemDura=math.fmod(Item.quality,100); local itemQual=(Item.quality-itemDura)/100; --User:inform("portions "..itemQual); -- build description local DisplayText=""; -- build quality text for i,qualLimit in pairs(BottleQualLm) do if (itemQual>=qualLimit ) then DisplayText = common.GetNLS( User, BottleQualDe[i], BottleQualEn[i] ); break; end end DisplayText = DisplayText..common.GetNLS( User, food[1], food[2] ); if lookAt.description ~= nil then -- append the label DisplayText = DisplayText..". "..lookAt.description; end lookAt.description = DisplayText return lookAt end return M
#0010576 fix bottles
#0010576 fix bottles
Lua
agpl-3.0
Baylamon/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content
9a1c34fd1fea617aeaf0df8c175d5a9c49442b71
lua/entities/gmod_wire_hydraulic/init.lua
lua/entities/gmod_wire_hydraulic/init.lua
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) ENT.WireDebugName = "Hydraulic" include('shared.lua') function ENT:Initialize() self.Entity:PhysicsInit( SOLID_VPHYSICS ) self.Entity:SetMoveType( MOVETYPE_VPHYSICS ) self.Entity:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs( self.Entity, { "Length", "Constant", "Damping" } ) self.Outputs = Wire_CreateOutputs( self.Entity, { "Length", "Constant", "Damping" } ) self.Trigger = 0 if (self.constraint) then WireLib.TriggerOutput( self.Entity, "Constant", self.constraint:GetKeyValues().constant ) WireLib.TriggerOutput( self.Entity, "Damping", self.constraint:GetKeyValues().damping ) end end function ENT:Think() local c = self.constraint if(not (c and c:IsValid())) then return end; local p1 = self:GetWPos(c:GetTable().Ent1, c:GetTable().Phys1, c:GetTable().LPos1) local p2 = self:GetWPos(c:GetTable().Ent2, c:GetTable().Phys2, c:GetTable().LPos2) Wire_TriggerOutput(self.Entity, "Length", (p1 - p2):Length()) self.Entity:NextThink(CurTime()+0.04) end function ENT:Setup() self.current_length = 0 self.IsOn = true end function ENT:GetWPos( ent, phys, lpos ) if (ent:EntIndex() == 0) then return lpos end if (phys) and (phys:IsValid()) then return phys:LocalToWorld( lpos ) else return ent:LocalToWorld( lpos ) end end function ENT:SetConstraint( c ) self.constraint = c local p1 = self:GetWPos(c:GetTable().Ent1, c:GetTable().Phys1, c:GetTable().LPos1) local p2 = self:GetWPos(c:GetTable().Ent2, c:GetTable().Phys2, c:GetTable().LPos2) local dist = (p1 - p2) self:SetOverlayText( "Hydraulic length : " .. self.current_length .. "\nConstant: -\nDamping: -" ) WireLib.TriggerOutput( self.Entity, "Constant", self.constraint:GetKeyValues().constant ) WireLib.TriggerOutput( self.Entity, "Damping", self.constraint:GetKeyValues().damping ) self.constraint:Fire("SetSpringLength", self.current_length, 0) if self.rope then self.rope:Fire("SetLength", self.current_length, 0) end end function ENT:SetRope( r ) self.rope = r end function ENT:TriggerInput(iname, value) if (!self.constraint) then return end if (iname == "Length") then self.current_length = math.max(value,1) self.constraint:Fire("SetSpringLength", self.current_length) if self.rope then self.rope:Fire("SetLength", self.current_length, 0) end elseif (iname == "Constant") then self.current_constant = math.max(value,1)--math.Clamp(value,1,50000) self.constraint:Fire("SetSpringConstant",self.current_constant) timer.Simple( 0.1, function(a) WireLib.TriggerOutput( a.Entity, "Constant", a.constraint:GetKeyValues().constant ) end, self ) -- Needs to be delayed because ent:Fire doesn't update that fast. elseif (iname == "Damping") then self.current_damping = math.max(value,1)--math.Clamp(value,1,10000) self.constraint:Fire("SetSpringDamping",self.current_damping) timer.Simple( 0.1, function(a) WireLib.TriggerOutput( a.Entity, "Damping", a.constraint:GetKeyValues().damping ) end, self ) end self:SetOverlayText( "Hydraulic Length : " .. self.current_length .. "\nConstant: " .. (self.current_constant or "-") .. "\nDamping: " .. (self.current_damping or "-") ) end --[[ function ENT:ShowOutput() end ]] /*function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if (self.constraint) and (self.constraint:IsValid()) then info.constraint = self.constraint:EntIndex() end if (self.rope) and (self.rope:IsValid()) then info.rope = self.rope:EntIndex() end return info end*/ function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID, GetConstByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID, GetConstByID) if (GetConstByID) then if (info.constraint) and (info.constraint > 0) then local const = GetConstByID(info.constraint) if (const) then self:SetConstraint(const) end end if (info.rope) and (info.rope > 0) then local rope = GetConstByTable(info.rope) if (rope) then self:SetConstraint(rope) end end end end
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) ENT.WireDebugName = "Hydraulic" include('shared.lua') function ENT:Initialize() self.Entity:PhysicsInit( SOLID_VPHYSICS ) self.Entity:SetMoveType( MOVETYPE_VPHYSICS ) self.Entity:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs( self.Entity, { "Length", "Constant", "Damping" } ) self.Outputs = Wire_CreateOutputs( self.Entity, { "Length", "Constant", "Damping" } ) self.Trigger = 0 if (self.constraint) then WireLib.TriggerOutput( self.Entity, "Constant", self.constraint:GetKeyValues().constant ) WireLib.TriggerOutput( self.Entity, "Damping", self.constraint:GetKeyValues().damping ) end end function ENT:Think() local c = self.constraint if(not (c and c:IsValid())) then return end; local p1 = self:GetWPos(c:GetTable().Ent1, c:GetTable().Phys1, c:GetTable().LPos1) local p2 = self:GetWPos(c:GetTable().Ent2, c:GetTable().Phys2, c:GetTable().LPos2) Wire_TriggerOutput(self.Entity, "Length", (p1 - p2):Length()) self.Entity:NextThink(CurTime()+0.04) end function ENT:Setup() self.current_length = 0 self.IsOn = true end function ENT:GetWPos( ent, phys, lpos ) if (ent:EntIndex() == 0) then return lpos end if (phys) and (phys:IsValid()) then return phys:LocalToWorld( lpos ) else return ent:LocalToWorld( lpos ) end end function ENT:SetConstraint( c ) self.constraint = c local p1 = self:GetWPos(c:GetTable().Ent1, c:GetTable().Phys1, c:GetTable().LPos1) local p2 = self:GetWPos(c:GetTable().Ent2, c:GetTable().Phys2, c:GetTable().LPos2) local dist = (p1 - p2) self.current_length = dist:Length() self:SetOverlayText( "Hydraulic length : " .. self.current_length .. "\nConstant: -\nDamping: -" ) WireLib.TriggerOutput( self.Entity, "Constant", self.constraint:GetKeyValues().constant ) WireLib.TriggerOutput( self.Entity, "Damping", self.constraint:GetKeyValues().damping ) self.constraint:Fire("SetSpringLength", self.current_length, 0) if self.rope then self.rope:Fire("SetLength", self.current_length, 0) end end function ENT:SetRope( r ) self.rope = r end function ENT:TriggerInput(iname, value) if (!self.constraint) then return end if (iname == "Length") then self.current_length = math.max(value,1) self.constraint:Fire("SetSpringLength", self.current_length) if self.rope then self.rope:Fire("SetLength", self.current_length, 0) end elseif (iname == "Constant") then self.current_constant = math.max(value,1)--math.Clamp(value,1,50000) self.constraint:Fire("SetSpringConstant",self.current_constant) timer.Simple( 0.1, function(a) WireLib.TriggerOutput( a.Entity, "Constant", a.constraint:GetKeyValues().constant ) end, self ) -- Needs to be delayed because ent:Fire doesn't update that fast. elseif (iname == "Damping") then self.current_damping = math.max(value,1)--math.Clamp(value,1,10000) self.constraint:Fire("SetSpringDamping",self.current_damping) timer.Simple( 0.1, function(a) WireLib.TriggerOutput( a.Entity, "Damping", a.constraint:GetKeyValues().damping ) end, self ) end self:SetOverlayText( "Hydraulic Length : " .. self.current_length .. "\nConstant: " .. (self.current_constant or "-") .. "\nDamping: " .. (self.current_damping or "-") ) end --[[ function ENT:ShowOutput() end ]] /*function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if (self.constraint) and (self.constraint:IsValid()) then info.constraint = self.constraint:EntIndex() end if (self.rope) and (self.rope:IsValid()) then info.rope = self.rope:EntIndex() end return info end*/ function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID, GetConstByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID, GetConstByID) if (GetConstByID) then if (info.constraint) and (info.constraint > 0) then local const = GetConstByID(info.constraint) if (const) then self:SetConstraint(const) end end if (info.rope) and (info.rope > 0) then local rope = GetConstByTable(info.rope) if (rope) then self:SetConstraint(rope) end end end end
[Hydraulic] Fixed hydraulic length starting at 0, causing the props to snap together unless they were frozen. The length now starts at whatever length is when the hydraulic is created.
[Hydraulic] Fixed hydraulic length starting at 0, causing the props to snap together unless they were frozen. The length now starts at whatever length is when the hydraulic is created.
Lua
apache-2.0
NezzKryptic/Wire,thegrb93/wire,dvdvideo1234/wire,wiremod/wire,bigdogmat/wire,notcake/wire,CaptainPRICE/wire,Grocel/wire,immibis/wiremod,garrysmodlua/wire,mms92/wire,plinkopenguin/wiremod,mitterdoo/wire,sammyt291/wire,rafradek/wire,Python1320/wire
f95ec132bd17ac240c59f53ffa9cf5196927da23
include/mars/util/mars-compile-evts.lua
include/mars/util/mars-compile-evts.lua
if not arg[1] then print ('Error: no input source specified') return end if not arg[2] then print ('Error: no prog file specified') return end local CODE_TEMPLATE = 'code/await Emit_{#1}_Event ({#2}) -> none\ndo\n' .. '\tawait async ({#3}) do\n' .. '\t\temit {#4} ({#5});\n' .. '\tend\n' .. 'end' local f = io.open (arg[1], 'r') local maestro_src = f:read ('*all') f:close() lines = io.lines (arg[2]) inputs_evt = {} for line in io.lines (arg[2]) do line = line:gsub("^%s*(.-)%s*$", "%1") if line:sub (1, 5) == 'input' then table.insert (inputs_evt, {}) inputs_evt[#inputs_evt] = { line = line, args = {}, evt = '', emitter = '' } end end local TO_GEN = '' TO_GEN = '/*' .. '\n * This excerpt of code is automatically generated by Mars.' .. '\n * Do not edit it.' .. '\n */\n\n' for i=1, #inputs_evt do local input = inputs_evt[i].line input = input:sub (5 + 1):gsub("^%s*(.-)%s*$", "%1") local args = input:match ("%((.-)%)") local evt = input:match ("%).-$"):sub(2):gsub("^%s*(.-)%s*;$", "%1") local code_name = evt:lower():gsub('_.', string.upper):gsub('^.', string.upper) local code = string.gsub (CODE_TEMPLATE, '{#1}', code_name) local params = '' if args == 'none' then params = args else local k = 1 for arg in args:gmatch('([^,]+)') do arg = arg:gsub("^%s*(.-)%s*$", "%1") table.insert(inputs_evt[i].args, arg) params = params .. 'var ' .. arg .. ' arg' .. k .. ', ' k = k + 1 end params = params:sub (1, -3) end code = code:gsub ('{#2}', params) params = params:gsub ('(var .-).- ,-', '') if params == 'none' then params = '_' end code = code:gsub ('{#3}', params) code = code:gsub ('{#4}', evt) if params == '_' then params = '' end code = code:gsub ('{#5}', params) inputs_evt[i].evt = evt inputs_evt[i].emitter = 'Emit_' .. code_name .. '_Event'; TO_GEN = TO_GEN .. code .. '\n' end CODE_TEMPLATE = '\n' .. 'code/await Handle_Mapping (var _char&& mapping) -> none\n' .. 'do\n' .. '\tvar Exception.Lua? e;\n' .. '\tcatch e do\n' .. '\t{#1}\n' .. '\tend\n' .. '\tif e? then\n' .. '\t\t_fprintf (_stderr, "[Mapping error:] %%s\\n", e!.message);\n' .. '\tend\n' .. 'end' code = '' local cond = '_strcmp(mapping, "{#1}") == 0' for i = 1, #inputs_evt do input = inputs_evt[i] local statement if i == 1 then statement = '\tif' else statement = '\telse/if' end code = code .. statement .. ' ' .. cond:gsub('{#1}', input.evt) .. ' then\n' local body = '' local params = '' local attrs = '' local mapping_args = '' local ident = '\t\t\t' for j = 1, #input.args do local varname = 'arg' .. j local vardecl = 'var ' .. input.args[j] .. ' ' .. varname body = body .. ident .. vardecl .. ' = _;\n' params = params .. varname .. ', ' mapping_args = mapping_args .. '@' .. varname .. ', ' attrs = attrs .. ident .. varname .. ' = [[ CLIENT.mapping.args[' .. j .. '] or @' .. varname .. ' ]];\n' end params = params:sub (1, -3) mapping_args = mapping_args:sub (1, -3) body = body .. ident .. '[[ apply_mapping ("' .. input.evt ..'", ' .. mapping_args .. ') ]]\n' body = body .. attrs body = body .. '\t\t\t' .. 'await ' .. input.emitter .. '(' .. params .. ');\n' code = code .. body .. '\t\tend' end code = code TO_GEN = TO_GEN .. CODE_TEMPLATE:gsub('{#1}', code) .. '\n' maestro_src = maestro_src:gsub ('__COMPILED_EVTS__', TO_GEN) f = io.open (arg[1], 'w') f:write (maestro_src) f:close()
if not arg[1] then print ('Error: no input source specified') return end if not arg[2] then print ('Error: no prog file specified') return end local CODE_TEMPLATE = 'code/await Emit_{#1}_Event ({#2}) -> none\ndo\n' .. '\tawait async ({#3}) do\n' .. '\t\temit {#4} ({#5});\n' .. '\tend\n' .. 'end' local f = io.open (arg[1], 'r') local maestro_src = f:read ('*all') f:close() lines = io.lines (arg[2]) inputs_evt = {} for line in io.lines (arg[2]) do line = line:gsub("^%s*(.-)%s*$", "%1") if line:sub (1, 5) == 'input' then table.insert (inputs_evt, {}) inputs_evt[#inputs_evt] = { line = line, args = {}, evt = '', emitter = '' } end end local TO_GEN = '' TO_GEN = '/*' .. '\n * This excerpt of code is automatically generated by Mars.' .. '\n * Do not edit it.' .. '\n */\n\n' for i=1, #inputs_evt do local input = inputs_evt[i].line input = input:sub (5 + 1):gsub("^%s*(.-)%s*$", "%1") local args = input:match ("%((.-)%)") local evt = input:match ("%).-$"):sub(2):gsub("^%s*(.-)%s*;$", "%1") local code_name = evt:lower():gsub('_.', string.upper):gsub('^.', string.upper) local code = string.gsub (CODE_TEMPLATE, '{#1}', code_name) local params = '' if args == 'none' then params = args else local k = 1 for arg in args:gmatch('([^,]+)') do arg = arg:gsub("^%s*(.-)%s*$", "%1") table.insert(inputs_evt[i].args, arg) params = params .. 'var ' .. arg .. ' arg' .. k .. ', ' k = k + 1 end params = params:sub (1, -3) end code = code:gsub ('{#2}', params) params = params:gsub ('(var .-).- ,-', '') if params == 'none' then params = '_' end code = code:gsub ('{#3}', params) code = code:gsub ('{#4}', evt) if params == '_' then params = '' end code = code:gsub ('{#5}', params) inputs_evt[i].evt = evt inputs_evt[i].emitter = 'Emit_' .. code_name .. '_Event'; TO_GEN = TO_GEN .. code .. '\n' end CODE_TEMPLATE = '\n' .. 'code/await Handle_Mapping (var _char&& mapping) -> none\n' .. 'do\n' .. '\tvar Exception.Lua? e;\n' .. '\tcatch e do\n' .. '\t{#1}\n' .. '\tend\n' .. '\tif e? then\n' .. '\t\t_fprintf (_stderr, "[Mapping error:] %%s\\n", e!.message);\n' .. '\tend\n' .. 'end' code = '' local cond = '_strcmp(mapping, "{#1}") == 0' for i = 1, #inputs_evt do input = inputs_evt[i] local statement if i == 1 then statement = '\tif' else statement = '\telse/if' end code = code .. statement .. ' ' .. cond:gsub('{#1}', input.evt) .. ' then\n' local body = '' local params = '' local attrs = '' local mapping_args = '' local ident = '\t\t\t' for j = 1, #input.args do local varname = 'arg' .. j local vardecl = 'var ' .. input.args[j] .. ' ' .. varname body = body .. ident .. vardecl .. ' = _;\n' params = params .. varname .. ', ' mapping_args = mapping_args .. '@' .. varname .. ', ' attrs = attrs .. ident .. varname .. ' = [[ CLIENT.mapping.args[' .. j .. '] or @' .. varname .. ' ]];\n' end params = params:sub (1, -3) mapping_args = mapping_args:sub (1, -3) body = body .. ident .. '[[ apply_mapping ("' .. input.evt ..'", ' .. mapping_args .. ') ]]\n' body = body .. attrs body = body .. '\t\t\t' .. 'await ' .. input.emitter .. '(' .. params .. ');\n' if (i == #inputs_evt) then code = code .. body .. '\t\tend' end end code = code TO_GEN = TO_GEN .. CODE_TEMPLATE:gsub('{#1}', code) .. '\n' maestro_src = maestro_src:gsub ('__COMPILED_EVTS__', TO_GEN) f = io.open (arg[1], 'w') f:write (maestro_src) f:close()
Fix events code generation
Fix events code generation * include/mars/util/mars-compile-evts.lua
Lua
mit
rodrimc/ceu-media-multidevice
d5e6f21608ce577c245f384705c8e01cdeb0fe19
plugins/mod_vcard.lua
plugins/mod_vcard.lua
require "util.datamanager" local datamanager = datamanager; local st = require "util.stanza" local send = require "core.sessionmanager".send_to_session local t_concat, t_insert = table.concat, table.insert; require "util.jid" local jid_split = jid.split; add_iq_handler("c2s", "vcard-temp", function (session, stanza) if stanza.tags[1].name == "vCard" then local to = stanza.attr.to; if stanza.attr.type == "get" then local vCard; if to then local node, host = jid_split(to); if hosts[host] and hosts[host].type == "local" then vCard = st.deserialize(datamanager.load(node, host, "vCard")); -- load vCard for user or server end else vCard = st.deserialize(datamanager.load(session.username, session.host, "vCard"));-- load user's own vCard end if vCard then local iq = st.reply(stanza); iq:add_child(vCard); send(session, iq); -- send vCard! else send(session, st.error_reply(stanza, "cancel", "item-not-found")); end elseif stanza.attr.type == "set" then if not to or to == session.username.."@"..session.host then if datamanager.store(session.username, session.host, "vCard", st.preserialize(stanza.tags[1])) then send(session, st.reply(stanza)); else -- TODO unable to write file, file may be locked, etc, what's the correct error? send(session, st.error_reply(stanza, "wait", "internal-server-error")); end else send(session, st.error_reply(stanza, "auth", "forbidden")); end end return true; end end); add_event_hook("stream-features", function (session, features) if session.type == "c2s" then t_insert(features, "<feature var='vcard-temp'/>"); end end);
require "util.datamanager" local datamanager = datamanager; local st = require "util.stanza" local send = require "core.sessionmanager".send_to_session local t_concat, t_insert = table.concat, table.insert; require "util.jid" local jid_split = jid.split; add_iq_handler("c2s", "vcard-temp", function (session, stanza) if stanza.tags[1].name == "vCard" then local to = stanza.attr.to; if stanza.attr.type == "get" then local vCard; if to then local node, host = jid_split(to); if hosts[host] and hosts[host].type == "local" then vCard = st.deserialize(datamanager.load(node, host, "vCard")); -- load vCard for user or server end else vCard = st.deserialize(datamanager.load(session.username, session.host, "vCard"));-- load user's own vCard end if vCard then send(session, st.reply(stanza):add_child(vCard)); -- send vCard! else send(session, st.error_reply(stanza, "cancel", "item-not-found")); end elseif stanza.attr.type == "set" then if not to or to == session.username.."@"..session.host then if datamanager.store(session.username, session.host, "vCard", st.preserialize(stanza.tags[1])) then send(session, st.reply(stanza)); else -- TODO unable to write file, file may be locked, etc, what's the correct error? send(session, st.error_reply(stanza, "wait", "internal-server-error")); end else send(session, st.error_reply(stanza, "auth", "forbidden")); end end return true; end end); add_event_hook("stream-features", function (session, features) if session.type == "c2s" then t_insert(features, "<feature var='vcard-temp'/>"); end end);
mod_vcard: Fixed to use new util.stanza.add_child
mod_vcard: Fixed to use new util.stanza.add_child
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
2ea572eeeaea1ed45736067c4f992dc8a5f48548
lua/timestamping.lua
lua/timestamping.lua
--- Hardware timestamping. local mod = {} local ffi = require "ffi" local dpdkc = require "dpdkc" local dpdk = require "dpdk" local device = require "device" local eth = require "proto.ethernet" local memory = require "memory" local timer = require "timer" local log = require "log" local filter = require "filter" local libmoon = require "libmoon" local timestamper = {} timestamper.__index = timestamper --- Create a new timestamper. --- A NIC can only be used by one thread at a time due to clock synchronization. --- Best current pratice is to use only one timestamping thread to avoid problems. function mod:newTimestamper(txQueue, rxQueue, mem, udp) mem = mem or memory.createMemPool(function(buf) -- defaults are good enough for us here if udp then buf:getUdpPtpPacket():fill{ ethSrc = txQueue, } else buf:getPtpPacket():fill{ ethSrc = txQueue, } end end) txQueue:enableTimestamps() rxQueue:enableTimestamps() if udp and rxQueue.dev.supportsFdir then rxQueue:filterUdpTimestamps() elseif not udp then rxQueue:filterL2Timestamps() end return setmetatable({ mem = mem, txBufs = mem:bufArray(1), rxBufs = mem:bufArray(128), txQueue = txQueue, rxQueue = rxQueue, txDev = txQueue.dev, rxDev = rxQueue.dev, seq = 1, udp = udp, useTimesync = rxQueue.dev.useTimsyncIds, }, timestamper) end --- See newTimestamper() function mod:newUdpTimestamper(txQueue, rxQueue, mem) return self:newTimestamper(txQueue, rxQueue, mem, true) end --- Try to measure the latency of a single packet. --- @param pktSize optional, the size of the generated packet, optional, defaults to the smallest possible size --- @param packetModifier optional, a function that is called with the generated packet, e.g. to modified addresses --- @param maxWait optional (cannot be the only argument) the time in ms to wait before the packet is assumed to be lost (default = 15) function timestamper:measureLatency(pktSize, packetModifier, maxWait) if type(pktSize) == "function" then -- optional first argument was skipped return self:measureLatency(nil, pktSize, packetModifier) end pktSize = pktSize or self.udp and 76 or 60 maxWait = (maxWait or 15) / 1000 self.txBufs:alloc(pktSize) local buf = self.txBufs[1] buf:enableTimestamps() local expectedSeq = self.seq self.seq = (self.seq + 1) % 2^16 if self.udp then buf:getUdpPtpPacket().ptp:setSequenceID(expectedSeq) else buf:getPtpPacket().ptp:setSequenceID(expectedSeq) end local skipReconfigure if packetModifier then skipReconfigure = packetModifier(buf) end if self.udp then -- change timestamped UDP port as each packet may be on a different port self.rxQueue:enableTimestamps(buf:getUdpPacket().udp:getDstPort()) self.txBufs:offloadUdpChecksums() if self.rxQueue.dev.reconfigureUdpTimestampFilter and not skipReconfigure then -- i40e driver fdir filters are broken -- it is not possible to match on flex bytes in udp packets without matching IPs and ports as well -- so we have to look at that packet and reconfigure the filters self.rxQueue.dev:reconfigureUdpTimestampFilter(self.rxQueue, buf:getUdpPacket()) end else end mod.syncClocks(self.txDev, self.rxDev) -- clear any "leftover" timestamps self.rxDev:clearTimestamps() self.txQueue:send(self.txBufs) local tx = self.txQueue:getTimestamp(500) if tx then -- sent was successful, try to get the packet back (assume that it is lost after a given delay) local timer = timer:new(maxWait) while timer:running() do local rx = self.rxQueue:tryRecv(self.rxBufs, 1000) local timestampedPkt = self.rxDev:hasRxTimestamp() if not timestampedPkt then -- NIC didn't save a timestamp yet, just throw away the packets self.rxBufs:freeAll() else -- received a timestamped packet (not necessarily in this batch) for i = 1, rx do local buf = self.rxBufs[i] local timesync = self.useTimesync and buf:getTimesync() or 0 local seq = (self.udp and buf:getUdpPtpPacket() or buf:getPtpPacket()).ptp:getSequenceID() if buf:hasTimestamp() and seq == expectedSeq and (seq == timestampedPkt or timestampedPkt == -1) then -- yay! local rxTs = self.rxQueue:getTimestamp(nil, timesync) if not rxTs then -- can happen if you hotplug cables return nil end self.rxBufs:freeAll() local lat = rxTs - tx if lat > 0 and lat < 2 * maxWait * 10^9 then -- negative latencies may happen if the link state changes -- (timers depend on a clock that scales with link speed on some NICs) -- really large latencies (we only wait for up to maxWait ms) -- also sometimes happen since changing to DPDK for reading the timing registers -- probably something wrong with the DPDK wraparound tracking -- (but that's really rare and the resulting latency > a few days, so we don't really care) return lat end elseif buf:hasTimestamp() and (seq == timestampedPkt or timestampedPkt == -1) then -- we got a timestamp but the wrong sequence number. meh. self.rxQueue:getTimestamp(nil, timesync) -- clears the register -- continue, we may still get our packet :) elseif seq == expectedSeq and (seq ~= timestampedPkt and timestampedPkt ~= -1) then -- we got our packet back but it wasn't timestamped -- we likely ran into the previous case earlier and cleared the ts register too late self.rxBufs:freeAll() return end end end end -- looks like our packet got lost :( return else -- happens when hotplugging cables log:warn("Failed to timestamp packet on transmission") timer:new(maxWait):wait() end end function mod.syncClocks(dev1, dev2) local regs1 = dev1.timeRegisters local regs2 = dev2.timeRegisters if regs1[1] ~= regs2[1] or regs1[2] ~= regs2[2] or regs1[3] ~= regs2[3] or regs1[4] ~= regs2[4] then log:fatal("NICs incompatible, cannot sync clocks") end dpdkc.libmoon_sync_clocks(dev1.id, dev2.id, unpack(regs1)) -- just to tell the driver that we are resetting the clock -- otherwise the cycle tracker becomes confused on long latencies dev1:resetTimeCounters() dev2:resetTimeCounters() end return mod
--- Hardware timestamping. local mod = {} local ffi = require "ffi" local dpdkc = require "dpdkc" local dpdk = require "dpdk" local device = require "device" local eth = require "proto.ethernet" local memory = require "memory" local timer = require "timer" local log = require "log" local filter = require "filter" local libmoon = require "libmoon" local timestamper = {} timestamper.__index = timestamper --- Create a new timestamper. --- A NIC can only be used by one thread at a time due to clock synchronization. --- Best current pratice is to use only one timestamping thread to avoid problems. function mod:newTimestamper(txQueue, rxQueue, mem, udp) mem = mem or memory.createMemPool(function(buf) -- defaults are good enough for us here if udp then buf:getUdpPtpPacket():fill{ ethSrc = txQueue, } else buf:getPtpPacket():fill{ ethSrc = txQueue, } end end) txQueue:enableTimestamps() rxQueue:enableTimestamps() if udp and rxQueue.dev.supportsFdir then rxQueue:filterUdpTimestamps() elseif not udp then rxQueue:filterL2Timestamps() end return setmetatable({ mem = mem, txBufs = mem:bufArray(1), rxBufs = mem:bufArray(128), txQueue = txQueue, rxQueue = rxQueue, txDev = txQueue.dev, rxDev = rxQueue.dev, seq = 1, udp = udp, useTimesync = rxQueue.dev.useTimsyncIds, }, timestamper) end --- See newTimestamper() function mod:newUdpTimestamper(txQueue, rxQueue, mem) return self:newTimestamper(txQueue, rxQueue, mem, true) end --- Try to measure the latency of a single packet. --- @param pktSize optional, the size of the generated packet, optional, defaults to the smallest possible size --- @param packetModifier optional, a function that is called with the generated packet, e.g. to modified addresses --- @param maxWait optional (cannot be the only argument) the time in ms to wait before the packet is assumed to be lost (default = 15) function timestamper:measureLatency(pktSize, packetModifier, maxWait) if type(pktSize) == "function" then -- optional first argument was skipped return self:measureLatency(nil, pktSize, packetModifier) end pktSize = pktSize or self.udp and 76 or 60 maxWait = (maxWait or 15) / 1000 self.txBufs:alloc(pktSize) local buf = self.txBufs[1] buf:enableTimestamps() local expectedSeq = self.seq self.seq = (self.seq + 1) % 2^16 if self.udp then buf:getUdpPtpPacket().ptp:setSequenceID(expectedSeq) else buf:getPtpPacket().ptp:setSequenceID(expectedSeq) end local skipReconfigure if packetModifier then skipReconfigure = packetModifier(buf) end if self.udp then -- change timestamped UDP port as each packet may be on a different port self.rxQueue:enableTimestamps(buf:getUdpPacket().udp:getDstPort()) buf:getUdpPtpPacket():setLength(pktSize) self.txBufs:offloadUdpChecksums() if self.rxQueue.dev.reconfigureUdpTimestampFilter and not skipReconfigure then -- i40e driver fdir filters are broken -- it is not possible to match on flex bytes in udp packets without matching IPs and ports as well -- so we have to look at that packet and reconfigure the filters self.rxQueue.dev:reconfigureUdpTimestampFilter(self.rxQueue, buf:getUdpPacket()) end end mod.syncClocks(self.txDev, self.rxDev) -- clear any "leftover" timestamps self.rxDev:clearTimestamps() self.txQueue:send(self.txBufs) local tx = self.txQueue:getTimestamp(500) if tx then -- sent was successful, try to get the packet back (assume that it is lost after a given delay) local timer = timer:new(maxWait) while timer:running() do local rx = self.rxQueue:tryRecv(self.rxBufs, 1000) local timestampedPkt = self.rxDev:hasRxTimestamp() if not timestampedPkt then -- NIC didn't save a timestamp yet, just throw away the packets self.rxBufs:freeAll() else -- received a timestamped packet (not necessarily in this batch) for i = 1, rx do local buf = self.rxBufs[i] local timesync = self.useTimesync and buf:getTimesync() or 0 local seq = (self.udp and buf:getUdpPtpPacket() or buf:getPtpPacket()).ptp:getSequenceID() if buf:hasTimestamp() and seq == expectedSeq and (seq == timestampedPkt or timestampedPkt == -1) then -- yay! local rxTs = self.rxQueue:getTimestamp(nil, timesync) if not rxTs then -- can happen if you hotplug cables return nil end self.rxBufs:freeAll() local lat = rxTs - tx if lat > 0 and lat < 2 * maxWait * 10^9 then -- negative latencies may happen if the link state changes -- (timers depend on a clock that scales with link speed on some NICs) -- really large latencies (we only wait for up to maxWait ms) -- also sometimes happen since changing to DPDK for reading the timing registers -- probably something wrong with the DPDK wraparound tracking -- (but that's really rare and the resulting latency > a few days, so we don't really care) return lat end elseif buf:hasTimestamp() and (seq == timestampedPkt or timestampedPkt == -1) then -- we got a timestamp but the wrong sequence number. meh. self.rxQueue:getTimestamp(nil, timesync) -- clears the register -- continue, we may still get our packet :) elseif seq == expectedSeq and (seq ~= timestampedPkt and timestampedPkt ~= -1) then -- we got our packet back but it wasn't timestamped -- we likely ran into the previous case earlier and cleared the ts register too late self.rxBufs:freeAll() return end end end end -- looks like our packet got lost :( return else -- happens when hotplugging cables log:warn("Failed to timestamp packet on transmission") timer:new(maxWait):wait() end end function mod.syncClocks(dev1, dev2) local regs1 = dev1.timeRegisters local regs2 = dev2.timeRegisters if regs1[1] ~= regs2[1] or regs1[2] ~= regs2[2] or regs1[3] ~= regs2[3] or regs1[4] ~= regs2[4] then log:fatal("NICs incompatible, cannot sync clocks") end dpdkc.libmoon_sync_clocks(dev1.id, dev2.id, unpack(regs1)) -- just to tell the driver that we are resetting the clock -- otherwise the cycle tracker becomes confused on long latencies dev1:resetTimeCounters() dev2:resetTimeCounters() end return mod
timestamper: fix UDP header length field
timestamper: fix UDP header length field was previously set too short, but apparently no one really cared about this
Lua
mit
emmericp/libmoon,libmoon/libmoon,libmoon/libmoon,emmericp/libmoon,emmericp/libmoon,scholzd/libmoon,scholzd/libmoon,libmoon/libmoon,scholzd/libmoon
4a339d1c9fd27cb87240fb11d0ed3366c09b15b3
generator/operators.lua
generator/operators.lua
module('operators', package.seeall) local operatorTrans = { ['<<'] = 'IN', ['>>'] = 'OUT', ['+='] = 'ADD', ['-='] = 'SUB', ['*='] = 'MUL', ['/='] = 'DIV', ['++'] = 'INC', ['--'] = 'DEC', ['+'] = '__add', ['-'] = '__sub', ['_'] = '__unm', ['*'] = '__mul', ['/'] = '__div', ['=='] = '__eq', } function fix_operators(index) for f in pairs(index) do if f.label == "Function" then if f.xarg.name == 'operator-' and #f.arguments == 1 then -- use '_' as a marker for unary minus f.xarg.name = 'operator_' table.remove(f, 1) table.remove(f.arguments, 1) elseif f.xarg.name:match("^operator") and f.xarg.friend then if f[1].xarg.type_base == f.xarg.member_of then -- overloaded friend operator - its first argument is 'this', -- needs to be removed table.remove(f, 1) table.remove(f.arguments, 1) else -- operator in form: number OP class - do not bind these f.ignore = true end end end end end function call_line(f) local op = operators.get_operator(f.xarg.name) if op == "*" and #f.arguments == 0 then ignore(f.xarg.fullname, "pointer dereference operator", f.xarg.member_of_class) return nil elseif op == '_' then -- unary minus return '- *self', false elseif op == '++' or op == '--' then -- the ++ and -- operators don't line () at the end, like: *self ++() if f.arguments[1] then f.arguments[1] = nil return op..' *self', false else return '*self '..op, false end else return '*self '..op..'(', true end end function get_operator(name) return name:match('^operator(.+)$') end function is_operator(name) return name:match('^operator.') and operatorTrans[get_operator(name)] end function rename_operator(name) local trans = operatorTrans[get_operator(name)] if is_operator(name) and trans then return trans end return name end
module('operators', package.seeall) local operatorTrans = { ['<<'] = 'IN', ['>>'] = 'OUT', ['+='] = 'ADD', ['-='] = 'SUB', ['*='] = 'MUL', ['/='] = 'DIV', ['++'] = 'INC', ['--'] = 'DEC', ['+'] = '__add', ['-'] = '__sub', ['_'] = '__unm', ['*'] = '__mul', ['/'] = '__div', ['=='] = '__eq', } local function is_helper_function(name) local s1 = name:sub(1,1) local s2 = name:sub(2,2) return s1 == 'q' and s2 == s2:upper() end function fix_operators(index) for f in pairs(index) do if f.label == "Function" then if f.xarg.name:match("^operator") and f.xarg.friend then if f[1].xarg.type_base == f.xarg.member_of then -- overloaded friend operator - its first argument is 'this', -- needs to be removed table.remove(f, 1) table.remove(f.arguments, 1) if f.xarg.name == 'operator-' and #f.arguments == 0 then -- use '_' as a marker for unary minus f.xarg.name = 'operator_' end else -- operator in form: number OP class - do not bind these f.ignore = true end elseif is_helper_function(f.xarg.name) then f.ignore = true end end end end function call_line(f) local op = operators.get_operator(f.xarg.name) if op == "*" and #f.arguments == 0 then ignore(f.xarg.fullname, "pointer dereference operator", f.xarg.member_of_class) return nil elseif op == '_' then -- unary minus return '- *self', false elseif op == '++' or op == '--' then -- the ++ and -- operators don't line () at the end, like: *self ++() if f.arguments[1] then f.arguments[1] = nil return op..' *self', false else return '*self '..op, false end else return '*self '..op..'(', true end end function get_operator(name) return name:match('^operator(.+)$') end function is_operator(name) return name:match('^operator.') and operatorTrans[get_operator(name)] end function rename_operator(name) local trans = operatorTrans[get_operator(name)] if is_operator(name) and trans then return trans end return name end
fix binding of overloaded operators
fix binding of overloaded operators
Lua
mit
mkottman/lqt,mkottman/lqt
4b34eb4967fdeae3e16a20720a90d88ff45113e5
mod_auth_dovecot/mod_auth_dovecot.lua
mod_auth_dovecot/mod_auth_dovecot.lua
-- Dovecot authentication backend for Prosody -- -- Copyright (C) 2010 Javier Torres -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- local socket_unix = require "socket.unix"; local datamanager = require "util.datamanager"; local log = require "util.logger".init("auth_dovecot"); local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local base64 = require "util.encodings".base64; local pposix = require "util.pposix"; local prosody = _G.prosody; local socket_path = module:get_option_string("dovecot_auth_socket", "/var/run/dovecot/auth-login"); function new_default_provider(host) local provider = { name = "dovecot", c = nil }; log("debug", "initializing dovecot authentication provider for host '%s'", host); -- Closes the socket function provider.close(self) if (provider.c ~= nil) then provider.c:close(); end provider.c = nil; end -- The following connects to a new socket and send the handshake function provider.connect(self) -- Destroy old socket provider:close(); provider.c = socket.unix(); -- Create a connection to dovecot socket local r, e = provider.c:connect(socket_path); if (not r) then log("warn", "error connecting to dovecot socket at '%s'. error was '%s'. check permissions", socket_path, e); provider:close(); return false; end -- Send our handshake local pid = pposix.getpid(); if not provider:send("VERSION\t1\t1\n") then return false end if (not provider:send("CPID\t" .. pid .. "\n")) then return false end -- Parse Dovecot's handshake local done = false; while (not done) do local l = provider:receive(); if (not l) then return false; end parts = string.gmatch(l, "[^\t]+"); first = parts(); if (first == "VERSION") then -- Version should be 1.1 local v1 = parts(); local v2 = parts(); if (not (v1 == "1" and v2 == "1")) then log("warn", "server version is not 1.1. it is %s.%s", v1, v2); provider:close(); return false; end elseif (first == "MECH") then -- Mechanisms should include PLAIN local ok = false; for p in parts do if p == "PLAIN" then ok = true; end end if (not ok) then log("warn", "server doesn't support PLAIN mechanism. It supports '%s'", l); provider:close(); return false; end elseif (first == "DONE") then done = true; end end return true; end -- Wrapper for send(). Handles errors function provider.send(self, data) local r, e = provider.c:send(data); if (not r) then log("warn", "error sending '%s' to dovecot. error was '%s'", data, e); provider:close(); return false; end return true; end -- Wrapper for receive(). Handles errors function provider.receive(self) local r, e = provider.c:receive(); if (not r) then log("warn", "error receiving data from dovecot. error was '%s'", socket, e); provider:close(); return false; end return r; end function provider.test_password(username, password) log("debug", "test password '%s' for user %s at host %s", password, username, module.host); local tries = 0; if (provider.c == nil or tries > 0) then if (not provider:connect()) then return nil, "Auth failed. Dovecot communications error"; end end -- Send auth data username = username .. "@" .. module.host; -- FIXME: this is actually a hack for my server local b64 = base64.encode(username .. "\0" .. username .. "\0" .. password); local id = "54321"; -- FIXME: probably can just be a fixed value if making one request per connection if (not provider:send("AUTH\t" .. id .. "\tPLAIN\tservice=XMPP\tresp=" .. b64 .. "\n")) then return nil, "Auth failed. Dovecot communications error"; end -- Get response local l = provider:receive(); if (not l) then return nil, "Auth failed. Dovecot communications error"; end local parts = string.gmatch(l, "[^\t]+"); -- Check response if (parts() == "OK") then return true; else return nil, "Auth failed. Invalid username or password."; end end function provider.get_password(username) return nil, "Cannot get_password in dovecot backend."; end function provider.set_password(username, password) return nil, "Cannot set_password in dovecot backend."; end function provider.user_exists(username) --TODO: Send an auth request. If it returns FAIL <id> user=<user> then user exists. return nil, "user_exists not yet implemented in dovecot backend."; end function provider.create_user(username, password) return nil, "Cannot create_user in dovecot backend."; end function provider.get_sasl_handler() local realm = module:get_option("sasl_realm") or module.host; local getpass_authentication_profile = { plain_test = function(username, password, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end return usermanager.test_password(prepped_username, realm, password), true; end }; return new_sasl(realm, getpass_authentication_profile); end return provider; end module:add_item("auth-provider", new_default_provider(module.host));
-- Dovecot authentication backend for Prosody -- -- Copyright (C) 2010 Javier Torres -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- local socket_unix = require "socket.unix"; local datamanager = require "util.datamanager"; local log = require "util.logger".init("auth_dovecot"); local new_sasl = require "util.sasl".new; local nodeprep = require "util.encodings".stringprep.nodeprep; local base64 = require "util.encodings".base64; local pposix = require "util.pposix"; local prosody = _G.prosody; local socket_path = module:get_option_string("dovecot_auth_socket", "/var/run/dovecot/auth-login"); function new_default_provider(host) local provider = { name = "dovecot", c = nil, request_id = 0 }; log("debug", "initializing dovecot authentication provider for host '%s'", host); -- Closes the socket function provider.close(self) if (provider.c ~= nil) then provider.c:close(); end provider.c = nil; end -- The following connects to a new socket and send the handshake function provider.connect(self) -- Destroy old socket provider:close(); provider.c = socket.unix(); -- Create a connection to dovecot socket local r, e = provider.c:connect(socket_path); if (not r) then log("warn", "error connecting to dovecot socket at '%s'. error was '%s'. check permissions", socket_path, e); provider:close(); return false; end -- Send our handshake local pid = pposix.getpid(); if not provider:send("VERSION\t1\t1\n") then return false end if (not provider:send("CPID\t" .. pid .. "\n")) then return false end -- Parse Dovecot's handshake local done = false; while (not done) do local l = provider:receive(); if (not l) then return false; end parts = string.gmatch(l, "[^\t]+"); first = parts(); if (first == "VERSION") then -- Version should be 1.1 local v1 = parts(); local v2 = parts(); if (not (v1 == "1" and v2 == "1")) then log("warn", "server version is not 1.1. it is %s.%s", v1, v2); provider:close(); return false; end elseif (first == "MECH") then -- Mechanisms should include PLAIN local ok = false; for p in parts do if p == "PLAIN" then ok = true; end end if (not ok) then log("warn", "server doesn't support PLAIN mechanism. It supports '%s'", l); provider:close(); return false; end elseif (first == "DONE") then done = true; end end return true; end -- Wrapper for send(). Handles errors function provider.send(self, data) local r, e = provider.c:send(data); if (not r) then log("warn", "error sending '%s' to dovecot. error was '%s'", data, e); provider:close(); return false; end return true; end -- Wrapper for receive(). Handles errors function provider.receive(self) local r, e = provider.c:receive(); if (not r) then log("warn", "error receiving data from dovecot. error was '%s'", socket, e); provider:close(); return false; end return r; end function provider.test_password(username, password) log("debug", "test password '%s' for user %s at host %s", password, username, module.host); local tries = 0; if (provider.c == nil or tries > 0) then if (not provider:connect()) then return nil, "Auth failed. Dovecot communications error"; end end -- Send auth data username = username .. "@" .. module.host; -- FIXME: this is actually a hack for my server local b64 = base64.encode(username .. "\0" .. username .. "\0" .. password); provider.request_id = provider.request_id + 1 if (not provider:send("AUTH\t" .. provider.request_id .. "\tPLAIN\tservice=XMPP\tresp=" .. b64 .. "\n")) then return nil, "Auth failed. Dovecot communications error"; end -- Get response local l = provider:receive(); if (not l) then return nil, "Auth failed. Dovecot communications error"; end local parts = string.gmatch(l, "[^\t]+"); -- Check response if (parts() == "OK") then return true; else return nil, "Auth failed. Invalid username or password."; end end function provider.get_password(username) return nil, "Cannot get_password in dovecot backend."; end function provider.set_password(username, password) return nil, "Cannot set_password in dovecot backend."; end function provider.user_exists(username) --TODO: Send an auth request. If it returns FAIL <id> user=<user> then user exists. return nil, "user_exists not yet implemented in dovecot backend."; end function provider.create_user(username, password) return nil, "Cannot create_user in dovecot backend."; end function provider.get_sasl_handler() local realm = module:get_option("sasl_realm") or module.host; local getpass_authentication_profile = { plain_test = function(username, password, realm) local prepped_username = nodeprep(username); if not prepped_username then log("debug", "NODEprep failed on username: %s", username); return "", nil; end return usermanager.test_password(prepped_username, realm, password), true; end }; return new_sasl(realm, getpass_authentication_profile); end return provider; end module:add_item("auth-provider", new_default_provider(module.host));
mod_auth_dovecot: Use sequential (instead of fixed) id for messages
mod_auth_dovecot: Use sequential (instead of fixed) id for messages
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
a707a1a2ce4c5246e14a3885d80918bf0adad04e
lua/brainfuck.lua
lua/brainfuck.lua
#!/usr/bin/env lua -- Copyright (c) 2016 Francois Perrad local f = arg[1] and assert(io.open(arg[1], 'r')) or io.stdin local src = string.gsub(f:read'*a', '[^><+%-%.,%[%]]', '') local len = string.len(src) f:close() local stack = {} local jump = {} local code = {} for pc = 1, len do local opcode = src:sub(pc, pc) code[pc] = opcode if opcode == '[' then stack[#stack+1] = pc elseif opcode == ']' then local target = stack[#stack] stack[#stack] = nil jump[target] = pc jump[pc] = target end end src = nil stack = nil local buffer = setmetatable({}, { __index = function () return 0 -- default value end }) local ptr = 1 local pc = 1 while pc <= len do local opcode = code[pc] if opcode == '>' then ptr = ptr + 1 elseif opcode == '<' then ptr = ptr - 1 elseif opcode == '+' then buffer[ptr] = buffer[ptr] + 1 elseif opcode == '-' then buffer[ptr] = buffer[ptr] - 1 elseif opcode == '.' then io.stdout:write(string.char(buffer[ptr])) io.stdout:flush() elseif opcode == ',' then buffer[ptr] = string.byte(io.stdin:read(1)) or os.exit(0) elseif opcode == '[' then if buffer[ptr] == 0 then pc = jump[pc] end elseif opcode == ']' then if buffer[ptr] ~= 0 then pc = jump[pc] end end pc = pc + 1 end
#!/usr/bin/env lua -- Copyright (c) 2016 Francois Perrad local f = arg[1] and assert(io.open(arg[1], 'r')) or io.stdin local src = string.gsub(f:read'*a', '[^><+%-%.,%[%]]', '') local len = string.len(src) f:close() local stack = {} local jump = {} local code = {} for pc = 1, len do local opcode = src:sub(pc, pc) code[pc] = opcode if opcode == '[' then stack[#stack+1] = pc elseif opcode == ']' then local target = stack[#stack] stack[#stack] = nil jump[target] = pc jump[pc] = target end end src = nil stack = nil local buffer = setmetatable({}, { __index = function () return 0 -- default value end }) local ptr = 1 local pc = 1 while pc <= len do local opcode = code[pc] if opcode == '>' then ptr = ptr + 1 elseif opcode == '<' then ptr = ptr - 1 elseif opcode == '+' then buffer[ptr] = buffer[ptr] + 1 elseif opcode == '-' then buffer[ptr] = buffer[ptr] - 1 elseif opcode == '.' then io.stdout:write(string.char(buffer[ptr])) elseif opcode == ',' then buffer[ptr] = string.byte(io.stdin:read(1) or '\0') elseif opcode == '[' then if buffer[ptr] == 0 then pc = jump[pc] end elseif opcode == ']' then if buffer[ptr] ~= 0 then pc = jump[pc] end end pc = pc + 1 end
fix IO in Lua interpreter
fix IO in Lua interpreter
Lua
mit
pablojorge/brainfuck,pablojorge/brainfuck,pablojorge/brainfuck,pablojorge/brainfuck,pablojorge/brainfuck,pablojorge/brainfuck,pablojorge/brainfuck
de3c81d16b02a2551d007d3d1d9cdf141ad3b393
plugins/feedback.lua
plugins/feedback.lua
function run(msg, matches) local text = lang_text(receiver, 'feedStart') if msg.from.first_name then text = text .. lang_text(receiver, 'feedName') .. msg.from.first_name end if msg.from.last_name then text = text .. lang_text(receiver, 'feedSurname') .. msg.from.last_name end if msg.from.username then text = text .. lang_text(receiver, 'feedUsername') .. msg.from.username end text = text .. '\n🆔: ' .. msg.from.id .. '\n\nFeedback:\n' .. matches[1] send_large_msg('chat#id120307338', text) return lang_text(receiver, 'feedSent') end return { description = "FEEDBACK", patterns = { "^[#!/][Ff][Ee][Ee][Dd][Bb][Aa][Cc][Kk] (.*)$", }, run = run, min_rank = 0 -- usage -- #feedback <text> }
function run(msg, matches) local text = lang_text('feedStart') if msg.from.first_name then text = text .. lang_text('feedName') .. msg.from.first_name end if msg.from.last_name then text = text .. lang_text('feedSurname') .. msg.from.last_name end if msg.from.username then text = text .. lang_text('feedUsername') .. msg.from.username end text = text .. '\n🆔: ' .. msg.from.id .. '\n\nFeedback:\n' .. matches[1] send_large_msg('chat#id120307338', text) return lang_text('feedSent') end return { description = "FEEDBACK", patterns = { "^[#!/][Ff][Ee][Ee][Dd][Bb][Aa][Cc][Kk] (.*)$", }, run = run, min_rank = 0 -- usage -- #feedback <text> }
fix feedback
fix feedback
Lua
agpl-3.0
xsolinsx/AISasha
058acba8d0e656f0e0c9c7cfa0932be419023fb9
script/c800000040.lua
script/c800000040.lua
--CX 風紀大宮司サイモン function c800000040.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,aux.XyzFilterFunction(c,7),3) c:EnableReviveLimit() --unaffectable local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_IMMUNE_EFFECT) e1:SetValue(c800000040.efilter) c:RegisterEffect(e1) --pos&atk local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_POSITION+CATEGORY_DISABLE) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetCondition(c800000040.damcon) e2:SetCost(c800000040.poscost) e2:SetTarget(c800000040.postg) e2:SetOperation(c800000040.posop) c:RegisterEffect(e2) end function c800000040.efilter(e,te) return te:IsActiveType(TYPE_EFFECT) end function c800000040.damcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,800000039) end function c800000040.poscost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST) end function c800000040.filter(c) return not c:IsDisabled() end function c800000040.postg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) end if chk==0 then return Duel.IsExistingTarget(c800000040.filter,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET) local g=Duel.SelectTarget(tp,c800000040.filter,tp,0,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_POSITION,g,1,0,0) Duel.SetOperationInfo(0,CATEGORY_DISABLE,g,1,0,0) end function c800000040.posop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and not tc:IsDisabled() then Duel.ChangePosition(tc,POS_FACEUP_DEFENCE,POS_FACEDOWN_DEFENCE,POS_FACEUP_ATTACK,POS_FACEUP_ATTACK) Duel.NegateRelatedChain(tc,RESET_TURN_SET) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_DISABLE) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END) tc:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_DISABLE_EFFECT) e2:SetValue(RESET_TURN_SET) e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END) tc:RegisterEffect(e2) end end
--CX 風紀大宮司サイモン function c800000040.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,aux.XyzFilterFunction(c,7),3) c:EnableReviveLimit() --unaffectable local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_IMMUNE_EFFECT) e1:SetValue(c800000040.efilter) c:RegisterEffect(e1) --pos&atk local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_POSITION+CATEGORY_DISABLE) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetCode(EVENT_FREE_CHAIN) e2:SetCondition(c800000040.damcon) e2:SetCost(c800000040.poscost) e2:SetTarget(c800000040.postg) e2:SetOperation(c800000040.posop) c:RegisterEffect(e2) end function c800000040.efilter(e,te) return te:IsActiveType(TYPE_EFFECT) end function c800000040.damcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,800000039) end function c800000040.poscost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST) end function c800000040.filter(c) return not c:IsDisabled() end function c800000040.postg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) end if chk==0 then return Duel.IsExistingTarget(c800000040.filter,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET) local g=Duel.SelectTarget(tp,c800000040.filter,tp,0,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_POSITION,g,1,0,0) Duel.SetOperationInfo(0,CATEGORY_DISABLE,g,1,0,0) end function c800000040.posop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() local c=e:GetHandler() if tc:IsRelateToEffect(e) and not tc:IsDisabled() then Duel.ChangePosition(tc,POS_FACEUP_DEFENCE,POS_FACEDOWN_DEFENCE,POS_FACEUP_ATTACK,POS_FACEUP_ATTACK) Duel.NegateRelatedChain(tc,RESET_TURN_SET) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_DISABLE) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END) tc:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_DISABLE_EFFECT) e2:SetValue(RESET_TURN_SET) e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END) tc:RegisterEffect(e2) end end
fix
fix fixed effect being Ignition instead of Quick. added missing Variable
Lua
mit
Tic-Tac-Toc/DevProLauncher,SuperAndroid17/DevProLauncher,sidschingis/DevProLauncher
800e8290a82e7623c758c5d95a4b5a41fa7c0d0d
examples/l3-load-latency.lua
examples/l3-load-latency.lua
local dpdk = require "dpdk" local memory = require "memory" local device = require "device" local ts = require "timestamping" local dpdkc = require "dpdkc" local filter = require "filter" local ffi = require "ffi" -- set addresses here local srcmac = "00:42:00:00:00:01" local dstmac = "00:42:00:00:00:02" local dstip = 0x0A000001 local srcip = 0x0A000002 function master(...) local txPort, rxPort, rate, flows, size = tonumberall(...) if not txPort or not rxPort then errorf("usage: txPort rxPort [rate [flows [size]]]") end flows = flows or 4 rate = rate or 2000 size = (size or 128) - 4 -- 4 bytes for CRC will be added by NIC local rxMempool = memory.createMemPool() if txPort == rxPort then txDev = device.config(txPort, rxMempool, 2, 2) rxDev = txDev txDev:wait() else txDev = device.config(txPort, rxMempool, 1, 2) rxDev = device.config(rxPort, rxMempool, 2, 1) device.waitForLinks() end txDev:getTxQueue(1):setRate(rate) dpdk.launchLua("timerSlave", txPort, rxPort, 0, 1, size, flows) dpdk.launchLua("loadSlave", txPort, 1, size, flows) dpdk.launchLua("counterSlave", rxPort, size) dpdk.waitForSlaves() end function loadSlave(port, queue, size, numFlows) local queue = device.get(port):getTxQueue(queue) local mempool = memory.createMemPool(function(buf) ts.fillPacket(buf, 1234, size) local data = ffi.cast("uint8_t*", buf.pkt.data) data[43] = 0x00 -- PTP version, set to 0 to disable timestamping for load packets end) local lastPrint = dpdk.getTime() local totalSent = 0 local lastTotal = 0 local lastSent = 0 local bufs = mempool:bufArray(128) local baseIP = srcip local counter = 0 while dpdk.running() do bufs:alloc(size) for i, buf in ipairs(bufs) do local pkt = buf:getUdpPacket() pkt.eth.src:setString(srcmac) pkt.eth.dst:setString(dstmac) pkt.ip.src:set(baseIP + counter) pkt.ip.dst:set(dstip) if numFlows <= 32 then -- this is significantly faster for small numbers -- TODO: this optimization shouldn't be necessary... counter = (counter + 1) % numFlows else counter = counter == numFlows and 0 or counter + 1 end end -- UDP checksums are optional, so using just IPv4 checksums would be sufficient here bufs:offloadUdpChecksums() totalSent = totalSent + queue:send(bufs) local time = dpdk.getTime() if time - lastPrint > 1 then local mpps = (totalSent - lastTotal) / (time - lastPrint) / 10^6 printf("Sent %d packets, current rate %.2f Mpps, %.2f MBit/s, %.2f MBit/s wire rate", totalSent, mpps, mpps * (size + 4) * 8, mpps * (size + 24) * 8) lastTotal = totalSent lastPrint = time end end printf("Sent %d packets", totalSent) end function counterSlave(port) local dev = device.get(port) local total = 0 while dpdk.running() do local time = dpdk.getTime() dpdk.sleepMillis(1000) local elapsed = dpdk.getTime() - time local pkts = dev:getRxStats(port) total = total + pkts printf("Received %d packets, current rate %.2f Mpps", total, pkts / elapsed / 10^6) end printf("Received %d packets", total) end function timerSlave(txPort, rxPort, txQueue, rxQueue, size, numFlows) local txDev = device.get(txPort) local rxDev = device.get(rxPort) local txQueue = txDev:getTxQueue(txQueue) local rxQueue = rxDev:getRxQueue(rxQueue) local mem = memory.createMemPool() local bufs = mem:bufArray(1) local rxBufs = mem:bufArray(128) txQueue:enableTimestamps() rxQueue:enableTimestamps(1234) rxDev:filterTimestamps(rxQueue) local hist = {} -- wait one second, otherwise we might start timestamping before the load is applied dpdk.sleepMillis(1000) local counter = 0 local baseIP = dstip while dpdk.running() do bufs:alloc(size + 4) local pkt = bufs[1]:getUdpPacket() ts.fillPacket(bufs[1], 1234, size) pkt.eth.src:setString(srcmac) pkt.eth.dst:setString(dstmac) pkt.ip.src:set(baseIP + counter) pkt.ip.dst:set(dstip) counter = (counter + 1) % numFlows bufs:offloadUdpChecksums() -- sync clocks and send ts.syncClocks(txDev, rxDev) txQueue:send(bufs) -- increment the wait time when using large packets or slower links local tx = txQueue:getTimestamp(100) if tx then dpdk.sleepMicros(500) -- minimum latency to limit the packet rate -- sent was successful, try to get the packet back (max. 10 ms wait time before we assume the packet is lost) local rx = rxQueue:tryRecv(rxBufs, 10000) if rx > 0 then local numPkts = 0 for i = 1, rx do if bit.bor(rxBufs[i].ol_flags, dpdk.PKT_RX_IEEE1588_TMST) ~= 0 then numPkts = numPkts + 1 end end local delay = (rxQueue:getTimestamp() - tx) * 6.4 if numPkts == 1 then if delay > 0 and delay < 100000000 then hist[delay] = (hist[delay] or 0) + 1 end end -- else: got more than one packet, so we got a problem -- TODO: use sequence numbers in the packets to avoid bugs here rxBufs:freeAll() end end end local sortedHist = {} for k, v in pairs(hist) do table.insert(sortedHist, { k = k, v = v }) end local sum = 0 local samples = 0 table.sort(sortedHist, function(e1, e2) return e1.k < e2.k end) print("Histogram:") for _, v in ipairs(sortedHist) do sum = sum + v.k * v.v samples = samples + v.v print(v.k, v.v) end print() print("Average: " .. (sum / samples) .. " ns, " .. samples .. " samples") print("----------------------------------------------") end
local dpdk = require "dpdk" local memory = require "memory" local device = require "device" local ts = require "timestamping" local dpdkc = require "dpdkc" local filter = require "filter" local ffi = require "ffi" -- set addresses here local srcmac = "00:42:00:00:00:01" local dstmac = "00:42:00:00:00:02" local dstip = 0x0A000001 local srcip = 0x0A000002 function master(...) local txPort, rxPort, rate, flows, size = tonumberall(...) if not txPort or not rxPort then errorf("usage: txPort rxPort [rate [flows [size]]]") end flows = flows or 4 rate = rate or 2000 size = (size or 128) - 4 -- 4 bytes for CRC will be added by NIC local rxMempool = memory.createMemPool() if txPort == rxPort then txDev = device.config(txPort, rxMempool, 2, 2) rxDev = txDev txDev:wait() else txDev = device.config(txPort, rxMempool, 1, 2) rxDev = device.config(rxPort, rxMempool, 2, 1) device.waitForLinks() end txDev:getTxQueue(1):setRate(rate) dpdk.launchLua("timerSlave", txPort, rxPort, 0, 1, size, flows) dpdk.launchLua("loadSlave", txPort, 1, size, flows) dpdk.launchLua("counterSlave", rxPort, size) dpdk.waitForSlaves() end function loadSlave(port, queue, size, numFlows) local queue = device.get(port):getTxQueue(queue) local mempool = memory.createMemPool(function(buf) -- TODO: port this to new PTP/timestamping functions, ffi.cast in a userscript is not the point ts.fillPacket(buf, 1234, size) local data = ffi.cast("uint8_t*", buf.pkt.data) data[43] = 0x00 -- PTP version, set to 0 to disable timestamping for load packets local pkt = buf:getUdpPacket() pkt.eth.src:setString(srcmac) pkt.eth.dst:setString(dstmac) pkt.ip.dst:set(dstip) end) local lastPrint = dpdk.getTime() local totalSent = 0 local lastTotal = 0 local lastSent = 0 local bufs = mempool:bufArray(128) local baseIP = srcip local counter = 0 while dpdk.running() do bufs:alloc(size) for i, buf in ipairs(bufs) do local pkt = buf:getUdpPacket() pkt.ip.src:set(baseIP + counter) if numFlows <= 32 then -- this is significantly faster for small numbers -- TODO: this optimization shouldn't be necessary... counter = (counter + 1) % numFlows else counter = counter == numFlows and 0 or counter + 1 end end -- UDP checksums are optional, so using just IPv4 checksums would be sufficient here bufs:offloadUdpChecksums() totalSent = totalSent + queue:send(bufs) local time = dpdk.getTime() if time - lastPrint > 1 then local mpps = (totalSent - lastTotal) / (time - lastPrint) / 10^6 printf("Sent %d packets, current rate %.2f Mpps, %.2f MBit/s, %.2f MBit/s wire rate", totalSent, mpps, mpps * (size + 4) * 8, mpps * (size + 24) * 8) lastTotal = totalSent lastPrint = time end end printf("Sent %d packets", totalSent) end function counterSlave(port) local dev = device.get(port) local total = 0 while dpdk.running() do local time = dpdk.getTime() dpdk.sleepMillis(1000) local elapsed = dpdk.getTime() - time local pkts = dev:getRxStats(port) total = total + pkts printf("Received %d packets, current rate %.2f Mpps", total, pkts / elapsed / 10^6) end printf("Received %d packets", total) end function timerSlave(txPort, rxPort, txQueue, rxQueue, size, numFlows) local txDev = device.get(txPort) local rxDev = device.get(rxPort) local txQueue = txDev:getTxQueue(txQueue) local rxQueue = rxDev:getRxQueue(rxQueue) local mem = memory.createMemPool() local bufs = mem:bufArray(1) local rxBufs = mem:bufArray(128) txQueue:enableTimestamps() rxQueue:enableTimestamps(1234) rxDev:filterTimestamps(rxQueue) local hist = {} -- wait one second, otherwise we might start timestamping before the load is applied dpdk.sleepMillis(1000) local counter = 0 local baseIP = dstip while dpdk.running() do bufs:alloc(size + 4) local pkt = bufs[1]:getUdpPacket() ts.fillPacket(bufs[1], 1234, size) pkt.eth.src:setString(srcmac) pkt.eth.dst:setString(dstmac) pkt.ip.src:set(baseIP + counter) pkt.ip.dst:set(dstip) counter = (counter + 1) % numFlows bufs:offloadUdpChecksums() -- sync clocks and send ts.syncClocks(txDev, rxDev) txQueue:send(bufs) -- increment the wait time when using large packets or slower links local tx = txQueue:getTimestamp(100) if tx then dpdk.sleepMicros(500) -- minimum latency to limit the packet rate -- sent was successful, try to get the packet back (max. 10 ms wait time before we assume the packet is lost) local rx = rxQueue:tryRecv(rxBufs, 10000) if rx > 0 then local numPkts = 0 for i = 1, rx do if bit.bor(rxBufs[i].ol_flags, dpdk.PKT_RX_IEEE1588_TMST) ~= 0 then numPkts = numPkts + 1 end end local delay = (rxQueue:getTimestamp() - tx) * 6.4 if numPkts == 1 then if delay > 0 and delay < 100000000 then hist[delay] = (hist[delay] or 0) + 1 end end -- else: got more than one packet, so we got a problem -- TODO: use sequence numbers in the packets to avoid bugs here rxBufs:freeAll() end end end local sortedHist = {} for k, v in pairs(hist) do table.insert(sortedHist, { k = k, v = v }) end local sum = 0 local samples = 0 table.sort(sortedHist, function(e1, e2) return e1.k < e2.k end) print("Histogram:") for _, v in ipairs(sortedHist) do sum = sum + v.k * v.v samples = samples + v.v print(v.k, v.v) end print() print("Average: " .. (sum / samples) .. " ns, " .. samples .. " samples") print("----------------------------------------------") end
fix performance of l3-load-latency
fix performance of l3-load-latency
Lua
mit
slyon/MoonGen,kidaa/MoonGen,schoenb/MoonGen,schoenb/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen,slyon/MoonGen,scholzd/MoonGen,bmichalo/MoonGen,kidaa/MoonGen,gallenmu/MoonGen,atheurer/MoonGen,wenhuizhang/MoonGen,pavel-odintsov/MoonGen,pavel-odintsov/MoonGen,werpat/MoonGen,wenhuizhang/MoonGen,emmericp/MoonGen,bmichalo/MoonGen,scholzd/MoonGen,atheurer/MoonGen,bmichalo/MoonGen,gallenmu/MoonGen,kidaa/MoonGen,NetronomeMoongen/MoonGen,dschoeffm/MoonGen,NetronomeMoongen/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen,slyon/MoonGen,wenhuizhang/MoonGen,gallenmu/MoonGen,NetronomeMoongen/MoonGen,gallenmu/MoonGen,pavel-odintsov/MoonGen,emmericp/MoonGen,dschoeffm/MoonGen,slyon/MoonGen,bmichalo/MoonGen,gallenmu/MoonGen,werpat/MoonGen,werpat/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen,schoenb/MoonGen,dschoeffm/MoonGen,scholzd/MoonGen,emmericp/MoonGen
35c030cae36ef3cc0b0ab1d4ac547ea9b4810aef
scripts/downloadimagenet.lua
scripts/downloadimagenet.lua
local dl = require 'dataload' cmd = torch.CmdLine() cmd:text() cmd:text('Script to download and extract ImageNet dataset (ILSVRC2014 Classification)') cmd:text('You will require 360GB of space to complete the download and extraction process.') cmd:text('You can download each tarball in a different partition if you dont have that much space in one partition.') cmd:text('Example:') cmd:text('$> th downloadimagenet.lua ') cmd:text('Options:') cmd:option('--savePath', paths.concat(dl.DATA_PATH, 'ImageNet'), 'where to download and extract the files') cmd:option('--metaURL', 'https://stife076.files.wordpress.com/2015/02/metadata.zip', 'URL for file containing serialized JSON mapping word net ids to class index, name and description') cmd:option('--trainURL', 'http://www.image-net.org/challenges/LSVRC/2012/nonpub/ILSVRC2012_img_train.tar', 'URL of train images') cmd:option('--validURL', 'http://www.image-net.org/challenges/LSVRC/2012/nonpub/ILSVRC2012_img_val.tar', 'URL of validation images') cmd:option('--testURL', 'http://www.image-net.org/challenges/LSVRC/2012/nonpub/ILSVRC2012_img_test.tar', 'URL of test images') cmd:option('--devkitURL', 'http://image-net.org/image/ilsvrc2014/ILSVRC2014_devkit.tgz', 'URL of devkit') cmd:option('--what', 'all', 'what to download : all, train, valid, test, devkit, meta') cmd:option('--squash', false, 'squash existing downloaded files.') cmd:text() opt = cmd:parse(arg or {}) if opt.what == 'all' then opt.urls = {opt.trainURL, opt.validURL, opt.testURL, opt.devkitURL, opt.metaURL} else opt.urls = {opt[opt.what..'URL']} end paths.mkdir(opt.savePath) assert(paths.dirp(opt.savePath), 'error creating --savePath') for i, url in ipairs(opt.urls) do local tarName = paths.basename(url) local tarPath = paths.concat(opt.savePath, tarName) -- download file if paths.filep(tarPath) and not opt.squash then print(string.format("skipping download as dir %s already exists. Use --squash to squash", tarPath)) else if paths.filep(tarPath) then os.execute("rm "..tarPath) end dl.downloadfile(opt.savePath, url) end -- extract file local extractPath = paths.concat(opt.savePath, tarName:match("([^.]*)%.")) if paths.dirp(extractPath) and not opt.squash then print(string.format("skipping extraction as dir %s already exists. Use --squash to squash", extractPath)) else if paths.dirp(tarPath) then paths.rmdir(tarPath) end print(string.format("extracting downloaded file : %s", tarPath)) dl.decompressfile(opt.savePath, tarPath, nil, true, (not tarPath:find('devkit')) and extractPath or nil) assert(paths.dirp(extractPath), string.format("expecting tar %s to be extracted at %s", tarName, extractPath)) -- for the training directory, which contains a tar for each class for subTar in lfs.dir(extractPath) do local subDir = subTar:match("([^.]*)%.tar") if subDir then local subExtractPath = paths.concat(extractPath, subDir) local subTarPath = paths.concat(extractPath, subTar) if paths.dirp(subExtractPath) and not opt.squash then print(string.format("skipping extraction as dir %s already exists. Use --squash to squash", subExtractPath)) else dl.untar(subTarPath, subExtractPath) end end end end end
local dl = require 'dataload' cmd = torch.CmdLine() cmd:text() cmd:text('Script to download and extract ImageNet dataset (ILSVRC2014 Classification)') cmd:text('You will require 360GB of space to complete the download and extraction process.') cmd:text('You can download each tarball in a different partition if you dont have that much space in one partition.') cmd:text('Example:') cmd:text('$> th downloadimagenet.lua ') cmd:text('Options:') cmd:option('--savePath', paths.concat(dl.DATA_PATH, 'ImageNet'), 'where to download and extract the files') cmd:option('--metaURL', 'https://stife076.files.wordpress.com/2015/02/metadata.zip', 'URL for file containing serialized JSON mapping word net ids to class index, name and description') cmd:option('--trainURL', 'http://www.image-net.org/challenges/LSVRC/2012/nnoupb/ILSVRC2012_img_train.tar', 'URL of train images') -- train task 3: http://www.image-net.org/challenges/LSVRC/2012/nnoupb/ILSVRC2012_img_train_t3.tar cmd:option('--validURL', 'http://www.image-net.org/challenges/LSVRC/2012/nnoupb/ILSVRC2012_img_val.tar', 'URL of validation images') cmd:option('--testURL', 'http://www.image-net.org/challenges/LSVRC/2012/nnoupb/ILSVRC2012_img_test.tar', 'URL of test images') cmd:option('--devkitURL', 'http://www.image-net.org/challenges/LSVRC/2012/nnoupb/ILSVRC2012_devkit_t12.tar.gz', 'URL of devkit') -- dev kit task 3: http://www.image-net.org/challenges/LSVRC/2012/nnoupb/ILSVRC2012_devkit_t3.tar.gz cmd:option('--what', 'all', 'what to download : all, train, valid, test, devkit, meta') cmd:option('--squash', false, 'squash existing downloaded files.') cmd:text() opt = cmd:parse(arg or {}) if opt.what == 'all' then opt.urls = {opt.trainURL, opt.validURL, opt.testURL, opt.devkitURL, opt.metaURL} else opt.urls = {opt[opt.what..'URL']} end paths.mkdir(opt.savePath) assert(paths.dirp(opt.savePath), 'error creating --savePath') for i, url in ipairs(opt.urls) do local tarName = paths.basename(url) local tarPath = paths.concat(opt.savePath, tarName) -- download file if paths.filep(tarPath) and not opt.squash then print(string.format("skipping download as dir %s already exists. Use --squash to squash", tarPath)) else if paths.filep(tarPath) then os.execute("rm "..tarPath) end dl.downloadfile(opt.savePath, url) end -- extract file local extractPath = paths.concat(opt.savePath, tarName:match("([^.]*)%.")) if paths.dirp(extractPath) and not opt.squash then print(string.format("skipping extraction as dir %s already exists. Use --squash to squash", extractPath)) else if paths.dirp(tarPath) then paths.rmdir(tarPath) end print(string.format("extracting downloaded file : %s", tarPath)) dl.decompressfile(opt.savePath, tarPath, nil, true, (not tarPath:find('devkit')) and extractPath or nil) assert(paths.dirp(extractPath), string.format("expecting tar %s to be extracted at %s", tarName, extractPath)) -- for the training directory, which contains a tar for each class for subTar in lfs.dir(extractPath) do local subDir = subTar:match("([^.]*)%.tar") if subDir then local subExtractPath = paths.concat(extractPath, subDir) local subTarPath = paths.concat(extractPath, subTar) if paths.dirp(subExtractPath) and not opt.squash then print(string.format("skipping extraction as dir %s already exists. Use --squash to squash", subExtractPath)) else dl.untar(subTarPath, subExtractPath) end end end end end
fix imagenet links
fix imagenet links
Lua
bsd-3-clause
Element-Research/dataload
97352cf987c139094c5d06b34eff67a946c07d18
src/lib/protocol/ipv4.lua
src/lib/protocol/ipv4.lua
module(..., package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") local header = require("lib.protocol.header") local ipsum = require("lib.checksum").ipsum -- TODO: generalize local AF_INET = 2 local INET_ADDRSTRLEN = 16 local ipv4hdr_t = ffi.typeof[[ struct { uint16_t ihl_v_tos; // ihl:4, version:4, tos(dscp:6 + ecn:2) uint16_t total_length; uint16_t id; uint16_t frag_off; // flags:3, fragmen_offset:13 uint8_t ttl; uint8_t protocol; uint16_t checksum; uint8_t src_ip[4]; uint8_t dst_ip[4]; } __attribute__((packed)) ]] local ipv4hdr_pseudo_t = ffi.typeof[[ struct { uint8_t src_ip[4]; uint8_t dst_ip[4]; uint8_t ulp_zero; uint8_t ulp_protocol; uint16_t ulp_length; } __attribute__((packed)) ]] local ipv4_addr_t = ffi.typeof("uint8_t[4]") local ipv4_addr_t_size = ffi.sizeof(ipv4_addr_t) local ipv4 = subClass(header) -- Class variables ipv4._name = "ipv4" ipv4._header_type = ipv4hdr_t ipv4._header_ptr_type = ffi.typeof("$*", ipv4hdr_t) ipv4._ulp = { class_map = { [6] = "lib.protocol.tcp", [17] = "lib.protocol.udp", [47] = "lib.protocol.gre", [58] = "lib.protocol.icmp.header", }, method = 'protocol' } -- Class methods function ipv4:new (config) local o = ipv4:superClass().new(self) o:header().ihl_v_tos = C.htonl(0x4000) -- v4 o:ihl(o:sizeof() / 4) o:dscp(config.dscp or 0) o:ecn(config.ecn or 0) o:total_length(o:sizeof()) -- default to header only o:id(config.id or 0) o:flags(config.flags or 0) o:frag_off(config.frag_off or 0) o:ttl(config.ttl or 0) o:protocol(config.protocol or 0xff) o:src(config.src) o:dst(config.dst) o:checksum() return o end function ipv4:pton (p) local in_addr = ffi.new("uint8_t[4]") local result = C.inet_pton(AF_INET, p, in_addr) if result ~= 1 then return false, "malformed IPv4 address: " .. address end return in_addr end function ipv4:ntop (n) local p = ffi.new("char[?]", INET_ADDRSTRLEN) local c_str = C.inet_ntop(AF_INET, n, p, INET_ADDRSTRLEN) return ffi.string(c_str) end -- Instance methods function ipv4:version (v) return lib.bitfield(16, self:header(), 'ihl_v_tos', 0, 4, v) end function ipv4:ihl (ihl) return lib.bitfield(16, self:header(), 'ihl_v_tos', 4, 4, ihl) end function ipv4:dscp (dscp) return lib.bitfield(16, self:header(), 'ihl_v_tos', 8, 6, dscp) end function ipv4:ecn (ecn) return lib.bitfield(16, self:header(), 'ihl_v_tos', 14, 2, ecn) end function ipv4:total_length (length) if length ~= nil then self:header().total_length = C.htons(length) else return(C.ntohs(self:header().total_length)) end end function ipv4:id (id) if id ~= nil then self:header().id = C.htons(id) else return(C.ntohs(self:header().id)) end end function ipv4:flags (flags) return lib.bitfield(16, self:header(), 'frag_off', 0, 3, flags) end function ipv4:frag_off (frag_off) return lib.bitfield(16, self:header(), 'frag_off', 3, 13, frag_off) end function ipv4:ttl (ttl) if ttl ~= nil then self:header().ttl = ttl else return self:header().ttl end end function ipv4:protocol (protocol) if protocol ~= nil then self:header().protocol = protocol else return self:header().protocol end end function ipv4:checksum () self:header().checksum = C.htons(ipsum(ffi.cast("uint8_t *", self:header()), self:sizeof(), 0)) return C.ntohs(self:header().checksum) end function ipv4:src (ip) if ip ~= nil then ffi.copy(self:header().src_ip, ip, ipv4_addr_t_size) else return self:header().src_ip end end function ipv4:src_eq (ip) return C.memcmp(ip, self:header().src_ip, ipv4_addr_t_size) == 0 end function ipv4:dst (ip) if ip ~= nil then ffi.copy(self:header().dst_ip, ip, ipv4_addr_t_size) else return self:header().dst_ip end end function ipv4:dst_eq (ip) return C.memcmp(ip, self:header().dst_ip, ipv4_addr_t_size) == 0 end -- override the default equality method function ipv4:eq (other) --compare significant fields return (self:ihl() == other:ihl()) and (self:id() == other:id()) and (self:protocol() == other:protocol()) and self:src_eq(other:src()) and self:dst_eq(other:dst()) end -- Return a pseudo header for checksum calculation in a upper-layer -- protocol (e.g. icmp). Note that the payload length and next-header -- values in the pseudo-header refer to the effective upper-layer -- protocol. They differ from the respective values of the ipv6 -- header if extension headers are present. function ipv4:pseudo_header (ulplen, proto) local ph = ipv4hdr_pseudo_t() local h = self:header() ffi.copy(ph, h.src_ip, 2*ipv4_addr_t_size) -- Copy source and destination ph.ulp_length = C.htons(ulplen) ph.ulp_protocol = proto return(ph) end function selftest() local ipv4_address = "192.168.1.1" assert(ipv4_address == ipv4:ntop(ipv4:pton(ipv4_address)), 'ipv4 text to binary conversion failed.') end ipv4.selftest = selftest return ipv4
module(..., package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") local header = require("lib.protocol.header") local ipsum = require("lib.checksum").ipsum -- TODO: generalize local AF_INET = 2 local INET_ADDRSTRLEN = 16 local ipv4hdr_t = ffi.typeof[[ struct { uint16_t ihl_v_tos; // ihl:4, version:4, tos(dscp:6 + ecn:2) uint16_t total_length; uint16_t id; uint16_t frag_off; // flags:3, fragmen_offset:13 uint8_t ttl; uint8_t protocol; uint16_t checksum; uint8_t src_ip[4]; uint8_t dst_ip[4]; } __attribute__((packed)) ]] local ipv4hdr_pseudo_t = ffi.typeof[[ struct { uint8_t src_ip[4]; uint8_t dst_ip[4]; uint8_t ulp_zero; uint8_t ulp_protocol; uint16_t ulp_length; } __attribute__((packed)) ]] local ipv4_addr_t = ffi.typeof("uint8_t[4]") local ipv4_addr_t_size = ffi.sizeof(ipv4_addr_t) local ipv4 = subClass(header) -- Class variables ipv4._name = "ipv4" ipv4._header_type = ipv4hdr_t ipv4._header_ptr_type = ffi.typeof("$*", ipv4hdr_t) ipv4._ulp = { class_map = { [6] = "lib.protocol.tcp", [17] = "lib.protocol.udp", [47] = "lib.protocol.gre", [58] = "lib.protocol.icmp.header", }, method = 'protocol' } -- Class methods function ipv4:new (config) local o = ipv4:superClass().new(self) o:header().ihl_v_tos = C.htons(0x4000) -- v4 o:ihl(o:sizeof() / 4) o:dscp(config.dscp or 0) o:ecn(config.ecn or 0) o:total_length(o:sizeof()) -- default to header only o:id(config.id or 0) o:flags(config.flags or 0) o:frag_off(config.frag_off or 0) o:ttl(config.ttl or 0) o:protocol(config.protocol or 0xff) o:src(config.src) o:dst(config.dst) o:checksum() return o end function ipv4:pton (p) local in_addr = ffi.new("uint8_t[4]") local result = C.inet_pton(AF_INET, p, in_addr) if result ~= 1 then return false, "malformed IPv4 address: " .. address end return in_addr end function ipv4:ntop (n) local p = ffi.new("char[?]", INET_ADDRSTRLEN) local c_str = C.inet_ntop(AF_INET, n, p, INET_ADDRSTRLEN) return ffi.string(c_str) end -- Instance methods function ipv4:version (v) return lib.bitfield(16, self:header(), 'ihl_v_tos', 0, 4, v) end function ipv4:ihl (ihl) return lib.bitfield(16, self:header(), 'ihl_v_tos', 4, 4, ihl) end function ipv4:dscp (dscp) return lib.bitfield(16, self:header(), 'ihl_v_tos', 8, 6, dscp) end function ipv4:ecn (ecn) return lib.bitfield(16, self:header(), 'ihl_v_tos', 14, 2, ecn) end function ipv4:total_length (length) if length ~= nil then self:header().total_length = C.htons(length) else return(C.ntohs(self:header().total_length)) end end function ipv4:id (id) if id ~= nil then self:header().id = C.htons(id) else return(C.ntohs(self:header().id)) end end function ipv4:flags (flags) return lib.bitfield(16, self:header(), 'frag_off', 0, 3, flags) end function ipv4:frag_off (frag_off) return lib.bitfield(16, self:header(), 'frag_off', 3, 13, frag_off) end function ipv4:ttl (ttl) if ttl ~= nil then self:header().ttl = ttl else return self:header().ttl end end function ipv4:protocol (protocol) if protocol ~= nil then self:header().protocol = protocol else return self:header().protocol end end function ipv4:checksum () self:header().checksum = C.htons(ipsum(ffi.cast("uint8_t *", self:header()), self:sizeof(), 0)) return C.ntohs(self:header().checksum) end function ipv4:src (ip) if ip ~= nil then ffi.copy(self:header().src_ip, ip, ipv4_addr_t_size) else return self:header().src_ip end end function ipv4:src_eq (ip) return C.memcmp(ip, self:header().src_ip, ipv4_addr_t_size) == 0 end function ipv4:dst (ip) if ip ~= nil then ffi.copy(self:header().dst_ip, ip, ipv4_addr_t_size) else return self:header().dst_ip end end function ipv4:dst_eq (ip) return C.memcmp(ip, self:header().dst_ip, ipv4_addr_t_size) == 0 end -- override the default equality method function ipv4:eq (other) --compare significant fields return (self:ihl() == other:ihl()) and (self:id() == other:id()) and (self:protocol() == other:protocol()) and self:src_eq(other:src()) and self:dst_eq(other:dst()) end -- Return a pseudo header for checksum calculation in a upper-layer -- protocol (e.g. icmp). Note that the payload length and next-header -- values in the pseudo-header refer to the effective upper-layer -- protocol. They differ from the respective values of the ipv6 -- header if extension headers are present. function ipv4:pseudo_header (ulplen, proto) local ph = ipv4hdr_pseudo_t() local h = self:header() ffi.copy(ph, h.src_ip, 2*ipv4_addr_t_size) -- Copy source and destination ph.ulp_length = C.htons(ulplen) ph.ulp_protocol = proto return(ph) end function selftest() local ipv4_address = "192.168.1.1" assert(ipv4_address == ipv4:ntop(ipv4:pton(ipv4_address)), 'ipv4 text to binary conversion failed.') local ipv4hdr = ipv4:new({}) assert(C.ntohs(ipv4hdr:header().ihl_v_tos) == 0x4500, 'ipv4 header field ihl_v_tos not initialized correctly.') end ipv4.selftest = selftest return ipv4
Fix ipv4 header initialization.
Fix ipv4 header initialization. The version/header length/TOS field is 16 not 32 bits wide. Also add a self-test.
Lua
apache-2.0
justincormack/snabbswitch,Igalia/snabb,dwdm/snabbswitch,andywingo/snabbswitch,heryii/snabb,aperezdc/snabbswitch,dpino/snabb,snabbnfv-goodies/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,lukego/snabbswitch,kbara/snabb,andywingo/snabbswitch,Igalia/snabb,eugeneia/snabb,eugeneia/snabbswitch,wingo/snabbswitch,Igalia/snabb,Igalia/snabb,alexandergall/snabbswitch,snabbco/snabb,lukego/snabbswitch,kbara/snabb,pirate/snabbswitch,eugeneia/snabb,heryii/snabb,heryii/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,wingo/snabb,alexandergall/snabbswitch,dpino/snabb,eugeneia/snabb,lukego/snabb,justincormack/snabbswitch,wingo/snabbswitch,eugeneia/snabb,heryii/snabb,dpino/snabb,wingo/snabb,dpino/snabb,Igalia/snabb,dpino/snabb,andywingo/snabbswitch,snabbco/snabb,andywingo/snabbswitch,mixflowtech/logsensor,justincormack/snabbswitch,Igalia/snabbswitch,Igalia/snabbswitch,Igalia/snabb,wingo/snabb,kbara/snabb,snabbco/snabb,kbara/snabb,Igalia/snabbswitch,dwdm/snabbswitch,dpino/snabbswitch,hb9cwp/snabbswitch,plajjan/snabbswitch,dpino/snabbswitch,mixflowtech/logsensor,eugeneia/snabb,snabbco/snabb,SnabbCo/snabbswitch,lukego/snabb,wingo/snabbswitch,kbara/snabb,aperezdc/snabbswitch,aperezdc/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,Igalia/snabb,kbara/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,mixflowtech/logsensor,dpino/snabbswitch,alexandergall/snabbswitch,wingo/snabb,hb9cwp/snabbswitch,SnabbCo/snabbswitch,hb9cwp/snabbswitch,aperezdc/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,snabbnfv-goodies/snabbswitch,lukego/snabb,lukego/snabbswitch,wingo/snabb,snabbnfv-goodies/snabbswitch,mixflowtech/logsensor,dpino/snabbswitch,alexandergall/snabbswitch,lukego/snabb,Igalia/snabb,lukego/snabbswitch,justincormack/snabbswitch,pirate/snabbswitch,snabbco/snabb,heryii/snabb,wingo/snabb,Igalia/snabbswitch,eugeneia/snabb,dpino/snabb,wingo/snabbswitch,plajjan/snabbswitch,plajjan/snabbswitch,mixflowtech/logsensor,heryii/snabb,dpino/snabb,dwdm/snabbswitch,snabbnfv-goodies/snabbswitch,plajjan/snabbswitch,eugeneia/snabb,eugeneia/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,pirate/snabbswitch,hb9cwp/snabbswitch
8af8e494bd993647bc82fed78676096d86831b72
src/patch/ui/lib/mppatch_softhook.lua
src/patch/ui/lib/mppatch_softhook.lua
-- Copyright (c) 2015-2017 Lymia Alusyia <[email protected]> -- -- 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. do local patch = DB.GetMemoryUsage("216f0090-85dd-4061-8371-3d8ba2099a70") local debugPrint if patch.__mppatch_marker then function debugPrint(line) print("[MPPatch] "..line) end else function debugPrint(line) patch.debugPrint(line) print("[MPPatch] "..line) end end include "mppatch_softhook_info.lua" if _mpPatch_SoftHookInfo and ContextPtr and ContextPtr:GetID() then local contextId = ContextPtr:GetID() local data = _mpPatch_SoftHookInfo[contextId] if data and not data.loaded then debugPrint("Loading soft hook for context "..contextId.."...") data.loaded = true for _, v in ipairs(data.include) do debugPrint("- Loading include "..v) include(v) end for _, v in ipairs(data.inject) do debugPrint("- Injecting "..v) include(v) end end end end
-- Copyright (c) 2015-2017 Lymia Alusyia <[email protected]> -- -- 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. do local patch = DB.GetMemoryUsage("216f0090-85dd-4061-8371-3d8ba2099a70") local debugPrint if patch.__mppatch_marker then function debugPrint(line) patch.debugPrint(line) print("[MPPatch] "..line) end else function debugPrint(line) print("[MPPatch] "..line) end end include "mppatch_softhook_info.lua" if _mpPatch_SoftHookInfo and ContextPtr and ContextPtr:GetID() then local contextId = ContextPtr:GetID() local data = _mpPatch_SoftHookInfo[contextId] if data and not data.loaded then debugPrint("Loading soft hook for context "..contextId.."...") data.loaded = true for _, v in ipairs(data.include) do debugPrint("- Loading include "..v) include(v) end for _, v in ipairs(data.inject) do debugPrint("- Injecting "..v) include(v) end end end end
Minor fix to softhook.
Minor fix to softhook.
Lua
mit
Lymia/MPPatch,Lymia/MPPatch,Lymia/CivV_Mod2DLC,Lymia/MultiverseModManager,Lymia/MultiverseModManager,Lymia/MPPatch,Lymia/MPPatch
effc2cb84466d59501fcc2e1e6a8d7a97f6a9d92
lua/timestamping.lua
lua/timestamping.lua
--- Hardware timestamping. local mod = {} local ffi = require "ffi" local dpdkc = require "dpdkc" local dpdk = require "dpdk" local device = require "device" local eth = require "proto.ethernet" local memory = require "memory" local timer = require "timer" local log = require "log" local filter = require "filter" local libmoon = require "libmoon" local timestamper = {} timestamper.__index = timestamper --- Create a new timestamper. --- A NIC can only be used by one thread at a time due to clock synchronization. --- Best current pratice is to use only one timestamping thread to avoid problems. function mod:newTimestamper(txQueue, rxQueue, mem, udp, doNotConfigureUdpPort) mem = mem or memory.createMemPool(function(buf) -- defaults are good enough for us here if udp then buf:getUdpPtpPacket():fill{ ethSrc = txQueue, } else buf:getPtpPacket():fill{ ethSrc = txQueue, } end end) txQueue:enableTimestamps() rxQueue:enableTimestamps() if udp and rxQueue.dev.supportsFdir then rxQueue:filterUdpTimestamps() elseif not udp then rxQueue:filterL2Timestamps() end return setmetatable({ mem = mem, txBufs = mem:bufArray(1), rxBufs = mem:bufArray(128), txQueue = txQueue, rxQueue = rxQueue, txDev = txQueue.dev, rxDev = rxQueue.dev, seq = 1, udp = udp, useTimesync = rxQueue.dev.useTimsyncIds, doNotConfigureUdpPort = doNotConfigureUdpPort }, timestamper) end --- See newTimestamper() function mod:newUdpTimestamper(txQueue, rxQueue, mem, doNotConfigureUdpPort) return self:newTimestamper(txQueue, rxQueue, mem, true, doNotConfigureUdpPort) end --- Try to measure the latency of a single packet. --- @param pktSize optional, the size of the generated packet, optional, defaults to the smallest possible size --- @param packetModifier optional, a function that is called with the generated packet, e.g. to modified addresses --- @param maxWait optional (cannot be the only argument) the time in ms to wait before the packet is assumed to be lost (default = 15) function timestamper:measureLatency(pktSize, packetModifier, maxWait) if type(pktSize) == "function" then -- optional first argument was skipped return self:measureLatency(nil, pktSize, packetModifier) end pktSize = pktSize or self.udp and 76 or 60 maxWait = (maxWait or 15) / 1000 self.txBufs:alloc(pktSize) local buf = self.txBufs[1] buf:enableTimestamps() local expectedSeq = self.seq self.seq = (self.seq + 1) % 2^16 if self.udp then buf:getUdpPtpPacket().ptp:setSequenceID(expectedSeq) else buf:getPtpPacket().ptp:setSequenceID(expectedSeq) end local skipReconfigure if packetModifier then skipReconfigure = packetModifier(buf) end if self.udp then if not self.doNotConfigureUdpPort then -- change timestamped UDP port as each packet may be on a different port self.rxQueue:enableTimestamps(buf:getUdpPacket().udp:getDstPort()) end buf:getUdpPtpPacket():setLength(pktSize) self.txBufs:offloadUdpChecksums() if self.rxQueue.dev.reconfigureUdpTimestampFilter and not skipReconfigure then -- i40e driver fdir filters are broken -- it is not possible to match on flex bytes in udp packets without matching IPs and ports as well -- so we have to look at that packet and reconfigure the filters self.rxQueue.dev:reconfigureUdpTimestampFilter(self.rxQueue, buf:getUdpPacket()) end end mod.syncClocks(self.txDev, self.rxDev) -- clear any "leftover" timestamps self.rxDev:clearTimestamps() self.txQueue:send(self.txBufs) local tx = self.txQueue:getTimestamp(500) local numPkts = 0 if tx then -- sent was successful, try to get the packet back (assume that it is lost after a given delay) local timer = timer:new(maxWait) while timer:running() do local rx = self.rxQueue:tryRecv(self.rxBufs, 1000) numPkts = numPkts + rx local timestampedPkt = self.rxDev:hasRxTimestamp() if not timestampedPkt then -- NIC didn't save a timestamp yet, just throw away the packets self.rxBufs:freeAll() else -- received a timestamped packet (not necessarily in this batch) for i = 1, rx do local buf = self.rxBufs[i] local timesync = self.useTimesync and buf:getTimesync() or 0 local seq = (self.udp and buf:getUdpPtpPacket() or buf:getPtpPacket()).ptp:getSequenceID() if buf:hasTimestamp() and seq == expectedSeq and (seq == timestampedPkt or timestampedPkt == -1) then -- yay! local rxTs = self.rxQueue:getTimestamp(nil, timesync) if not rxTs then -- can happen if you hotplug cables return nil, numPkts end self.rxBufs:freeAll() local lat = rxTs - tx if lat > 0 and lat < 2 * maxWait * 10^9 then -- negative latencies may happen if the link state changes -- (timers depend on a clock that scales with link speed on some NICs) -- really large latencies (we only wait for up to maxWait ms) -- also sometimes happen since changing to DPDK for reading the timing registers -- probably something wrong with the DPDK wraparound tracking -- (but that's really rare and the resulting latency > a few days, so we don't really care) return lat, numPkts end elseif buf:hasTimestamp() and (seq == timestampedPkt or timestampedPkt == -1) then -- we got a timestamp but the wrong sequence number. meh. self.rxQueue:getTimestamp(nil, timesync) -- clears the register -- continue, we may still get our packet :) elseif seq == expectedSeq and (seq ~= timestampedPkt and timestampedPkt ~= -1) then -- we got our packet back but it wasn't timestamped -- we likely ran into the previous case earlier and cleared the ts register too late self.rxBufs:freeAll() return nil, numPkts end end end end -- looks like our packet got lost :( return nil, numPkts else -- happens when hotplugging cables log:warn("Failed to timestamp packet on transmission") timer:new(maxWait):wait() return nil, numPkts end end function mod.syncClocks(dev1, dev2) local regs1 = dev1.timeRegisters local regs2 = dev2.timeRegisters if regs1[1] ~= regs2[1] or regs1[2] ~= regs2[2] or regs1[3] ~= regs2[3] or regs1[4] ~= regs2[4] then log:fatal("NICs incompatible, cannot sync clocks") end dpdkc.libmoon_sync_clocks(dev1.id, dev2.id, unpack(regs1)) -- just to tell the driver that we are resetting the clock -- otherwise the cycle tracker becomes confused on long latencies dev1:resetTimeCounters() dev2:resetTimeCounters() end return mod
--- Hardware timestamping. local mod = {} local ffi = require "ffi" local dpdkc = require "dpdkc" local dpdk = require "dpdk" local device = require "device" local eth = require "proto.ethernet" local memory = require "memory" local timer = require "timer" local log = require "log" local filter = require "filter" local libmoon = require "libmoon" local timestamper = {} timestamper.__index = timestamper --- Create a new timestamper. --- A NIC can only be used by one thread at a time due to clock synchronization. --- Best current pratice is to use only one timestamping thread to avoid problems. function mod:newTimestamper(txQueue, rxQueue, mem, udp, doNotConfigureUdpPort) mem = mem or memory.createMemPool(function(buf) -- defaults are good enough for us here if udp then buf:getUdpPtpPacket():fill{ ethSrc = txQueue, } else buf:getPtpPacket():fill{ ethSrc = txQueue, } end end) txQueue:enableTimestamps() rxQueue:enableTimestamps() if udp and rxQueue.dev.supportsFdir then rxQueue:filterUdpTimestamps() elseif not udp then rxQueue:filterL2Timestamps() end return setmetatable({ mem = mem, txBufs = mem:bufArray(1), rxBufs = mem:bufArray(128), txQueue = txQueue, rxQueue = rxQueue, txDev = txQueue.dev, rxDev = rxQueue.dev, seq = 1, udp = udp, useTimesync = rxQueue.dev.useTimsyncIds, doNotConfigureUdpPort = doNotConfigureUdpPort }, timestamper) end --- See newTimestamper() function mod:newUdpTimestamper(txQueue, rxQueue, mem, doNotConfigureUdpPort) return self:newTimestamper(txQueue, rxQueue, mem, true, doNotConfigureUdpPort) end --- Try to measure the latency of a single packet. --- @param pktSize optional, the size of the generated packet, optional, defaults to the smallest possible size --- @param packetModifier optional, a function that is called with the generated packet, e.g. to modified addresses --- @param maxWait optional (cannot be the only argument) the time in ms to wait before the packet is assumed to be lost (default = 15) function timestamper:measureLatency(pktSize, packetModifier, maxWait) if type(pktSize) == "function" then -- optional first argument was skipped return self:measureLatency(nil, pktSize, packetModifier) end pktSize = pktSize or self.udp and 76 or 60 maxWait = (maxWait or 15) / 1000 self.txBufs:alloc(pktSize) local buf = self.txBufs[1] buf:enableTimestamps() local expectedSeq = self.seq self.seq = (self.seq + 1) % 2^16 if self.udp then buf:getUdpPtpPacket().ptp:setSequenceID(expectedSeq) else buf:getPtpPacket().ptp:setSequenceID(expectedSeq) end local skipReconfigure if packetModifier then skipReconfigure = packetModifier(buf) end if self.udp then if not self.doNotConfigureUdpPort then -- change timestamped UDP port as each packet may be on a different port self.rxQueue:enableTimestamps(buf:getUdpPacket().udp:getDstPort()) end buf:getUdpPtpPacket():setLength(pktSize) self.txBufs:offloadUdpChecksums() if self.rxQueue.dev.reconfigureUdpTimestampFilter and not skipReconfigure then -- i40e driver fdir filters are broken -- it is not possible to match on flex bytes in udp packets without matching IPs and ports as well -- so we have to look at that packet and reconfigure the filters self.rxQueue.dev:reconfigureUdpTimestampFilter(self.rxQueue, buf:getUdpPacket()) end end mod.syncClocks(self.txDev, self.rxDev) -- clear any "leftover" timestamps self.rxDev:clearTimestamps() self.txQueue:send(self.txBufs) local tx = self.txQueue:getTimestamp(500) local numPkts = 0 if tx then -- sent was successful, try to get the packet back (assume that it is lost after a given delay) local timer = timer:new(maxWait) while timer:running() do local rx = self.rxQueue:tryRecv(self.rxBufs, 1000) numPkts = numPkts + rx local timestampedPkt = self.rxDev:hasRxTimestamp() if not timestampedPkt then -- NIC didn't save a timestamp yet, just throw away the packets self.rxBufs:freeAll() else -- received a timestamped packet (not necessarily in this batch) for i = 1, rx do local buf = self.rxBufs[i] local timesync = self.useTimesync and buf:getTimesync() or 0 local seq = (self.udp and buf:getUdpPtpPacket() or buf:getPtpPacket()).ptp:getSequenceID() if buf:hasTimestamp() and seq == expectedSeq and (seq == timestampedPkt or timestampedPkt == -1) then -- yay! local rxTs = self.rxQueue:getTimestamp(nil, timesync) if not rxTs then -- can happen if you hotplug cables return nil, numPkts end self.rxBufs:freeAll() local lat = rxTs - tx if lat > 0 and lat < 2 * maxWait * 10^9 then -- negative latencies may happen if the link state changes -- (timers depend on a clock that scales with link speed on some NICs) -- really large latencies (we only wait for up to maxWait ms) -- also sometimes happen since changing to DPDK for reading the timing registers -- probably something wrong with the DPDK wraparound tracking -- (but that's really rare and the resulting latency > a few days, so we don't really care) return lat, numPkts else return nil, numPkts end elseif buf:hasTimestamp() and (seq == timestampedPkt or timestampedPkt == -1) then -- we got a timestamp but the wrong sequence number. meh. self.rxQueue:getTimestamp(nil, timesync) -- clears the register -- continue, we may still get our packet :) elseif seq == expectedSeq and (seq ~= timestampedPkt and timestampedPkt ~= -1) then -- we got our packet back but it wasn't timestamped -- we likely ran into the previous case earlier and cleared the ts register too late self.rxBufs:freeAll() return nil, numPkts end end end end -- looks like our packet got lost :( return nil, numPkts else -- happens when hotplugging cables log:warn("Failed to timestamp packet on transmission") timer:new(maxWait):wait() return nil, numPkts end end function mod.syncClocks(dev1, dev2) local regs1 = dev1.timeRegisters local regs2 = dev2.timeRegisters if regs1[1] ~= regs2[1] or regs1[2] ~= regs2[2] or regs1[3] ~= regs2[3] or regs1[4] ~= regs2[4] then log:fatal("NICs incompatible, cannot sync clocks") end dpdkc.libmoon_sync_clocks(dev1.id, dev2.id, unpack(regs1)) -- just to tell the driver that we are resetting the clock -- otherwise the cycle tracker becomes confused on long latencies dev1:resetTimeCounters() dev2:resetTimeCounters() end return mod
timestamping: don't wait unnecessarily
timestamping: don't wait unnecessarily fixes #61
Lua
mit
libmoon/libmoon,libmoon/libmoon,libmoon/libmoon,emmericp/libmoon,scholzd/libmoon,scholzd/libmoon,scholzd/libmoon,emmericp/libmoon,emmericp/libmoon
cd075db3763ae9e096804c4a0a8310f51d0dc9f7
nvim/lua/options.lua
nvim/lua/options.lua
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd') local fn = vim.fn -- to call Vim functions e.g. fn.bufnr() local g = vim.g -- a table to access global variables local opt = vim.opt -- to set options g.mapleader = ',' opt.clipboard = 'unnamed' opt.hidden = true opt.ignorecase = true opt.number = true opt.smartcase = true opt.wildmode = 'longest,list' opt.tabstop = 2 opt.shiftwidth = 2 opt.shiftround = true opt.expandtab = true opt.cmdheight = 2 opt.listchars = { tab = '»\t', trail = '·', eol = '↲' } opt.modeline = false opt.showbreak = '>\\' opt.winaltkeys = 'no' opt.inccommand = 'split' opt.completeopt = 'menuone,noselect' opt.mouse = 'a' g.nvim_tree_side = 'right'
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd') local fn = vim.fn -- to call Vim functions e.g. fn.bufnr() local g = vim.g -- a table to access global variables local opt = vim.opt -- to set options g.mapleader = ',' opt.clipboard = 'unnamed' opt.hidden = true opt.ignorecase = true opt.number = true opt.smartcase = true opt.wildmode = 'longest,list' opt.tabstop = 2 opt.shiftwidth = 2 opt.shiftround = true opt.expandtab = true opt.cmdheight = 2 -- opt.listchars = { tab = '»\t', trail = '·', eol = '↲' } vim.cmd('set listchars=tab:»\\ ,trail:·,eol:↲') opt.modeline = false opt.showbreak = '>\\' opt.winaltkeys = 'no' opt.inccommand = 'split' opt.completeopt = 'menuone,noselect' opt.mouse = 'a' g.nvim_tree_side = 'right'
fix: listchar bug? with nvim 0.7
fix: listchar bug? with nvim 0.7
Lua
mit
drmohundro/dotfiles
b8f8467dddc14c1908e0c3bc6a9ec47fdea1ce74
json/decode.lua
json/decode.lua
local lpeg = require("lpeg") local util = require("json.util") local setmetatable, getmetatable = setmetatable, getmetatable local assert = assert local print = print local tonumber = tonumber local ipairs = ipairs local string = string module("json.decode") local digit = lpeg.R("09") local digits = digit^1 local alpha = lpeg.R("AZ","az") local hex = lpeg.R("09","AF","af") local hexpair = hex * hex local identifier = lpeg.R("AZ","az","__") * lpeg.R("AZ","az", "__", "09") ^0 local space = lpeg.S(" \n\r\t\f") local comment = (lpeg.P("//") * (1 - lpeg.P("\n"))^0 * lpeg.P("\n")) + (lpeg.P("/*") * (1 - lpeg.P("*/"))^0 * lpeg.P("*/")) local ignored = (space + comment)^0 local knownReplacements = { n = "\n", r = "\r", f = "\f", t = "\t", b = "\b", z = "\z", ['\\'] = "\\", ['/'] = "/", ['"'] = '"' } local function unicodeParse(code1, code2) code1, code2 = tonumber(code1, 16), tonumber(code2, 16) return string.char(code1, code2) end -- Potential deviation, allow for newlines inside strings local function buildStringCapture(stopParse, escapeMatch) return lpeg.P('"') * lpeg.Cs(((1 - lpeg.S(stopParse)) + (lpeg.P("\\") / "" * escapeMatch))^0) * lpeg.P('"') end local doSimpleSub = lpeg.C(lpeg.S("rnfbt/\\z\"")) / knownReplacements local doUniSub = (lpeg.P('u') * lpeg.C(hexpair) * lpeg.C(hexpair) + lpeg.P(false)) / unicodeParse local doSub = doSimpleSub + doUniSub -- Non-strict capture just spits back input value w/o slash local captureString = buildStringCapture('"\\', doSub + lpeg.C(1)) local strictCaptureString = buildStringCapture('"\\\r\n\f\b\t', #lpeg.S("rnfbt/\\\"u") * doSub) -- Deviation.. permit leading zeroes, permit inf number of negatives w/ space between local int = lpeg.P('-')^0 * space^0 * digits local number, strictNumber local strictInt = (lpeg.P('-') + 0) * (lpeg.R("19") * digits + digit) do local frac = lpeg.P('.') * digits local exp = lpeg.S("Ee") * (lpeg.S("-+") + 0) * digits -- Optional +- after the E local function getNumber(intBase) return intBase * (frac + 0) * (exp + 0) end number = getNumber(int) strictNumber = getNumber(strictInt) end local VAL, TABLE, ARRAY = 2,3,4 -- For null and undefined, use the util.null value to preserve null-ness local valueCapture = ignored * ( captureString + lpeg.C(number) / tonumber + lpeg.P("true") * lpeg.Cc(true) + lpeg.P("false") * lpeg.Cc(false) + (lpeg.P("null") + lpeg.P("undefined")) * lpeg.Cc(util.null) + lpeg.V(TABLE) + lpeg.V(ARRAY) ) * ignored local strictValueCapture = ignored * ( strictCaptureString + lpeg.C(strictNumber) / tonumber + lpeg.P("true") * lpeg.Cc(true) + lpeg.P("false") * lpeg.Cc(false) + lpeg.P("null") * lpeg.Cc(util.null) + lpeg.V(TABLE) + lpeg.V(ARRAY) ) * ignored local currentDepth local function initDepth(s, i) currentDepth = 0 return i end local function incDepth(s, i) currentDepth = currentDepth + 1 return currentDepth < 20 and i or false end local function decDepth(s, i) currentDepth = currentDepth - 1 return i end local tableKey = lpeg.C(identifier) + captureString + int / tonumber local strictTableKey = captureString local tableVal = lpeg.V(VAL) -- tableItem == pair local tableItem = tableKey * ignored * lpeg.P(':') * ignored * tableVal local strictTableItem = strictTableKey * ignored * lpeg.P(':') * ignored * tableVal local function applyTableKey(tab, key, val) if not tab then tab = {} end -- Initialize table for this set... tab[key] = val return tab end tableItem = tableItem / applyTableKey strictTableItem = strictTableItem / applyTableKey local tableElements = lpeg.Ca(lpeg.Cc(false) * tableItem * (ignored * lpeg.P(',') * ignored * tableItem)^0) local strictTableElements = lpeg.Ca(lpeg.Cc(false) * strictTableItem * (ignored * lpeg.P(',') * ignored * strictTableItem)^0) local tableCapture = lpeg.P("{") * ignored * (tableElements + 0) * ignored * (lpeg.P(',') + 0) * ignored * lpeg.P("}") local strictTableCapture = lpeg.P("{") * lpeg.P(incDepth) * ignored * (strictTableElements + 0) * ignored * lpeg.P("}") * lpeg.P(decDepth) -- Utility function to help manage slighly sparse arrays local function processArray(array) array.n = #array for i,v in ipairs(array) do if v == util.null then array[i] = nil end end if #array == array.n then array.n = nil end return array end -- arrayItem == element local arrayItem = lpeg.V(VAL) local arrayElements = lpeg.Ct(arrayItem * (ignored * lpeg.P(',') * ignored * arrayItem)^0) / processArray local strictArrayCapture = lpeg.P("[") * lpeg.P(incDepth) * ignored * (arrayElements + 0) * ignored * lpeg.P("]") * lpeg.P(decDepth) local arrayCapture = lpeg.P("[") * ignored * (arrayElements + 0) * ignored * (lpeg.P(",") + 0) * ignored * lpeg.P("]") -- Deviation: allow for trailing comma, allow for "undefined" to be a value... local grammar = lpeg.P({ [1] = lpeg.V(2), [VALUE] = valueCapture, [TABLE] = tableCapture, [ARRAY] = arrayCapture }) * ignored * -1 local strictGrammar = lpeg.P({ [1] = lpeg.P(initDepth) * (lpeg.V(TABLE) + lpeg.V(ARRAY)), -- Initial value MUST be an object or array [VALUE] = strictValueCapture, [TABLE] = strictTableCapture, [ARRAY] = strictArrayCapture }) * ignored * -1 --NOTE: Certificate was trimmed down to make it easier to read.... function decode(data, strict) return (assert(lpeg.match(not strict and grammar or strictGrammar, data), "Invalid JSON data")) end local mt = getmetatable(_M) or {} mt.__call = function(self, ...) return decode(...) end setmetatable(_M, mt)
local lpeg = require("lpeg") local util = require("json.util") local setmetatable, getmetatable = setmetatable, getmetatable local assert = assert local print = print local tonumber = tonumber local ipairs = ipairs local string = string module("json.decode") local digit = lpeg.R("09") local digits = digit^1 local alpha = lpeg.R("AZ","az") local hex = lpeg.R("09","AF","af") local hexpair = hex * hex local identifier = lpeg.R("AZ","az","__") * lpeg.R("AZ","az", "__", "09") ^0 local space = lpeg.S(" \n\r\t\f") local comment = (lpeg.P("//") * (1 - lpeg.P("\n"))^0 * lpeg.P("\n")) + (lpeg.P("/*") * (1 - lpeg.P("*/"))^0 * lpeg.P("*/")) local ignored = (space + comment)^0 local knownReplacements = { n = "\n", r = "\r", f = "\f", t = "\t", b = "\b", z = "\z", ['\\'] = "\\", ['/'] = "/", ['"'] = '"' } local function unicodeParse(code1, code2) code1, code2 = tonumber(code1, 16), tonumber(code2, 16) return string.char(code1, code2) end -- Potential deviation, allow for newlines inside strings local function buildStringCapture(stopParse, escapeMatch) return lpeg.P('"') * lpeg.Cs(((1 - lpeg.S(stopParse)) + (lpeg.P("\\") / "" * escapeMatch))^0) * lpeg.P('"') end local doSimpleSub = lpeg.C(lpeg.S("rnfbt/\\z\"")) / knownReplacements local doUniSub = (lpeg.P('u') * lpeg.C(hexpair) * lpeg.C(hexpair) + lpeg.P(false)) / unicodeParse local doSub = doSimpleSub + doUniSub -- Non-strict capture just spits back input value w/o slash local captureString = buildStringCapture('"\\', doSub + lpeg.C(1)) local strictCaptureString = buildStringCapture('"\\\r\n\f\b\t', #lpeg.S("rnfbt/\\\"u") * doSub) -- Deviation.. permit leading zeroes, permit inf number of negatives w/ space between local int = lpeg.P('-')^0 * space^0 * digits local number, strictNumber local strictInt = (lpeg.P('-') + 0) * (lpeg.R("19") * digits + digit) do local frac = lpeg.P('.') * digits local exp = lpeg.S("Ee") * (lpeg.S("-+") + 0) * digits -- Optional +- after the E local function getNumber(intBase) return intBase * (frac + 0) * (exp + 0) end number = getNumber(int) strictNumber = getNumber(strictInt) end local VALUE, TABLE, ARRAY = 2,3,4 -- For null and undefined, use the util.null value to preserve null-ness local valueCapture = ignored * ( captureString + lpeg.C(number) / tonumber + lpeg.P("true") * lpeg.Cc(true) + lpeg.P("false") * lpeg.Cc(false) + (lpeg.P("null") + lpeg.P("undefined")) * lpeg.Cc(util.null) + lpeg.V(TABLE) + lpeg.V(ARRAY) ) * ignored local strictValueCapture = ignored * ( strictCaptureString + lpeg.C(strictNumber) / tonumber + lpeg.P("true") * lpeg.Cc(true) + lpeg.P("false") * lpeg.Cc(false) + lpeg.P("null") * lpeg.Cc(util.null) + lpeg.V(TABLE) + lpeg.V(ARRAY) ) * ignored local currentDepth local function initDepth(s, i) currentDepth = 0 return i end local function incDepth(s, i) currentDepth = currentDepth + 1 return currentDepth < 20 and i or false end local function decDepth(s, i) currentDepth = currentDepth - 1 return i end local tableKey = lpeg.C(identifier) + captureString + int / tonumber local strictTableKey = captureString local tableVal = lpeg.V(VALUE) -- tableItem == pair local function applyTableKey(tab, key, val) if not tab then tab = {} end -- Initialize table for this set... tab[key] = val return tab end local function createTableItem(keyParser) return (keyParser * ignored * lpeg.P(':') * ignored * tableVal) / applyTableKey end local tableItem = createTableItem(tableKey) local strictTableItem = createTableItem(strictTableKey) local tableElements = lpeg.Ca(lpeg.Cc(false) * tableItem * (ignored * lpeg.P(',') * ignored * tableItem)^0) local strictTableElements = lpeg.Ca(lpeg.Cc(false) * strictTableItem * (ignored * lpeg.P(',') * ignored * strictTableItem)^0) local tableCapture = lpeg.P("{") * ignored * (tableElements + 0) * ignored * (lpeg.P(',') + 0) * ignored * lpeg.P("}") local strictTableCapture = lpeg.P("{") * lpeg.P(incDepth) * ignored * (strictTableElements + 0) * ignored * lpeg.P("}") * lpeg.P(decDepth) -- Utility function to help manage slighly sparse arrays local function processArray(array) array.n = #array for i,v in ipairs(array) do if v == util.null then array[i] = nil end end if #array == array.n then array.n = nil end return array end -- arrayItem == element local arrayItem = lpeg.V(VALUE) local arrayElements = lpeg.Ct(arrayItem * (ignored * lpeg.P(',') * ignored * arrayItem)^0) / processArray local strictArrayCapture = lpeg.P("[") * lpeg.P(incDepth) * ignored * (arrayElements + 0) * ignored * lpeg.P("]") * lpeg.P(decDepth) local arrayCapture = lpeg.P("[") * ignored * (arrayElements + 0) * ignored * (lpeg.P(",") + 0) * ignored * lpeg.P("]") -- Deviation: allow for trailing comma, allow for "undefined" to be a value... local grammar = lpeg.P({ [1] = lpeg.V(VALUE), [VALUE] = valueCapture, [TABLE] = tableCapture, [ARRAY] = arrayCapture }) * ignored * -1 local strictGrammar = lpeg.P({ [1] = lpeg.P(initDepth) * (lpeg.V(TABLE) + lpeg.V(ARRAY)), -- Initial value MUST be an object or array [VALUE] = strictValueCapture, [TABLE] = strictTableCapture, [ARRAY] = strictArrayCapture }) * ignored * -1 --NOTE: Certificate was trimmed down to make it easier to read.... function decode(data, strict) return (assert(lpeg.match(not strict and grammar or strictGrammar, data), "Invalid JSON data")) end local mt = getmetatable(_M) or {} mt.__call = function(self, ...) return decode(...) end setmetatable(_M, mt)
* Fixed a few regressions and refactored table-items
* Fixed a few regressions and refactored table-items
Lua
mit
renchunxiao/luajson
28fefbcda569ea3593614a3bccbc7b980ff15d76
timeline_0.0.1/interface.lua
timeline_0.0.1/interface.lua
local mark_timeline = require "timeline" remote.add_interface("timeline", { add_timeline_mark = function(force, name, params, value) mark_timeline(force, name, params, value) end, advanced_combinator_callback = function(params, entity, current) local param_name = params[1] local param_params = params[2] local param_value = params[3] local value = remote.call("advanced-combinator", "resolve", param_value, entity, current) mark_timeline(entity.force, param_name, param_params, value) end }) local function setup_integrations() if remote.interfaces["advanced-combinator"] then local advanced_combinator = remote.interfaces["advanced-combinator"] remote.call("advanced-combinator", "add_function", "add_timeline_mark", { description = "Add a mark to the timeline, with the specified name, params and value.", parameters = { "string", "string", "number" }, result = "command", parse = { interface = "timeline", func = "advanced_combinator_callback" } }) end end return { setup_integrations = setup_integrations }
local mark_timeline = require "timeline" remote.add_interface("timeline", { add_timeline_mark = function(force, name, params, value) mark_timeline(force, name, params, value) end, advanced_combinator_callback = function(params, entity, current) local param_name = params[1] local param_params = params[2] local param_value = params[3] local value = remote.call("advanced-combinator", "resolve", param_value, entity, current) mark_timeline(entity.force, param_name, param_params, value) end }) local function setup_integrations() if remote.interfaces["advanced-combinator"] then remote.call("advanced-combinator", "add_function", "add_timeline_mark", { description = "Add a mark to the timeline, with the specified name, params and value.", parameters = { "string", "string", "number" }, result = "command", parse = { interface = "timeline", func = "advanced_combinator_callback" } }) end end return { setup_integrations = setup_integrations }
Timeline: Luacheck fix
Timeline: Luacheck fix
Lua
mit
Zomis/FactorioMods
0e855411fbc9b3f63950c16bb863aaa88ac905ca
lib/switchboard_modules/lua_script_debugger/premade_scripts/I2C/gyro-L3GD20H.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/I2C/gyro-L3GD20H.lua
--This is an example that uses the LSM303DLHC Accelerometer & Magnetometer on the I2C Bus on EIO4(SCL) and EIO5(SDA) --Outputs data to Registers: --X gyro = 46012 --Y gyro = 46014 --Z gyro = 46016 fwver = MB.R(60004, 3) devType = MB.R(60000, 3) if (fwver < 1.0224 and devType == 7) or (fwver < 0.2037 and devType == 4) then print("This lua script requires a higher firmware version (T7 Requires 1.0224 or higher, T4 requires 0.2037 or higher). Program Stopping") MB.W(6000, 1, 0) end function convert_16_bit(msb, lsb, conv)--Returns a number, adjusted using the conversion factor. Use 1 if not desired res = 0 if msb >= 128 then res = (-0x7FFF+((msb-128)*256+lsb))/conv else res = (msb*256+lsb)/conv end return res end SLAVE_ADDRESS = 0x6B I2C.config(13, 12, 65516, 0, SLAVE_ADDRESS, 0)--configure the I2C Bus addrs = I2C.search(0, 127) addrsLen = table.getn(addrs) found = 0 for i=1, addrsLen do--verify that the target device was found if addrs[i] == SLAVE_ADDRESS then print("I2C Slave Detected") found = 1 break end end if found == 0 then print("No I2C Slave detected, program stopping") MB.W(6000, 1, 0) end --init slave I2C.write({0x21, 0x00})--1. Write CTRL2, disable filtering I2C.write({0x22, 0x00})--2. Write CTRL3, disable interupts I2C.write({0x23, 0x60})--3. Write CTRL4, continuous update, MSB at lower addr,2000 deg per second I2C.write({0x25, 0x00})--5. Write Reference to default 0 I2C.write({0x24, 0x00})--9. Write CTRL5, disable FIFO and interupts I2C.write({0x20, 0xBF})--10. Write CTRL1, enable all axes, 380Hz ODR LJ.IntervalConfig(0, 200) while true do if LJ.CheckInterval(0) then dataRaw = {} for i=0, 5 do I2C.write({0x28+i}) dataIn, errorIn = I2C.read(2) table.insert(dataRaw, dataIn[1]) end data = {} for i=0, 2 do table.insert(data, convert_16_bit(dataRaw[1+i*2], dataRaw[2+i*2], (0x7FFF/2000))) MB.W(46012+i*2, 3, data[i+1]) end print("X: "..data[1]) print("Y: "..data[2]) print("Z: "..data[3]) print("------") end end
--This is an example that uses the L3GD20H Gyroscope on the I2C Bus on EIO4(SCL) and EIO5(SDA) --Outputs data to Registers: --X gyro = 46012 --Y gyro = 46014 --Z gyro = 46016 fwver = MB.R(60004, 3) devType = MB.R(60000, 3) if (fwver < 1.0224 and devType == 7) or (fwver < 0.2037 and devType == 4) then print("This lua script requires a higher firmware version (T7 Requires 1.0224 or higher, T4 requires 0.2037 or higher). Program Stopping") MB.W(6000, 1, 0) end function convert_16_bit(msb, lsb, conv)--Returns a number, adjusted using the conversion factor. Use 1 if not desired res = 0 if msb >= 128 then res = (-0x7FFF+((msb-128)*256+lsb))/conv else res = (msb*256+lsb)/conv end return res end SLAVE_ADDRESS = 0x6B I2C.config(13, 12, 65516, 0, SLAVE_ADDRESS, 0)--configure the I2C Bus addrs = I2C.search(0, 127) addrsLen = table.getn(addrs) found = 0 for i=1, addrsLen do--verify that the target device was found if addrs[i] == SLAVE_ADDRESS then print("I2C Slave Detected") found = 1 break end end if found == 0 then print("No I2C Slave detected, program stopping") MB.W(6000, 1, 0) end --init slave I2C.write({0x21, 0x00})--1. Write CTRL2, disable filtering I2C.write({0x22, 0x00})--2. Write CTRL3, disable interupts I2C.write({0x23, 0x60})--3. Write CTRL4, continuous update, MSB at lower addr,2000 deg per second I2C.write({0x25, 0x00})--5. Write Reference to default 0 I2C.write({0x24, 0x00})--9. Write CTRL5, disable FIFO and interupts I2C.write({0x20, 0xBF})--10. Write CTRL1, enable all axes, 380Hz ODR LJ.IntervalConfig(0, 200) while true do if LJ.CheckInterval(0) then dataRaw = {} for i=0, 5 do I2C.write({0x28+i}) dataIn, errorIn = I2C.read(2) table.insert(dataRaw, dataIn[1]) end data = {} for i=0, 2 do table.insert(data, convert_16_bit(dataRaw[1+i*2], dataRaw[2+i*2], (0x7FFF/2000))) MB.W(46012+i*2, 3, data[i+1]) end print("X: "..data[1]) print("Y: "..data[2]) print("Z: "..data[3]) print("------") end end
fixed a lua script comment
fixed a lua script comment
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
390ee4ba112a07c9fd4a586d38cff22e41a9b79d
scripts/lmkbuild.lua
scripts/lmkbuild.lua
require "lmk" require "lmkutil" require "lmkbase" local assert = assert local error = error local io = io local ipairs = ipairs local lmk = lmk local lmkbase = lmkbase local lmkutil = lmkutil local os = os local print = print local tostring = tostring local type = type module (...) add_files = lmk.add_files_local append_global = lmk.append_global append_local = lmk.append_local get_var = lmk.get_var resolve = lmk.resolve set_local = lmk.set_local set_global = lmk.set_global system = lmk.system is_dir = lmkbase.is_dir directories = lmkbase.directories files = lmkbase.files function print_success (msg) print (lmk.ConsoleGreen .. msg .. lmk.ConsoleDefault) end function print_fail (msg) print (lmk.ConsoleRed .. msg .. lmk.ConsoleDefault) end function verbose () return lmk.IsVerbose end local buildPart1 = nil local buildPart2 = nil function get_build_number () if not buildPart1 or not buildPart2 then buildPart1 = os.date ("!%y%m%d") buildPart2 = os.date ("!%H%M%S") end return tostring (buildPart1) .. "-" .. tostring (buildPart2), tostring (buildPart1), tostring (buildPart2) end function append_table (target, add) if type (target) ~= "table" then error ("Expect table but was given: " .. type (target)) end local size = #target if type (add) ~= "table" then target[size + 1] = add else for ix = 1, #add do target[size + ix] = add[ix] end end end function set_persist (name, value) set_global (name, value, true) end function rm (path) path = lmkutil.clean_path (lmk.resolve (path)) local result, msg = true, nil if lmkbase.is_valid (path) then print ("Removing: " .. path) result, msg = lmkutil.raw_rm (path) end return result, msg end function mkdir (path) path = lmkutil.clean_path (lmk.resolve (path)) local result, msg = true, nil assert (path ~= "", "Path not defined for lmkbuild.mkdir") if path then result, msg = lmkutil.raw_mkdir (path) end return result, msg end function split (path) path = lmkutil.clean_path (lmk.resolve (path)) local file, ext = nil, nil if path then path, file, ext = lmkutil.raw_split (path) end return path, file, ext end function split_path_and_file (path) local file, ext = nil, nil path, file, ext = split (path) if ext and file then file = file .. "." .. ext end return path, file end function abs_path (path) return lmkutil.raw_abs_path (lmk.resolve (path)) end local function copy_file (src, target) local result = false local inp = io.open (src, "rb") local out = io.open (target, "wb") if inp and out then local data = inp:read ("*all") out:write (data) io.close (inp) io.close (out) result = true end return result end function cp (fileList, target) local result = true target = lmkutil.clean_path (lmk.resolve (target)) if type (fileList) ~= "table" then fileList = { fileList } end if lmkbase.is_dir (target) then for index, file in ipairs (fileList) do file = lmkutil.clean_path (lmk.resolve (file)) if lmkbase.is_valid (file) then local path = nil path, file = split_path_and_file (file) if not copy_file (file, target .. "/" .. file) then result = false end end end else if #fileList == 1 then local file = lmk.resolve (fileList[1]) if (lmkbase.is_valid (file)) then result = copy_file (file, target) else result = false; end else result = false msg = "Unable to copy multiple files to single file" end end return result end function is_valid (path) return lmkbase.is_valid (lmk.resolve (path)) end function file_newer (src, target) local result, msg = false, nil if type (src) ~= "table" then src = { src } end target = lmkutil.clean_path (lmk.resolve (target)) if lmkbase.is_valid (target) then for index, file in ipairs (src) do file = lmkutil.clean_path (lmk.resolve (file)) if lmkbase.is_valid (file) then result = lmkbase.file_newer (file, target) if result then break end else result = true print ("Warning: source file: " .. file .. " does not exist for target file: " .. target) break end end else result = true end return result, msg end function exec (list) if type (list) ~= "table" then list = { list } end for index, item in ipairs (list) do local todo = resolve (item) assert (todo and todo ~= "", "Empty exec string from: " .. item) if lmk.IsVerbose then print (todo) local result = os.execute (todo) assert (result == 0, "Build faild in " .. lmkbase.pwd ()) else local result = os.execute (todo) if result ~= 0 then print (todo) error ("Build failded in " .. lmkbase.pwd ()) end end end end function find_file (item, paths) local file = lmk.resolve (item) if is_valid (file) then file = abs_path (file) elseif paths then local p, f, e = split (file) file = nil for ix = 1, #paths do local testPath = resolve (paths[ix] .. "/" .. item) if is_valid (testPath) then file = abs_path (testPath); break else testPath = resolve (paths[ix]) .. f .. (e and ("." .. e) or "") if is_valid (testPath) then file = abs_path (testPath); break end end end end return file end
require "lmk" require "lmkutil" require "lmkbase" local assert = assert local error = error local io = io local ipairs = ipairs local lmk = lmk local lmkbase = lmkbase local lmkutil = lmkutil local os = os local print = print local tostring = tostring local type = type module (...) add_files = lmk.add_files_local append_global = lmk.append_global append_local = lmk.append_local get_var = lmk.get_var resolve = lmk.resolve set_local = lmk.set_local set_global = lmk.set_global system = lmk.system is_dir = lmkbase.is_dir directories = lmkbase.directories files = lmkbase.files function print_success (msg) print (lmk.ConsoleGreen .. msg .. lmk.ConsoleDefault) end function print_fail (msg) print (lmk.ConsoleRed .. msg .. lmk.ConsoleDefault) end function verbose () return lmk.IsVerbose end local buildPart1 = nil local buildPart2 = nil function get_build_number () if not buildPart1 or not buildPart2 then buildPart1 = os.date ("!%y%m%d") buildPart2 = os.date ("!%H%M%S") end return tostring (buildPart1) .. "-" .. tostring (buildPart2), tostring (buildPart1), tostring (buildPart2) end function append_table (target, add) if type (target) ~= "table" then error ("Expect table but was given: " .. type (target)) end local size = #target if type (add) ~= "table" then target[size + 1] = add else for ix = 1, #add do target[size + ix] = add[ix] end end end function set_persist (name, value) set_global (name, value, true) end function rm (path) path = lmkutil.clean_path (lmk.resolve (path)) local result, msg = true, nil if lmkbase.is_valid (path) then print ("Removing: " .. path) result, msg = lmkutil.raw_rm (path) end return result, msg end function mkdir (path) path = lmkutil.clean_path (lmk.resolve (path)) local result, msg = true, nil assert (path ~= "", "Path not defined for lmkbuild.mkdir") if path then result, msg = lmkutil.raw_mkdir (path) end return result, msg end function split (path) path = lmkutil.clean_path (lmk.resolve (path)) local file, ext = nil, nil if path then path, file, ext = lmkutil.raw_split (path) end return path, file, ext end function split_path_and_file (path) local file, ext = nil, nil path, file, ext = split (path) if ext and file then file = file .. "." .. ext end return path, file end function abs_path (path) return lmkutil.raw_abs_path (lmk.resolve (path)) end local function copy_file (src, target) local result = false local inp = io.open (src, "rb") local out = io.open (target, "wb") if inp and out then local data = inp:read ("*all") out:write (data) io.close (inp) io.close (out) result = true end return result end function cp (fileList, target) local result = true target = lmkutil.clean_path (lmk.resolve (target)) if type (fileList) ~= "table" then fileList = { fileList } end if lmkbase.is_dir (target) then for index, file in ipairs (fileList) do file = lmkutil.clean_path (lmk.resolve (file)) if lmkbase.is_valid (file) then local path = nil path, fileName = split_path_and_file (file) if not copy_file (file, target .. "/" .. fileName) then result = false end end end else if #fileList == 1 then local file = lmk.resolve (fileList[1]) if (lmkbase.is_valid (file)) then result = copy_file (file, target) else result = false; end else result = false msg = "Unable to copy multiple files to single file" end end return result end function is_valid (path) return lmkbase.is_valid (lmk.resolve (path)) end function file_newer (src, target) local result, msg = false, nil target = lmkutil.clean_path (lmk.resolve (target)) if type (src) ~= "table" then src = { src } end target = lmkutil.clean_path (lmk.resolve (target)) if lmkbase.is_valid (target) then for index, file in ipairs (src) do file = lmkutil.clean_path (lmk.resolve (file)) if lmkbase.is_valid (file) then result = lmkbase.file_newer (file, target) if result then break end else result = true print ("Warning: source file: " .. file .. " does not exist for target file: " .. target) break end end else result = true end return result, msg end function exec (list) if type (list) ~= "table" then list = { list } end for index, item in ipairs (list) do local todo = resolve (item) assert (todo and todo ~= "", "Empty exec string from: " .. item) if lmk.IsVerbose then print (todo) local result = os.execute (todo) assert (result == 0, "Build faild in " .. lmkbase.pwd ()) else local result = os.execute (todo) if result ~= 0 then print (todo) error ("Build failded in " .. lmkbase.pwd ()) end end end end function find_file (item, paths) local file = lmk.resolve (item) if is_valid (file) then file = abs_path (file) elseif paths then local p, f, e = split (file) file = nil for ix = 1, #paths do local testPath = resolve (paths[ix] .. "/" .. item) if is_valid (testPath) then file = abs_path (testPath); break else testPath = resolve (paths[ix]) .. f .. (e and ("." .. e) or "") if is_valid (testPath) then file = abs_path (testPath); break end end end end return file end
bugfix: lmkbuild.cp would fail when copying a file to a directory
bugfix: lmkbuild.cp would fail when copying a file to a directory
Lua
mit
dmzgroup/lmk,shillcock/lmk
d18b7f588a8887644d53cb5f044589085097f98e
xmake/core/base/template.lua
xmake/core/base/template.lua
--!The Automatic Cross-platform Build Tool -- -- XMake is free software; you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as published by -- the Free Software Foundation; either version 2.1 of the License, or -- (at your option) any later version. -- -- XMake is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public License -- along with XMake; -- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a> -- -- Copyright (C) 2009 - 2015, ruki All rights reserved. -- -- @author ruki -- @file template.lua -- -- define module: template local template = template or {} -- load modules local os = require("base/os") local io = require("base/io") local path = require("base/path") local table = require("base/table") local utils = require("base/utils") local string = require("base/string") local filter = require("base/filter") local sandbox = require("base/sandbox") local interpreter = require("base/interpreter") -- get interpreter function template._interpreter() -- the interpreter has been initialized? return it directly if template._INTERPRETER then return template._INTERPRETER end -- init interpreter local interp = interpreter.init() assert(interp) -- register api: set_values() for root interp:api_register_set_values(nil, nil, "description" , "projectdir") -- register api: add_values() for root interp:api_register_add_values(nil, nil, "macrofiles") -- register api: add_keyvalues() for root interp:api_register_add_keyvalues(nil, nil, "macros") -- register api: set_script() for root interp:api_register_set_script(nil, nil, "createscript") -- save interpreter template._INTERPRETER = interp -- ok? return interp end -- replace macros function template._replace(macros, macrofiles) -- check assert(macros and macrofiles) -- make all files local files = {} for _, macrofile in ipairs(utils.wrap(macrofiles)) do local matchfiles = os.match(macrofile) if matchfiles then table.join2(files, matchfiles) end end -- replace all files for _, file in ipairs(files) do for macro, value in pairs(macros) do io.gsub(file, "%[" .. macro .. "%]", value) end end -- ok return true end -- get the language list function template.languages() -- make list local list = {} -- get the language list local languages = os.match(xmake._TEMPLATES_DIR .. "/*", true) if languages then for _, v in ipairs(languages) do table.insert(list, path.basename(v)) end end -- ok? return list end -- load all templates from the given language function template.loadall(language) -- check assert(language) -- get interpreter local interp = template._interpreter() assert(interp) -- load all templates local templates = {} local templatefiles = os.match(string.format("%s/%s/**/template.lua", xmake._TEMPLATES_DIR, language)) if templatefiles then -- load template for _, templatefile in ipairs(templatefiles) do -- load templates local results, errors = interp:load(templatefile, nil, true, true) if not results then -- trace utils.error(errors) utils.abort() end -- save template directory results._DIRECTORY = path.directory(templatefile) -- insert to templates table.insert(templates, results) end end -- ok? return templates end -- create project from template function template.create(language, templateid, targetname) -- check the language if not language then return false, "no language!" end -- check the template id if not templateid then return false, "no template id!" end templateid = tonumber(templateid) if type(templateid) ~= "number" then return false, "invalid template id!" end -- get interpreter local interp = template._interpreter() assert(interp) -- set filter interp:filter_set(filter.init(function (variable) -- init maps local maps = { targetname = targetname , projectdir = xmake._PROJECT_DIR , packagesdir = xmake._PACKAGES_DIR } -- map it local result = maps[variable] if result ~= nil then return result end -- ok? return variable end)) -- load all templates for the given language local templates = template.loadall(language) -- load the template module local module = nil if templates then module = templates[templateid] end if not module then return false, string.format("invalid template id: %d!", templateid) end -- enter the template directory if not module._DIRECTORY or not os.cd(module._DIRECTORY) then return false, string.format("not found template id: %d!", templateid) end -- check the template project if not module.projectdir or not os.isdir(module.projectdir) then return false, string.format("the template project not exists!") end -- ensure the project directory if not os.isdir(xmake._PROJECT_DIR) then os.mkdir(xmake._PROJECT_DIR) end -- copy the project files local ok, errors = os.cp(path.join(module.projectdir, "*"), xmake._PROJECT_DIR) if not ok then return false, errors end -- enter the project directory if not os.cd(xmake._PROJECT_DIR) then return false, string.format("can not enter %s!", xmake._PROJECT_DIR) end -- replace macros if module.macros and module.macrofiles then ok, errors = template._replace(module.macros, module.macrofiles) if not ok then return false, errors end end -- check if not module.createscript then utils.error("please set_createscript() first!") return false end -- create project local ok, errors = sandbox.load(module.createscript) if not ok then utils.errors(errors) return false end -- ok return true end -- return module: template return template
--!The Automatic Cross-platform Build Tool -- -- XMake is free software; you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as published by -- the Free Software Foundation; either version 2.1 of the License, or -- (at your option) any later version. -- -- XMake is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public License -- along with XMake; -- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a> -- -- Copyright (C) 2009 - 2015, ruki All rights reserved. -- -- @author ruki -- @file template.lua -- -- define module: template local template = template or {} -- load modules local os = require("base/os") local io = require("base/io") local path = require("base/path") local table = require("base/table") local utils = require("base/utils") local string = require("base/string") local filter = require("base/filter") local sandbox = require("base/sandbox") local interpreter = require("base/interpreter") -- get interpreter function template._interpreter() -- the interpreter has been initialized? return it directly if template._INTERPRETER then return template._INTERPRETER end -- init interpreter local interp = interpreter.init() assert(interp) -- register api: set_values() for root interp:api_register_set_values(nil, nil, "description" , "projectdir") -- register api: add_values() for root interp:api_register_add_values(nil, nil, "macrofiles") -- register api: add_keyvalues() for root interp:api_register_add_keyvalues(nil, nil, "macros") -- register api: set_script() for root interp:api_register_set_script(nil, nil, "createscript") -- save interpreter template._INTERPRETER = interp -- ok? return interp end -- replace macros function template._replace(macros, macrofiles) -- check assert(macros and macrofiles) -- make all files local files = {} for _, macrofile in ipairs(utils.wrap(macrofiles)) do local matchfiles = os.match(macrofile) if matchfiles then table.join2(files, matchfiles) end end -- replace all files for _, file in ipairs(files) do for macro, value in pairs(macros) do io.gsub(file, "%[" .. macro .. "%]", value) end end -- ok return true end -- get the language list function template.languages() -- make list local list = {} -- get the language list local languages = os.match(xmake._TEMPLATES_DIR .. "/*", true) if languages then for _, v in ipairs(languages) do table.insert(list, path.basename(v)) end end -- ok? return list end -- load all templates from the given language function template.loadall(language) -- check assert(language) -- get interpreter local interp = template._interpreter() assert(interp) -- load all templates local templates = {} local templatefiles = os.match(string.format("%s/%s/**/template.lua", xmake._TEMPLATES_DIR, language)) if templatefiles then -- load template for _, templatefile in ipairs(templatefiles) do -- load templates local results, errors = interp:load(templatefile, nil, true, true) if not results then -- trace utils.error(errors) utils.abort() end -- save template directory results._DIRECTORY = path.directory(templatefile) -- insert to templates table.insert(templates, results) end end -- ok? return templates end -- create project from template function template.create(language, templateid, targetname) -- check the language if not language then return false, "no language!" end -- check the template id if not templateid then return false, "no template id!" end templateid = tonumber(templateid) if type(templateid) ~= "number" then return false, "invalid template id!" end -- get interpreter local interp = template._interpreter() assert(interp) -- set filter interp:filter_set(filter.init(function (variable) -- init maps local maps = { targetname = targetname , projectdir = xmake._PROJECT_DIR , packagesdir = xmake._PACKAGES_DIR } -- map it local result = maps[variable] if result ~= nil then return result end -- ok? return variable end)) -- load all templates for the given language local templates = template.loadall(language) -- load the template module local module = nil if templates then module = templates[templateid] end if not module then return false, string.format("invalid template id: %d!", templateid) end -- enter the template directory if not module._DIRECTORY or not os.cd(module._DIRECTORY) then return false, string.format("not found template id: %d!", templateid) end -- check the template project if not module.projectdir or not os.isdir(module.projectdir) then return false, string.format("the template project not exists!") end -- ensure the project directory if not os.isdir(xmake._PROJECT_DIR) then os.mkdir(xmake._PROJECT_DIR) end -- copy the project files local ok, errors = os.cp(path.join(module.projectdir, "*"), xmake._PROJECT_DIR) if not ok then return false, errors end -- enter the project directory if not os.cd(xmake._PROJECT_DIR) then return false, string.format("can not enter %s!", xmake._PROJECT_DIR) end -- replace macros if module.macros and module.macrofiles then ok, errors = template._replace(module.macros, module.macrofiles) if not ok then return false, errors end end -- create project if module.createscript then local ok, errors = sandbox.load(module.createscript) if not ok then utils.errors(errors) return false end end -- ok return true end -- return module: template return template
fix template bug
fix template bug
Lua
apache-2.0
tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake
068999656addf230aac038b5c1de0e3db976dbf1
xmake/scripts/tools/make.lua
xmake/scripts/tools/make.lua
--!The Automatic Cross-platform Build Tool -- -- XMake is free software; you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as published by -- the Free Software Foundation; either version 2.1 of the License, or -- (at your option) any later version. -- -- XMake is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public License -- along with XMake; -- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a> -- -- Copyright (C) 2009 - 2015, ruki All rights reserved. -- -- @author ruki -- @file make.lua -- -- load modules local os = require("base/os") local utils = require("base/utils") -- define module: make local make = make or {} -- the init function function make.init(self, name) -- save name self.name = name or "make" -- is verbose? self._VERBOSE = utils.ifelse(xmake._OPTIONS.verbose, "-v", "") end -- the main function function make.main(self, mkfile, target) -- make command local cmd = nil if mkfile and os.isfile(mkfile) then cmd = string.format("%s -j4 -f %s %s VERBOSE=%s", self.name, mkfile, target or "", self._VERBOSE) else cmd = string.format("%s -j4 %s VERBOSE=%s", self.name, target or "", self._VERBOSE) end -- done local ok = os.execute(cmd) if ok ~= 0 then return false end -- ok return true end -- return module: make return make
--!The Automatic Cross-platform Build Tool -- -- XMake is free software; you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as published by -- the Free Software Foundation; either version 2.1 of the License, or -- (at your option) any later version. -- -- XMake is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public License -- along with XMake; -- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a> -- -- Copyright (C) 2009 - 2015, ruki All rights reserved. -- -- @author ruki -- @file make.lua -- -- load modules local os = require("base/os") local utils = require("base/utils") -- define module: make local make = make or {} -- the init function function make.init(self, name) -- save name self.name = name or "make" -- is verbose? self._VERBOSE = utils.ifelse(xmake._OPTIONS.verbose, "-v", "") end -- the main function function make.main(self, mkfile, target) -- make command local cmd = nil if mkfile and os.isfile(mkfile) then cmd = string.format("%s -j4 -f %s %s VERBOSE=%s", self.name, mkfile, target or "", self._VERBOSE) else cmd = string.format("%s -j4 %s VERBOSE=%s", self.name, target or "", self._VERBOSE) end -- done local ok = os.execute(cmd) if ok ~= 0 then -- attempt to execute it again for getting the error logs without -j4 if mkfile and os.isfile(mkfile) then cmd = string.format("%s -f %s %s VERBOSE=%s", self.name, mkfile, target or "", self._VERBOSE) else cmd = string.format("%s %s VERBOSE=%s", self.name, target or "", self._VERBOSE) end -- done return os.execute(cmd) == 0 end -- ok return true end -- return module: make return make
fix cannot get error log when make with -j4
fix cannot get error log when make with -j4
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake
84913a3ce400d520803e4be83ac501884b4ed118
resources/GTWturnsignals/turninsignals.lua
resources/GTWturnsignals/turninsignals.lua
--[[ ******************************************************************************** Project: GTW RPG Owner: GTW Games Location: Sweden Developers: MrBrutus Copyrights: See: "license.txt" Website: http://code.albonius.com Version: (git) Status: Stable release ******************************************************************************** ]]-- -- Global data and pointers toggler = { } dtype = { } syncTimer = { } currHeadLightColor = {{ }} -- Bind keys function bindTurnIndicators() bindKey(source, ",", "down", lightHandler, source, "lleft") bindKey(source, ".", "down", lightHandler, source, "lright") bindKey(source, "-", "down", lightHandler, source, "warn") end addEventHandler("onPlayerJoin", root, bindTurnIndicators) -- Bind on resource start for k,v in pairs(getElementsByType("players")) do bindKey(v, ",", "down", lightHandler, v, "lleft") bindKey(v, ".", "down", lightHandler, v, "lright") bindKey(v, "-", "down", lightHandler, v, "warn") end -- Toggling lights function toggleLights( veh ) if isElement( veh ) then setVehicleOverrideLights( veh, 2 ) if toggler[veh] == 1 then setVehicleLightState( veh, 0, 1 ) setVehicleLightState( veh, 1, 1 ) setVehicleLightState( veh, 2, 1 ) setVehicleLightState( veh, 3, 1 ) if getVehicleTowedByVehicle( veh ) then local veh2 = getVehicleTowedByVehicle( veh ) if veh2 then setVehicleLightState( veh2, 0, 1 ) setVehicleLightState( veh2, 1, 1 ) setVehicleLightState( veh2, 2, 1 ) setVehicleLightState( veh2, 3, 1 ) end end toggler[veh] = 0 else if dtype[veh] == "lleft" then setVehicleLightState( veh, 0, 0 ) setVehicleLightState( veh, 1, 1 ) setVehicleLightState( veh, 2, 1 ) setVehicleLightState( veh, 3, 0 ) if getVehicleTowedByVehicle( veh ) then local veh2 = getVehicleTowedByVehicle( veh ) if veh2 then setVehicleLightState( veh2, 0, 0 ) setVehicleLightState( veh2, 1, 1 ) setVehicleLightState( veh2, 2, 1 ) setVehicleLightState( veh2, 3, 0 ) end end elseif dtype[veh] == "lright" then setVehicleLightState( veh, 0, 1 ) setVehicleLightState( veh, 1, 0 ) setVehicleLightState( veh, 2, 0 ) setVehicleLightState( veh, 3, 1 ) if getVehicleTowedByVehicle( veh ) then local veh2 = getVehicleTowedByVehicle( veh ) if veh2 then setVehicleLightState( veh2, 0, 1 ) setVehicleLightState( veh2, 1, 0 ) setVehicleLightState( veh2, 2, 0 ) setVehicleLightState( veh2, 3, 1 ) end end elseif dtype[veh] == "warn" then setVehicleLightState( veh, 0, 0 ) setVehicleLightState( veh, 1, 0 ) setVehicleLightState( veh, 2, 0 ) setVehicleLightState( veh, 3, 0 ) if getVehicleTowedByVehicle( veh ) then local veh2 = getVehicleTowedByVehicle( veh ) if veh2 then setVehicleLightState( veh2, 0, 0 ) setVehicleLightState( veh2, 1, 0 ) setVehicleLightState( veh2, 2, 0 ) setVehicleLightState( veh2, 3, 0 ) end end end toggler[veh] = 1 end end end -- Left function lightHandler( player, cmd ) if player and isElement( player ) and getPedOccupiedVehicle( player ) then local veh = getPedOccupiedVehicle( player ) if ( not isTimer( syncTimer[veh] ) or cmd ~= dtype[veh] ) and getVehicleOccupants(veh)[0] == player then -- Save the current head light color setVehicleLightState( veh, 0, 1 ) setVehicleLightState( veh, 1, 1 ) setVehicleLightState( veh, 2, 1 ) setVehicleLightState( veh, 3, 1 ) if getVehicleTowedByVehicle( veh ) then local veh2 = getVehicleTowedByVehicle( veh ) if veh2 then setVehicleLightState( veh2, 0, 1 ) setVehicleLightState( veh2, 1, 1 ) setVehicleLightState( veh2, 2, 1 ) setVehicleLightState( veh2, 3, 1 ) end end if not currHeadLightColor[veh] then currHeadLightColor[veh] = { } currHeadLightColor[veh][1],currHeadLightColor[veh][2],currHeadLightColor[veh][3] = getVehicleHeadLightColor( veh ) end -- Set the new headlight color to yellow setVehicleHeadLightColor( veh, 255, 200, 0 ) -- Start the syn timer if isTimer( syncTimer[veh] ) then killTimer( syncTimer[veh] ) end syncTimer[veh] = setTimer( toggleLights, 380, 0, veh ) toggler[veh] = 1 dtype[veh] = cmd toggleLights( veh ) else if isTimer( syncTimer[veh] ) then killTimer( syncTimer[veh] ) setVehicleHeadLightColor( veh, currHeadLightColor[veh][1],currHeadLightColor[veh][2],currHeadLightColor[veh][3] ) currHeadLightColor[veh][1] = nil currHeadLightColor[veh][2] = nil currHeadLightColor[veh][3] = nil currHeadLightColor[veh] = nil end startLights(veh) end end end addCommandHandler( "lleft", lightHandler ) addCommandHandler( "lright", lightHandler ) addCommandHandler( "warn", lightHandler ) --[[ Turn on all lights ]]-- function startLights(veh) if not veh or not isElement(veh) then return end setVehicleLightState( veh, 0, 0 ) setVehicleLightState( veh, 1, 0 ) setVehicleLightState( veh, 2, 0 ) setVehicleLightState( veh, 3, 0 ) setVehicleOverrideLights( veh, 2 ) if getVehicleTowedByVehicle( veh ) then local veh2 = getVehicleTowedByVehicle( veh ) if veh2 then setVehicleLightState( veh2, 0, 0 ) setVehicleLightState( veh2, 1, 0 ) setVehicleLightState( veh2, 2, 0 ) setVehicleLightState( veh2, 3, 0 ) setVehicleOverrideLights( veh2, 2 ) end end end --[[ Attempt's to cleanup tables 2014-12-11 ]]-- function cleanUp(plr, seat, jacked, door) if (door or 0) > 0 then return end if isTimer(syncTimer[source]) then killTimer(syncTimer[source]) end syncTimer[source] = nil toggler[source] = nil dtype[source] = nil -- Reset color if currHeadLightColor[source] and currHeadLightColor[source][1] and currHeadLightColor[source][2] and currHeadLightColor[source][3] then setVehicleHeadLightColor( source, currHeadLightColor[source][1],currHeadLightColor[source][2],currHeadLightColor[source][3] ) currHeadLightColor[source][1] = nil currHeadLightColor[source][2] = nil currHeadLightColor[source][3] = nil currHeadLightColor[source] = nil end -- Reset light state startLights(veh) end addEventHandler("onVehicleStartExit", root, cleanUp)
--[[ ******************************************************************************** Project: GTW RPG Owner: GTW Games Location: Sweden Developers: MrBrutus Copyrights: See: "license.txt" Website: http://code.albonius.com Version: (git) Status: Stable release ******************************************************************************** ]]-- -- Global data and pointers toggler = { } dtype = { } syncTimer = { } currHeadLightColor = {{ }} -- Bind keys function bindTurnIndicators() bindKey(source, ",", "down", "lleft") bindKey(source, ".", "down", "lright") bindKey(source, "-", "down", "warn") end addEventHandler("onPlayerJoin", root, bindTurnIndicators) -- Bind on resource start for k,v in pairs(getElementsByType("players")) do bindKey(v, ",", "down", "lleft") bindKey(v, ".", "down", "lright") bindKey(v, "-", "down", "warn") outputServerLog("player: "..getPlayerName(v)) end -- Toggling lights function toggleLights( veh ) if isElement( veh ) then setVehicleOverrideLights( veh, 2 ) if toggler[veh] == 1 then setVehicleLightState( veh, 0, 1 ) setVehicleLightState( veh, 1, 1 ) setVehicleLightState( veh, 2, 1 ) setVehicleLightState( veh, 3, 1 ) if getVehicleTowedByVehicle( veh ) then local veh2 = getVehicleTowedByVehicle( veh ) if veh2 then setVehicleLightState( veh2, 0, 1 ) setVehicleLightState( veh2, 1, 1 ) setVehicleLightState( veh2, 2, 1 ) setVehicleLightState( veh2, 3, 1 ) end end toggler[veh] = 0 else if dtype[veh] == "lleft" then setVehicleLightState( veh, 0, 0 ) setVehicleLightState( veh, 1, 1 ) setVehicleLightState( veh, 2, 1 ) setVehicleLightState( veh, 3, 0 ) if getVehicleTowedByVehicle( veh ) then local veh2 = getVehicleTowedByVehicle( veh ) if veh2 then setVehicleLightState( veh2, 0, 0 ) setVehicleLightState( veh2, 1, 1 ) setVehicleLightState( veh2, 2, 1 ) setVehicleLightState( veh2, 3, 0 ) end end elseif dtype[veh] == "lright" then setVehicleLightState( veh, 0, 1 ) setVehicleLightState( veh, 1, 0 ) setVehicleLightState( veh, 2, 0 ) setVehicleLightState( veh, 3, 1 ) if getVehicleTowedByVehicle( veh ) then local veh2 = getVehicleTowedByVehicle( veh ) if veh2 then setVehicleLightState( veh2, 0, 1 ) setVehicleLightState( veh2, 1, 0 ) setVehicleLightState( veh2, 2, 0 ) setVehicleLightState( veh2, 3, 1 ) end end elseif dtype[veh] == "warn" then setVehicleLightState( veh, 0, 0 ) setVehicleLightState( veh, 1, 0 ) setVehicleLightState( veh, 2, 0 ) setVehicleLightState( veh, 3, 0 ) if getVehicleTowedByVehicle( veh ) then local veh2 = getVehicleTowedByVehicle( veh ) if veh2 then setVehicleLightState( veh2, 0, 0 ) setVehicleLightState( veh2, 1, 0 ) setVehicleLightState( veh2, 2, 0 ) setVehicleLightState( veh2, 3, 0 ) end end end toggler[veh] = 1 end end end -- Left function lightHandler( player, cmd ) if player and isElement( player ) and getPedOccupiedVehicle( player ) then local veh = getPedOccupiedVehicle( player ) if ( not isTimer( syncTimer[veh] ) or cmd ~= dtype[veh] ) and getVehicleOccupants(veh)[0] == player then -- Save the current head light color setVehicleLightState( veh, 0, 1 ) setVehicleLightState( veh, 1, 1 ) setVehicleLightState( veh, 2, 1 ) setVehicleLightState( veh, 3, 1 ) if getVehicleTowedByVehicle( veh ) then local veh2 = getVehicleTowedByVehicle( veh ) if veh2 then setVehicleLightState( veh2, 0, 1 ) setVehicleLightState( veh2, 1, 1 ) setVehicleLightState( veh2, 2, 1 ) setVehicleLightState( veh2, 3, 1 ) end end if not currHeadLightColor[veh] then currHeadLightColor[veh] = { } currHeadLightColor[veh][1],currHeadLightColor[veh][2],currHeadLightColor[veh][3] = getVehicleHeadLightColor( veh ) end -- Set the new headlight color to yellow setVehicleHeadLightColor( veh, 255, 200, 0 ) -- Start the syn timer if isTimer( syncTimer[veh] ) then killTimer( syncTimer[veh] ) end syncTimer[veh] = setTimer( toggleLights, 380, 0, veh ) toggler[veh] = 1 dtype[veh] = cmd toggleLights( veh ) else if isTimer( syncTimer[veh] ) then killTimer( syncTimer[veh] ) setVehicleHeadLightColor( veh, currHeadLightColor[veh][1],currHeadLightColor[veh][2],currHeadLightColor[veh][3] ) currHeadLightColor[veh][1] = nil currHeadLightColor[veh][2] = nil currHeadLightColor[veh][3] = nil currHeadLightColor[veh] = nil end startLights(veh) end end end addCommandHandler( "lleft", lightHandler ) addCommandHandler( "lright", lightHandler ) addCommandHandler( "warn", lightHandler ) --[[ Turn on all lights ]]-- function startLights(veh) if not veh or not isElement(veh) then return end setVehicleLightState( veh, 0, 0 ) setVehicleLightState( veh, 1, 0 ) setVehicleLightState( veh, 2, 0 ) setVehicleLightState( veh, 3, 0 ) setVehicleOverrideLights( veh, 2 ) if getVehicleTowedByVehicle( veh ) then local veh2 = getVehicleTowedByVehicle( veh ) if veh2 then setVehicleLightState( veh2, 0, 0 ) setVehicleLightState( veh2, 1, 0 ) setVehicleLightState( veh2, 2, 0 ) setVehicleLightState( veh2, 3, 0 ) setVehicleOverrideLights( veh2, 2 ) end end end --[[ Attempt's to cleanup tables 2014-12-11 ]]-- function cleanUp(plr, seat, jacked, door) if (door or 0) > 0 then return end if isTimer(syncTimer[source]) then killTimer(syncTimer[source]) end syncTimer[source] = nil toggler[source] = nil dtype[source] = nil -- Reset color if currHeadLightColor[source] and currHeadLightColor[source][1] and currHeadLightColor[source][2] and currHeadLightColor[source][3] then setVehicleHeadLightColor( source, currHeadLightColor[source][1],currHeadLightColor[source][2],currHeadLightColor[source][3] ) currHeadLightColor[source][1] = nil currHeadLightColor[source][2] = nil currHeadLightColor[source][3] = nil currHeadLightColor[source] = nil end -- Reset light state startLights(veh) end addEventHandler("onVehicleStartExit", root, cleanUp)
Bugfix to turnsignals
Bugfix to turnsignals The bug appears to be related to the keybind, this update should make the lights work again.
Lua
bsd-2-clause
404rq/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG,404rq/GTW-RPG,SpRoXx/GTW-RPG,SpRoXx/GTW-RPG,GTWCode/GTW-RPG,GTWCode/GTW-RPG
4d2496d5b87a128e78f33177d523983f6e9a66c6
SpatialBatchNormalization.lua
SpatialBatchNormalization.lua
--[[ This file implements Batch Normalization as described in the paper: "Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift" by Sergey Ioffe, Christian Szegedy This implementation is useful for inputs coming from convolution layers. For Non-convolutional layers, see BatchNormalization.lua The operation implemented is: y = ( x - mean(x) ) -------------------- * gamma + beta standard-deviation(x) where gamma and beta are learnable parameters. The learning of gamma and beta is optional. Usage: with learnable parameters: nn.BatchNormalization(N [,eps] [,momentum]) where N = dimensionality of input without learnable parameters: nn.BatchNormalization(N [,eps] [,momentum], false) eps is a small value added to the variance to avoid divide-by-zero. Defaults to 1e-5 In training time, this layer keeps a running estimate of it's computed mean and std. The running sum is kept with a default momentup of 0.1 (unless over-ridden) In test time, this running mean/std is used to normalize. ]]-- local BN,parent = torch.class('nn.SpatialBatchNormalization', 'nn.Module') BN.__version = 2 function BN:__init(nFeature, eps, momentum, affine) parent.__init(self) assert(nFeature and type(nFeature) == 'number', 'Missing argument #1: Number of feature planes. ') assert(nFeature ~= 0, 'To set affine=false call SpatialBatchNormalization' .. '(nFeature, eps, momentum, false) ') if affine ~= nil then assert(type(affine) == 'boolean', 'affine has to be true/false') self.affine = affine else self.affine = true end self.eps = eps or 1e-5 self.train = true self.momentum = momentum or 0.1 self.running_mean = torch.zeros(nFeature) self.running_var = torch.ones(nFeature) if self.affine then self.weight = torch.Tensor(nFeature) self.bias = torch.Tensor(nFeature) self.gradWeight = torch.Tensor(nFeature) self.gradBias = torch.Tensor(nFeature) self:reset() end end function BN:reset() if self.weight then self.weight:uniform() end if self.bias then self.bias:zero() end self.running_mean:zero() self.running_var:fill(1) end function BN:updateOutput(input) assert(input:dim() == 4, 'only mini-batch supported (4D tensor), got ' .. input:dim() .. 'D tensor instead') self.output:resizeAs(input) self.save_mean = self.save_mean or input.new():resizeAs(self.running_mean) self.save_std = self.save_std or input.new():resizeAs(self.running_var) input.nn.SpatialBatchNormalization_updateOutput( input, self.output, self.weight, self.bias, self.train, self.eps, self.momentum, self.running_mean, self.running_var, self.save_mean, self.save_std) return self.output end local function backward(self, input, gradOutput, scale, gradInput, gradWeight, gradBias) assert(input:dim() == 4, 'only mini-batch supported') assert(gradOutput:dim() == 4, 'only mini-batch supported') assert(self.train == true, 'should be in training mode when self.train is true') assert(self.save_mean and self.save_std, 'must call :updateOutput() first') scale = scale or 1 if gradInput then gradInput:resizeAs(gradOutput) end input.nn.SpatialBatchNormalization_backward( input, gradOutput, gradInput, gradWeight, gradBias, self.weight, self.save_mean, self.save_std, scale) return self.gradInput end function BN:backward(input, gradOutput, scale) return backward(self, input, gradOutput, scale, self.gradInput, self.gradWeight, self.gradBias) end function BN:updateGradInput(input, gradOutput) return backward(self, input, gradOutput, 1, self.gradInput) end function BN:accGradParameters(input, gradOutput, scale) return backward(self, input, gradOutput, scale, nil, self.gradWeight, self.gradBias) end function BN:read(file, version) local var = file:readObject() for k,v in pairs(var) do if version < 2 and k == 'running_std' then k = 'running_var' v = v:cmul(v):pow(-1) end self[k] = v end end
--[[ This file implements Batch Normalization as described in the paper: "Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift" by Sergey Ioffe, Christian Szegedy This implementation is useful for inputs coming from convolution layers. For Non-convolutional layers, see BatchNormalization.lua The operation implemented is: y = ( x - mean(x) ) -------------------- * gamma + beta standard-deviation(x) where gamma and beta are learnable parameters. The learning of gamma and beta is optional. Usage: with learnable parameters: nn.BatchNormalization(N [,eps] [,momentum]) where N = dimensionality of input without learnable parameters: nn.BatchNormalization(N [,eps] [,momentum], false) eps is a small value added to the variance to avoid divide-by-zero. Defaults to 1e-5 In training time, this layer keeps a running estimate of it's computed mean and std. The running sum is kept with a default momentup of 0.1 (unless over-ridden) In test time, this running mean/std is used to normalize. ]]-- local BN,parent = torch.class('nn.SpatialBatchNormalization', 'nn.Module') BN.__version = 2 function BN:__init(nFeature, eps, momentum, affine) parent.__init(self) assert(nFeature and type(nFeature) == 'number', 'Missing argument #1: Number of feature planes. ') assert(nFeature ~= 0, 'To set affine=false call SpatialBatchNormalization' .. '(nFeature, eps, momentum, false) ') if affine ~= nil then assert(type(affine) == 'boolean', 'affine has to be true/false') self.affine = affine else self.affine = true end self.eps = eps or 1e-5 self.train = true self.momentum = momentum or 0.1 self.running_mean = torch.zeros(nFeature) self.running_var = torch.ones(nFeature) if self.affine then self.weight = torch.Tensor(nFeature) self.bias = torch.Tensor(nFeature) self.gradWeight = torch.Tensor(nFeature) self.gradBias = torch.Tensor(nFeature) self:reset() end end function BN:reset() if self.weight then self.weight:uniform() end if self.bias then self.bias:zero() end self.running_mean:zero() self.running_var:fill(1) end function BN:updateOutput(input) assert(input:dim() == 4, 'only mini-batch supported (4D tensor), got ' .. input:dim() .. 'D tensor instead') self.output:resizeAs(input) self.save_mean = self.save_mean or input.new():resizeAs(self.running_mean) self.save_std = self.save_std or input.new():resizeAs(self.running_var) input.nn.SpatialBatchNormalization_updateOutput( input, self.output, self.weight, self.bias, self.train, self.eps, self.momentum, self.running_mean, self.running_var, self.save_mean, self.save_std) return self.output end local function backward(self, input, gradOutput, scale, gradInput, gradWeight, gradBias) assert(input:dim() == 4, 'only mini-batch supported') assert(gradOutput:dim() == 4, 'only mini-batch supported') assert(self.train == true, 'should be in training mode when self.train is true') assert(self.save_mean and self.save_std, 'must call :updateOutput() first') scale = scale or 1 if gradInput then gradInput:resizeAs(gradOutput) end input.nn.SpatialBatchNormalization_backward( input, gradOutput, gradInput, gradWeight, gradBias, self.weight, self.save_mean, self.save_std, scale) return self.gradInput end function BN:backward(input, gradOutput, scale) return backward(self, input, gradOutput, scale, self.gradInput, self.gradWeight, self.gradBias) end function BN:updateGradInput(input, gradOutput) return backward(self, input, gradOutput, 1, self.gradInput) end function BN:accGradParameters(input, gradOutput, scale) return backward(self, input, gradOutput, scale, nil, self.gradWeight, self.gradBias) end function BN:read(file, version) parent.read(self, file) if version < 2 then if self.running_std then self.running_var = self.running_std:pow(-2):add(-self.eps) self.running_std = nil end end end
Fix loading of old SpatialBatchNormalization modules
Fix loading of old SpatialBatchNormalization modules The old-style running_std is actually the E[1/sqrt(var + eps)]. I forgot to subtract out the 'eps' when converting to running_var.
Lua
bsd-3-clause
apaszke/nn,andreaskoepf/nn,kmul00/nn,elbamos/nn,jhjin/nn,joeyhng/nn,diz-vara/nn,eriche2016/nn,nicholas-leonard/nn,jonathantompson/nn,PraveerSINGH/nn,xianjiec/nn,sagarwaghmare69/nn,caldweln/nn,colesbury/nn
0571b964cacad8a07c71d2cafc6e5f034fb25f1a
BIOS/init.lua
BIOS/init.lua
--The BIOS should control the system of LIKO-12 and load the peripherals-- --For now it's just a simple BIOS to get LIKO-12 working. --Require the engine libraries-- local events = require("Engine.events") local coreg = require("Engine.coreg") local function splitFilePath(path) return path:match("(.-)([^\\/]-%.?([^%.\\/]*))$") end --A function to split path to path, name, extension. local Peripherals = {} --The loaded peripherals. local MPer = {} --Mounted and initialized peripherals. --A function to load the peripherals. local function indexPeripherals(path) local files = love.filesystem.getDirectoryItems(path) for k,filename in ipairs(files) do if love.filesystem.isDirectory(path..filename) then indexPeripherals(path..filename.."/") else local p, n, e = splitFilePath(path..filename) if e == "lua" then local chunk, err = love.filesystem.load(path..n) if not chunk then Peripherals[n:sub(0,-5)] = "Err: "..tostring(err) else Peripherals[n:sub(0,-5)] = chunk() end end end end end indexPeripherals("/Peripherals/") --Index and Load the peripherals --Peripheral, Err = P(PeriheralName, MountedName, ConfigTabel) local function P(per,m,conf) if not per then return false, "Should provide peripheral name" end if type(per) ~= "string" then return false, "Peripheral name should be a string, provided "..type(per) end if not Peripherals[per] then return false, "'"..per.."' Peripheral doesn't exists" end if type(Peripherals[per]) == "string" then return false, "Compile "..Peripherals[per] end local m = m or per if type(m) ~= "string" then return false, "Mounting name should be a string, provided "..type(m) end if MPer[m] then return false, "Mounting name '"..m.."' is already taken" end local conf = conf or {} if type(conf) ~= "table" then return false, "Configuration table should be a table, provided "..type(conf) end local success, peripheral = pcall(Peripherals[per],conf) if success then MPer[m] = peripheral coreg:register(peripheral,m) else peripheral = "Init Err: "..peripheral end return success, peripheral end if not love.filesystem.exists("/bconf.lua") or true then love.filesystem.write("/bconf.lua",love.filesystem.read("/BIOS/bconf.lua")) end local bconfC, bconfErr, bconfDErr = love.filesystem.load("/bconf.lua") if not bconfC then bconfC, bconfDErr = love.filesystem.load("/BIOS/bconf.lua") end --Load the default BConfig if not bconfC then error(bconfDErr) end setfenv(bconfC,{P = P,error=error,assert=assert}) --BConfig sandboxing local success, bconfRErr = pcall(bconfC) if not success then bconfC, err = love.filesystem.load("/BIOS/bconf.lua") if not bconfC then error(err) end setfenv(bconfC,{P = P,error=error,assert=assert}) --BConfig sandboxing bconfC() end --Load the default BConfig coreg:register(function() local list = {} for per, funcs in pairs(MPer) do list[per] = {} for name, func in pairs(funcs) do table.insert(list[per],name) end end return true, list end,"BIOS:listPeripherals") local function exe(...) --Excute a LIKO12 api function (to handle errors) local args = {...} if args[1] then local nargs = {} for k,v in ipairs(args) do --Clone the args, removing the first one nargs[k-1] = v end return unpack(nargs) else return error(args[2]) end end local function flushOS(os,path) local h = MPer.HDD local path = path or "/" local files = love.filesystem.getDirectoryItems("/OS/"..os..path) for k,v in pairs(files) do if love.filesystem.isDirectory("/OS/"..os..path..v) then flushOS(os,path..v.."/") else exe(h.drive("C")) --Opereating systems are installed on C drive exe(h.write(path..v,love.filesystem.read("/OS/"..os..path..v))) end end end --No OS Screen local function noOS() if MPer.GPU then flushOS("CartOS") --Should be replaced by a gui else flushOS("CartOS") end end local function startCoroutine() if not MPer.HDD then return error("No HDD Periphrtal") end local h = MPer.HDD exe(h.drive("C")) if (not exe(h.exists("/boot.lua"))) or true then noOS() end local chunk, err = exe(h.load("/boot.lua")) if not chunk then error(err or "") end coreg:sandboxCoroutine(chunk) local co = coroutine.create(chunk) coreg:setCoroutine(co) --For peripherals to use. coreg:resumeCoroutine() end --POST screen if MPer.GPU then --If there is an initialized gpu local g = MPer.GPU g.color(8) local chars = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","-","_","@","#","$","&","*","!","+","=","%"} --48x16 Terminal Size function drawAnim() g.clear() for x=1,48 do for y=1,16 do math.randomseed(os.clock()*os.time()*x) g.color(math.floor(math.random(2,16))) g.printCursor(x,y) math.randomseed(os.clock()*os.time()*y) local c = chars[math.floor(math.random(1,#chars))] if math.random(0,20) % 2 == 0 then c = c:upper() end g.print(c) end end end g.clear() local timer = 0 local stage = 1 events:register("love:update",function(dt) if stage == 7 then --Create the coroutine g.color(8) g.clear(1) g.printCursor(1,1) startCoroutine() stage = 8 --So coroutine don't get duplicated end if stage < 4 and stage > 1 then drawAnim() end if stage < 8 then timer = timer + dt if timer > 0.25 then timer = timer -0.25 stage = stage +1 if stage < 5 then --[[drawAnim()]] elseif stage == 5 then g.clear() end end end end) else --Incase the gpu doesn't exists (Then can't enter the bios nor do the boot animation startCoroutine() end --[[local GPU = Peripherals.GPU({_ClearOnRender=true}) --Create a new GPU --FPS display events:register("love:update",function(dt) love.window.setTitle("LIKO-12 FPS: "..love.timer.getFPS()) end) --Debug Draw-- GPU.points(1,1, 192,1, 192,128, 1,128, 8) GPU.points(0,1, 193,1, 193,128, 0,128, 3) GPU.points(1,0, 192,0, 192,129, 1,129, 3) GPU.rect(2,2, 190,126, true, 12) GPU.line(2,2,191,2,191,127,2,127,2,2,12) GPU.line(2,2, 191,127, 9) GPU.line(191, 2,2,127, 9) GPU.rect(10,42,10,10,false,9) GPU.rect(10,30,10,10,false,9) GPU.rect(10,30,10,10,true,8) GPU.points(10,10, 10,19, 19,19, 19,10, 8)]]
--The BIOS should control the system of LIKO-12 and load the peripherals-- --For now it's just a simple BIOS to get LIKO-12 working. --Require the engine libraries-- local events = require("Engine.events") local coreg = require("Engine.coreg") local function splitFilePath(path) return path:match("(.-)([^\\/]-%.?([^%.\\/]*))$") end --A function to split path to path, name, extension. local Peripherals = {} --The loaded peripherals. local MPer = {} --Mounted and initialized peripherals. --A function to load the peripherals. local function indexPeripherals(path) local files = love.filesystem.getDirectoryItems(path) for k,filename in ipairs(files) do if love.filesystem.isDirectory(path..filename) then indexPeripherals(path..filename.."/") else local p, n, e = splitFilePath(path..filename) if e == "lua" then local chunk, err = love.filesystem.load(path..n) if not chunk then Peripherals[n:sub(0,-5)] = "Err: "..tostring(err) else Peripherals[n:sub(0,-5)] = chunk() end end end end end indexPeripherals("/Peripherals/") --Index and Load the peripherals --Peripheral, Err = P(PeriheralName, MountedName, ConfigTabel) local function P(per,m,conf) if not per then return false, "Should provide peripheral name" end if type(per) ~= "string" then return false, "Peripheral name should be a string, provided "..type(per) end if not Peripherals[per] then return false, "'"..per.."' Peripheral doesn't exists" end if type(Peripherals[per]) == "string" then return false, "Compile "..Peripherals[per] end local m = m or per if type(m) ~= "string" then return false, "Mounting name should be a string, provided "..type(m) end if MPer[m] then return MPer[m] end--return false, "Mounting name '"..m.."' is already taken" end local conf = conf or {} if type(conf) ~= "table" then return false, "Configuration table should be a table, provided "..type(conf) end local success, peripheral = pcall(Peripherals[per],conf) if success then MPer[m] = peripheral coreg:register(peripheral,m) else peripheral = "Init Err: "..peripheral end return success, peripheral end if not love.filesystem.exists("/bconf.lua") or true then love.filesystem.write("/bconf.lua",love.filesystem.read("/BIOS/bconf.lua")) end local bconfC, bconfErr, bconfDErr = love.filesystem.load("/bconf.lua") if not bconfC then bconfC, bconfDErr = love.filesystem.load("/BIOS/bconf.lua") end --Load the default BConfig if not bconfC then error(bconfDErr) end setfenv(bconfC,{P = P,error=error,assert=assert}) --BConfig sandboxing local success, bconfRErr = pcall(bconfC) if not success then bconfC, err = love.filesystem.load("/BIOS/bconf.lua") if not bconfC then error(err) end setfenv(bconfC,{P = P,error=error,assert=assert}) --BConfig sandboxing bconfC() end --Load the default BConfig coreg:register(function() local list = {} for per, funcs in pairs(MPer) do list[per] = {} for name, func in pairs(funcs) do table.insert(list[per],name) end end return true, list end,"BIOS:listPeripherals") local function exe(...) --Excute a LIKO12 api function (to handle errors) local args = {...} if args[1] then local nargs = {} for k,v in ipairs(args) do --Clone the args, removing the first one nargs[k-1] = v end return unpack(nargs) else return error(args[2]) end end local function flushOS(os,path) local h = MPer.HDD local path = path or "/" local files = love.filesystem.getDirectoryItems("/OS/"..os..path) for k,v in pairs(files) do if love.filesystem.isDirectory("/OS/"..os..path..v) then flushOS(os,path..v.."/") else exe(h.drive("C")) --Opereating systems are installed on C drive exe(h.write(path..v,love.filesystem.read("/OS/"..os..path..v))) end end end --No OS Screen local function noOS() if MPer.GPU then flushOS("CartOS") --Should be replaced by a gui else flushOS("CartOS") end end local function startCoroutine() if not MPer.HDD then return error("No HDD Periphrtal") end local h = MPer.HDD exe(h.drive("C")) if (not exe(h.exists("/boot.lua"))) or true then noOS() end local chunk, err = exe(h.load("/boot.lua")) if not chunk then error(err or "") end coreg:sandboxCoroutine(chunk) local co = coroutine.create(chunk) coreg:setCoroutine(co) --For peripherals to use. coreg:resumeCoroutine() end --POST screen if MPer.GPU then --If there is an initialized gpu local g = MPer.GPU g.color(8) local chars = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","-","_","@","#","$","&","*","!","+","=","%"} --48x16 Terminal Size function drawAnim() g.clear() for x=1,exe(g.termwidth()) do for y=1,exe(g.termheight()) do math.randomseed(os.clock()*os.time()*x) g.color(math.floor(math.random(2,16))) g.printCursor(x,y) math.randomseed(os.clock()*os.time()*y) local c = chars[math.floor(math.random(1,#chars))] if math.random(0,20) % 2 == 0 then c = c:upper() end g.print(c) end end end g.clear() local timer = 0 local stage = 1 events:register("love:update",function(dt) if stage == 7 then --Create the coroutine g.color(8) g.clear(1) g.printCursor(1,1) startCoroutine() stage = 8 --So coroutine don't get duplicated end if stage < 4 and stage > 1 then drawAnim() end if stage < 8 then timer = timer + dt if timer > 0.25 then timer = timer -0.25 stage = stage +1 if stage < 5 then --[[drawAnim()]] elseif stage == 5 then g.clear() end end end end) else --Incase the gpu doesn't exists (Then can't enter the bios nor do the boot animation startCoroutine() end --[[local GPU = Peripherals.GPU({_ClearOnRender=true}) --Create a new GPU --FPS display events:register("love:update",function(dt) love.window.setTitle("LIKO-12 FPS: "..love.timer.getFPS()) end) --Debug Draw-- GPU.points(1,1, 192,1, 192,128, 1,128, 8) GPU.points(0,1, 193,1, 193,128, 0,128, 3) GPU.points(1,0, 192,0, 192,129, 1,129, 3) GPU.rect(2,2, 190,126, true, 12) GPU.line(2,2,191,2,191,127,2,127,2,2,12) GPU.line(2,2, 191,127, 9) GPU.line(191, 2,2,127, 9) GPU.rect(10,42,10,10,false,9) GPU.rect(10,30,10,10,false,9) GPU.rect(10,30,10,10,true,8) GPU.points(10,10, 10,19, 19,19, 19,10, 8)]]
Bugfix
Bugfix
Lua
mit
RamiLego4Game/LIKO-12
a1224f33a6826077e89555428b5cc763afbe4415
src/api.lua
src/api.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 --]] zpm.api = {} function zpm.uses(libraries) local found = true if type(libraries) ~= "table" then libraries = {libraries} end for _, library in ipairs(libraries) do local package, access = zpm.loader.project.builder:build(library, "libraries") --print(zpm.meta.project, library, package, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") zpm.util.setTable(zpm.loader.project.builder.cursor, {"projects", zpm.meta.project, "uses", library}, { package = package } ) found = found and package end return found end function zpm.has(library) for _, access in ipairs({"public", "private"}) do if zpm.loader.project.builder.cursor[access] and zpm.loader.project.builder.cursor[access]["libraries"] then for _, pkg in ipairs(zpm.loader.project.builder.cursor[access]["libraries"]) do if pkg.name == library then return true end end end end return zpm.loader.project.builder.solution.tree.closed.public["libraries"][library] end function zpm.export(commands) local cursor = zpm.loader.project.builder.cursor local index = {"projects", zpm.meta.project, "exportFunctions"} local func = function() zpm.loader.project.from = cursor --print(commands) zpm.sandbox.run(commands, {env = zpm.loader.project.builder:getEnv("libraries", cursor)}) zpm.loader.project.from = nil end zpm.util.insertTable(zpm.loader.project.builder.cursor, index, func) local fltr = table.deepcopy(zpm.meta.filter) filter {} zpm.sandbox.run(commands, {env = zpm.loader.project.builder:getEnv("libraries")}) filter(fltr) end function zpm.setting(setting) local cursor = iif(zpm.loader.project.from, zpm.loader.project.from, zpm.loader.project.cursor) local tab = zpm.loader.settings({cursor.package.manifest.name, cursor.name, cursor.tag, setting}) if not tab then warningf("Setting '%s' does not exist on package '%s'", setting, zpm.loader.project.cursor.name) return nil end local values = tab.values if not values then return tab.default end values = zpm.util.reverse(values) if tab.reduce then if zpm.settings.reduce[tab.reduce] then zpm.settings.reduce[tab.reduce](values) else -- @todo end end return values end function zpm.configuration(setting, default) local config = zpm.loader.config({"configuration", setting}) return iif(config, config, default) end
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- -- @endcond --]] zpm.api = {} function zpm.uses(libraries) local found = true if type(libraries) ~= "table" then libraries = {libraries} end for _, library in ipairs(libraries) do local package, access = zpm.loader.project.builder:build(library, "libraries") --print(zpm.meta.project, library, package, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") zpm.util.setTable(zpm.loader.project.builder.cursor, {"projects", zpm.meta.project, "uses", library}, { package = package } ) found = found and package end return found end function zpm.has(library, tpe) tpe = iif(tpe, tpe, "libraries") for _, access in ipairs({"public", "private"}) do if zpm.loader.project.builder.cursor[access] and zpm.loader.project.builder.cursor[access][tpe] then for _, pkg in ipairs(zpm.loader.project.builder.cursor[access][tpe]) do if pkg.name == library then return true end end end end return zpm.loader.project.builder.solution.tree.closed.public[tpe][library] end function zpm.export(commands) local cursor = zpm.loader.project.builder.cursor local index = {"projects", zpm.meta.project, "exportFunctions"} local func = function() zpm.loader.project.from = cursor --print(commands) zpm.sandbox.run(commands, {env = zpm.loader.project.builder:getEnv("libraries", cursor)}) zpm.loader.project.from = nil end zpm.util.insertTable(zpm.loader.project.builder.cursor, index, func) local fltr = table.deepcopy(zpm.meta.filter) filter {} zpm.sandbox.run(commands, {env = zpm.loader.project.builder:getEnv("libraries")}) filter(fltr) end function zpm.setting(setting) local cursor = iif(zpm.loader.project.from, zpm.loader.project.from, zpm.loader.project.cursor) local tab = zpm.loader.settings({cursor.package.manifest.name, cursor.name, cursor.tag, setting}) if not tab then warningf("Setting '%s' does not exist on package '%s'", setting, zpm.loader.project.cursor.name) return nil end local values = tab.values if not values then return tab.default end values = zpm.util.reverse(values) if tab.reduce then if zpm.settings.reduce[tab.reduce] then zpm.settings.reduce[tab.reduce](values) else -- @todo end end return values end function zpm.configuration(setting, default) local config = zpm.loader.config({"configuration", setting}) return iif(config, config, default) end
Fix typing
Fix typing
Lua
mit
Zefiros-Software/ZPM
e168b1d79d29ee55bb8fd41d8e568cae6e719df9
libs/httpd/luasrc/httpd/handler/luci.lua
libs/httpd/luasrc/httpd/handler/luci.lua
--[[ HTTP server implementation for LuCI - luci handler (c) 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.httpd.handler.luci", package.seeall) require("luci.dispatcher") require("luci.http") require("luci.http.protocol.date") require("ltn12") Luci = luci.util.class(luci.httpd.module.Handler) Response = luci.httpd.module.Response function Luci.__init__(self) luci.httpd.module.Handler.__init__(self) end function Luci.handle_head(self, ...) local response, sourceout = self:handle_get(...) return response end function Luci.handle_post(self, ...) return self:handle_get(...) end function Luci.handle_get(self, request, sourcein, sinkerr) local r = luci.http.Request( request.env, sourcein, sinkerr ) local res, id, data1, data2 = true, 0, nil, nil local headers = {} local status = 200 local x = coroutine.create(luci.dispatcher.httpdispatch) while not id or id < 3 do coroutine.yield() res, id, data1, data2 = coroutine.resume(x, r) if not res then status = 500 headers["Content-Type"] = "text/plain" local err = {id} return Response( status, headers ), function() return table.remove(err) end end if id == 1 then status = data1 elseif id == 2 then headers[data1] = data2 end end <<<<<<< HEAD:libs/httpd/luasrc/httpd/handler/luci.lua ======= >>>>>>> * libs/httpd: Added Cache-Control header to LuCI:libs/httpd/luasrc/httpd/handler/luci.lua local function iter() local res, id, data = coroutine.resume(x) if not res then return nil, id elseif not id then return true elseif id == 5 then return nil else return data end end headers["Expires"] = luci.http.protocol.date.to_http( os.time() ) headers["Date"] = headers["Expires"] headers["Cache-Control"] = "no-cache" return Response(status, headers), iter end
--[[ HTTP server implementation for LuCI - luci handler (c) 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.httpd.handler.luci", package.seeall) require("luci.dispatcher") require("luci.http") require("luci.http.protocol.date") require("ltn12") Luci = luci.util.class(luci.httpd.module.Handler) Response = luci.httpd.module.Response function Luci.__init__(self) luci.httpd.module.Handler.__init__(self) end function Luci.handle_head(self, ...) local response, sourceout = self:handle_get(...) return response end function Luci.handle_post(self, ...) return self:handle_get(...) end function Luci.handle_get(self, request, sourcein, sinkerr) local r = luci.http.Request( request.env, sourcein, sinkerr ) local res, id, data1, data2 = true, 0, nil, nil local headers = {} local status = 200 local x = coroutine.create(luci.dispatcher.httpdispatch) while not id or id < 3 do coroutine.yield() res, id, data1, data2 = coroutine.resume(x, r) if not res then status = 500 headers["Content-Type"] = "text/plain" local err = {id} return Response( status, headers ), function() return table.remove(err) end end if id == 1 then status = data1 elseif id == 2 then headers[data1] = data2 end end local function iter() local res, id, data = coroutine.resume(x) if not res then return nil, id elseif not id then return true elseif id == 5 then return nil else return data end end headers["Expires"] = luci.http.protocol.date.to_http( os.time() ) headers["Date"] = headers["Expires"] headers["Cache-Control"] = "no-cache" return Response(status, headers), iter end
* Fixed last commit
* Fixed last commit
Lua
apache-2.0
deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci
da11851284a7015d2890d24dbff34aa1db5b8aec
src/plugins/core/console/scripts.lua
src/plugins/core/console/scripts.lua
--- === plugins.core.console.scripts === --- --- Adds all installed AppleScripts to the Search Console. local require = require local hs = _G.hs local log = require "hs.logger".new "applications" local image = require "hs.image" local fs = require "hs.fs" local config = require "cp.config" local spotlight = require "hs.spotlight" local displayName = fs.displayName local execute = hs.execute local imageFromPath = image.imageFromPath local mod = {} mod.appCache = {} local function modifyNameMap(info, add) for _, item in ipairs(info) do local displayname = item.kMDItemDisplayName or displayName(item.kMDItemPath) -------------------------------------------------------------------------------- -- Add to the cache: -------------------------------------------------------------------------------- if add then -------------------------------------------------------------------------------- -- AppleScript Icon: -------------------------------------------------------------------------------- local icon = imageFromPath(config.bundledPluginsPath .. "/core/console/images/SEScriptDocument.icns") -------------------------------------------------------------------------------- -- Add application to cache: -------------------------------------------------------------------------------- mod.appCache[displayname] = { path = item.kMDItemPath, icon = icon } -------------------------------------------------------------------------------- -- Remove from the cache: -------------------------------------------------------------------------------- else mod.appCache[displayname] = nil end end mod._handler:reset() end local function updateNameMap(_, msg, info) if info then -------------------------------------------------------------------------------- -- All three can occur in either message, so check them all: -------------------------------------------------------------------------------- if info.kMDQueryUpdateAddedItems then modifyNameMap(info.kMDQueryUpdateAddedItems, true) end if info.kMDQueryUpdateChangedItems then modifyNameMap(info.kMDQueryUpdateChangedItems, true) end if info.kMDQueryUpdateRemovedItems then modifyNameMap(info.kMDQueryUpdateRemovedItems, false) end else -------------------------------------------------------------------------------- -- This shouldn't happen for didUpdate or inProgress: -------------------------------------------------------------------------------- log.df("userInfo from SpotLight was empty for " .. msg) end end function mod.startSpotlightSearch() local searchPaths = { "/Applications", "/System/Applications", "~/Applications", "/Developer/Applications", "/Applications/Xcode.app/Contents/Applications", "/System/Library/PreferencePanes", "/Library/PreferencePanes", "~/Library/PreferencePanes", "/System/Library/CoreServices/Applications", "/System/Library/CoreServices/", "/usr/local/Cellar", "/Library/Scripts", "~/Library/Scripts" } mod.spotlight = spotlight.new():queryString([[ (kMDItemContentType = "com.apple.applescript.text") || (kMDItemContentType = "com.apple.applescript.script") ]]) :callbackMessages("didUpdate", "inProgress") :setCallback(updateNameMap) :searchScopes(searchPaths) :start() end local plugin = { id = "core.console.scripts", group = "core", dependencies = { ["core.action.manager"] = "actionmanager", } } function plugin.init(deps) -------------------------------------------------------------------------------- -- Start Spotlight Search: -------------------------------------------------------------------------------- mod.startSpotlightSearch() -------------------------------------------------------------------------------- -- Setup Handler: -------------------------------------------------------------------------------- mod._handler = deps.actionmanager.addHandler("global_scripts", "global") :onChoices(function(choices) for name, app in pairs(mod.appCache) do choices:add(name) :subText(app["path"]) :params({ ["path"] = app["path"], }) :image(app["icon"]) :id("global_applications_" .. name) end end) :onExecute(function(action) execute(string.format("/usr/bin/osascript '%s'", action["path"])) end) :onActionId(function() return "global_scripts" end) return mod end return plugin
--- === plugins.core.console.scripts === --- --- Adds all installed AppleScripts to the Search Console. local require = require local hs = _G.hs local log = require "hs.logger".new "applications" local image = require "hs.image" local fs = require "hs.fs" local config = require "cp.config" local spotlight = require "hs.spotlight" local displayName = fs.displayName local execute = hs.execute local imageFromPath = image.imageFromPath local mod = {} mod.appCache = {} local function modifyNameMap(info, add) for _, item in ipairs(info) do local path = item and item.kMDItemPath if path then local displayname = item.kMDItemDisplayName or displayName(path) -------------------------------------------------------------------------------- -- Add to the cache: -------------------------------------------------------------------------------- if add then -------------------------------------------------------------------------------- -- AppleScript Icon: -------------------------------------------------------------------------------- local icon = imageFromPath(config.bundledPluginsPath .. "/core/console/images/SEScriptDocument.icns") -------------------------------------------------------------------------------- -- Add application to cache: -------------------------------------------------------------------------------- mod.appCache[displayname] = { path = path, icon = icon } -------------------------------------------------------------------------------- -- Remove from the cache: -------------------------------------------------------------------------------- else mod.appCache[displayname] = nil end end end mod._handler:reset() end local function updateNameMap(_, msg, info) if info then -------------------------------------------------------------------------------- -- All three can occur in either message, so check them all: -------------------------------------------------------------------------------- if info.kMDQueryUpdateAddedItems then modifyNameMap(info.kMDQueryUpdateAddedItems, true) end if info.kMDQueryUpdateChangedItems then modifyNameMap(info.kMDQueryUpdateChangedItems, true) end if info.kMDQueryUpdateRemovedItems then modifyNameMap(info.kMDQueryUpdateRemovedItems, false) end else -------------------------------------------------------------------------------- -- This shouldn't happen for didUpdate or inProgress: -------------------------------------------------------------------------------- log.df("userInfo from SpotLight was empty for " .. msg) end end function mod.startSpotlightSearch() local searchPaths = { "/Applications", "/System/Applications", "~/Applications", "/Developer/Applications", "/Applications/Xcode.app/Contents/Applications", "/System/Library/PreferencePanes", "/Library/PreferencePanes", "~/Library/PreferencePanes", "/System/Library/CoreServices/Applications", "/System/Library/CoreServices/", "/usr/local/Cellar", "/Library/Scripts", "~/Library/Scripts" } mod.spotlight = spotlight.new():queryString([[ (kMDItemContentType = "com.apple.applescript.text") || (kMDItemContentType = "com.apple.applescript.script") ]]) :callbackMessages("didUpdate", "inProgress") :setCallback(updateNameMap) :searchScopes(searchPaths) :start() end local plugin = { id = "core.console.scripts", group = "core", dependencies = { ["core.action.manager"] = "actionmanager", } } function plugin.init(deps) -------------------------------------------------------------------------------- -- Start Spotlight Search: -------------------------------------------------------------------------------- mod.startSpotlightSearch() -------------------------------------------------------------------------------- -- Setup Handler: -------------------------------------------------------------------------------- mod._handler = deps.actionmanager.addHandler("global_scripts", "global") :onChoices(function(choices) for name, app in pairs(mod.appCache) do choices:add(name) :subText(app["path"]) :params({ ["path"] = app["path"], }) :image(app["icon"]) :id("global_applications_" .. name) end end) :onExecute(function(action) execute(string.format("/usr/bin/osascript '%s'", action["path"])) end) :onActionId(function() return "global_scripts" end) return mod end return plugin
Fixed potential nil error in AppleScript actions
Fixed potential nil error in AppleScript actions - Closes #3137
Lua
mit
CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost
064e256771423182975f5b68d452513d89aa5a0d
lua/entities/sent_deployableballoons.lua
lua/entities/sent_deployableballoons.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Balloon Deployer" ENT.Author = "LuaPinapple" ENT.Contact = "[email protected]" ENT.Purpose = "It Deploys Balloons." ENT.Instructions = "Use wire." ENT.Category = "Wiremod" ENT.Spawnable = true ENT.AdminOnly = false ENT.WireDebugName = "Balloon Deployer" cleanup.Register("wire_deployers") if CLIENT then language.Add( "Cleanup_wire_deployers", "Balloon Deployers" ) language.Add( "Cleaned_wire_deployers", "Cleaned up Balloon Deployers" ) language.Add( "SBoxLimit_wire_deployers", "You have hit the Balloon Deployers limit!" ) return -- No more client end local material = "cable/rope" CreateConVar('sbox_maxwire_deployers', 2) local function MakeBalloonSpawner(pl, Data) if not pl:CheckLimit("wire_deployers") then return nil end local ent = ents.Create("sent_deployableballoons") if not ent:IsValid() then return end duplicator.DoGeneric(ent, Data) ent:SetPlayer(pl) ent:Spawn() ent:Activate() duplicator.DoGenericPhysics(ent, pl, Data) pl:AddCount("wire_deployers", ent) pl:AddCleanup("wire_deployers", ent) return ent end duplicator.RegisterEntityClass("sent_deployableballoons", MakeBalloonSpawner, "Data") function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) --Moves old "Lenght" input to new "Length" input for older dupes if info.Wires and info.Wires.Lenght then info.Wires.Length = info.Wires.Lenght info.Wires.Lenght = nil end self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) end function ENT:SpawnFunction( ply, tr ) if (not tr.Hit) then return end local SpawnPos = tr.HitPos+tr.HitNormal*16 local ent = MakeBalloonSpawner(ply, {Pos=SpawnPos}) return ent end function ENT:Initialize() self:SetModel("models/props_junk/PropaneCanister001a.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid(SOLID_VPHYSICS) self.Deployed = 0 self.Balloon = nil self.Constraints = {} self.force = 500 self.weld = false self.popable = true self.rl = 64 if WireAddon then self.Inputs = Wire_CreateInputs(self,{ "Force", "Length", "Weld?", "Popable?", "Deploy" }) self.Outputs = Wire_CreateOutputs(self,{ "Deployed" }) Wire_TriggerOutput(self,"Deployed", self.Deployed) --Wire_TriggerOutput(self,"Force", self.force) end local phys = self:GetPhysicsObject() if(phys:IsValid()) then phys:SetMass(250) phys:Wake() end self:UpdateOverlay() end function ENT:TriggerInput(key,value) if (key == "Deploy") then if value ~= 0 then if self.Deployed == 0 then self:DeployBalloons() self.Deployed = 1 end Wire_TriggerOutput(self, "Deployed", self.Deployed) else if self.Deployed ~= 0 then self:RetractBalloons() self.Deployed = 0 end Wire_TriggerOutput(self, "Deployed", self.Deployed) end elseif (key == "Force") then self.force = value if self.Deployed ~= 0 then self.Balloon:SetForce(value) end elseif (key == "Length") then self.rl = value elseif (key == "Weld?") then self.weld = value ~= 0 elseif (key == "Popable?") then //self.popable = value ~= 0 -- Invinsible balloons don't seem to exist anymore end self:UpdateOverlay() end local balloon_registry = {} hook.Add("EntityRemoved", "balloon_deployer", function(ent) local deployer = balloon_registry[ent] if IsValid(deployer) and deployer.TriggerInput then deployer.Deployed = 0 deployer:TriggerInput("Deploy", 0) end end) function ENT:DeployBalloons() local balloon if self.popable then balloon = ents.Create("gmod_balloon") --normal balloon else balloon = ents.Create("gmod_iballoon") --invincible balloon end balloon:SetModel("models/MaxOfS2D/balloon_classic.mdl") balloon:Spawn() balloon:SetRenderMode( RENDERMODE_TRANSALPHA ) balloon:SetColor(Color(math.random(0,255), math.random(0,255), math.random(0,255), 255)) balloon:SetForce(self.force) balloon:SetMaterial("models/balloon/balloon") balloon:SetPlayer(self:GetPlayer()) duplicator.DoGeneric(balloon,{Pos = self:GetPos() + (self:GetUp()*25)}) duplicator.DoGenericPhysics(balloon,pl,{Pos = Pos}) local spawnervec = (self:GetPos()-balloon:GetPos()):GetNormalized()*250 --just to be sure local trace = util.QuickTrace(balloon:GetPos(),spawnervec,balloon) local Pos = self:GetPos()+(self:GetUp()*25) local LPos1 = balloon:WorldToLocal(Pos) local LPos2 = trace.Entity:WorldToLocal(trace.HitPos) local phys = trace.Entity:GetPhysicsObjectNum(trace.PhysicsBone) if phys and phys:IsValid() then LPos2 = phys:WorldToLocal(trace.HitPos) end if self.weld then local constraint = constraint.Weld( balloon, trace.Entity, 0, trace.PhysicsBone, 0) balloon:DeleteOnRemove(constraint) else local constraint, rope = constraint.Rope(balloon,trace.Entity,0,trace.PhysicsBone,LPos1,LPos2,0,self.rl,0,1.5,material,nil) if constraint then balloon:DeleteOnRemove(constraint) balloon:DeleteOnRemove(rope) end end self:DeleteOnRemove(balloon) self.Balloon = balloon balloon_registry[balloon] = self end function ENT:OnRemove() if self.Balloon then balloon_registry[self.Balloon] = nil end Wire_Remove(self) end function ENT:RetractBalloons() if self.Balloon:IsValid() then local c = self.Balloon:GetColor() local effectdata = EffectData() effectdata:SetOrigin( self.Balloon:GetPos() ) effectdata:SetStart( Vector(c.r,c.g,c.b) ) util.Effect( "balloon_pop", effectdata ) self.Balloon:Remove() else self.Balloon = nil end end function ENT:UpdateOverlay() self:SetOverlayText( "Deployed = " .. ((self.Deployed ~= 0) and "yes" or "no") ) end
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Balloon Deployer" ENT.Author = "LuaPinapple" ENT.Contact = "[email protected]" ENT.Purpose = "It Deploys Balloons." ENT.Instructions = "Use wire." ENT.Category = "Wiremod" ENT.Spawnable = true ENT.AdminOnly = false ENT.WireDebugName = "Balloon Deployer" cleanup.Register("wire_deployers") if CLIENT then language.Add( "Cleanup_wire_deployers", "Balloon Deployers" ) language.Add( "Cleaned_wire_deployers", "Cleaned up Balloon Deployers" ) language.Add( "SBoxLimit_wire_deployers", "You have hit the Balloon Deployers limit!" ) return -- No more client end local material = "cable/rope" CreateConVar('sbox_maxwire_deployers', 2) local function MakeBalloonSpawner(pl, Data) if not pl:CheckLimit("wire_deployers") then return nil end local ent = ents.Create("sent_deployableballoons") if not ent:IsValid() then return end duplicator.DoGeneric(ent, Data) ent:SetPlayer(pl) ent:Spawn() ent:Activate() duplicator.DoGenericPhysics(ent, pl, Data) pl:AddCount("wire_deployers", ent) pl:AddCleanup("wire_deployers", ent) return ent end duplicator.RegisterEntityClass("sent_deployableballoons", MakeBalloonSpawner, "Data") function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) --Moves old "Lenght" input to new "Length" input for older dupes if info.Wires and info.Wires.Lenght then info.Wires.Length = info.Wires.Lenght info.Wires.Lenght = nil end self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) end function ENT:SpawnFunction( ply, tr ) if (not tr.Hit) then return end local SpawnPos = tr.HitPos+tr.HitNormal*16 local ent = MakeBalloonSpawner(ply, {Pos=SpawnPos}) return ent end function ENT:Initialize() self:SetModel("models/props_junk/PropaneCanister001a.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid(SOLID_VPHYSICS) self.Deployed = 0 self.Balloon = nil self.Constraints = {} self.force = 500 self.weld = false self.popable = true self.rl = 64 if WireAddon then self.Inputs = Wire_CreateInputs(self,{ "Force", "Length", "Weld?", "Popable?", "Deploy" }) self.Outputs = Wire_CreateOutputs(self,{ "Deployed" }) Wire_TriggerOutput(self,"Deployed", self.Deployed) --Wire_TriggerOutput(self,"Force", self.force) end local phys = self:GetPhysicsObject() if(phys:IsValid()) then phys:SetMass(250) phys:Wake() end self:UpdateOverlay() end function ENT:TriggerInput(key,value) if (key == "Deploy") then if value ~= 0 then if self.Deployed == 0 then self:DeployBalloons() self.Deployed = 1 end Wire_TriggerOutput(self, "Deployed", self.Deployed) else if self.Deployed ~= 0 then self:RetractBalloons() self.Deployed = 0 end Wire_TriggerOutput(self, "Deployed", self.Deployed) end elseif (key == "Force") then self.force = value if self.Deployed ~= 0 then self.Balloon:SetForce(value) end elseif (key == "Length") then self.rl = value elseif (key == "Weld?") then self.weld = value ~= 0 elseif (key == "Popable?") then //self.popable = value ~= 0 -- Invinsible balloons don't seem to exist anymore end self:UpdateOverlay() end local balloon_registry = {} hook.Add("EntityRemoved", "balloon_deployer", function(ent) local deployer = balloon_registry[ent] if IsValid(deployer) and deployer.TriggerInput then deployer.Deployed = 0 deployer:TriggerInput("Deploy", 0) end end) function ENT:DeployBalloons() local balloon if self.popable then balloon = ents.Create("gmod_balloon") --normal balloon else balloon = ents.Create("gmod_iballoon") --invincible balloon end balloon:SetModel("models/MaxOfS2D/balloon_classic.mdl") balloon:Spawn() balloon:SetRenderMode( RENDERMODE_TRANSALPHA ) balloon:SetColor(Color(math.random(0,255), math.random(0,255), math.random(0,255), 255)) balloon:SetForce(self.force) balloon:SetMaterial("models/balloon/balloon") balloon:SetPlayer(self:GetPlayer()) duplicator.DoGeneric(balloon,{Pos = self:GetPos() + (self:GetUp()*25)}) duplicator.DoGenericPhysics(balloon,pl,{Pos = Pos}) local balloonPos = balloon:GetPos() -- the origin the balloon is at the bottom local hitEntity = self local hitPos = self:LocalToWorld(Vector(0, 0, self:OBBMaxs().z)) -- the top of the spawner -- We trace from the balloon to us, and if there's anything in the way, we -- attach a constraint to that instead - that way, the balloon spawner can -- be hidden underneath a plate which magically gets balloons attached to it. local balloonToSpawner = (hitPos - balloonPos):GetNormalized() * 250 local trace = util.QuickTrace(balloon:GetPos(), balloonToSpawner, balloon) if constraint.CanConstrain(trace.Entity, trace.PhysicsBone) then local phys = trace.Entity:GetPhysicsObjectNum(trace.PhysicsBone) if IsValid(phys) then hitEntity = trace.Entity hitPos = trace.HitPos end end if self.weld then local constraint = constraint.Weld( balloon, hitEntity, 0, trace.PhysicsBone, 0) balloon:DeleteOnRemove(constraint) else balloonPos = balloon:WorldToLocal(balloonPos) hitPos = hitEntity:WorldToLocal(hitPos) local constraint, rope = constraint.Rope( balloon, hitEntity, 0, trace.PhysicsBone, balloonPos, hitPos, 0, self.rl, 0, 1.5, material, false) if constraint then balloon:DeleteOnRemove(constraint) balloon:DeleteOnRemove(rope) end end self:DeleteOnRemove(balloon) self.Balloon = balloon balloon_registry[balloon] = self end function ENT:OnRemove() if self.Balloon then balloon_registry[self.Balloon] = nil end Wire_Remove(self) end function ENT:RetractBalloons() if self.Balloon:IsValid() then local c = self.Balloon:GetColor() local effectdata = EffectData() effectdata:SetOrigin( self.Balloon:GetPos() ) effectdata:SetStart( Vector(c.r,c.g,c.b) ) util.Effect( "balloon_pop", effectdata ) self.Balloon:Remove() else self.Balloon = nil end end function ENT:UpdateOverlay() self:SetOverlayText( "Deployed = " .. ((self.Deployed ~= 0) and "yes" or "no") ) end
Fix #621. Make balloon spawner checks safer.
Fix #621. Make balloon spawner checks safer.
Lua
apache-2.0
notcake/wire,garrysmodlua/wire,immibis/wiremod,rafradek/wire,thegrb93/wire,dvdvideo1234/wire,Python1320/wire,sammyt291/wire,NezzKryptic/Wire,CaptainPRICE/wire,mitterdoo/wire,wiremod/wire,plinkopenguin/wiremod,mms92/wire,bigdogmat/wire,Grocel/wire
1fef1f9363a2d5028c212523b7d6912faf342b45
Parallel.lua
Parallel.lua
local Parallel, parent = torch.class('nn.Parallel', 'nn.Container') function Parallel:__init(inputDimension,outputDimension) parent.__init(self) self.modules = {} self.inputDimension = inputDimension self.outputDimension = outputDimension end function Parallel:updateOutput(input) local nModule=input:size(self.inputDimension) local outputs = {} local totalOutputSize = torch.LongStorage() for i=1,nModule do local currentInput = input:select(self.inputDimension,i) local currentOutput = self.modules[i]:updateOutput(currentInput) table.insert(outputs, currentOutput) local outputSize = currentOutput:size(self.outputDimension) if i == 1 then totalOutputSize:resize(currentOutput:dim()):copy(currentOutput:size()) else totalOutputSize[self.outputDimension] = totalOutputSize[self.outputDimension] + outputSize end end self.output:resize(totalOutputSize) local offset = 1 for i=1,nModule do local currentOutput = outputs[i] local outputSize = currentOutput:size(self.outputDimension) self.output:narrow(self.outputDimension, offset, outputSize):copy(currentOutput) offset = offset + currentOutput:size(self.outputDimension) end return self.output end function Parallel:updateGradInput(input, gradOutput) local nModule=input:size(self.inputDimension) self.gradInput:resizeAs(input) local offset = 1 for i=1,nModule do local module=self.modules[i] local currentInput = input:select(self.inputDimension,i) local currentOutput = module.output local outputSize = currentOutput:size(self.outputDimension) local currentGradOutput = gradOutput:narrow(self.outputDimension, offset, outputSize) local currentGradInput = module:updateGradInput(currentInput, currentGradOutput) self.gradInput:select(self.inputDimension,i):copy(currentGradInput) offset = offset + outputSize end return self.gradInput end function Parallel:accGradParameters(input, gradOutput, scale) local nModule=input:size(self.inputDimension) local offset = 1 for i=1,nModule do local module = self.modules[i] local currentOutput = module.output local outputSize = currentOutput:size(self.outputDimension) module:accGradParameters( input:select(self.inputDimension,i), gradOutput:narrow(self.outputDimension, offset,outputSize), scale ) offset = offset + outputSize end end function Parallel:accUpdateGradParameters(input, gradOutput, lr) local nModule=input:size(self.inputDimension) local offset = 1 for i=1,nModule do local module = self.modules[i]; local currentOutput = module.output module:accUpdateGradParameters( input:select(self.inputDimension,i), gradOutput:narrow(self.outputDimension, offset, currentOutput:size(self.outputDimension)), lr) offset = offset + currentOutput:size(self.outputDimension) end end function Parallel:__tostring__() local tab = ' ' local line = '\n' local next = ' |`-> ' local ext = ' | ' local extlast = ' ' local last = ' ... -> ' local str = torch.type(self) str = str .. ' {' .. line .. tab .. 'input' for i=1,#self.modules do if i == self.modules then str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. extlast) else str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. ext) end end str = str .. line .. tab .. last .. 'output' str = str .. line .. '}' return str end
local Parallel, parent = torch.class('nn.Parallel', 'nn.Container') function Parallel:__init(inputDimension,outputDimension) parent.__init(self) self.modules = {} self.inputDimension = inputDimension self.outputDimension = outputDimension end function Parallel:updateOutput(input) local nModule=input:size(self.inputDimension) local outputs = {} self.totalOutputSize = self.totalOutputSize or torch.LongStorage() local totalOutputSize = self.totalOutputSize for i=1,nModule do local currentInput = input:select(self.inputDimension,i) local currentOutput = self.modules[i]:updateOutput(currentInput) table.insert(outputs, currentOutput) local outputSize = currentOutput:size(self.outputDimension) if i == 1 then totalOutputSize:resize(currentOutput:dim()):copy(currentOutput:size()) else totalOutputSize[self.outputDimension] = totalOutputSize[self.outputDimension] + outputSize end end self.output:resize(totalOutputSize) local offset = 1 for i=1,nModule do local currentOutput = outputs[i] local outputSize = currentOutput:size(self.outputDimension) self.output:narrow(self.outputDimension, offset, outputSize):copy(currentOutput) offset = offset + currentOutput:size(self.outputDimension) end return self.output end function Parallel:updateGradInput(input, gradOutput) local nModule=input:size(self.inputDimension) self.gradInput:resizeAs(input) local offset = 1 for i=1,nModule do local module=self.modules[i] local currentInput = input:select(self.inputDimension,i) local currentOutput = module.output local outputSize = currentOutput:size(self.outputDimension) local currentGradOutput = gradOutput:narrow(self.outputDimension, offset, outputSize) local currentGradInput = module:updateGradInput(currentInput, currentGradOutput) self.gradInput:select(self.inputDimension,i):copy(currentGradInput) offset = offset + outputSize end return self.gradInput end function Parallel:accGradParameters(input, gradOutput, scale) local nModule=input:size(self.inputDimension) local offset = 1 for i=1,nModule do local module = self.modules[i] local currentOutput = module.output local outputSize = currentOutput:size(self.outputDimension) module:accGradParameters( input:select(self.inputDimension,i), gradOutput:narrow(self.outputDimension, offset,outputSize), scale ) offset = offset + outputSize end end function Parallel:accUpdateGradParameters(input, gradOutput, lr) local nModule=input:size(self.inputDimension) local offset = 1 for i=1,nModule do local module = self.modules[i]; local currentOutput = module.output module:accUpdateGradParameters( input:select(self.inputDimension,i), gradOutput:narrow(self.outputDimension, offset, currentOutput:size(self.outputDimension)), lr) offset = offset + currentOutput:size(self.outputDimension) end end function Parallel:__tostring__() local tab = ' ' local line = '\n' local next = ' |`-> ' local ext = ' | ' local extlast = ' ' local last = ' ... -> ' local str = torch.type(self) str = str .. ' {' .. line .. tab .. 'input' for i=1,#self.modules do if i == self.modules then str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. extlast) else str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. ext) end end str = str .. line .. tab .. last .. 'output' str = str .. line .. '}' return str end
fix size for parallel container
fix size for parallel container
Lua
bsd-3-clause
xianjiec/nn,andreaskoepf/nn,Moodstocks/nn,elbamos/nn,apaszke/nn,PraveerSINGH/nn,eriche2016/nn,colesbury/nn,lukasc-ch/nn,nicholas-leonard/nn,diz-vara/nn,jhjin/nn,kmul00/nn,joeyhng/nn,jonathantompson/nn,caldweln/nn,witgo/nn,sagarwaghmare69/nn
49e0822fa91b27d364835c1aa6b079b03983603e
main.lua
main.lua
require "lib.gooi" require "pixelfunctions" dp = love.window.toPixels fd = love.window.fromPixels lg = love.graphics nB = gooi.newButton sw, sh = lg.getDimensions() require "styles" Camera = require"lib.hump.camera" showgrid = true showAlphaBG = true Timer = require"lib.hump.timer" require "guifunctions" require "colorpicker" require "toolbar" function love.load() history = {} lg.setFont(fonts.rr) love.graphics.setDefaultFilter("nearest") lg.setBackgroundColor(150, 150, 150) newdata = love.image.newImageData(32, 32) camera = Camera(newdata:getWidth()/2, newdata:getHeight()/2, 4) --newdata:mapPixel(pixelFunction.allwhite) currentimage = love.graphics.newImage(newdata) palettedata = love.image.newImageData("palettes/todayland.png") paletteImage = love.graphics.newImage(palettedata) paletteCamera = Camera(0,0) paletteCamera:zoomTo(dp(22)) alphaBG = love.graphics.newImage("bg.png") alphaBG:setWrap("repeat") updateAlphaQuad() alphaCamera = Camera(newdata:getWidth(), newdata:getHeight()) local cx, cy = paletteCamera:worldCoords(sw - dp(4), sh) local wx, wy = paletteCamera:worldCoords(0, dp(48)) paletteCamera:lookAt(paletteImage:getWidth() - cx, (-wy)) candraw = true currentcolor = {0, 0, 0, 255} gui.load() colorpicker.load() toolbar.load() table.insert(history, 1, newdata:encode("png")) --currentimage:setWrap("repeat") imgx, imgy = 0, 0 xamm = 0 yamm = 0 imgQuad = love.graphics.newQuad(0, 0, newdata:getWidth(), newdata:getHeight(), newdata:getWidth(), newdata:getHeight()) end function love.update(dt) Timer.update(dt) if zoomslider.value <= 0.01 then camera:zoomTo(1) alphaCamera:zoomTo(.5) else camera:zoomTo(zoomslider.value *dp(50)) alphaCamera:zoomTo(zoomslider.value *dp(25)) end gooi.update(dt) colorpicker.update(dt) cp.bgColor = currentcolor toolbar.update(dt) showgrid = menus.viewMenu.components.gridCheck.checked end function love.draw() lg.setColor(255, 255, 255) if menus.viewMenu.components.alphaBgCheck.checked then alphaCamera:attach() lg.draw(alphaBG, alphaQuad, 0, 0) alphaCamera:detach() end camera:attach() --lg.draw(currentimage, 0, 0) lg.draw(currentimage, imgQuad, 0, 0) camera:detach() drawGrid(1, 1, {0, 0, 0, 50}) drawGrid(8, 8, {255, 0, 0, 250}) drawGrid(16, 16, {0, 0, 255, 250}) lg.setColor(255, 255, 255) paletteCamera:attach() lg.draw(paletteImage, 0, 0) paletteCamera:detach() drawPaletteGrid(colors.black) lg.setColor(colors.primary) lg.rectangle("fill", 0, 0, sw, dp(44)) --top bar gooi.draw() gooi.draw("fileMenu") gooi.draw("saveMenu") gooi.draw("viewMenu") gooi.draw("newFileMenu") gooi.draw("colorpicker") lg.setColor(255, 255, 255) end function love.touchpressed(id, x, y) gooi.pressed(id, x, y) touchx, touchy = camera:worldCoords(x, y) if y <= dp(46) or y >= undo.y or x <= dp(44) or gui.checkOpenMenus() or fileBrowser ~= nil or colorpicker.enabled then candraw = false elseif y > dp(46) or x > dp(44) then candraw = true end local palx, paly = paletteCamera:worldCoords(x, y) if palx >= 0 and palx <= paletteImage:getWidth() and paly >= 0 and paly <= paletteImage:getHeight() then candraw = false currentcolor = {palettedata:getPixel(palx, paly)} colorpicker.updateSliders() end drawFunctions() currentimage:refresh() end h = 0 function love.touchreleased(id, x, y) gooi.released(id, x, y) if candraw and touchx >= 0 and touchx <= newdata:getWidth() and touchy >= 0 and touchy <= newdata:getHeight() and tool ~= tools.pan and tool ~= none or tool == tools.move then --history[#history + 1] = newdata:encode("png") table.insert(history, #history + 1, newdata:encode("png")) if #history >= 10 then table.remove(history, 1) end h = #history end if tool == tools.move and candraw then imgQuad:setViewport(0, 0, newdata:getWidth(), newdata:getHeight()) newdata:mapPixel(pixelFunction.allwhite) pastedata = love.image.newImageData(history[h]) newdata:paste(pastedata, xamm, yamm, 0, 0, pastedata:getWidth(), pastedata:getHeight()) xamm, yamm = 0, 0 else end touchx, touchy = nil, nil currentimage:refresh() end local ql, qr, qu, qd = 0, 0, 0, 0 function love.touchmoved(id, x, y) gooi.moved(id, x, y) if tool ~= tools.pan and tool ~= tools.move then touchx, touchy = camera:worldCoords(x, y) elseif tool == tools.pan and y > dp(46) then local newtouchx, newtouchy = camera:worldCoords(x, y) camera:move(touchx - newtouchx, touchy - newtouchy) alphaCamera:move((touchx-newtouchx)*2, (touchy - newtouchy)*2) end if tool == tools.move and y > dp(46) then local newtouchx, newtouchy = camera:worldCoords(x, y) --imgQuad:setViewport(math.ceil(touchx - newtouchx), math.ceil(touchy - newtouchy), newdata:getWidth(), newdata:getHeight()) xamm = (math.ceil(touchx - newtouchx) * -1) yamm = (math.ceil(touchy - newtouchy) * -1) imgQuad:setViewport(xamm * -1, yamm * - 1, newdata:getWidth(), newdata:getHeight()) --gui.toast("x: "..tostring(xamm).." y: "..tostring(yamm)) --touchx = touchx - newtouchx end drawFunctions() currentimage:refresh() end function love.textinput(text) gooi.textinput(text) end function love.keypressed(key) gooi.keypressed(key) end function drawGrid(xsize, ysize, color) if showgrid then love.graphics.setColor(color) love.graphics.setLineWidth(dp(1)) for i = xsize, (currentimage:getWidth() - 1), xsize do local x, y = camera:cameraCoords(i, 0) local x2, y2 = camera:cameraCoords(i, currentimage:getHeight()) love.graphics.line(x, y, x2, y2) end for i = ysize, (currentimage:getHeight() - 1), ysize do local x, y = camera:cameraCoords(0, i) local x2, y2 = camera:cameraCoords(currentimage:getWidth(), i) love.graphics.line(x, y, x2, y2) end end end function drawPaletteGrid(color) love.graphics.setColor(color) love.graphics.setLineWidth(dp(3)) for i = 0, (paletteImage:getWidth()) do local x, y = paletteCamera:cameraCoords(i, 0) local x2, y2 = paletteCamera:cameraCoords(i, paletteImage:getHeight()) love.graphics.line(x, y, x2, y2) end for i = 0, (paletteImage:getHeight()) do local x, y = paletteCamera:cameraCoords(0, i) local x2, y2 = paletteCamera:cameraCoords(paletteImage:getWidth(), i) love.graphics.line(x, y, x2, y2) end end function updateAlphaQuad() alphaQuad = love.graphics.newQuad(0, 0, (newdata:getWidth() * 2), (newdata:getHeight() * 2), 2, 2) end
require "lib.gooi" require "pixelfunctions" dp = love.window.toPixels fd = love.window.fromPixels lg = love.graphics nB = gooi.newButton sw, sh = lg.getDimensions() require "styles" Camera = require"lib.hump.camera" showgrid = true showAlphaBG = true Timer = require"lib.hump.timer" require "guifunctions" require "colorpicker" require "toolbar" function love.load() history = {} lg.setFont(fonts.rr) love.graphics.setDefaultFilter("nearest") lg.setBackgroundColor(150, 150, 150) newdata = love.image.newImageData(32, 32) camera = Camera(newdata:getWidth()/2, newdata:getHeight()/2, 4) --newdata:mapPixel(pixelFunction.allwhite) currentimage = love.graphics.newImage(newdata) palettedata = love.image.newImageData("palettes/todayland.png") paletteImage = love.graphics.newImage(palettedata) paletteCamera = Camera(0,0) paletteCamera:zoomTo(dp(22)) alphaBG = love.graphics.newImage("bg.png") alphaBG:setWrap("repeat") updateAlphaQuad() alphaCamera = Camera(newdata:getWidth(), newdata:getHeight()) local cx, cy = paletteCamera:worldCoords(sw - dp(4), sh) local wx, wy = paletteCamera:worldCoords(0, dp(48)) paletteCamera:lookAt(paletteImage:getWidth() - cx, (-wy)) candraw = true currentcolor = {0, 0, 0, 255} gui.load() colorpicker.load() toolbar.load() table.insert(history, 1, newdata:encode("png")) --currentimage:setWrap("repeat") imgx, imgy = 0, 0 xamm = 0 yamm = 0 imgQuad = love.graphics.newQuad(0, 0, newdata:getWidth(), newdata:getHeight(), newdata:getWidth(), newdata:getHeight()) end function love.update(dt) Timer.update(dt) if zoomslider.value <= 0.01 then camera:zoomTo(1) alphaCamera:zoomTo(.5) else camera:zoomTo(zoomslider.value *dp(50)) alphaCamera:zoomTo(zoomslider.value *dp(25)) end gooi.update(dt) colorpicker.update(dt) cp.bgColor = currentcolor toolbar.update(dt) showgrid = menus.viewMenu.components.gridCheck.checked end function love.draw() lg.setColor(255, 255, 255) if menus.viewMenu.components.alphaBgCheck.checked then alphaCamera:attach() lg.draw(alphaBG, alphaQuad, 0, 0) alphaCamera:detach() end camera:attach() --lg.draw(currentimage, 0, 0) lg.draw(currentimage, imgQuad, 0, 0) camera:detach() drawGrid(1, 1, {0, 0, 0, 50}) drawGrid(8, 8, {255, 0, 0, 250}) drawGrid(16, 16, {0, 0, 255, 250}) lg.setColor(255, 255, 255) paletteCamera:attach() lg.draw(paletteImage, 0, 0) paletteCamera:detach() drawPaletteGrid(colors.black) lg.setColor(colors.primary) lg.rectangle("fill", 0, 0, sw, dp(44)) --top bar gooi.draw() gooi.draw("fileMenu") gooi.draw("saveMenu") gooi.draw("viewMenu") gooi.draw("newFileMenu") gooi.draw("colorpicker") lg.setColor(255, 255, 255) end function love.touchpressed(id, x, y) gooi.pressed(id, x, y) touchx, touchy = camera:worldCoords(x, y) if y <= dp(46) or y >= undo.y or x <= dp(44) or gui.checkOpenMenus() or fileBrowser ~= nil or colorpicker.enabled then candraw = false elseif y > dp(46) or x > dp(44) then candraw = true end local palx, paly = paletteCamera:worldCoords(x, y) if palx >= 0 and palx <= paletteImage:getWidth() and paly >= 0 and paly <= paletteImage:getHeight() then candraw = false if not colorpicker.enabled then currentcolor = {palettedata:getPixel(palx, paly)} colorpicker.updateSliders() else colorpicker.rslider.value, colorpicker.gslider.value, colorpicker.bslider.value = palettedata:getPixel(palx, paly) colorpicker.rslider.value = colorpicker.rslider.value / 255 colorpicker.gslider.value = colorpicker.gslider.value / 255 colorpicker.bslider.value = colorpicker.bslider.value / 255 end end drawFunctions() currentimage:refresh() end h = 0 function love.touchreleased(id, x, y) gooi.released(id, x, y) if candraw and touchx >= 0 and touchx <= newdata:getWidth() and touchy >= 0 and touchy <= newdata:getHeight() and tool ~= tools.pan and tool ~= none or tool == tools.move then --history[#history + 1] = newdata:encode("png") table.insert(history, #history + 1, newdata:encode("png")) if #history >= 10 then table.remove(history, 1) end h = #history end if tool == tools.move and candraw then imgQuad:setViewport(0, 0, newdata:getWidth(), newdata:getHeight()) newdata:mapPixel(pixelFunction.allwhite) pastedata = love.image.newImageData(history[h]) newdata:paste(pastedata, xamm, yamm, 0, 0, pastedata:getWidth(), pastedata:getHeight()) xamm, yamm = 0, 0 else end touchx, touchy = nil, nil currentimage:refresh() end local ql, qr, qu, qd = 0, 0, 0, 0 function love.touchmoved(id, x, y) gooi.moved(id, x, y) if tool ~= tools.pan and tool ~= tools.move then touchx, touchy = camera:worldCoords(x, y) elseif tool == tools.pan and y > dp(46) then local newtouchx, newtouchy = camera:worldCoords(x, y) camera:move(touchx - newtouchx, touchy - newtouchy) alphaCamera:move((touchx-newtouchx)*2, (touchy - newtouchy)*2) end if tool == tools.move and y > dp(46) then local newtouchx, newtouchy = camera:worldCoords(x, y) --imgQuad:setViewport(math.ceil(touchx - newtouchx), math.ceil(touchy - newtouchy), newdata:getWidth(), newdata:getHeight()) xamm = (math.ceil(touchx - newtouchx) * -1) yamm = (math.ceil(touchy - newtouchy) * -1) imgQuad:setViewport(xamm * -1, yamm * - 1, newdata:getWidth(), newdata:getHeight()) --gui.toast("x: "..tostring(xamm).." y: "..tostring(yamm)) --touchx = touchx - newtouchx end drawFunctions() currentimage:refresh() end function love.textinput(text) gooi.textinput(text) end function love.keypressed(key) gooi.keypressed(key) end function drawGrid(xsize, ysize, color) if showgrid then love.graphics.setColor(color) love.graphics.setLineWidth(dp(1)) for i = xsize, (currentimage:getWidth() - 1), xsize do local x, y = camera:cameraCoords(i, 0) local x2, y2 = camera:cameraCoords(i, currentimage:getHeight()) love.graphics.line(x, y, x2, y2) end for i = ysize, (currentimage:getHeight() - 1), ysize do local x, y = camera:cameraCoords(0, i) local x2, y2 = camera:cameraCoords(currentimage:getWidth(), i) love.graphics.line(x, y, x2, y2) end end end function drawPaletteGrid(color) love.graphics.setColor(color) love.graphics.setLineWidth(dp(3)) for i = 0, (paletteImage:getWidth()) do local x, y = paletteCamera:cameraCoords(i, 0) local x2, y2 = paletteCamera:cameraCoords(i, paletteImage:getHeight()) love.graphics.line(x, y, x2, y2) end for i = 0, (paletteImage:getHeight()) do local x, y = paletteCamera:cameraCoords(0, i) local x2, y2 = paletteCamera:cameraCoords(paletteImage:getWidth(), i) love.graphics.line(x, y, x2, y2) end end function updateAlphaQuad() alphaQuad = love.graphics.newQuad(0, 0, (newdata:getWidth() * 2), (newdata:getHeight() * 2), 2, 2) end
colorpicker bug fix
colorpicker bug fix
Lua
mit
trelemar/TM-Paint,trelemar/Dither
139930540fe18c2f920efca051765437d0676d96
game/scripts/vscripts/modules/hero_selection/hero_replacer.lua
game/scripts/vscripts/modules/hero_selection/hero_replacer.lua
function HeroSelection:SelectHero(playerId, heroName, callback, bSkipPrecache) HeroSelection:UpdateStatusForPlayer(playerId, "picked", heroName) Timers:CreateTimer(function() local connectionState = PlayerResource:GetConnectionState(playerId) if connectionState == DOTA_CONNECTION_STATE_CONNECTED then local function SpawnHero() Timers:CreateTimer(function() connectionState = PlayerResource:GetConnectionState(playerId) if connectionState == DOTA_CONNECTION_STATE_CONNECTED then local heroTableCustom = NPC_HEROES_CUSTOM[heroName] or NPC_HEROES[heroName] local oldhero = PlayerResource:GetSelectedHeroEntity(playerId) local hero local baseNewHero = heroTableCustom.base_hero or heroName if oldhero then Timers:CreateTimer(0.03, function() oldhero:ClearNetworkableEntityInfo() UTIL_Remove(oldhero) end) if oldhero:GetUnitName() == baseNewHero then -- Base unit equals, ReplaceHeroWith won't do anything local temp = PlayerResource:ReplaceHeroWith(playerId, FORCE_PICKED_HERO, 0, 0) Timers:CreateTimer(0.03, function() temp:ClearNetworkableEntityInfo() UTIL_Remove(temp) end) end hero = PlayerResource:ReplaceHeroWith(playerId, baseNewHero, 0, 0) else print("[HeroSelection] For some reason player " .. playerId .. " has no hero. This player can't get a hero. Returning") return end HeroSelection:InitializeHeroClass(hero, heroTableCustom) if heroTableCustom.base_hero then TransformUnitClass(hero, heroTableCustom) hero.UnitName = heroName end if Options:IsEquals("EnableAbilityShop") then for i = 0, hero:GetAbilityCount() - 1 do if hero:GetAbilityByIndex(i) then hero:RemoveAbility(hero:GetAbilityByIndex(i):GetName()) end end hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") end if callback then callback(hero) end else return 0.1 end end) end if bSkipPrecache then SpawnHero() else PrecacheUnitByNameAsync(GetKeyValue(heroName, "base_hero") or heroName, SpawnHero, playerId) end else return 0.1 end end) end function HeroSelection:ChangeHero(playerId, newHeroName, keepExp, duration, item, callback) local hero = PlayerResource:GetSelectedHeroEntity(playerId) hero.ChangingHeroProcessRunning = true ProjectileManager:ProjectileDodge(hero) if hero.PocketItem then hero.PocketHostEntity = nil UTIL_Remove(hero.PocketItem) hero.PocketItem = nil end hero:DestroyAllModifiers() hero:AddNewModifier(hero, nil, "modifier_hero_selection_transformation", nil) local xp = hero:GetCurrentXP() local fountatin = FindFountain(PlayerResource:GetTeam(playerId)) local location = hero:GetAbsOrigin() if fountatin then location = location or fountatin:GetAbsOrigin() end local items = {} for i = DOTA_ITEM_SLOT_1, DOTA_STASH_SLOT_6 do local citem = hero:GetItemInSlot(i) if citem and citem ~= item then local newItem = CreateItem(citem:GetName(), nil, nil) if citem:GetPurchaser() ~= hero then newItem.NotPurchasedByOwner = true newItem:SetPurchaser(citem:GetPurchaser()) end newItem:SetPurchaseTime(citem:GetPurchaseTime()) newItem:SetCurrentCharges(citem:GetCurrentCharges()) if citem:GetCooldownTimeRemaining() > 0 then newItem.SavedCooldown = citem:GetCooldownTimeRemaining() end table.insert(items, newItem) else table.insert(items, CreateItem("item_dummy", hero, hero)) end end local duelData = { StatusBeforeArena = hero.StatusBeforeArena, OnDuel = hero.OnDuel, ArenaBeforeTpLocation = hero.ArenaBeforeTpLocation, DuelChecked = hero.DuelChecked, } for team,tab in pairs(Duel.heroes_teams_for_duel or {}) do for i,unit in pairs(tab) do if unit == hero then duelData.path = {team, i} end end end RemoveAllOwnedUnits(playerId) local startTime = GameRules:GetDOTATime(true, true) HeroSelection:SelectHero(playerId, newHeroName, function(newHero) newHero:AddNewModifier(newHero, nil, "modifier_hero_selection_transformation", nil) FindClearSpaceForUnit(newHero, location, true) if keepExp then newHero:AddExperience(xp, 0, true, true) end for _,v in ipairs(items) do v:SetOwner(newHero) if not v.NotPurchasedByOwner then v:SetPurchaser(newHero) v.NotPurchasedByOwner = nil end if v.SavedCooldown then v:StartCooldown(v.SavedCooldown) v.SavedCooldown = nil end newHero:AddItem(v) end ClearSlotsFromDummy(newHero) for k,v in pairs(duelData) do if k ~= "path" then newHero[k] = v else Duel.heroes_teams_for_duel[v[1]][v[1]] = newHero end end Timers:CreateTimer(startTime + duration - GameRules:GetDOTATime(true, true), function() if IsValidEntity(newHero) then newHero:RemoveModifierByName("modifier_hero_selection_transformation") end end) if callback then callback(newHero) end end) end
function HeroSelection:SelectHero(playerId, heroName, callback, bSkipPrecache) HeroSelection:UpdateStatusForPlayer(playerId, "picked", heroName) Timers:CreateTimer(function() local connectionState = PlayerResource:GetConnectionState(playerId) if connectionState == DOTA_CONNECTION_STATE_CONNECTED then local function SpawnHero() Timers:CreateTimer(function() connectionState = PlayerResource:GetConnectionState(playerId) if connectionState == DOTA_CONNECTION_STATE_CONNECTED then local heroTableCustom = NPC_HEROES_CUSTOM[heroName] or NPC_HEROES[heroName] local oldhero = PlayerResource:GetSelectedHeroEntity(playerId) local hero local baseNewHero = heroTableCustom.base_hero or heroName if oldhero then Timers:CreateTimer(0.03, function() oldhero:ClearNetworkableEntityInfo() UTIL_Remove(oldhero) end) if oldhero:GetUnitName() == baseNewHero then -- Base unit equals, ReplaceHeroWith won't do anything local temp = PlayerResource:ReplaceHeroWith(playerId, FORCE_PICKED_HERO, 0, 0) Timers:CreateTimer(0.03, function() temp:ClearNetworkableEntityInfo() UTIL_Remove(temp) end) end hero = PlayerResource:ReplaceHeroWith(playerId, baseNewHero, 0, 0) else print("[HeroSelection] For some reason player " .. playerId .. " has no hero. This player can't get a hero. Returning") return end HeroSelection:InitializeHeroClass(hero, heroTableCustom) if heroTableCustom.base_hero then TransformUnitClass(hero, heroTableCustom) hero.UnitName = heroName end if Options:IsEquals("EnableAbilityShop") then for i = 0, hero:GetAbilityCount() - 1 do if hero:GetAbilityByIndex(i) then hero:RemoveAbility(hero:GetAbilityByIndex(i):GetName()) end end hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") hero:AddAbility("ability_empty") end if callback then callback(hero) end else return 0.1 end end) end if bSkipPrecache then SpawnHero() else PrecacheUnitByNameAsync(GetKeyValue(heroName, "base_hero") or heroName, SpawnHero, playerId) end else return 0.1 end end) end function HeroSelection:ChangeHero(playerId, newHeroName, keepExp, duration, item, callback) local hero = PlayerResource:GetSelectedHeroEntity(playerId) hero.ChangingHeroProcessRunning = true ProjectileManager:ProjectileDodge(hero) if hero.PocketItem then hero.PocketHostEntity = nil UTIL_Remove(hero.PocketItem) hero.PocketItem = nil end hero:DestroyAllModifiers() hero:InterruptMotionControllers(false) hero:AddNewModifier(hero, nil, "modifier_hero_selection_transformation", nil) local xp = hero:GetCurrentXP() local fountatin = FindFountain(PlayerResource:GetTeam(playerId)) local location = hero:GetAbsOrigin() if fountatin then location = location or fountatin:GetAbsOrigin() end local items = {} for i = DOTA_ITEM_SLOT_1, DOTA_STASH_SLOT_6 do local citem = hero:GetItemInSlot(i) if citem and citem ~= item then local newItem = CreateItem(citem:GetName(), nil, nil) if citem:GetPurchaser() ~= hero then newItem.NotPurchasedByOwner = true newItem:SetPurchaser(citem:GetPurchaser()) end newItem:SetPurchaseTime(citem:GetPurchaseTime()) newItem:SetCurrentCharges(citem:GetCurrentCharges()) if citem:GetCooldownTimeRemaining() > 0 then newItem.SavedCooldown = citem:GetCooldownTimeRemaining() end table.insert(items, newItem) else table.insert(items, CreateItem("item_dummy", hero, hero)) end end local duelData = { StatusBeforeArena = hero.StatusBeforeArena, OnDuel = hero.OnDuel, ArenaBeforeTpLocation = hero.ArenaBeforeTpLocation, DuelChecked = hero.DuelChecked, } for team,tab in pairs(Duel.heroes_teams_for_duel or {}) do for i,unit in pairs(tab) do if unit == hero then duelData.path = {team, i} end end end RemoveAllOwnedUnits(playerId) local startTime = GameRules:GetDOTATime(true, true) HeroSelection:SelectHero(playerId, newHeroName, function(newHero) newHero:AddNewModifier(newHero, nil, "modifier_hero_selection_transformation", nil) FindClearSpaceForUnit(newHero, location, true) if keepExp then newHero:AddExperience(xp, 0, true, true) end for _,v in ipairs(items) do v:SetOwner(newHero) if not v.NotPurchasedByOwner then v:SetPurchaser(newHero) v.NotPurchasedByOwner = nil end if v.SavedCooldown then v:StartCooldown(v.SavedCooldown) v.SavedCooldown = nil end newHero:AddItem(v) end ClearSlotsFromDummy(newHero) for k,v in pairs(duelData) do if k ~= "path" then newHero[k] = v else Duel.heroes_teams_for_duel[v[1]][v[1]] = newHero end end Timers:CreateTimer(startTime + duration - GameRules:GetDOTATime(true, true), function() if IsValidEntity(newHero) then newHero:RemoveModifierByName("modifier_hero_selection_transformation") end end) if callback then callback(newHero) end end) end
Changing hero now interrupts motion controllers, so that fixes pudge crash
Changing hero now interrupts motion controllers, so that fixes pudge crash
Lua
mit
ark120202/aabs
685d12dc71797d69c7f24a6c6ced0d47dc404704
core/base-shaper.lua
core/base-shaper.lua
if not SILE.shapers then SILE.shapers = { } end -- local smallTokenSize = 20 -- Small words will be cached -- local shapeCache = {} -- local _key = function (options) -- return table.concat({ options.family;options.language;options.script;options.size;("%d"):format(options.weight);options.style;options.variant;options.features;options.direction;options.filename }, ";") -- end SILE.settings.declare({ parameter = "shaper.variablespaces", type = "boolean", default = true }) SILE.settings.declare({ parameter = "shaper.spaceenlargementfactor", type = "number or integer", default = 1.2 }) SILE.settings.declare({ parameter = "shaper.spacestretchfactor", type = "number or integer", default = 1/2 }) SILE.settings.declare({ parameter = "shaper.spaceshrinkfactor", type = "number or integer", default = 1/3 }) SILE.settings.declare({ parameter = "shaper.tracking", type = "number or nil", default = nil }) -- Function for testing shaping in the repl -- luacheck: ignore makenodes makenodes = function (token, options) return SILE.shaper:createNnodes(token, SILE.font.loadDefaults(options or {})) end local function shapespace (spacewidth) spacewidth = SU.cast("measurement", spacewidth) local length = spacewidth * SILE.settings.get("shaper.spaceenlargementfactor") local stretch = spacewidth * SILE.settings.get("shaper.spacestretchfactor") local shrink = spacewidth * SILE.settings.get("shaper.spaceshrinkfactor") return SILE.length(length, stretch, shrink) end SILE.shapers.base = pl.class({ -- Return the length of a space character -- with a particular set of font options, -- giving preference to document.spaceskip -- Caching this has no significant speedup measureSpace = function (self, options) local ss = SILE.settings.get("document.spaceskip") if ss then SILE.settings.temporarily(function () SILE.settings.set("font.size", options.size) SILE.settings.set("font.family", options.family) SILE.settings.set("font.filename", options.filename) ss = ss:absolute() end) return ss end local items, width = self:shapeToken(" ", options) if not width and not items[1] then SU.warn("Could not measure the width of a space") return SILE.length() end return shapespace(width and width.length or items[1].width) end, measureChar = function (self, char) local options = SILE.font.loadDefaults({}) options.tracking = SILE.settings.get("shaper.tracking") local items = self:shapeToken(char, options) if #items > 0 then return { height = items[1].height, width = items[1].width } else SU.error("Unable to measure character", char) end end, -- Given a text and some font options, return a bunch of boxes shapeToken = function (_, _, _) SU.error("Abstract function shapeToken called", true) end, -- Given font options, select a font. We will handle -- caching here. Returns an arbitrary, implementation-specific -- object (ie a PAL for Pango, font number for libtexpdf, ...) getFace = function (_) SU.error("Abstract function getFace called", true) end, addShapedGlyphToNnodeValue = function (_, _, _) SU.error("Abstract function addShapedGlyphToNnodeValue called", true) end, preAddNodes = function (_, _, _) end, createNnodes = function (self, token, options) options.tracking = SILE.settings.get("shaper.tracking") local items, _ = self:shapeToken(token, options) if #items < 1 then return {} end local lang = options.language SILE.languageSupport.loadLanguage(lang) local nodeMaker = SILE.nodeMakers[lang] or SILE.nodeMakers.unicode local nodes = {} for node in nodeMaker(options):iterator(items, token) do table.insert(nodes, node) end return nodes end, formNnode = function (self, contents, token, options) local nnodeContents = {} -- local glyphs = {} local totalWidth = 0 local totalDepth = 0 local totalHeight = 0 -- local glyphNames = {} local nnodeValue = { text = token, options = options, glyphString = {} } SILE.shaper:preAddNodes(contents, nnodeValue) local misfit = false if SILE.typesetter.frame and SILE.typesetter.frame:writingDirection() == "TTB" then if options.direction == "LTR" then misfit = true end else if options.direction == "TTB" then misfit = true end end for i = 1, #contents do local glyph = contents[i] if (options.direction == "TTB") ~= misfit then if glyph.width > totalHeight then totalHeight = glyph.width end totalWidth = totalWidth + glyph.height else if glyph.depth > totalDepth then totalDepth = glyph.depth end if glyph.height > totalHeight then totalHeight = glyph.height end totalWidth = totalWidth + glyph.width end self:addShapedGlyphToNnodeValue(nnodeValue, glyph) end table.insert(nnodeContents, SILE.nodefactory.hbox({ depth = totalDepth, height = totalHeight, misfit = misfit, width = SILE.length(totalWidth), value = nnodeValue })) return SILE.nodefactory.nnode({ nodes = nnodeContents, text = token, misfit = misfit, options = options, language = options.language }) end, makeSpaceNode = function (_, options, item) local width if SILE.settings.get("shaper.variablespaces") then width = shapespace(item.width) else width = SILE.shaper:measureSpace(options) end return SILE.nodefactory.glue(width) end })
if not SILE.shapers then SILE.shapers = { } end -- local smallTokenSize = 20 -- Small words will be cached -- local shapeCache = {} -- local _key = function (options) -- return table.concat({ options.family;options.language;options.script;options.size;("%d"):format(options.weight);options.style;options.variant;options.features;options.direction;options.filename }, ";") -- end SILE.settings.declare({ parameter = "shaper.variablespaces", type = "boolean", default = true }) SILE.settings.declare({ parameter = "shaper.spaceenlargementfactor", type = "number or integer", default = 1.2 }) SILE.settings.declare({ parameter = "shaper.spacestretchfactor", type = "number or integer", default = 1/2 }) SILE.settings.declare({ parameter = "shaper.spaceshrinkfactor", type = "number or integer", default = 1/3 }) SILE.settings.declare({ parameter = "shaper.tracking", type = "number or nil", default = nil }) -- Function for testing shaping in the repl -- luacheck: ignore makenodes makenodes = function (token, options) return SILE.shaper:createNnodes(token, SILE.font.loadDefaults(options or {})) end local function shapespace (spacewidth) spacewidth = SU.cast("measurement", spacewidth) -- In some scripts with word-level kerning, glue can be negative. -- Use absolute value to ensure stretch and shrink work as expected. local absoluteSpaceWidth = math.abs(spacewidth:tonumber()) local length = spacewidth * SILE.settings.get("shaper.spaceenlargementfactor") local stretch = absoluteSpaceWidth * SILE.settings.get("shaper.spacestretchfactor") local shrink = absoluteSpaceWidth * SILE.settings.get("shaper.spaceshrinkfactor") return SILE.length(length, stretch, shrink) end SILE.shapers.base = pl.class({ -- Return the length of a space character -- with a particular set of font options, -- giving preference to document.spaceskip -- Caching this has no significant speedup measureSpace = function (self, options) local ss = SILE.settings.get("document.spaceskip") if ss then SILE.settings.temporarily(function () SILE.settings.set("font.size", options.size) SILE.settings.set("font.family", options.family) SILE.settings.set("font.filename", options.filename) ss = ss:absolute() end) return ss end local items, width = self:shapeToken(" ", options) if not width and not items[1] then SU.warn("Could not measure the width of a space") return SILE.length() end return shapespace(width and width.length or items[1].width) end, measureChar = function (self, char) local options = SILE.font.loadDefaults({}) options.tracking = SILE.settings.get("shaper.tracking") local items = self:shapeToken(char, options) if #items > 0 then return { height = items[1].height, width = items[1].width } else SU.error("Unable to measure character", char) end end, -- Given a text and some font options, return a bunch of boxes shapeToken = function (_, _, _) SU.error("Abstract function shapeToken called", true) end, -- Given font options, select a font. We will handle -- caching here. Returns an arbitrary, implementation-specific -- object (ie a PAL for Pango, font number for libtexpdf, ...) getFace = function (_) SU.error("Abstract function getFace called", true) end, addShapedGlyphToNnodeValue = function (_, _, _) SU.error("Abstract function addShapedGlyphToNnodeValue called", true) end, preAddNodes = function (_, _, _) end, createNnodes = function (self, token, options) options.tracking = SILE.settings.get("shaper.tracking") local items, _ = self:shapeToken(token, options) if #items < 1 then return {} end local lang = options.language SILE.languageSupport.loadLanguage(lang) local nodeMaker = SILE.nodeMakers[lang] or SILE.nodeMakers.unicode local nodes = {} for node in nodeMaker(options):iterator(items, token) do table.insert(nodes, node) end return nodes end, formNnode = function (self, contents, token, options) local nnodeContents = {} -- local glyphs = {} local totalWidth = 0 local totalDepth = 0 local totalHeight = 0 -- local glyphNames = {} local nnodeValue = { text = token, options = options, glyphString = {} } SILE.shaper:preAddNodes(contents, nnodeValue) local misfit = false if SILE.typesetter.frame and SILE.typesetter.frame:writingDirection() == "TTB" then if options.direction == "LTR" then misfit = true end else if options.direction == "TTB" then misfit = true end end for i = 1, #contents do local glyph = contents[i] if (options.direction == "TTB") ~= misfit then if glyph.width > totalHeight then totalHeight = glyph.width end totalWidth = totalWidth + glyph.height else if glyph.depth > totalDepth then totalDepth = glyph.depth end if glyph.height > totalHeight then totalHeight = glyph.height end totalWidth = totalWidth + glyph.width end self:addShapedGlyphToNnodeValue(nnodeValue, glyph) end table.insert(nnodeContents, SILE.nodefactory.hbox({ depth = totalDepth, height = totalHeight, misfit = misfit, width = SILE.length(totalWidth), value = nnodeValue })) return SILE.nodefactory.nnode({ nodes = nnodeContents, text = token, misfit = misfit, options = options, language = options.language }) end, makeSpaceNode = function (_, options, item) local width if SILE.settings.get("shaper.variablespaces") then width = shapespace(item.width) else width = SILE.shaper:measureSpace(options) end return SILE.nodefactory.glue(width) end })
fix(shaper): Fix line length calcs with negative width word spacing
fix(shaper): Fix line length calcs with negative width word spacing Corrects regression of #579 in f4a64e7d, primarily affects nastaliq with negative spaces between clusters.
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
5cc42a1d6356c952b94e7c4e399bf57f36c6bb79
nylon/debug.lua
nylon/debug.lua
-- Nylon Copyright (c) 2013 David M. Placek see [doc/license.txt] local Debug = {} local config = nil require 'nylon.syscore' local Nylon = {} -- require 'nylon.core'() local tbase = os.time() or 0 -- it's crazy, but if you have a system for whatever reason set to a really old date (probably pre-1970), os.time() returns nil. local tbasetick = NylonSysCore.uptime() local function openOutFile( name ) if config.outfile then config.outfile:close() end config.outfile = io.open( name, 'w' ) if not config.outfile then config.outfile = io.stdout end end --local logmsgndx = 2 local pluggable_log_io = function( groups, text ) -- logmsgndx = logmsgndx + 1 if not config.outfile then if not config.filename then config.filename = string.format('%s/%s.log', config.dir, config.name ) end openOutFile( config.filename ) end local tnow = (NylonSysCore.uptime() - tbasetick + tbase) local tnowfrac = math.fmod( tnow, 60) -- local dt = os.date( '*t', tnow ) config.outfile:write( os.date("%m%d %H:%M:", math.floor(tnow)) ) config.outfile:write( string.format("%05.3f ", tnowfrac ) ) local cord = Nylon.self if cord then -- config.outfile:write '<' config.outfile:write( cord.name ) config.outfile:write '/ ' end -- config.outfile:write( tostring(logmsgndx) ) config.outfile:write( string.format("{%s} ", groups) ) config.outfile:write( text ) config.outfile:write( '\n' ) config.outfile:flush() end local log_disable = { mbox = true, evt = true, ['trace,core,post'] = true } function Debug.configure( p ) -- print( 'Got call to debug.configur, p.name=%s', tostring(p.name) ) local o = {} if not (p and p.nocordcheck) then Nylon = require 'nylon.core'() end local lconfig = { dir = (os.getenv 'nylonloghome') or (os.getenv 'TEMP') or '/tmp', name = 'nylon' } config = lconfig if p and p.name then lconfig.name = p.name end lconfig.filename = string.format('%s/%s.log', lconfig.dir, lconfig.name ) if p and p.filename then lconfig.filename = p.filename end openOutFile( lconfig.filename ) return setmetatable( o, { __index = function(t,key) config = lconfig return Debug[key] end } ) end function Debug.log_active( grps ) if log_disable[grps] then return false else return true end end function Debug.log( grps, fmt, ... ) if not fmt then fmt = grps grps = 'debug' end if not Debug.log_active( grps ) then return end local formatted_msg local ok, err = pcall( function(...) formatted_msg = string.format( fmt, ... ) end, ... ) if ok then local info = debug.getinfo( 2, "Sln" ) pluggable_log_io( grps, string.format("%s:%d %s", info.short_src, info.currentline, formatted_msg ) ) else pluggable_log_io( 'error', string.format( '%s\n\t%s\n%s', err, (fmt or '[[NULL-FMT-STRING]]'), Debug.backtrace() ) ) end end function Debug.submodule( self, modname ) local logif = {} end Debug.setpluggable = { log_io = function( fn ) pluggable_log_io = fn end, } local function backtrace_msg_x_( ignoreLevels, returnOpt ) -- if dbgoff then -- dbgoff() -- end local traces = {} local fudge = ((returnOpt and 1) or 0) local tablePos = 1-fudge local level = 2 + (ignoreLevels or 0) local tailCallDepth = 0 while true do -- usw.log( "check level:" .. (level) ) local info = debug.getinfo( level, "Sln" ) if not info then break end -- usw.log( "level:" .. (level) .. " what:" .. (info.what) ) if info.what == 'tail' then tailCallDepth = tailCallDepth + 1 if (not gDebug) and (tailCallDepth > 100) then traces[tablePos] = '[TAIL CALL] x {{max depth exceeded}} (' .. (tailCallDepth) .. ')' break end else if tailCallDepth > 0 then traces[tablePos] = '[TAIL CALL] x ' .. (tailCallDepth) tailCallDepth = 0 tablePos = tablePos + 1 end if info.what == 'C' then traces[tablePos] = "C Function" else traces[tablePos] = string.format("[%s]:%d {%s}", info.short_src, (info.currentline or -1), --info.what, info.name or '???' )-- , info.func ) end tablePos = tablePos + 1 end level = level+1 end if returnOpt then return traces[0], table.concat( traces, "\n\t" ) -- {'foo','bar'} ) -- traces, "\n\t" ) else return table.concat( traces, "\n\t" ) -- {'foo','bar'} ) -- traces, "\n\t" ) end end function Debug.backtrace( ignoreLevels, returnOpt ) return backtrace_msg_x_( ignoreLevels, returnOpt ) end function Debug.deprecated( msg ) Debug.log('abnorm','Deprecated call%s\n\t%s', ((msg and ': ' .. msg) or ''), Debug.backtrace(2) ) end setmetatable( Debug, { __call = function( t, p ) return Debug.configure( p ) end }) return Debug
-- Nylon Copyright (c) 2013 David M. Placek see [doc/license.txt] local Debug = {} local config = nil require 'nylon.syscore' local Nylon = {} -- require 'nylon.core'() local tbase = os.time() or 0 -- it's crazy, but if you have a system for whatever reason set to a really old date (probably pre-1970), os.time() returns nil. local tbasetick = NylonSysCore.uptime() local function openOutFile( name ) if config.outfile then config.outfile:close() end config.outfile = io.open( name, 'w' ) if not config.outfile then config.outfile = io.stdout end end --local logmsgndx = 2 local pluggable_log_io = function( groups, text ) -- logmsgndx = logmsgndx + 1 if not config.outfile then if not config.filename then config.filename = string.format('%s/%s.log', config.dir, config.name ) end openOutFile( config.filename ) end local tnow = (NylonSysCore.uptime() - tbasetick + tbase) local tnowfrac = math.fmod( tnow, 60) -- local dt = os.date( '*t', tnow ) config.outfile:write( os.date("%m%d %H:%M:", math.floor(tnow)) ) config.outfile:write( string.format("%06.3f ", tnowfrac ) ) local cord = Nylon.self if cord then -- config.outfile:write '<' config.outfile:write( cord.name ) config.outfile:write '/ ' end -- config.outfile:write( tostring(logmsgndx) ) config.outfile:write( string.format("{%s} ", groups) ) config.outfile:write( text ) config.outfile:write( '\n' ) config.outfile:flush() end local log_disable = { mbox = true, evt = true, ['trace,core,post'] = true } local progname = '' function Debug.configure( p ) -- print( 'Got call to debug.configur, p.name=%s', tostring(p.name) ) local o = {} if not (p and (p.nocordcheck or p.program)) then Nylon = require 'nylon.core'() end local lconfig = { dir = (os.getenv 'nylonloghome') or (os.getenv 'TEMP') or '/tmp', name = 'nylon' } config = lconfig if p and p.name then lconfig.name = p.name end if p and p.program then progname = p.program .. '/' end lconfig.filename = string.format('%s/%s%s.log', lconfig.dir, progname, lconfig.name ) if p and p.filename then lconfig.filename = p.filename end openOutFile( lconfig.filename ) return setmetatable( o, { __index = function(t,key) config = lconfig return Debug[key] end } ) end function Debug.log_active( grps ) if log_disable[grps] then return false else return true end end function Debug.log( grps, fmt, ... ) if not fmt then fmt = grps grps = 'debug' end if not Debug.log_active( grps ) then return end local formatted_msg local ok, err = pcall( function(...) formatted_msg = string.format( fmt, ... ) end, ... ) if ok then local info = debug.getinfo( 2, "Sln" ) pluggable_log_io( grps, string.format("%s:%d %s", info.short_src, info.currentline, formatted_msg ) ) else pluggable_log_io( 'error', string.format( '%s\n\t%s\n%s', err, (fmt or '[[NULL-FMT-STRING]]'), Debug.backtrace() ) ) end end function Debug.submodule( self, modname ) local logif = {} end Debug.setpluggable = { log_io = function( fn ) pluggable_log_io = fn end, } local function backtrace_msg_x_( ignoreLevels, returnOpt ) -- if dbgoff then -- dbgoff() -- end local traces = {} local fudge = ((returnOpt and 1) or 0) local tablePos = 1-fudge local level = 2 + (ignoreLevels or 0) local tailCallDepth = 0 while true do -- usw.log( "check level:" .. (level) ) local info = debug.getinfo( level, "Sln" ) if not info then break end -- usw.log( "level:" .. (level) .. " what:" .. (info.what) ) if info.what == 'tail' then tailCallDepth = tailCallDepth + 1 if (not gDebug) and (tailCallDepth > 100) then traces[tablePos] = '[TAIL CALL] x {{max depth exceeded}} (' .. (tailCallDepth) .. ')' break end else if tailCallDepth > 0 then traces[tablePos] = '[TAIL CALL] x ' .. (tailCallDepth) tailCallDepth = 0 tablePos = tablePos + 1 end if info.what == 'C' then traces[tablePos] = "C Function" else traces[tablePos] = string.format("[%s]:%d {%s}", info.short_src, (info.currentline or -1), --info.what, info.name or '???' )-- , info.func ) end tablePos = tablePos + 1 end level = level+1 end if returnOpt then return traces[0], table.concat( traces, "\n\t" ) -- {'foo','bar'} ) -- traces, "\n\t" ) else return table.concat( traces, "\n\t" ) -- {'foo','bar'} ) -- traces, "\n\t" ) end end function Debug.backtrace( ignoreLevels, returnOpt ) return backtrace_msg_x_( ignoreLevels, returnOpt ) end function Debug.deprecated( msg ) Debug.log('abnorm','Deprecated call%s\n\t%s', ((msg and ': ' .. msg) or ''), Debug.backtrace(2) ) end setmetatable( Debug, { __call = function( t, p ) return Debug.configure( p ) end }) return Debug
fix to allow setting of program to move all logfiles to a subdirectory
fix to allow setting of program to move all logfiles to a subdirectory
Lua
mit
dmattp/nylon,dmattp/nylon
71c2b3a137a6dcb78cf19195b60dbcb1d1d1972c
test/test_fl_create.lua
test/test_fl_create.lua
--[[---------------------------------------------------------------------------- --- @file test_fl_create.lua --- @brief Unit test for fl create command. ----------------------------------------------------------------------------]]-- local Helpers = require "test.helpers" local UUID = Helpers.FAKE_UUID local UUID_HEAD = Helpers.FAKE_UUID_HEAD local UUID_TAIL = Helpers.FAKE_UUID_TAIL local ROOT = Helpers.FAKE_ROOT local TIMESTAMP = Helpers.FAKE_OS_TIME local createMocks = Helpers.createMocks local unwrap = Helpers.unwrap local restoreBackup = Helpers.restoreBackup local revertMocks = Helpers.revertMocks local CARDS = ROOT .. "/.fl/cards/" local META = ROOT .. "/.fl/meta/" local BOARDS = ROOT .. "/.fl/boards/" local CARD_MD = CARDS .. UUID_HEAD .. "/" .. UUID_TAIL .. ".md" describe("fácil's create command", function() local fl -- Core module of fácil. local uuid -- uuid library. local lfs -- LuaFileSystem library. before_each(function() -- Load and configure fácil module. fl = require "facil" -- Loads explicitly system libraries for mocking. uuid = require "uuid" lfs = require "lfs" end) after_each(function() -- Unload modules. fl, package.loaded["facil"], package.loaded["facil.core"] = nil, nil, nil uuid, package.loaded["uuid"] = nil, nil lfs, package.loaded["lfs"] = nil, nil -- Removes all stubs and spies. unwrap(io) unwrap(os) end) it("exists", function() assert.is.not_equal(fl.create, nil) end) it("fails with empty arguments", function() local result, details = fl.create() assert.is.equal(result, nil) assert.is.equal(details, "Invalid argument.") end) it("returns error on invalid file creation", function() local backup = createMocks(lfs, uuid, nil, os) io = mock(io, true) local result, details = fl.create("name") assert.is.equal(result, nil) assert.is.equal(details:find("Can't create file: "), 1) io = unwrap(io) os = unwrap(os) revertMocks(backup, lfs, uuid, nil, os) end) it("creates card and meta with valid names", function() local backup = createMocks(lfs, uuid, nil, os) io = mock(io, true) local result, details = fl.create("new card") -- Stub will return nil on io.open always, -- as result fl.create should fail assert.is.equal(result, nil) assert.is.equal(details:find("Can't create file: "), 1) -- Check that stub was called with correct arguments. assert.stub(io.open).was.called(1) assert.stub(io.open).was.called_with(CARD_MD, "w") io = unwrap(io) revertMocks(backup, lfs, uuid, nil, os) end) it("returns error if didn't get current directory", function() io = mock(io, true) lfs = mock(lfs, true) local result, description = fl.create("wrong") assert.is.equal(result, nil) assert.is.equal("Can't generate file name for card.", description) lfs = unwrap(lfs) io = unwrap(io) end) it("creates required directories", function() local backup = createMocks(lfs, uuid, nil, os) io = mock(io, true) fl.create("task #1") -- Restore stub from backup to be able to call was.called restoreBackup(backup, lfs) assert.stub(lfs.mkdir).was.called(1) assert.stub(lfs.mkdir).was.called_with(CARDS .. UUID_HEAD .. "/") io = unwrap(io) revertMocks(backup, lfs, uuid, nil, os) end) it("fills card with markdown template", function() local fileHistory = {} local backup = createMocks(lfs, uuid, io, os, fileHistory) fl.create("markdown test card") local template = require "facil.template.md" assert.is.not_equal(fileHistory.write, nil) assert.is.not_equal(fileHistory.write[1], nil) assert.is.not_equal(fileHistory.write[1][1], nil) assert.is.equal(template.value, fileHistory.write[1][1]) revertMocks(backup, lfs, uuid, io, os) end) it("opens $EDITOR to edit just created card.", function() local backup = createMocks(lfs, uuid, io, os) fl.create("opens edior") assert.stub(os.execute).was.called(1) assert.stub(os.execute).was.called_with("$EDITOR " .. CARD_MD) revertMocks(backup, lfs, uuid, io, os) end) it("creates required directories for meta data", function() local backup = createMocks(lfs, uuid, io, os) fl.create("meta data") -- Restore stub from backup to be able to call was.called restoreBackup(backup, lfs) assert.stub(lfs.mkdir).was.called() assert.stub(lfs.mkdir).was.called_with(META .. UUID_HEAD .. "/") revertMocks(backup, lfs, uuid, io, os) end) it("creates metafile for card", function() local fileHistory = {} local backup = createMocks(lfs, uuid, io, os, fileHistory) local expected = [[ return { id = aaaa-bbbb-cccc-dddd, name = meta file, created = 1234567 }]] fl.create("meta file") assert.is.not_equal(fileHistory.write, nil) assert.is.not_equal(fileHistory.write[2], nil) assert.is.not_equal(fileHistory.write[2][1], nil) assert.is.equal(expected, fileHistory.write[2][1]) revertMocks(backup, lfs, uuid, io, os) end) it("returns id of new card", function() local backup = createMocks(lfs, uuid, io, os) local code, id = fl.create("create returns id") assert.is.equal(true, code) assert.is.equal(UUID, id) Helpers.revertMocks(backup, lfs, uuid, io, os) end) it("sticks new card onto backlog board", function() local backup = createMocks(lfs, uuid, io, os) fl.create("new card to backlog") restoreBackup(backup, nil, nil, io) assert.stub(io.open).was.called_with(BOARDS .. "backlog/" .. UUID, "w") revertMocks(backup, lfs, uuid, io, os) end) it("puts timestamp into marker file inside backlog", function() local fileHistory = {} local backup = createMocks(lfs, uuid, io, os, fileHistory) fl.create("timestamp in backlog") assert.is.not_equal(fileHistory.write, nil) assert.is.not_equal(fileHistory.write[3], nil) assert.is.not_equal(fileHistory.write[3][1], nil) assert.is.equal(tostring(TIMESTAMP), fileHistory.write[3][1]) revertMocks(backup, lfs, uuid, io, os) end) end)
--[[---------------------------------------------------------------------------- --- @file test_fl_create.lua --- @brief Unit test for fl create command. ----------------------------------------------------------------------------]]-- local Helpers = require "test.helpers" local UUID = Helpers.FAKE_UUID local UUID_HEAD = Helpers.FAKE_UUID_HEAD local UUID_TAIL = Helpers.FAKE_UUID_TAIL local ROOT = Helpers.FAKE_ROOT local TIMESTAMP = Helpers.FAKE_OS_TIME local createMocks = Helpers.createMocks local unwrap = Helpers.unwrap local restoreBackup = Helpers.restoreBackup local revertMocks = Helpers.revertMocks local CARDS = ROOT .. "/.fl/cards/" local META = ROOT .. "/.fl/meta/" local BOARDS = ROOT .. "/.fl/boards/" local CARD_MD = CARDS .. UUID_HEAD .. "/" .. UUID_TAIL .. ".md" describe("fácil's create command", function() local fl -- Core module of fácil. local uuid -- uuid library. local lfs -- LuaFileSystem library. before_each(function() -- Load and configure fácil module. fl = require "facil" -- Loads explicitly system libraries for mocking. uuid = require "uuid" lfs = require "lfs" end) after_each(function() -- Unload modules. fl, package.loaded["facil"], package.loaded["facil.core"] = nil, nil, nil uuid, package.loaded["uuid"] = nil, nil lfs, package.loaded["lfs"] = nil, nil -- Removes all stubs and spies. unwrap(io) unwrap(os) end) it("exists", function() assert.is.not_equal(fl.create, nil) end) it("fails with empty arguments", function() local result, details = fl.create() assert.is.equal(result, nil) assert.is.equal(details, "Invalid argument.") end) it("returns error on invalid file creation", function() local backup = createMocks(lfs, uuid, nil, os) io = mock(io, true) local result, details = fl.create("name") assert.is.equal(result, nil) assert.is.equal(details:find("Can't create file: "), 1) io = unwrap(io) os = unwrap(os) revertMocks(backup, lfs, uuid, nil, os) end) it("creates card and meta with valid names", function() local backup = createMocks(lfs, uuid, nil, os) io = mock(io, true) local result, details = fl.create("new card") -- Stub will return nil on io.open always, -- as result fl.create should fail assert.is.equal(result, nil) assert.is.equal(details:find("Can't create file: "), 1) -- Check that stub was called with correct arguments. assert.stub(io.open).was.called(1) assert.stub(io.open).was.called_with(CARD_MD, "w") io = unwrap(io) revertMocks(backup, lfs, uuid, nil, os) end) it("returns error if didn't get current directory", function() io = mock(io, true) lfs = mock(lfs, true) local result, description = fl.create("wrong") assert.is.equal(result, nil) assert.is.equal("Can't generate file name for card.", description) lfs = unwrap(lfs) io = unwrap(io) end) it("creates required directories", function() local backup = createMocks(lfs, uuid, nil, os) io = mock(io, true) fl.create("task #1") -- Restore stub from backup to be able to call was.called restoreBackup(backup, lfs) assert.stub(lfs.mkdir).was.called(1) assert.stub(lfs.mkdir).was.called_with(CARDS .. UUID_HEAD .. "/") io = unwrap(io) revertMocks(backup, lfs, uuid, nil, os) end) it("fills card with markdown template", function() local fileHistory = {} local backup = createMocks(lfs, uuid, io, os, fileHistory) fl.create("markdown test card") local template = require "facil.template.md" assert.is.not_equal(fileHistory.write, nil) assert.is.not_equal(fileHistory.write[1], nil) assert.is.not_equal(fileHistory.write[1][1], nil) assert.is.equal(template.value, fileHistory.write[1][1]) revertMocks(backup, lfs, uuid, io, os) end) it("opens $EDITOR to edit just created card.", function() local backup = createMocks(lfs, uuid, io, os) fl.create("opens edior") assert.stub(os.execute).was.called(1) assert.stub(os.execute).was.called_with("$EDITOR " .. CARD_MD) revertMocks(backup, lfs, uuid, io, os) end) it("creates required directories for meta data", function() local backup = createMocks(lfs, uuid, io, os) fl.create("meta data") -- Restore stub from backup to be able to call was.called restoreBackup(backup, lfs) assert.stub(lfs.mkdir).was.called() assert.stub(lfs.mkdir).was.called_with(META .. UUID_HEAD .. "/") revertMocks(backup, lfs, uuid, io, os) end) it("creates metafile for card", function() local fileHistory = {} local backup = createMocks(lfs, uuid, io, os, fileHistory) local taskName = "meta file" local expected = table.concat{ "return {", "\n", " id = ", UUID, ",", "\n", " name = ", taskName, ",", "\n", " created = ", TIMESTAMP, "\n", "}" } fl.create(taskName) assert.is.not_equal(fileHistory.write, nil) assert.is.not_equal(fileHistory.write[2], nil) assert.is.not_equal(fileHistory.write[2][1], nil) assert.is.equal(expected, fileHistory.write[2][1]) revertMocks(backup, lfs, uuid, io, os) end) it("returns id of new card", function() local backup = createMocks(lfs, uuid, io, os) local code, id = fl.create("create returns id") assert.is.equal(true, code) assert.is.equal(UUID, id) Helpers.revertMocks(backup, lfs, uuid, io, os) end) it("sticks new card onto backlog board", function() local backup = createMocks(lfs, uuid, io, os) fl.create("new card to backlog") restoreBackup(backup, nil, nil, io) assert.stub(io.open).was.called_with(BOARDS .. "backlog/" .. UUID, "w") revertMocks(backup, lfs, uuid, io, os) end) it("puts timestamp into marker file inside backlog", function() local fileHistory = {} local backup = createMocks(lfs, uuid, io, os, fileHistory) fl.create("timestamp in backlog") assert.is.not_equal(fileHistory.write, nil) assert.is.not_equal(fileHistory.write[3], nil) assert.is.not_equal(fileHistory.write[3][1], nil) assert.is.equal(tostring(TIMESTAMP), fileHistory.write[3][1]) revertMocks(backup, lfs, uuid, io, os) end) end)
Fix: hardcoded valu in fl create test.
Fix: hardcoded valu in fl create test.
Lua
mit
norefle/facil
87371093d28d58b48447c866773c9a4d48753fd7
UCDplaytime/server.lua
UCDplaytime/server.lua
-- Global variables local playerTickCount = {} -- Events function onLogin(_, theCurrentAccount) if (not isGuestAccount(theCurrentAccount)) then source:setData("playtime", exports.UCDaccounts:GAD(source, "playtime"), true) playerTickCount[source] = getTickCount() end end addEventHandler("onPlayerLogin", root, onLogin) function onQuit() if (not exports.UCDaccounts:isPlayerLoggedIn(source)) then return end local pAccTime = exports.UCDaccounts:GAD(source, "playtime") local pPlayTime = math.floor((getTickCount() - playerTickCount[source]) / 1000) exports.UCDaccounts:SAD(source, "playtime", tonumber(pAccTime + pPlayTime)) playerTickCount[source] = nil end addEventHandler("onPlayerQuit", root, onQuit) function updateScoreboard() for _, plr in pairs(Element.getAllByType("player")) do if (not exports.UCDaccounts:isPlayerLoggedIn(plr)) then return end if (not playerTickCount[plr]) then playerTickCount[plr] = getTickCount() end local currentTime = math.floor((getTickCount() - playerTickCount[plr]) / 1000) local totalTime = plr:getData("playtime") + currentTime plr:setData("dxscoreboard_playtime", exports.UCDutil:secondsToHoursMinutes(totalTime)) end end function onStart() for _, plr in pairs(Element.getAllByType("player")) do if (exports.UCDaccounts:isPlayerLoggedIn(plr)) then if (not playerTickCount[plr]) then playerTickCount[plr] = getTickCount() end plr:setData("playtime", exports.UCDaccounts:GAD(plr, "playtime"), true) end end updateScoreboard() setTimer(updateScoreboard, 900, 0) -- There is no need to define a variable for the timer but we might need this variable in the future. end addEventHandler("onResourceStart", resourceRoot, onStart) function onStop() for _, plr in pairs(Element.getAllByType("player")) do if (not exports.UCDaccounts:isPlayerLoggedIn(plr)) then local accPlayTime = exports.UCDaccounts:GAD(plr, "playtime") local currPlayTime = math.floor((getTickCount() - playerTickCount[plr]) / 1000) exports.UCDaccounts:SAD(plr, "playtime", tonumber(accPlayTime + currPlayTime)) playerTickCount[plr] = nil end end end addEventHandler("onResourceStop", resourceRoot, onStop)
-- Global variables local playerTickCount = {} -- Events function onLogin(_, theCurrentAccount) if (not isGuestAccount(theCurrentAccount)) then source:setData("playtime", exports.UCDaccounts:GAD(source, "playtime"), true) playerTickCount[source] = getTickCount() end end addEventHandler("onPlayerLogin", root, onLogin) function onQuit() if (not exports.UCDaccounts:isPlayerLoggedIn(source)) then return end local pAccTime = exports.UCDaccounts:GAD(source, "playtime") local pPlayTime = math.floor((getTickCount() - playerTickCount[source]) / 1000) exports.UCDaccounts:SAD(source, "playtime", tonumber(pAccTime + pPlayTime)) playerTickCount[source] = nil end addEventHandler("onPlayerQuit", root, onQuit) function updateScoreboard() for _, plr in pairs(Element.getAllByType("player")) do if (exports.UCDaccounts:isPlayerLoggedIn(plr)) then if (not playerTickCount[plr]) then playerTickCount[plr] = getTickCount() end local currentTime = math.floor((getTickCount() - playerTickCount[plr]) / 1000) local totalTime = plr:getData("playtime") + currentTime plr:setData("dxscoreboard_playtime", exports.UCDutil:secondsToHoursMinutes(totalTime)) end end end function onStart() for _, plr in pairs(Element.getAllByType("player")) do if (exports.UCDaccounts:isPlayerLoggedIn(plr)) then if (not playerTickCount[plr]) then playerTickCount[plr] = getTickCount() end plr:setData("playtime", exports.UCDaccounts:GAD(plr, "playtime"), true) end end updateScoreboard() setTimer(updateScoreboard, 900, 0) -- There is no need to define a variable for the timer but we might need this variable in the future. end addEventHandler("onResourceStart", resourceRoot, onStart) function onStop() for _, plr in pairs(Element.getAllByType("player")) do if (exports.UCDaccounts:isPlayerLoggedIn(plr)) then local accPlayTime = exports.UCDaccounts:GAD(plr, "playtime") local currPlayTime = math.floor((getTickCount() - playerTickCount[plr]) / 1000) exports.UCDaccounts:SAD(plr, "playtime", tonumber(accPlayTime + currPlayTime)) playerTickCount[plr] = nil end end end addEventHandler("onResourceStop", resourceRoot, onStop)
UCDplaytime
UCDplaytime - Fixed some monumental bugs where playtime would not save and would sometimes not update.
Lua
mit
nokizorque/ucd,nokizorque/ucd
145133a8380ed4162f1008a58e25fda8891e53c0
src/spy.lua
src/spy.lua
-- module will return spy table, and register its assertions with the main assert engine local assert = require('luassert.assert') local util = require('luassert.util') -- Spy metatable local spy_mt = { __call = function(self, ...) local arguments = {...} arguments.n = select('#',...) -- add argument count for trailing nils table.insert(self.calls, arguments) return self.callback(...) end } local spy -- must make local before defining table, because table contents refers to the table (recursion) spy = { new = function(callback) if not util.callable(callback) then error("Cannot spy on type '" .. type(callback) .. "', only on functions or callable elements", 2) end local s = setmetatable( { calls = {}, callback = callback, target_table = nil, -- these will be set when using 'spy.on' target_key = nil, revert = function(self) if not self.reverted then if self.target_table and self.target_key then self.target_table[self.target_key] = self.callback end self.reverted = true end return self.callback end, called = function(self, times, compare) if times or compare then local compare = compare or function(count, expected) return count == expected end return compare(#self.calls, times), #self.calls end return (#self.calls > 0), #self.calls end, called_with = function(self, args) for _,v in ipairs(self.calls) do if util.deepcompare(v, args) then return true end end return false end }, spy_mt) assert:add_spy(s) -- register with the current state return s end, is_spy = function(object) return type(object) == "table" and getmetatable(object) == spy_mt end, on = function(target_table, target_key) local s = spy.new(target_table[target_key]) target_table[target_key] = s -- store original data s.target_table = target_table s.target_key = target_key return s end } local function set_spy(state) end local function called_with(state, arguments) if rawget(state, "payload") and rawget(state, "payload").called_with then return state.payload:called_with(arguments) else error("'called_with' must be chained after 'spy(aspy)'") end end local function called(state, arguments, compare) local num_times = arguments[1] if state.payload and type(state.payload) == "table" and state.payload.called then local result, count = state.payload:called(num_times, compare) arguments[1] = tostring(arguments[1]) table.insert(arguments, 2, tostring(count)) arguments.n = arguments.n + 1 arguments.nofmt = arguments.nofmt or {} arguments.nofmt[1] = true arguments.nofmt[2] = true return result elseif state.payload and type(state.payload) == "function" then error("When calling 'spy(aspy)', 'aspy' must not be the original function, but the spy function replacing the original") else error("'called' must be chained after 'spy(aspy)'") end end local function called_at_least(state, arguments) return called(state, arguments, function(count, expected) return count >= expected end) end local function called_at_most(state, arguments) return called(state, arguments, function(count, expected) return count <= expected end) end local function called_more_than(state, arguments) return called(state, arguments, function(count, expected) return count > expected end) end local function called_less_than(state, arguments) return called(state, arguments, function(count, expected) return count < expected end) end assert:register("modifier", "spy", set_spy) assert:register("assertion", "called_with", called_with, "assertion.called_with.positive", "assertion.called_with.negative") assert:register("assertion", "called", called, "assertion.called.positive", "assertion.called.negative") assert:register("assertion", "called_at_least", called_at_least, "assertion.called_at_least.positive", "assertion.called_at_least.negative") assert:register("assertion", "called_at_most", called_at_most, "assertion.called_at_most.positive", "assertion.called_at_most.negative") assert:register("assertion", "called_more_than", called_more_than, "assertion.called_more_than.positive", "assertion.called_more_than.negative") assert:register("assertion", "called_less_than", called_less_than, "assertion.called_less_than.positive", "assertion.called_less_than.negative") return spy
-- module will return spy table, and register its assertions with the main assert engine local assert = require('luassert.assert') local util = require('luassert.util') -- Spy metatable local spy_mt = { __call = function(self, ...) local arguments = {...} arguments.n = select('#',...) -- add argument count for trailing nils table.insert(self.calls, arguments) return self.callback(...) end } local spy -- must make local before defining table, because table contents refers to the table (recursion) spy = { new = function(callback) if not util.callable(callback) then error("Cannot spy on type '" .. type(callback) .. "', only on functions or callable elements", 2) end local s = setmetatable( { calls = {}, callback = callback, target_table = nil, -- these will be set when using 'spy.on' target_key = nil, revert = function(self) if not self.reverted then if self.target_table and self.target_key then self.target_table[self.target_key] = self.callback end self.reverted = true end return self.callback end, called = function(self, times, compare) if times or compare then local compare = compare or function(count, expected) return count == expected end return compare(#self.calls, times), #self.calls end return (#self.calls > 0), #self.calls end, called_with = function(self, args) for _,v in ipairs(self.calls) do if util.deepcompare(v, args) then return true end end return false end }, spy_mt) assert:add_spy(s) -- register with the current state return s end, is_spy = function(object) return type(object) == "table" and getmetatable(object) == spy_mt end, on = function(target_table, target_key) local s = spy.new(target_table[target_key]) target_table[target_key] = s -- store original data s.target_table = target_table s.target_key = target_key return s end } local function set_spy(state) end local function called_with(state, arguments) if rawget(state, "payload") and rawget(state, "payload").called_with then return state.payload:called_with(arguments) else error("'called_with' must be chained after 'spy(aspy)'") end end local function called(state, arguments, compare) local num_times = arguments[1] if not num_times and not state.mod then state.mod = true num_times = 0 end if state.payload and type(state.payload) == "table" and state.payload.called then local result, count = state.payload:called(num_times, compare) arguments[1] = tostring(num_times or ">0") table.insert(arguments, 2, tostring(count)) arguments.n = arguments.n + 1 arguments.nofmt = arguments.nofmt or {} arguments.nofmt[1] = true arguments.nofmt[2] = true return result elseif state.payload and type(state.payload) == "function" then error("When calling 'spy(aspy)', 'aspy' must not be the original function, but the spy function replacing the original") else error("'called' must be chained after 'spy(aspy)'") end end local function called_at_least(state, arguments) return called(state, arguments, function(count, expected) return count >= expected end) end local function called_at_most(state, arguments) return called(state, arguments, function(count, expected) return count <= expected end) end local function called_more_than(state, arguments) return called(state, arguments, function(count, expected) return count > expected end) end local function called_less_than(state, arguments) return called(state, arguments, function(count, expected) return count < expected end) end assert:register("modifier", "spy", set_spy) assert:register("assertion", "called_with", called_with, "assertion.called_with.positive", "assertion.called_with.negative") assert:register("assertion", "called", called, "assertion.called.positive", "assertion.called.negative") assert:register("assertion", "called_at_least", called_at_least, "assertion.called_at_least.positive", "assertion.called_at_least.negative") assert:register("assertion", "called_at_most", called_at_most, "assertion.called_at_most.positive", "assertion.called_at_most.negative") assert:register("assertion", "called_more_than", called_more_than, "assertion.called_more_than.positive", "assertion.called_more_than.negative") assert:register("assertion", "called_less_than", called_less_than, "assertion.called_less_than.positive", "assertion.called_less_than.negative") return spy
Fix confusing error messages for `called` asserts
Fix confusing error messages for `called` asserts This fixes the `called` error messages to print either `0` or `>0` instead of `nil` for the expected call count. Hence, the following error messages: - "Expected not to be called exactly nil time(s), but it was." - "Expected to be called nil time(s), but was called 0 time(s)" are transformed into the following: - "Expected to be called 0 time(s), but was called 1 time(s)" - "Expected to be called >0 time(s), but was called 0 time(s)"
Lua
mit
mpeterv/luassert,ZyX-I/luassert,o-lim/luassert
06730642de02d064de022a28db20ea1554363dab
ui/keys.lua
ui/keys.lua
local bindings = {} -- key -> command map function ui.readkey() tty.flip() local key = tty.readkey() return bindings[key] or 'key:'..key end local function set(...) local R = {} for _,v in ipairs {...} do R[v] = true end return R end -- Keybinding validation. -- Checks that all critical keys are bound, and that no key is bound to more than -- one command. function ui.validate_bindings() local errors = {} local critical = set('activate', 'cancel', 'up', 'down', 'left', 'right') local seen = {} for setting in settings.get('Keybinds') do if critical[setting.command] and #setting() == 0 then table.insert(errors, 'Critical command [%s] is unbound' % setting.command) else for _,key in ipairs(setting()) do if seen[key] then table.insert(errors, 'Key [%s] is bound to both [%s] and [%s]' % { key, seen[key].command, setting.command }) else seen[key] = setting end end end end if #errors > 0 then return nil,errors else return true end end function ui.update_bindings() bindings = {} for setting in settings.get('Keybinds') do for _,key in ipairs(setting()) do bindings[key] = setting.command end end end -- -- Everything below this line is related to loading the default keybinds and the -- key remapping UI elements from ui.key_defaults -- local keybind_tree = require 'ui.key_defaults' keybind_tree.name = 'Keybinds' settings.Category { name = 'Keybinds'; tree = function(self) return keybind_tree end; save = function(self) local r,e = ui.validate_bindings() if not r then e.colour = { 255, 0, 0 } e.readonly = true table.insert(e, '') table.insert(e, 'Keybinds not saved.') ui.message('Error', e) return false end ui.update_bindings() return settings.Category.save(self) end; } local KeySetting = settings.Raw:subclass {} function KeySetting:show() return '[%6s][%6s]' % { self.value[1] or '------', self.value[2] or '------', } end function KeySetting:activate() local width = #self.name+4; ui.box(ui.centered(width, 3), self.name) tty.flip() local key = tty.readkey() if key == self.value[1] then return end self:set { key, self.value[1] } end function KeySetting:reset() self:set {} end for _,category in ipairs(keybind_tree) do for i,command in ipairs(category) do category[i] = KeySetting { category = 'Keybinds'; name = command.name; command = command.command; value = command.keys; } end end ui.update_bindings()
local bindings = {} -- key -> command map function ui.readkey() tty.flip() local key = tty.readkey() return bindings[key] or 'key:'..key end local function set(...) local R = {} for _,v in ipairs {...} do R[v] = true end return R end -- Keybinding validation. -- Checks that all critical keys are bound, and that no key is bound to more than -- one command. function ui.validate_bindings() local errors = {} local critical = set('activate', 'cancel', 'up', 'down', 'left', 'right') local seen = {} for setting in settings.get('Keybinds') do if critical[setting.command] and #setting() == 0 then table.insert(errors, 'Critical command [%s] is unbound' % setting.command) else for _,key in ipairs(setting()) do if seen[key] then table.insert(errors, 'Key [%s] is bound to both [%s] and [%s]' % { key, seen[key].command, setting.command }) else seen[key] = setting end end end end if #errors > 0 then return nil,errors else return true end end function ui.update_bindings() bindings = {} for setting in settings.get('Keybinds') do for _,key in ipairs(setting()) do bindings[key] = setting.command end end end -- -- Everything below this line is related to loading the default keybinds and the -- key remapping UI elements from ui.key_defaults -- local keybind_tree = require 'ui.key_defaults' keybind_tree.name = 'Keybinds' settings.Category { name = 'Keybinds'; tree = function(self) return keybind_tree end; save = function(self) local r,e = ui.validate_bindings() if not r then e.colour = { 255, 0, 0 } e.readonly = true table.insert(e, '') table.insert(e, 'Keybinds not saved.') ui.message('Error', e) return false end ui.update_bindings() return settings.Category.save(self) end; load = function(self) settings.Category.load(self) ui.update_bindings() end; } local KeySetting = settings.Raw:subclass {} function KeySetting:show() return '[%6s][%6s]' % { self.value[1] or '------', self.value[2] or '------', } end function KeySetting:activate() local width = #self.name+4; ui.box(ui.centered(width, 3), self.name) tty.flip() local key = tty.readkey() if key == self.value[1] then return end self:set { key, self.value[1] } end function KeySetting:reset() self:set {} end for _,category in ipairs(keybind_tree) do for i,command in ipairs(category) do category[i] = KeySetting { category = 'Keybinds'; name = command.name; command = command.command; value = command.keys; } end end ui.update_bindings()
Fix error where keybinds weren't properly loaded
Fix error where keybinds weren't properly loaded
Lua
mit
ToxicFrog/ttymor
91d378a86ef6dfd34f80ad10bb83ec3b5fd14a72
src/ssl.lua
src/ssl.lua
------------------------------------------------------------------------------ -- LuaSec 0.5 -- Copyright (C) 2006-2014 Bruno Silvestre -- ------------------------------------------------------------------------------ local core = require("ssl.core") local context = require("ssl.context") local x509 = require("ssl.x509") -- We must prevent the contexts to be collected before the connections, -- otherwise the C registry will be cleared. local registry = setmetatable({}, {__mode="k"}) -- -- -- local function optexec(func, param, ctx) if param then if type(param) == "table" then return func(ctx, unpack(param)) else return func(ctx, param) end end return true end -- -- -- local function newcontext(cfg) local succ, msg, ctx -- Create the context ctx, msg = context.create(cfg.protocol) if not ctx then return nil, msg end -- Mode succ, msg = context.setmode(ctx, cfg.mode) if not succ then return nil, msg end -- Load the key if cfg.key then if cfg.password and type(cfg.password) ~= "function" and type(cfg.password) ~= "string" then return nil, "invalid password type" end succ, msg = context.loadkey(ctx, cfg.key, cfg.password) if not succ then return nil, msg end end -- Load the certificate if cfg.certificate then succ, msg = context.loadcert(ctx, cfg.certificate) if not succ then return nil, msg end if cfg.key and context.checkkey then succ = context.checkkey(ctx) if not succ then return nil, "private key does not match public key" end end end -- Load the CA certificates if cfg.cafile or cfg.capath then succ, msg = context.locations(ctx, cfg.cafile, cfg.capath) if not succ then return nil, msg end end -- Set SSL ciphers if cfg.ciphers then succ, msg = context.setcipher(ctx, cfg.ciphers) if not succ then return nil, msg end end -- Set the verification options succ, msg = optexec(context.setverify, cfg.verify, ctx) if not succ then return nil, msg end -- Set SSL options succ, msg = optexec(context.setoptions, cfg.options, ctx) if not succ then return nil, msg end -- Set the depth for certificate verification if cfg.depth then succ, msg = context.setdepth(ctx, cfg.depth) if not succ then return nil, msg end end -- NOTE: Setting DH parameters and elliptic curves needs to come after -- setoptions(), in case the user has specified the single_{dh,ecdh}_use -- options. -- Set DH parameters if cfg.dhparam then if type(cfg.dhparam) ~= "function" then return nil, "invalid DH parameter type" end context.setdhparam(ctx, cfg.dhparam) end -- Set elliptic curve if cfg.curve then succ, msg = context.setcurve(ctx, cfg.curve) if not succ then return nil, msg end end -- Set extra verification options if cfg.verifyext and ctx.setverifyext then succ, msg = optexec(ctx.setverifyext, cfg.verifyext, ctx) if not succ then return nil, msg end end return ctx end -- -- -- local function wrap(sock, cfg) local ctx, msg if type(cfg) == "table" then ctx, msg = newcontext(cfg) if not ctx then return nil, msg end else ctx = cfg end local s, msg = core.create(ctx) if s then core.setfd(s, sock:getfd()) sock:setfd(-1) registry[s] = ctx return s end return nil, msg end -- -- Extract connection information. -- local function info(ssl, field) local str, comp, err, protocol comp, err = core.compression(ssl) if err then return comp, err end -- Avoid parser if field == "compression" then return comp end local info = {compression = comp} str, info.bits, info.algbits, protocol = core.info(ssl) if str then info.cipher, info.protocol, info.key, info.authentication, info.encryption, info.mac = string.match(str, "^(%S+)%s+(%S+)%s+Kx=(%S+)%s+Au=(%S+)%s+Enc=(%S+)%s+Mac=(%S+)") info.export = (string.match(str, "%sexport%s*$") ~= nil) end if protocol then info.protocol = protocol end if field then return info[field] end -- Empty? return ( (next(info)) and info ) end -- -- Set method for SSL connections. -- core.setmethod("info", info) -------------------------------------------------------------------------------- -- Export module -- local _M = { _VERSION = "0.5", _COPYRIGHT = core.copyright(), loadcertificate = x509.load, newcontext = newcontext, wrap = wrap, } return _M
------------------------------------------------------------------------------ -- LuaSec 0.5 -- Copyright (C) 2006-2014 Bruno Silvestre -- ------------------------------------------------------------------------------ local core = require("ssl.core") local context = require("ssl.context") local x509 = require("ssl.x509") local unpack = table.unpack or unpack -- We must prevent the contexts to be collected before the connections, -- otherwise the C registry will be cleared. local registry = setmetatable({}, {__mode="k"}) -- -- -- local function optexec(func, param, ctx) if param then if type(param) == "table" then return func(ctx, unpack(param)) else return func(ctx, param) end end return true end -- -- -- local function newcontext(cfg) local succ, msg, ctx -- Create the context ctx, msg = context.create(cfg.protocol) if not ctx then return nil, msg end -- Mode succ, msg = context.setmode(ctx, cfg.mode) if not succ then return nil, msg end -- Load the key if cfg.key then if cfg.password and type(cfg.password) ~= "function" and type(cfg.password) ~= "string" then return nil, "invalid password type" end succ, msg = context.loadkey(ctx, cfg.key, cfg.password) if not succ then return nil, msg end end -- Load the certificate if cfg.certificate then succ, msg = context.loadcert(ctx, cfg.certificate) if not succ then return nil, msg end if cfg.key and context.checkkey then succ = context.checkkey(ctx) if not succ then return nil, "private key does not match public key" end end end -- Load the CA certificates if cfg.cafile or cfg.capath then succ, msg = context.locations(ctx, cfg.cafile, cfg.capath) if not succ then return nil, msg end end -- Set SSL ciphers if cfg.ciphers then succ, msg = context.setcipher(ctx, cfg.ciphers) if not succ then return nil, msg end end -- Set the verification options succ, msg = optexec(context.setverify, cfg.verify, ctx) if not succ then return nil, msg end -- Set SSL options succ, msg = optexec(context.setoptions, cfg.options, ctx) if not succ then return nil, msg end -- Set the depth for certificate verification if cfg.depth then succ, msg = context.setdepth(ctx, cfg.depth) if not succ then return nil, msg end end -- NOTE: Setting DH parameters and elliptic curves needs to come after -- setoptions(), in case the user has specified the single_{dh,ecdh}_use -- options. -- Set DH parameters if cfg.dhparam then if type(cfg.dhparam) ~= "function" then return nil, "invalid DH parameter type" end context.setdhparam(ctx, cfg.dhparam) end -- Set elliptic curve if cfg.curve then succ, msg = context.setcurve(ctx, cfg.curve) if not succ then return nil, msg end end -- Set extra verification options if cfg.verifyext and ctx.setverifyext then succ, msg = optexec(ctx.setverifyext, cfg.verifyext, ctx) if not succ then return nil, msg end end return ctx end -- -- -- local function wrap(sock, cfg) local ctx, msg if type(cfg) == "table" then ctx, msg = newcontext(cfg) if not ctx then return nil, msg end else ctx = cfg end local s, msg = core.create(ctx) if s then core.setfd(s, sock:getfd()) sock:setfd(-1) registry[s] = ctx return s end return nil, msg end -- -- Extract connection information. -- local function info(ssl, field) local str, comp, err, protocol comp, err = core.compression(ssl) if err then return comp, err end -- Avoid parser if field == "compression" then return comp end local info = {compression = comp} str, info.bits, info.algbits, protocol = core.info(ssl) if str then info.cipher, info.protocol, info.key, info.authentication, info.encryption, info.mac = string.match(str, "^(%S+)%s+(%S+)%s+Kx=(%S+)%s+Au=(%S+)%s+Enc=(%S+)%s+Mac=(%S+)") info.export = (string.match(str, "%sexport%s*$") ~= nil) end if protocol then info.protocol = protocol end if field then return info[field] end -- Empty? return ( (next(info)) and info ) end -- -- Set method for SSL connections. -- core.setmethod("info", info) -------------------------------------------------------------------------------- -- Export module -- local _M = { _VERSION = "0.5", _COPYRIGHT = core.copyright(), loadcertificate = x509.load, newcontext = newcontext, wrap = wrap, } return _M
Fix unpack().
Fix unpack().
Lua
mit
Tieske/luasec,Tieske/luasec,fhaoquan/luasec,ignacio/luasec,masoudre11/luasec,xnyhps/luasec,kernelsauce/luasec,ignacio/luasec,kernelsauce/luasec,xnyhps/luasec,fhaoquan/luasec,masoudre11/luasec
20320c8e3255188f2f33fda3b40031a0b44abf8b
kong/runloop/plugin_servers/mp_rpc.lua
kong/runloop/plugin_servers/mp_rpc.lua
local msgpack = require "MessagePack" local mp_pack = msgpack.pack local mp_unpacker = msgpack.unpacker local Rpc = {} Rpc.__index = Rpc Rpc.notifications_callbacks = {} function Rpc.new(socket_path, notifications) kong.log.debug("mp_rpc.new: ", socket_path) return setmetatable({ socket_path = socket_path, msg_id = 0, notifications_callbacks = notifications, }, Rpc) end -- add MessagePack empty array/map msgpack.packers['function'] = function (buffer, f) f(buffer) end local function mp_empty_array(buffer) msgpack.packers['array'](buffer, {}, 0) end local function mp_empty_map(buffer) msgpack.packers['map'](buffer, {}, 0) end --- fix_mmap(t) : preprocess complex maps function Rpc.fix_mmap(t) local o, empty = {}, true for k, v in pairs(t) do empty = false if v == true then o[k] = mp_empty_array elseif type(v) == "string" then o[k] = { v } else o[k] = v end end if empty then return mp_empty_map end return o end function Rpc:call(method, ...) self.msg_id = self.msg_id + 1 local c, err = ngx.socket.connect("unix:" .. self.socket_path) if not c then kong.log.err("trying to connect: ", err) return nil, err end -- request: [ 0, msg_id, method, args ] local bytes, err = c:send(mp_pack({0, self.msg_id, method, {...}})) if not bytes then c:setkeepalive() return nil, err end local reader = mp_unpacker(function() return c:receiveany(4096) end) while true do -- read an MP object local ok, data = reader() if not ok then c:setkeepalive() return nil, "no data" end if data[1] == 2 then -- notification: [ 2, label, args ] self:notification(data[2], data[3]) else -- response: [ 1, msg_id, error, result ] assert(data[1] == 1, "RPC response expected from Go plugin server") assert(data[2] == self.msg_id, "unexpected RPC response ID from Go plugin server") -- it's our answer c:setkeepalive() if data[3] ~= nil then return nil, data[3] end return data[4] end end end function Rpc:notification(label, args) local f = self.notifications_callbacks[label] if f then f(self, args) end end return Rpc
local msgpack = require "MessagePack" local mp_pack = msgpack.pack local mp_unpacker = msgpack.unpacker local Rpc = {} Rpc.__index = Rpc Rpc.notifications_callbacks = {} function Rpc.new(socket_path, notifications) kong.log.debug("mp_rpc.new: ", socket_path) return setmetatable({ socket_path = socket_path, msg_id = 0, notifications_callbacks = notifications, }, Rpc) end -- add MessagePack empty array/map msgpack.packers['function'] = function (buffer, f) f(buffer) end local function mp_empty_array(buffer) msgpack.packers['array'](buffer, {}, 0) end local function mp_empty_map(buffer) msgpack.packers['map'](buffer, {}, 0) end --- fix_mmap(t) : preprocess complex maps function Rpc.fix_mmap(t) local o, empty = {}, true for k, v in pairs(t) do empty = false if v == true then o[k] = mp_empty_array elseif type(v) == "string" then o[k] = { v } else o[k] = v end end if empty then return mp_empty_map end return o end function Rpc:call(method, ...) self.msg_id = self.msg_id + 1 local msg_id = self.msg_id local c, err = ngx.socket.connect("unix:" .. self.socket_path) if not c then kong.log.err("trying to connect: ", err) return nil, err end -- request: [ 0, msg_id, method, args ] local bytes, err = c:send(mp_pack({0, msg_id, method, {...}})) if not bytes then c:setkeepalive() return nil, err end local reader = mp_unpacker(function() return c:receiveany(4096) end) while true do -- read an MP object local ok, data = reader() if not ok then c:setkeepalive() return nil, "no data" end if data[1] == 2 then -- notification: [ 2, label, args ] self:notification(data[2], data[3]) else -- response: [ 1, msg_id, error, result ] assert(data[1] == 1, "RPC response expected from Go plugin server") assert(data[2] == msg_id, "unexpected RPC response ID from Go plugin server") -- it's our answer c:setkeepalive() if data[3] ~= nil then return nil, data[3] end return data[4] end end end function Rpc:notification(label, args) local f = self.notifications_callbacks[label] if f then f(self, args) end end return Rpc
fix(ext-plugin): store msg_id scope per-connection, not per-pluginserver to avoid races with concurrent calls
fix(ext-plugin): store msg_id scope per-connection, not per-pluginserver to avoid races with concurrent calls
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
dd85bd5dd8d44dfff55787446ee5469d0972a688
lua_scripts/pathmaps/maemo/00_default.lua
lua_scripts/pathmaps/maemo/00_default.lua
-- Copyright (C) 2007 Lauri Leukkunen <[email protected]> -- Licensed under MIT license. tools = tools_root if (not tools) then tools = "/" end simple_chain = { next_chain = nil, binary = nil, rules = { {prefix = "/lib", map_to = target_root}, {prefix = "/usr/share/osso", map_to = target_root}, {prefix = "/usr/lib/perl", map_to = tools_root}, {prefix = "/usr/lib/dpkg", map_to = tools_root}, {prefix = "/usr/lib/apt", map_to = tools_root}, {prefix = "/usr/lib/cdbs", map_to = tools_root}, {prefix = "/usr/lib/libfakeroot", map_to = tools_root}, {prefix = "/usr/lib", map_to = target_root}, {prefix = "/usr/include", map_to = target_root}, {prefix = "/var/lib/apt", map_to = target_root}, {prefix = "/var/cache/apt", map_to = target_root}, {prefix = "/var/lib/dpkg", map_to = target_root}, {prefix = "/var/cache/dpkg", map_to = target_root}, {prefix = "/home/user", map_to = target_root}, {prefix = "/home", map_to = nil}, {prefix = "/host_usr", map_to = target_root}, {prefix = "/tmp", map_to = nil}, {prefix = "/dev", map_to = nil}, {prefix = "/proc", map_to = nil}, {prefix = "/sys", map_to = nil}, {prefix = "/etc/resolv.conf", map_to = nil}, {prefix = "/etc/apt", map_to = target_root}, {prefix = tools, map_to = nil}, {path = "/", map_to = nil}, {prefix = "/", map_to = tools_root} } } qemu_chain = { next_chain = nil, binary = basename(os.getenv("SBOX_CPUTRANSPARENCY_METHOD")), rules = { {prefix = "/lib", map_to = target_root}, {prefix = "/usr/lib", map_to = target_root}, {prefix = "/usr/local/lib", map_to = target_root}, {prefix = "/tmp", map_to = nil}, {prefix = "/dev", map_to = nil}, {prefix = "/proc", map_to = nil}, {prefix = "/sys", map_to = nil}, {prefix = "/etc/resolv.conf", map_to = nil}, {prefix = tools, map_to = nil}, {path = "/", map_to = nil}, {prefix = "/", map_to = tools_root} } } export_chains = { qemu_chain, simple_chain }
-- Copyright (C) 2007 Lauri Leukkunen <[email protected]> -- Licensed under MIT license. tools = tools_root if (not tools) then tools = "/" end simple_chain = { next_chain = nil, binary = nil, rules = { {prefix = "/lib", map_to = target_root}, {prefix = "/usr/share/osso", map_to = target_root}, {prefix = "/usr/lib/perl", map_to = tools_root}, {prefix = "/usr/lib/dpkg", map_to = tools_root}, {prefix = "/usr/lib/apt", map_to = tools_root}, {prefix = "/usr/lib/cdbs", map_to = tools_root}, {prefix = "/usr/lib/libfakeroot", map_to = tools_root}, {prefix = "/usr/X11R6/lib", map_to = target_root}, {prefix = "/usr/lib", map_to = target_root}, {prefix = "/usr/include", map_to = target_root}, {prefix = "/var/lib/apt", map_to = target_root}, {prefix = "/var/cache/apt", map_to = target_root}, {prefix = "/var/lib/dpkg", map_to = target_root}, {prefix = "/var/cache/dpkg", map_to = target_root}, {prefix = "/home/user", map_to = target_root}, {prefix = "/home", map_to = nil}, {prefix = "/host_usr", map_to = target_root}, {prefix = "/tmp", map_to = nil}, {prefix = "/dev", map_to = nil}, {prefix = "/proc", map_to = nil}, {prefix = "/sys", map_to = nil}, {prefix = "/etc/resolv.conf", map_to = nil}, {prefix = "/etc/apt", map_to = target_root}, {prefix = tools, map_to = nil}, {path = "/", map_to = nil}, {prefix = "/", map_to = tools_root} } } qemu_chain = { next_chain = nil, binary = basename(os.getenv("SBOX_CPUTRANSPARENCY_METHOD")), rules = { {prefix = "/lib", map_to = target_root}, {prefix = "/usr/lib", map_to = target_root}, {prefix = "/usr/local/lib", map_to = target_root}, {prefix = "/tmp", map_to = nil}, {prefix = "/dev", map_to = nil}, {prefix = "/proc", map_to = nil}, {prefix = "/sys", map_to = nil}, {prefix = "/etc/resolv.conf", map_to = nil}, {prefix = tools, map_to = nil}, {path = "/", map_to = nil}, {prefix = "/", map_to = tools_root} } } export_chains = { qemu_chain, simple_chain }
Map /usr/X11R6/lib in maemo mode
Map /usr/X11R6/lib in maemo mode Fixes Maemo 2.x rootstraps. Signed-off-by: Lauri Leukkunen <[email protected]>
Lua
lgpl-2.1
OlegGirko/ldbox,lbt/scratchbox2,BinChengfei/scratchbox2,BinChengfei/scratchbox2,neeraj9/sbox2,BinChengfei/scratchbox2,loganchien/scratchbox2,madscientist42/scratchbox2,madscientist42/scratchbox2,BinChengfei/scratchbox2,neeraj9/sbox2,loganchien/scratchbox2,h113331pp/scratchbox2,neeraj9/sbox2,ldbox/ldbox,h113331pp/scratchbox2,loganchien/scratchbox2,neeraj9/sbox2,BinChengfei/scratchbox2,loganchien/scratchbox2,h113331pp/scratchbox2,freedesktop-unofficial-mirror/sbox2,ldbox/ldbox,OlegGirko/ldbox,BinChengfei/scratchbox2,loganchien/scratchbox2,lbt/scratchbox2,OlegGirko/ldbox,madscientist42/scratchbox2,ldbox/ldbox,neeraj9/sbox2,neeraj9/sbox2,ldbox/ldbox,OlegGirko/ldbox,freedesktop-unofficial-mirror/sbox2,madscientist42/scratchbox2,freedesktop-unofficial-mirror/sbox2,freedesktop-unofficial-mirror/sbox2,h113331pp/scratchbox2,ldbox/ldbox,OlegGirko/ldbox,OlegGirko/ldbox,h113331pp/scratchbox2,ldbox/ldbox,freedesktop-unofficial-mirror/sbox2,lbt/scratchbox2,madscientist42/scratchbox2,madscientist42/scratchbox2,freedesktop-unofficial-mirror/sbox2,loganchien/scratchbox2,lbt/scratchbox2,lbt/scratchbox2,h113331pp/scratchbox2
f4a34eeab3c71df6578b1035f5b6fb5eb60e35bd
shared/unit.lua
shared/unit.lua
local blocking = require "shared.blocking" local GameMath = require "shared.gamemath" local Entity = require "shared.entity" local Unit = Entity:subclass("Unit") -- speed: pixels/second -- orientation: radians function Unit:initialize(entityStatic, player) Entity.initialize(self, entityStatic, player) self.speed = self.speed or 300 -- self.orientation = orientation self.targetPosition = GameMath.Vector2:new(self.position.x, self.position.y) self.stopRange = 1 self.waypoints = false end function Unit:update(dt) self:updateMove(dt) Entity.update(self, dt) end function Unit:moveTo(x, y, stopRange) self.targetPosition.x = x self.targetPosition.y = y self.stopRange = stopRange or self.stopRange self.waypoints = blocking.findPath(self.position.x, self.position.y, self.targetPosition.x, self.targetPosition.y) end function Unit:reachedTarget(target, step) local direction = (target - self.position) local length = direction:length() -- RETURN REACHED, direction vector, direction length return length <= step, direction, length end function Unit:updateMove(dt) if self.waypoints and #self.waypoints > 0 then local waypoints = self.waypoints local target = GameMath.Vector2:new(waypoints[1].x, waypoints[1].y) local step = dt * self.speed local reached, direction, length = self:reachedTarget(target, step) -- Update orientation if length > 0 then self.orientation = math.atan2(direction.y, direction.x) end -- print(length, reached, self.position, target) if #waypoints > 1 or length > self.stopRange then if reached then self.position.x = target.x self.position.y = target.y table.remove(waypoints, 1) else self.position = self.position + direction * dt * self.speed / length end return true else return false end end end function Unit:drawPath() if self.waypoints and #self.waypoints > 0 then local waypoints = self.waypoints -- Draw the path to the destination love.graphics.setColor(255,0,0,64) love.graphics.setPointSize(5) local px, py = self.position.x, self.position.y for i, waypoint in ipairs(waypoints) do local x, y = waypoint.x, waypoint.y if px then love.graphics.line(px, py, x, y) else love.graphics.point(x, y) end px, py = x, y end love.graphics.point(px, py) end end function Unit:setPosition(x, y) self.targetPosition.x = x self.targetPosition.y = y Entity.setPosition(self, x, y) end return Unit
local blocking = require "shared.blocking" local GameMath = require "shared.gamemath" local Entity = require "shared.entity" local Unit = Entity:subclass("Unit") -- speed: pixels/second -- orientation: radians function Unit:initialize(entityStatic, player) Entity.initialize(self, entityStatic, player) self.speed = self.speed or 300 -- self.orientation = orientation self.targetPosition = GameMath.Vector2:new(self.position.x, self.position.y) self.stopRange = 1 self.waypoints = false end function Unit:update(dt) self:updateMove(dt) Entity.update(self, dt) end function Unit:moveTo(x, y, stopRange) self.targetPosition.x = x self.targetPosition.y = y self.stopRange = stopRange or self.stopRange self.waypoints = blocking.findPath(self.position.x, self.position.y, self.targetPosition.x, self.targetPosition.y) end function Unit:reachedTarget(target, step) local direction = (target - self.position) local length = direction:length() -- RETURN REACHED, direction vector, direction length return length <= step, direction, length end function Unit:updateMove(dt) if self.waypoints and #self.waypoints > 0 then local waypoints = self.waypoints local target = GameMath.Vector2:new(waypoints[1].x, waypoints[1].y) local step = dt * self.speed local reached, direction, length = self:reachedTarget(target, step) -- Update orientation if length > 0 then self.orientation = math.atan2(direction.y, direction.x) end if #waypoints > 1 or length > self.stopRange then if reached then self.position.x = target.x self.position.y = target.y table.remove(waypoints, 1) else direction:normalize() self.position = self.position + direction * step / length end return true else return false end end end function Unit:drawPath() if self.waypoints and #self.waypoints > 0 then local waypoints = self.waypoints -- Draw the path to the destination love.graphics.setColor(255,0,0,64) love.graphics.setPointSize(5) local px, py = self.position.x, self.position.y for i, waypoint in ipairs(waypoints) do local x, y = waypoint.x, waypoint.y if px then love.graphics.line(px, py, x, y) else love.graphics.point(x, y) end px, py = x, y end love.graphics.point(px, py) end end function Unit:setPosition(x, y) self.targetPosition.x = x self.targetPosition.y = y Entity.setPosition(self, x, y) end return Unit
Fix: Movement normalization
Fix: Movement normalization
Lua
mit
ExcelF/project-navel
7b76e1c7ae1c08cbc5fec93e92a68d2e1d6a9c9d
MMOCoreORB/bin/scripts/screenplays/static_spawns/dantooine_static_spawns.lua
MMOCoreORB/bin/scripts/screenplays/static_spawns/dantooine_static_spawns.lua
--This is to be used for static spawns that are NOT part of caves, cities, dungeons, poi's, or other large screenplays. DantooineStaticSpawnsScreenPlay = ScreenPlay:new { numberOfActs = 1, screenplayName = "DantooineStaticSpawnsScreenPlay", } registerScreenPlay("DantooineStaticSpawnsScreenPlay", true) function DantooineStaticSpawnsScreenPlay:start() if (isZoneEnabled("dantooine")) then self:spawnMobiles() end end function DantooineStaticSpawnsScreenPlay:spawnMobiles() --Need to add the rest of static spawns (Incomplete). end
--This is to be used for static spawns that are NOT part of caves, cities, dungeons, poi's, or other large screenplays. DantooineStaticSpawnsScreenPlay = ScreenPlay:new { numberOfActs = 1, screenplayName = "DantooineStaticSpawnsScreenPlay", } registerScreenPlay("DantooineStaticSpawnsScreenPlay", true) function DantooineStaticSpawnsScreenPlay:start() if (isZoneEnabled("dantooine")) then self:spawnMobiles() end end function DantooineStaticSpawnsScreenPlay:spawnMobiles() --Need to add the rest of static spawns (Incomplete). -- Vexed Voritor Lizard Spawn (-5500 -1800) spawnMobile("dantooine", "vexed_voritor_lizard", 300, -5500, 15, -1780, getRandomNumber(360), 0) spawnMobile("dantooine", "vexed_voritor_lizard", 300, -5502, 15, -1790, getRandomNumber(360), 0) spawnMobile("dantooine", "vexed_voritor_lizard", 300, -5483, 15, -1777, getRandomNumber(360), 0) end
[fixed] mantis 5656 added vexed voritor static spawn to dantooine
[fixed] mantis 5656 added vexed voritor static spawn to dantooine Change-Id: I694ba69fc20042204a0f900ce2f3d14cc07e5b9e
Lua
agpl-3.0
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
6a3ccfe602f1e3f62157554915447450ee8b93d5
tests/09-data.lua
tests/09-data.lua
local _ = require("underscore")._ , assert = require("assert") , One = require("../lib/tally_ho").Tally_Ho.new() ; describe( 'data', function () it( 'holds changes done in callbacks', function () One:on('change', function (f) f.data.a = 1; end) local data = {}; One:run('change', data) assert.equal(data.a, 1) end) it( 'merges changes done in callbacks', function () One:on('merge', function (f) f.data.b = 2; end) local data = {}; One:run('merge', data) assert.equal(data.b, 2) end) it( 'merges multiple objects into the first', function () One:on('multi-merge', function (f) f.data.c = 3; end) local d1 = {}, d2 = {d=4}; One:run('multi-merge', d1, d2) assert.same(d1, {c=3, d=4}) end) end) -- === end desc
local _ = require("underscore") local Jam = require("jam_bo_ree") local One = Jam.new() describe( 'data', function () it( 'holds changes done in callbacks', function () One:on('change', function (f) f.a = 1 end) local data = {} One:run('change', data) assert.equal(data.a, 1) end) it( 'merges changes done in callbacks', function () One:on('merge', function (f) f.b = 2 end) local data = {} One:run('merge', data) assert.equal(data.b, 2) end) it( 'merges multiple objects into the first', function () One:on('multi-merge', function (f) f.c = 3 end) local d1 = {} local d2 = {d=4} One:run('multi-merge', d1, d2) assert.same(d1, {c=3, d=4}) end) end) -- === end desc
Fixed: typos in tests
Fixed: typos in tests
Lua
mit
da99/jam_bo_ree
33e539c5b3dca6e3599210763f0b92caa686b37e
game/lua-scripts/lenses/winkeltripel.lua
game/lua-scripts/lenses/winkeltripel.lua
-- cos of the standard parallel at 50 degrees 28' clat0 = 2/pi max_fov = 360 max_vfov = 180 onload = "f_contain" function lens_forward(x,y,z) local lat,lon = ray_to_latlon(x,y,z) local clat = cos(lat) local temp = clat*cos(lon*0.5) local D = acos(temp) local C = 1 - temp*temp temp = D/sqrt(C) local x = 0.5 * (2*temp*clat*sin(lon*0.5)+lon*clat0) local y = 0.5 * (temp*sin(lat) + lat) return x,y end -- from: -- https://github.com/d3/d3-geo-projection/blob/master/src/winkel3.js function lens_inverse(x,y) if abs(y) >= lens_height/2 then return nil end local lambda = x local phi = y eps = 0.0001 halfpi = pi/2 for iter=1,25 do local cosphi = cos(phi) local sinphi = sin(phi) local sin_2phi = sin(2 * phi) local sin2phi = sinphi * sinphi local cos2phi = cosphi * cosphi local sinlambda = sin(lambda) local coslambda_2 = cos(lambda / 2) local sinlambda_2 = sin(lambda / 2) local sin2lambda_2 = sinlambda_2 * sinlambda_2 local C = 1 - cos2phi * coslambda_2 * coslambda_2 local E local F if C ~= 0 then F = 1/C E = acos(cosphi * coslambda_2) * sqrt(F) else E = 0 F = 0 end local fx = .5 * (2 * E * cosphi * sinlambda_2 + lambda / halfpi) - x local fy = .5 * (E * sinphi + phi) - y local sigxsiglambda = .5 * F * (cos2phi * sin2lambda_2 + E * cosphi * coslambda_2 * sin2phi) + .5 / halfpi local sigxsigphi = F * (sinlambda * sin_2phi / 4 - E * sinphi * sinlambda_2) local sigysiglambda = .125 * F * (sin_2phi * sinlambda_2 - E * sinphi * cos2phi * sinlambda) local sigysigphi = .5 * F * (sin2phi * coslambda_2 + E * sin2lambda_2 * cosphi) + .5 local denominator = sigxsigphi * sigysiglambda - sigysigphi * sigxsiglambda local siglambda = (fy * sigxsigphi - fx * sigysigphi) / denominator local sigphi = (fx * sigysiglambda - fy * sigxsiglambda) / denominator lambda = lambda - siglambda phi = phi - sigphi if abs(siglambda) < eps and abs(sigphi) < eps then break end end lat,lon = phi, lambda x0,y0 = lens_forward(latlon_to_ray(lat, pi)) if abs(x) < abs(x0) then return latlon_to_ray(lat, lon) end return nil end local x,y = lens_forward(latlon_to_ray(pi/2,0)) lens_height = 2*y x,y = lens_forward(latlon_to_ray(0,pi)) lens_width = 2*x
-- cos of the standard parallel at 50 degrees 28' clat0 = 2/pi max_fov = 360 max_vfov = 180 onload = "f_contain" function lens_forward(x,y,z) local lat,lon = ray_to_latlon(x,y,z) local clat = cos(lat) local temp = clat*cos(lon*0.5) local D = acos(temp) local C = 1 - temp*temp temp = D/sqrt(C) local x = 0.5 * (2*temp*clat*sin(lon*0.5)+lon*clat0) local y = 0.5 * (temp*sin(lat) + lat) return x,y end -- from: -- https://github.com/d3/d3-geo-projection/blob/master/src/winkel3.js function lens_inverse(x,y) if abs(y) >= lens_height/2 then return nil end if is_inside_artifact_box(x,y) then return nil end local lambda = x local phi = y eps = 0.0001 halfpi = pi/2 for iter=1,25 do local cosphi = cos(phi) local sinphi = sin(phi) local sin_2phi = sin(2 * phi) local sin2phi = sinphi * sinphi local cos2phi = cosphi * cosphi local sinlambda = sin(lambda) local coslambda_2 = cos(lambda / 2) local sinlambda_2 = sin(lambda / 2) local sin2lambda_2 = sinlambda_2 * sinlambda_2 local C = 1 - cos2phi * coslambda_2 * coslambda_2 local E local F if C ~= 0 then F = 1/C E = acos(cosphi * coslambda_2) * sqrt(F) else E = 0 F = 0 end local fx = .5 * (2 * E * cosphi * sinlambda_2 + lambda / halfpi) - x local fy = .5 * (E * sinphi + phi) - y local sigxsiglambda = .5 * F * (cos2phi * sin2lambda_2 + E * cosphi * coslambda_2 * sin2phi) + .5 / halfpi local sigxsigphi = F * (sinlambda * sin_2phi / 4 - E * sinphi * sinlambda_2) local sigysiglambda = .125 * F * (sin_2phi * sinlambda_2 - E * sinphi * cos2phi * sinlambda) local sigysigphi = .5 * F * (sin2phi * coslambda_2 + E * sin2lambda_2 * cosphi) + .5 local denominator = sigxsigphi * sigysiglambda - sigysigphi * sigxsiglambda local siglambda = (fy * sigxsigphi - fx * sigysigphi) / denominator local sigphi = (fx * sigysiglambda - fy * sigxsiglambda) / denominator lambda = lambda - siglambda phi = phi - sigphi if abs(siglambda) < eps and abs(sigphi) < eps then break end end lat,lon = phi, lambda x0,y0 = lens_forward(latlon_to_ray(lat, pi)) if abs(x) < abs(x0) then return latlon_to_ray(lat, lon) end return nil end local x,y = lens_forward(latlon_to_ray(pi/2,0)) lens_height = 2*y x,y = lens_forward(latlon_to_ray(0,pi)) lens_width = 2*x -- there are some bad artifacts in the corners of the image -- (just remove them here manually) artifact_x = lens_width/2*0.71 artifact_y = lens_height/2*0.81 function is_inside_artifact_box(x,y) return abs(x) > artifact_x and abs(y) > artifact_y end
fix winkel tripel artifacts (just a hack)
fix winkel tripel artifacts (just a hack)
Lua
mit
khonkhortisan/blinky,khonkhortisan/blinky,shaunlebron/blinky,shaunlebron/blinky,khonkhortisan/blinky,shaunlebron/blinky
a8440060b02074ecd6427a19df1b60a00451299b
spec/unit/statics_spec.lua
spec/unit/statics_spec.lua
local spec_helper = require "spec.spec_helpers" local constants = require "kong.constants" local stringy = require "stringy" local IO = require "kong.tools.io" local fs = require "luarocks.fs" describe("Static files", function() describe("Constants", function() it("version set in constants should match the one in the rockspec", function() local rockspec_path for _, filename in ipairs(fs.list_dir(".")) do if stringy.endswith(filename, "rockspec") then rockspec_path = filename break end end if not rockspec_path then error("Can't find the rockspec file") end local file_content = IO.read_file(rockspec_path) local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+") local extracted_version = res:sub(2, res:len() - 1) assert.are.same(constants.VERSION, extracted_version) end) end) describe("Configuration", function() it("should equal to this template to make sure no errors are pushed in the default config", function() local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE) assert.are.same([[ # Available plugins on this server plugins_available: - keyauth - basicauth - ratelimiting - tcplog - udplog - filelog - cors - request_transformer nginx_working_dir: /usr/local/kong/ proxy_port: 8000 admin_api_port: 8001 dnsmasq_port: 8053 # Specify the DAO to use database: cassandra # Databases configuration databases_available: cassandra: properties: hosts: "localhost" port: 9042 timeout: 1000 keyspace: kong keepalive: 60000 # in milliseconds # Cassandra cache configuration database_cache_expiration: 5 # in seconds # Sends anonymous error reports send_anonymous_reports: true # Nginx configuration nginx: | worker_processes auto; error_log logs/error.log info; daemon on; worker_rlimit_nofile {{auto_worker_rlimit_nofile}}; env KONG_CONF; events { worker_connections {{auto_worker_connections}}; multi_accept on; } http { resolver {{dns_resolver}}; charset UTF-8; access_log logs/access.log; access_log on; # Timeouts keepalive_timeout 60s; client_header_timeout 60s; client_body_timeout 60s; send_timeout 60s; # Proxy Settings proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_ssl_server_name on; # IP Address real_ip_header X-Forwarded-For; set_real_ip_from 0.0.0.0/0; real_ip_recursive on; # Other Settings client_max_body_size 128m; underscores_in_headers on; reset_timedout_connection on; tcp_nopush on; ################################################ # The following code is required to run Kong # # Please be careful if you'd like to change it # ################################################ # Lua Settings lua_package_path ';;'; lua_code_cache on; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict cache 512m; lua_socket_log_errors off; init_by_lua ' kong = require "kong" local status, err = pcall(kong.init) if not status then ngx.log(ngx.ERR, "Startup error: "..err) os.exit(1) end '; server { listen {{proxy_port}}; location / { default_type 'text/plain'; # This property will be used later by proxy_pass set $backend_url nil; # Authenticate the user and load the API info access_by_lua 'kong.exec_plugins_access()'; # Proxy the request proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass $backend_url; proxy_pass_header Server; # Add additional response headers header_filter_by_lua 'kong.exec_plugins_header_filter()'; # Change the response body body_filter_by_lua 'kong.exec_plugins_body_filter()'; # Log the request log_by_lua 'kong.exec_plugins_log()'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } error_page 500 /500.html; location = /500.html { internal; content_by_lua ' local utils = require "kong.tools.utils" utils.show_error(ngx.status, "Oops, an unexpected error occurred!") '; } } server { listen {{admin_api_port}}; location / { default_type application/json; content_by_lua 'require("lapis").serve("kong.api.app")'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } # Do not remove, additional configuration placeholder for some plugins # {{additional_configuration}} } } ]], configuration) end) end) end)
local spec_helper = require "spec.spec_helpers" local constants = require "kong.constants" local stringy = require "stringy" local IO = require "kong.tools.io" local fs = require "luarocks.fs" describe("Static files", function() describe("Constants", function() it("version set in constants should match the one in the rockspec", function() local rockspec_path for _, filename in ipairs(fs.list_dir(".")) do if stringy.endswith(filename, "rockspec") then rockspec_path = filename break end end if not rockspec_path then error("Can't find the rockspec file") end local file_content = IO.read_file(rockspec_path) local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+") local extracted_version = res:sub(2, res:len() - 1) assert.are.same(constants.VERSION, extracted_version) end) end) describe("Configuration", function() it("should equal to this template to make sure no errors are pushed in the default config", function() local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE) assert.are.same([[ # Available plugins on this server plugins_available: - keyauth - basicauth - ratelimiting - tcplog - udplog - filelog - cors - request_transformer nginx_working_dir: /usr/local/kong/ proxy_port: 8000 admin_api_port: 8001 dnsmasq_port: 8053 # Specify the DAO to use database: cassandra # Databases configuration databases_available: cassandra: properties: hosts: "localhost" port: 9042 timeout: 1000 keyspace: kong keepalive: 60000 # in milliseconds # Cassandra cache configuration database_cache_expiration: 5 # in seconds # Sends anonymous error reports send_anonymous_reports: true # In-memory cache size (MB) memory_cache_size: 128 # Nginx configuration nginx: | worker_processes auto; error_log logs/error.log info; daemon on; worker_rlimit_nofile {{auto_worker_rlimit_nofile}}; env KONG_CONF; events { worker_connections {{auto_worker_connections}}; multi_accept on; } http { resolver {{dns_resolver}}; charset UTF-8; access_log logs/access.log; access_log on; # Timeouts keepalive_timeout 60s; client_header_timeout 60s; client_body_timeout 60s; send_timeout 60s; # Proxy Settings proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_ssl_server_name on; # IP Address real_ip_header X-Forwarded-For; set_real_ip_from 0.0.0.0/0; real_ip_recursive on; # Other Settings client_max_body_size 128m; underscores_in_headers on; reset_timedout_connection on; tcp_nopush on; ################################################ # The following code is required to run Kong # # Please be careful if you'd like to change it # ################################################ # Lua Settings lua_package_path ';;'; lua_code_cache on; lua_max_running_timers 4096; lua_max_pending_timers 16384; lua_shared_dict cache {{memory_cache_size}}m; lua_socket_log_errors off; init_by_lua ' kong = require "kong" local status, err = pcall(kong.init) if not status then ngx.log(ngx.ERR, "Startup error: "..err) os.exit(1) end '; server { listen {{proxy_port}}; location / { default_type 'text/plain'; # This property will be used later by proxy_pass set $backend_url nil; # Authenticate the user and load the API info access_by_lua 'kong.exec_plugins_access()'; # Proxy the request proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass $backend_url; proxy_pass_header Server; # Add additional response headers header_filter_by_lua 'kong.exec_plugins_header_filter()'; # Change the response body body_filter_by_lua 'kong.exec_plugins_body_filter()'; # Log the request log_by_lua 'kong.exec_plugins_log()'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } error_page 500 /500.html; location = /500.html { internal; content_by_lua ' local utils = require "kong.tools.utils" utils.show_error(ngx.status, "Oops, an unexpected error occurred!") '; } } server { listen {{admin_api_port}}; location / { default_type application/json; content_by_lua 'require("lapis").serve("kong.api.app")'; } location /robots.txt { return 200 'User-agent: *\nDisallow: /'; } # Do not remove, additional configuration placeholder for some plugins # {{additional_configuration}} } } ]], configuration) end) end) end)
Fixing configuration test
Fixing configuration test
Lua
apache-2.0
ejoncas/kong,jebenexer/kong,Kong/kong,akh00/kong,smanolache/kong,ind9/kong,streamdataio/kong,streamdataio/kong,xvaara/kong,ajayk/kong,beauli/kong,icyxp/kong,Kong/kong,isdom/kong,ind9/kong,ejoncas/kong,Kong/kong,kyroskoh/kong,rafael/kong,ccyphers/kong,li-wl/kong,shiprabehera/kong,Vermeille/kong,jerizm/kong,rafael/kong,isdom/kong,vzaramel/kong,Mashape/kong,vzaramel/kong,salazar/kong,kyroskoh/kong
5358c40a029252c1bfcabb4132e05621934a2cf6
spotify-widget/spotify.lua
spotify-widget/spotify.lua
------------------------------------------------- -- Spotify Widget for Awesome Window Manager -- Shows currently playing song on Spotify for Linux client -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/spotify-widget -- @author Pavel Makhov -- @copyright 2020 Pavel Makhov ------------------------------------------------- local awful = require("awful") local wibox = require("wibox") local watch = require("awful.widget.watch") local function ellipsize(text, length) -- utf8 only available in Lua 5.3+ if utf8 == nil then return text:sub(0, length) end return (utf8.len(text) > length and length > 0) and text:sub(0, utf8.offset(text, length - 2) - 1) .. '...' or text end local spotify_widget = {} local function worker(user_args) local args = user_args or {} local play_icon = args.play_icon or '/usr/share/icons/Arc/actions/24/player_play.png' local pause_icon = args.pause_icon or '/usr/share/icons/Arc/actions/24/player_pause.png' local font = args.font or 'Play 9' local dim_when_paused = args.dim_when_paused == nil and false or args.dim_when_paused local dim_opacity = args.dim_opacity or 0.2 local max_length = args.max_length or 15 local show_tooltip = args.show_tooltip == nil and true or args.show_tooltip local timeout = args.timeout or 1 local sp_bin = args.sp_bin or 'sp' local GET_SPOTIFY_STATUS_CMD = sp_bin .. ' status' local GET_CURRENT_SONG_CMD = sp_bin .. ' current' local cur_artist = '' local cur_title = '' local cur_album = '' spotify_widget = wibox.widget { { id = 'artistw', font = font, widget = wibox.widget.textbox, }, { layout = wibox.layout.stack, { id = "icon", widget = wibox.widget.imagebox, }, { widget = wibox.widget.textbox, font = font, text = ' ', forced_height = 1 } }, { layout = wibox.container.scroll.horizontal, max_size = 100, step_function = wibox.container.scroll.step_functions.waiting_nonlinear_back_and_forth, speed = 40, { id = 'titlew', font = font, widget = wibox.widget.textbox } }, layout = wibox.layout.align.horizontal, set_status = function(self, is_playing) self.icon.image = (is_playing and play_icon or pause_icon) if dim_when_paused then self:get_children_by_id('icon')[1]:set_opacity(is_playing and 1 or dim_opacity) self:get_children_by_id('titlew')[1]:set_opacity(is_playing and 1 or dim_opacity) self:get_children_by_id('titlew')[1]:emit_signal('widget::redraw_needed') self:get_children_by_id('artistw')[1]:set_opacity(is_playing and 1 or dim_opacity) self:get_children_by_id('artistw')[1]:emit_signal('widget::redraw_needed') end end, set_text = function(self, artist, song) local artist_to_display = ellipsize(artist, max_length) if self:get_children_by_id('artistw')[1]:get_markup() ~= artist_to_display then self:get_children_by_id('artistw')[1]:set_markup(artist_to_display) end local title_to_display = ellipsize(song, max_length) if self:get_children_by_id('titlew')[1]:get_markup() ~= title_to_display then self:get_children_by_id('titlew')[1]:set_markup(title_to_display) end end } local update_widget_icon = function(widget, stdout, _, _, _) stdout = string.gsub(stdout, "\n", "") widget:set_status(stdout == 'Playing' and true or false) end local update_widget_text = function(widget, stdout, _, _, _) if string.find(stdout, 'Error: Spotify is not running.') ~= nil then widget:set_text('','') widget:set_visible(false) return end local escaped = string.gsub(stdout, "&", '&amp;') local album, _, artist, title = string.match(escaped, 'Album%s*(.*)\nAlbumArtist%s*(.*)\nArtist%s*(.*)\nTitle%s*(.*)\n') if album ~= nil and title ~=nil and artist ~= nil then cur_artist = artist cur_title = title cur_album = album widget:set_text(artist, title) widget:set_visible(true) end end watch(GET_SPOTIFY_STATUS_CMD, timeout, update_widget_icon, spotify_widget) watch(GET_CURRENT_SONG_CMD, timeout, update_widget_text, spotify_widget) --- Adds mouse controls to the widget: -- - left click - play/pause -- - scroll up - play next song -- - scroll down - play previous song spotify_widget:connect_signal("button::press", function(_, _, _, button) if (button == 1) then awful.spawn("sp play", false) -- left click elseif (button == 4) then awful.spawn("sp next", false) -- scroll up elseif (button == 5) then awful.spawn("sp prev", false) -- scroll down end awful.spawn.easy_async(GET_SPOTIFY_STATUS_CMD, function(stdout, stderr, exitreason, exitcode) update_widget_icon(spotify_widget, stdout, stderr, exitreason, exitcode) end) end) if show_tooltip then local spotify_tooltip = awful.tooltip { mode = 'outside', preferred_positions = {'bottom'}, } spotify_tooltip:add_to_object(spotify_widget) spotify_widget:connect_signal('mouse::enter', function() spotify_tooltip.markup = '<b>Album</b>: ' .. cur_album .. '\n<b>Artist</b>: ' .. cur_artist .. '\n<b>Song</b>: ' .. cur_title end) end return spotify_widget end return setmetatable(spotify_widget, { __call = function(_, ...) return worker(...) end })
------------------------------------------------- -- Spotify Widget for Awesome Window Manager -- Shows currently playing song on Spotify for Linux client -- More details could be found here: -- https://github.com/streetturtle/awesome-wm-widgets/tree/master/spotify-widget -- @author Pavel Makhov -- @copyright 2020 Pavel Makhov ------------------------------------------------- local awful = require("awful") local wibox = require("wibox") local watch = require("awful.widget.watch") local function ellipsize(text, length) -- utf8 only available in Lua 5.3+ if utf8 == nil then return text:sub(0, length) end return (utf8.len(text) > length and length > 0) and text:sub(0, utf8.offset(text, length - 2) - 1) .. '...' or text end local spotify_widget = {} local function worker(user_args) local args = user_args or {} local play_icon = args.play_icon or '/usr/share/icons/Arc/actions/24/player_play.png' local pause_icon = args.pause_icon or '/usr/share/icons/Arc/actions/24/player_pause.png' local font = args.font or 'Play 9' local dim_when_paused = args.dim_when_paused == nil and false or args.dim_when_paused local dim_opacity = args.dim_opacity or 0.2 local max_length = args.max_length or 15 local show_tooltip = args.show_tooltip == nil and true or args.show_tooltip local timeout = args.timeout or 1 local sp_bin = args.sp_bin or 'sp' local GET_SPOTIFY_STATUS_CMD = sp_bin .. ' status' local GET_CURRENT_SONG_CMD = sp_bin .. ' current' local cur_artist = '' local cur_title = '' local cur_album = '' spotify_widget = wibox.widget { { id = 'artistw', font = font, widget = wibox.widget.textbox, }, { layout = wibox.layout.stack, { id = "icon", widget = wibox.widget.imagebox, }, { widget = wibox.widget.textbox, font = font, text = ' ', forced_height = 1 } }, { layout = wibox.container.scroll.horizontal, max_size = 100, step_function = wibox.container.scroll.step_functions.waiting_nonlinear_back_and_forth, speed = 40, { id = 'titlew', font = font, widget = wibox.widget.textbox } }, layout = wibox.layout.align.horizontal, set_status = function(self, is_playing) self:get_children_by_id('icon')[1]:set_image(is_playing and play_icon or pause_icon) if dim_when_paused then self:get_children_by_id('icon')[1]:set_opacity(is_playing and 1 or dim_opacity) self:get_children_by_id('titlew')[1]:set_opacity(is_playing and 1 or dim_opacity) self:get_children_by_id('titlew')[1]:emit_signal('widget::redraw_needed') self:get_children_by_id('artistw')[1]:set_opacity(is_playing and 1 or dim_opacity) self:get_children_by_id('artistw')[1]:emit_signal('widget::redraw_needed') end end, set_text = function(self, artist, song) local artist_to_display = ellipsize(artist, max_length) if self:get_children_by_id('artistw')[1]:get_markup() ~= artist_to_display then self:get_children_by_id('artistw')[1]:set_markup(artist_to_display) end local title_to_display = ellipsize(song, max_length) if self:get_children_by_id('titlew')[1]:get_markup() ~= title_to_display then self:get_children_by_id('titlew')[1]:set_markup(title_to_display) end end } local update_widget_icon = function(widget, stdout, _, _, _) stdout = string.gsub(stdout, "\n", "") widget:set_status(stdout == 'Playing' and true or false) end local update_widget_text = function(widget, stdout, _, _, _) if string.find(stdout, 'Error: Spotify is not running.') ~= nil then widget:set_text('','') widget:set_visible(false) return end local escaped = string.gsub(stdout, "&", '&amp;') local album, _, artist, title = string.match(escaped, 'Album%s*(.*)\nAlbumArtist%s*(.*)\nArtist%s*(.*)\nTitle%s*(.*)\n') if album ~= nil and title ~=nil and artist ~= nil then cur_artist = artist cur_title = title cur_album = album widget:set_text(artist, title) widget:set_visible(true) end end watch(GET_SPOTIFY_STATUS_CMD, timeout, update_widget_icon, spotify_widget) watch(GET_CURRENT_SONG_CMD, timeout, update_widget_text, spotify_widget) --- Adds mouse controls to the widget: -- - left click - play/pause -- - scroll up - play next song -- - scroll down - play previous song spotify_widget:connect_signal("button::press", function(_, _, _, button) if (button == 1) then awful.spawn("sp play", false) -- left click elseif (button == 4) then awful.spawn("sp next", false) -- scroll up elseif (button == 5) then awful.spawn("sp prev", false) -- scroll down end awful.spawn.easy_async(GET_SPOTIFY_STATUS_CMD, function(stdout, stderr, exitreason, exitcode) update_widget_icon(spotify_widget, stdout, stderr, exitreason, exitcode) end) end) if show_tooltip then local spotify_tooltip = awful.tooltip { mode = 'outside', preferred_positions = {'bottom'}, } spotify_tooltip:add_to_object(spotify_widget) spotify_widget:connect_signal('mouse::enter', function() spotify_tooltip.markup = '<b>Album</b>: ' .. cur_album .. '\n<b>Artist</b>: ' .. cur_artist .. '\n<b>Song</b>: ' .. cur_title end) end return spotify_widget end return setmetatable(spotify_widget, { __call = function(_, ...) return worker(...) end })
Fix bug introduced by #367
Fix bug introduced by #367
Lua
mit
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
e23f583ff297259f974c2b1b0075cbefb40c3e14
lua/entities/gmod_wire_hologram/cl_init.lua
lua/entities/gmod_wire_hologram/cl_init.lua
include( "shared.lua" ) ENT.RenderGroup = RENDERGROUP_BOTH local blocked = {} local scale_buffer = {} local clip_buffer = {} local vis_buffer = {} function ENT:Initialize( ) self:DoScale() local ownerid = self:GetNetworkedInt("ownerid") self.blocked = blocked[ownerid] or false self.clips = {} self.visible = true end function ENT:SetupClipping() local eidx = self:EntIndex() if clip_buffer[eidx] != nil then table.Merge( self.clips, clip_buffer[eidx] ) clip_buffer[eidx] = nil end local nclips = 0 if self.clips then nclips = table.Count( self.clips ) end if nclips > 0 then render.EnableClipping( true ) for _,clip in pairs( self.clips ) do if clip.enabled and clip.normal and clip.origin then local norm = clip.normal local origin = clip.origin if !clip.isglobal then norm = self:LocalToWorld( norm ) - self:GetPos() origin = self:LocalToWorld( origin ) end render.PushCustomClipPlane( norm, norm:Dot( origin ) ) end end end end function ENT:FinishClipping() local nclips = 0 if self.clips then nclips = table.Count( self.clips ) end if nclips > 0 then for i = 1, nclips do render.PopCustomClipPlane() end render.EnableClipping( false ) end end function ENT:Draw() local eidx = self:EntIndex() if self.visible != vis_buffer[eidx] then self.visible = vis_buffer[eidx] end if self.blocked or self.visible == false then return end self:SetupClipping() if self:GetNWBool( "disable_shading" ) then render.SuppressEngineLighting( true ) end self:DrawModel() render.SuppressEngineLighting( false ) self:FinishClipping() end /******************************************************************************/ local function CheckClip(eidx, cidx) clip_buffer[eidx] = clip_buffer[eidx] or {} clip_buffer[eidx][cidx] = clip_buffer[eidx][cidx] or {} return clip_buffer[eidx][cidx] end local function SetClipEnabled(eidx, cidx, enabled) local clip = CheckClip(eidx, cidx) clip.enabled = enabled end local function SetClip(eidx, cidx, origin, norm, isglobal) local clip = CheckClip(eidx, cidx) clip.normal = norm clip.origin = origin clip.isglobal = isglobal end net.Receive("wire_holograms_clip", function( netlen ) local entid = net.ReadUInt(16) while entid ~= 0 do local clipid = net.ReadUInt(16) if net.ReadBit() ~= 0 then SetClipEnabled(entid, clipid, net.ReadBit()) else SetClip(entid, clipid, net.ReadVector(), net.ReadVector(), net.ReadBit() ~= 0) end entid = net.ReadUInt(16) end end) /******************************************************************************/ local function SetScale(entindex, scale) scale_buffer[entindex] = scale local ent = Entity(entindex) if ent and ent.DoScale then ent:DoScale() end end function ENT:DoScale() local eidx = self:EntIndex() local scale = scale_buffer[eidx] or Vector(1,1,1) if self.EnableMatrix then local mat = Matrix() mat:Scale(scale) self:EnableMatrix("RenderMultiply", mat) else -- Some entities, like ragdolls, cannot be resized with EnableMatrix, so lets average the three components to get a float self:SetModelScale((scale.x+scale.y+scale.z)/3,0) end scale_buffer[eidx] = nil end net.Receive("wire_holograms_set_scale", function( netlen ) local index = net.ReadUInt(16) while index ~= 0 do SetScale(index, Vector(net.ReadFloat(),net.ReadFloat(),net.ReadFloat())) index = net.ReadUInt(16) end end) /******************************************************************************/ net.Receive("wire_holograms_set_visible", function( netlen ) local index = net.ReadUInt(16) while index ~= 0 do vis_buffer[index] = net.ReadBit() ~= 0 index = net.ReadUInt(16) end end ) /******************************************************************************/ concommand.Add("wire_holograms_block_client", function(ply, command, args) local toblock for _,ply in ipairs(player.GetAll()) do if ply:Name() == args[1] then toblock = ply break end end if not toblock then error("Player not found") end local id = toblock:UserID() blocked[id] = true for _,ent in ipairs(ents.FindByClass("gmod_wire_hologram")) do if ent:GetNetworkedInt("ownerid") == id then ent.blocked = true end end end, function() local names = {} for _,ply in ipairs(player.GetAll()) do table.insert(names, "wire_holograms_block_client \""..ply:Name().."\"") end table.sort(names) return names end ) concommand.Add( "wire_holograms_unblock_client", function(ply, command, args) local toblock for _,ply in ipairs(player.GetAll()) do if ply:Name() == args[1] then toblock = ply break end end if not toblock then error("Player not found") end local id = toblock:UserID() blocked[id] = nil for _,ent in ipairs(ents.FindByClass("gmod_wire_hologram")) do if ent:GetNetworkedInt("ownerid") == id then ent.blocked = false end end end, function() local names = {} for _,ply in ipairs(player.GetAll()) do if blocked[ply:UserID()] then table.insert(names, "wire_holograms_unblock_client \""..ply:Name().."\"") end end table.sort(names) return names end )
include( "shared.lua" ) ENT.RenderGroup = RENDERGROUP_BOTH local blocked = {} local scale_buffer = {} local clip_buffer = {} local vis_buffer = {} function ENT:Initialize( ) self:DoScale() local ownerid = self:GetNetworkedInt("ownerid") self.blocked = blocked[ownerid] or false self.clips = {} self.visible = true end function ENT:SetupClipping() local eidx = self:EntIndex() if clip_buffer[eidx] != nil then table.Merge( self.clips, clip_buffer[eidx] ) clip_buffer[eidx] = nil end local nclips = 0 if self.clips then nclips = table.Count( self.clips ) end if nclips > 0 then render.EnableClipping( true ) for _,clip in pairs( self.clips ) do if clip.enabled and clip.normal and clip.origin then local norm = clip.normal local origin = clip.origin if !clip.isglobal then norm = self:LocalToWorld( norm ) - self:GetPos() origin = self:LocalToWorld( origin ) end render.PushCustomClipPlane( norm, norm:Dot( origin ) ) end end end end function ENT:FinishClipping() local nclips = 0 if self.clips then nclips = table.Count( self.clips ) end if nclips > 0 then for i = 1, nclips do render.PopCustomClipPlane() end render.EnableClipping( false ) end end function ENT:Draw() local eidx = self:EntIndex() if self.visible != vis_buffer[eidx] then self.visible = vis_buffer[eidx] end if self.blocked or self.visible == false then return end self:SetupClipping() if self:GetNWBool( "disable_shading" ) then render.SuppressEngineLighting( true ) end self:DrawModel() render.SuppressEngineLighting( false ) self:FinishClipping() end /******************************************************************************/ local function CheckClip(eidx, cidx) clip_buffer[eidx] = clip_buffer[eidx] or {} clip_buffer[eidx][cidx] = clip_buffer[eidx][cidx] or {} return clip_buffer[eidx][cidx] end local function SetClipEnabled(eidx, cidx, enabled) local clip = CheckClip(eidx, cidx) clip.enabled = enabled end local function SetClip(eidx, cidx, origin, norm, isglobal) local clip = CheckClip(eidx, cidx) clip.normal = norm clip.origin = origin clip.isglobal = isglobal end net.Receive("wire_holograms_clip", function( netlen ) local entid = net.ReadUInt(16) while entid ~= 0 do local clipid = net.ReadUInt(16) if net.ReadBit() ~= 0 then SetClipEnabled(entid, clipid, net.ReadBit()) else SetClip(entid, clipid, net.ReadVector(), net.ReadVector(), net.ReadBit() ~= 0) end entid = net.ReadUInt(16) end end) /******************************************************************************/ local function SetScale(entindex, scale) scale_buffer[entindex] = scale local ent = Entity(entindex) if ent and ent.DoScale then ent:DoScale() end end function ENT:DoScale() local eidx = self:EntIndex() local scale = scale_buffer[eidx] or Vector(1,1,1) if self.EnableMatrix then local mat = Matrix() mat:Scale(scale) -- Note: We're swapping X and Y because RenderMultiply isn't consistant with the rest of source self:EnableMatrix("RenderMultiply", mat) else -- Some entities, like ragdolls, cannot be resized with EnableMatrix, so lets average the three components to get a float self:SetModelScale((scale.x+scale.y+scale.z)/3,0) end scale_buffer[eidx] = nil end net.Receive("wire_holograms_set_scale", function( netlen ) local index = net.ReadUInt(16) while index ~= 0 do local x,y,z = net.ReadFloat(),net.ReadFloat(),net.ReadFloat() SetScale(index, Vector(y,x,z)) -- Note: We're swapping X and Y because RenderMultiply isn't consistant with the rest of source index = net.ReadUInt(16) end end) /******************************************************************************/ net.Receive("wire_holograms_set_visible", function( netlen ) local index = net.ReadUInt(16) while index ~= 0 do vis_buffer[index] = net.ReadBit() ~= 0 index = net.ReadUInt(16) end end ) /******************************************************************************/ concommand.Add("wire_holograms_block_client", function(ply, command, args) local toblock for _,ply in ipairs(player.GetAll()) do if ply:Name() == args[1] then toblock = ply break end end if not toblock then error("Player not found") end local id = toblock:UserID() blocked[id] = true for _,ent in ipairs(ents.FindByClass("gmod_wire_hologram")) do if ent:GetNetworkedInt("ownerid") == id then ent.blocked = true end end end, function() local names = {} for _,ply in ipairs(player.GetAll()) do table.insert(names, "wire_holograms_block_client \""..ply:Name().."\"") end table.sort(names) return names end ) concommand.Add( "wire_holograms_unblock_client", function(ply, command, args) local toblock for _,ply in ipairs(player.GetAll()) do if ply:Name() == args[1] then toblock = ply break end end if not toblock then error("Player not found") end local id = toblock:UserID() blocked[id] = nil for _,ent in ipairs(ents.FindByClass("gmod_wire_hologram")) do if ent:GetNetworkedInt("ownerid") == id then ent.blocked = false end end end, function() local names = {} for _,ply in ipairs(player.GetAll()) do if blocked[ply:UserID()] then table.insert(names, "wire_holograms_unblock_client \""..ply:Name().."\"") end end table.sort(names) return names end )
Holograms: Swapped X and Y in scale Fixes #147 Scaling is now consistent with Gmod12 holograms, and the rest of source
Holograms: Swapped X and Y in scale Fixes #147 Scaling is now consistent with Gmod12 holograms, and the rest of source
Lua
apache-2.0
mms92/wire,plinkopenguin/wiremod,garrysmodlua/wire,mitterdoo/wire,dvdvideo1234/wire,notcake/wire,sammyt291/wire,CaptainPRICE/wire,wiremod/wire,immibis/wiremod,Grocel/wire,bigdogmat/wire,NezzKryptic/Wire,thegrb93/wire,rafradek/wire,Python1320/wire
a45940bf32f7a2f086c53aa0f079c7c51d974e25
packages/ubus-lime-utils/files/usr/lib/lua/lime/upgrade.lua
packages/ubus-lime-utils/files/usr/lib/lua/lime/upgrade.lua
#!/usr/bin/env lua --[[ Copyright (C) 2020 LibreMesh.org This is free software, licensed under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 Copyright 2020 Santiago Piccinini <[email protected]> ]]-- local json = require 'luci.jsonc' local utils = require 'lime.utils' local pkg = {} pkg.UPGRADE_INFO_CACHE_FILE = '/tmp/upgrade_info_cache' pkg.UPGRADE_STATUS_DEFAULT = 'NOT_STARTED' pkg.UPGRADE_STATUS_UPGRADING = 'UPGRADING' pkg.UPGRADE_STATUS_FAILED = 'FAILED' pkg.LIME_SYSUPGRADE_BACKUP_EXTRA_DIR = "/tmp/lime-sysupgrade/preserve" pkg.UPGRADE_METADATA_FILE = "/etc/upgrade_metadata" function pkg.safe_upgrade_confirm_remaining_s() print("safe_upgrade_confirm_remaining_s") local remaining_s = tonumber(utils.unsafe_shell("safe-upgrade confirm-remaining")) if not remaining_s then remaining_s = -1 end return remaining_s end function pkg.is_upgrade_confirm_supported() local exit_value = os.execute("safe-upgrade board-supported > /dev/null 2>&1") return exit_value == 0 end function pkg.get_upgrade_status() local info = utils.read_obj_store(pkg.UPGRADE_INFO_CACHE_FILE) if info.status == nil then return pkg.UPGRADE_STATUS_DEFAULT else return info.status end end function pkg.set_upgrade_status(status) return utils.write_obj_store_var(pkg.UPGRADE_INFO_CACHE_FILE, 'status', status) end function pkg.get_upgrade_info() local result = utils.read_obj_store(pkg.UPGRADE_INFO_CACHE_FILE) if result.is_upgrade_confirm_supported == nil then result.is_upgrade_confirm_supported = pkg.is_upgrade_confirm_supported() end if not result.is_upgrade_confirm_supported then result.safe_upgrade_confirm_remaining_s = -1 else result.safe_upgrade_confirm_remaining_s = pkg.safe_upgrade_confirm_remaining_s() end utils.write_obj_store(pkg.UPGRADE_INFO_CACHE_FILE, result) return result end function pkg.firmware_verify(fw_path) local command if pkg.is_upgrade_confirm_supported() then command = "safe-upgrade verify " else command = "sysupgrade --test " end command = command .. fw_path .. " > /dev/null 2>&1" local exit_value = os.execute(command) return exit_value == 0 end function pkg.firmware_upgrade(fw_path, preserve_config, metadata, fw_type) if not fw_path then return nil, "Firmware file needed" end if not utils.file_exists(fw_path) then return nil, "Firmware file not found" end if pkg.get_upgrade_status() == pkg.UPGRADE_STATUS_UPGRADING then return nil, "There is an upgrade in progress" end metadata = metadata or {} if not fw_type then if utils.stringEnds(fw_path, ".bin") then fw_type = 'sysupgrade' elseif utils.stringEnds(fw_path, ".sh") then fw_type = 'installer' else return nil, "Unsupported firmware type" end end if fw_type == 'sysupgrade' then if not pkg.firmware_verify(fw_path) then return nil, "Invalid firmware" end end local backup = "" if not preserve_config then backup = "DO_NOT_BACKUP=1" end metadata['config_preserved'] = preserve_config or false -- store info of the current firmware local current_fw_description = utils.release_info()["DISTRIB_DESCRIPTION"] if current_fw_description then metadata['old_release_description'] = current_fw_description end metadata['local_timestamp'] = os.time() --! Use the BACKUP_EXTRA_DIR function of lime-sysupgrade to store the medatada file utils.unsafe_shell("mkdir -p " .. pkg.LIME_SYSUPGRADE_BACKUP_EXTRA_DIR .. "/etc") local meta_file_path = pkg.LIME_SYSUPGRADE_BACKUP_EXTRA_DIR .. pkg.UPGRADE_METADATA_FILE if not utils.write_file(meta_file_path, json.stringify(metadata)) then return nil, "Can't write " .. meta_file_path end pkg.set_upgrade_status(pkg.UPGRADE_STATUS_UPGRADING) if fw_type == 'sysupgrade' then --! Give some time so the response can be returned to the client local cmd = "sleep 3; FORCE=1 " .. backup .. " lime-sysupgrade " .. fw_path --! stdin must be /dev/null because of a tar bug when using gzip that tries to read from stin and fails --! if it is closed utils.execute_daemonized(cmd, "/tmp/lime-sysupgrade.log", "/dev/null") elseif fw_type == 'installer' then utils.unsafe_shell("chmod +x " .. fw_path) utils.execute_daemonized(fw_path, "/tmp/upgrade-installer.log", "/dev/null") --! give the installer some time and try to collect the status up to that moment utils.unsafe_shell("sleep 10s") local progress_status = utils.read_file("/tmp/upgrade-installer-status") or 'unknown' if progress_status == 'failed' then pkg.set_upgrade_status(pkg.UPGRADE_STATUS_FAILED) return nil, utils.read_file("/tmp/upgrade-installer-error-mesage") or 'Installer failed without error message' end end return true, metadata end return pkg
#!/usr/bin/env lua --[[ Copyright (C) 2020 LibreMesh.org This is free software, licensed under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 Copyright 2020 Santiago Piccinini <[email protected]> ]]-- local json = require 'luci.jsonc' local utils = require 'lime.utils' local pkg = {} pkg.UPGRADE_INFO_CACHE_FILE = '/tmp/upgrade_info_cache' pkg.UPGRADE_STATUS_DEFAULT = 'NOT_STARTED' pkg.UPGRADE_STATUS_UPGRADING = 'UPGRADING' pkg.UPGRADE_STATUS_FAILED = 'FAILED' pkg.LIME_SYSUPGRADE_BACKUP_EXTRA_DIR = "/tmp/lime-sysupgrade/preserve" pkg.UPGRADE_METADATA_FILE = "/etc/upgrade_metadata" function pkg.safe_upgrade_confirm_remaining_s() local remaining_s = tonumber(utils.unsafe_shell("safe-upgrade confirm-remaining")) if not remaining_s then remaining_s = -1 end return remaining_s end function pkg.is_upgrade_confirm_supported() local exit_value = os.execute("safe-upgrade board-supported > /dev/null 2>&1") return exit_value == 0 end function pkg.get_upgrade_status() local info = utils.read_obj_store(pkg.UPGRADE_INFO_CACHE_FILE) if info.status == nil then return pkg.UPGRADE_STATUS_DEFAULT else return info.status end end function pkg.set_upgrade_status(status) return utils.write_obj_store_var(pkg.UPGRADE_INFO_CACHE_FILE, 'status', status) end function pkg.get_upgrade_info() local result = utils.read_obj_store(pkg.UPGRADE_INFO_CACHE_FILE) if result.is_upgrade_confirm_supported == nil then result.is_upgrade_confirm_supported = pkg.is_upgrade_confirm_supported() end if not result.is_upgrade_confirm_supported then result.safe_upgrade_confirm_remaining_s = -1 else result.safe_upgrade_confirm_remaining_s = pkg.safe_upgrade_confirm_remaining_s() end utils.write_obj_store(pkg.UPGRADE_INFO_CACHE_FILE, result) return result end function pkg.firmware_verify(fw_path) local command if pkg.is_upgrade_confirm_supported() then command = "safe-upgrade verify " else command = "sysupgrade --test " end command = command .. fw_path .. " > /dev/null 2>&1" local exit_value = os.execute(command) return exit_value == 0 end function pkg.firmware_upgrade(fw_path, preserve_config, metadata, fw_type) if not fw_path then return nil, "Firmware file needed" end if not utils.file_exists(fw_path) then return nil, "Firmware file not found" end if pkg.get_upgrade_status() == pkg.UPGRADE_STATUS_UPGRADING then return nil, "There is an upgrade in progress" end metadata = metadata or {} if not fw_type then if utils.stringEnds(fw_path, ".bin") then fw_type = 'sysupgrade' elseif utils.stringEnds(fw_path, ".sh") then fw_type = 'installer' else return nil, "Unsupported firmware type" end end if fw_type == 'sysupgrade' then if not pkg.firmware_verify(fw_path) then return nil, "Invalid firmware" end end local backup = "" if not preserve_config then backup = "DO_NOT_BACKUP=1" end metadata['config_preserved'] = preserve_config or false -- store info of the current firmware local current_fw_description = utils.release_info()["DISTRIB_DESCRIPTION"] if current_fw_description then metadata['old_release_description'] = current_fw_description end metadata['local_timestamp'] = os.time() --! Use the BACKUP_EXTRA_DIR function of lime-sysupgrade to store the medatada file utils.unsafe_shell("mkdir -p " .. pkg.LIME_SYSUPGRADE_BACKUP_EXTRA_DIR .. "/etc") local meta_file_path = pkg.LIME_SYSUPGRADE_BACKUP_EXTRA_DIR .. pkg.UPGRADE_METADATA_FILE if not utils.write_file(meta_file_path, json.stringify(metadata)) then return nil, "Can't write " .. meta_file_path end pkg.set_upgrade_status(pkg.UPGRADE_STATUS_UPGRADING) if fw_type == 'sysupgrade' then --! Give some time so the response can be returned to the client local cmd = "sleep 3; FORCE=1 " .. backup .. " lime-sysupgrade " .. fw_path --! stdin must be /dev/null because of a tar bug when using gzip that tries to read from stin and fails --! if it is closed utils.execute_daemonized(cmd, "/tmp/lime-sysupgrade.log", "/dev/null") elseif fw_type == 'installer' then utils.unsafe_shell("chmod +x " .. fw_path) utils.execute_daemonized(fw_path, "/tmp/upgrade-installer.log", "/dev/null") --! give the installer some time and try to collect the status up to that moment utils.unsafe_shell("sleep 10s") local progress_status = utils.read_file("/tmp/upgrade-installer-status") or 'unknown' if progress_status == 'failed' then pkg.set_upgrade_status(pkg.UPGRADE_STATUS_FAILED) return nil, utils.read_file("/tmp/upgrade-installer-error-mesage") or 'Installer failed without error message' end end return true, metadata end return pkg
lime-utils: remove debugging print
lime-utils: remove debugging print Fix the get_upgrade_info ubus endpoint, broken by the intrusion of the print into the json output.
Lua
agpl-3.0
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
c1b69a09445005af6e1a031ac085e572694aaafd
popups.lua
popups.lua
local mod = EPGP:NewModule("EPGP_Popups") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local GPTooltip = EPGP:GetModule("EPGP_GPTooltip") local function EPGP_CONFIRM_GP_CREDIT_UpdateButtons(self) local link = self.itemFrame.link local gp = tonumber(self.editBox:GetText()) if EPGP:CanIncGPBy(link, gp) then self.button1:Enable() self.button3:Enable() else self.button1:Disable() self.button3:Disable() end end StaticPopupDialogs["EPGP_CONFIRM_GP_CREDIT"] = { text = L["Credit GP to %s"], button1 = ACCEPT, button2 = CANCEL, timeout = 0, whileDead = 1, maxLetters = 16, hideOnEscape = 1, hasEditBox = 1, hasItemFrame = 1, OnAccept = function(self) local link = self.itemFrame.link local gp = tonumber(self.editBox:GetText()) EPGP:IncGPBy(self.name, link, gp) end, OnCancel = function(self) self:Hide() ClearCursor() end, OnShow = function(self) local itemFrame = getglobal(self:GetName().."ItemFrame") local editBox = getglobal(self:GetName().."EditBox") local button1 = getglobal(self:GetName().."Button1") itemFrame:SetPoint("TOPLEFT", 35, -35) editBox:SetPoint("TOPLEFT", itemFrame, "TOPRIGHT", 150, -10) editBox:SetPoint("RIGHT", -35, 0) button1:SetPoint("TOPRIGHT", itemFrame, "BOTTOMRIGHT", 85, -6) local gp1, gp2 = GPTooltip:GetGPValue(itemFrame.link) if gp1 then if gp2 then editBox:SetText(L["%d or %d"]:format(gp1, gp2)) else editBox:SetText(gp1) end end editBox:HighlightText() EPGP_CONFIRM_GP_CREDIT_UpdateButtons(self) end, OnHide = function(self) local itemFrame = getglobal(self:GetName().."ItemFrame") local editBox = getglobal(self:GetName().."EditBox") local button1 = getglobal(self:GetName().."Button1") -- Clear anchor points of frames that we modified, and revert them. itemFrame:ClearAllPoints() editBox:ClearAllPoints() button1:ClearAllPoints() itemFrame:SetPoint("TOP", getglobal(self:GetName().."Text"), "BOTTOM", 0, -16) itemFrame:SetPoint("LEFT", getglobal(self:GetName()), "LEFT", 82, 0) editBox:SetPoint("BOTTOM", getglobal(self:GetName()), "BOTTOM", 0, 45) button1:SetPoint("TOPRIGHT", getglobal(self:GetName().."EditBox"), "BOTTOM", -6, -8) if ChatFrameEditBox:IsShown() then ChatFrameEditBox:SetFocus() end end, EditBoxOnEnterPressed = function(self) local parent = self:GetParent() local link = parent.itemFrame.link local gp = tonumber(parent.editBox:GetText()) if EPGP:CanIncGPBy(link, gp) then EPGP:IncGPBy(parent.name, link, gp) parent:Hide() end end, EditBoxOnTextChanged = function(self) local parent = self:GetParent() EPGP_CONFIRM_GP_CREDIT_UpdateButtons(parent) end, EditBoxOnEscapePressed = function(self) self:GetParent():Hide() ClearCursor() end } StaticPopupDialogs["EPGP_DECAY_EPGP"] = { text = "", button1 = ACCEPT, button2 = CANCEL, timeout = 0, hideOnEscape = 1, whileDead = 1, OnShow = function() local text = getglobal(this:GetName().."Text") text:SetFormattedText(L["Decay EP and GP by %d%%?"], EPGP:GetDecayPercent()) end, OnAccept = function() EPGP:DecayEPGP() end } StaticPopupDialogs["EPGP_RESET_EPGP"] = { text = L["Reset all main toons' EP and GP to 0?"], button1 = ACCEPT, button2 = CANCEL, timeout = 0, hideOnEscape = 1, whileDead = 1, OnAccept = function() EPGP:ResetEPGP() end } local function Debug(fmt, ...) DEFAULT_CHAT_FRAME:AddMessage(string.format(fmt, ...)) end function mod:OnInitialize() -- local playername = UnitName("player") -- local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(34541) -- local r, g, b = GetItemQualityColor(itemRarity); -- Debug("ItemName: %s ItemLink: %s ItemRarity: %d ItemTexture: %s", -- itemName, itemLink, itemRarity, itemTexture) -- local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", playername, "", { -- texture = itemTexture, -- name = itemName, -- color = {r, g, b, 1}, -- link = itemLink -- }) -- if dialog then -- dialog.name = playername -- end end
local mod = EPGP:NewModule("EPGP_Popups") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local GPTooltip = EPGP:GetModule("EPGP_GPTooltip") local function EPGP_CONFIRM_GP_CREDIT_UpdateButtons(self) local link = self.itemFrame.link local gp = tonumber(self.editBox:GetText()) if EPGP:CanIncGPBy(link, gp) then self.button1:Enable() self.button3:Enable() else self.button1:Disable() self.button3:Disable() end end local blizzardAnchors = {} local function savePoint(frame, i) local point, relativeTo, relativePoint, x, y = frame:GetPoint(i) if point then tinsert(blizzardAnchors, {frame, point, relativeTo, relativePoint, x, y}) end end local function makeAnchorTable(itemFrame, editBox, button1) for i=1,itemFrame:GetNumPoints() do savePoint(itemFrame, i) end for i=1,editBox:GetNumPoints() do savePoint(editBox, i) end for i=1,button1:GetNumPoints() do savePoint(button1, i) end end StaticPopupDialogs["EPGP_CONFIRM_GP_CREDIT"] = { text = L["Credit GP to %s"], button1 = ACCEPT, button2 = CANCEL, timeout = 0, whileDead = 1, maxLetters = 16, hideOnEscape = 1, hasEditBox = 1, hasItemFrame = 1, OnAccept = function(self) local link = self.itemFrame.link local gp = tonumber(self.editBox:GetText()) EPGP:IncGPBy(self.name, link, gp) end, OnCancel = function(self) self:Hide() ClearCursor() end, OnShow = function(self) local itemFrame = getglobal(self:GetName().."ItemFrame") local editBox = getglobal(self:GetName().."EditBox") local button1 = getglobal(self:GetName().."Button1") if #blizzardAnchors == 0 then makeAnchorTable(itemFrame, editBox, button1) end itemFrame:SetPoint("TOPLEFT", 35, -35) editBox:SetPoint("TOPLEFT", itemFrame, "TOPRIGHT", 150, -10) editBox:SetPoint("RIGHT", -35, 0) button1:SetPoint("TOPRIGHT", itemFrame, "BOTTOMRIGHT", 85, -6) local gp1, gp2 = GPTooltip:GetGPValue(itemFrame.link) if gp1 then if gp2 then editBox:SetText(L["%d or %d"]:format(gp1, gp2)) else editBox:SetText(gp1) end end editBox:HighlightText() EPGP_CONFIRM_GP_CREDIT_UpdateButtons(self) end, OnHide = function(self) local itemFrame = getglobal(self:GetName().."ItemFrame") local editBox = getglobal(self:GetName().."EditBox") local button1 = getglobal(self:GetName().."Button1") -- Clear anchor points of frames that we modified, and revert them. itemFrame:ClearAllPoints() editBox:ClearAllPoints() button1:ClearAllPoints() for p=1,#blizzardAnchors do local frame, point, relativeTo, relativePoint, x, y = unpack(blizzardAnchors[p]) frame:SetPoint(point, relativeTo, relativePoint, x, y) end if ChatFrameEditBox:IsShown() then ChatFrameEditBox:SetFocus() end end, EditBoxOnEnterPressed = function(self) local parent = self:GetParent() local link = parent.itemFrame.link local gp = tonumber(parent.editBox:GetText()) if EPGP:CanIncGPBy(link, gp) then EPGP:IncGPBy(parent.name, link, gp) parent:Hide() end end, EditBoxOnTextChanged = function(self) local parent = self:GetParent() EPGP_CONFIRM_GP_CREDIT_UpdateButtons(parent) end, EditBoxOnEscapePressed = function(self) self:GetParent():Hide() ClearCursor() end } StaticPopupDialogs["EPGP_DECAY_EPGP"] = { text = "", button1 = ACCEPT, button2 = CANCEL, timeout = 0, hideOnEscape = 1, whileDead = 1, OnShow = function() local text = getglobal(this:GetName().."Text") text:SetFormattedText(L["Decay EP and GP by %d%%?"], EPGP:GetDecayPercent()) end, OnAccept = function() EPGP:DecayEPGP() end } StaticPopupDialogs["EPGP_RESET_EPGP"] = { text = L["Reset all main toons' EP and GP to 0?"], button1 = ACCEPT, button2 = CANCEL, timeout = 0, hideOnEscape = 1, whileDead = 1, OnAccept = function() EPGP:ResetEPGP() end } local function Debug(fmt, ...) DEFAULT_CHAT_FRAME:AddMessage(string.format(fmt, ...)) end function mod:OnInitialize() -- local playername = UnitName("player") -- local itemName, itemLink, itemRarity, _, _, _, _, _, _, itemTexture = GetItemInfo(34541) -- local r, g, b = GetItemQualityColor(itemRarity); -- Debug("ItemName: %s ItemLink: %s ItemRarity: %d ItemTexture: %s", -- itemName, itemLink, itemRarity, itemTexture) -- local dialog = StaticPopup_Show("EPGP_CONFIRM_GP_CREDIT", playername, "", { -- texture = itemTexture, -- name = itemName, -- color = {r, g, b, 1}, -- link = itemLink -- }) -- if dialog then -- dialog.name = playername -- end end
Further modifications to make the popup patch more resilient. This fixes issue 251 .
Further modifications to make the popup patch more resilient. This fixes issue 251 .
Lua
bsd-3-clause
hayword/tfatf_epgp,hayword/tfatf_epgp,sheldon/epgp,sheldon/epgp,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf
30da8edab25939b8160fa62e988afe1e56a45b2e
random.lua
random.lua
local wrap = require 'cwrap' require 'torchcwrap' local interface = wrap.CInterface.new() interface:print( [[ #include "luaT.h" #include "TH.h" ]]) for _,name in ipairs({"seed", "initialSeed"}) do interface:wrap(name, string.format("THRandom_%s",name), {{name='Generator', default=true}, {name="long", creturned=true}}) end interface:wrap('manualSeed', 'THRandom_manualSeed', {{name='Generator', default=true}, {name="long"}}) interface:wrap('getRNGState', 'THLongTensor_getRNGState', {{name='Generator', default=true}, {name='LongTensor',default=true,returned=true,method={default='nil'}} }) interface:wrap('setRNGState', 'THLongTensor_setRNGState', {{name='Generator', default=true}, {name='LongTensor',default=true,returned=true,method={default='nil'}} }) interface:register("random__") interface:print( [[ void torch_random_init(lua_State *L) { torch_Generator_init(L); torch_Generator_new(L); lua_setfield(L, -2, "_gen"); luaL_register(L, NULL, random__); } ]]) interface:tofile(arg[1])
local wrap = require 'cwrap' require 'torchcwrap' local interface = wrap.CInterface.new() interface:print( [[ #include "luaT.h" #include "TH.h" extern void torch_Generator_init(lua_State *L); extern void torch_Generator_new(lua_State *L); ]]) for _,name in ipairs({"seed", "initialSeed"}) do interface:wrap(name, string.format("THRandom_%s",name), {{name='Generator', default=true}, {name="long", creturned=true}}) end interface:wrap('manualSeed', 'THRandom_manualSeed', {{name='Generator', default=true}, {name="long"}}) interface:wrap('getRNGState', 'THLongTensor_getRNGState', {{name='Generator', default=true}, {name='LongTensor',default=true,returned=true,method={default='nil'}} }) interface:wrap('setRNGState', 'THLongTensor_setRNGState', {{name='Generator', default=true}, {name='LongTensor',default=true,returned=true,method={default='nil'}} }) interface:register("random__") interface:print( [[ void torch_random_init(lua_State *L) { torch_Generator_init(L); torch_Generator_new(L); lua_setfield(L, -2, "_gen"); luaL_register(L, NULL, random__); } ]]) interface:tofile(arg[1])
Fix build warnings.
Fix build warnings.
Lua
bsd-3-clause
ujjwalkarn/torch7,yt752/torch7,Atcold/torch7,golden1232004/torch7,hechenfon/torch7,Atcold/torch7,ujjwalkarn/torch7,jlegendary/torch7,Moodstocks/torch7,adamlerer/torch7,LinusU/torch7,eulerreich/torch7,waitwaitforget/torch7,ninjin/torch7,dominikgrewe/torch7,kaustubhcs/torch7,colesbury/torch7,pushups/torch7,dariosena/torch7,wgapl/torch7,WangHong-yang/torch7,chenfsjz/torch7,breakds/torch7,MOUlili/torch7,yozw/torch7,hechenfon/torch7,ominux/torch7,hughperkins/torch7,kod3r/torch7,kidaa/torch7,Moodstocks/torch7,fmassa/torch7,massimobernava/torch7,PrajitR/torch7,rickyHong/torchPlusDQN,wangg12/torch7,massimobernava/torch7,kod3r/torch7,yozw/torch7,ninjin/torch7,jibaro/torch7,u20024804/torch7,Srisai85/torch7,hughperkins/torch7,clementfarabet/torch7,yt752/torch7,jbeich/torch7,0wu/torch7,rickyHong/torchPlusDQN,redbill/torch7,eriche2016/torch7,Peilong/torch7,bartvm/torch7,alexbw/torch7,iamtrask/torch7,wangg12/torch7,LinusU/torch7,kirangonella/torch7,colesbury/torch7,redbill/torch7,ilovecv/torch7,0wu/torch7,hmandal/torch7,kaustubhcs/torch7,ominux/torch7,nicholas-leonard/torch7,PierrotLC/torch7,Cadene/torch7,PierrotLC/torch7,akhti/torch7,nkhuyu/torch7,fmassa/torch7,xindaya/torch7,voidException/torch7,diz-vara/torch7,PrajitR/torch7,nicholas-leonard/torch7,jaak-s/torch7,golden1232004/torch7,xindaya/torch7,rotmanmi/torch7,dominikgrewe/torch7,bnk-iitb/torch7,eulerreich/torch7,hmandal/torch7,WangHong-yang/torch7,mr-justin/torch7,bartvm/torch7,waitwaitforget/torch7,jibaro/torch7,Jai-Chaudhary/torch7,Srisai85/torch7,Jai-Chaudhary/torch7,nkhuyu/torch7,syhw/torch7,clementfarabet/torch7,rotmanmi/torch7,szagoruyko/torch7,douwekiela/torch7,diz-vara/torch7,szagoruyko/torch7,kidaa/torch7,jbeich/torch7,jaak-s/torch7,iamtrask/torch7,douwekiela/torch7,adamlerer/torch7,ilovecv/torch7,breakds/torch7,yaolubrain/torch7,voidException/torch7,wgapl/torch7,stein2013/torch7,wickedfoo/torch7,Peilong/torch7,eriche2016/torch7,wickedfoo/torch7,kirangonella/torch7,yaolubrain/torch7,wheatwaves/torch7,stein2013/torch7,wheatwaves/torch7,mr-justin/torch7,dhruvparamhans/torch7,pushups/torch7,Cadene/torch7,MOUlili/torch7,jlegendary/torch7,u20024804/torch7,dariosena/torch7,syhw/torch7,chenfsjz/torch7,dhruvparamhans/torch7,bnk-iitb/torch7,alexbw/torch7,akhti/torch7
09b4705a33de9307e6502524a09c4bb1d0f46fbe
modules/game_textmessage/textmessage.lua
modules/game_textmessage/textmessage.lua
MessageTypesConf = { ConsoleRed = { color = '#F55E5E', consoleTab = tr('Default') }, ConsoleOrange = { color = '#FE6500', consoleTab = tr('Default') }, ConsoleBlue = { color = '#9F9DFD', consoleTab = tr('Default') }, Warning = { color = '#F55E5E', consoleTab = tr('Server Log'), labelId = 'warningLabel' }, Info = { color = '#00EB00', consoleTab = tr('Server Log'), labelId = 'infoLabel', consoleOption = 'showInfoMessagesInConsole' }, EventAdvance = { color = '#FFFFFF', consoleTab = tr('Server Log'), labelId = 'advanceLabel', consoleOption = 'showEventMessagesInConsole' }, EventDefault = { color = '#FFFFFF', consoleTab = tr('Server Log'), labelId = 'statusLabel', consoleOption = 'showEventMessagesInConsole' }, StatusDefault = { color = '#FFFFFF', consoleTab = tr('Server Log'), labelId = 'statusLabel', consoleOption = 'showStatusMessagesInConsole' }, StatusSmall = { color = '#FFFFFF', labelId = 'statusLabel' }, Private = { color = '#5FF7F7', labelId = 'privateLabel' } } centerTextMessagePanel = nil statusLabel = nil privateLabel = nil warningLabel = nil advanceLabel = nil infoLabel = nil function init() connect(g_game, { onTextMessage = displayMessage, onGameStart = clearMessages }) registerProtocol() g_ui.importStyle('textmessage.otui') centerTextMessagePanel = g_ui.createWidget('Panel', GameInterface.getMapPanel()) centerTextMessagePanel:setId('centerTextMessagePanel') local layout = UIVerticalLayout.create(centerTextMessagePanel) layout:setFitChildren(true) centerTextMessagePanel:setLayout(layout) centerTextMessagePanel:setWidth(360) centerTextMessagePanel:centerIn('parent') warningLabel = createTextMessageLabel('warningLabel', centerTextMessagePanel, 'CenterLabel') advanceLabel = createTextMessageLabel('advanceLabel', centerTextMessagePanel, 'CenterLabel') infoLabel = createTextMessageLabel('infoLabel', centerTextMessagePanel, 'CenterLabel') privateLabel = createTextMessageLabel('privateLabel', GameInterface.getMapPanel(), 'TopCenterLabel') statusLabel = createTextMessageLabel('statusLabel', GameInterface.getMapPanel(), 'BottomLabel') export({ clearMessages = clearMessages, displayStatus = function() displayMessage(MessageTypes.StatusSmall, msg) end, displayEventAdvance = function() displayMessage(MessageTypes.EventAdvance, msg, time) end, displayPrivate = function() displayPrivate(msg, time) end }, 'TextMessage') end function terminate() disconnect(g_game, { onTextMessage = display, onGameStart = clearMessages }) unregisterProtocol() removeEvent(warningLabel.hideEvent) removeEvent(advanceLabel.hideEvent) removeEvent(infoLabel.hideEvent) removeEvent(privateLabel.hideEvent) removeEvent(statusLabel.hideEvent) centerTextMessagePanel:destroy() statusLabel:destroy() privateLabel:destroy() unexport('TextMessage') end function clearMessages() warningLabel:hide() advanceLabel:hide() infoLabel:hide() privateLabel:hide() statusLabel:hide() end function createTextMessageLabel(id, parent, class) local label = g_ui.createWidget(class, parent) label:setFont('verdana-11px-rounded') label:setId(id) return label end function displayMessage(msgtype, msg, time) if not g_game.isOnline() then return end msgtypeconf = MessageTypesConf[msgtype] if msgtypeconf.consoleTab ~= nil then if msgtypeconf.consoleOption == nil or Options.getOption(msgtypeconf.consoleOption) then Console.addText(msg, msgtypeconf, msgtypeconf.consoleTab) end end if msgtypeconf.labelId then local label = GameInterface.getMapPanel():recursiveGetChildById(msgtypeconf.labelId) label:setText(msg) label:setColor(msgtypeconf.color) if not time then time = math.max(#msg * 100, 4000) else time = time * 1000 end removeEvent(label.hideEvent) addEvent(function() label:setVisible(true) end) label.hideEvent = scheduleEvent(function() label:setVisible(false) end, time) end end
MessageTypes = { ConsoleRed = { color = '#F55E5E', consoleTab = tr('Default') }, ConsoleOrange = { color = '#FE6500', consoleTab = tr('Default') }, ConsoleBlue = { color = '#9F9DFD', consoleTab = tr('Default') }, Warning = { color = '#F55E5E', consoleTab = tr('Server Log'), labelId = 'warningLabel' }, Info = { color = '#00EB00', consoleTab = tr('Server Log'), labelId = 'infoLabel', consoleOption = 'showInfoMessagesInConsole' }, EventAdvance = { color = '#FFFFFF', consoleTab = tr('Server Log'), labelId = 'advanceLabel', consoleOption = 'showEventMessagesInConsole' }, EventDefault = { color = '#FFFFFF', consoleTab = tr('Server Log'), labelId = 'statusLabel', consoleOption = 'showEventMessagesInConsole' }, StatusDefault = { color = '#FFFFFF', consoleTab = tr('Server Log'), labelId = 'statusLabel', consoleOption = 'showStatusMessagesInConsole' }, StatusSmall = { color = '#FFFFFF', labelId = 'statusLabel' }, Private = { color = '#5FF7F7', labelId = 'privateLabel' } } centerTextMessagePanel = nil statusLabel = nil privateLabel = nil warningLabel = nil advanceLabel = nil infoLabel = nil function init() connect(g_game, { onTextMessage = displayMessage, onGameStart = clearMessages }) registerProtocol() g_ui.importStyle('textmessage.otui') centerTextMessagePanel = g_ui.createWidget('Panel', GameInterface.getMapPanel()) centerTextMessagePanel:setId('centerTextMessagePanel') local layout = UIVerticalLayout.create(centerTextMessagePanel) layout:setFitChildren(true) centerTextMessagePanel:setLayout(layout) centerTextMessagePanel:setWidth(360) centerTextMessagePanel:centerIn('parent') warningLabel = createTextMessageLabel('warningLabel', centerTextMessagePanel, 'CenterLabel') advanceLabel = createTextMessageLabel('advanceLabel', centerTextMessagePanel, 'CenterLabel') infoLabel = createTextMessageLabel('infoLabel', centerTextMessagePanel, 'CenterLabel') privateLabel = createTextMessageLabel('privateLabel', GameInterface.getMapPanel(), 'TopCenterLabel') statusLabel = createTextMessageLabel('statusLabel', GameInterface.getMapPanel(), 'BottomLabel') export({ clearMessages = clearMessages, displayStatus = function(msg, time) displayMessage('StatusSmall', msg) end, displayEventAdvance = function(msg, time) displayMessage('EventAdvance', msg, time) end, displayPrivate = function(msg, time) displayMessage('Private', time) end }, 'TextMessage') end function terminate() disconnect(g_game, { onTextMessage = display, onGameStart = clearMessages }) unregisterProtocol() removeEvent(warningLabel.hideEvent) removeEvent(advanceLabel.hideEvent) removeEvent(infoLabel.hideEvent) removeEvent(privateLabel.hideEvent) removeEvent(statusLabel.hideEvent) centerTextMessagePanel:destroy() statusLabel:destroy() privateLabel:destroy() unexport('TextMessage') end function clearMessages() warningLabel:hide() advanceLabel:hide() infoLabel:hide() privateLabel:hide() statusLabel:hide() end function createTextMessageLabel(id, parent, class) local label = g_ui.createWidget(class, parent) label:setFont('verdana-11px-rounded') label:setId(id) return label end function displayMessage(msgtype, msg, time) if not g_game.isOnline() then return end msgtype = MessageTypes[msgtype] if msgtype.consoleTab ~= nil then if msgtype.consoleOption == nil or Options.getOption(msgtype.consoleOption) then Console.addText(msg, msgtype, msgtype.consoleTab) end end if msgtype.labelId then local label = GameInterface.getMapPanel():recursiveGetChildById(msgtype.labelId) label:setText(msg) label:setColor(msgtype.color) if not time then time = math.max(#msg * 100, 4000) else time = time * 1000 end removeEvent(label.hideEvent) addEvent(function() label:setVisible(true) end) label.hideEvent = scheduleEvent(function() label:setVisible(false) end, time) end end
Fixes errors in textmessage
Fixes errors in textmessage
Lua
mit
dreamsxin/otclient,gpedro/otclient,Radseq/otclient,gpedro/otclient,EvilHero90/otclient,EvilHero90/otclient,Cavitt/otclient_mapgen,kwketh/otclient,dreamsxin/otclient,kwketh/otclient,Radseq/otclient,gpedro/otclient,dreamsxin/otclient,Cavitt/otclient_mapgen
663a0c06b8e9b95ab555695273c00b1b4f9f36af
data/dist/shooter/main.lua
data/dist/shooter/main.lua
oldprint = print print = function(...) local args = { n = select("#", ...), ... } local t = "" for i=1,args.n do t = t .. tostring(args[i]) end oldprint(t) end print('Hello world') IsDown = function(key) return key.state > 0.1 end WasDown = function(key) return key.last_state > 0.1 end JustPressed = function(key) return IsDown(key) and not WasDown(key) end StarRandom = Math.NewRandom() Types = { Pos2= Registry.GetPosition2Id(), Sprite= Registry.GetSpriteId(), Player= Registry.New("Player"), MoveUp= Registry.New("MoveUp"), Star= Registry.New("Star", function(args) c = {} c.speed = args:GetNumber("speed") + StarRandom:NextRangeFloat(args:GetNumber("random_boost")) return c end), DestroyOutside= Registry.New("DestroyOutside"), TimeOut= Registry.New("TimeOut", function() c = {} c.time = 4 return c end) } -- todo: create some on init callback, to spawn the stars -- or enter level callback -- or init callback on entity that is directly destroyed, or keep spawning points -- move sprite anchor to config Systems.OnInit("place star", {Types.Pos2, Types.Star}, function(entity) local vec = Registry.GetPosition2vec(entity) local p = StarRandom:NextPoint2(Camera.GetRect()) vec.x = p.x vec.y = p.y end) Systems.AddUpdate("star movement", function(dt) local ents = Registry.Entities({Types.Sprite, Types.Star}) for _, entity in pairs(ents) do local star = Registry.Get(entity, Types.Star) local vec = Registry.GetPosition2vec(entity) if vec ~= null then vec.y = vec.y - dt * star.speed; local vy = vec.y -- print("Moving star to ", vy) if vy < 0.0 then vec.x = StarRandom:NextRangeFloat(Camera.GetRect():GetWidth()) vec.y = vec.y + Camera.GetRect():GetHeight() print("Reseting star to ", vec.x, " ", vec.y) end end end end) -- todo: new update function -- Systems.OnUpdate("move up", [Types.Pos2, Types.MoveUp], function(dt, entities) { }); time = 0 bark = 0 Systems.AddUpdate("bark", function(dt) time = time + dt if time>1 then time = time - 1 bark = bark + 1 print('Bark!', bark) end end) Systems.AddUpdate("move up", function(dt) local ents = Registry.Entities({Types.Pos2, Types.MoveUp}) for _, entity in pairs(ents) do local vec = Registry.GetPosition2vec(entity) if vec ~= null then local speed = 250 vec.y = vec.y + dt * speed end end end) Systems.AddUpdate("time out", function(dt) local ents = Registry.Entities({Types.TimeOut}); for _, entity in pairs(ents) do local data = Registry.Get(entity, Types.TimeOut) data.time = data.time - dt if data.time < 0 then print("Timeout") Registry.DestroyEntity(entity) end end end) Systems.AddUpdate("destroy outside", function (dt) local ents = Registry.Entities({Types.Sprite, Types.Pos2, Types.DestroyOutside}) for _, entity in pairs(ents) do local sp = Registry.GetSprite(entity) local p = Registry.GetPosition2(entity) if sp ~= null then local cam = Camera.GetRect() local r = sp.GetRect(p) if not cam:Contains(r) then Registry.DestroyEntity(entity) end end end end) shotTemplate = Templates.Find("shot") Systems.AddUpdate("player", function(dt) ents = Registry.Entities({Types.Pos2, Types.Player}) for _, entity in pairs(ents) do local vec = Registry.GetPosition2vec(entity) if vec ~= null then local speed = 150 local vertical = Input.up.state - Input.down.state local horizontal = Input.right.state - Input.left.state if JustPressed(Input.fire) then if not shotTemplate then print("no shot") else local shot = shotTemplate:Create() local v = Registry.GetPosition2vec(shot) if v ~= null then v.x = vec.x v.y = vec.y end end end vec.y = vec.y + dt * speed * vertical vec.x = vec.x + dt * speed * horizontal end end end)
oldprint = print print = function(...) local args = { n = select("#", ...), ... } local t = "" for i=1,args.n do t = t .. tostring(args[i]) end oldprint(t) end print('Hello world') IsDown = function(key) return key.state > 0.1 end WasDown = function(key) return key.last_state > 0.1 end JustPressed = function(key) return IsDown(key) and not WasDown(key) end StarRandom = Math.NewRandom() Types = { Pos2= Registry.GetPosition2Id(), Sprite= Registry.GetSpriteId(), Player= Registry.New("Player"), MoveUp= Registry.New("MoveUp"), Star= Registry.New("Star", function(args) c = {} c.speed = args:GetNumber("speed") + StarRandom:NextRangeFloat(args:GetNumber("random_boost")) return c end), DestroyOutside= Registry.New("DestroyOutside"), TimeOut= Registry.New("TimeOut", function() c = {} c.time = 4 return c end) } -- todo: create some on init callback, to spawn the stars -- or enter level callback -- or init callback on entity that is directly destroyed, or keep spawning points -- move sprite anchor to config Systems.OnInit("place star", {Types.Pos2, Types.Star}, function(entity) local vec = Registry.GetPosition2vec(entity) local p = StarRandom:NextPoint2(Camera.GetRect()) vec.x = p.x vec.y = p.y end) Systems.AddUpdate("star movement", function(dt) local ents = Registry.Entities({Types.Sprite, Types.Star}) for _, entity in pairs(ents) do local star = Registry.Get(entity, Types.Star) local vec = Registry.GetPosition2vec(entity) if vec ~= null then vec.y = vec.y - dt * star.speed; local vy = vec.y -- print("Moving star to ", vy) if vy < 0.0 then vec.x = StarRandom:NextRangeFloat(Camera.GetRect():GetWidth()) vec.y = vec.y + Camera.GetRect():GetHeight() print("Reseting star to ", vec.x, " ", vec.y) end end end end) -- todo: new update function -- Systems.OnUpdate("move up", [Types.Pos2, Types.MoveUp], function(dt, entities) { }); time = 0 bark = 0 Systems.AddUpdate("bark", function(dt) time = time + dt if time>1 then time = time - 1 bark = bark + 1 print('Bark!', bark) end end) Systems.AddUpdate("move up", function(dt) local ents = Registry.Entities({Types.Pos2, Types.MoveUp}) for _, entity in pairs(ents) do local vec = Registry.GetPosition2vec(entity) if vec ~= null then local speed = 250 vec.y = vec.y + dt * speed end end end) Systems.AddUpdate("time out", function(dt) local ents = Registry.Entities({Types.TimeOut}); for _, entity in pairs(ents) do local data = Registry.Get(entity, Types.TimeOut) data.time = data.time - dt if data.time < 0 then print("Timeout") Registry.DestroyEntity(entity) end end end) Systems.AddUpdate("destroy outside", function (dt) local ents = Registry.Entities({Types.Sprite, Types.Pos2, Types.DestroyOutside}) for _, entity in pairs(ents) do local sp = Registry.GetSprite(entity) local p = Registry.GetPosition2(entity) if sp ~= null then local cam = Camera.GetRect() local r = sp.GetRect(p) if not cam:Contains(r) then Registry.DestroyEntity(entity) end end end end) shotTemplate = Templates.Find("shot") Systems.AddUpdate("player", function(dt) ents = Registry.Entities({Types.Pos2, Types.Player}) for _, entity in pairs(ents) do local vec = Registry.GetPosition2vec(entity) if vec ~= null then local speed = 150 local vertical = Input.up.state - Input.down.state local horizontal = Input.right.state - Input.left.state if JustPressed(Input.fire) then if not shotTemplate then print("no shot") else local shot = shotTemplate:Create() local v = Registry.GetPosition2vec(shot) if v ~= null then v.x = vec.x v.y = vec.y end end end vec.y = vec.y + dt * speed * vertical vec.x = vec.x + dt * speed * horizontal end end end)
fixed indentation to 4 spaces
fixed indentation to 4 spaces
Lua
mit
madeso/euphoria,madeso/euphoria,madeso/euphoria,madeso/euphoria,madeso/euphoria,madeso/euphoria
1f91548c6e434128a2dae13061ccc31274f65265
waifu2x.lua
waifu2x.lua
local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)() package.path = path.join(path.dirname(__FILE__), "lib", "?.lua;") .. package.path require 'sys' require 'pl' require 'w2nn' local iproc = require 'iproc' local reconstruct = require 'reconstruct' local image_loader = require 'image_loader' torch.setdefaulttensortype('torch.FloatTensor') local function convert_image(opt) local x, alpha = image_loader.load_float(opt.i) local new_x = nil local t = sys.clock() if opt.o == "(auto)" then local name = path.basename(opt.i) local e = path.extension(name) local base = name:sub(0, name:len() - e:len()) opt.o = path.join(path.dirname(opt.i), string.format("%s(%s).png", base, opt.m)) end if opt.m == "noise" then local model = torch.load(path.join(opt.model_dir, ("noise%d_model.t7"):format(opt.noise_level)), "ascii") --local srcnn = require 'lib/srcnn' --local model = srcnn.waifu2x("rgb"):cuda() model:evaluate() new_x = reconstruct.image(model, x, opt.crop_size) elseif opt.m == "scale" then local model = torch.load(path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)), "ascii") model:evaluate() new_x = reconstruct.scale(model, opt.scale, x, opt.crop_size) elseif opt.m == "noise_scale" then local noise_model = torch.load(path.join(opt.model_dir, ("noise%d_model.t7"):format(opt.noise_level)), "ascii") local scale_model = torch.load(path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)), "ascii") noise_model:evaluate() scale_model:evaluate() x = reconstruct.image(noise_model, x) new_x = reconstruct.scale(scale_model, opt.scale, x, opt.crop_size) else error("undefined method:" .. opt.method) end image_loader.save_png(opt.o, new_x, alpha) print(opt.o .. ": " .. (sys.clock() - t) .. " sec") end local function convert_frames(opt) local noise1_model = torch.load(path.join(opt.model_dir, "noise1_model.t7"), "ascii") local noise2_model = torch.load(path.join(opt.model_dir, "noise2_model.t7"), "ascii") local scale_model = torch.load(path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)), "ascii") noise1_model:evaluate() noise2_model:evaluate() scale_model:evaluate() local fp = io.open(opt.l) local count = 0 local lines = {} for line in fp:lines() do table.insert(lines, line) end fp:close() for i = 1, #lines do if opt.resume == 0 or path.exists(string.format(opt.o, i)) == false then local x, alpha = image_loader.load_float(lines[i]) local new_x = nil if opt.m == "noise" and opt.noise_level == 1 then new_x = reconstruct.image(noise1_model, x, opt.crop_size) elseif opt.m == "noise" and opt.noise_level == 2 then new_x = reconstruct.image(noise2_model, x) elseif opt.m == "scale" then new_x = reconstruct.scale(scale_model, opt.scale, x, opt.crop_size) elseif opt.m == "noise_scale" and opt.noise_level == 1 then x = reconstruct.image(noise1_model, x) new_x = reconstruct.scale(scale_model, opt.scale, x, opt.crop_size) elseif opt.m == "noise_scale" and opt.noise_level == 2 then x = reconstruct.image(noise2_model, x) new_x = reconstruct.scale(scale_model, opt.scale, x, opt.crop_size) else error("undefined method:" .. opt.method) end local output = nil if opt.o == "(auto)" then local name = path.basename(lines[i]) local e = path.extension(name) local base = name:sub(0, name:len() - e:len()) output = path.join(path.dirname(opt.i), string.format("%s(%s).png", base, opt.m)) else output = string.format(opt.o, i) end image_loader.save_png(output, new_x, alpha) xlua.progress(i, #lines) if i % 10 == 0 then collectgarbage() end else xlua.progress(i, #lines) end end end local function waifu2x() local cmd = torch.CmdLine() cmd:text() cmd:text("waifu2x") cmd:text("Options:") cmd:option("-i", "images/miku_small.png", 'path of the input image') cmd:option("-l", "", 'path of the image-list') cmd:option("-scale", 2, 'scale factor') cmd:option("-o", "(auto)", 'path of the output file') cmd:option("-model_dir", "./models/anime_style_art_rgb", 'model directory') cmd:option("-m", "noise_scale", 'method (noise|scale|noise_scale)') cmd:option("-noise_level", 1, '(1|2)') cmd:option("-crop_size", 128, 'patch size per process') cmd:option("-resume", 0, "skip existing files (0|1)") cmd:option("-thread", -1, "number of CPU threads") local opt = cmd:parse(arg) if opt.thread > 0 then torch.setnumthreads(opt.thread) end if cudnn then cudnn.fastest = true cudnn.benchmark = false end if string.len(opt.l) == 0 then convert_image(opt) else convert_frames(opt) end end waifu2x()
local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)() package.path = path.join(path.dirname(__FILE__), "lib", "?.lua;") .. package.path require 'sys' require 'pl' require 'w2nn' local iproc = require 'iproc' local reconstruct = require 'reconstruct' local image_loader = require 'image_loader' torch.setdefaulttensortype('torch.FloatTensor') local function convert_image(opt) local x, alpha = image_loader.load_float(opt.i) local new_x = nil local t = sys.clock() if opt.o == "(auto)" then local name = path.basename(opt.i) local e = path.extension(name) local base = name:sub(0, name:len() - e:len()) opt.o = path.join(path.dirname(opt.i), string.format("%s_%s.png", base, opt.m)) end if opt.m == "noise" then local model_path = path.join(opt.model_dir, ("noise%d_model.t7"):format(opt.noise_level)) local model = torch.load(model_path, "ascii") if not model then error("Load Error: " .. model_path) end new_x = reconstruct.image(model, x, opt.crop_size) elseif opt.m == "scale" then local model_path = path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)) local model = torch.load(model_path, "ascii") if not model then error("Load Error: " .. model_path) end new_x = reconstruct.scale(model, opt.scale, x, opt.crop_size) elseif opt.m == "noise_scale" then local noise_model_path = path.join(opt.model_dir, ("noise%d_model.t7"):format(opt.noise_level)) local noise_model = torch.load(noise_model_path, "ascii") local scale_model_path = path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)) local scale_model = torch.load(scale_model_path, "ascii") if not noise_model then error("Load Error: " .. noise_model_path) end if not scale_model then error("Load Error: " .. scale_model_path) end x = reconstruct.image(noise_model, x) new_x = reconstruct.scale(scale_model, opt.scale, x, opt.crop_size) else error("undefined method:" .. opt.method) end image_loader.save_png(opt.o, new_x, alpha) print(opt.o .. ": " .. (sys.clock() - t) .. " sec") end local function convert_frames(opt) local noise1_model, noise2_model, scale_model if opt.m == "scale" then local model_path = path.join(opt.model_dir, ("scale%.1fx_model.t7"):format(opt.scale)) scale_model = torch.load(model_path, "ascii") if not scale_model then error("Load Error: " .. model_path) end elseif opt.m == "noise" and opt.noise_level == 1 then local model_path = path.join(opt.model_dir, "noise1_model.t7") noise1_model = torch.load(model_path, "ascii") if not noise1_model then error("Load Error: " .. model_path) end elseif opt.m == "noise" and opt.noise_level == 2 then local model_path = path.join(opt.model_dir, "noise2_model.t7") noise2_model = torch.load(model_path, "ascii") if not noise2_model then error("Load Error: " .. model_path) end end local fp = io.open(opt.l) if not fp then error("Open Error: " .. opt.l) end local count = 0 local lines = {} for line in fp:lines() do table.insert(lines, line) end fp:close() for i = 1, #lines do if opt.resume == 0 or path.exists(string.format(opt.o, i)) == false then local x, alpha = image_loader.load_float(lines[i]) local new_x = nil if opt.m == "noise" and opt.noise_level == 1 then new_x = reconstruct.image(noise1_model, x, opt.crop_size) elseif opt.m == "noise" and opt.noise_level == 2 then new_x = reconstruct.image(noise2_model, x) elseif opt.m == "scale" then new_x = reconstruct.scale(scale_model, opt.scale, x, opt.crop_size) elseif opt.m == "noise_scale" and opt.noise_level == 1 then x = reconstruct.image(noise1_model, x) new_x = reconstruct.scale(scale_model, opt.scale, x, opt.crop_size) elseif opt.m == "noise_scale" and opt.noise_level == 2 then x = reconstruct.image(noise2_model, x) new_x = reconstruct.scale(scale_model, opt.scale, x, opt.crop_size) else error("undefined method:" .. opt.method) end local output = nil if opt.o == "(auto)" then local name = path.basename(lines[i]) local e = path.extension(name) local base = name:sub(0, name:len() - e:len()) output = path.join(path.dirname(opt.i), string.format("%s(%s).png", base, opt.m)) else output = string.format(opt.o, i) end image_loader.save_png(output, new_x, alpha) xlua.progress(i, #lines) if i % 10 == 0 then collectgarbage() end else xlua.progress(i, #lines) end end end local function waifu2x() local cmd = torch.CmdLine() cmd:text() cmd:text("waifu2x") cmd:text("Options:") cmd:option("-i", "images/miku_small.png", 'path of the input image') cmd:option("-l", "", 'path of the image-list') cmd:option("-scale", 2, 'scale factor') cmd:option("-o", "(auto)", 'path of the output file') cmd:option("-model_dir", "./models/anime_style_art_rgb", 'model directory') cmd:option("-m", "noise_scale", 'method (noise|scale|noise_scale)') cmd:option("-noise_level", 1, '(1|2)') cmd:option("-crop_size", 128, 'patch size per process') cmd:option("-resume", 0, "skip existing files (0|1)") cmd:option("-thread", -1, "number of CPU threads") local opt = cmd:parse(arg) if opt.thread > 0 then torch.setnumthreads(opt.thread) end if cudnn then cudnn.fastest = true cudnn.benchmark = false end if string.len(opt.l) == 0 then convert_image(opt) else convert_frames(opt) end end waifu2x()
Fix model loading error when using ukbench model; Add error handling
Fix model loading error when using ukbench model; Add error handling
Lua
mit
higankanshi/waifu2x,higankanshi/waifu2x,higankanshi/waifu2x,Spitfire1900/upscaler,nagadomi/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,zyhkz/waifu2x,vitaliylag/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,vitaliylag/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,vitaliylag/waifu2x,Spitfire1900/upscaler
cbfd8651370aabedcd4f0285de8630ae3958ce4e
src/plugins/lua/emails.lua
src/plugins/lua/emails.lua
-- Emails is module for different checks for emails inside messages -- Rules format: -- symbol = sym, map = file:///path/to/file, domain_only = yes -- symbol = sym2, dnsbl = bl.somehost.com, domain_only = no local rules = {} local logger = require "rspamd_logger" -- Check rule for a single email local function check_email_rule(task, rule, addr) local function emails_dns_cb(resolver, to_resolve, results, err) task:inc_dns_req() if results then logger.info(string.format('<%s> email: [%s] resolved for symbol: %s', task:get_message():get_message_id(), to_resolve, rule['symbol'])) task:insert_result(rule['symbol'], 1) end end if rule['dnsbl'] then local to_resolve = '' if rule['domain_only'] then to_resolve = string.format('%s.%s', addr:get_host(), rule['dnsbl']) else to_resolve = string.format('%s.%s.%s', addr:get_user(), addr:get_host(), rule['dnsbl']) end task:get_resolver():resolve_a(task:get_session(), task:get_mempool(), to_resolve, emails_dns_cb) elseif rule['map'] then if rule['domain_only'] then local key = addr:get_host() if rule['map']:get_key(key) then task:insert_result(rule['symbol'], 1) logger.info(string.format('<%s> email: \'%s\' is found in list: %s', task:get_message():get_message_id(), key, rule['symbol'])) end else local key = string.format('%s@%s', addr:get_user(), addr:get_host()) if rule['map']:get_key(key) then task:insert_result(rule['symbol'], 1) logger.info(string.format('<%s> email: \'%s\' is found in list: %s', task:get_message():get_message_id(), key, rule['symbol'])) end end end end -- Check email local function check_emails(task) local emails = task:get_emails() local checked = {} if emails then for _,addr in ipairs(emails) do local to_check = string.format('%s@%s', addr:get_user(), addr:get_host()) if not checked['to_check'] then for _,rule in ipairs(rules) do check_email_rule(task, rule, addr) end checked[to_check] = true end end end end -- Registration if type(rspamd_config.get_api_version) ~= 'nil' then if rspamd_config:get_api_version() >= 2 then rspamd_config:register_module_option('emails', 'rule', 'string') else logger.err('Invalid rspamd version for this plugin') end end local opts = rspamd_config:get_all_opt('emails', 'rule') if opts and type(opts) == 'table' then for k,v in pairs(opts) do if k == 'rule' and type(v) == 'table' then local rule = v if not rule['symbol'] then rule['symbol'] = k end if rule['map'] then rule['name'] = rule['map'] rule['map'] = rspamd_config:add_hash_map (rule['name']) end if not rule['symbol'] or (not rule['map'] and not rule['dnsbl']) then logger.err('incomplete rule') else table.insert(rules, rule) rspamd_config:register_virtual_symbol(rule['symbol'], 1.0) end end end end if table.maxn(rules) > 0 then -- add fake symbol to check all maps inside a single callback if type(rspamd_config.get_api_version) ~= 'nil' then rspamd_config:register_callback_symbol('EMAILS', 1.0, check_emails) else rspamd_config:register_symbol('EMAILS', 1.0, check_emails) end end
-- Emails is module for different checks for emails inside messages -- Rules format: -- symbol = sym, map = file:///path/to/file, domain_only = yes -- symbol = sym2, dnsbl = bl.somehost.com, domain_only = no local rules = {} local logger = require "rspamd_logger" -- Check rule for a single email local function check_email_rule(task, rule, addr) local function emails_dns_cb(resolver, to_resolve, results, err) task:inc_dns_req() if results then logger.info(string.format('<%s> email: [%s] resolved for symbol: %s', task:get_message_id(), to_resolve, rule['symbol'])) task:insert_result(rule['symbol'], 1) end end if rule['dnsbl'] then local to_resolve = '' if rule['domain_only'] then to_resolve = string.format('%s.%s', addr:get_host(), rule['dnsbl']) else to_resolve = string.format('%s.%s.%s', addr:get_user(), addr:get_host(), rule['dnsbl']) end task:get_resolver():resolve_a(task:get_session(), task:get_mempool(), to_resolve, emails_dns_cb) elseif rule['map'] then if rule['domain_only'] then local key = addr:get_host() if rule['map']:get_key(key) then task:insert_result(rule['symbol'], 1) logger.info(string.format('<%s> email: \'%s\' is found in list: %s', task:get_message_id(), key, rule['symbol'])) end else local key = string.format('%s@%s', addr:get_user(), addr:get_host()) if rule['map']:get_key(key) then task:insert_result(rule['symbol'], 1) logger.info(string.format('<%s> email: \'%s\' is found in list: %s', task:get_message_id(), key, rule['symbol'])) end end end end -- Check email local function check_emails(task) local emails = task:get_emails() local checked = {} if emails then for _,addr in ipairs(emails) do local to_check = string.format('%s@%s', addr:get_user(), addr:get_host()) if not checked['to_check'] then for _,rule in ipairs(rules) do check_email_rule(task, rule, addr) end checked[to_check] = true end end end end -- Registration if type(rspamd_config.get_api_version) ~= 'nil' then if rspamd_config:get_api_version() >= 2 then rspamd_config:register_module_option('emails', 'rule', 'string') else logger.err('Invalid rspamd version for this plugin') end end local opts = rspamd_config:get_all_opt('emails', 'rule') if opts and type(opts) == 'table' then for k,v in pairs(opts) do if k == 'rule' and type(v) == 'table' then local rule = v if not rule['symbol'] then rule['symbol'] = k end if rule['map'] then rule['name'] = rule['map'] rule['map'] = rspamd_config:add_hash_map (rule['name']) end if not rule['symbol'] or (not rule['map'] and not rule['dnsbl']) then logger.err('incomplete rule') else table.insert(rules, rule) rspamd_config:register_virtual_symbol(rule['symbol'], 1.0) end end end end if table.maxn(rules) > 0 then -- add fake symbol to check all maps inside a single callback if type(rspamd_config.get_api_version) ~= 'nil' then rspamd_config:register_callback_symbol('EMAILS', 1.0, check_emails) else rspamd_config:register_symbol('EMAILS', 1.0, check_emails) end end
Fix emails plugin.
Fix emails plugin.
Lua
bsd-2-clause
AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,amohanta/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,dark-al/rspamd,amohanta/rspamd,minaevmike/rspamd,awhitesong/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,dark-al/rspamd,dark-al/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,amohanta/rspamd,AlexeySa/rspamd,awhitesong/rspamd,awhitesong/rspamd,dark-al/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,amohanta/rspamd,AlexeySa/rspamd,minaevmike/rspamd,dark-al/rspamd,amohanta/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,awhitesong/rspamd
cab87cf5c02abd666713dce397fec2ee6b0e4aee
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
modules/admin-full/luasrc/model/cbi/admin_network/routes.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.tools.webadmin") m = Map("network", translate("Routes"), translate("a_n_routes1")) local routes6 = luci.sys.net.routes6() local bit = require "bit" s = m:section(TypedSection, "route", translate("Static IPv4 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) s:option(Value, "target", translate("Target"), translate("Host-<abbr title=\"Internet Protocol Address\">IP</abbr> or Network")) s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"), translate("if target is a network")).rmemepty = true s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway")) if routes6 then s = m:section(TypedSection, "route6", translate("Static IPv6 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) s:option(Value, "target", translate("Target"), translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address or Network (CIDR)")) s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")).rmempty = true end return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.tools.webadmin") m = Map("network", translate("Routes"), translate("Routes specify over which interface and gateway a certain host or network " .. "can be reached.")) local routes6 = luci.sys.net.routes6() local bit = require "bit" s = m:section(TypedSection, "route", translate("Static IPv4 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) s:option(Value, "target", translate("Target"), translate("Host-<abbr title=\"Internet Protocol Address\">IP</abbr> or Network")) s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"), translate("if target is a network")).rmemepty = true s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway")) if routes6 then s = m:section(TypedSection, "route6", translate("Static IPv6 Routes")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" iface = s:option(ListValue, "interface", translate("Interface")) luci.tools.webadmin.cbi_add_networks(iface) s:option(Value, "target", translate("Target"), translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Address or Network (CIDR)")) s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Gateway")).rmempty = true end return m
modules/admin-full: fix static routes page
modules/admin-full: fix static routes page
Lua
apache-2.0
deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci
9a7e9831774d56234b3a6ed6bd4690c61cebecbb
hindsight/output/executive_summary.lua
hindsight/output/executive_summary.lua
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. --[[ Outputs a executive summary based on the main and crash pings as a derived stream in the specified format one table/file per day. Config: filename = "executive_summary.lua" message_matcher = "Logger == 'fx' && Type == 'executive_summary'" format = "redshift.psv" buffer_path = "/mnt/output" buffer_size = 20 * 1024 * 1024 s3_path = "s3://test" --]] local ds = require "derived_stream" local name = "executive_summary" local schema = { -- column name type length attributes field /function {"Timestamp" ,"TIMESTAMP" ,nil ,"SORTKEY" ,"Timestamp"}, {"activityTimestamp" ,"TIMESTAMP" ,nil ,nil ,"Fields[activityTimestamp]"}, {"profileCreationTimestamp" ,"TIMESTAMP" ,nil ,nil ,"Fields[profileCreationTimestamp]"}, {"buildId" ,"CHAR" ,14 ,nil ,"Fields[appBuildId]"}, {"clientId" ,"CHAR" ,36 ,"DISTKEY" ,"Fields[clientId]"}, {"documentId" ,"CHAR" ,36 ,nil ,"Fields[documentId]"}, {"docType" ,"CHAR" ,36 ,nil ,"Fields[docType]"}, {"country" ,"VARCHAR" ,5 ,nil ,"Fields[geoCountry]"}, {"channel" ,"VARCHAR" ,7 ,nil ,"Fields[appUpdateChannel]"}, {"os" ,"VARCHAR" ,7 ,nil ,"Fields[os]"}, {"osVersion" ,"VARCHAR" ,32 ,nil ,"Fields[osVersion]"}, {"app" ,"VARCHAR" ,32 ,nil ,"Fields[appName]"}, {"version" ,"VARCHAR" ,32 ,nil ,"Fields[appVersion]"}, {"vendor" ,"VARCHAR" ,32 ,nil ,"Fields[appVendor]"}, {"reason" ,"VARCHAR" ,32 ,nil ,"Fields[reason]"}, {'"default"' ,"BOOLEAN" ,nil ,nil ,"Fields[default]"}, {"hours" ,"DOUBLE PRECISION" ,nil ,nil ,"Fields[hours]"}, {"google" ,"INTEGER" ,nil ,nil ,"Fields[google]"}, {"bing" ,"INTEGER" ,nil ,nil ,"Fields[bing]"}, {"yahoo" ,"INTEGER" ,nil ,nil ,"Fields[yahoo]"}, {"other" ,"INTEGER" ,nil ,nil ,"Fields[other]"}, } process_message, timer_event = ds.load_schema(name, schema)
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. --[[ Outputs a executive summary based on the main and crash pings as a derived stream in the specified format one table/file per day. Config: filename = "executive_summary.lua" message_matcher = "Logger == 'fx' && Type == 'executive_summary'" format = "redshift.psv" buffer_path = "/mnt/output" buffer_size = 20 * 1024 * 1024 s3_path = "s3://test" --]] local ds = require "derived_stream" local name = "executive_summary" local schema = { -- column name type length attributes field /function {"Timestamp" ,"TIMESTAMP" ,nil ,"SORTKEY" ,"Timestamp"}, {"activityTimestamp" ,"TIMESTAMP" ,nil ,nil ,"Fields[activityTimestamp]"}, {"profileCreationTimestamp" ,"TIMESTAMP" ,nil ,nil ,"Fields[profileCreationTimestamp]"}, {"buildId" ,"CHAR" ,14 ,nil ,"Fields[buildId]"}, {"clientId" ,"CHAR" ,36 ,"DISTKEY" ,"Fields[clientId]"}, {"documentId" ,"CHAR" ,36 ,nil ,"Fields[documentId]"}, {"docType" ,"CHAR" ,36 ,nil ,"Fields[docType]"}, {"country" ,"VARCHAR" ,5 ,nil ,"Fields[country]"}, {"channel" ,"VARCHAR" ,7 ,nil ,"Fields[channel]"}, {"os" ,"VARCHAR" ,7 ,nil ,"Fields[os]"}, {"osVersion" ,"VARCHAR" ,32 ,nil ,"Fields[osVersion]"}, {"app" ,"VARCHAR" ,32 ,nil ,"Fields[app]"}, {"version" ,"VARCHAR" ,32 ,nil ,"Fields[version]"}, {"vendor" ,"VARCHAR" ,32 ,nil ,"Fields[vendor]"}, {"reason" ,"VARCHAR" ,32 ,nil ,"Fields[reason]"}, {'"default"' ,"BOOLEAN" ,nil ,nil ,"Fields[default]"}, {"hours" ,"DOUBLE PRECISION" ,nil ,nil ,"Fields[hours]"}, {"google" ,"INTEGER" ,nil ,nil ,"Fields[google]"}, {"bing" ,"INTEGER" ,nil ,nil ,"Fields[bing]"}, {"yahoo" ,"INTEGER" ,nil ,nil ,"Fields[yahoo]"}, {"other" ,"INTEGER" ,nil ,nil ,"Fields[other]"}, } process_message, timer_event = ds.load_schema(name, schema)
Fix the Field names to match what is in the executive summary
Fix the Field names to match what is in the executive summary
Lua
mpl-2.0
mozilla-services/data-pipeline,sapohl/data-pipeline,mozilla-services/data-pipeline,whd/data-pipeline,mozilla-services/data-pipeline,acmiyaguchi/data-pipeline,whd/data-pipeline,acmiyaguchi/data-pipeline,acmiyaguchi/data-pipeline,whd/data-pipeline,sapohl/data-pipeline,acmiyaguchi/data-pipeline,sapohl/data-pipeline,mozilla-services/data-pipeline,whd/data-pipeline,sapohl/data-pipeline
18e5e47d1a6cf77d2668cba500356a4d805b16fc
premake5.lua
premake5.lua
newoption { trigger = 'enable-big-endian', description = 'Enable big-endian byte order support (default is little-endian)' } newoption { trigger = 'disable-int64', description = 'Disable 64 bits integers support (enabled by default)' } solution "cborphine" configurations { "Debug", "Release" } platforms { "x64", "x32" } if _OPTIONS['enable-big-endian'] then defines { "CBOR_BIGENDIAN_PLATFORM" } end if not _OPTIONS['disable-int64'] then defines { "CBOR_INT64_SUPPORT" } end project "cborphine" kind "StaticLib" language "C" targetdir "bin/%{cfg.platform}/%{cfg.buildcfg}" includedirs { "./include" } files { "**.h", "src/**.c" } filter "configurations:Debug" defines { "DEBUG" } flags { "Symbols", "FatalWarnings", "FatalCompileWarnings" } filter "configurations:Release" defines { "NDEBUG" } optimize "On" project "cborphine-tests" kind "ConsoleApp" language "C" targetdir "bin/%{cfg.platform}/%{cfg.buildcfg}" includedirs { "./include" } links { "cborphine" } files { "**.h", "test/**.c" } filter "configurations:Debug" defines { "DEBUG" } flags { "Symbols", } filter "configurations:Release" defines { "NDEBUG" } optimize "On"
newoption { trigger = 'enable-big-endian', description = 'Enable big-endian byte order support (default is little-endian)' } newoption { trigger = 'disable-int64', description = 'Disable 64 bits integers support (enabled by default)' } solution "cborphine" configurations { "Debug", "Release" } platforms { "x64", "x32" } if _OPTIONS['enable-big-endian'] then defines { "CBOR_BIGENDIAN_PLATFORM" } end if not _OPTIONS['disable-int64'] then defines { "CBOR_INT64_SUPPORT" } end project "cborphine" kind "StaticLib" language "C" targetdir "bin/%{cfg.platform}/%{cfg.buildcfg}" includedirs { "./include" } files { "**.h", "src/**.c" } filter "configurations:Debug" defines { "DEBUG" } flags { "Symbols", "FatalWarnings", "FatalCompileWarnings" } filter "configurations:Release" defines { "NDEBUG" } optimize "On" project "cborphine-tests" kind "ConsoleApp" language "C" targetdir "bin/%{cfg.platform}/%{cfg.buildcfg}" includedirs { "./include" } links { "cborphine" } files { "**.h", "test/**.c" } filter "configurations:Debug" defines { "DEBUG" } flags { "Symbols" } filter "configurations:Release" defines { "NDEBUG" } optimize "On"
Fix formatting
Fix formatting
Lua
mit
morphim/cborphine,morphim/cborphine
f3ca3a8916d4f62e1e44b7c5f8f45a23a2a70231
lua/main.lua
lua/main.lua
--- Main file called by all tasks on startup -- set up logger before doing anything else local log = require "log" -- set log level log:setLevel("INFO") -- enable logging to file --log:fileEnable() -- globally available utility functions require "utils" local phobos = require "phobos" local dpdk = require "dpdk" local dpdkc = require "dpdkc" local device = require "device" local stp = require "StackTracePlus" local ffi = require "ffi" local memory = require "memory" local serpent = require "Serpent" local argparse = require "argparse" -- all available headers, packets, ... and their utility functions require "proto.proto" -- TODO: add command line switches for this and other luajit-debugging features --require("jit.v").on() local function getStackTrace(err) print(red("[FATAL] Lua error in task %s", PHOBOS_TASK_NAME)) print(stp.stacktrace(err, 2)) end local function run(file, ...) local script, err = loadfile(file) if not script then error(err) end return xpcall(script, getStackTrace, ...) end local function parseCommandLineArgs(...) local args = { ... } local dpdkCfg for i, v in ipairs(args) do -- find --dpdk-config=foo parameter local cfg, count = string.gsub(v, "%-%-dpdk%-config%=", "") if count == 1 then dpdkCfg = cfg else -- is it just a simple number? if tonumber(v) then v = tonumber(v) end args[i] = v end end return args, dpdkCfg end local function master(_, file, ...) memory.testAllocationSpace() PHOBOS_TASK_NAME = "master" local args, cfgFile = parseCommandLineArgs(...) phobos.config.dpdkConfig = cfgFile phobos.config.userscript = file phobos.setupPaths() -- need the userscript first because we want to use the path -- run the userscript local ok = run(file) if not ok then return end local parsedArgs = {} if _G.configure then local parser = argparse() parser:args(unpack(args)) parsedArgs = {xpcall(_G.configure, getStackTrace, parser, unpack(args))} if not parsedArgs[1] then return end table.remove(parsedArgs, 1) -- nothing returned but the parser was used -- just try to call the parser ourselves here if #parsedArgs == 0 and (#parser._arguments ~= 0 or #parser._options ~= 0 or #parser._commands ~= 0) then parsedArgs = {parser:parse()} end end if not phobos.config.skipInit then if not dpdk.init() then log:fatal("Could not initialize DPDK") end end xpcall(_G.master, getStackTrace, unpack(concatArrays(parsedArgs, args))) -- exit program once the master task finishes -- it is up to the user program to wait for slaves to finish, e.g. by calling dpdk.waitForSlaves() end local function slave(args) phobos.setupPaths() -- must be done before parsing the args as they might rely on deserializers loaded by the script local ok = run(phobos.config.userscript) if not ok then return end -- core > max core means this is a shared task if phobos.getCore() > phobos.config.cores[#phobos.config.cores] then -- disabling this warning must be done before deserializing the arguments phobos.disableBadSocketWarning() end args = loadstring(args)() local taskId = args[1] local func = args[2] if not _G[func] then log:fatal("slave function %s not found", func) end --require("jit.p").start("l") --require("jit.dump").on() PHOBOS_TASK_NAME = func PHOBOS_TASK_ID = taskId local results = { select(2, xpcall(_G[func], getStackTrace, select(3, unpackAll(args)))) } local vals = serpent.dump(results) local buf = ffi.new("char[?]", #vals + 1) ffi.copy(buf, vals) ffi.C.task_store_result(taskId, buf) if phobos.running() then local ok, err = pcall(device.reclaimTxBuffers) if ok then memory.freeMemPools() else log:warn("Could not reclaim tx memory: %s", err) end end --require("jit.p").stop() end function main(task, ...) if task == "master" then master(...) elseif task == "slave" then slave(...) else log:fatal("invalid task type %s", task) end end
--- Main file called by all tasks on startup -- set up logger before doing anything else local log = require "log" -- set log level log:setLevel("INFO") -- enable logging to file --log:fileEnable() -- globally available utility functions require "utils" local phobos = require "phobos" local dpdk = require "dpdk" local dpdkc = require "dpdkc" local device = require "device" local stp = require "StackTracePlus" local ffi = require "ffi" local memory = require "memory" local serpent = require "Serpent" local argparse = require "argparse" -- all available headers, packets, ... and their utility functions require "proto.proto" -- TODO: add command line switches for this and other luajit-debugging features --require("jit.v").on() local function getStackTrace(err) print(red("[FATAL] Lua error in task %s", PHOBOS_TASK_NAME)) print(stp.stacktrace(err, 2)) end local function run(file, ...) local script, err = loadfile(file) if not script then error(err) end return xpcall(script, getStackTrace, ...) end local function parseCommandLineArgs(...) local args = { ... } local dpdkCfg for i = #args, 1, -1 do local v = args[i] -- find --dpdk-config=foo parameter local cfg, count = string.gsub(v, "%-%-dpdk%-config%=", "") if count == 1 then dpdkCfg = cfg table.remove(args, i) else -- is it just a simple number? if tonumber(v) then v = tonumber(v) end args[i] = v end end return args, dpdkCfg end local function master(_, file, ...) memory.testAllocationSpace() PHOBOS_TASK_NAME = "master" local args, cfgFile = parseCommandLineArgs(...) phobos.config.dpdkConfig = cfgFile phobos.config.userscript = file phobos.setupPaths() -- need the userscript first because we want to use the path -- run the userscript local ok = run(file) if not ok then return end local parsedArgs = {} if _G.configure then local parser = argparse() parser:args(unpack(args)) parsedArgs = {xpcall(_G.configure, getStackTrace, parser, unpack(args))} if not parsedArgs[1] then return end table.remove(parsedArgs, 1) -- nothing returned but the parser was used -- just try to call the parser ourselves here if #parsedArgs == 0 and (#parser._arguments ~= 0 or #parser._options ~= 0 or #parser._commands ~= 0) then parsedArgs = {parser:parse()} end end if not phobos.config.skipInit then if not dpdk.init() then log:fatal("Could not initialize DPDK") end end xpcall(_G.master, getStackTrace, unpack(concatArrays(parsedArgs, args))) -- exit program once the master task finishes -- it is up to the user program to wait for slaves to finish, e.g. by calling dpdk.waitForSlaves() end local function slave(args) phobos.setupPaths() -- must be done before parsing the args as they might rely on deserializers loaded by the script local ok = run(phobos.config.userscript) if not ok then return end -- core > max core means this is a shared task if phobos.getCore() > phobos.config.cores[#phobos.config.cores] then -- disabling this warning must be done before deserializing the arguments phobos.disableBadSocketWarning() end args = loadstring(args)() local taskId = args[1] local func = args[2] if not _G[func] then log:fatal("slave function %s not found", func) end --require("jit.p").start("l") --require("jit.dump").on() PHOBOS_TASK_NAME = func PHOBOS_TASK_ID = taskId local results = { select(2, xpcall(_G[func], getStackTrace, select(3, unpackAll(args)))) } local vals = serpent.dump(results) local buf = ffi.new("char[?]", #vals + 1) ffi.copy(buf, vals) ffi.C.task_store_result(taskId, buf) if phobos.running() then local ok, err = pcall(device.reclaimTxBuffers) if ok then memory.freeMemPools() else log:warn("Could not reclaim tx memory: %s", err) end end --require("jit.p").stop() end function main(task, ...) if task == "master" then master(...) elseif task == "slave" then slave(...) else log:fatal("invalid task type %s", task) end end
fix --dpdk-conf option
fix --dpdk-conf option
Lua
mit
libmoon/libmoon,libmoon/libmoon,scholzd/libmoon,libmoon/libmoon,emmericp/libmoon,scholzd/libmoon,scholzd/libmoon,emmericp/libmoon,emmericp/libmoon
8a2148921ee83ad7d6846c38199e812b53ea63c2
base/symbols.lua
base/symbols.lua
if not Flang then Flang = {} end Symbols = {} Flang.Symbols = Symbols Symbols.__index = Symbols -- turn the Table of {element, ...} into a table of {element = true, ...} -- will be queried later function Symbols:Set(table) local s = {} for _,v in pairs(table) do s[v] = true end return s end -- Returns true if element in set, nil otherwise function Symbols:contains(set, element) return set[element] end function Symbols:isKeyword(e) return Symbols:contains(Symbols.KEYWORDS, e) end function Symbols:isOneCharacterSymbol(e) return Symbols:contains(Symbols.ONE_CHARACTER_SYMBOLS, e) end function Symbols:isTwoCharacterSymbol(e) return Symbols:contains(Symbols.TWO_CHARACTER_SYMBOLS, e) end Symbols.KEYWORDS = Symbols:Set{ "if", -- "then", "else", -- "elif", -- "endif", "while", "for", -- "loop", -- "endloop", "print", "return", "exit" } Symbols.ONE_CHARACTER_SYMBOLS = Symbols:Set{ "=", "(", ")", "{", "}", "<", ">", "/", "*", "+", "-", "!", "&", ".", ";" } Symbols.TWO_CHARACTER_SYMBOLS = Symbols:Set{ "==", "<=", ">=", -- "<>", "!=", -- "++", -- "**", -- "--", -- "+=", -- "-=", "||" } -- IDENTIFIER_STARTCHARS = string.letters -- IDENTIFIER_CHARS = string.letters + string.digits + "_" -- -- NUMBER_STARTCHARS = string.digits -- NUMBER_CHARS = string.digits + "." IDENTIFIER_STARTCHARS = Symbols:Set{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" } IDENTIFIER_CHARS = Symbols:Set{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "_" } NUMBER_STARTCHARS = Symbols:Set{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"} NUMBER_CHARS = Symbols:Set{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."} STRING_STARTCHARS = Symbols:Set{"'", '"'} WHITESPACE_CHARS = Symbols:Set{" ", "\t", "\n"} ----------------------------------------------------------------------- -- TokenTypes for things other than symbols and keywords ----------------------------------------------------------------------- STRING = "String" IDENTIFIER = "Identifier" NUMBER = "Number" WHITESPACE = "Whitespace" COMMENT = "Comment" EOF = "Eof" -- a = "*" -- print(Symbols:contains(Symbols.KEYWORDS, a)) -- print(Symbols:contains(Symbols.ONE_CHARACTER_SYMBOLS, a)) -- print(Symbols:contains(Symbols.TWO_CHARACTER_SYMBOLS, a)) -- -- a = "!=" -- print(Symbols:isKeyword(a)) -- print(Symbols:isOneCharacterSymbol(a)) -- print(Symbols:isTwoCharacterSymbol(a))
if not Flang then Flang = {} end Symbols = {} Flang.Symbols = Symbols Symbols.__index = Symbols -- turn the Table of {element, ...} into a table of {element = true, ...} -- will be queried later function Symbols.Set(table) local s = {} for _,v in pairs(table) do s[v] = true end return s end -- Returns true if element in set, nil otherwise function Symbols.contains(set, element) return set[element] end function Symbols.isKeyword(e) return Symbols.contains(Symbols.KEYWORDS, e) end function Symbols.isOneCharacterSymbol(e) return Symbols.contains(Symbols.ONE_CHARACTER_SYMBOLS, e) end function Symbols.isTwoCharacterSymbol(e) return Symbols.contains(Symbols.TWO_CHARACTER_SYMBOLS, e) end function Symbols.isWhitespace(e) return Symbols.contains(Symbols.WHITESPACE_CHARS, e) end function Symbols.isIdentifierStartChar(e) return Symbols.contains(Symbols.IDENTIFIER_STARTCHARS, e) end function Symbols.isIdentifierChar(e) return Symbols.contains(Symbols.IDENTIFIER_CHARS, e) end Symbols.KEYWORDS = Symbols.Set{ "if", -- "then", "else", -- "elif", -- "endif", "while", "for", -- "loop", -- "endloop", "print", "return", "exit" } Symbols.ONE_CHARACTER_SYMBOLS = Symbols.Set{ "=", "(", ")", "{", "}", "<", ">", "/", "*", "+", "-", "!", "&", ".", ";" } Symbols.TWO_CHARACTER_SYMBOLS = Symbols.Set{ "==", "<=", ">=", -- "<>", "!=", -- "++", -- "**", -- "--", -- "+=", -- "-=", "||" } -- IDENTIFIER_STARTCHARS = string.letters -- IDENTIFIER_CHARS = string.letters + string.digits + "_" -- -- NUMBER_STARTCHARS = string.digits -- NUMBER_CHARS = string.digits + "." IDENTIFIER_STARTCHARS = Symbols.Set{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" } IDENTIFIER_CHARS = Symbols.Set{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "_" } Symbols.NUMBER_STARTCHARS = Symbols.Set{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"} Symbols.NUMBER_CHARS = Symbols.Set{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."} Symbols.STRING_STARTCHARS = Symbols.Set{"'", '"'} Symbols.WHITESPACE_CHARS = Symbols.Set{" ", "\t", "\n"} ----------------------------------------------------------------------- -- TokenTypes for things other than symbols and keywords ----------------------------------------------------------------------- Symbols.STRING = "String" Symbols.IDENTIFIER = "Identifier" Symbols.NUMBER = "Number" Symbols.WHITESPACE = "Whitespace" Symbols.COMMENT = "Comment" Symbols.EOF = "Eof" -- a = "*" -- print(Symbols.contains(Symbols.KEYWORDS, a)) -- print(Symbols.contains(Symbols.ONE_CHARACTER_SYMBOLS, a)) -- print(Symbols.contains(Symbols.TWO_CHARACTER_SYMBOLS, a)) a = "!=" print(Symbols.isKeyword(a)) print(Symbols.isOneCharacterSymbol(a)) print(Symbols.isTwoCharacterSymbol(a))
Fixed self issue in symbols
Fixed self issue in symbols
Lua
mit
radixdev/flang
3703b70561003bd3cf291a9a2cf323c2dff08053
tests/actions/make/cpp/test_objects.lua
tests/actions/make/cpp/test_objects.lua
-- -- tests/actions/make/cpp/test_objects.lua -- Validate the list of objects for a makefile. -- Copyright (c) 2009-2014 Jason Perkins and the Premake project -- local suite = test.declare("make_cpp_objects") local make = premake.make local project = premake.project -- -- Setup -- local sln, prj function suite.setup() sln = test.createsolution() end local function prepare() prj = premake.solution.getproject(sln, 1) make.cppObjects(prj) end -- -- If a file is listed at the project level, it should get listed in -- the project level objects list. -- function suite.listFileInProjectObjects() files { "src/hello.cpp" } prepare() test.capture [[ OBJECTS := \ $(OBJDIR)/hello.o \ ]] end -- -- Only buildable files should be listed. -- function suite.onlyListBuildableFiles() files { "include/gl.h", "src/hello.cpp" } prepare() test.capture [[ OBJECTS := \ $(OBJDIR)/hello.o \ ]] end -- -- A file should only be listed in the configurations to which it belongs. -- function suite.configFilesAreConditioned() filter "Debug" files { "src/hello_debug.cpp" } filter "Release" files { "src/hello_release.cpp" } prepare() test.capture [[ OBJECTS := \ RESOURCES := \ ifeq ($(config),debug) OBJECTS += \ $(OBJDIR)/hello_debug.o \ endif ifeq ($(config),release) OBJECTS += \ $(OBJDIR)/hello_release.o \ endif ]] end -- -- Two files with the same base name should have different object files. -- function suite.uniqueObjNames_onBaseNameCollision() files { "src/hello.cpp", "src/greetings/hello.cpp" } prepare() test.capture [[ OBJECTS := \ $(OBJDIR)/hello.o \ $(OBJDIR)/hello1.o \ ]] end -- -- If a custom rule builds to an object file, include it in the -- link automatically to match the behavior of Visual Studio -- function suite.customBuildRule() files { "hello.x" } filter "files:**.x" buildmessage "Compiling %{file.name}" buildcommands { 'cxc -c "%{file.path}" -o "%{cfg.objdir}/%{file.basename}.xo"', 'c2o -c "%{cfg.objdir}/%{file.basename}.xo" -o "%{cfg.objdir}/%{file.basename}.obj"' } buildoutputs { "%{cfg.objdir}/%{file.basename}.obj" } prepare() test.capture [[ OBJECTS := \ RESOURCES := \ ifeq ($(config),debug) OBJECTS += \ obj/Debug/hello.obj \ endif ]] end -- -- If a file is excluded from a configuration, it should not be listed. -- function suite.excludedFromBuild_onExcludedFile() files { "hello.cpp" } filter "Debug" removefiles { "hello.cpp" } prepare() test.capture [[ OBJECTS := \ RESOURCES := \ ifeq ($(config),release) OBJECTS += \ $(OBJDIR)/hello.o \ endif ]] end function suite.excludedFromBuild_onExcludeFlag() files { "hello.cpp" } filter { "Debug", "files:hello.cpp" } flags { "ExcludeFromBuild" } prepare() test.capture [[ OBJECTS := \ RESOURCES := \ ifeq ($(config),release) OBJECTS += \ $(OBJDIR)/hello.o \ endif ]] end
-- -- tests/actions/make/cpp/test_objects.lua -- Validate the list of objects for a makefile. -- Copyright (c) 2009-2014 Jason Perkins and the Premake project -- local suite = test.declare("make_cpp_objects") local make = premake.make local project = premake.project -- -- Setup -- local sln, prj function suite.setup() sln = test.createsolution() end local function prepare() prj = premake.solution.getproject(sln, 1) make.cppObjects(prj) end -- -- If a file is listed at the project level, it should get listed in -- the project level objects list. -- function suite.listFileInProjectObjects() files { "src/hello.cpp" } prepare() test.capture [[ OBJECTS := \ $(OBJDIR)/hello.o \ ]] end -- -- Only buildable files should be listed. -- function suite.onlyListBuildableFiles() files { "include/gl.h", "src/hello.cpp" } prepare() test.capture [[ OBJECTS := \ $(OBJDIR)/hello.o \ ]] end -- -- A file should only be listed in the configurations to which it belongs. -- function suite.configFilesAreConditioned() filter "Debug" files { "src/hello_debug.cpp" } filter "Release" files { "src/hello_release.cpp" } prepare() test.capture [[ OBJECTS := \ RESOURCES := \ CUSTOMFILES := \ ifeq ($(config),debug) OBJECTS += \ $(OBJDIR)/hello_debug.o \ endif ifeq ($(config),release) OBJECTS += \ $(OBJDIR)/hello_release.o \ endif ]] end -- -- Two files with the same base name should have different object files. -- function suite.uniqueObjNames_onBaseNameCollision() files { "src/hello.cpp", "src/greetings/hello.cpp" } prepare() test.capture [[ OBJECTS := \ $(OBJDIR)/hello.o \ $(OBJDIR)/hello1.o \ ]] end -- -- If a custom rule builds to an object file, include it in the -- link automatically to match the behavior of Visual Studio -- function suite.customBuildRule() files { "hello.x" } filter "files:**.x" buildmessage "Compiling %{file.name}" buildcommands { 'cxc -c "%{file.path}" -o "%{cfg.objdir}/%{file.basename}.xo"', 'c2o -c "%{cfg.objdir}/%{file.basename}.xo" -o "%{cfg.objdir}/%{file.basename}.obj"' } buildoutputs { "%{cfg.objdir}/%{file.basename}.obj" } prepare() test.capture [[ OBJECTS := \ RESOURCES := \ CUSTOMFILES := \ ifeq ($(config),debug) OBJECTS += \ obj/Debug/hello.obj \ endif ]] end -- -- If a file is excluded from a configuration, it should not be listed. -- function suite.excludedFromBuild_onExcludedFile() files { "hello.cpp" } filter "Debug" removefiles { "hello.cpp" } prepare() test.capture [[ OBJECTS := \ RESOURCES := \ CUSTOMFILES := \ ifeq ($(config),release) OBJECTS += \ $(OBJDIR)/hello.o \ endif ]] end function suite.excludedFromBuild_onExcludeFlag() files { "hello.cpp" } filter { "Debug", "files:hello.cpp" } flags { "ExcludeFromBuild" } prepare() test.capture [[ OBJECTS := \ RESOURCES := \ CUSTOMFILES := \ ifeq ($(config),release) OBJECTS += \ $(OBJDIR)/hello.o \ endif ]] end
Fix unit tests broken by previous commit
Fix unit tests broken by previous commit --HG-- branch : assassini/fix-perfile-custom-build-commands-in-c-g-1411831836712
Lua
bsd-3-clause
annulen/premake,annulen/premake,annulen/premake,annulen/premake
57d75970e21742dbee389c4f7c3d474c09ea815f
core/sile.lua
core/sile.lua
SILE = {} SILE.version = "0.9.3-unreleased" SILE.utilities = require("core/utilities") SU = SILE.utilities SILE.inputs = {} SILE.Commands = {}; SILE.debugFlags = {} SILE.tokenizers = {} if not unpack then unpack = table.unpack end -- 5.3 compatibility std = require("std") SILE.documentState = std.object {}; SILE.scratch = {}; SILE.length = require("core/length") require("core/parserbits") require("core/measurements") require("core/baseclass") SILE.nodefactory = require("core/nodefactory") require("core/settings") require("core/inputs-texlike") require("core/inputs-xml") require("core/inputs-common") require("core/papersizes") require("core/colorparser") require("core/pagebuilder") require("core/typesetter") require("core/hyphenator-liang") require("core/languages") require("core/font") SILE.frameParser = require("core/frameparser") SILE.linebreak = require("core/break") require("core/frame") SILE.init = function() if not SILE.backend then if pcall(function () require("justenoughharfbuzz") end) then SILE.backend = "libtexpdf" elseif pcall(function() require("lgi") end) then SILE.backend = "pangocairo" else SU.error("Neither libtexpdf nor pangocairo backends available!") end end if SILE.backend == "libtexpdf" then require("core/harfbuzz-shaper") require("core/libtexpdf-output") else require("core/pango-shaper") require("core/cairo-output") end if SILE.dolua then _, err = pcall(SILE.dolua) if err then error(err) end end end SILE.require = function(d) -- path? return require(d) end SILE.parseArguments = function() local parser = std.optparse ("This is SILE "..SILE.version..[[ Usage: sile [options] file.sil|file.xml The SILE typesetter. Options: -d, --debug=VALUE debug SILE's operation -b, --backend=VALUE choose between libtexpdf/pangocairo backends -I, --include=[FILE] include a class or SILE file before processing main file -e, --evaluate=VALUE evaluate some Lua code before processing file --version display version information, then exit --help display this help, then exit ]]) parser:on ('--', parser.finished) _G.unparsed, _G.opts = parser:parse(_G.arg) SILE.debugFlags = {} if opts.debug then for k,v in ipairs(std.string.split(opts.debug, ",")) do SILE.debugFlags[v] = 1 end end if opts.backend then SILE.backend = opts.backend end if opts.include then SILE.preamble = opts.include end if opts.evaluate then SILE.dolua,err = loadstring(opts.evaluate) if err then SU.error(err) end end end function SILE.initRepl () SILE._repl = require 'repl.console' local has_linenoise = pcall(require, 'linenoise') if has_linenoise then SILE._repl:loadplugin 'linenoise' else -- XXX check that we're not receiving input from a non-tty local has_rlwrap = os.execute('which rlwrap >/dev/null 2>/dev/null') == 0 if has_rlwrap and not os.getenv 'LUA_REPL_RLWRAP' then local command = 'LUA_REPL_RLWRAP=1 rlwrap' local index = 0 while arg[index - 1] do index = index - 1 end while arg[index] do command = string.format('%s %q', command, arg[index]) index = index + 1 end os.execute(command) return end end SILE._repl:loadplugin 'history' SILE._repl:loadplugin 'completion' SILE._repl:loadplugin 'autoreturn' SILE._repl:loadplugin 'rcfile' end function SILE.repl() if not SILE._repl then SILE.initRepl() end SILE._repl:run() end function SILE.readFile(fn) SILE.currentlyProcessingFile = fn fn = SILE.resolveFile(fn) if not fn then SU.error("Could not find file") end local file, err = io.open(fn) if not file then print("Could not open "..fn..": "..err) return end io.write("<"..fn..">") -- Sniff first few bytes local sniff = file:read("*l") or "" file:seek("set", 0) if sniff:find("<") then SILE.inputs.XML.process(fn) else SILE.inputs.TeXlike.process(fn) end end local function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function SILE.resolveFile(fn) if file_exists(fn) then return fn end if file_exists(fn..".sil") then return fn..".sil" end for k in SU.gtoke(os.getenv("SILE_PATH"), ";") do if k.string then local f = std.io.catfile(k.string, fn) if file_exists(f) then return f end if file_exists(f..".sil") then return f..".sil" end end end end function SILE.call(cmd,options, content) SILE.currentCommand = content if not SILE.Commands[cmd] then SU.error("Unknown command "..cmd) end SILE.Commands[cmd](options or {}, content or {}) end return SILE
SILE = {} SILE.version = "0.9.3-unreleased" SILE.utilities = require("core/utilities") SU = SILE.utilities SILE.inputs = {} SILE.Commands = {}; SILE.debugFlags = {} SILE.tokenizers = {} loadstring = loadstring or load -- 5.3 compatibility if not unpack then unpack = table.unpack end -- 5.3 compatibility std = require("std") SILE.documentState = std.object {}; SILE.scratch = {}; SILE.length = require("core/length") require("core/parserbits") require("core/measurements") require("core/baseclass") SILE.nodefactory = require("core/nodefactory") require("core/settings") require("core/inputs-texlike") require("core/inputs-xml") require("core/inputs-common") require("core/papersizes") require("core/colorparser") require("core/pagebuilder") require("core/typesetter") require("core/hyphenator-liang") require("core/languages") require("core/font") SILE.frameParser = require("core/frameparser") SILE.linebreak = require("core/break") require("core/frame") SILE.init = function() if not SILE.backend then if pcall(function () require("justenoughharfbuzz") end) then SILE.backend = "libtexpdf" elseif pcall(function() require("lgi") end) then SILE.backend = "pangocairo" else SU.error("Neither libtexpdf nor pangocairo backends available!") end end if SILE.backend == "libtexpdf" then require("core/harfbuzz-shaper") require("core/libtexpdf-output") else require("core/pango-shaper") require("core/cairo-output") end if SILE.dolua then _, err = pcall(SILE.dolua) if err then error(err) end end end SILE.require = function(d) -- path? return require(d) end SILE.parseArguments = function() local parser = std.optparse ("This is SILE "..SILE.version..[[ Usage: sile [options] file.sil|file.xml The SILE typesetter. Options: -d, --debug=VALUE debug SILE's operation -b, --backend=VALUE choose between libtexpdf/pangocairo backends -I, --include=[FILE] include a class or SILE file before processing main file -e, --evaluate=VALUE evaluate some Lua code before processing file --version display version information, then exit --help display this help, then exit ]]) parser:on ('--', parser.finished) _G.unparsed, _G.opts = parser:parse(_G.arg) SILE.debugFlags = {} if opts.debug then for k,v in ipairs(std.string.split(opts.debug, ",")) do SILE.debugFlags[v] = 1 end end if opts.backend then SILE.backend = opts.backend end if opts.include then SILE.preamble = opts.include end if opts.evaluate then SILE.dolua,err = loadstring(opts.evaluate) if err then SU.error(err) end end end function SILE.initRepl () SILE._repl = require 'repl.console' local has_linenoise = pcall(require, 'linenoise') if has_linenoise then SILE._repl:loadplugin 'linenoise' else -- XXX check that we're not receiving input from a non-tty local has_rlwrap = os.execute('which rlwrap >/dev/null 2>/dev/null') == 0 if has_rlwrap and not os.getenv 'LUA_REPL_RLWRAP' then local command = 'LUA_REPL_RLWRAP=1 rlwrap' local index = 0 while arg[index - 1] do index = index - 1 end while arg[index] do command = string.format('%s %q', command, arg[index]) index = index + 1 end os.execute(command) return end end SILE._repl:loadplugin 'history' SILE._repl:loadplugin 'completion' SILE._repl:loadplugin 'autoreturn' SILE._repl:loadplugin 'rcfile' end function SILE.repl() if not SILE._repl then SILE.initRepl() end SILE._repl:run() end function SILE.readFile(fn) SILE.currentlyProcessingFile = fn fn = SILE.resolveFile(fn) if not fn then SU.error("Could not find file") end local file, err = io.open(fn) if not file then print("Could not open "..fn..": "..err) return end io.write("<"..fn..">") -- Sniff first few bytes local sniff = file:read("*l") or "" file:seek("set", 0) if sniff:find("<") then SILE.inputs.XML.process(fn) else SILE.inputs.TeXlike.process(fn) end end local function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function SILE.resolveFile(fn) if file_exists(fn) then return fn end if file_exists(fn..".sil") then return fn..".sil" end for k in SU.gtoke(os.getenv("SILE_PATH"), ";") do if k.string then local f = std.io.catfile(k.string, fn) if file_exists(f) then return f end if file_exists(f..".sil") then return f..".sil" end end end end function SILE.call(cmd,options, content) SILE.currentCommand = content if not SILE.Commands[cmd] then SU.error("Unknown command "..cmd) end SILE.Commands[cmd](options or {}, content or {}) end return SILE
(insert standard rant here about Lua making massive incompatible changes between minor versions) Fixes #111
(insert standard rant here about Lua making massive incompatible changes between minor versions) Fixes #111
Lua
mit
simoncozens/sile,neofob/sile,WAKAMAZU/sile_fe,anthrotype/sile,simoncozens/sile,anthrotype/sile,simoncozens/sile,simoncozens/sile,alerque/sile,WAKAMAZU/sile_fe,neofob/sile,anthrotype/sile,WAKAMAZU/sile_fe,alerque/sile,alerque/sile,alerque/sile,anthrotype/sile,WAKAMAZU/sile_fe,neofob/sile,neofob/sile
55d489b7a3be069db1ced7af8d9530cd604a668d
Modules/Gui/Markdown/MarkdownRender.lua
Modules/Gui/Markdown/MarkdownRender.lua
--- Renders the markdown -- See: MarkdownParser -- @classmod MarkdownRender local TextService = game:GetService("TextService") local MarkdownRender = {} MarkdownRender.__index = MarkdownRender MarkdownRender.ClassName = "MarkdownRender" MarkdownRender.SpaceAfterParagraph = 10 MarkdownRender.SpaceAfterHeader = 5 MarkdownRender.TextSize = 18 MarkdownRender.Indent = 30 MarkdownRender.TextColor3 = Color3.fromRGB(56, 56, 56) MarkdownRender.MaxHeaderLevel = 3 -- h5 is the largest --- Creates a new markdown render -- @tparam GuiObject gui -- @tparam number width Width to render at function MarkdownRender.new(gui, width) local self = setmetatable({}, MarkdownRender) self._gui = gui or error("No Gui") self._width = width or error("No width") return self end function MarkdownRender:WithOptions(options) self.TextSize = options.TextSize self.SpaceAfterParagraph = options.SpaceAfterParagraph return self end --- Renders the data in the given Gui -- @param data Data from MarkdownParser function MarkdownRender:Render(data) local height = 0 for index, item in pairs(data) do local gui if type(item) == "string" then gui = self:_renderParagraph(item) gui.Position = UDim2.new(gui.Position.X, UDim.new(0, height)) height = height + gui.Size.Y.Offset if index ~= #data then height = height + self.SpaceAfterParagraph end elseif type(item) == "table" then if item.Type == "List" then gui = self:_renderList(item) gui.Position = UDim2.new(gui.Position.X, UDim.new(0, height)) height = height + gui.Size.Y.Offset if not (type(data[index+1]) == "table" and data[index+1].Type == "List" and data[index+1].Level ~= item.Level) then height = height + self.SpaceAfterParagraph end elseif item.Type == "Header" then gui = self:_renderHeader(item) gui.Position = UDim2.new(gui.Position.X, UDim.new(0, height)) height = height + gui.Size.Y.Offset if index ~= #data then height = height + self.SpaceAfterHeader end else error(("Bad data type '%s'"):format(tostring(item.Type))) end else error("Bad data type") end if gui then gui.Name = ("%d_%s"):format(index, gui.Name) end end self._gui.Size = UDim2.new(self._gui.Size.X, UDim.new(0, height)) end function MarkdownRender:_getFrame() local frame = Instance.new("Frame") frame.BackgroundTransparency = 1 frame.BorderSizePixel = 0 frame.Size = UDim2.new(1, 0, 0, 0) frame.ZIndex = self._gui.ZIndex return frame end function MarkdownRender:_getTextLabel() local textLabel = Instance.new("TextLabel") textLabel.BackgroundTransparency = 1 textLabel.Size = UDim2.new(1, 0, 0, 0) textLabel.ZIndex = self._gui.ZIndex return self:_formatTextLabel(textLabel) end function MarkdownRender:_formatTextLabel(textLabel) textLabel.Font = Enum.Font.SourceSans textLabel.TextColor3 = self.TextColor3 textLabel.TextXAlignment = Enum.TextXAlignment.Left textLabel.TextYAlignment = Enum.TextYAlignment.Top textLabel.TextWrapped = true textLabel.TextSize = self.TextSize textLabel.TextStrokeTransparency = 1 return textLabel end --- Strip ending punctuation which screws with roblox's wordwrapping and .TextFits function MarkdownRender:_renderParagraphLabel(label, text) local labelWidth = label.Size.X.Scale*self._width + label.Size.X.Offset local strippedText = text:gsub("(%p+)$", "") local textSize = TextService:GetTextSize(strippedText, label.TextSize, label.Font, Vector2.new(labelWidth, label.TextSize*20)) label.Size = UDim2.new(label.Size.X, UDim.new(0, textSize.Y)) label.Text = text return label end function MarkdownRender:_renderParagraph(text, options) options = options or {} local label = self:_getTextLabel() label.Text = text label.Name = "Paragraph" label.Parent = options.Parent or self._gui self:_renderParagraphLabel(label, text) return label end function MarkdownRender:_getBullet(level) local bullet = Instance.new("Frame") bullet.Name = "bullet" bullet.BorderSizePixel = 0 bullet.BackgroundColor3 = self.TextColor3 bullet.ZIndex = self._gui.ZIndex if level == 2 then bullet.Size = UDim2.new(0, 6, 0, 1) else bullet.Size = UDim2.new(0, 4, 0, 4) end return bullet end function MarkdownRender:_renderList(listData) assert(type(listData.Level) == "number" and listData.Level > 0) local frame = self:_getFrame() frame.Name = ("List_%d"):format(listData.Level) frame.Size = UDim2.new(1, -(listData.Level)*self.Indent, 0, 0) frame.Position = UDim2.new(0, -frame.Size.X.Offset, 0, 0) frame.Parent = self._gui local height = 0 for index, text in ipairs(listData) do local textLabel = self:_renderParagraph(text, { Parent = frame }) textLabel.Name = ("%d_%s"):format(index, textLabel.Name) textLabel.Position = UDim2.new(textLabel.Position.X, UDim.new(0, height)) local bullet = self:_getBullet(listData.Level) bullet.AnchorPoint = Vector2.new(0.5, 0.5) bullet.Position = UDim2.new(0, -self.Indent/2, 0, self.TextSize/2 + 1) bullet.Parent = textLabel height = height + textLabel.Size.Y.Offset + 2 end frame.Size = UDim2.new(frame.Size.X, UDim.new(0, height)) return frame end function MarkdownRender:_renderHeader(headerData) local label = self:_getTextLabel() label.Name = "Header" .. headerData.Level label.TextSize = self.TextSize + (self.MaxHeaderLevel-headerData.Level) label.TextYAlignment = Enum.TextYAlignment.Center label.Parent = self._gui label.Font = Enum.Font.SourceSansSemibold self:_renderParagraphLabel(label, headerData.Text) label.Size = UDim2.new(label.Size.X, UDim.new(label.Size.Y.Scale, label.Size.Y.Offset + 6)) -- Extra padding local underline = self:_getFrame() underline.Name = "Underline" underline.BackgroundTransparency = 0 underline.BackgroundColor3 = Color3.new(0.9, 0.9, 0.9) underline.Size = UDim2.new(1, 0, 0, 1) underline.AnchorPoint = Vector2.new(0, 1) underline.Position = UDim2.new(0, 0, 1, 0) underline.Parent = label return label end return MarkdownRender
--- Renders the markdown -- See: MarkdownParser -- @classmod MarkdownRender local TextService = game:GetService("TextService") local MarkdownRender = {} MarkdownRender.__index = MarkdownRender MarkdownRender.ClassName = "MarkdownRender" MarkdownRender.SpaceAfterParagraph = 10 MarkdownRender.SpaceAfterHeader = 5 MarkdownRender.SpaceBetweenList = 2 MarkdownRender.TextSize = 18 MarkdownRender.Indent = 30 MarkdownRender.TextColor3 = Color3.fromRGB(56, 56, 56) MarkdownRender.MaxHeaderLevel = 3 -- h5 is the largest --- Creates a new markdown render -- @tparam GuiObject gui -- @tparam number width Width to render at function MarkdownRender.new(gui, width) local self = setmetatable({}, MarkdownRender) self._gui = gui or error("No Gui") self._width = width or error("No width") return self end function MarkdownRender:WithOptions(options) self.TextSize = options.TextSize self.SpaceAfterParagraph = options.SpaceAfterParagraph return self end --- Renders the data in the given Gui -- @param data Data from MarkdownParser function MarkdownRender:Render(data) local height = 0 for index, item in pairs(data) do local gui if type(item) == "string" then gui = self:_renderParagraph(item) gui.Position = UDim2.new(gui.Position.X, UDim.new(0, height)) height = height + gui.Size.Y.Offset if index ~= #data then height = height + self.SpaceAfterParagraph end elseif type(item) == "table" then if item.Type == "List" then gui = self:_renderList(item) gui.Position = UDim2.new(gui.Position.X, UDim.new(0, height)) height = height + gui.Size.Y.Offset local nextIsNestedList = (type(data[index+1]) == "table" and data[index+1].Type == "List" and data[index+1].Level ~= item.Level) if index ~= #data then if nextIsNestedList then height = height + self.SpaceBetweenList else height = height + self.SpaceAfterParagraph end end elseif item.Type == "Header" then gui = self:_renderHeader(item) gui.Position = UDim2.new(gui.Position.X, UDim.new(0, height)) height = height + gui.Size.Y.Offset if index ~= #data then height = height + self.SpaceAfterHeader end else error(("Bad data type '%s'"):format(tostring(item.Type))) end else error("Bad data type") end if gui then gui.Name = ("%d_%s"):format(index, gui.Name) end end self._gui.Size = UDim2.new(self._gui.Size.X, UDim.new(0, height)) end function MarkdownRender:_getFrame() local frame = Instance.new("Frame") frame.BackgroundTransparency = 1 frame.BorderSizePixel = 0 frame.Size = UDim2.new(1, 0, 0, 0) frame.ZIndex = self._gui.ZIndex return frame end function MarkdownRender:_getTextLabel() local textLabel = Instance.new("TextLabel") textLabel.BackgroundTransparency = 1 textLabel.Size = UDim2.new(1, 0, 0, 0) textLabel.ZIndex = self._gui.ZIndex return self:_formatTextLabel(textLabel) end function MarkdownRender:_formatTextLabel(textLabel) textLabel.Font = Enum.Font.SourceSans textLabel.TextColor3 = self.TextColor3 textLabel.TextXAlignment = Enum.TextXAlignment.Left textLabel.TextYAlignment = Enum.TextYAlignment.Top textLabel.TextWrapped = true textLabel.TextSize = self.TextSize textLabel.TextStrokeTransparency = 1 return textLabel end --- Strip ending punctuation which screws with roblox's wordwrapping and .TextFits function MarkdownRender:_renderParagraphLabel(label, text) local labelWidth = label.Size.X.Scale*self._width + label.Size.X.Offset local strippedText = text:gsub("(%p+)$", "") local textSize = TextService:GetTextSize(strippedText, label.TextSize, label.Font, Vector2.new(labelWidth, label.TextSize*20)) label.Size = UDim2.new(label.Size.X, UDim.new(0, textSize.Y)) label.Text = text return label end function MarkdownRender:_renderParagraph(text, options) options = options or {} local label = self:_getTextLabel() label.Text = text label.Name = "Paragraph" label.Parent = options.Parent or self._gui self:_renderParagraphLabel(label, text) return label end function MarkdownRender:_getBullet(level) local bullet = Instance.new("Frame") bullet.Name = "bullet" bullet.BorderSizePixel = 0 bullet.BackgroundColor3 = self.TextColor3 bullet.ZIndex = self._gui.ZIndex if level == 2 then bullet.Size = UDim2.new(0, 6, 0, 1) else bullet.Size = UDim2.new(0, 4, 0, 4) end return bullet end function MarkdownRender:_renderList(listData) assert(type(listData.Level) == "number" and listData.Level > 0) local frame = self:_getFrame() frame.Name = ("List_%d"):format(listData.Level) frame.Size = UDim2.new(1, -(listData.Level)*self.Indent, 0, 0) frame.Position = UDim2.new(0, -frame.Size.X.Offset, 0, 0) frame.Parent = self._gui local height = 0 for index, text in ipairs(listData) do local textLabel = self:_renderParagraph(text, { Parent = frame }) textLabel.Name = ("%d_%s"):format(index, textLabel.Name) textLabel.Position = UDim2.new(textLabel.Position.X, UDim.new(0, height)) local bullet = self:_getBullet(listData.Level) bullet.AnchorPoint = Vector2.new(0.5, 0.5) bullet.Position = UDim2.new(0, -self.Indent/2, 0, self.TextSize/2 + 1) bullet.Parent = textLabel height = height + textLabel.Size.Y.Offset if index ~= #listData then height = height + self.SpaceBetweenList end end frame.Size = UDim2.new(frame.Size.X, UDim.new(0, height)) return frame end function MarkdownRender:_renderHeader(headerData) local label = self:_getTextLabel() label.Name = "Header" .. headerData.Level label.TextSize = self.TextSize + (self.MaxHeaderLevel-headerData.Level) label.TextYAlignment = Enum.TextYAlignment.Center label.Parent = self._gui label.Font = Enum.Font.SourceSansSemibold self:_renderParagraphLabel(label, headerData.Text) label.Size = UDim2.new(label.Size.X, UDim.new(label.Size.Y.Scale, label.Size.Y.Offset + 6)) -- Extra padding local underline = self:_getFrame() underline.Name = "Underline" underline.BackgroundTransparency = 0 underline.BackgroundColor3 = Color3.new(0.9, 0.9, 0.9) underline.Size = UDim2.new(1, 0, 0, 1) underline.AnchorPoint = Vector2.new(0, 1) underline.Position = UDim2.new(0, 0, 1, 0) underline.Parent = label return label end return MarkdownRender
Fix extra spacing after lists that end markdown render
Fix extra spacing after lists that end markdown render
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
9e03189586153cf4be915a865c6745d2fdec38be
mods/farming/soil.lua
mods/farming/soil.lua
--= Soil Functions -- Normal Soil minetest.register_node("farming:soil", { description = "Soil", tiles = {"default_dirt.png^farming_soil.png", "default_dirt.png"}, drop = "default:dirt", is_ground_content = true, groups = {crumbly=3, not_in_creative_inventory=1, soil=2}, sounds = default.node_sound_dirt_defaults(), }) minetest.register_alias("farming:desert_sand_soil", "farming:soil") -- Wet Soil minetest.register_node("farming:soil_wet", { description = "Wet Soil", tiles = {"default_dirt.png^farming_soil_wet.png", "default_dirt.png^farming_soil_wet_side.png"}, drop = "default:dirt", is_ground_content = true, groups = {crumbly=3, not_in_creative_inventory=1, soil=3}, sounds = default.node_sound_dirt_defaults(), }) minetest.register_alias("farming:desert_sand_soil_wet", "farming:soil_wet") -- If Water near Soil then turn into Wet Soil minetest.register_abm({ nodenames = {"farming:soil", "farming:soil_wet"}, interval = 15, chance = 4, action = function(pos, node) pos.y = pos.y+1 local nn = minetest.get_node(pos).name pos.y = pos.y-1 -- what's on top of soil, if solid/not plant change soil to dirt if minetest.registered_nodes[nn] and minetest.registered_nodes[nn].walkable and minetest.get_item_group(nn, "plant") == 0 then minetest.set_node(pos, {name="default:dirt"}) end -- check if there is water nearby and change soil accordingly if minetest.find_node_near(pos, 3, {"group:water"}) and minetest.find_node_near(pos, 3, {"ignore"}) then if node.name == "farming:soil" then minetest.set_node(pos, {name="farming:soil_wet"}) end elseif node.name == "farming:soil_wet" then minetest.set_node(pos, {name="farming:soil"}) elseif node.name == "farming:soil" then minetest.set_node(pos, {name="default:dirt"}) end end, })
--= Soil Functions -- Normal Soil minetest.register_node("farming:soil", { description = "Soil", tiles = {"default_dirt.png^farming_soil.png", "default_dirt.png"}, drop = "default:dirt", is_ground_content = true, groups = {crumbly=3, not_in_creative_inventory=1, soil=2}, sounds = default.node_sound_dirt_defaults(), }) minetest.register_alias("farming:desert_sand_soil", "farming:soil") -- Wet Soil minetest.register_node("farming:soil_wet", { description = "Wet Soil", tiles = {"default_dirt.png^farming_soil_wet.png", "default_dirt.png^farming_soil_wet_side.png"}, drop = "default:dirt", is_ground_content = true, groups = {crumbly=3, not_in_creative_inventory=1, soil=3}, sounds = default.node_sound_dirt_defaults(), }) minetest.register_alias("farming:desert_sand_soil_wet", "farming:soil_wet") -- If Water near Soil then turn into Wet Soil minetest.register_abm({ nodenames = {"farming:soil", "farming:soil_wet"}, interval = 15, chance = 4, action = function(pos, node) pos.y = pos.y+1 local nn = minetest.get_node(pos).name pos.y = pos.y-1 -- what's on top of soil, if solid/not plant change soil to dirt if minetest.registered_nodes[nn] and minetest.registered_nodes[nn].walkable and minetest.get_item_group(nn, "plant") == 0 then minetest.set_node(pos, {name="default:dirt"}) end -- check if there is water nearby and change soil accordingly if minetest.find_node_near(pos, 3, {"group:water"}) then if node.name == "farming:soil" then minetest.set_node(pos, {name="farming:soil_wet"}) end else -- Don't turn wet soil into dry soil or dry soil into dirt -- if there are unloaded blocks nearby because they could be water. if minetest.find_node_near(pos, 3, {"ignore"}) then return end if node.name == "farming:soil_wet" then minetest.set_node(pos, {name="farming:soil"}) else -- [obviously] node.name == "farming:soil" minetest.set_node(pos, {name="default:dirt"}) end end end, })
Fixed the Soil abm.
Fixed the Soil abm.
Lua
unlicense
Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,crabman77/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,Ombridride/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,Coethium/server-minetestforfun,paly2/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun