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
|
|---|---|---|---|---|---|---|---|---|---|
0ae2da23a9af1bd2f973d53969170cf2bde51599
|
MMOCoreORB/bin/scripts/screenplays/racetracks/mosespa.lua
|
MMOCoreORB/bin/scripts/screenplays/racetracks/mosespa.lua
|
local ObjectManager = require("managers.object.object_manager")
RaceTrackManager = require("screenplays.racetracks.racetrackengine")
mosespa_racetrack_screenplay = RaceTrack:new {
trackConfig={
planetName = "tatooine", -- The planet the Track is on
badgeToAward=BDG_RACING_MOS_ESPA, -- Badge to be awarded for best daily time
trackName="MESPART", -- Internal trackname , should be unique to the track
trackCheckpoint="@theme_park/racing/racing:waypoint_name_checkpoint", --Waypoint names
trackLaptime="@theme_park/racing/racing:laptime_checkpoint", -- System message sent at each waypoint
waypointRadius=10, -- size of the waypoint observer
raceCoordinator = {x=2380,y=5000,z=2}, -- Location of the race coordinator. Note the Z coord is VERY important
waypoints = { {x = 1980, y = 4823}, -- The coords of the waypoints
{x = 1540, y = 4984},
{x = 1364, y = 5429},
{x = 709, y = 5429},
{x = 167, y = 5330},
{x = 416, y = 5077},
{x = -672, y = 4842},
{x = -770, y = 4327},
{x = -717, y = 3993},
{x = 64, y = 4074},
{x = 602, y = 4293},
{x = 926, y = 3853},
{x = 133, y = 4469},
{x = 1637, y = 4336},
{x = 2136, y = 4344},
{x = 2380, y = 5000}
}
}
}
registerScreenPlay("mosespa_racetrack_screenplay", true)
--------------------------------------
-- Initialize screenplay -
--------------------------------------
function mosespa_racetrack_screenplay:start()
if (isZoneEnabled(self.trackConfig.planetName)) then
self:spawnMobiles()
self:createRaceTrack("mosespa_racetrack_screenplay")
end
end
function mosespa_racetrack_screenplay:spawnMobiles()
local pCoord = spawnMobile(self.trackConfig.planetName, "mosespa_race_coordinator", 1, self.trackConfig.raceCoordinator.x, self.trackConfig.raceCoordinator.z, self.trackConfig.raceCoordinator.y, 35, 0 )
end
function mosespa_racetrack_screenplay:enteredWaypoint(pActiveArea, pObject)
self:processWaypoint(pActiveArea, pObject)
end
mosespa_conversationtemplate = Object:new {}
function mosespa_conversationtemplate:getNextConversationScreen(conversationTemplate, conversingPlayer, selectedOption)
return ObjectManager.withCreatureObject(conversingPlayer, function(creatureObject)
local convosession = creatureObject:getConversationSession()
local lastConversationScreen = nil
local conversation = LuaConversationTemplate(conversationTemplate)
local nextConversationScreen
if ( conversation ~= nil ) then
-- checking to see if we have a next screen
if ( convosession ~= nil ) then
local session = LuaConversationSession(convosession)
if ( session ~= nil ) then
lastConversationScreen = session:getLastConversationScreen()
else
print("session was not good in getNextScreen")
end
end
if ( lastConversationScreen == nil ) then
nextConversationScreen = conversation:getInitialScreen()
else
local luaLastConversationScreen = LuaConversationScreen(lastConversationScreen)
local optionLink = luaLastConversationScreen:getOptionLink(selectedOption)
nextConversationScreen = conversation:getScreen(optionLink)
end
end
return nextConversationScreen
end)
end
function mosespa_conversationtemplate:runScreenHandlers(conversationTemplate, conversingPlayer, conversingNPC, selectedOption, conversationScreen)
local screen = LuaConversationScreen(conversationScreen)
local screenID = screen:getScreenID()
if ( screenID == "cs_jsPlumb_1_116" ) then
mosespa_racetrack_screenplay:startRacing(conversingPlayer)
elseif ( screenID == "cs_jsPlumb_1_181" ) then -- Personal Best
mosespa_racetrack_screenplay:displayPersonalBestTime(conversingPlayer)
elseif ( screenID == "cs_jsPlumb_1_207" ) then -- Track Best
mosespa_racetrack_screenplay:displayTrackBestTime(conversingPlayer)
end
return conversationScreen
end
|
local ObjectManager = require("managers.object.object_manager")
RaceTrackManager = require("screenplays.racetracks.racetrackengine")
mosespa_racetrack_screenplay = RaceTrack:new {
trackConfig={
planetName = "tatooine", -- The planet the Track is on
badgeToAward=BDG_RACING_MOS_ESPA, -- Badge to be awarded for best daily time
trackName="MESPART", -- Internal trackname , should be unique to the track
trackCheckpoint="@theme_park/racing/racing:waypoint_name_checkpoint", --Waypoint names
trackLaptime="@theme_park/racing/racing:laptime_checkpoint", -- System message sent at each waypoint
waypointRadius=10, -- size of the waypoint observer
raceCoordinator = {x=2400,y=5000,z=2}, -- Location of the race coordinator. Note the Z coord is VERY important
waypoints = { {x = 1943, y = 4792}, -- The coords of the waypoints
{x = 1546, y = 4959},
{x = 1316, y = 5434},
{x = 688, y = 5439},
{x = 156, y = 5326},
{x = -414, y = 5090},
{x = -664, y = 4832},
{x = -769, y = 4340},
{x = -710, y = 3993},
{x = 81, y = 4092},
{x = 594, y = 4284},
{x = 917, y = 3841},
{x = 1333, y = 4457},
{x = 1630, y = 4326},
{x = 2132, y = 4346},
{x = 2400, y = 5000}
}
}
}
registerScreenPlay("mosespa_racetrack_screenplay", true)
--------------------------------------
-- Initialize screenplay -
--------------------------------------
function mosespa_racetrack_screenplay:start()
if (isZoneEnabled(self.trackConfig.planetName)) then
self:spawnMobiles()
self:createRaceTrack("mosespa_racetrack_screenplay")
end
end
function mosespa_racetrack_screenplay:spawnMobiles()
local pCoord = spawnMobile(self.trackConfig.planetName, "mosespa_race_coordinator", 1, self.trackConfig.raceCoordinator.x, self.trackConfig.raceCoordinator.z, self.trackConfig.raceCoordinator.y, 35, 0 )
end
function mosespa_racetrack_screenplay:enteredWaypoint(pActiveArea, pObject)
self:processWaypoint(pActiveArea, pObject)
end
mosespa_conversationtemplate = Object:new {}
function mosespa_conversationtemplate:getNextConversationScreen(conversationTemplate, conversingPlayer, selectedOption)
return ObjectManager.withCreatureObject(conversingPlayer, function(creatureObject)
local convosession = creatureObject:getConversationSession()
local lastConversationScreen = nil
local conversation = LuaConversationTemplate(conversationTemplate)
local nextConversationScreen
if ( conversation ~= nil ) then
-- checking to see if we have a next screen
if ( convosession ~= nil ) then
local session = LuaConversationSession(convosession)
if ( session ~= nil ) then
lastConversationScreen = session:getLastConversationScreen()
else
print("session was not good in getNextScreen")
end
end
if ( lastConversationScreen == nil ) then
nextConversationScreen = conversation:getInitialScreen()
else
local luaLastConversationScreen = LuaConversationScreen(lastConversationScreen)
local optionLink = luaLastConversationScreen:getOptionLink(selectedOption)
nextConversationScreen = conversation:getScreen(optionLink)
end
end
return nextConversationScreen
end)
end
function mosespa_conversationtemplate:runScreenHandlers(conversationTemplate, conversingPlayer, conversingNPC, selectedOption, conversationScreen)
local screen = LuaConversationScreen(conversationScreen)
local screenID = screen:getScreenID()
if ( screenID == "cs_jsPlumb_1_116" ) then
mosespa_racetrack_screenplay:startRacing(conversingPlayer)
elseif ( screenID == "cs_jsPlumb_1_181" ) then -- Personal Best
mosespa_racetrack_screenplay:displayPersonalBestTime(conversingPlayer)
elseif ( screenID == "cs_jsPlumb_1_207" ) then -- Track Best
mosespa_racetrack_screenplay:displayTrackBestTime(conversingPlayer)
end
return conversationScreen
end
|
[Fixed] Waypoints on Mos Espa racetrack Mantis #4557
|
[Fixed] Waypoints on Mos Espa racetrack Mantis #4557
Change-Id: I1ae47f31f82f592df692cf3c189edc1ba91562ee
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,lasko2112/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,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,Tatwi/legend-of-hondo
|
e8c25e5a0ddc1317d077d7db6d9c4990daa44e9a
|
lua/entities/gmod_wire_digitalscreen/cl_init.lua
|
lua/entities/gmod_wire_digitalscreen/cl_init.lua
|
if (not EmuFox) then
include('shared.lua')
end
function ENT:Initialize()
self.Memory1 = {}
self.Memory2 = {}
self.LastClk = true
self.NewClk = true
self.Memory1[1048575] = 1
self.Memory2[1048575] = 1
self.NeedRefresh = true
self.IsClear = true
self.ClearQueued = false
self.RefreshPixels = {}
self.RefreshRows = {}
self.ScreenWidth = 32
self.ScreenHeight = 32
for i=1,self.ScreenHeight do
self.RefreshRows[i] = i-1
end
//0..786431 - RGB data
//1048569 - Color mode (0: RGBXXX; 1: R G B)
//1048570 - Clear row
//1048571 - Clear column
//1048572 - Screen Height
//1048573 - Screen Width
//1048574 - Hardware Clear Screen
//1048575 - CLK
self.GPU = WireGPU(self)
WireLib.netRegister(self)
end
function ENT:OnRemove()
self.GPU:Finalize()
self.NeedRefresh = true
end
local pixelbits = {20, 8, 24, 30, 8}
net.Receive("wire_digitalscreen", function(netlen)
local ent = Entity(net.ReadUInt(16))
local pixelbit = pixelbits[net.ReadUInt(4)+1]
if IsValid(ent) and ent.Memory1 and ent.Memory2 then
while true do
local length = net.ReadUInt(20)
if length == 0 then break end
local address = net.ReadUInt(20)
for i=1, length do
ent:WriteCell(address, net.ReadUInt(pixelbit))
address = address + 1
end
end
end
end)
function ENT:ReadCell(Address,value)
if Address < 0 then return nil end
if Address >= 1048576 then return nil end
return self.Memory2[Address]
end
function ENT:WriteCell(Address,value)
if Address < 0 then return false end
if Address >= 1048576 then return false end
if Address == 1048575 then
self.NewClk = value ~= 0
elseif Address < 1048500 then
self.IsClear = false
end
if (self.NewClk) then
self.Memory1[Address] = value -- visible buffer
self.NeedRefresh = true
if self.Memory1[1048569] == 1 then -- R G B mode
local pixelno = math.floor(Address/3)
if self.RefreshPixels[#self.RefreshPixels] ~= pixelno then
self.RefreshPixels[#self.RefreshPixels+1] = pixelno
end
else -- other modes
self.RefreshPixels[#self.RefreshPixels+1] = Address
end
end
self.Memory2[Address] = value -- invisible buffer
if Address == 1048574 then
local mem1,mem2 = {},{}
for addr = 1048500,1048575 do
mem1[addr] = self.Memory1[addr]
mem2[addr] = self.Memory2[addr]
end
self.Memory1,self.Memory2 = mem1,mem2
self.IsClear = true
self.ClearQueued = true
self.NeedRefresh = true
elseif Address == 1048572 then
self.ScreenHeight = value
if not self.IsClear then
self.NeedRefresh = true
for i = 1,self.ScreenHeight do
self.RefreshRows[i] = i-1
end
end
elseif Address == 1048573 then
self.ScreenWidth = value
if not self.IsClear then
self.NeedRefresh = true
for i = 1,self.ScreenHeight do
self.RefreshRows[i] = i-1
end
end
end
if self.LastClk ~= self.NewClk then
-- swap the memory if clock changes
self.LastClk = self.NewClk
self.Memory1 = table.Copy(self.Memory2)
self.NeedRefresh = true
for i=1,self.ScreenHeight do
self.RefreshRows[i] = i-1
end
end
return true
end
local transformcolor = {}
transformcolor[0] = function(c) -- RGBXXX
local crgb = math.floor(c / 1000)
local cgray = c - math.floor(c / 1000)*1000
cb = cgray+28*math.fmod(crgb, 10)
cg = cgray+28*math.fmod(math.floor(crgb / 10), 10)
cr = cgray+28*math.fmod(math.floor(crgb / 100), 10)
return cr, cg, cb
end
transformcolor[2] = function(c) -- 24 bit mode
cb = math.fmod(c, 256)
cg = math.fmod(math.floor(c / 256), 256)
cr = math.fmod(math.floor(c / 65536), 256)
return cr, cg, cb
end
transformcolor[3] = function(c) -- RRRGGGBBB
cb = math.fmod(c, 1000)
cg = math.fmod(math.floor(c / 1e3), 1000)
cr = math.fmod(math.floor(c / 1e6), 1000)
return cr, cg, cb
end
transformcolor[4] = function(c) -- XXX
return c, c, c
end
local floor = math.floor
function ENT:RedrawPixel(a)
if a >= self.ScreenWidth*self.ScreenHeight then return end
local cr,cg,cb
local x = a % self.ScreenWidth
local y = math.floor(a / self.ScreenWidth)
local colormode = self.Memory1[1048569] or 0
if colormode == 1 then
cr = self.Memory1[a*3 ] or 0
cg = self.Memory1[a*3+1] or 0
cb = self.Memory1[a*3+2] or 0
else
local c = self.Memory1[a] or 0
cr, cg, cb = (transformcolor[colormode] or transformcolor[0])(c)
end
local xstep = (512/self.ScreenWidth)
local ystep = (512/self.ScreenHeight)
surface.SetDrawColor(cr,cg,cb,255)
local tx, ty = floor(x*xstep), floor(y*ystep)
surface.DrawRect( tx, ty, floor((x+1)*xstep-tx), floor((y+1)*ystep-ty) )
end
function ENT:RedrawRow(y)
local xstep = (512/self.ScreenWidth)
local ystep = (512/self.ScreenHeight)
if y >= self.ScreenHeight then return end
local a = y*self.ScreenWidth
local colormode = self.Memory1[1048569] or 0
for x = 0,self.ScreenWidth-1 do
local cr,cg,cb
if (colormode == 1) then
cr = self.Memory1[(a+x)*3 ] or 0
cg = self.Memory1[(a+x)*3+1] or 0
cb = self.Memory1[(a+x)*3+2] or 0
else
local c = self.Memory1[a+x] or 0
cr, cg, cb = (transformcolor[colormode] or transformcolor[0])(c)
end
surface.SetDrawColor(cr,cg,cb,255)
local tx, ty = floor(x*xstep), floor(y*ystep)
surface.DrawRect( tx, ty, floor((x+1)*xstep-tx), floor((y+1)*ystep-ty) )
end
end
function ENT:Draw()
self:DrawModel()
if self.NeedRefresh then
self.NeedRefresh = false
self.GPU:RenderToGPU(function()
local pixels = 0
local idx = 1
if self.ClearQueued then
surface.SetDrawColor(0,0,0,255)
surface.DrawRect(0,0, 512,512)
self.ClearQueued = false
end
if (#self.RefreshRows > 0) then
idx = #self.RefreshRows
while ((idx > 0) and (pixels < 8192)) do
self:RedrawRow(self.RefreshRows[idx])
self.RefreshRows[idx] = nil
idx = idx - 1
pixels = pixels + self.ScreenWidth
end
if (idx == 0) then
self.RefreshRows = {}
end
else
idx = #self.RefreshPixels
while ((idx > 0) and (pixels < 8192)) do
self:RedrawPixel(self.RefreshPixels[idx])
self.RefreshPixels[idx] = nil
idx = idx - 1
pixels = pixels + 1
end
if (idx == 0) then
self.RefreshRows = {}
end
end
end)
end
if EmuFox then return end
self.GPU:Render()
Wire_Render(self)
end
function ENT:IsTranslucent()
return true
end
|
if (not EmuFox) then
include('shared.lua')
end
function ENT:Initialize()
self.Memory1 = {}
self.Memory2 = {}
self.LastClk = true
self.NewClk = true
self.Memory1[1048575] = 1
self.Memory2[1048575] = 1
self.NeedRefresh = true
self.IsClear = true
self.ClearQueued = false
self.RefreshPixels = {}
self.RefreshRows = {}
self.ScreenWidth = 32
self.ScreenHeight = 32
for i=1,self.ScreenHeight do
self.RefreshRows[i] = i-1
end
//0..786431 - RGB data
//1048569 - Color mode (0: RGBXXX; 1: R G B)
//1048570 - Clear row
//1048571 - Clear column
//1048572 - Screen Height
//1048573 - Screen Width
//1048574 - Hardware Clear Screen
//1048575 - CLK
self.GPU = WireGPU(self)
WireLib.netRegister(self)
end
function ENT:OnRemove()
self.GPU:Finalize()
self.NeedRefresh = true
end
local pixelbits = {20, 8, 24, 30, 8}
net.Receive("wire_digitalscreen", function(netlen)
local ent = Entity(net.ReadUInt(16))
local pixelbit = pixelbits[net.ReadUInt(4)+1]
if IsValid(ent) and ent.Memory1 and ent.Memory2 then
while true do
local length = net.ReadUInt(20)
if length == 0 then break end
local address = net.ReadUInt(20)
for i=1, length do
ent:WriteCell(address, net.ReadUInt(pixelbit))
address = address + 1
end
end
end
end)
function ENT:ReadCell(Address,value)
if Address < 0 then return nil end
if Address >= 1048576 then return nil end
return self.Memory2[Address]
end
function ENT:WriteCell(Address,value)
if Address < 0 then return false end
if Address >= 1048576 then return false end
if Address == 1048575 then
self.NewClk = value ~= 0
elseif Address < 1048500 then
self.IsClear = false
end
if (self.NewClk) then
self.Memory1[Address] = value -- visible buffer
self.NeedRefresh = true
if self.Memory1[1048569] == 1 then -- R G B mode
local pixelno = math.floor(Address/3)
if self.RefreshPixels[#self.RefreshPixels] ~= pixelno then
self.RefreshPixels[#self.RefreshPixels+1] = pixelno
end
else -- other modes
self.RefreshPixels[#self.RefreshPixels+1] = Address
end
end
self.Memory2[Address] = value -- invisible buffer
if Address == 1048574 then
local mem1,mem2 = {},{}
for addr = 1048500,1048575 do
mem1[addr] = self.Memory1[addr]
mem2[addr] = self.Memory2[addr]
end
self.Memory1,self.Memory2 = mem1,mem2
self.IsClear = true
self.ClearQueued = true
self.NeedRefresh = true
elseif Address == 1048572 then
self.ScreenHeight = value
if not self.IsClear then
self.NeedRefresh = true
for i = 1,self.ScreenHeight do
self.RefreshRows[i] = i-1
end
end
elseif Address == 1048573 then
self.ScreenWidth = value
if not self.IsClear then
self.NeedRefresh = true
for i = 1,self.ScreenHeight do
self.RefreshRows[i] = i-1
end
end
end
if self.LastClk ~= self.NewClk then
-- swap the memory if clock changes
self.LastClk = self.NewClk
self.Memory1 = table.Copy(self.Memory2)
self.NeedRefresh = true
for i=1,self.ScreenHeight do
self.RefreshRows[i] = i-1
end
end
return true
end
local transformcolor = {}
transformcolor[0] = function(c) -- RGBXXX
local crgb = math.floor(c / 1000)
local cgray = c - math.floor(c / 1000)*1000
cb = cgray+28*math.fmod(crgb, 10)
cg = cgray+28*math.fmod(math.floor(crgb / 10), 10)
cr = cgray+28*math.fmod(math.floor(crgb / 100), 10)
return cr, cg, cb
end
transformcolor[2] = function(c) -- 24 bit mode
cb = math.fmod(c, 256)
cg = math.fmod(math.floor(c / 256), 256)
cr = math.fmod(math.floor(c / 65536), 256)
return cr, cg, cb
end
transformcolor[3] = function(c) -- RRRGGGBBB
cb = math.fmod(c, 1000)
cg = math.fmod(math.floor(c / 1e3), 1000)
cr = math.fmod(math.floor(c / 1e6), 1000)
return cr, cg, cb
end
transformcolor[4] = function(c) -- XXX
return c, c, c
end
local floor = math.floor
function ENT:RedrawPixel(a)
if a >= self.ScreenWidth*self.ScreenHeight then return end
local cr,cg,cb
local x = a % self.ScreenWidth
local y = math.floor(a / self.ScreenWidth)
local colormode = self.Memory1[1048569] or 0
if colormode == 1 then
cr = self.Memory1[a*3 ] or 0
cg = self.Memory1[a*3+1] or 0
cb = self.Memory1[a*3+2] or 0
else
local c = self.Memory1[a] or 0
cr, cg, cb = (transformcolor[colormode] or transformcolor[0])(c)
end
local xstep = (512/self.ScreenWidth)
local ystep = (512/self.ScreenHeight)
surface.SetDrawColor(cr,cg,cb,255)
local tx, ty = floor(x*xstep), floor(y*ystep)
surface.DrawRect( tx, ty, floor((x+1)*xstep-tx), floor((y+1)*ystep-ty) )
end
function ENT:RedrawRow(y)
local xstep = (512/self.ScreenWidth)
local ystep = (512/self.ScreenHeight)
if y >= self.ScreenHeight then return end
local a = y*self.ScreenWidth
local colormode = self.Memory1[1048569] or 0
for x = 0,self.ScreenWidth-1 do
local cr,cg,cb
if (colormode == 1) then
cr = self.Memory1[(a+x)*3 ] or 0
cg = self.Memory1[(a+x)*3+1] or 0
cb = self.Memory1[(a+x)*3+2] or 0
else
local c = self.Memory1[a+x] or 0
cr, cg, cb = (transformcolor[colormode] or transformcolor[0])(c)
end
surface.SetDrawColor(cr,cg,cb,255)
local tx, ty = floor(x*xstep), floor(y*ystep)
surface.DrawRect( tx, ty, floor((x+1)*xstep-tx), floor((y+1)*ystep-ty) )
end
end
function ENT:Draw()
self:DrawModel()
if self.NeedRefresh then
self.NeedRefresh = false
self.GPU:RenderToGPU(function()
local pixels = 0
local idx = 0
if self.ClearQueued then
surface.SetDrawColor(0,0,0,255)
surface.DrawRect(0,0, 512,512)
self.ClearQueued = false
end
if (#self.RefreshRows > 0) then
idx = #self.RefreshRows
while ((idx > 0) and (pixels < 8192)) do
self:RedrawRow(self.RefreshRows[idx])
self.RefreshRows[idx] = nil
idx = idx - 1
pixels = pixels + self.ScreenWidth
end
else
idx = #self.RefreshPixels
while ((idx > 0) and (pixels < 8192)) do
self:RedrawPixel(self.RefreshPixels[idx])
self.RefreshPixels[idx] = nil
idx = idx - 1
pixels = pixels + 1
end
end
if idx ~= 0 then
self.NeedRefresh = true
end
end)
end
if EmuFox then return end
self.GPU:Render()
Wire_Render(self)
end
function ENT:IsTranslucent()
return true
end
|
Digital Screen: Fixed clk not updating the whole screen
|
Digital Screen: Fixed clk not updating the whole screen
|
Lua
|
apache-2.0
|
CaptainPRICE/wire,Python1320/wire,mms92/wire,NezzKryptic/Wire,sammyt291/wire,thegrb93/wire,plinkopenguin/wiremod,Grocel/wire,rafradek/wire,mitterdoo/wire,immibis/wiremod,garrysmodlua/wire,wiremod/wire,dvdvideo1234/wire,notcake/wire,bigdogmat/wire
|
e65b80499530b2b977da5828d862f7a8b5db1bd9
|
kong/templates/nginx_kong_stream.lua
|
kong/templates/nginx_kong_stream.lua
|
return [[
log_format basic '$remote_addr [$time_local] '
'$protocol $status $bytes_sent $bytes_received '
'$session_time';
lua_shared_dict stream_kong 5m;
lua_shared_dict stream_kong_db_cache ${{MEM_CACHE_SIZE}};
lua_shared_dict stream_kong_db_cache_miss 12m;
lua_shared_dict stream_kong_locks 8m;
lua_shared_dict stream_kong_process_events 5m;
lua_shared_dict stream_kong_cluster_events 5m;
lua_shared_dict stream_kong_healthchecks 5m;
lua_shared_dict stream_kong_rate_limiting_counters 12m;
> if database == "cassandra" then
lua_shared_dict stream_kong_cassandra 5m;
> end
lua_shared_dict stream_prometheus_metrics 5m;
upstream kong_upstream {
server 0.0.0.1:1;
balancer_by_lua_block {
Kong.balancer()
}
}
init_by_lua_block {
-- shared dictionaries conflict between stream/http modules. use a prefix.
local shared = ngx.shared
ngx.shared = setmetatable({}, {
__index = function(t, k)
return shared["stream_"..k]
end,
})
-- XXX: lua-resty-core doesn't load the ffi regex module in the stream
-- subsystem. The code it binds is part of the http module. However
-- without it we can't use regex during the init phase.
require "resty.core.regex"
Kong = require 'kong'
Kong.init()
}
init_worker_by_lua_block {
Kong.init_worker()
}
server {
> for i = 1, #stream_listeners do
listen $(stream_listeners[i].listener);
> end
access_log ${{PROXY_ACCESS_LOG}} basic;
error_log ${{PROXY_ERROR_LOG}} ${{LOG_LEVEL}};
> if ssl_preread_enabled then
ssl_preread on;
> end
preread_by_lua_block {
Kong.preread()
}
proxy_pass kong_upstream;
log_by_lua_block {
Kong.log()
}
}
]]
|
return [[
log_format basic '$remote_addr [$time_local] '
'$protocol $status $bytes_sent $bytes_received '
'$session_time';
lua_package_path '${{LUA_PACKAGE_PATH}};;';
lua_package_cpath '${{LUA_PACKAGE_CPATH}};;';
lua_shared_dict stream_kong 5m;
lua_shared_dict stream_kong_db_cache ${{MEM_CACHE_SIZE}};
lua_shared_dict stream_kong_db_cache_miss 12m;
lua_shared_dict stream_kong_locks 8m;
lua_shared_dict stream_kong_process_events 5m;
lua_shared_dict stream_kong_cluster_events 5m;
lua_shared_dict stream_kong_healthchecks 5m;
lua_shared_dict stream_kong_rate_limiting_counters 12m;
> if database == "cassandra" then
lua_shared_dict stream_kong_cassandra 5m;
> end
lua_shared_dict stream_prometheus_metrics 5m;
upstream kong_upstream {
server 0.0.0.1:1;
balancer_by_lua_block {
Kong.balancer()
}
}
init_by_lua_block {
-- shared dictionaries conflict between stream/http modules. use a prefix.
local shared = ngx.shared
ngx.shared = setmetatable({}, {
__index = function(t, k)
return shared["stream_"..k]
end,
})
-- XXX: lua-resty-core doesn't load the ffi regex module in the stream
-- subsystem. The code it binds is part of the http module. However
-- without it we can't use regex during the init phase.
require "resty.core.regex"
Kong = require 'kong'
Kong.init()
}
init_worker_by_lua_block {
Kong.init_worker()
}
server {
> for i = 1, #stream_listeners do
listen $(stream_listeners[i].listener);
> end
access_log ${{PROXY_ACCESS_LOG}} basic;
error_log ${{PROXY_ERROR_LOG}} ${{LOG_LEVEL}};
> if ssl_preread_enabled then
ssl_preread on;
> end
preread_by_lua_block {
Kong.preread()
}
proxy_pass kong_upstream;
log_by_lua_block {
Kong.log()
}
}
]]
|
hotfix(templates) set lua_package_path in stream module
|
hotfix(templates) set lua_package_path in stream module
Make the stream module honor `lua_package_path` and `lua_package_cpath`
as set in `kong.conf`, so that plugins installed in custom paths can be
found.
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong,Mashape/kong
|
db43a820ea09079586736b8175d126b4ce4ee705
|
src/kong/plugins/authentication/schema.lua
|
src/kong/plugins/authentication/schema.lua
|
local constants = require "kong.constants"
local utils = require "kong.tools.utils"
local stringy = require "stringy"
local function check_authentication_key_names(names, plugin_value)
if plugin_value.authentication_type == constants.AUTHENTICATION.BASIC and names then
return false, "This field is not available for \""..constants.AUTHENTICATION.BASIC.."\" authentication"
elseif plugin_value.authentication_type ~= constants.AUTHENTICATION.BASIC then
if names then
if type(names) == "table" and utils.table_size(names) > 0 then
return true
else
return false, "You need to specify an array"
end
else
return false, "This field is required for query and header authentication"
end
end
end
return {
authentication_type = { required = true, immutable = true, enum = { constants.AUTHENTICATION.QUERY,
constants.AUTHENTICATION.BASIC,
constants.AUTHENTICATION.HEADER }},
authentication_key_names = { type = "table", func = check_authentication_key_names },
hide_credentials = { type = "boolean", default = false }
}
|
local constants = require "kong.constants"
local utils = require "kong.tools.utils"
local stringy = require "stringy"
local function check_authentication_key_names(names, plugin_value)
if plugin_value.authentication_type == constants.AUTHENTICATION.BASIC and names then
return false, "This field is not available for \""..constants.AUTHENTICATION.BASIC.."\" authentication"
elseif plugin_value.authentication_type ~= constants.AUTHENTICATION.BASIC then
if not names or type(names) ~= "table" or utils.table_size(names) == 0 then
return false, "You need to specify an array with at least one value"
end
end
return true
end
return {
authentication_type = { required = true, immutable = true, enum = { constants.AUTHENTICATION.QUERY,
constants.AUTHENTICATION.BASIC,
constants.AUTHENTICATION.HEADER }},
authentication_key_names = { type = "table", func = check_authentication_key_names },
hide_credentials = { type = "boolean", default = false }
}
|
fixing logic in authentication schema
|
fixing logic in authentication schema
|
Lua
|
mit
|
bbalu/kong,vmercierfr/kong,ropik/kong,AnsonSmith/kong,paritoshmmmec/kong,puug/kong,wakermahmud/kong,Skyscanner/kong,skynet/kong,chourobin/kong,ChristopherBiscardi/kong,sbuettner/kong,peterayeni/kong
|
ddf69ca7c510e5eb982f20378572f333a176e046
|
config.lua
|
config.lua
|
-- For details on configuration values, see README.md#configuration.
return {
-- Your authorization token from the botfather.
bot_api_key = '',
-- Your Telegram ID
admin = 00000000,
-- Two-letter language code.
-- Fetches it from the system if available, or defaults to English.
lang = os.getenv('LANG') and os.getenv('LANG'):sub(1,2) or 'en',
-- The channel, group, or user to send error reports to.
-- If this is not set, errors will be printed to the console.
log_chat = nil,
-- The port used to communicate with tg for administration.lua.
-- If you change this, make sure you also modify launch-tg.sh.
cli_port = 4567,
-- The symbol that starts a command. Usually noted as '/' in documentation.
cmd_pat = '/',
-- If drua is used, should a user be blocked when he's blacklisted?
drua_block_on_blacklist = false,
-- The filename of the database. If left nil, defaults to $username.db.
database_name = nil,
-- The block of text returned by /start and /about..
about_text = [[
Based on otouto by topkecleon.
]],
errors = { -- Generic error messages.
generic = 'An unexpected error occurred.',
connection = 'Connection error.',
results = 'No results found.',
argument = 'Invalid argument.',
syntax = 'Invalid syntax.',
specify_targets = 'Specify a target or targets by reply, username, or ID.',
specify_target = 'Specify a target by reply, username, or ID.'
},
-- Whether luarun should use serpent instead of dkjson for serialization.
luarun_serpent = false,
administration = {
-- Conversation, group, or channel for kick/ban notifications.
-- Defaults to config.log_chat if left empty.
log_chat = nil,
-- link or username
log_chat_link = nil,
-- Default autoban setting.
-- A user is banned after being autokicked this many times in a day.
autoban = 3,
-- Default flag settings.
flags = {
private = true,
antisquig = true,
antibot = true,
antilink = true
}
},
plugins = { -- To enable a plugin, add its name to the list.
'control',
'luarun',
'users',
'banremover',
'autopromoter',
'filterer',
'flags',
'antilink',
'antisquig',
'antisquigpp',
'antibot',
'nostickers',
'addgroup',
'removegroup',
'listgroups',
'listadmins',
'listmods',
'listrules',
'getlink',
'regenlink',
'automoderation',
'antihammer_whitelist',
'setrules',
'kickme',
'automoderation',
'addmod',
'demod',
'setgovernor',
'mute',
'unrestrict',
'hammer',
'unhammer',
'ban',
'kick',
'filter',
'description',
'setdescription',
'addadmin',
'deadmin',
'fixperms',
'help'
}
}
|
-- For details on configuration values, see README.md#configuration.
return {
-- Your authorization token from the botfather. (string, put quotes)
bot_api_key = os.getenv('OTOUTO_BOT_API_KEY'),
-- Your Telegram ID (number).
admin = os.getenv('ADMIN_ID'),
-- Two-letter language code.
-- Fetches it from the system if available, or defaults to English.
lang = os.getenv('LANG') and os.getenv('LANG'):sub(1,2) or 'en',
-- The channel, group, or user to send error reports to.
-- If this is not set, errors will be printed to the console.
log_chat = nil,
-- The port used to communicate with tg for administration.lua.
-- If you change this, make sure you also modify launch-tg.sh.
cli_port = 4567,
-- The symbol that starts a command. Usually noted as '/' in documentation.
cmd_pat = '/',
-- If drua is used, should a user be blocked when he's blacklisted?
drua_block_on_blacklist = false,
-- The filename of the database. If left nil, defaults to $username.db.
database_name = nil,
-- The block of text returned by /start and /about..
about_text = [[
Based on otouto by topkecleon.
]],
errors = { -- Generic error messages.
generic = 'An unexpected error occurred.',
connection = 'Connection error.',
results = 'No results found.',
argument = 'Invalid argument.',
syntax = 'Invalid syntax.',
specify_targets = 'Specify a target or targets by reply, username, or ID.',
specify_target = 'Specify a target by reply, username, or ID.'
},
-- Whether luarun should use serpent instead of dkjson for serialization.
luarun_serpent = false,
administration = {
-- Conversation, group, or channel for kick/ban notifications.
-- Defaults to config.log_chat if left empty.
log_chat = nil,
-- link or username
log_chat_link = nil,
-- Default autoban setting.
-- A user is banned after being autokicked this many times in a day.
autoban = 3,
-- Default flag settings.
flags = {
private = true,
antisquig = true,
antibot = true,
antilink = true
}
},
plugins = { -- To enable a plugin, add its name to the list.
'control',
'luarun',
'users',
'banremover',
'autopromoter',
'filterer',
'flags',
'antilink',
'antisquig',
'antisquigpp',
'antibot',
'nostickers',
'addgroup',
'removegroup',
'listgroups',
'listadmins',
'listmods',
'listrules',
'getlink',
'regenlink',
'automoderation',
'antihammer_whitelist',
'setrules',
'kickme',
'automoderation',
'addmod',
'demod',
'setgovernor',
'mute',
'unrestrict',
'hammer',
'unhammer',
'ban',
'kick',
'filter',
'description',
'setdescription',
'addadmin',
'deadmin',
'fixperms',
'help'
}
}
|
fixed docker stuff in config
|
fixed docker stuff in config
|
Lua
|
agpl-3.0
|
topkecleon/otouto
|
0e412312985079ab5b1e80f301d82830391f0371
|
lualib/skynet/datasheet/dump.lua
|
lualib/skynet/datasheet/dump.lua
|
--[[ file format
document :
int32 strtbloffset
int32 n
int32*n index table
table*n
strings
table:
int32 array
int32 dict
int8*(array+dict) type (align 4)
value*array
kvpair*dict
kvpair:
string k
value v
value: (union)
int32 integer
float real
int32 boolean
int32 table index
int32 string offset
type: (enum)
0 nil
1 integer
2 real
3 boolean
4 table
5 string
]]
local ctd = {}
local math = math
local table = table
local string = string
function ctd.dump(root)
local doc = {
table_n = 0,
table = {},
strings = {},
offset = 0,
}
local function dump_table(t)
local index = doc.table_n + 1
doc.table_n = index
doc.table[index] = false -- place holder
local array_n = 0
local array = {}
local kvs = {}
local types = {}
local function encode(v)
local t = type(v)
if t == "table" then
local index = dump_table(v)
return '\4', string.pack("<i4", index-1)
elseif t == "number" then
if math.tointeger(v) then
return '\1', string.pack("<i4", v)
else
return '\2', string.pack("<f",v)
end
elseif t == "boolean" then
if v then
return '\3', "\0\0\0\1"
else
return '\3', "\0\0\0\0"
end
elseif t == "string" then
local offset = doc.strings[v]
if not offset then
offset = doc.offset
doc.offset = offset + #v + 1
doc.strings[v] = offset
table.insert(doc.strings, v)
end
return '\5', string.pack("<I4", offset)
else
error ("Unsupport value " .. tostring(v))
end
end
for i,v in ipairs(t) do
types[i], array[i] = encode(v)
array_n = i
end
for k,v in pairs(t) do
if type(k) == "string" then
local _, kv = encode(k)
local tv, ev = encode(v)
table.insert(types, tv)
table.insert(kvs, kv .. ev)
else
local ik = math.tointeger(k)
assert(ik and ik > 0 and ik <= array_n)
end
end
-- encode table
local typeset = table.concat(types)
local align = string.rep("\0", (4 - #typeset & 3) & 3)
local tmp = {
string.pack("<i4i4", array_n, #kvs),
typeset,
align,
table.concat(array),
table.concat(kvs),
}
doc.table[index] = table.concat(tmp)
return index
end
dump_table(root)
-- encode document
local index = {}
local offset = 0
for i, v in ipairs(doc.table) do
index[i] = string.pack("<I4", offset)
offset = offset + #v
end
local tmp = {
string.pack("<I4", 4 + 4 + 4 * doc.table_n + offset),
string.pack("<I4", doc.table_n),
table.concat(index),
table.concat(doc.table),
table.concat(doc.strings, "\0"),
"\0",
}
return table.concat(tmp)
end
function ctd.undump(v)
local stringtbl, n = string.unpack("<I4I4",v)
local index = { string.unpack("<" .. string.rep("I4", n), v, 9) }
local header = 4 + 4 + 4 * n + 1
stringtbl = stringtbl + 1
local tblidx = {}
local function decode(n)
local toffset = index[n+1] + header
local array, dict = string.unpack("<I4I4", v, toffset)
local types = { string.unpack(string.rep("B", (array+dict)), v, toffset + 8) }
local offset = ((array + dict + 8 + 3) & ~3) + toffset
local result = {}
local function value(t)
local off = offset
offset = offset + 4
if t == 1 then -- integer
return (string.unpack("<i4", v, off))
elseif t == 2 then -- float
return (string.unpack("<f", v, off))
elseif t == 3 then -- boolean
return string.unpack("<i4", v, off) ~= 0
elseif t == 4 then -- table
local tindex = (string.unpack("<I4", v, off))
return decode(tindex)
elseif t == 5 then -- string
local sindex = string.unpack("<I4", v, off)
return (string.unpack("z", v, stringtbl + sindex))
else
error (string.format("Invalid data at %d (%d)", off, t))
end
end
for i=1,array do
table.insert(result, value(types[i]))
end
for i=1,dict do
local sindex = string.unpack("<I4", v, offset)
offset = offset + 4
local key = string.unpack("z", v, stringtbl + sindex)
result[key] = value(types[array + i])
end
tblidx[result] = n
return result
end
return decode(0), tblidx
end
local function diffmap(last, current)
local lastv, lasti = ctd.undump(last)
local curv, curi = ctd.undump(current)
local map = {} -- new(current index):old(last index)
local function comp(lastr, curr)
local old = lasti[lastr]
local new = curi[curr]
map[new] = old
for k,v in pairs(lastr) do
if type(v) == "table" then
local newv = curr[k]
if type(newv) == "table" then
comp(v, newv)
end
end
end
end
comp(lastv, curv)
return map
end
function ctd.diff(last, current)
local map = diffmap(last, current)
local stringtbl, n = string.unpack("<I4I4",current)
local _, lastn = string.unpack("<I4I4",last)
local existn = 0
for k,v in pairs(map) do
existn = existn + 1
end
local newn = lastn
for i = 0, n-1 do
if not map[i] then
map[i] = newn
newn = newn + 1
end
end
-- remap current
local index = { string.unpack("<" .. string.rep("I4", n), current, 9) }
local header = 4 + 4 + 4 * n + 1
local function remap(n)
local toffset = index[n+1] + header
local array, dict = string.unpack("<I4I4", current, toffset)
local types = { string.unpack(string.rep("B", (array+dict)), current, toffset + 8) }
local hlen = (array + dict + 8 + 3) & ~3
local hastable = false
for _, v in ipairs(types) do
if v == 4 then -- table
hastable = true
break
end
end
if not hastable then
return string.sub(current, toffset, toffset + hlen + (array + dict * 2) * 4 - 1)
end
local offset = hlen + toffset
local pat = "<" .. string.rep("I4", array + dict * 2)
local values = { string.unpack(pat, current, offset) }
for i = 1, array do
if types[i] == 4 then -- table
values[i] = map[values[i]]
end
end
for i = 1, dict do
if types[i + array] == 4 then -- table
values[array + i * 2] = map[values[array + i * 2]]
end
end
return string.sub(current, toffset, toffset + hlen - 1) ..
string.pack(pat, table.unpack(values))
end
-- rebuild
local oldindex = { string.unpack("<" .. string.rep("I4", n), current, 9) }
local index = {}
for i = 1, newn do
index[i] = 0xffffffff
end
for i = 0, #map do
index[map[i]+1] = oldindex[i+1]
end
local tmp = {
string.pack("<I4I4", stringtbl + (newn - n) * 4, newn), -- expand index table
string.pack("<" .. string.rep("I4", newn), table.unpack(index)),
}
for i = 0, n - 1 do
table.insert(tmp, remap(i))
end
table.insert(tmp, string.sub(current, stringtbl+1))
return table.concat(tmp)
end
return ctd
|
--[[ file format
document :
int32 strtbloffset
int32 n
int32*n index table
table*n
strings
table:
int32 array
int32 dict
int8*(array+dict) type (align 4)
value*array
kvpair*dict
kvpair:
string k
value v
value: (union)
int32 integer
float real
int32 boolean
int32 table index
int32 string offset
type: (enum)
0 nil
1 integer
2 real
3 boolean
4 table
5 string
]]
local ctd = {}
local math = math
local table = table
local string = string
function ctd.dump(root)
local doc = {
table_n = 0,
table = {},
strings = {},
offset = 0,
}
local function dump_table(t)
local index = doc.table_n + 1
doc.table_n = index
doc.table[index] = false -- place holder
local array_n = 0
local array = {}
local kvs = {}
local types = {}
local function encode(v)
local t = type(v)
if t == "table" then
local index = dump_table(v)
return '\4', string.pack("<i4", index-1)
elseif t == "number" then
if math.tointeger(v) and v <= 0x7FFFFFFF and v >= -(0x7FFFFFFF+1) then
return '\1', string.pack("<i4", v)
else
return '\2', string.pack("<f",v)
end
elseif t == "boolean" then
if v then
return '\3', "\0\0\0\1"
else
return '\3', "\0\0\0\0"
end
elseif t == "string" then
local offset = doc.strings[v]
if not offset then
offset = doc.offset
doc.offset = offset + #v + 1
doc.strings[v] = offset
table.insert(doc.strings, v)
end
return '\5', string.pack("<I4", offset)
else
error ("Unsupport value " .. tostring(v))
end
end
for i,v in ipairs(t) do
types[i], array[i] = encode(v)
array_n = i
end
for k,v in pairs(t) do
if type(k) == "string" then
local _, kv = encode(k)
local tv, ev = encode(v)
table.insert(types, tv)
table.insert(kvs, kv .. ev)
else
local ik = math.tointeger(k)
assert(ik and ik > 0 and ik <= array_n)
end
end
-- encode table
local typeset = table.concat(types)
local align = string.rep("\0", (4 - #typeset & 3) & 3)
local tmp = {
string.pack("<i4i4", array_n, #kvs),
typeset,
align,
table.concat(array),
table.concat(kvs),
}
doc.table[index] = table.concat(tmp)
return index
end
dump_table(root)
-- encode document
local index = {}
local offset = 0
for i, v in ipairs(doc.table) do
index[i] = string.pack("<I4", offset)
offset = offset + #v
end
local tmp = {
string.pack("<I4", 4 + 4 + 4 * doc.table_n + offset),
string.pack("<I4", doc.table_n),
table.concat(index),
table.concat(doc.table),
table.concat(doc.strings, "\0"),
"\0",
}
return table.concat(tmp)
end
function ctd.undump(v)
local stringtbl, n = string.unpack("<I4I4",v)
local index = { string.unpack("<" .. string.rep("I4", n), v, 9) }
local header = 4 + 4 + 4 * n + 1
stringtbl = stringtbl + 1
local tblidx = {}
local function decode(n)
local toffset = index[n+1] + header
local array, dict = string.unpack("<I4I4", v, toffset)
local types = { string.unpack(string.rep("B", (array+dict)), v, toffset + 8) }
local offset = ((array + dict + 8 + 3) & ~3) + toffset
local result = {}
local function value(t)
local off = offset
offset = offset + 4
if t == 1 then -- integer
return (string.unpack("<i4", v, off))
elseif t == 2 then -- float
return (string.unpack("<f", v, off))
elseif t == 3 then -- boolean
return string.unpack("<i4", v, off) ~= 0
elseif t == 4 then -- table
local tindex = (string.unpack("<I4", v, off))
return decode(tindex)
elseif t == 5 then -- string
local sindex = string.unpack("<I4", v, off)
return (string.unpack("z", v, stringtbl + sindex))
else
error (string.format("Invalid data at %d (%d)", off, t))
end
end
for i=1,array do
table.insert(result, value(types[i]))
end
for i=1,dict do
local sindex = string.unpack("<I4", v, offset)
offset = offset + 4
local key = string.unpack("z", v, stringtbl + sindex)
result[key] = value(types[array + i])
end
tblidx[result] = n
return result
end
return decode(0), tblidx
end
local function diffmap(last, current)
local lastv, lasti = ctd.undump(last)
local curv, curi = ctd.undump(current)
local map = {} -- new(current index):old(last index)
local function comp(lastr, curr)
local old = lasti[lastr]
local new = curi[curr]
map[new] = old
for k,v in pairs(lastr) do
if type(v) == "table" then
local newv = curr[k]
if type(newv) == "table" then
comp(v, newv)
end
end
end
end
comp(lastv, curv)
return map
end
function ctd.diff(last, current)
local map = diffmap(last, current)
local stringtbl, n = string.unpack("<I4I4",current)
local _, lastn = string.unpack("<I4I4",last)
local existn = 0
for k,v in pairs(map) do
existn = existn + 1
end
local newn = lastn
for i = 0, n-1 do
if not map[i] then
map[i] = newn
newn = newn + 1
end
end
-- remap current
local index = { string.unpack("<" .. string.rep("I4", n), current, 9) }
local header = 4 + 4 + 4 * n + 1
local function remap(n)
local toffset = index[n+1] + header
local array, dict = string.unpack("<I4I4", current, toffset)
local types = { string.unpack(string.rep("B", (array+dict)), current, toffset + 8) }
local hlen = (array + dict + 8 + 3) & ~3
local hastable = false
for _, v in ipairs(types) do
if v == 4 then -- table
hastable = true
break
end
end
if not hastable then
return string.sub(current, toffset, toffset + hlen + (array + dict * 2) * 4 - 1)
end
local offset = hlen + toffset
local pat = "<" .. string.rep("I4", array + dict * 2)
local values = { string.unpack(pat, current, offset) }
for i = 1, array do
if types[i] == 4 then -- table
values[i] = map[values[i]]
end
end
for i = 1, dict do
if types[i + array] == 4 then -- table
values[array + i * 2] = map[values[array + i * 2]]
end
end
return string.sub(current, toffset, toffset + hlen - 1) ..
string.pack(pat, table.unpack(values))
end
-- rebuild
local oldindex = { string.unpack("<" .. string.rep("I4", n), current, 9) }
local index = {}
for i = 1, newn do
index[i] = 0xffffffff
end
for i = 0, #map do
index[map[i]+1] = oldindex[i+1]
end
local tmp = {
string.pack("<I4I4", stringtbl + (newn - n) * 4, newn), -- expand index table
string.pack("<" .. string.rep("I4", newn), table.unpack(index)),
}
for i = 0, n - 1 do
table.insert(tmp, remap(i))
end
table.insert(tmp, string.sub(current, stringtbl+1))
return table.concat(tmp)
end
return ctd
|
fix #857
|
fix #857
|
Lua
|
mit
|
bttscut/skynet,hongling0/skynet,cloudwu/skynet,korialuo/skynet,hongling0/skynet,great90/skynet,bigrpg/skynet,Ding8222/skynet,pigparadise/skynet,zhangshiqian1214/skynet,bigrpg/skynet,great90/skynet,pigparadise/skynet,wangyi0226/skynet,firedtoad/skynet,JiessieDawn/skynet,firedtoad/skynet,korialuo/skynet,xjdrew/skynet,Ding8222/skynet,icetoggle/skynet,ag6ag/skynet,xcjmine/skynet,zhouxiaoxiaoxujian/skynet,zhangshiqian1214/skynet,jxlczjp77/skynet,jxlczjp77/skynet,JiessieDawn/skynet,firedtoad/skynet,cloudwu/skynet,zhouxiaoxiaoxujian/skynet,jxlczjp77/skynet,sundream/skynet,Ding8222/skynet,sanikoyes/skynet,JiessieDawn/skynet,sundream/skynet,xcjmine/skynet,ag6ag/skynet,zhangshiqian1214/skynet,ag6ag/skynet,sanikoyes/skynet,bttscut/skynet,icetoggle/skynet,sanikoyes/skynet,zhangshiqian1214/skynet,zhangshiqian1214/skynet,xjdrew/skynet,pigparadise/skynet,korialuo/skynet,cloudwu/skynet,wangyi0226/skynet,wangyi0226/skynet,zhouxiaoxiaoxujian/skynet,xjdrew/skynet,sundream/skynet,zhangshiqian1214/skynet,bigrpg/skynet,hongling0/skynet,bttscut/skynet,icetoggle/skynet,great90/skynet,xcjmine/skynet
|
0ed6176ebf058afaba5e22424d6c65e76112a09f
|
core/args.lua
|
core/args.lua
|
-- Copyright 2007-2018 Mitchell mitchell.att.foicica.com. See LICENSE.
local M = {}
--[[ This comment is for LuaDoc.
---
-- Processes command line arguments for Textadept.
-- @field _G.events.ARG_NONE (string)
-- Emitted when no command line arguments are passed to Textadept on startup.
module('args')]]
events.ARG_NONE = 'arg_none'
-- Contains registered command line switches.
-- @class table
-- @name switches
local switches = {}
---
-- Registers a command line switch with short and long versions *short* and
-- *long*, respectively. *narg* is the number of arguments the switch accepts,
-- *f* is the function called when the switch is tripped, and *description* is
-- the switch's description when displaying help.
-- @param short The string short version of the switch.
-- @param long The string long version of the switch.
-- @param narg The number of expected parameters for the switch.
-- @param f The Lua function to run when the switch is tripped.
-- @param description The string description of the switch for command line
-- help.
-- @name register
function M.register(short, long, narg, f, description)
local t = {f, narg, description}
switches[short], switches[long] = t, t
end
-- Processes command line argument table *arg*, handling switches previously
-- defined using `args.register()` and treating unrecognized arguments as
-- filenames to open.
-- Emits an `ARG_NONE` event when no arguments are present.
-- @param arg Argument table.
-- @see register
-- @see _G.events
local function process(arg)
local no_args = true
local i = 1
while i <= #arg do
local switch = switches[arg[i]]
if switch then
local f, n = table.unpack(switch)
f(table.unpack(arg, i + 1, i + n))
i = i + n
else
io.open_file(lfs.abspath(arg[i], arg[-1]))
no_args = false
end
i = i + 1
end
if no_args then events.emit(events.ARG_NONE) end
end
events.connect(events.INITIALIZED, function() if arg then process(arg) end end)
events.connect('cmd_line', process) -- undocumented, single-instance event
if not CURSES then
-- Shows all registered command line switches on the command line.
M.register('-h', '--help', 0, function()
print('Usage: textadept [args] [filenames]')
local line = " %s [%d args]: %s"
for k, v in pairs(switches) do print(line:format(k, table.unpack(v, 2))) end
os.exit()
end, 'Shows this')
-- Shows Textadept version and copyright on the command line.
M.register('-v', '--version', 0, function()
print(_RELEASE..'\n'.._COPYRIGHT)
quit()
end, 'Prints Textadept version and copyright')
-- After Textadept finishes initializing and processes arguments, remove the
-- help and version switches in order to prevent another instance from sending
-- '-h', '--help', '-v', and '--version' to the first instance, killing the
-- latter.
events.connect(events.INITIALIZED, function()
switches['-h'], switches['--help'] = nil, nil
switches['-v'], switches['--version'] = nil, nil
end)
end
-- Set `_G._USERHOME`.
_USERHOME = os.getenv(not WIN32 and 'HOME' or 'USERPROFILE')..'/.textadept'
for i = 1, #arg do
if (arg[i] == '-u' or arg[i] == '--userhome') and arg[i + 1] then
_USERHOME = arg[i + 1]
break
end
end
if not lfs.attributes(_USERHOME) then lfs.mkdir(_USERHOME) end
local f = io.open(_USERHOME..'/init.lua', 'a+') -- ensure existence
if f then f:close() end
M.register('-u', '--userhome', 1, function() end, 'Sets alternate _USERHOME')
M.register('-f', '--force', 0, function() end, 'Forces unique instance')
return M
|
-- Copyright 2007-2018 Mitchell mitchell.att.foicica.com. See LICENSE.
local M = {}
--[[ This comment is for LuaDoc.
---
-- Processes command line arguments for Textadept.
-- @field _G.events.ARG_NONE (string)
-- Emitted when no command line arguments are passed to Textadept on startup.
module('args')]]
events.ARG_NONE = 'arg_none'
-- Contains registered command line switches.
-- @class table
-- @name switches
local switches = {}
---
-- Registers a command line switch with short and long versions *short* and
-- *long*, respectively. *narg* is the number of arguments the switch accepts,
-- *f* is the function called when the switch is tripped, and *description* is
-- the switch's description when displaying help.
-- @param short The string short version of the switch.
-- @param long The string long version of the switch.
-- @param narg The number of expected parameters for the switch.
-- @param f The Lua function to run when the switch is tripped.
-- @param description The string description of the switch for command line
-- help.
-- @name register
function M.register(short, long, narg, f, description)
local t = {f, narg, description}
switches[short], switches[long] = t, t
end
-- Processes command line argument table *arg*, handling switches previously
-- defined using `args.register()` and treating unrecognized arguments as
-- filenames to open.
-- Emits an `ARG_NONE` event when no arguments are present unless
-- *no_emit_arg_none* is `true`.
-- @param arg Argument table.
-- @see register
-- @see _G.events
local function process(arg, no_emit_arg_none)
local no_args = true
local i = 1
while i <= #arg do
local switch = switches[arg[i]]
if switch then
local f, n = table.unpack(switch)
f(table.unpack(arg, i + 1, i + n))
i = i + n
else
io.open_file(lfs.abspath(arg[i], arg[-1]))
no_args = false
end
i = i + 1
end
if no_args and not no_emit_arg_none then events.emit(events.ARG_NONE) end
end
events.connect(events.INITIALIZED, function() if arg then process(arg) end end)
-- Undocumented, single-instance event handler for forwarding arguments.
events.connect('cmd_line', function(arg) process(arg, true) end)
if not CURSES then
-- Shows all registered command line switches on the command line.
M.register('-h', '--help', 0, function()
print('Usage: textadept [args] [filenames]')
local line = " %s [%d args]: %s"
for k, v in pairs(switches) do print(line:format(k, table.unpack(v, 2))) end
os.exit()
end, 'Shows this')
-- Shows Textadept version and copyright on the command line.
M.register('-v', '--version', 0, function()
print(_RELEASE..'\n'.._COPYRIGHT)
quit()
end, 'Prints Textadept version and copyright')
-- After Textadept finishes initializing and processes arguments, remove the
-- help and version switches in order to prevent another instance from sending
-- '-h', '--help', '-v', and '--version' to the first instance, killing the
-- latter.
events.connect(events.INITIALIZED, function()
switches['-h'], switches['--help'] = nil, nil
switches['-v'], switches['--version'] = nil, nil
end)
end
-- Set `_G._USERHOME`.
_USERHOME = os.getenv(not WIN32 and 'HOME' or 'USERPROFILE')..'/.textadept'
for i = 1, #arg do
if (arg[i] == '-u' or arg[i] == '--userhome') and arg[i + 1] then
_USERHOME = arg[i + 1]
break
end
end
if not lfs.attributes(_USERHOME) then lfs.mkdir(_USERHOME) end
local f = io.open(_USERHOME..'/init.lua', 'a+') -- ensure existence
if f then f:close() end
M.register('-u', '--userhome', 1, function() end, 'Sets alternate _USERHOME')
M.register('-f', '--force', 0, function() end, 'Forces unique instance')
return M
|
Fixed bug in remote-controlled Textadept when no args were initially given.
|
Fixed bug in remote-controlled Textadept when no args were initially given.
|
Lua
|
mit
|
rgieseke/textadept,rgieseke/textadept
|
5cc835e507585b33d47ab310a044245da0a792b9
|
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
|
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
require("luci.model.uci")
require("luci.util")
m = Map("dhcp",
translate("Dynamic <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr>"),
translate("With <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> network " ..
"members can automatically receive their network settings (<abbr title=" ..
"\"Internet Protocol\">IP</abbr>-address, netmask, <abbr title=\"Domain Name " ..
"System\">DNS</abbr>-server, ...)."))
s = m:section(TypedSection, "dhcp", "")
s.addremove = true
s.anonymous = true
iface = s:option(ListValue, "interface", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(iface)
local uci = luci.model.uci.cursor()
uci:foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
iface.default = iface.default or section[".name"]
s:depends("interface", section[".name"])
end
end)
uci:foreach("network", "alias",
function (section)
iface:value(section[".name"])
s:depends("interface", section[".name"])
end)
s:option(Value, "start", translate("Start")).rmempty = true
s:option(Value, "limit", translate("Limit")).rmempty = true
s:option(Value, "leasetime", translate("Leasetime")).rmempty = true
local dd = s:option(Flag, "dynamicdhcp", translate("dynamic"))
dd.rmempty = false
function dd.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "1"
end
s:option(Value, "name", translate("Name")).optional = true
ignore = s:option(Flag, "ignore",
translate("Ignore interface"),
translate("disable <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> for " ..
"this interface"))
ignore.optional = true
s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")).optional = true
s:option(Flag, "force", translate("Force")).optional = true
s:option(DynamicList, "dhcp_option", translate("DHCP-Options")).optional = true
for i, n in ipairs(s.children) do
if n ~= iface and n ~= ignore then
n:depends("ignore", "")
end
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.tools.webadmin")
require("luci.model.uci")
require("luci.util")
m = Map("dhcp",
translate("DHCP"),
translate("With <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> network " ..
"members can automatically receive their network settings (<abbr title=" ..
"\"Internet Protocol\">IP</abbr>-address, netmask, <abbr title=\"Domain Name " ..
"System\">DNS</abbr>-server, ...)."))
s = m:section(TypedSection, "dhcp", "")
s.addremove = true
s.anonymous = true
iface = s:option(ListValue, "interface", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(iface)
local uci = luci.model.uci.cursor()
uci:foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
iface.default = iface.default or section[".name"]
s:depends("interface", section[".name"])
end
end)
uci:foreach("network", "alias",
function (section)
iface:value(section[".name"])
s:depends("interface", section[".name"])
end)
s:option(Value, "start", translate("Start")).rmempty = true
s:option(Value, "limit", translate("Limit")).rmempty = true
s:option(Value, "leasetime", translate("Leasetime")).rmempty = true
local dd = s:option(Flag, "dynamicdhcp",
translate("Dynamic <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr>"))
dd.rmempty = false
function dd.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "1"
end
s:option(Value, "name", translate("Name")).optional = true
ignore = s:option(Flag, "ignore",
translate("Ignore interface"),
translate("disable <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> for " ..
"this interface"))
ignore.optional = true
s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")).optional = true
s:option(Flag, "force", translate("Force")).optional = true
s:option(DynamicList, "dhcp_option", translate("DHCP-Options")).optional = true
for i, n in ipairs(s.children) do
if n ~= iface and n ~= ignore then
n:depends("ignore", "")
end
end
return m
|
modules/admin-full: fix last commit
|
modules/admin-full: fix last commit
|
Lua
|
apache-2.0
|
urueedi/luci,deepak78/new-luci,jchuang1977/luci-1,florian-shellfire/luci,openwrt/luci,981213/luci-1,kuoruan/lede-luci,schidler/ionic-luci,chris5560/openwrt-luci,lcf258/openwrtcn,dwmw2/luci,sujeet14108/luci,dwmw2/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,Hostle/luci,joaofvieira/luci,taiha/luci,slayerrensky/luci,nmav/luci,tcatm/luci,thess/OpenWrt-luci,daofeng2015/luci,Kyklas/luci-proto-hso,obsy/luci,dismantl/luci-0.12,rogerpueyo/luci,kuoruan/luci,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,nmav/luci,RuiChen1113/luci,remakeelectric/luci,opentechinstitute/luci,hnyman/luci,palmettos/cnLuCI,db260179/openwrt-bpi-r1-luci,ollie27/openwrt_luci,tobiaswaldvogel/luci,chris5560/openwrt-luci,kuoruan/luci,MinFu/luci,florian-shellfire/luci,maxrio/luci981213,nmav/luci,ollie27/openwrt_luci,aa65535/luci,bright-things/ionic-luci,ff94315/luci-1,zhaoxx063/luci,ff94315/luci-1,ReclaimYourPrivacy/cloak-luci,lcf258/openwrtcn,LuttyYang/luci,Kyklas/luci-proto-hso,teslamint/luci,cshore/luci,mumuqz/luci,bright-things/ionic-luci,male-puppies/luci,nwf/openwrt-luci,jlopenwrtluci/luci,Wedmer/luci,Hostle/luci,artynet/luci,NeoRaider/luci,RedSnake64/openwrt-luci-packages,Hostle/openwrt-luci-multi-user,male-puppies/luci,981213/luci-1,oneru/luci,jlopenwrtluci/luci,wongsyrone/luci-1,joaofvieira/luci,openwrt-es/openwrt-luci,cshore/luci,cshore-firmware/openwrt-luci,Noltari/luci,forward619/luci,MinFu/luci,sujeet14108/luci,opentechinstitute/luci,deepak78/new-luci,ff94315/luci-1,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/cnLuCI,Kyklas/luci-proto-hso,david-xiao/luci,jchuang1977/luci-1,palmettos/test,ReclaimYourPrivacy/cloak-luci,harveyhu2012/luci,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,joaofvieira/luci,ReclaimYourPrivacy/cloak-luci,florian-shellfire/luci,cshore-firmware/openwrt-luci,palmettos/test,openwrt/luci,cappiewu/luci,db260179/openwrt-bpi-r1-luci,jlopenwrtluci/luci,keyidadi/luci,jlopenwrtluci/luci,dwmw2/luci,joaofvieira/luci,artynet/luci,kuoruan/lede-luci,MinFu/luci,schidler/ionic-luci,kuoruan/lede-luci,remakeelectric/luci,male-puppies/luci,harveyhu2012/luci,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,palmettos/cnLuCI,david-xiao/luci,rogerpueyo/luci,daofeng2015/luci,palmettos/test,tobiaswaldvogel/luci,RedSnake64/openwrt-luci-packages,MinFu/luci,forward619/luci,LuttyYang/luci,remakeelectric/luci,bittorf/luci,sujeet14108/luci,lcf258/openwrtcn,oyido/luci,dismantl/luci-0.12,thesabbir/luci,mumuqz/luci,slayerrensky/luci,artynet/luci,harveyhu2012/luci,jchuang1977/luci-1,RuiChen1113/luci,shangjiyu/luci-with-extra,NeoRaider/luci,aircross/OpenWrt-Firefly-LuCI,marcel-sch/luci,tcatm/luci,shangjiyu/luci-with-extra,Sakura-Winkey/LuCI,david-xiao/luci,teslamint/luci,Kyklas/luci-proto-hso,david-xiao/luci,joaofvieira/luci,taiha/luci,urueedi/luci,LuttyYang/luci,kuoruan/luci,bittorf/luci,Sakura-Winkey/LuCI,keyidadi/luci,tobiaswaldvogel/luci,slayerrensky/luci,tcatm/luci,florian-shellfire/luci,marcel-sch/luci,lbthomsen/openwrt-luci,harveyhu2012/luci,fkooman/luci,chris5560/openwrt-luci,cshore/luci,wongsyrone/luci-1,daofeng2015/luci,Sakura-Winkey/LuCI,schidler/ionic-luci,ff94315/luci-1,openwrt/luci,artynet/luci,bittorf/luci,bright-things/ionic-luci,ollie27/openwrt_luci,chris5560/openwrt-luci,LuttyYang/luci,oneru/luci,david-xiao/luci,LazyZhu/openwrt-luci-trunk-mod,dismantl/luci-0.12,db260179/openwrt-bpi-r1-luci,cappiewu/luci,ff94315/luci-1,obsy/luci,nwf/openwrt-luci,rogerpueyo/luci,keyidadi/luci,cappiewu/luci,male-puppies/luci,RuiChen1113/luci,nwf/openwrt-luci,wongsyrone/luci-1,LazyZhu/openwrt-luci-trunk-mod,male-puppies/luci,fkooman/luci,bright-things/ionic-luci,jlopenwrtluci/luci,981213/luci-1,palmettos/cnLuCI,dwmw2/luci,LuttyYang/luci,dwmw2/luci,forward619/luci,obsy/luci,openwrt/luci,jorgifumi/luci,rogerpueyo/luci,ReclaimYourPrivacy/cloak-luci,marcel-sch/luci,oyido/luci,oneru/luci,schidler/ionic-luci,kuoruan/lede-luci,nwf/openwrt-luci,teslamint/luci,MinFu/luci,bittorf/luci,dismantl/luci-0.12,nmav/luci,Kyklas/luci-proto-hso,db260179/openwrt-bpi-r1-luci,kuoruan/lede-luci,marcel-sch/luci,harveyhu2012/luci,ollie27/openwrt_luci,NeoRaider/luci,taiha/luci,Wedmer/luci,openwrt-es/openwrt-luci,keyidadi/luci,shangjiyu/luci-with-extra,schidler/ionic-luci,slayerrensky/luci,david-xiao/luci,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,remakeelectric/luci,hnyman/luci,thesabbir/luci,teslamint/luci,florian-shellfire/luci,cshore/luci,jorgifumi/luci,db260179/openwrt-bpi-r1-luci,cshore-firmware/openwrt-luci,fkooman/luci,oyido/luci,maxrio/luci981213,mumuqz/luci,cappiewu/luci,joaofvieira/luci,bright-things/ionic-luci,tobiaswaldvogel/luci,openwrt/luci,dismantl/luci-0.12,jchuang1977/luci-1,zhaoxx063/luci,dwmw2/luci,teslamint/luci,Wedmer/luci,nwf/openwrt-luci,dwmw2/luci,thesabbir/luci,openwrt-es/openwrt-luci,RuiChen1113/luci,aa65535/luci,wongsyrone/luci-1,RuiChen1113/luci,cappiewu/luci,MinFu/luci,maxrio/luci981213,joaofvieira/luci,nwf/openwrt-luci,cshore-firmware/openwrt-luci,marcel-sch/luci,Sakura-Winkey/LuCI,wongsyrone/luci-1,daofeng2015/luci,openwrt-es/openwrt-luci,Hostle/luci,ff94315/luci-1,jorgifumi/luci,NeoRaider/luci,thess/OpenWrt-luci,taiha/luci,bright-things/ionic-luci,urueedi/luci,rogerpueyo/luci,openwrt/luci,daofeng2015/luci,slayerrensky/luci,nwf/openwrt-luci,deepak78/new-luci,florian-shellfire/luci,RedSnake64/openwrt-luci-packages,ReclaimYourPrivacy/cloak-luci,cappiewu/luci,cshore-firmware/openwrt-luci,Noltari/luci,forward619/luci,thesabbir/luci,thesabbir/luci,jlopenwrtluci/luci,oneru/luci,palmettos/test,LuttyYang/luci,urueedi/luci,palmettos/test,lcf258/openwrtcn,lbthomsen/openwrt-luci,male-puppies/luci,shangjiyu/luci-with-extra,bittorf/luci,artynet/luci,remakeelectric/luci,fkooman/luci,LuttyYang/luci,NeoRaider/luci,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,schidler/ionic-luci,jchuang1977/luci-1,fkooman/luci,artynet/luci,Noltari/luci,thess/OpenWrt-luci,forward619/luci,Noltari/luci,jorgifumi/luci,obsy/luci,shangjiyu/luci-with-extra,shangjiyu/luci-with-extra,artynet/luci,rogerpueyo/luci,Hostle/luci,openwrt-es/openwrt-luci,Noltari/luci,thess/OpenWrt-luci,Hostle/openwrt-luci-multi-user,ollie27/openwrt_luci,fkooman/luci,florian-shellfire/luci,aircross/OpenWrt-Firefly-LuCI,chris5560/openwrt-luci,Noltari/luci,david-xiao/luci,nmav/luci,kuoruan/lede-luci,teslamint/luci,marcel-sch/luci,981213/luci-1,Kyklas/luci-proto-hso,MinFu/luci,aa65535/luci,wongsyrone/luci-1,oneru/luci,taiha/luci,zhaoxx063/luci,Hostle/luci,aircross/OpenWrt-Firefly-LuCI,tcatm/luci,oyido/luci,shangjiyu/luci-with-extra,mumuqz/luci,Wedmer/luci,nwf/openwrt-luci,remakeelectric/luci,urueedi/luci,thess/OpenWrt-luci,oneru/luci,lbthomsen/openwrt-luci,NeoRaider/luci,deepak78/new-luci,NeoRaider/luci,tobiaswaldvogel/luci,hnyman/luci,Noltari/luci,nmav/luci,ollie27/openwrt_luci,kuoruan/luci,palmettos/test,cshore/luci,aircross/OpenWrt-Firefly-LuCI,male-puppies/luci,openwrt-es/openwrt-luci,jlopenwrtluci/luci,lcf258/openwrtcn,artynet/luci,urueedi/luci,mumuqz/luci,NeoRaider/luci,forward619/luci,ollie27/openwrt_luci,ReclaimYourPrivacy/cloak-luci,palmettos/test,jorgifumi/luci,Kyklas/luci-proto-hso,zhaoxx063/luci,tobiaswaldvogel/luci,obsy/luci,zhaoxx063/luci,db260179/openwrt-bpi-r1-luci,aircross/OpenWrt-Firefly-LuCI,harveyhu2012/luci,cshore/luci,schidler/ionic-luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,jchuang1977/luci-1,sujeet14108/luci,jchuang1977/luci-1,maxrio/luci981213,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,obsy/luci,tcatm/luci,maxrio/luci981213,rogerpueyo/luci,Sakura-Winkey/LuCI,openwrt-es/openwrt-luci,oneru/luci,aircross/OpenWrt-Firefly-LuCI,palmettos/test,taiha/luci,thesabbir/luci,david-xiao/luci,lcf258/openwrtcn,deepak78/new-luci,slayerrensky/luci,Noltari/luci,opentechinstitute/luci,lbthomsen/openwrt-luci,remakeelectric/luci,Wedmer/luci,keyidadi/luci,981213/luci-1,schidler/ionic-luci,mumuqz/luci,daofeng2015/luci,Hostle/openwrt-luci-multi-user,Hostle/luci,keyidadi/luci,keyidadi/luci,cshore/luci,sujeet14108/luci,palmettos/cnLuCI,thesabbir/luci,LazyZhu/openwrt-luci-trunk-mod,urueedi/luci,harveyhu2012/luci,cappiewu/luci,LazyZhu/openwrt-luci-trunk-mod,hnyman/luci,Hostle/luci,deepak78/new-luci,taiha/luci,opentechinstitute/luci,fkooman/luci,Noltari/luci,urueedi/luci,obsy/luci,nmav/luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/lede-luci,Wedmer/luci,nmav/luci,teslamint/luci,lbthomsen/openwrt-luci,forward619/luci,aa65535/luci,cshore/luci,LazyZhu/openwrt-luci-trunk-mod,bittorf/luci,oneru/luci,sujeet14108/luci,dismantl/luci-0.12,lbthomsen/openwrt-luci,opentechinstitute/luci,hnyman/luci,keyidadi/luci,Hostle/luci,hnyman/luci,Sakura-Winkey/LuCI,sujeet14108/luci,bittorf/luci,wongsyrone/luci-1,Wedmer/luci,male-puppies/luci,maxrio/luci981213,thesabbir/luci,hnyman/luci,marcel-sch/luci,RedSnake64/openwrt-luci-packages,bright-things/ionic-luci,lbthomsen/openwrt-luci,jorgifumi/luci,kuoruan/luci,palmettos/cnLuCI,chris5560/openwrt-luci,db260179/openwrt-bpi-r1-luci,taiha/luci,Wedmer/luci,kuoruan/luci,openwrt/luci,mumuqz/luci,nmav/luci,Sakura-Winkey/LuCI,tcatm/luci,jorgifumi/luci,deepak78/new-luci,aircross/OpenWrt-Firefly-LuCI,oyido/luci,LuttyYang/luci,hnyman/luci,joaofvieira/luci,RuiChen1113/luci,chris5560/openwrt-luci,981213/luci-1,RuiChen1113/luci,lcf258/openwrtcn,981213/luci-1,ollie27/openwrt_luci,oyido/luci,MinFu/luci,artynet/luci,thess/OpenWrt-luci,rogerpueyo/luci,aa65535/luci,RedSnake64/openwrt-luci-packages,shangjiyu/luci-with-extra,kuoruan/lede-luci,daofeng2015/luci,jorgifumi/luci,jlopenwrtluci/luci,jchuang1977/luci-1,cshore-firmware/openwrt-luci,obsy/luci,dwmw2/luci,dismantl/luci-0.12,openwrt/luci,maxrio/luci981213,zhaoxx063/luci,thess/OpenWrt-luci,bright-things/ionic-luci,remakeelectric/luci,tobiaswaldvogel/luci,fkooman/luci,palmettos/cnLuCI,deepak78/new-luci,teslamint/luci,Hostle/openwrt-luci-multi-user,lcf258/openwrtcn,chris5560/openwrt-luci,zhaoxx063/luci,slayerrensky/luci,ff94315/luci-1,lcf258/openwrtcn,cappiewu/luci,sujeet14108/luci,tcatm/luci,zhaoxx063/luci,kuoruan/luci,tcatm/luci,cshore-firmware/openwrt-luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,aa65535/luci,thess/OpenWrt-luci,oyido/luci,forward619/luci,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,aa65535/luci,oyido/luci,ff94315/luci-1,opentechinstitute/luci,slayerrensky/luci,marcel-sch/luci,aa65535/luci,mumuqz/luci,maxrio/luci981213,RedSnake64/openwrt-luci-packages,daofeng2015/luci
|
d4e1d385cfc35f7cacb480169a7ba3353382e460
|
focuspoints.lrdevplugin/PointsRendererFactory.lua
|
focuspoints.lrdevplugin/PointsRendererFactory.lua
|
--[[
Copyright 2016 Joshua Musselwhite, Whizzbang Inc
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.
--]]
--[[
Factory for creating the focus point renderer and getting the focus points.
--]]
require "DefaultPointRenderer"
require "PointsUtils"
require "DefaultDelegates"
require "FujiDelegates"
local LrErrors = import 'LrErrors'
PointsRendererFactory = {}
function PointsRendererFactory.createRenderer(photo)
local cameraMake = photo:getFormattedMetadata("cameraMake")
local cameraModel = photo:getFormattedMetadata("cameraModel")
if (camerMake == nil or camerModel == nil) then
LrErrors.throwUserError("File doesn't contain camera maker or model")
end
cameraMake = string.lower(camerMake)
cameraModel = string.lower(camerModel)
if (cameraMake == "fujifilm") then
DefaultDelegates.focusPointsMap = nil -- unused
DefaultDelegates.focusPointDimen = nil -- unused
DefaultPointRenderer.funcGetAFPixels = FujiDelegates.getFujiAfPoints
else
local pointsMap, pointDimen = PointsRendererFactory.getFocusPoints(photo)
DefaultDelegates.focusPointsMap = pointsMap
DefaultDelegates.focusPointDimen = pointDimen
DefaultPointRenderer.funcGetAFPixels = DefaultDelegates.getDefaultAfPoints
end
DefaultPointRenderer.funcGetShotOrientation = DefaultDelegates.getShotOrientation
return DefaultPointRenderer
end
function PointsRendererFactory.getFocusPoints(photo)
local cameraMake = string.lower(photo:getFormattedMetadata("cameraMake"))
local cameraModel = string.lower(photo:getFormattedMetadata("cameraModel"))
local focusPoints, focusPointDimens = PointsUtils.readIntoTable(cameraMake, cameraModel .. ".txt")
if (focusPoints == nil) then
return "No (or incorrect) mapping found at: \n" .. cameraMake .. "/" .. cameraModel .. ".txt"
else
return focusPoints, focusPointDimens
end
end
|
--[[
Copyright 2016 Joshua Musselwhite, Whizzbang Inc
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.
--]]
--[[
Factory for creating the focus point renderer and getting the focus points.
--]]
require "DefaultPointRenderer"
require "PointsUtils"
require "DefaultDelegates"
require "FujiDelegates"
local LrErrors = import 'LrErrors'
PointsRendererFactory = {}
function PointsRendererFactory.createRenderer(photo)
local cameraMake = photo:getFormattedMetadata("cameraMake")
local cameraModel = photo:getFormattedMetadata("cameraModel")
log ("cameraMake: " .. cameraMake)
log ("cameraModel: " .. cameraModel)
if (cameraMake == nil or cameraModel == nil) then
LrErrors.throwUserError("File doesn't contain camera maker or model")
end
cameraMake = string.lower(cameraMake)
cameraModel = string.lower(cameraModel)
if (cameraMake == "fujifilm") then
DefaultDelegates.focusPointsMap = nil -- unused
DefaultDelegates.focusPointDimen = nil -- unused
DefaultPointRenderer.funcGetAFPixels = FujiDelegates.getFujiAfPoints
else
local pointsMap, pointDimen = PointsRendererFactory.getFocusPoints(photo)
DefaultDelegates.focusPointsMap = pointsMap
DefaultDelegates.focusPointDimen = pointDimen
DefaultPointRenderer.funcGetAFPixels = DefaultDelegates.getDefaultAfPoints
end
DefaultPointRenderer.funcGetShotOrientation = DefaultDelegates.getShotOrientation
return DefaultPointRenderer
end
function PointsRendererFactory.getFocusPoints(photo)
local cameraMake = string.lower(photo:getFormattedMetadata("cameraMake"))
local cameraModel = string.lower(photo:getFormattedMetadata("cameraModel"))
local focusPoints, focusPointDimens = PointsUtils.readIntoTable(cameraMake, cameraModel .. ".txt")
if (focusPoints == nil) then
return "No (or incorrect) mapping found at: \n" .. cameraMake .. "/" .. cameraModel .. ".txt"
else
return focusPoints, focusPointDimens
end
end
|
fixed spelling mistake crashing app
|
fixed spelling mistake crashing app
|
Lua
|
apache-2.0
|
philmoz/Focus-Points,rderimay/Focus-Points,project802/Focus-Points,philmoz/Focus-Points,musselwhizzle/Focus-Points,project802/Focus-Points,mkjanke/Focus-Points,musselwhizzle/Focus-Points,project802/Focus-Points,project802/Focus-Points,rderimay/Focus-Points,mkjanke/Focus-Points
|
50eb33d1313f73c5134d46474b24ea5772a541c5
|
tests/testutils.lua
|
tests/testutils.lua
|
local table = require("Quadtastic/tableplus")
local testutils = {}
-- Returns a stub function and a function that returns how often the stub
-- function was called. If a function is given, then that function will be
-- wrapped by the stub function
function testutils.call_spy(f)
local n = 0 -- the number of times the function was called
local function stub(...)
n = n + 1
if f then return f(...) end
end
local function num_calls()
return n
end
return stub, num_calls
end
-- Returns whether the two values are similar by value
function testutils.equals(a, b)
if type(a) ~= type(b) then return false end
local t = type(a)
if not t then return true -- in case a and b are nil
elseif t == "number" or t == "string" or t == "function" then
return a == b
elseif t == "table" then
local all_keys = table.union(table.keys(a), table.keys(b))
for _,key in ipairs(all_keys) do
if not a[key] or not b[key] then return false end
return testutils.equals(a[key], b[key])
end
else
error("Cannot compare values of type " .. t)
end
end
function testutils.clone(thing)
local t = type(thing)
if t == "table" then
local c = {}
for k,v in pairs(thing) do
c[k] = testutils.clone(v)
end
return c
elseif t == "thread" then
error("Cannot clone a thread")
elseif t == "function" then
error("Cannot clone a function")
else -- all other types are immutable
return thing
end
end
return testutils
|
local table = require("Quadtastic/tableplus")
local testutils = {}
-- Returns a stub function and a function that returns how often the stub
-- function was called. If a function is given, then that function will be
-- wrapped by the stub function
function testutils.call_spy(f)
local n = 0 -- the number of times the function was called
local function stub(...)
n = n + 1
if f then return f(...) end
end
local function num_calls()
return n
end
return stub, num_calls
end
-- Returns whether the two values are similar by value
function testutils.equals(a, b)
if type(a) ~= type(b) then return false end
local t = type(a)
if not t then return true -- in case a and b are nil
elseif t == "number" or t == "string" or t == "function" then
return a == b
elseif t == "table" then
local all_keys = table.union(table.keys(a), table.keys(b))
local is_equal = true
for _,key in ipairs(all_keys) do
if not a[key] or not b[key] then return false end
is_equal = is_equal and testutils.equals(a[key], b[key])
end
return is_equal
else
error("Cannot compare values of type " .. t)
end
end
function testutils.clone(thing)
local t = type(thing)
if t == "table" then
local c = {}
for k,v in pairs(thing) do
c[k] = testutils.clone(v)
end
return c
elseif t == "thread" then
error("Cannot clone a thread")
elseif t == "function" then
error("Cannot clone a function")
else -- all other types are immutable
return thing
end
end
return testutils
|
Fix busted test logic for comparing tables
|
Fix busted test logic for comparing tables
guess I should have tested my testutils.......
|
Lua
|
mit
|
25A0/Quadtastic,25A0/Quadtastic
|
194ff68e57fe91a410d6eb8070c4c6eb2d1891ed
|
contrib/package/ffluci-splash/src/luci-splash.lua
|
contrib/package/ffluci-splash/src/luci-splash.lua
|
#!/usr/bin/lua
package.path = "/usr/lib/lua/?.lua;/usr/lib/lua/?/init.lua;" .. package.path
package.cpath = "/usr/lib/lua/?.so;" .. package.cpath
require("ffluci.http")
require("ffluci.sys")
require("ffluci.model.uci")
-- Init state session
uci = ffluci.model.uci.StateSession()
function main(argv)
local cmd = argv[1]
local arg = argv[2]
if not cmd then
print("Usage: " .. argv[0] .. " <status|add|remove|sync> [MAC]")
os.exit(1)
elseif cmd == "status" then
if not arg then
os.exit(1)
end
if iswhitelisted(arg) then
print("whitelisted")
os.exit(0)
end
if haslease(arg) then
print("lease")
os.exit(0)
end
print("unknown")
os.exit(0)
elseif cmd == "add" then
if not arg then
os.exit(1)
end
if not haslease(arg) then
add_lease(arg)
else
print("already leased!")
os.exit(2)
end
os.exit(0)
elseif cmd == "remove" then
if not cmd[2] then
os.exit(1)
end
remove_lease(arg)
os.exit(0)
elseif cmd == "sync" then
sync()
os.exit(0)
end
end
-- Add a lease to state and invoke add_rule
function add_lease(mac)
local key = uci:add("luci_splash", "lease")
uci:set("luci_splash", key, "mac", mac)
uci:set("luci_splash", key, "start", os.time())
add_rule(mac)
end
-- Remove a lease from state and invoke remove_rule
function remove_lease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v.mac:lower() == mac then
remove_rule(mac)
uci:del("luci_splash", k)
end
end
end
-- Add an iptables rule
function add_rule(mac)
return os.execute("iptables -t nat -I luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Remove an iptables rule
function remove_rule(mac)
return os.execute("iptables -t nat -D luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Check whether a MAC-Address is listed in the lease state list
function haslease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "lease" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Check whether a MAC-Address is whitelisted
function iswhitelisted(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "whitelist" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Returns a list of MAC-Addresses for which a rule is existing
function listrules()
local cmd = "iptables -t nat -L luci_splash_leases | grep RETURN |"
cmd = cmd .. "egrep -io [0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+"
return ffluci.util.split(ffluci.sys.exec(cmd))
end
-- Synchronise leases, remove abandoned rules
function sync()
local written = {}
local time = os.time()
-- Current leases in state files
local leases = uci:show("luci_splash").luci_splash
-- Convert leasetime to seconds
local leasetime = tonumber(uci:get("luci_splash", "general", "leasetime")) * 3600
-- Clean state file
uci:revert("luci_splash")
-- For all leases
for k, v in pairs(uci:show("luci_splash")) do
if v[".type"] == "lease" then
if os.difftime(time, tonumber(v.start)) > leasetime then
-- Remove expired
remove_rule(v.mac)
else
-- Rewrite state
local n = uci:add("luci_splash", "lease")
uci:set("luci_splash", n, "mac", v.mac)
uci:set("luci_splash", n, "start", v.start)
written[v.mac:lower()] = 1
end
end
end
-- Delete rules without state
for i, r in ipairs(listrules()) do
if #r > 0 and not written[r:lower()] then
remove_rule(r)
end
end
end
main(arg)
|
#!/usr/bin/lua
package.path = "/usr/lib/lua/?.lua;/usr/lib/lua/?/init.lua;" .. package.path
package.cpath = "/usr/lib/lua/?.so;" .. package.cpath
require("ffluci.http")
require("ffluci.sys")
require("ffluci.model.uci")
-- Init state session
uci = ffluci.model.uci.StateSession()
function main(argv)
local cmd = argv[1]
local arg = argv[2]
if cmd == "status" then
if not arg then
os.exit(1)
end
if iswhitelisted(arg) then
print("whitelisted")
os.exit(0)
end
if haslease(arg) then
print("lease")
os.exit(0)
end
print("unknown")
os.exit(0)
elseif cmd == "add" then
if not arg then
os.exit(1)
end
if not haslease(arg) then
add_lease(arg)
else
print("already leased!")
os.exit(2)
end
os.exit(0)
elseif cmd == "remove" then
if not arg then
os.exit(1)
end
remove_lease(arg)
os.exit(0)
elseif cmd == "sync" then
sync()
os.exit(0)
else
print("Usage: " .. argv[0] .. " <status|add|remove|sync> [MAC]")
os.exit(1)
end
end
-- Add a lease to state and invoke add_rule
function add_lease(mac)
local key = uci:add("luci_splash", "lease")
uci:set("luci_splash", key, "mac", mac)
uci:set("luci_splash", key, "start", os.time())
add_rule(mac)
end
-- Remove a lease from state and invoke remove_rule
function remove_lease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v.mac:lower() == mac then
remove_rule(mac)
uci:del("luci_splash", k)
end
end
end
-- Add an iptables rule
function add_rule(mac)
return os.execute("iptables -t nat -I luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Remove an iptables rule
function remove_rule(mac)
return os.execute("iptables -t nat -D luci_splash_leases -m mac --mac-source '"..mac.."' -j RETURN")
end
-- Check whether a MAC-Address is listed in the lease state list
function haslease(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "lease" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Check whether a MAC-Address is whitelisted
function iswhitelisted(mac)
mac = mac:lower()
for k, v in pairs(uci:show("luci_splash").luci_splash) do
if v[".type"] == "whitelist" and v.mac and v.mac:lower() == mac then
return true
end
end
return false
end
-- Returns a list of MAC-Addresses for which a rule is existing
function listrules()
local cmd = "iptables -t nat -L luci_splash_leases | grep RETURN |"
cmd = cmd .. "egrep -io [0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+"
return ffluci.util.split(ffluci.sys.exec(cmd))
end
-- Synchronise leases, remove abandoned rules
function sync()
local written = {}
local time = os.time()
-- Current leases in state files
local leases = uci:show("luci_splash").luci_splash
-- Convert leasetime to seconds
local leasetime = tonumber(uci:get("luci_splash", "general", "leasetime")) * 3600
-- Clean state file
uci:revert("luci_splash")
-- For all leases
for k, v in pairs(uci:show("luci_splash")) do
if v[".type"] == "lease" then
if os.difftime(time, tonumber(v.start)) > leasetime then
-- Remove expired
remove_rule(v.mac)
else
-- Rewrite state
local n = uci:add("luci_splash", "lease")
uci:set("luci_splash", n, "mac", v.mac)
uci:set("luci_splash", n, "start", v.start)
written[v.mac:lower()] = 1
end
end
end
-- Delete rules without state
for i, r in ipairs(listrules()) do
if #r > 0 and not written[r:lower()] then
remove_rule(r)
end
end
end
main(arg)
|
ffluci-splash: Minor fixes
|
ffluci-splash: Minor fixes
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@1963 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
projectbismark/luci-bismark,phi-psi/luci,jschmidlapp/luci,Flexibity/luci,gwlim/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,gwlim/luci,Flexibity/luci,phi-psi/luci,freifunk-gluon/luci,dtaht/cerowrt-luci-3.3,freifunk-gluon/luci,stephank/luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,stephank/luci,alxhh/piratenluci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,gwlim/luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,Canaan-Creative/luci,alxhh/piratenluci,projectbismark/luci-bismark,jschmidlapp/luci,jschmidlapp/luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,projectbismark/luci-bismark,Canaan-Creative/luci,freifunk-gluon/luci,gwlim/luci,saraedum/luci-packages-old,Canaan-Creative/luci,vhpham80/luci,phi-psi/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,phi-psi/luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,alxhh/piratenluci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,saraedum/luci-packages-old,ThingMesh/openwrt-luci,phi-psi/luci,vhpham80/luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,alxhh/piratenluci,eugenesan/openwrt-luci,yeewang/openwrt-luci,ch3n2k/luci,gwlim/luci,vhpham80/luci,alxhh/piratenluci,yeewang/openwrt-luci,ch3n2k/luci,stephank/luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,saraedum/luci-packages-old,projectbismark/luci-bismark,jschmidlapp/luci,zwhfly/openwrt-luci,alxhh/piratenluci,8devices/carambola2-luci,projectbismark/luci-bismark,gwlim/luci,ch3n2k/luci,eugenesan/openwrt-luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,ch3n2k/luci,freifunk-gluon/luci,jschmidlapp/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,Canaan-Creative/luci,ch3n2k/luci,Flexibity/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,stephank/luci,vhpham80/luci,zwhfly/openwrt-luci,stephank/luci,Canaan-Creative/luci,8devices/carambola2-luci,ch3n2k/luci,ThingMesh/openwrt-luci,yeewang/openwrt-luci,ch3n2k/luci,Flexibity/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,Canaan-Creative/luci,Canaan-Creative/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,saraedum/luci-packages-old,jschmidlapp/luci,Flexibity/luci,phi-psi/luci,alxhh/piratenluci,zwhfly/openwrt-luci,stephank/luci,vhpham80/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,8devices/carambola2-luci,8devices/carambola2-luci,Flexibity/luci
|
1e22b5db32ca37832ff134ed59a07a50cd82921f
|
Peripherals/WEB/init.lua
|
Peripherals/WEB/init.lua
|
if (not love.thread) or (not jit) then error("WEB peripherals requires love.thread and luajit") end
local perpath = select(1,...) --The path to the web folder
local bit = require("bit")
local events = require("Engine.events")
local json = require("Engine.JSON")
local thread = love.thread.newThread(perpath.."webthread.lua")
local to_channel = love.thread.newChannel()
local from_channel = love.thread.newChannel()
local to_counter = 0
local from_counter = 0
thread:start(to_channel, from_channel)
local function clearFuncsFromTable(t)
for k,v in pairs(t) do
if type(v) == "function" then
t[k] = nil
elseif type(v) == "table" then
clearFuncsFromTable(v)
end
end
end
return function(config) --A function that creates a new WEB peripheral.
if not thread:isRunning() then error("Failed to load luajit-request: "..tostring(thread:getError())) end
local timeout = config.timeout or 5
local CPUKit = config.CPUKit
if not CPUKit then error("WEB Peripheral can't work without the CPUKit passed") end
local indirect = {} --List of functions that requires custom coroutine.resume
local devkit = {}
local WEB, yWEB = {}, {}
function WEB.send(url,args)
if type(url) ~= "string" then return error("URL must be a string, provided: "..type(url)) end
local args = args or {}
if type(args) ~= "table" then return error("Args Must be a table or nil, provided: "..type(args)) end
clearFuncsFromTable(args) --Since JSON can't encode functions !
args.timeout = timeout
args = json:encode(args)
to_channel:push({url,args})
to_counter = to_counter + 1
return to_counter --Return the request ID
end
function WEB.urlEncode(str)
if type(str) ~= "string" then return error("STR must be a string, provided: "..type(str)) end
str = str:gsub("\n", "\r\n")
str = str:gsub("\r\r\n", "\r\n")
tr = str:gsub("([^A-Za-z0-9 %-%_%.])", function(c)
local n = string.byte(c)
if n < 128 then
-- ASCII
return string.format("%%%02X", n)
else
-- Non-ASCII (encode as UTF-8)
return string.format("%%%02X", 192 + bit.band( bit.arshift(n,6), 31 )) ..
string.format("%%%02X", 128 + bit.band( n, 63 ))
end
end)
str = str:gsub("%+", "%%2b")
str = str:gsub(" ", "+")
return str
end
events:register("love:update",function(dt)
local result = from_channel:pop()
if result then
from_counter = from_counter +1
local data = json:decode(result)
CPUKit.triggerEvent("webrequest",from_counter,unpack(data))
end
end)
events:register("love:reboot",function()
to_channel:clear()
to_channel:push("shutdown")
end)
events:register("love:quit",function()
love.window.close()
to_channel:clear()
to_channel:push("shutdown")
thread:wait()
end)
return WEB, yWEB, devkit
end
|
if (not love.thread) or (not jit) then error("WEB peripherals requires love.thread and luajit") end
local perpath = select(1,...) --The path to the web folder
local bit = require("bit")
local events = require("Engine.events")
local json = require("Engine.JSON")
local thread = love.thread.newThread(perpath.."webthread.lua")
local to_channel = love.thread.newChannel()
local from_channel = love.thread.newChannel()
local to_counter = 0
local from_counter = 0
thread:start(to_channel, from_channel)
local function clearFuncsFromTable(t)
for k,v in pairs(t) do
if type(v) == "function" then
t[k] = nil
elseif type(v) == "table" then
clearFuncsFromTable(v)
end
end
end
return function(config) --A function that creates a new WEB peripheral.
if not thread:isRunning() then error("Failed to load luajit-request: "..tostring(thread:getError())) end
local timeout = config.timeout or 5
local CPUKit = config.CPUKit
if not CPUKit then error("WEB Peripheral can't work without the CPUKit passed") end
local indirect = {} --List of functions that requires custom coroutine.resume
local devkit = {}
local WEB, yWEB = {}, {}
function WEB.send(url,args)
if type(url) ~= "string" then return error("URL must be a string, provided: "..type(url)) end
local args = args or {}
if type(args) ~= "table" then return error("Args Must be a table or nil, provided: "..type(args)) end
clearFuncsFromTable(args) --Since JSON can't encode functions !
args.timeout = timeout
args = json:encode(args)
to_channel:push({url,args})
to_counter = to_counter + 1
return to_counter --Return the request ID
end
function WEB.urlEncode(str)
if type(str) ~= "string" then return error("STR must be a string, provided: "..type(str)) end
str = str:gsub("\n", "\r\n")
str = str:gsub("\r\r\n", "\r\n")
str = str:gsub("([^A-Za-z0-9 %-%_%.])", function(c)
local n = string.byte(c)
if n < 128 then
-- ASCII
return string.format("%%%02X", n)
else
-- Non-ASCII (encode as UTF-8)
return string.format("%%%02X", 192 + bit.band( bit.arshift(n,6), 31 )) ..
string.format("%%%02X", 128 + bit.band( n, 63 ))
end
end)
str = str:gsub(" ", "+")
return str
end
events:register("love:update",function(dt)
local result = from_channel:pop()
if result then
from_counter = from_counter +1
local data = json:decode(result)
CPUKit.triggerEvent("webrequest",from_counter,unpack(data))
end
end)
events:register("love:reboot",function()
to_channel:clear()
to_channel:push("shutdown")
end)
events:register("love:quit",function()
love.window.close()
to_channel:clear()
to_channel:push("shutdown")
thread:wait()
end)
return WEB, yWEB, devkit
end
|
Bugfix a bug in WEB.urlEncode which existed since long time ago, WITHOUT BEING NOTICED !
|
Bugfix a bug in WEB.urlEncode which existed since long time ago, WITHOUT BEING NOTICED !
Former-commit-id: 61969af46d4f902cfd966117b1dad7053bcd40ae
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
ca03576e926a66549a8245cbc4238de91de1ea92
|
GuemUICastingBarFrame.lua
|
GuemUICastingBarFrame.lua
|
local AddonName, AddonTable = ...
local LSM = LibStub("LibSharedMedia-3.0")
_G[AddonName] = _G[AddonName] or LibStub("AceAddon-3.0"):NewAddon(AddonName)
local Addon = _G[AddonName]
local assert = assert
local type = type
local getmetatable = getmetatable
local CreateFrame = CreateFrame
local GetSpellInfo = GetSpellInfo
local GetTime = GetTime
local GetNetStats = GetNetStats
local UnitCastingInfo = UnitCastingInfo
local UnitChannelInfo = UnitChannelInfo
local IsHarmfulSpell = IsHarmfulSpell
local IsHelpfulSpell = IsHelpfulSpell
local UIParent = UIParent
local INTERRUPTED = INTERRUPTED
function Addon:CreateClass(Class, Name, Parent)
Name = Name or nil
Parent = Parent or UIParent
local obj = CreateFrame(Class, Name, Parent)
local base = getmetatable(obj).__index
obj.callbacks = {}
--Wrapping RegisterUnitEvent method
function obj:RegisterUnitEvent(event, unit, callback)
assert(type(callback) == "function" , "Usage : obj:RegisterUnitEvent(string event, string unitID, function callback")
self.callbacks[event] = callback
base.RegisterUnitEvent(self, event, unit)
end
--Wrapping UnregisterAllEvent method
function obj:UnregisterAllEvents()
self.callbacks = {}
base.UnregisterAllEvents()
end
--Wrapping UnregisterEvent method
function obj:UnregisterEvent(event)
assert(type(event) == "string", "Usage : obj:UnregisterEvent(string event)")
self.callbacks[event] = nil
base.UnregisterEvent(self, event)
end
--SetScript will call self.callbacks[event] on "OnEvent" fired
obj:SetScript("OnEvent", function(self, event, ...)
self.callbacks[event](self, event, ...)
end)
return obj
end
function Addon:CreateCastingBarFrame(Unit, Parent)
assert(type(Unit) == "string", "Usage : CreateCastingBarFrame(string Unit)")
Parent = Parent or UIParent
local f = self:CreateClass("Frame", AddonName..Unit, Parent)
local s = self:CreateClass("StatusBar", nil, f)
local sparkle = CreateFrame("Frame", nil, s)
local nameText = CreateFrame("Frame", nil, f)
local timerText = CreateFrame("Frame", nil, f)
f:Hide()
f:SetSize(220, 24)
f:SetPoint("BOTTOM", 0, 170)
local t = f:CreateTexture("Texture")
t:SetColorTexture(0, 0, 0)
t:SetAllPoints(f)
s:SetAllPoints(f)
s:SetStatusBarTexture("Interface\\AddOns\\"..AddonName.."\\Media\\Solid")
s:SetStatusBarColor(0, 0.5, 8.0)
s:SetFillStyle("STANDARD")
s:SetMinMaxValues(0.0, 1.0)
s:SetScript("OnValueChanged", function(self, val)
if(val <= 0.0 or val >= 1.0) then
sparkle:Hide()
else
sparkle:Show()
end
end)
sparkle:SetPoint("TOPLEFT", s:GetStatusBarTexture(), "TOPRIGHT", -7, 15)
sparkle:SetPoint("BOTTOMRIGHT", s:GetStatusBarTexture(), "BOTTOMRIGHT", 7, -15)
local t = sparkle:CreateTexture()
t:SetTexture("Interface\\CastingBar\\UI-CastingBar-Spark")
t:SetVertexColor(s:GetStatusBarColor())
t:SetBlendMode("ADD")
t:SetAllPoints(sparkle)
nameText:SetAllPoints(f)
local text = nameText:CreateFontString()
text:SetFont("Fonts\\2002.TTF", 10, "OUTLINE")
text:SetAllPoints(f)
text:SetTextColor( 1, 1, 1)
timerText:SetPoint("TOPRIGHT", f, "TOPRIGHT")
timerText:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT")
timerText:SetWidth(60)
local ttext = timerText:CreateFontString()
ttext:SetFont("Fonts\\2002.TTF", 8, "OUTLINE")
ttext:SetJustifyH("RIGHT")
ttext:SetAllPoints(timerText)
f.fadein = f:CreateAnimationGroup()
f.fadein:SetLooping("NONE")
local alpha = f.fadein:CreateAnimation("Alpha")
alpha:SetDuration(0.2)
alpha:SetFromAlpha(0.0)
alpha:SetToAlpha(1.0)
f.fadeout = f:CreateAnimationGroup()
f.fadeout:SetLooping("NONE")
local alpha = f.fadeout:CreateAnimation("Alpha")
alpha:SetDuration(0.5)
alpha:SetFromAlpha(1.0)
alpha:SetToAlpha(0.0)
f.fadeout:SetScript("OnFinished", function(self, ...)
f:Hide()
end)
local ccname, cctext, cctexture, ccstime, ccetime, cccastID
f:RegisterUnitEvent("UNIT_SPELLCAST_START", Unit, function(self, event, unit, ...)
ccname, _, cctext, cctexture, ccstime, ccetime, _, cccastID = UnitCastingInfo(unit)
text:SetFormattedText("%s", cctext)
self:Show()
self.fadeout:Stop()
self.fadein:Play()
end)
f:RegisterUnitEvent("UNIT_SPELLCAST_STOP", Unit, function(self, event, unit, name, rank, castid, spellid)
ccname, _, cctext, cctexture, ccstime, ccetime, _, cccastID = UnitCastingInfo(unit)
self.fadeout:Play()
end)
f:RegisterUnitEvent("UNIT_SPELLCAST_INTERRUPTED", Unit, function(self, event, unit, name, rank, castid, spellid)
local val = s:GetMinMaxValues()
text:SetText(INTERRUPTED)
s:SetValue(val)
end)
f:RegisterUnitEvent("UNIT_SPELLCAST_SUCCEEDED", Unit, function(self, event, unit, name, rank, castid, spellid)
if(castid == cccastID) then
local _, val = s:GetMinMaxValues()
s:SetValue(val)
end
end)
f:SetScript('OnUpdate', function(self, rate)
if ccstime and ccetime then
local t = GetTime() * 1000
s:SetValue((t - ccstime) / (ccetime-ccstime))
--ttext:SetFormattedText("%.1f / %.1f", (t - ccstime)/1000, (ccetime-ccstime)/1000)
ttext:SetFormattedText("%.1f", (ccetime - t)/1000)
end
end)
return f
end
|
local AddonName, AddonTable = ...
local LSM = LibStub("LibSharedMedia-3.0")
_G[AddonName] = _G[AddonName] or LibStub("AceAddon-3.0"):NewAddon(AddonName)
local Addon = _G[AddonName]
local assert = assert
local type = type
local getmetatable = getmetatable
local CreateFrame = CreateFrame
local GetSpellInfo = GetSpellInfo
local GetTime = GetTime
local GetNetStats = GetNetStats
local UnitCastingInfo = UnitCastingInfo
local UnitChannelInfo = UnitChannelInfo
local IsHarmfulSpell = IsHarmfulSpell
local IsHelpfulSpell = IsHelpfulSpell
local UIParent = UIParent
local INTERRUPTED = INTERRUPTED
function Addon:CreateClass(Class, Name, Parent)
Name = Name or nil
Parent = Parent or UIParent
local obj = CreateFrame(Class, Name, Parent)
local base = getmetatable(obj).__index
obj.callbacks = {}
--Wrapping RegisterUnitEvent method
function obj:RegisterUnitEvent(event, unit, callback)
assert(type(callback) == "function" , "Usage : obj:RegisterUnitEvent(string event, string unitID, function callback")
self.callbacks[event] = callback
base.RegisterUnitEvent(self, event, unit)
end
--Wrapping UnregisterAllEvent method
function obj:UnregisterAllEvents()
self.callbacks = {}
base.UnregisterAllEvents()
end
--Wrapping UnregisterEvent method
function obj:UnregisterEvent(event)
assert(type(event) == "string", "Usage : obj:UnregisterEvent(string event)")
self.callbacks[event] = nil
base.UnregisterEvent(self, event)
end
--SetScript will call self.callbacks[event] on "OnEvent" fired
obj:SetScript("OnEvent", function(self, event, ...)
self.callbacks[event](self, event, ...)
end)
return obj
end
function Addon:CreateCastingBarFrame(Unit, Parent)
assert(type(Unit) == "string", "Usage : CreateCastingBarFrame(string Unit)")
Parent = Parent or UIParent
local f = self:CreateClass("Frame", AddonName..Unit, Parent)
local s = self:CreateClass("StatusBar", nil, f)
local sparkle = CreateFrame("Frame", nil, s)
local nameText = CreateFrame("Frame", nil, f)
local timerText = CreateFrame("Frame", nil, f)
local latencyoverlay = CreateFrame("Frame", "Latencyoverlay", f)
f:Hide()
f:SetSize(220, 24)
f:SetPoint("BOTTOM", 0, 170)
local t = f:CreateTexture("Texture")
t:SetColorTexture(0, 0, 0)
t:SetAllPoints(f)
s:SetAllPoints(f)
s:SetStatusBarTexture("Interface\\AddOns\\"..AddonName.."\\Media\\Solid")
s:SetStatusBarColor(0, 0.5, 8.0)
s:SetFillStyle("STANDARD_NO_RANGE_FILL")
s:SetMinMaxValues(0.0, 1.0)
s:SetScript("OnValueChanged", function(self, val)
if(val <= 0.0 or val >= 1.0) then
sparkle:Hide()
else
sparkle:Show()
end
end)
sparkle:SetPoint("TOPLEFT", s:GetStatusBarTexture(), "TOPRIGHT", -7, 15)
sparkle:SetPoint("BOTTOMRIGHT", s:GetStatusBarTexture(), "BOTTOMRIGHT", 7, -15)
local t = sparkle:CreateTexture()
t:SetTexture("Interface\\CastingBar\\UI-CastingBar-Spark")
t:SetVertexColor(s:GetStatusBarColor())
t:SetBlendMode("ADD")
t:SetAllPoints(sparkle)
nameText:SetAllPoints(f)
local text = nameText:CreateFontString()
text:SetFont("Fonts\\2002.TTF", 10, "OUTLINE")
text:SetAllPoints(f)
text:SetTextColor( 1, 1, 1)
timerText:SetPoint("TOPLEFT", f, "TOPRIGHT", -60, 0)
timerText:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", -2, 0)
timerText:SetWidth(60)
local ttext = timerText:CreateFontString()
ttext:SetFont("Fonts\\2002.TTF", 8, "OUTLINE")
ttext:SetJustifyH("RIGHT")
ttext:SetAllPoints(timerText)
latencyoverlay:SetPoint("TOPRIGHT", f, "TOPRIGHT")
latencyoverlay:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT")
local t = latencyoverlay:CreateTexture()
t:SetColorTexture(0.8, 0.6, 0.0, 0.3)
t:SetAllPoints(latencyoverlay)
f.fadein = f:CreateAnimationGroup()
f.fadein:SetLooping("NONE")
local alpha = f.fadein:CreateAnimation("Alpha")
alpha:SetDuration(0.2)
alpha:SetFromAlpha(0.0)
alpha:SetToAlpha(1.0)
f.fadeout = f:CreateAnimationGroup()
f.fadeout:SetLooping("NONE")
local alpha = f.fadeout:CreateAnimation("Alpha")
alpha:SetDuration(0.5)
alpha:SetFromAlpha(1.0)
alpha:SetToAlpha(0.0)
f.fadeout:SetScript("OnFinished", function(self, ...)
f:Hide()
end)
local ccname, cctext, cctexture, ccstime, ccetime, cccastID
local wlatency
f:RegisterUnitEvent("UNIT_SPELLCAST_START", Unit, function(self, event, unit, ...)
ccname, _, cctext, cctexture, ccstime, ccetime, _, cccastID = UnitCastingInfo(unit)
_, _, _, wlatency = GetNetStats()
latencyoverlay:SetWidth(wlatency * 1000 / (ccetime-ccstime))
text:SetFormattedText("%s", string.sub( cctext, 1, 40 ))
self:Show()
self.fadeout:Stop()
self.fadein:Play()
end)
f:RegisterUnitEvent("UNIT_SPELLCAST_CHANNEL_START", Unit, function(self, event, unit, ...)
ccname, _, cctext, cctexture, ccetime, ccstime, _, cccastID = UnitChannelInfo(unit)
_, _, _, wlatency = GetNetStats()
latencyoverlay:SetWidth(0)
text:SetFormattedText("%s", string.sub( ccname, 1, 40 ))
self:Show()
self.fadeout:Stop()
self.fadein:Play()
end)
f:RegisterUnitEvent("UNIT_SPELLCAST_STOP", Unit, function(self, event, unit, name, rank, castid, spellid)
ccname, _, cctext, cctexture, ccstime, ccetime, _, cccastID = UnitCastingInfo(unit)
self.fadeout:Play()
end)
f:RegisterUnitEvent("UNIT_SPELLCAST_CHANNEL_STOP", Unit, function(self, event, unit, name, rank, castid, spellid)
ccname, _, cctext, cctexture, ccstime, ccetime, _, cccastID = UnitChannelInfo(unit)
self.fadeout:Play()
end)
f:RegisterUnitEvent("UNIT_SPELLCAST_INTERRUPTED", Unit, function(self, event, unit, name, rank, castid, spellid)
local val = s:GetMinMaxValues()
text:SetText(INTERRUPTED)
ttext:SetText("")
s:SetValue(val)
end)
f:RegisterUnitEvent("UNIT_SPELLCAST_SUCCEEDED", Unit, function(self, event, unit, name, rank, castid, spellid)
if(castid == cccastID) then
local _, val = s:GetMinMaxValues()
s:SetValue(val)
end
end)
f:SetScript('OnUpdate', function(self, rate)
if ccstime and ccetime then
local t = GetTime() * 1000
s:SetValue((t - ccstime) / (ccetime-ccstime))
--ttext:SetFormattedText("%.1f / %.1f", (t - ccstime)/1000, (ccetime-ccstime)/1000)
ttext:SetFormattedText("%.1f", (ccetime - t)/1000)
end
end)
return f
end
|
Multiple bug fixes, and now support channelings.
|
Multiple bug fixes, and now support channelings.
|
Lua
|
unlicense
|
Guema/gCastBars,Guema/GuemUICastBars
|
065fb2fd632bf8e81b3f556e8069956f371d1582
|
Hydra/API/window.lua
|
Hydra/API/window.lua
|
--- window
---
--- Functions for managing any window.
---
--- To get windows, see `window.focusedwindow` and `window.visiblewindows`.
---
--- To get window geometrical attributes, see `window.{frame,size,topleft}`.
---
--- To move and resize windows, see `window.set{frame,size,topleft}`.
---
--- It may be handy to get a window's app or screen via `window.application` and `window.screen`.
---
--- See the `screen` module for detailed explanation of how Hydra uses window/screen coordinates.
--- window.allwindows() -> win[]
--- Returns all windows
function window.allwindows()
return fnutils.mapcat(application.runningapplications(), application.allwindows)
end
--- window.windowforid() -> win or nil
--- Returns the window for the given id, or nil if it's an invalid id.
function window.windowforid(id)
return fnutils.find(window.allwindows(), function(win) return win:id() == id end)
end
--- window:isvisible() -> bool
--- True if the app is not hidden or minimized.
function window:isvisible()
return not self:application():ishidden() and not self:isminimized()
end
--- window:frame() -> rect
--- Get the frame of the window in absolute coordinates.
function window:frame()
local s = self:size()
local tl = self:topleft()
return {x = tl.x, y = tl.y, w = s.w, h = s.h}
end
--- window:setframe(rect)
--- Set the frame of the window in absolute coordinates.
function window:setframe(f)
self:setsize(f)
self:settopleft(f)
self:setsize(f)
end
--- window:otherwindows_samescreen() -> win[]
--- Get other windows on the same screen as self.
function window:otherwindows_samescreen()
return fnutils.filter(window.visiblewindows(), function(win) return self ~= win and self:screen() == win:screen() end)
end
--- window:otherwindows_allscreens() -> win[]
--- Get every window except this one.
function window:otherwindows_allscreens()
return fnutils.filter(window.visiblewindows(), function(win) return self ~= win end)
end
--- window:focus() -> bool
--- Try to make this window focused.
function window:focus()
return self:becomemain() and self:application():_bringtofront()
end
--- window.visiblewindows() -> win[]
--- Get all windows on all screens that match window.isvisible.
function window.visiblewindows()
return fnutils.filter(window:allwindows(), window.isvisible)
end
--- window.orderedwindows() -> win[]
--- Returns all visible windows, ordered from front to back.
function window.orderedwindows()
local orderedwins = {}
local orderedwinids = window._orderedwinids()
local windows = window.visiblewindows()
for _, orderedwinid in pairs(orderedwinids) do
for _, win in pairs(windows) do
if orderedwinid == win:id() then
table.insert(orderedwins, win)
break
end
end
end
return orderedwins
end
--- window:maximize()
--- Make this window fill the whole screen its on, without covering the dock or menu.
function window:maximize()
local screenrect = self:screen():frame_without_dock_or_menu()
self:setframe(screenrect)
end
--- window:screen()
--- Get the screen which most contains this window (by area).
function window:screen()
local windowframe = self:frame()
local lastvolume = 0
local lastscreen = nil
for _, screen in pairs(screen.allscreens()) do
local screenframe = screen:frame_including_dock_and_menu()
local intersection = geometry.intersectionrect(windowframe, screenframe)
local volume = intersection.w * intersection.h
if volume > lastvolume then
lastvolume = volume
lastscreen = screen
end
end
return lastscreen
end
local function windows_in_direction(win, numrotations)
-- assume looking to east
-- use the score distance/cos(A/2), where A is the angle by which it
-- differs from the straight line in the direction you're looking
-- for. (may have to manually prevent division by zero.)
-- thanks mark!
local thiswindow = window.focusedwindow()
local startingpoint = geometry.rectmidpoint(thiswindow:frame())
local otherwindows = fnutils.filter(thiswindow:otherwindows_allscreens(), function(win) return window.isvisible(win) and window.isstandard(win) end)
local closestwindows = {}
for _, win in pairs(otherwindows) do
local otherpoint = geometry.rectmidpoint(win:frame())
otherpoint = geometry.rotateccw(otherpoint, startingpoint, numrotations)
local delta = {
x = otherpoint.x - startingpoint.x,
y = otherpoint.y - startingpoint.y,
}
if delta.x > 0 then
local angle = math.atan2(delta.y, delta.x)
local distance = geometry.hypot(delta)
local anglediff = -angle
local score = distance / math.cos(anglediff / 2)
table.insert(closestwindows, {win = win, score = score})
end
end
table.sort(closestwindows, function(a, b) return a.score < b.score end)
return fnutils.map(closestwindows, function(x) return x.win end)
end
local function focus_first_valid_window(ordered_wins)
for _, win in pairs(ordered_wins) do
if win:focus() then return true end
end
return false
end
--- window:windows_to_east()
--- Get all windows east of this one, ordered by closeness.
function window:windows_to_east() return windows_in_direction(self, 0) end
--- window:windows_to_west()
--- Get all windows west of this one, ordered by closeness.
function window:windows_to_west() return windows_in_direction(self, 2) end
--- window:windows_to_north()
--- Get all windows north of this one, ordered by closeness.
function window:windows_to_north() return windows_in_direction(self, 1) end
--- window:windows_to_south()
--- Get all windows south of this one, ordered by closeness.
function window:windows_to_south() return windows_in_direction(self, 3) end
--- window:focuswindow_east()
--- Focus the first focus-able window to the east of this one.
function window:focuswindow_east() return focus_first_valid_window(self:windows_to_east()) end
--- window:focuswindow_west()
--- Focus the first focus-able window to the west of this one.
function window:focuswindow_west() return focus_first_valid_window(self:windows_to_west()) end
--- window:focuswindow_north()
--- Focus the first focus-able window to the north of this one.
function window:focuswindow_north() return focus_first_valid_window(self:windows_to_north()) end
--- window:focuswindow_south()
--- Focus the first focus-able window to the south of this one.
function window:focuswindow_south() return focus_first_valid_window(self:windows_to_south()) end
|
--- window
---
--- Functions for managing any window.
---
--- To get windows, see `window.focusedwindow` and `window.visiblewindows`.
---
--- To get window geometrical attributes, see `window.{frame,size,topleft}`.
---
--- To move and resize windows, see `window.set{frame,size,topleft}`.
---
--- It may be handy to get a window's app or screen via `window.application` and `window.screen`.
---
--- See the `screen` module for detailed explanation of how Hydra uses window/screen coordinates.
--- window.allwindows() -> win[]
--- Returns all windows
function window.allwindows()
return fnutils.mapcat(application.runningapplications(), application.allwindows)
end
--- window.windowforid() -> win or nil
--- Returns the window for the given id, or nil if it's an invalid id.
function window.windowforid(id)
return fnutils.find(window.allwindows(), function(win) return win:id() == id end)
end
--- window:isvisible() -> bool
--- True if the app is not hidden or minimized.
function window:isvisible()
return not self:application():ishidden() and not self:isminimized()
end
--- window:frame() -> rect
--- Get the frame of the window in absolute coordinates.
function window:frame()
local s = self:size()
local tl = self:topleft()
return {x = tl.x, y = tl.y, w = s.w, h = s.h}
end
--- window:setframe(rect)
--- Set the frame of the window in absolute coordinates.
function window:setframe(f)
self:setsize(f)
self:settopleft(f)
self:setsize(f)
end
--- window:otherwindows_samescreen() -> win[]
--- Get other windows on the same screen as self.
function window:otherwindows_samescreen()
return fnutils.filter(window.visiblewindows(), function(win) return self ~= win and self:screen() == win:screen() end)
end
--- window:otherwindows_allscreens() -> win[]
--- Get every window except this one.
function window:otherwindows_allscreens()
return fnutils.filter(window.visiblewindows(), function(win) return self ~= win end)
end
--- window:focus() -> bool
--- Try to make this window focused.
function window:focus()
return self:becomemain() and self:application():_bringtofront()
end
--- window.visiblewindows() -> win[]
--- Get all windows on all screens that match window.isvisible.
function window.visiblewindows()
return fnutils.filter(window:allwindows(), window.isvisible)
end
--- window.orderedwindows() -> win[]
--- Returns all visible windows, ordered from front to back.
function window.orderedwindows()
local orderedwins = {}
local orderedwinids = window._orderedwinids()
local windows = window.visiblewindows()
for _, orderedwinid in pairs(orderedwinids) do
for _, win in pairs(windows) do
if orderedwinid == win:id() then
table.insert(orderedwins, win)
break
end
end
end
return orderedwins
end
--- window:maximize()
--- Make this window fill the whole screen its on, without covering the dock or menu.
function window:maximize()
local screenrect = self:screen():frame_without_dock_or_menu()
self:setframe(screenrect)
end
--- window:screen()
--- Get the screen which most contains this window (by area).
function window:screen()
local windowframe = self:frame()
local lastvolume = 0
local lastscreen = nil
for _, screen in pairs(screen.allscreens()) do
local screenframe = screen:frame_including_dock_and_menu()
local intersection = geometry.intersectionrect(windowframe, screenframe)
local volume = intersection.w * intersection.h
if volume > lastvolume then
lastvolume = volume
lastscreen = screen
end
end
return lastscreen
end
local function windows_in_direction(win, numrotations)
-- assume looking to east
-- use the score distance/cos(A/2), where A is the angle by which it
-- differs from the straight line in the direction you're looking
-- for. (may have to manually prevent division by zero.)
-- thanks mark!
local startingpoint = geometry.rectmidpoint(win:frame())
local otherwindows = fnutils.filter(win:otherwindows_allscreens(), function(win) return window.isvisible(win) and window.isstandard(win) end)
local closestwindows = {}
for _, win in pairs(otherwindows) do
local otherpoint = geometry.rectmidpoint(win:frame())
otherpoint = geometry.rotateccw(otherpoint, startingpoint, numrotations)
local delta = {
x = otherpoint.x - startingpoint.x,
y = otherpoint.y - startingpoint.y,
}
if delta.x > 0 then
local angle = math.atan2(delta.y, delta.x)
local distance = geometry.hypot(delta)
local anglediff = -angle
local score = distance / math.cos(anglediff / 2)
table.insert(closestwindows, {win = win, score = score})
end
end
table.sort(closestwindows, function(a, b) return a.score < b.score end)
return fnutils.map(closestwindows, function(x) return x.win end)
end
local function focus_first_valid_window(ordered_wins)
for _, win in pairs(ordered_wins) do
if win:focus() then return true end
end
return false
end
--- window:windows_to_east()
--- Get all windows east of this one, ordered by closeness.
function window:windows_to_east() return windows_in_direction(self, 0) end
--- window:windows_to_west()
--- Get all windows west of this one, ordered by closeness.
function window:windows_to_west() return windows_in_direction(self, 2) end
--- window:windows_to_north()
--- Get all windows north of this one, ordered by closeness.
function window:windows_to_north() return windows_in_direction(self, 1) end
--- window:windows_to_south()
--- Get all windows south of this one, ordered by closeness.
function window:windows_to_south() return windows_in_direction(self, 3) end
--- window:focuswindow_east()
--- Focus the first focus-able window to the east of this one.
function window:focuswindow_east() return focus_first_valid_window(self:windows_to_east()) end
--- window:focuswindow_west()
--- Focus the first focus-able window to the west of this one.
function window:focuswindow_west() return focus_first_valid_window(self:windows_to_west()) end
--- window:focuswindow_north()
--- Focus the first focus-able window to the north of this one.
function window:focuswindow_north() return focus_first_valid_window(self:windows_to_north()) end
--- window:focuswindow_south()
--- Focus the first focus-able window to the south of this one.
function window:focuswindow_south() return focus_first_valid_window(self:windows_to_south()) end
|
Fix window:focuswindow_* and window:windows_to_* methods.
|
Fix window:focuswindow_* and window:windows_to_* methods.
|
Lua
|
mit
|
latenitefilms/hammerspoon,ocurr/hammerspoon,wvierber/hammerspoon,heptal/hammerspoon,wsmith323/hammerspoon,zzamboni/hammerspoon,kkamdooong/hammerspoon,CommandPost/CommandPost-App,dopcn/hammerspoon,ocurr/hammerspoon,cmsj/hammerspoon,TimVonsee/hammerspoon,Stimim/hammerspoon,cmsj/hammerspoon,wvierber/hammerspoon,emoses/hammerspoon,nkgm/hammerspoon,CommandPost/CommandPost-App,heptal/hammerspoon,Hammerspoon/hammerspoon,zzamboni/hammerspoon,joehanchoi/hammerspoon,joehanchoi/hammerspoon,knu/hammerspoon,knu/hammerspoon,cmsj/hammerspoon,bradparks/hammerspoon,Habbie/hammerspoon,lowne/hammerspoon,zzamboni/hammerspoon,Hammerspoon/hammerspoon,tmandry/hammerspoon,dopcn/hammerspoon,knu/hammerspoon,wvierber/hammerspoon,peterhajas/hammerspoon,knu/hammerspoon,peterhajas/hammerspoon,asmagill/hammerspoon,nkgm/hammerspoon,wvierber/hammerspoon,TimVonsee/hammerspoon,knl/hammerspoon,asmagill/hammerspoon,zzamboni/hammerspoon,bradparks/hammerspoon,Stimim/hammerspoon,knu/hammerspoon,kkamdooong/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,hypebeast/hammerspoon,chrisjbray/hammerspoon,peterhajas/hammerspoon,knl/hammerspoon,Stimim/hammerspoon,CommandPost/CommandPost-App,kkamdooong/hammerspoon,Hammerspoon/hammerspoon,ocurr/hammerspoon,junkblocker/hammerspoon,trishume/hammerspoon,lowne/hammerspoon,joehanchoi/hammerspoon,zzamboni/hammerspoon,bradparks/hammerspoon,junkblocker/hammerspoon,tmandry/hammerspoon,heptal/hammerspoon,peterhajas/hammerspoon,junkblocker/hammerspoon,TimVonsee/hammerspoon,heptal/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,nkgm/hammerspoon,trishume/hammerspoon,Hammerspoon/hammerspoon,joehanchoi/hammerspoon,lowne/hammerspoon,CommandPost/CommandPost-App,dopcn/hammerspoon,junkblocker/hammerspoon,Habbie/hammerspoon,bradparks/hammerspoon,chrisjbray/hammerspoon,latenitefilms/hammerspoon,ocurr/hammerspoon,CommandPost/CommandPost-App,knl/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,wsmith323/hammerspoon,asmagill/hammerspoon,wsmith323/hammerspoon,zzamboni/hammerspoon,chrisjbray/hammerspoon,hypebeast/hammerspoon,TimVonsee/hammerspoon,wsmith323/hammerspoon,wsmith323/hammerspoon,hypebeast/hammerspoon,hypebeast/hammerspoon,heptal/hammerspoon,emoses/hammerspoon,junkblocker/hammerspoon,knl/hammerspoon,nkgm/hammerspoon,nkgm/hammerspoon,ocurr/hammerspoon,kkamdooong/hammerspoon,Stimim/hammerspoon,chrisjbray/hammerspoon,Hammerspoon/hammerspoon,emoses/hammerspoon,Habbie/hammerspoon,chrisjbray/hammerspoon,joehanchoi/hammerspoon,latenitefilms/hammerspoon,kkamdooong/hammerspoon,asmagill/hammerspoon,hypebeast/hammerspoon,dopcn/hammerspoon,Habbie/hammerspoon,knu/hammerspoon,lowne/hammerspoon,asmagill/hammerspoon,knl/hammerspoon,TimVonsee/hammerspoon,peterhajas/hammerspoon,Stimim/hammerspoon,asmagill/hammerspoon,lowne/hammerspoon,chrisjbray/hammerspoon,Hammerspoon/hammerspoon,trishume/hammerspoon,dopcn/hammerspoon,tmandry/hammerspoon,cmsj/hammerspoon,emoses/hammerspoon,emoses/hammerspoon,wvierber/hammerspoon,Habbie/hammerspoon,bradparks/hammerspoon
|
8fa906a132133820c97a49b94d5fffb6c8d5737f
|
lua/quicDetect.lua
|
lua/quicDetect.lua
|
local ffi = require "ffi"
local lm = require "libmoon"
local pktLib = require "packet"
local eth = require "proto.ethernet"
local ip4 = require "proto.ip4"
local ip6 = require "proto.ip6"
local tuple = require "tuple"
local log = require "log"
local hmap = require "hmap"
local namespace = require "namespaces"
local band = bit.band
ffi.cdef [[
int memcmp(const void *s1, const void *s2, size_t n);
]]
local module = {}
-- A protocol detector/tracker for quic as of RFC version 00
ffi.cdef [[
struct conn_id {
uint64_t id;
};
]]
module.flowKeys = {
"struct ipv4_5tuple",
--"struct conn_id"
}
ffi.cdef [[
struct quic_flow_state {
uint64_t last_seen;
uint64_t first_seen;
uint64_t connection_id;
uint16_t initial_port;
uint32_t initial_ip;
uint8_t tracked;
};
]]
module.stateType = "struct quic_flow_state"
module.defaultState = {}
module.mode = "qq"
local shared = namespace:get()
local IDtable = nil
local acc = nil
shared.lock(function()
if shared.tbl == nil then
shared.tbl = hmap.createHashmap(8, ffi.sizeof("struct ipv4_5tuple"))
end
IDtable = shared.tbl
acc = IDtable.newAccessor()
ffi.gc(acc, acc.free)
end)
function module.extractFlowKey(buf, keyBuf)
local success, idx = tuple.extractIP5Tuple(buf, keyBuf) -- Reuse 5-tuple extractor
if success and idx == 1 then
keyBuf = ffi.cast("struct ipv4_5tuple&", keyBuf)
if keyBuf.proto == ip4.PROTO_UDP and (keyBuf.port_a == 443 or keyBuf.port_b == 443) then
return success, idx
end
end
return false
end
function module.handlePacket(flowKey, state, buf, isFirstPacket)
local t = buf:getTimestamp() * 10^6
state.last_seen = t
if isFirstPacket then
state.first_seen = t
end
print(flowKey)
local udpPkt = pktLib.getUdp4Packet(buf)
--local quicFrame = udpPkt.payload.uint8
local flags = udpPkt.payload.uint8[0]
if band(flags, 0x08) ~= 0 then
local dump = false
local cid = ffi.cast("uint64_t*", udpPkt.payload.uint8 + 1)[0]
print("has CID!", cid)
if not isFirstPacket and cid ~= state.connection_id then
log:warn("Connection ID changed for flow %s: %s -> %s", flowKey, tonumber(state.connection_id), tonumber(cid))
end
state.connection_id = cid
-- Check ID -> 5-Tuple map
local keyBuf = ffi.new("uint8_t[?]", IDtable.keyBufSize())
ffi.copy(keyBuf, udpPkt.payload.uint8 + 1, 8)
local new = IDtable:access(acc, keyBuf)
local tpl = ffi.cast("struct ipv4_5tuple&", acc:get())
if new then
ffi.copy(tpl, flowKey, ffi.sizeof("struct ipv4_5tuple"))
end
if ffi.C.memcmp(tpl, flowKey, ffi.sizeof(flowKey)) ~= 0 then
log:warn("Connection migration of id %i from %s to %s", tonumber(cid), tpl, flowKey)
state.tracked = 1
dump = true
end
acc:release()
return dump
else
print("no CID!")
if isFirstPacket then
log:warn("First packet in flow and no connection ID!")
end
end
return true
end
-- #### Checker configuration ####
module.checkInterval = 5
function module.checkExpiry(flowKey, state, checkState)
local t = lm.getTime() * 10^6
if state.tracked == 1 and tonumber(state.last_seen) + 30 * 10^6 < t then
return true, tonumber(state.last_seen) / 10^6
end
return false
end
-- #### Dumper configuration ####
-- Only applicable if mode is set to "qq"
module.maxDumperRules = 100
-- Function that returns a packet filter string in pcap syntax from a given flow key
function module.buildPacketFilter(flowKey)
return flowKey:getPflang()
end
return module
|
local ffi = require "ffi"
local lm = require "libmoon"
local pktLib = require "packet"
local eth = require "proto.ethernet"
local ip4 = require "proto.ip4"
local ip6 = require "proto.ip6"
local tuple = require "tuple"
local log = require "log"
local hmap = require "hmap"
local namespace = require "namespaces"
local band = bit.band
ffi.cdef [[
int memcmp(const void *s1, const void *s2, size_t n);
]]
local module = {}
-- A protocol detector/tracker for quic as of RFC version 00
ffi.cdef [[
struct conn_id {
uint64_t id;
};
]]
module.flowKeys = {
"struct ipv4_5tuple",
--"struct conn_id"
}
ffi.cdef [[
struct quic_flow_state {
uint64_t last_seen;
uint64_t first_seen;
uint64_t connection_id;
uint16_t initial_port;
uint32_t initial_ip;
uint8_t tracked;
};
]]
module.stateType = "struct quic_flow_state"
module.defaultState = {}
module.mode = "qq"
local shared = namespace:get()
local IDtable = nil
local acc = nil
local IDkeyBuf = nl
shared.lock(function()
if shared.tbl == nil then
shared.tbl = hmap.createHashmap(8, ffi.sizeof("struct ipv4_5tuple"))
end
IDtable = shared.tbl
acc = IDtable.newAccessor()
ffi.gc(acc, acc.free)
IDkeyBuf = ffi.new("uint8_t[?]", IDtable.keyBufSize())
end)
function module.extractFlowKey(buf, keyBuf)
local success, idx = tuple.extractIP5Tuple(buf, keyBuf) -- Reuse 5-tuple extractor
if success and idx == 1 then
keyBuf = ffi.cast("struct ipv4_5tuple&", keyBuf)
if keyBuf.proto == ip4.PROTO_UDP and (keyBuf.port_a == 443 or keyBuf.port_b == 443) then
return success, idx
end
end
return false
end
function module.handlePacket(flowKey, state, buf, isFirstPacket)
local t = buf:getTimestamp() * 10^6
state.last_seen = t
if isFirstPacket then
state.first_seen = t
end
local udpPkt = pktLib.getUdp4Packet(buf)
--local quicFrame = udpPkt.payload.uint8
local flags = udpPkt.payload.uint8[0]
if band(flags, 0x08) ~= 0 then
local dump = false
local cid = ffi.cast("uint64_t*", udpPkt.payload.uint8 + 1)[0]
print("has CID!", cid)
if not isFirstPacket and cid ~= state.connection_id then
log:warn("Connection ID changed for flow %s: %s -> %s", flowKey, tonumber(state.connection_id), tonumber(cid))
end
state.connection_id = cid
-- Check ID -> 5-Tuple map
ffi.copy(IDkeyBuf, udpPkt.payload.uint8 + 1, 8)
local new = IDtable:access(acc, IDkeyBuf)
local tpl = ffi.cast("struct ipv4_5tuple&", acc:get())
if new then
ffi.copy(tpl, flowKey, ffi.sizeof("struct ipv4_5tuple"))
end
if ffi.C.memcmp(tpl, flowKey, ffi.sizeof("struct ipv4_5tuple")) ~= 0 then
log:warn("Connection migration of id %i from %s to %s", tonumber(cid), tpl, flowKey)
state.tracked = 1
dump = true
end
acc:release()
return dump
else
print("no CID!")
if isFirstPacket then
log:warn("First packet in flow and no connection ID!")
end
end
return false
end
-- #### Checker configuration ####
module.checkInterval = 5
function module.checkExpiry(flowKey, state, checkState)
local t = lm.getTime() * 10^6
if state.tracked == 1 and tonumber(state.last_seen) + 30 * 10^6 < t then
return true, tonumber(state.last_seen) / 10^6
end
return false
end
-- #### Dumper configuration ####
-- Only applicable if mode is set to "qq"
module.maxDumperRules = 100
-- Function that returns a packet filter string in pcap syntax from a given flow key
function module.buildPacketFilter(flowKey)
return flowKey:getPflang()
end
return module
|
Fix key compare in quic module. Cleanup small errors.
|
Fix key compare in quic module.
Cleanup small errors.
|
Lua
|
mit
|
emmericp/FlowScope
|
61254d035643de23013b8995a7385ac79a673cbd
|
MCServer/Plugins/APIDump/Hooks/OnPluginsLoaded.lua
|
MCServer/Plugins/APIDump/Hooks/OnPluginsLoaded.lua
|
return
{
HOOK_PLUGINS_LOADED =
{
CalledWhen = "All the enabled plugins have been loaded",
DefaultFnName = "OnPluginsLoaded", -- also used as pagename
Desc = [[
This callback gets called when the server finishes loading and initializing plugins. This is the
perfect occasion for a plugin to query other plugins and possibly start communicating with them using
the {{cPluginManager}}:Call() function.
]],
Params = {},
Returns = [[
The return value is ignored, all registered callbacks are called.
]],
CodeExamples =
{
{
Title = "CoreMessaging",
Desc = [[
This example shows how to implement the CoreMessaging functionality - messages to players will be
sent through the Core plugin, formatted by that plugin. As a fallback for when the Core plugin is
not present, the messages are sent directly by this code, unformatted.
]],
Code = [[
-- These are the fallback functions used when the Core is not present:
local function SendMessageFallback(a_Player, a_Message)
a_Player:SendMessage(a_Message);
end
local function SendMessageSuccessFallback(a_Player, a_Message)
a_Player:SendMessage(a_Message);
end
local function SendMessageFailureFallback(a_Player, a_Message)
a_Player:SendMessage(a_Message);
end
-- These three "variables" will hold the actual functions to call.
-- By default they are initialized to the Fallback variants, but will be redirected to Core when all plugins load
SendMessage = SendMessageFallback;
SendMessageSuccess = SendMessageSuccessFallback;
SendMessageFailure = SendMessageFailureFallback;
-- The callback tries to connect to the Core, if successful, overwrites the three functions with Core ones
local function OnPluginsLoaded()
local CorePlugin = cPluginManager:Get():GetPlugin("Core");
if (CorePlugin == nil) then
-- The Core is not loaded, keep the Fallback functions
return;
end
-- Overwrite the three functions with Core functionality:
SendMessage = function(a_Player, a_Message)
CorePlugin:Call("SendMessage", a_Player, a_Message);
end
SendMessageSuccess = function(a_Player, a_Message)
CorePlugin:Call("SendMessageSuccess", a_Player, a_Message);
end
SendMessageFailure = function(a_Player, a_Message)
CorePlugin:Call("SendMessageFailure", a_Player, a_Message);
end
end
-- Global scope, register the callback:
cPluginManager.AddHook(cPluginManager.HOOK_PLUGINS_LOADED, CoreMessagingPluginsLoaded);
-- Usage, anywhere else in the plugin:
SendMessageFailure(a_Player, "Cannot teleport to player, the destination player " .. PlayerName .. " was not found");
]],
},
} , -- CodeExamples
}, -- HOOK_PLUGINS_LOADED
}
|
return
{
HOOK_PLUGINS_LOADED =
{
CalledWhen = "All the enabled plugins have been loaded",
DefaultFnName = "OnPluginsLoaded", -- also used as pagename
Desc = [[
This callback gets called when the server finishes loading and initializing plugins. This is the
perfect occasion for a plugin to query other plugins through {{cPluginManager}}:GetPlugin() and
possibly start communicating with them using the {{cPlugin}}:Call() function.
]],
Params = {},
Returns = [[
The return value is ignored, all registered callbacks are called.
]],
CodeExamples =
{
{
Title = "CoreMessaging",
Desc = [[
This example shows how to implement the CoreMessaging functionality - messages to players will be
sent through the Core plugin, formatted by that plugin. As a fallback for when the Core plugin is
not present, the messages are sent directly by this code, unformatted.
]],
Code = [[
-- These are the fallback functions used when the Core is not present:
local function SendMessageFallback(a_Player, a_Message)
a_Player:SendMessage(a_Message);
end
local function SendMessageSuccessFallback(a_Player, a_Message)
a_Player:SendMessage(a_Message);
end
local function SendMessageFailureFallback(a_Player, a_Message)
a_Player:SendMessage(a_Message);
end
-- These three "variables" will hold the actual functions to call.
-- By default they are initialized to the Fallback variants, but will be redirected to Core when all plugins load
SendMessage = SendMessageFallback;
SendMessageSuccess = SendMessageSuccessFallback;
SendMessageFailure = SendMessageFailureFallback;
-- The callback tries to connect to the Core, if successful, overwrites the three functions with Core ones
local function OnPluginsLoaded()
local CorePlugin = cPluginManager:Get():GetPlugin("Core");
if (CorePlugin == nil) then
-- The Core is not loaded, keep the Fallback functions
return;
end
-- Overwrite the three functions with Core functionality:
SendMessage = function(a_Player, a_Message)
CorePlugin:Call("SendMessage", a_Player, a_Message);
end
SendMessageSuccess = function(a_Player, a_Message)
CorePlugin:Call("SendMessageSuccess", a_Player, a_Message);
end
SendMessageFailure = function(a_Player, a_Message)
CorePlugin:Call("SendMessageFailure", a_Player, a_Message);
end
end
-- Global scope, register the callback:
cPluginManager.AddHook(cPluginManager.HOOK_PLUGINS_LOADED, CoreMessagingPluginsLoaded);
-- Usage, anywhere else in the plugin:
SendMessageFailure(a_Player, "Cannot teleport to player, the destination player " .. PlayerName .. " was not found");
]],
},
} , -- CodeExamples
}, -- HOOK_PLUGINS_LOADED
}
|
APIDump: Fixed a factual error in OnPluginsLoaded description.
|
APIDump: Fixed a factual error in OnPluginsLoaded description.
|
Lua
|
apache-2.0
|
Tri125/MCServer,Frownigami1/cuberite,Haxi52/cuberite,thetaeo/cuberite,bendl/cuberite,marvinkopf/cuberite,nichwall/cuberite,guijun/MCServer,guijun/MCServer,nicodinh/cuberite,electromatter/cuberite,QUSpilPrgm/cuberite,Schwertspize/cuberite,kevinr/cuberite,kevinr/cuberite,kevinr/cuberite,linnemannr/MCServer,nicodinh/cuberite,nounoursheureux/MCServer,birkett/MCServer,Haxi52/cuberite,electromatter/cuberite,bendl/cuberite,ionux/MCServer,nicodinh/cuberite,Fighter19/cuberite,MuhammadWang/MCServer,birkett/MCServer,Altenius/cuberite,birkett/MCServer,nounoursheureux/MCServer,nevercast/cuberite,jammet/MCServer,zackp30/cuberite,birkett/cuberite,mjssw/cuberite,thetaeo/cuberite,QUSpilPrgm/cuberite,tonibm19/cuberite,nichwall/cuberite,HelenaKitty/EbooMC,Tri125/MCServer,mjssw/cuberite,MuhammadWang/MCServer,Schwertspize/cuberite,Tri125/MCServer,MuhammadWang/MCServer,tonibm19/cuberite,mmdk95/cuberite,johnsoch/cuberite,nevercast/cuberite,linnemannr/MCServer,thetaeo/cuberite,kevinr/cuberite,Haxi52/cuberite,Fighter19/cuberite,ionux/MCServer,mc-server/MCServer,Haxi52/cuberite,thetaeo/cuberite,linnemannr/MCServer,nevercast/cuberite,thetaeo/cuberite,Howaner/MCServer,ionux/MCServer,mjssw/cuberite,mc-server/MCServer,HelenaKitty/EbooMC,QUSpilPrgm/cuberite,zackp30/cuberite,Tri125/MCServer,Howaner/MCServer,mmdk95/cuberite,mmdk95/cuberite,Frownigami1/cuberite,nounoursheureux/MCServer,birkett/cuberite,electromatter/cuberite,mc-server/MCServer,Fighter19/cuberite,mc-server/MCServer,johnsoch/cuberite,nevercast/cuberite,nichwall/cuberite,marvinkopf/cuberite,johnsoch/cuberite,jammet/MCServer,Altenius/cuberite,electromatter/cuberite,guijun/MCServer,nichwall/cuberite,birkett/MCServer,nicodinh/cuberite,tonibm19/cuberite,Altenius/cuberite,HelenaKitty/EbooMC,SamOatesPlugins/cuberite,Haxi52/cuberite,HelenaKitty/EbooMC,electromatter/cuberite,mmdk95/cuberite,guijun/MCServer,jammet/MCServer,Howaner/MCServer,birkett/MCServer,mmdk95/cuberite,jammet/MCServer,QUSpilPrgm/cuberite,bendl/cuberite,tonibm19/cuberite,birkett/MCServer,nevercast/cuberite,ionux/MCServer,marvinkopf/cuberite,thetaeo/cuberite,MuhammadWang/MCServer,Schwertspize/cuberite,Fighter19/cuberite,ionux/MCServer,linnemannr/MCServer,Frownigami1/cuberite,johnsoch/cuberite,mjssw/cuberite,birkett/cuberite,tonibm19/cuberite,mjssw/cuberite,SamOatesPlugins/cuberite,birkett/cuberite,nevercast/cuberite,Fighter19/cuberite,Frownigami1/cuberite,Tri125/MCServer,nounoursheureux/MCServer,marvinkopf/cuberite,SamOatesPlugins/cuberite,Howaner/MCServer,QUSpilPrgm/cuberite,zackp30/cuberite,QUSpilPrgm/cuberite,mc-server/MCServer,mc-server/MCServer,jammet/MCServer,Schwertspize/cuberite,zackp30/cuberite,nichwall/cuberite,zackp30/cuberite,mmdk95/cuberite,kevinr/cuberite,Howaner/MCServer,linnemannr/MCServer,nounoursheureux/MCServer,HelenaKitty/EbooMC,ionux/MCServer,marvinkopf/cuberite,Howaner/MCServer,jammet/MCServer,nichwall/cuberite,marvinkopf/cuberite,electromatter/cuberite,SamOatesPlugins/cuberite,Tri125/MCServer,MuhammadWang/MCServer,nicodinh/cuberite,kevinr/cuberite,nounoursheureux/MCServer,zackp30/cuberite,birkett/cuberite,mjssw/cuberite,Altenius/cuberite,nicodinh/cuberite,birkett/cuberite,guijun/MCServer,Haxi52/cuberite,Altenius/cuberite,guijun/MCServer,Frownigami1/cuberite,Fighter19/cuberite,johnsoch/cuberite,Schwertspize/cuberite,SamOatesPlugins/cuberite,linnemannr/MCServer,bendl/cuberite,tonibm19/cuberite,bendl/cuberite
|
eb71045c38360caa713bba9b6cc8f1db66944de6
|
tests/base/test_aliasing.lua
|
tests/base/test_aliasing.lua
|
--
-- tests/base/test_aliasing.lua
-- Verify handling of function aliases.
-- Copyright (c) 2015 Jason Perkins and the Premake project
--
local suite = test.declare("premake_alias")
local p = premake
function suite.setup()
suite.testfunc = function()
return 48
end
suite.aliased = nil
suite.aliased2 = nil
end
function suite.returnsOriginalFunction_onNoAlias()
local scope, f = p.resolveAlias(suite, "testfunc")
test.isequal("testfunc", f)
end
function suite.pointsAliasToOriginalFunction()
p.alias(suite, "testfunc", "aliased")
test.isequal(48, suite.aliased())
end
function suite.returnsOriginalFunction_onAlias()
p.alias(suite, "testfunc", "aliased")
local scope, f = p.resolveAlias(suite, "aliased")
test.isequal("testfunc", f)
end
function suite.returnsOriginalFunction_onChainedAliases()
p.alias(suite, "testfunc", "aliased")
p.alias(suite, "aliased", "aliased2")
local scope, f = p.resolveAlias(suite, "aliased2")
test.isequal("testfunc", f)
end
function suite.overrideResolvesAliases()
p.alias(suite, "testfunc", "aliased")
p.override(suite, "aliased", function(base)
return base() + 1
end)
test.isequal(49, suite.testfunc())
end
function suite.aliasTracksOverrides()
p.alias(suite, "testfunc", "aliased")
p.override(suite, "testfunc", function(base)
return base() + 1
end)
test.isequal(49, suite.aliased())
end
|
--
-- tests/base/test_aliasing.lua
-- Verify handling of function aliases.
-- Copyright (c) 2015 Jason Perkins and the Premake project
--
local suite = test.declare("premake_alias")
local m = {}
local p = premake
function suite.setup()
m.testfunc = function()
return 48
end
m.aliased = nil
m.aliased2 = nil
end
function suite.returnsOriginalFunction_onNoAlias()
local scope, f = p.resolveAlias(m, "testfunc")
test.isequal("testfunc", f)
end
function suite.pointsAliasToOriginalFunction()
p.alias(m, "testfunc", "aliased")
test.isequal(48, m.aliased())
end
function suite.returnsOriginalFunction_onAlias()
p.alias(m, "testfunc", "aliased")
local scope, f = p.resolveAlias(m, "aliased")
test.isequal("testfunc", f)
end
function suite.returnsOriginalFunction_onChainedAliases()
p.alias(m, "testfunc", "aliased")
p.alias(m, "aliased", "aliased2")
local scope, f = p.resolveAlias(m, "aliased2")
test.isequal("testfunc", f)
end
function suite.overrideResolvesAliases()
p.alias(m, "testfunc", "aliased")
p.override(m, "aliased", function(base)
return base() + 1
end)
test.isequal(49, m.testfunc())
end
function suite.aliasTracksOverrides()
p.alias(m, "testfunc", "aliased")
p.override(m, "testfunc", function(base)
return base() + 1
end)
test.isequal(49, m.aliased())
end
|
Fixed bug with alias tests that caused one to three extra tests to be run
|
Fixed bug with alias tests that caused one to three extra tests to be run
|
Lua
|
bsd-3-clause
|
mandersan/premake-core,soundsrc/premake-core,noresources/premake-core,premake/premake-core,soundsrc/premake-core,sleepingwit/premake-core,dcourtois/premake-core,LORgames/premake-core,LORgames/premake-core,TurkeyMan/premake-core,mandersan/premake-core,Zefiros-Software/premake-core,tvandijck/premake-core,premake/premake-core,mandersan/premake-core,sleepingwit/premake-core,TurkeyMan/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,premake/premake-core,premake/premake-core,starkos/premake-core,LORgames/premake-core,noresources/premake-core,Zefiros-Software/premake-core,TurkeyMan/premake-core,noresources/premake-core,soundsrc/premake-core,sleepingwit/premake-core,Zefiros-Software/premake-core,tvandijck/premake-core,sleepingwit/premake-core,soundsrc/premake-core,noresources/premake-core,Zefiros-Software/premake-core,starkos/premake-core,tvandijck/premake-core,dcourtois/premake-core,tvandijck/premake-core,starkos/premake-core,LORgames/premake-core,starkos/premake-core,dcourtois/premake-core,soundsrc/premake-core,premake/premake-core,mandersan/premake-core,starkos/premake-core,dcourtois/premake-core,premake/premake-core,noresources/premake-core,TurkeyMan/premake-core,TurkeyMan/premake-core,premake/premake-core,starkos/premake-core,sleepingwit/premake-core,mandersan/premake-core,dcourtois/premake-core,noresources/premake-core,tvandijck/premake-core,dcourtois/premake-core,LORgames/premake-core,noresources/premake-core,starkos/premake-core
|
22e41ee2fe7266218b1619a782d43034e0355be0
|
otouto/plugins/blacklist.lua
|
otouto/plugins/blacklist.lua
|
-- This plugin will allow the admin to blacklist users who will be unable to
-- use the bot. This plugin should be at the top of your plugin list in config.
local blacklist = {}
local utilities = require('otouto.utilities')
local bindings = require('otouto.bindings')
function blacklist:init()
if not self.database.blacklist then
self.database.blacklist = {}
end
end
blacklist.triggers = {
''
}
blacklist.error = false
function blacklist:action(msg, config)
if self.database.blacklist[tostring(msg.from.id)] then
return
elseif self.database.blacklist[tostring(msg.chat.id)] then
bindings.leaveChat(self, { chat_id = msg.chat.id })
return
end
if not (
msg.from.id == config.admin
and (
msg.text:match('^'..config.cmd_pat..'blacklist')
or msg.text:match('^'..config.cmd_pat..'unblacklist')
)
) then
return true
end
local targets = {}
if msg.reply_to_message then
table.insert(targets, {
id_str = tostring(msg.reply_to_message.from.id),
name = utilities.build_name(msg.reply_to_message.from.first_name, msg.reply_to_message.from.last_name)
})
else
local input = utilities.input(msg.text)
if input then
for _, user in ipairs(utilities.index(input)) do
if self.database.users[user] then
table.insert(targets, {
id = self.database.users[user].id,
id_str = tostring(self.database.users[user].id),
name = utilities.build_name(self.database.users[user].first_name, self.database.users[user].last_name)
})
elseif tonumber(user) then
local t = {
id_str = user,
id = tonumber(user)
}
if tonumber(user) < 0 then
t.name = 'Group (' .. user .. ')'
else
t.name = 'Unknown (' .. user .. ')'
end
table.insert(targets, t)
elseif user:match('^@') then
local u = utilities.resolve_username(self, user)
if u then
table.insert(targets, {
id = u.id,
id_str = tostring(u.id),
name = utilities.build_name(u.first_name, u.last_name)
})
else
table.insert(targets, { err = 'Sorry, I do not recognize that username ('..user..').' })
end
else
table.insert(targets, { err = 'Invalid username or ID ('..user..').' })
end
end
else
utilities.send_reply(self, msg, 'Please specify a user or users via reply, username, or ID, or a group or groups via ID.')
return
end
end
local output = ''
if msg.text:match('^'..config.cmd_pat..'blacklist') then
for _, target in ipairs(targets) do
if target.err then
output = output .. target.err .. '\n'
elseif self.database.blacklist[target.id_str] then
output = output .. target.name .. ' is already blacklisted.\n'
else
self.database.blacklist[target.id_str] = true
output = output .. target.name .. ' is now blacklisted.\n'
if config.drua_block_on_blacklist and target.id > 0 then
require('drua-tg').block(target.id)
end
end
end
elseif msg.text:match('^'..config.cmd_pat..'unblacklist') then
for _, target in ipairs(targets) do
if target.err then
output = output .. target.err .. '\n'
elseif not self.database.blacklist[target.id_str] then
output = output .. target.name .. ' is not blacklisted.\n'
else
self.database.blacklist[target.id_str] = nil
output = output .. target.name .. ' is no longer blacklisted.\n'
if config.drua_block_on_blacklist and target.id > 0 then
require('drua-tg').unblock(target.id)
end
end
end
end
utilities.send_reply(self, msg, output)
end
return blacklist
|
-- This plugin will allow the admin to blacklist users who will be unable to
-- use the bot. This plugin should be at the top of your plugin list in config.
local blacklist = {}
local utilities = require('otouto.utilities')
local bindings = require('otouto.bindings')
function blacklist:init()
if not self.database.blacklist then
self.database.blacklist = {}
end
end
blacklist.triggers = {
''
}
blacklist.error = false
function blacklist:action(msg, config)
if self.database.blacklist[tostring(msg.from.id)] then
return
elseif self.database.blacklist[tostring(msg.chat.id)] then
bindings.leaveChat(self, { chat_id = msg.chat.id })
return
end
if not (
msg.from.id == config.admin
and (
msg.text:match('^'..config.cmd_pat..'blacklist')
or msg.text:match('^'..config.cmd_pat..'unblacklist')
)
) then
return true
end
local targets = {}
if msg.reply_to_message then
table.insert(targets, {
id = msg.reply_to_message.from.id,
id_str = tostring(msg.reply_to_message.from.id),
name = utilities.build_name(msg.reply_to_message.from.first_name, msg.reply_to_message.from.last_name)
})
else
local input = utilities.input(msg.text)
if input then
for _, user in ipairs(utilities.index(input)) do
if self.database.users[user] then
table.insert(targets, {
id = self.database.users[user].id,
id_str = tostring(self.database.users[user].id),
name = utilities.build_name(self.database.users[user].first_name, self.database.users[user].last_name)
})
elseif tonumber(user) then
local t = {
id_str = user,
id = tonumber(user)
}
if tonumber(user) < 0 then
t.name = 'Group (' .. user .. ')'
else
t.name = 'Unknown (' .. user .. ')'
end
table.insert(targets, t)
elseif user:match('^@') then
local u = utilities.resolve_username(self, user)
if u then
table.insert(targets, {
id = u.id,
id_str = tostring(u.id),
name = utilities.build_name(u.first_name, u.last_name)
})
else
table.insert(targets, { err = 'Sorry, I do not recognize that username ('..user..').' })
end
else
table.insert(targets, { err = 'Invalid username or ID ('..user..').' })
end
end
else
utilities.send_reply(self, msg, 'Please specify a user or users via reply, username, or ID, or a group or groups via ID.')
return
end
end
local output = ''
if msg.text:match('^'..config.cmd_pat..'blacklist') then
for _, target in ipairs(targets) do
if target.err then
output = output .. target.err .. '\n'
elseif self.database.blacklist[target.id_str] then
output = output .. target.name .. ' is already blacklisted.\n'
else
self.database.blacklist[target.id_str] = true
output = output .. target.name .. ' is now blacklisted.\n'
if config.drua_block_on_blacklist and target.id > 0 then
require('drua-tg').block(target.id)
end
end
end
elseif msg.text:match('^'..config.cmd_pat..'unblacklist') then
for _, target in ipairs(targets) do
if target.err then
output = output .. target.err .. '\n'
elseif not self.database.blacklist[target.id_str] then
output = output .. target.name .. ' is not blacklisted.\n'
else
self.database.blacklist[target.id_str] = nil
output = output .. target.name .. ' is no longer blacklisted.\n'
if config.drua_block_on_blacklist and target.id > 0 then
require('drua-tg').unblock(target.id)
end
end
end
end
utilities.send_reply(self, msg, output)
end
return blacklist
|
blacklist.lua bugfix
|
blacklist.lua bugfix
|
Lua
|
agpl-3.0
|
topkecleon/otouto,barreeeiroo/BarrePolice,bb010g/otouto,Brawl345/Brawlbot-v2
|
380ddd079a3616332dd0c1ff4876f465156d37ce
|
access.lua
|
access.lua
|
-- import requirements
-- allow either ccjsonjson, or th-LuaJSON
local has_cjson, jsonmod = pcall(require, "cjson")
if not has_cjson then
jsonmod = require "json"
end
-- Ubuntu broke the install. Puts the source in /usr/share/lua/5.1/https.lua,
-- but since the source defines itself as the module "ssl.https", after we
-- load the source, we need to grab the actual thing.
pcall(require,"https")
local https = require "ssl.https" -- /usr/share/lua/5.1/https.lua
local ltn12 = require("ltn12")
local uri = ngx.var.uri
local uri_args = ngx.req.get_uri_args()
local scheme = ngx.var.scheme
local server_name = ngx.var.server_name
-- setup some app-level vars
local client_id = ngx.var.ngo_client_id
local client_secret = ngx.var.ngo_client_secret
local domain = ngx.var.ngo_domain
local cb_scheme = ngx.var.ngo_callback_scheme or scheme
local cb_server_name = ngx.var.ngo_callback_host or server_name
local cb_uri = ngx.var.ngo_callback_uri or "/_oauth"
local cb_url = cb_scheme.."://"..cb_server_name..cb_uri
local redir_url = cb_scheme.."://"..cb_server_name..uri
local signout_uri = ngx.var.ngo_signout_uri or "/_signout"
local debug = ngx.var.ngo_debug
local whitelist = ngx.var.ngo_whitelist
local blacklist = ngx.var.ngo_blacklist
local secure_cookies = ngx.var.ngo_secure_cookies
local token_secret = ngx.var.ngo_token_secret or "UNSET"
-- Force the user to set a token secret
if token_secret == "UNSET" then
ngx.log(ngx.ERR, "$ngo_token_secret must be set in Nginx config!")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
-- See https://developers.google.com/accounts/docs/OAuth2WebServer
if uri == signout_uri then
ngx.header["Set-Cookie"] = "AccessToken=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"
return ngx.redirect(cb_scheme.."://"..server_name)
end
-- Enforce token security and expiration
local oauth_expires = tonumber(ngx.var.cookie_OauthExpires) or 0
local oauth_email = ngx.unescape_uri(ngx.var.cookie_OauthEmail or "")
local oauth_access_token = ngx.unescape_uri(ngx.var.cookie_OauthAccessToken or "")
local expected_token = ngx.encode_base64(ngx.hmac_sha1(token_secret, cb_server_name .. oauth_email .. oauth_expires))
if oauth_access_token == expected_token and oauth_expires and oauth_expires > ngx.time() then
return
else
-- If no access token and this isn't the callback URI, redirect to oauth
if uri ~= cb_uri then
-- Redirect to the /oauth endpoint, request access to ALL scopes
return ngx.redirect("https://accounts.google.com/o/oauth2/auth?client_id="..client_id.."&scope=email&response_type=code&redirect_uri="..ngx.escape_uri(cb_url).."&state="..ngx.escape_uri(redir_url).."&login_hint="..ngx.escape_uri(domain))
end
-- Fetch teh authorization code from the parameters
local auth_code = uri_args["code"]
local auth_error = uri_args["error"]
if auth_error then
ngx.log(ngx.ERR, "received "..auth_error.." from https://accounts.google.com/o/oauth2/auth")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
if debug then
ngx.log(ngx.ERR, "DEBUG: fetching token for auth code "..auth_code)
end
-- TODO: Switch to NBIO sockets
-- If I get around to working luasec, this says how to pass a function which
-- can generate a socket, needed for NBIO using nginx cosocket
-- http://lua-users.org/lists/lua-l/2009-02/msg00251.html
local res, code, headers, status = https.request(
"https://accounts.google.com/o/oauth2/token",
"code="..ngx.escape_uri(auth_code).."&client_id="..client_id.."&client_secret="..client_secret.."&redirect_uri="..ngx.escape_uri(cb_url).."&grant_type=authorization_code"
)
if debug then
ngx.log(ngx.ERR, "DEBUG: token response "..res..code..status)
end
if code~=200 then
ngx.log(ngx.ERR, "received "..code.." from https://accounts.google.com/o/oauth2/token")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
-- use version 1 cookies so we don't have to encode. MSIE-old beware
local json = jsonmod.decode( res )
local access_token = json["access_token"]
local expires = ngx.time() + json["expires_in"]
local cookie_tail = ";version=1;path=/;Max-Age="..json["expires_in"]
if secure_cookies then
cookie_tail = cookie_tail..";secure"
end
local send_headers = {
Authorization = "Bearer "..access_token,
}
local result_table = {}
local res2, code2, headers2, status2 = https.request({
url = "https://www.googleapis.com/oauth2/v2/userinfo",
method = "GET",
headers = send_headers,
sink = ltn12.sink.table(result_table),
})
if code2~=200 then
ngx.log(ngx.ERR, "received "..code2.." from https://www.googleapis.com/oauth2/v2/userinfo")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
if debug then
ngx.log(ngx.ERR, "DEBUG: userinfo response "..res2..code2..status2..table.concat(result_table))
end
json = jsonmod.decode( table.concat(result_table) )
local name = json["name"]
local email = json["email"]
local picture = json["picture"]
local token = ngx.encode_base64(ngx.hmac_sha1(token_secret, cb_server_name .. email .. expires))
-- If no whitelist or blacklist, match on domain
if not whitelist and not blacklist and domain then
if not string.find(email, "@"..domain) then
if debug then
ngx.log(ngx.ERR, "DEBUG: "..email.." not in "..domain)
end
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
end
if whitelist then
if not string.find(whitelist, email) then
if debug then
ngx.log(ngx.ERR, "DEBUG: "..email.." not in whitelist")
end
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
end
if blacklist then
if string.find(blacklist, email) then
if debug then
ngx.log(ngx.ERR, "DEBUG: "..email.." in blacklist")
end
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
end
ngx.header["Set-Cookie"] = {
"OauthAccessToken="..ngx.escape_uri(token)..cookie_tail,
"OauthExpires="..expires..cookie_tail,
"OauthName="..ngx.escape_uri(name)..cookie_tail,
"OauthEmail="..ngx.escape_uri(email)..cookie_tail,
"OauthPicture="..ngx.escape_uri(picture)..cookie_tail
}
-- Redirect
if debug then
ngx.log(ngx.ERR, "DEBUG: authorized "..json["email"]..", redirecting to "..uri_args["state"])
end
return ngx.redirect(uri_args["state"])
end
|
-- import requirements
-- allow either ccjsonjson, or th-LuaJSON
local has_cjson, jsonmod = pcall(require, "cjson")
if not has_cjson then
jsonmod = require "json"
end
-- Ubuntu broke the install. Puts the source in /usr/share/lua/5.1/https.lua,
-- but since the source defines itself as the module "ssl.https", after we
-- load the source, we need to grab the actual thing.
pcall(require,"https")
local https = require "ssl.https" -- /usr/share/lua/5.1/https.lua
local ltn12 = require("ltn12")
local uri = ngx.var.uri
local uri_args = ngx.req.get_uri_args()
local scheme = ngx.var.scheme
local server_name = ngx.var.server_name
-- setup some app-level vars
local client_id = ngx.var.ngo_client_id
local client_secret = ngx.var.ngo_client_secret
local domain = ngx.var.ngo_domain
local cb_scheme = ngx.var.ngo_callback_scheme or scheme
local cb_server_name = ngx.var.ngo_callback_host or server_name
local cb_uri = ngx.var.ngo_callback_uri or "/_oauth"
local cb_url = cb_scheme.."://"..cb_server_name..cb_uri
local redir_url = cb_scheme.."://"..cb_server_name..uri
local signout_uri = ngx.var.ngo_signout_uri or "/_signout"
local debug = ngx.var.ngo_debug
local whitelist = ngx.var.ngo_whitelist
local blacklist = ngx.var.ngo_blacklist
local secure_cookies = ngx.var.ngo_secure_cookies
local token_secret = ngx.var.ngo_token_secret or "UNSET"
-- Force the user to set a token secret
if token_secret == "UNSET" then
ngx.log(ngx.ERR, "$ngo_token_secret must be set in Nginx config!")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
-- See https://developers.google.com/accounts/docs/OAuth2WebServer
if uri == signout_uri then
ngx.header["Set-Cookie"] = "AccessToken=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"
return ngx.redirect(cb_scheme.."://"..server_name)
end
-- Enforce token security and expiration
local oauth_expires = tonumber(ngx.var.cookie_OauthExpires) or 0
local oauth_email = ngx.unescape_uri(ngx.var.cookie_OauthEmail or "")
local oauth_access_token = ngx.unescape_uri(ngx.var.cookie_OauthAccessToken or "")
local expected_token = ngx.encode_base64(ngx.hmac_sha1(token_secret, cb_server_name .. oauth_email .. oauth_expires))
if oauth_access_token == expected_token and oauth_expires and oauth_expires > ngx.time() then
return
else
-- If no access token and this isn't the callback URI, redirect to oauth
if uri ~= cb_uri then
-- Redirect to the /oauth endpoint, request access to ALL scopes
return ngx.redirect("https://accounts.google.com/o/oauth2/auth?client_id="..client_id.."&scope=email&response_type=code&redirect_uri="..ngx.escape_uri(cb_url).."&state="..ngx.escape_uri(redir_url).."&login_hint="..ngx.escape_uri(domain))
end
-- Fetch teh authorization code from the parameters
local auth_code = uri_args["code"]
local auth_error = uri_args["error"]
if auth_error then
ngx.log(ngx.ERR, "received "..auth_error.." from https://accounts.google.com/o/oauth2/auth")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
if debug then
ngx.log(ngx.ERR, "DEBUG: fetching token for auth code "..auth_code)
end
-- TODO: Switch to NBIO sockets
-- If I get around to working luasec, this says how to pass a function which
-- can generate a socket, needed for NBIO using nginx cosocket
-- http://lua-users.org/lists/lua-l/2009-02/msg00251.html
local res, code, headers, status = https.request(
"https://accounts.google.com/o/oauth2/token",
"code="..ngx.escape_uri(auth_code).."&client_id="..client_id.."&client_secret="..client_secret.."&redirect_uri="..ngx.escape_uri(cb_url).."&grant_type=authorization_code"
)
if debug then
ngx.log(ngx.ERR, "DEBUG: token response "..res..code..status)
end
if code~=200 then
ngx.log(ngx.ERR, "received "..code.." from https://accounts.google.com/o/oauth2/token")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
-- use version 1 cookies so we don't have to encode. MSIE-old beware
local json = jsonmod.decode( res )
local access_token = json["access_token"]
local expires = ngx.time() + json["expires_in"]
local cookie_tail = ";version=1;path=/;Max-Age="..json["expires_in"]
if secure_cookies then
cookie_tail = cookie_tail..";secure"
end
local send_headers = {
Authorization = "Bearer "..access_token,
}
local result_table = {}
local res2, code2, headers2, status2 = https.request({
url = "https://www.googleapis.com/oauth2/v2/userinfo",
method = "GET",
headers = send_headers,
sink = ltn12.sink.table(result_table),
})
if code2~=200 then
ngx.log(ngx.ERR, "received "..code2.." from https://www.googleapis.com/oauth2/v2/userinfo")
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
if debug then
ngx.log(ngx.ERR, "DEBUG: userinfo response "..res2..code2..status2..table.concat(result_table))
end
json = jsonmod.decode( table.concat(result_table) )
local name = json["name"]
local email = json["email"]
local picture = json["picture"]
local token = ngx.encode_base64(ngx.hmac_sha1(token_secret, cb_server_name .. email .. expires))
-- If no whitelist or blacklist, match on domain
if not whitelist and not blacklist and domain then
if not string.find(email, "@"..domain) then
if debug then
ngx.log(ngx.ERR, "DEBUG: "..email.." not in "..domain)
end
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
end
if whitelist then
if not string.find(" " .. whitelist .. " ", " " .. email .. " ") then
if debug then
ngx.log(ngx.ERR, "DEBUG: "..email.." not in whitelist")
end
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
end
if blacklist then
if string.find(" " .. blacklist .. " ", " " .. email .. " ") then
if debug then
ngx.log(ngx.ERR, "DEBUG: "..email.." in blacklist")
end
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
end
ngx.header["Set-Cookie"] = {
"OauthAccessToken="..ngx.escape_uri(token)..cookie_tail,
"OauthExpires="..expires..cookie_tail,
"OauthName="..ngx.escape_uri(name)..cookie_tail,
"OauthEmail="..ngx.escape_uri(email)..cookie_tail,
"OauthPicture="..ngx.escape_uri(picture)..cookie_tail
}
-- Redirect
if debug then
ngx.log(ngx.ERR, "DEBUG: authorized "..json["email"]..", redirecting to "..uri_args["state"])
end
return ngx.redirect(uri_args["state"])
end
|
Fixed bug where substring match could lead to accidentally triggering whitelist or blacklist (i.e. whitelist for "c@a.org" matches "abc@a.org")
|
Fixed bug where substring match could lead to accidentally triggering whitelist or blacklist (i.e. whitelist for "c@a.org" matches "abc@a.org")
|
Lua
|
mit
|
milliwayslabs/nginx-google-oauth,milliwayslabs/nginx-google-oauth,agoragames/nginx-google-oauth,agoragames/nginx-google-oauth,ivan1986/nginx-google-oauth,ivan1986/nginx-google-oauth
|
70f2e099be4c11754bd358c3657794279f7c65e0
|
nvim/lua/treesitter_config.lua
|
nvim/lua/treesitter_config.lua
|
local max_lines = 1000
require('nvim-treesitter.configs').setup {
-- One of "all", "maintained" (parsers with maintainers), or a list of languages
ensure_installed = "maintained",
sync_install = false,
ignore_install = {},
highlight = {
enable = true,
disable = function(lang, bufnr)
return vim.api.nvim_buf_line_count(bufnr) > max_lines
end,
-- Setting this to true will run `:h syntax` and tree-sitter at the same time.
-- Set this to `true` if you depend on 'syntax' being enabled (like for indentation).
-- Using this option may slow down your editor, and you may see some duplicate highlights.
-- Instead of true it can also be a list of languages
additional_vim_regex_highlighting = false,
},
indent = {
enable = true,
disable = function(lang, bufnr)
return vim.api.nvim_buf_line_count(bufnr) > max_lines or lang ~= "prisma"
end,
},
incremental_selection = {
enable = true,
disable = function(lang, bufnr)
return vim.api.nvim_buf_line_count(bufnr) > max_lines
end,
keymaps = {
init_selection = "gnn",
node_incremental = "grn",
scope_incremental = "grc",
node_decremental = "grm",
},
},
playground = {
enable = false,
disable = {},
updatetime = 25, -- Debounced time for highlighting nodes in the playground from source code
persist_queries = false, -- Whether the query persists across vim sessions
keybindings = {
toggle_query_editor = 'o',
toggle_hl_groups = 'i',
toggle_injected_languages = 't',
toggle_anonymous_nodes = 'a',
toggle_language_display = 'I',
focus_language = 'f',
unfocus_language = 'F',
update = 'R',
goto_node = '<cr>',
show_help = '?',
},
},
}
|
local max_lines = 1000
require('nvim-treesitter.configs').setup {
-- One of "all", "maintained" (parsers with maintainers), or a list of languages
ensure_installed = {
'bash',
'c', 'cpp', 'rust',
'javascript', 'typescript',
'json', 'toml',
'vim', 'lua',
},
sync_install = false,
ignore_install = {},
highlight = {
enable = true,
disable = function(lang, bufnr)
return vim.api.nvim_buf_line_count(bufnr) > max_lines
end,
-- Setting this to true will run `:h syntax` and tree-sitter at the same time.
-- Set this to `true` if you depend on 'syntax' being enabled (like for indentation).
-- Using this option may slow down your editor, and you may see some duplicate highlights.
-- Instead of true it can also be a list of languages
additional_vim_regex_highlighting = false,
},
indent = {
enable = true,
disable = function(lang, bufnr)
return vim.api.nvim_buf_line_count(bufnr) > max_lines or lang ~= "prisma"
end,
},
incremental_selection = {
enable = true,
disable = function(lang, bufnr)
return vim.api.nvim_buf_line_count(bufnr) > max_lines
end,
keymaps = {
init_selection = "gnn",
node_incremental = "grn",
scope_incremental = "grc",
node_decremental = "grm",
},
},
playground = {
enable = false,
disable = {},
updatetime = 25, -- Debounced time for highlighting nodes in the playground from source code
persist_queries = false, -- Whether the query persists across vim sessions
keybindings = {
toggle_query_editor = 'o',
toggle_hl_groups = 'i',
toggle_injected_languages = 't',
toggle_anonymous_nodes = 'a',
toggle_language_display = 'I',
focus_language = 'f',
unfocus_language = 'F',
update = 'R',
goto_node = '<cr>',
show_help = '?',
},
},
}
|
nvim: fix treesitter config after upstream changes
|
nvim: fix treesitter config after upstream changes
|
Lua
|
unlicense
|
aqrln/dotfiles,aqrln/dotfiles
|
6160010cbc434e02ab3b8f2c414afd96a5fb2c30
|
SpatialLPPooling.lua
|
SpatialLPPooling.lua
|
local SpatialLPPooling, parent = torch.class('nn.SpatialLPPooling', 'nn.Sequential')
function SpatialLPPooling:__init(nInputPlane, pnorm, kW, kH, dW, dH)
parent.__init(self)
dW = dW or kW
dH = dH or kH
self.kW = kW
self.kH = kH
self.dW = dW
self.dH = dH
self.nInputPlane = nInputPlane
self.learnKernel = learnKernel
if pnorm == 2 then
self:add(nn.Square())
else
self:add(nn.Power(pnorm))
end
self:add(nn.SpatialConvolutionMap(nn.tables.oneToOne(nInputPlane), kW, kH, dW, dH))
if pnorm == 2 then
self:add(nn.Sqrt(1e-7))
else
self:add(nn.Power(1/pnorm))
end
self:get(2).bias:zero()
self:get(2).weight:fill(1/(kW*kH))
end
-- we have to override some stuff to avoid nonsense happening
function SpatialLPPooling:reset()
end
function SpatialLPPooling:accGradParameters()
end
function SpatialLPPooling:accUpdateGradParameters()
end
function SpatialLPPooling:zeroGradParameters()
end
function SpatialLPPooling:updateParameters()
end
|
local SpatialLPPooling, parent = torch.class('nn.SpatialLPPooling', 'nn.Sequential')
function SpatialLPPooling:__init(nInputPlane, pnorm, kW, kH, dW, dH)
parent.__init(self)
dW = dW or kW
dH = dH or kH
self.kW = kW
self.kH = kH
self.dW = dW
self.dH = dH
self.nInputPlane = nInputPlane
if pnorm == 2 then
self:add(nn.Square())
else
self:add(nn.Power(pnorm))
end
self:add(nn.SpatialSubSampling(nInputPlane, kW, kH, dW, dH))
if pnorm == 2 then
self:add(nn.Sqrt())
else
self:add(nn.Power(1/pnorm))
end
self:get(2).bias:zero()
self:get(2).weight:fill(1)
end
-- the module is a Sequential: by default, it'll try to learn the parameters
-- of the sub sampler: we avoid that by redefining its methods.
function SpatialLPPooling:reset()
end
function SpatialLPPooling:accGradParameters()
end
function SpatialLPPooling:accUpdateGradParameters()
end
function SpatialLPPooling:zeroGradParameters()
end
function SpatialLPPooling:updateParameters()
end
|
Fixed some GPU modules ; made SpatialLPPooling compat with CUDA.
|
Fixed some GPU modules ; made SpatialLPPooling compat with CUDA.
|
Lua
|
bsd-3-clause
|
nicholas-leonard/nn,Moodstocks/nn,eriche2016/nn,andreaskoepf/nn,jzbontar/nn,jhjin/nn,witgo/nn,eulerreich/nn,caldweln/nn,boknilev/nn,vgire/nn,bartvm/nn,hery/nn,abeschneider/nn,colesbury/nn,forty-2/nn,elbamos/nn,ivendrov/nn,jonathantompson/nn,douwekiela/nn,ominux/nn,zchengquan/nn,davidBelanger/nn,adamlerer/nn,aaiijmrtt/nn,GregSatre/nn,fmassa/nn,soumith/nn,rotmanmi/nn,apaszke/nn,rickyHong/nn_lib_torch,clementfarabet/nn,hughperkins/nn,EnjoyHacking/nn,PraveerSINGH/nn,kmul00/nn,Djabbz/nn,mys007/nn,szagoruyko/nn,lvdmaaten/nn,joeyhng/nn,sagarwaghmare69/nn,sbodenstein/nn,Aysegul/nn,Jeffyrao/nn,noa/nn,xianjiec/nn,diz-vara/nn,karpathy/nn,LinusU/nn,mlosch/nn,lukasc-ch/nn,zhangxiangxiao/nn,PierrotLC/nn
|
b7fbfcde8441ec712cf8d2e54d0c4c3cffc11073
|
src/db.lua
|
src/db.lua
|
-- Imports / module wrapper
local Pkg = {}
local std = _G
local error = error
local print = print
local type = type
local tostring = tostring
local getmetatable = getmetatable
local setmetatable = setmetatable
local pairs = pairs
local ipairs = ipairs
local string = string
local table = table
local util = require("util")
local Set = require("set").Set
setfenv(1, Pkg)
OUT = "$$OUT"
IN = "$$IN"
STRONG_IN = "$$STRONG_IN"
OPT = "$$OPT"
local sigSymbols = {[OUT] = "f", [IN] = "b", [STRONG_IN] = "B", [OPT] = "?"}
local function fmtSignature(args, signature)
local result = ""
local multi = false
for _, arg in ipairs(args) do
if multi then result = result .. ", " end
result = result .. arg .. ": " .. sigSymbols[signature[arg]]
multi = true
end
return result
end
local Signature = {}
function Signature.__tostring(signature)
local args = {}
for arg in pairs(signature) do
args[#args + 1] = arg
end
return fmtSignature(args, signature)
end
function getSignature(bindings, bound)
local signature = setmetatable({}, Signature)
for _, binding in ipairs(bindings) do
if bound[binding.variable] or binding.constant then
signature[binding.field] = IN
else
signature[binding.field] = OUT
end
end
return signature
end
local Schema = {}
function Schema.__tostring(schema)
local signature = fmtSignature(schema.args, schema.signature)
local rest = schema.rest and (", ...: " .. sigSymbols[schema.rest]) or ""
return string.format("Schema<%s, (%s%s)>", schema.name or "UNNAMED", signature, rest)
end
local function schema(args, name, kind)
local schema = {args = {}, signature = setmetatable({}, Signature), name = name, kind = kind}
setmetatable(schema, Schema)
if args.name then
schema.name = args.name
end
local mode = OUT
for ix, arg in ipairs(args) do
if arg == OUT or arg == IN or arg == STRONG_IN or arg == OPT then
mode = arg
if ix == #args then -- a mode token in the final slot signifies a variadic expression that takes any number of vars matching the given mode
schema.rest = arg
end
else
schema.args[#schema.args + 1] = arg
schema.signature[arg] = mode
end
end
return schema
end
local function rename(name, schema)
local neue = util.shallowCopy(schema)
neue.name = name
return neue
end
local schemas = {
unary = schema{"return", IN, "a"},
unaryBound = schema{IN, "return", "a"},
unaryFilter = schema{IN, "a"},
binary = schema{"return", IN, "a", "b"},
binaryBound = schema{IN, "return", "a", "b"},
binaryFilter = schema{IN, "a", "b"},
moveIn = schema{"a", IN, "b"},
moveOut = schema{"b", IN, "a"}
}
local expressions = {
["+"] = {rename("plus", schemas.binary)},
["-"] = {rename("minus", schemas.binary)},
["*"] = {rename("multiply", schemas.binary)},
["/"] = {rename("divide", schemas.binary)},
["<"] = {rename("less_than", schemas.binary), rename("is_less_than", schemas.binaryFilter)},
["<="] = {rename("less_than_or_equal", schemas.binary), rename("is_less_than_or_equal", schemas.binaryFilter)},
[">"] = {rename("greater_than", schemas.binary), rename("is_greater_than", schemas.binaryFilter)},
[">="] = {rename("greater_than_or_equal", schemas.binary), rename("is_greater_than_or_equal", schemas.binaryFilter)},
["="] = {rename("equal", schemas.binary), rename("is_equal", schemas.binaryFilter), rename("move", schemas.moveIn), rename("move", schemas.moveOut)},
["!="] = {rename("not_equal", schemas.binary), rename("is_not_equal", schemas.binaryFilter)},
concat = {schema({"return", IN}, "concat")},
length = {rename("length", schemas.unary)},
is = {rename("is", schemas.unary)},
abs = {rename("abs", schemas.unary)},
sin = {rename("sin", schemas.unary)},
cos = {rename("cos", schemas.unary)},
tan = {rename("tan", schemas.unary)},
time = {schema({"return", OPT, "seconds", "minutes", "hours"}, "time")},
-- Aggregates
count = {schema({"return"}, "count", "aggregate"), schema({IN, "return"}, "count", "aggregate")},
sum = {schema({"return", STRONG_IN, "a"}, "sum", "aggregate"), schema({IN, "return", STRONG_IN, "a"}, "sum", "aggregate")}
}
function getExpressions()
local exprs = Set:new()
for expr in pairs(expressions) do
exprs:add(expr)
end
return exprs
end
function getSchemas(name)
return expressions[name]
end
function getSchema(name, signature)
if not expressions[name] then error("Unknown expression '" .. name .. "'") end
if not signature then error("Must specify signature to disambiguate expression alternatives") end
local result
for _, schema in ipairs(expressions[name]) do
local match = true
local required = Set:new()
for arg, mode in pairs(schema.signature) do
if mode == OUT or mode == IN or mode == STRONG_IN then
required:add(arg)
end
end
for arg, mode in pairs(signature) do
required:remove(arg)
local schemaMode = schema.signature[arg] or schema.rest
if schemaMode ~= mode and schemaMode ~= OPT and (schemaMode ~= IN and mode ~= STRONG_IN) and (schemaMode ~= STRONG_IN and mode ~= IN) then
match = false
break
end
end
if match and required:length() == 0 then
result = schema
break
end
end
if not result then
local available = {}
for _, schema in ipairs(expressions[name]) do
available[#available + 1] = string.format("%s(%s)", name, fmtSignature(schema.args, schema.signature))
end
error(string.format("No matching signature for expression %s(%s); Available signatures:\n %s", name, signature, table.concat(available, "\n ")))
end
return result
end
function getArgs(schema, bindings)
local map = {}
for _, binding in ipairs(bindings) do
map[binding.field] = binding.variable or binding.constant
end
local args = {}
local fields = {}
for _, arg in ipairs(schema.args) do
if map[arg] then
args[#args + 1] = map[arg]
fields[#fields + 1] = arg
end
end
return args, fields
end
return Pkg
|
-- Imports / module wrapper
local Pkg = {}
local std = _G
local error = error
local print = print
local type = type
local tostring = tostring
local getmetatable = getmetatable
local setmetatable = setmetatable
local pairs = pairs
local ipairs = ipairs
local string = string
local table = table
local util = require("util")
local Set = require("set").Set
setfenv(1, Pkg)
OUT = "$$OUT"
IN = "$$IN"
STRONG_IN = "$$STRONG_IN"
OPT = "$$OPT"
local sigSymbols = {[OUT] = "f", [IN] = "b", [STRONG_IN] = "B", [OPT] = "?"}
local function fmtSignature(args, signature)
local result = ""
local multi = false
for _, arg in ipairs(args) do
if multi then result = result .. ", " end
result = result .. arg .. ": " .. sigSymbols[signature[arg]]
multi = true
end
return result
end
local Signature = {}
function Signature.__tostring(signature)
local args = {}
for arg in pairs(signature) do
args[#args + 1] = arg
end
return fmtSignature(args, signature)
end
function getSignature(bindings, bound)
local signature = setmetatable({}, Signature)
for _, binding in ipairs(bindings) do
if bound[binding.variable] or binding.constant then
signature[binding.field] = IN
else
signature[binding.field] = OUT
end
end
return signature
end
local Schema = {}
function Schema.__tostring(schema)
local signature = fmtSignature(schema.args, schema.signature)
local rest = schema.rest and (", ...: " .. sigSymbols[schema.rest]) or ""
return string.format("Schema<%s, (%s%s)>", schema.name or "UNNAMED", signature, rest)
end
local function schema(args, name, kind)
local schema = {args = {}, signature = setmetatable({}, Signature), name = name, kind = kind}
setmetatable(schema, Schema)
if args.name then
schema.name = args.name
end
local mode = OUT
for ix, arg in ipairs(args) do
if arg == OUT or arg == IN or arg == STRONG_IN or arg == OPT then
mode = arg
if ix == #args then -- a mode token in the final slot signifies a variadic expression that takes any number of vars matching the given mode
schema.rest = arg
end
else
schema.args[#schema.args + 1] = arg
schema.signature[arg] = mode
end
end
return schema
end
local function rename(name, schema)
local neue = util.shallowCopy(schema)
neue.name = name
return neue
end
local schemas = {
unary = schema{"return", IN, "a"},
unaryBound = schema{IN, "return", "a"},
unaryFilter = schema{IN, "a"},
binary = schema{"return", IN, "a", "b"},
binaryBound = schema{IN, "return", "a", "b"},
binaryFilter = schema{IN, "a", "b"},
moveIn = schema{"a", IN, "b"},
moveOut = schema{"b", IN, "a"}
}
local expressions = {
["+"] = {rename("plus", schemas.binary)},
["-"] = {rename("minus", schemas.binary)},
["*"] = {rename("multiply", schemas.binary)},
["/"] = {rename("divide", schemas.binary)},
["<"] = {rename("less_than", schemas.binary), rename("is_less_than", schemas.binaryFilter)},
["<="] = {rename("less_than_or_equal", schemas.binary), rename("is_less_than_or_equal", schemas.binaryFilter)},
[">"] = {rename("greater_than", schemas.binary), rename("is_greater_than", schemas.binaryFilter)},
[">="] = {rename("greater_than_or_equal", schemas.binary), rename("is_greater_than_or_equal", schemas.binaryFilter)},
["="] = {rename("equal", schemas.binary), rename("is_equal", schemas.binaryFilter), rename("move", schemas.moveIn), rename("move", schemas.moveOut)},
["!="] = {rename("not_equal", schemas.binary), rename("is_not_equal", schemas.binaryFilter)},
concat = {schema({"return", IN}, "concat")},
length = {rename("length", schemas.unary)},
is = {rename("is", schemas.unary)},
abs = {rename("abs", schemas.unary)},
sin = {rename("sin", schemas.unary)},
cos = {rename("cos", schemas.unary)},
tan = {rename("tan", schemas.unary)},
time = {schema({"return", OPT, "seconds", "minutes", "hours"}, "time")},
-- Aggregates
count = {schema({"return"}, "count", "aggregate"), schema({IN, "return"}, "count", "aggregate")},
sum = {schema({"return", STRONG_IN, "a"}, "sum", "aggregate"), schema({IN, "return", STRONG_IN, "a"}, "sum", "aggregate")}
}
function getExpressions()
local exprs = Set:new()
for expr in pairs(expressions) do
exprs:add(expr)
end
return exprs
end
function getSchemas(name)
return expressions[name]
end
function getSchema(name, signature)
if not expressions[name] then error("Unknown expression '" .. name .. "'") end
if not signature then error("Must specify signature to disambiguate expression alternatives") end
local result
for _, schema in ipairs(expressions[name]) do
local match = true
local required = Set:new()
for arg, mode in pairs(schema.signature) do
if mode == OUT or mode == IN or mode == STRONG_IN then
required:add(arg)
end
end
for arg, mode in pairs(signature) do
required:remove(arg)
local schemaMode = schema.signature[arg] or schema.rest
if schemaMode == STRONG_IN then
schemaMode = IN
end
if schemaMode ~= mode and schemaMode ~= OPT then
match = false
break
end
end
if match and required:length() == 0 then
result = schema
break
end
end
if not result then
local available = {}
for _, schema in ipairs(expressions[name]) do
available[#available + 1] = string.format("%s(%s)", name, fmtSignature(schema.args, schema.signature))
end
error(string.format("No matching signature for expression %s(%s); Available signatures:\n %s", name, signature, table.concat(available, "\n ")))
end
return result
end
function getArgs(schema, bindings)
local map = {}
local positions = {}
for _, binding in ipairs(bindings) do
map[binding.field] = binding.variable or binding.constant
positions[#positions + 1] = binding.field
end
local args = {}
local fields = {}
for _, arg in ipairs(schema.args) do
if map[arg] then
args[#args + 1] = map[arg]
fields[#fields + 1] = arg
end
end
if schema.rest then
fields[#fields + 1] = "..."
args["..."] = {}
for _, field in ipairs(positions) do
if not schema.signature[field] then
args["..."][#args["..."] + 1] = map[field]
end
end
end
return args, fields
end
return Pkg
|
Fix schema matching (broken from STRONG_IN) and add variadic support to getArgs
|
Fix schema matching (broken from STRONG_IN) and add variadic support to getArgs
|
Lua
|
apache-2.0
|
shamrin/Eve,witheve/lueve,nmsmith/Eve,witheve/Eve,witheve/Eve,witheve/lueve,shamrin/Eve,witheve/Eve,nmsmith/Eve,nmsmith/Eve,shamrin/Eve
|
62d4f1408ed8262b86f3d85795524cddba81db23
|
factions/server/factions.lua
|
factions/server/factions.lua
|
--[[
The MIT License (MIT)
Copyright (c) 2014 Socialz (+ soc-i-alz GitHub organization)
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 factions = { }
function getFactions( )
return factions
end
function getFactionByID( id )
for index, faction in pairs( getFactions( ) ) do
if ( faction.id == id ) then
return faction, index
end
end
return false
end
function getFactionByName( name )
for index, faction in pairs( getFactions( ) ) do
if ( faction.name == name ) then
return faction, index
end
end
return false
end
function createFaction( name )
local ranks = { }
for i = 1, factionRankCount do
table.insert( ranks, {
name = "Rank #" .. i,
wage = 0
} )
end
local id = exports.database:insert_id( "INSERT INTO `factions` (`name`, `ranks`) VALUES (?, ?)", name, toJSON( ranks ) )
return id and loadFaction( id ) or false
end
function deleteFaction( id )
local found, index = getFactionByID( id )
if ( found ) then
if ( exports.database:execute( "DELETE FROM `factions` WHERE `id` = ?", id ) ) then
factions[ index ] = nil
exports.database:execute( "DELETE FROM `factions_characters` WHERE `faction_id` = ?", id )
return true
end
end
return false
end
function addCharacterToFaction( characterID, id, rank, isLeader )
if ( not isCharacterInFaction( characterID, id ) ) and ( exports.database:execute( "INSERT INTO `factions_characters` (`character_id`, `faction_id`, `rank`, `is_leader`) VALUES (?, ?, ?, ?)", characterID, id, rank, isLeader ) ) then
local faction = getFactionByID( id )
table.insert( faction.players, { id = characterID, rank = rank, leader = isLeader } )
for _, data in pairs( faction.players ) do
local player = exports.common:getPlayerByCharacterID( data.id )
if ( player ) then
triggerClientEvent( player, "factions:update", player, faction )
end
end
return true
end
return false
end
function addPlayerToFaction( player, id )
return addCharacterToFaction( exports.common:getCharacterID( player ), id )
end
function removeCharacterFromFaction( characterID, id )
local index = isCharacterInFaction( characterID, id )
if ( index ) and ( exports.database:execute( "DELETE FROM `factions_characters` WHERE `character_id` = ? AND `faction_id` = ?", characterID, id ) ) then
local faction = getFactionByID( id )
table.remove( faction.players, index )
for _, data in pairs( faction.players ) do
local player = exports.common:getPlayerByCharacterID( data.id )
if ( player ) then
triggerClientEvent( player, "factions:update", player, faction )
end
end
return true
end
return false
end
function removePlayerFromFaction( player, id )
return removeCharacterFromFaction( exports.common:getCharacterID( player ), id )
end
function isCharacterInFaction( characterID, id, checkForLeadership )
local faction = getFactionByID( id )
if ( faction ) then
for index, data in pairs( faction.players ) do
if ( data.character_id == characterID ) and ( ( not checkForLeadership ) or ( data.leader ) ) then
return index
end
end
end
return false
end
function isPlayerInFaction( player, id, checkForLeadership )
return isCharacterInFaction( exports.common:getCharacterID( player ), id, checkForLeadership )
end
function getCharacterFactions( characterID )
local query = exports.database:query( "SELECT `faction_id` FROM `factions_characters` WHERE `character_id` = ?", id )
if ( query ) then
local playerFactions = { }
for _, data in ipairs( query ) do
table.insert( playerFactions, data.faction_id )
end
return playerFactions
end
return false
end
function getPlayerFactions( player, id )
return getCharacterFactions( exports.common:getCharacterID( player ) )
end
function loadFaction( id )
local _, index = getFactionByID( id )
factions[ index ] = nil
local query = exports.database:query_single( "SELECT * FROM `factions` WHERE `id` = ? LIMIT 1", id )
if ( query ) then
local ranks = fromJSON( query.ranks )
local faction = {
id = query.id,
name = query.name,
motd = query.motd,
ranks = ranks,
players = { }
}
for i = 1, factionRankCount do
if ( not faction.ranks[ i ] ) then
faction.ranks[ i ] = {
name = "Rank #" .. i,
wage = 0
}
end
end
if ( exports.common:count( faction.ranks ) ~= exports.common:count( ranks ) ) then
exports.database:execute( "UPDATE `factions` SET `ranks` = ? WHERE `id` = ?", toJSON( faction.ranks ) )
end
local players = exports.database:query( "SELECT `character_id` FROM `factions_characters` WHERE `faction_id` = ?", query.id )
if ( players ) then
for _, data in ipairs( players ) do
local rank = data.rank
if ( not faction.ranks[ rank ] ) then
rank = math.min( factionRankCount, math.max( 1, rank ) )
exports.database:execute( "UPDATE `faction_characters` SET `rank` = ? WHERE `character_id` = ?", rank, data.character_id )
end
table.insert( faction.players, { id = data.character_id, rank = data.rank, leader = data.is_leader == 1 } )
local player = exports.common:getPlayerByCharacterID( data.character_id )
if ( player ) then
triggerClientEvent( player, "factions:update", player, faction )
end
end
end
table.insert( factions, faction )
return true
end
return false
end
function loadFactions( )
local query = exports.database:query( "SELECT * FROM `factions`" )
if ( query ) then
for _, data in ipairs( query ) do
loadFaction( data.id )
end
return true
end
return false
end
addEventHandler( "onResourceStart", resourceRoot,
function( )
loadFactions( )
end
)
|
--[[
The MIT License (MIT)
Copyright (c) 2014 Socialz (+ soc-i-alz GitHub organization)
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 factions = { }
function getFactions( )
return factions
end
function getFactionByID( id )
for index, faction in pairs( getFactions( ) ) do
if ( faction.id == id ) then
return faction, index
end
end
return false
end
function getFactionByName( name )
for index, faction in pairs( getFactions( ) ) do
if ( faction.name == name ) then
return faction, index
end
end
return false
end
function createFaction( name, type )
local type = type or 1
local ranks = { }
for i = 1, factionRankCount do
table.insert( ranks, {
name = "Rank #" .. i,
wage = 0
} )
end
local id = exports.database:insert_id( "INSERT INTO `factions` (`name`, `type`, `ranks`) VALUES (?, ?, ?)", name, type, toJSON( ranks ) )
return id and loadFaction( id ) or false
end
function deleteFaction( id )
local found, index = getFactionByID( id )
if ( found ) then
if ( exports.database:execute( "DELETE FROM `factions` WHERE `id` = ?", id ) ) then
factions[ index ] = nil
exports.database:execute( "DELETE FROM `factions_characters` WHERE `faction_id` = ?", id )
return true
end
end
return false
end
function addCharacterToFaction( characterID, id, rank, isLeader )
rank = tonumber( rank ) or 1
isLeader = type( isLeader ) == "boolean" and isLeader or false
if ( not isCharacterInFaction( characterID, id ) ) and ( exports.database:execute( "INSERT INTO `factions_characters` (`character_id`, `faction_id`, `rank`, `is_leader`) VALUES (?, ?, ?, ?)", characterID, id, rank, isLeader ) ) then
local faction = getFactionByID( id )
table.insert( faction.players, { id = characterID, rank = rank, leader = isLeader } )
for _, data in pairs( faction.players ) do
local player = exports.common:getPlayerByCharacterID( data.id )
if ( player ) then
triggerClientEvent( player, "factions:update", player, faction )
end
end
return true
end
return false
end
function addPlayerToFaction( player, id )
return addCharacterToFaction( exports.common:getCharacterID( player ), id )
end
function removeCharacterFromFaction( characterID, id )
local index = isCharacterInFaction( characterID, id )
if ( index ) and ( exports.database:execute( "DELETE FROM `factions_characters` WHERE `character_id` = ? AND `faction_id` = ?", characterID, id ) ) then
local faction = getFactionByID( id )
table.remove( faction.players, index )
for _, data in pairs( faction.players ) do
local player = exports.common:getPlayerByCharacterID( data.id )
if ( player ) then
triggerClientEvent( player, "factions:update", player, faction )
end
end
return true
end
return false
end
function removePlayerFromFaction( player, id )
return removeCharacterFromFaction( exports.common:getCharacterID( player ), id )
end
function isCharacterInFaction( characterID, id, checkForLeadership )
local faction = getFactionByID( id )
if ( faction ) then
for index, data in pairs( faction.players ) do
if ( data.character_id == characterID ) and ( ( not checkForLeadership ) or ( data.leader ) ) then
return index
end
end
end
return false
end
function isPlayerInFaction( player, id, checkForLeadership )
return isCharacterInFaction( exports.common:getCharacterID( player ), id, checkForLeadership )
end
function getCharacterFactions( characterID )
local query = exports.database:query( "SELECT `faction_id` FROM `factions_characters` WHERE `character_id` = ?", id )
if ( query ) then
local playerFactions = { }
for _, data in ipairs( query ) do
table.insert( playerFactions, data.faction_id )
end
return playerFactions
end
return false
end
function getPlayerFactions( player, id )
return getCharacterFactions( exports.common:getCharacterID( player ) )
end
function loadFaction( id )
local _, index = getFactionByID( id )
if ( factions[ index ] ) then
factions[ index ] = nil
end
local query = exports.database:query_single( "SELECT * FROM `factions` WHERE `id` = ? LIMIT 1", id )
if ( query ) then
local ranks = fromJSON( query.ranks )
local faction = {
id = query.id,
name = query.name,
motd = query.motd,
ranks = ranks,
players = { }
}
for i = 1, factionRankCount do
if ( not faction.ranks[ i ] ) then
faction.ranks[ i ] = {
name = "Rank #" .. i,
wage = 0
}
end
end
if ( exports.common:count( faction.ranks ) ~= exports.common:count( ranks ) ) then
exports.database:execute( "UPDATE `factions` SET `ranks` = ? WHERE `id` = ?", toJSON( faction.ranks ) )
end
local players = exports.database:query( "SELECT `character_id` FROM `factions_characters` WHERE `faction_id` = ?", query.id )
if ( players ) then
for _, data in ipairs( players ) do
local rank = data.rank
if ( not faction.ranks[ rank ] ) then
rank = math.min( factionRankCount, math.max( 1, rank ) )
exports.database:execute( "UPDATE `faction_characters` SET `rank` = ? WHERE `character_id` = ?", rank, data.character_id )
end
table.insert( faction.players, { id = data.character_id, rank = data.rank, leader = data.is_leader == 1 } )
local player = exports.common:getPlayerByCharacterID( data.character_id )
if ( player ) then
triggerClientEvent( player, "factions:update", player, faction )
end
end
end
table.insert( factions, faction )
return getFactionByID( id )
end
return false
end
function loadFactions( )
local query = exports.database:query( "SELECT * FROM `factions`" )
if ( query ) then
for _, data in ipairs( query ) do
loadFaction( data.id )
end
return true
end
return false
end
addEventHandler( "onResourceStart", resourceRoot,
function( )
loadFactions( )
end
)
|
factions: added few parameters + fix
|
factions: added few parameters + fix
Added type parameter to createFaction (and hooked with the SQL query);
addCharacterToFaction now defaults rank and isLeader to the 1/0
respectively;
loadFaction returned error when nilling a nil table child;
loadFaction now returns the faction that was loaded.
|
Lua
|
mit
|
smile-tmb/lua-mta-fairplay-roleplay
|
0506b476bfd2ac51d64f57c81e1e7291488a5c0e
|
mock/common/PrefabAsset.lua
|
mock/common/PrefabAsset.lua
|
module 'mock'
--------------------------------------------------------------------
CLASS: Prefab ()
function Prefab:__init( data, id )
self.data = data
self.id = id
end
function Prefab:createInstance()
local instance
local data = self.data
if not data.entities then
_stat('loading empty prefab')
instance = Entity()
else
instance = deserializeEntity( data )
end
instance.__prefabId = self.id or true
return instance
end
--------------------------------------------------------------------
function createPrefabInstance( path )
local prefab, node = loadAsset( path )
if prefab and node:getType() == 'prefab' then
return prefab:createInstance()
else
_warn( 'prefab not found:', path )
return nil
end
end
--------------------------------------------------------------------
function saveEntityToPrefab( entity, prefabFile )
local data = serializeEntity( entity )
local str = encodeJSON( data )
local file = io.open( prefabFile, 'wb' )
if file then
file:write( str )
file:close()
else
_error( 'can not write to scene file', prefabFile )
return false
end
return true
end
--------------------------------------------------------------------
function PrefabLoader( node )
local path = node:getObjectFile( 'def' )
local data = loadAssetDataTable( path )
return Prefab( data, node:getNodePath() )
end
registerAssetLoader( 'prefab', PrefabLoader )
|
module 'mock'
--------------------------------------------------------------------
CLASS: Prefab ()
function Prefab:__init( data, id )
self.data = data
self.id = id
self.rootId = data.entities[1]['id']
local rootData = data.map[ self.rootId ]
self.rootName = rootData['body']['name']
end
function Prefab:getRootName()
return self.rootName
end
function Prefab:createInstance()
local instance
local data = self.data
if not data.entities then
_stat('loading empty prefab')
instance = Entity()
else
instance = deserializeEntity( data )
end
instance.__prefabId = self.id or true
return instance
end
--------------------------------------------------------------------
function createPrefabInstance( path )
local prefab, node = loadAsset( path )
if prefab and node:getType() == 'prefab' then
return prefab:createInstance()
else
_warn( 'prefab not found:', path )
return nil
end
end
--------------------------------------------------------------------
function saveEntityToPrefab( entity, prefabFile )
local data = serializeEntity( entity )
data.guid = {}
local str = encodeJSON( data )
local file = io.open( prefabFile, 'wb' )
if file then
file:write( str )
file:close()
else
_error( 'can not write to scene file', prefabFile )
return false
end
return true
end
--------------------------------------------------------------------
function PrefabLoader( node )
local path = node:getObjectFile( 'def' )
local data = loadAssetDataTable( path )
return Prefab( data, node:getNodePath() )
end
registerAssetLoader( 'prefab', PrefabLoader )
|
fixed Prefab guid issue
|
fixed Prefab guid issue
|
Lua
|
mit
|
tommo/mock
|
0a24560291d9a6720d6bab52fc57bd2db791aad4
|
src/api-umbrella/proxy/jobs/distributed_rate_limit_pusher.lua
|
src/api-umbrella/proxy/jobs/distributed_rate_limit_pusher.lua
|
local _M = {}
local distributed_rate_limit_queue = require "api-umbrella.proxy.distributed_rate_limit_queue"
local interval_lock = require "api-umbrella.utils.interval_lock"
local mongo = require "api-umbrella.utils.mongo"
local types = require "pl.types"
local is_empty = types.is_empty
local delay = 0.25 -- in seconds
local indexes_created = false
local function create_indexes()
if not indexes_created then
local _, err = mongo.create("system.indexes", {
ns = config["mongodb"]["_database"] .. ".rate_limits",
key = {
ts = -1,
},
name = "ts",
background = true,
})
if err then
ngx.log(ngx.ERR, "failed to create mongodb ts index: ", err)
end
_, err = mongo.create("system.indexes", {
ns = config["mongodb"]["_database"] .. ".rate_limits",
key = {
expire_at = 1,
},
name = "expire_at",
expireAfterSeconds = 0,
background = true,
})
if err then
ngx.log(ngx.ERR, "failed to create mongodb expire_at index: ", err)
end
indexes_created = true
end
end
local function do_check()
create_indexes()
local current_save_time = ngx.now() * 1000
local data = distributed_rate_limit_queue.pop()
if is_empty(data) then
return
end
local success = true
for key, count in pairs(data) do
local _, err = mongo.update("rate_limits", key, {
["$currentDate"] = {
ts = { ["$type"] = "timestamp" },
},
["$inc"] = {
count = count,
},
["$setOnInsert"] = {
expire_at = {
["$date"] = ngx.now() * 1000 + 60000,
},
},
})
if err then
ngx.log(ngx.ERR, "failed to update rate limits in mongodb: ", err)
success = false
end
end
if success then
ngx.shared.stats:set("distributed_last_pushed_at", current_save_time)
end
end
function _M.spawn()
interval_lock.repeat_with_mutex('distributed_rate_limit_pusher', delay, do_check)
end
return _M
|
local _M = {}
local distributed_rate_limit_queue = require "api-umbrella.proxy.distributed_rate_limit_queue"
local mongo = require "api-umbrella.utils.mongo"
local types = require "pl.types"
local is_empty = types.is_empty
local delay = 0.25 -- in seconds
local new_timer = ngx.timer.at
local indexes_created = false
local function create_indexes()
if not indexes_created then
local _, err = mongo.create("system.indexes", {
ns = config["mongodb"]["_database"] .. ".rate_limits",
key = {
ts = -1,
},
name = "ts",
background = true,
})
if err then
ngx.log(ngx.ERR, "failed to create mongodb ts index: ", err)
end
_, err = mongo.create("system.indexes", {
ns = config["mongodb"]["_database"] .. ".rate_limits",
key = {
expire_at = 1,
},
name = "expire_at",
expireAfterSeconds = 0,
background = true,
})
if err then
ngx.log(ngx.ERR, "failed to create mongodb expire_at index: ", err)
end
indexes_created = true
end
end
local function do_check()
create_indexes()
local current_save_time = ngx.now() * 1000
local data = distributed_rate_limit_queue.pop()
if is_empty(data) then
return
end
local success = true
for key, count in pairs(data) do
local _, err = mongo.update("rate_limits", key, {
["$currentDate"] = {
ts = { ["$type"] = "timestamp" },
},
["$inc"] = {
count = count,
},
["$setOnInsert"] = {
expire_at = {
["$date"] = ngx.now() * 1000 + 60000,
},
},
})
if err then
ngx.log(ngx.ERR, "failed to update rate limits in mongodb: ", err)
success = false
end
end
if success then
ngx.shared.stats:set("distributed_last_pushed_at", current_save_time)
end
end
-- Repeat calls to do_check() inside each worker on the specified interval
-- (every 0.25 seconds).
--
-- We don't use interval_lock.repeat_with_mutex() here like most of our other
-- background jobs, because in this job's case we're pushing local worker data
-- into the database. In this case, we don't want a mutex across workers, since
-- we want each worker to operate independently and fire every 0.25 seconds to
-- push it's local data to the database. With a mutex, certain workers may not
-- be called for longer periods of time causing the local data to build up and
-- not be synced as frequently as we expect.
local function check(premature)
if premature then
return
end
local ok, err = pcall(do_check)
if not ok then
ngx.log(ngx.ERR, "failed to run backend load cycle: ", err)
end
ok, err = new_timer(delay, check)
if not ok then
if err ~= "process exiting" then
ngx.log(ngx.ERR, "failed to create timer: ", err)
end
return
end
end
function _M.spawn()
local ok, err = new_timer(0, check)
if not ok then
ngx.log(ngx.ERR, "failed to create timer: ", err)
return
end
end
return _M
|
Fix the distributed rate limit pusher not firing as often as needed.
|
Fix the distributed rate limit pusher not firing as often as needed.
This was causing some test failures, since each worker process was not
syncing its local data as frequently as expected. The rate limit pusher
is a bit of an odd case amongst our background workers, since it's the
one place where we don't actually want a mutex or locking of any
fashion. So we've reverted its timer setup to the previous setup that
doesn't use the new interval_lock utility, but adding a comment about
why this is done differently.
|
Lua
|
mit
|
apinf/api-umbrella,NREL/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,apinf/api-umbrella,NREL/api-umbrella
|
19884146f09b89699209063f1e19c9ec818ab506
|
pud/system/CollisionSystem.lua
|
pud/system/CollisionSystem.lua
|
local Class = require 'lib.hump.class'
local ListenerBag = getClass 'pud.kit.ListenerBag'
local property = require 'pud.component.property'
local message = require 'pud.component.message'
local match = string.match
-- CollisionSystem
--
local CollisionSystem = Class{name='CollisionSystem',
function(self, level)
self._registered = ListenerBag()
self._level = level
end
}
-- destructor
function CollisionSystem:destroy()
self._registered:destroy()
self._registered = nil
self._level = nil
end
-- register an object
function CollisionSystem:register(obj)
self._registered:push(obj)
end
-- unregister an object
function CollisionSystem:unregister(obj)
self._registered:pop(obj)
end
-- check for collision between the given object and position
function CollisionSystem:check(obj, pos)
local collision = false
local oldpos = obj:query(property('Position'))
local entities = self._level:getEntitiesAtLocation(pos)
local collideEnemy = message('COLLIDE_ENEMY')
local collideHero = message('COLLIDE_HERO')
if entities then
local numEntities = #entities
for i=1,numEntities do
local otherEntity = entities[i]
if otherEntity ~= obj and self._registered:exists(otherEntity) then
local otherEntityType = otherEntity:getType()
if otherEntityType == 'enemy' then
obj:send(collideEnemy, otherEntity)
collision = true
elseif otherEntityType == 'hero' then
obj:send(collideHero, otherEntity)
collision = true
end
end
end
end
if not collision then
local node = self._level:getMapNode(pos)
local blocked = false
local mapType = node:getMapType()
local variant = mapType:getVariant()
local mt = match(tostring(mapType.__class), '^(%w+)MapType')
if mt then
blocked = obj:query(property('BlockedBy'), function(t)
for _,p in pairs(t) do
if p[mt] and (variant == p[mt] or p[mt] == 'ALL') then
return true
end
end
return false
end)
end
if blocked then
obj:send(message('COLLIDE_BLOCKED'), node)
collision = true
end
end
if not collision then
obj:send(message('COLLIDE_NONE'), pos, oldpos)
end
return collision
end
-- the class
return CollisionSystem
|
local Class = require 'lib.hump.class'
local ListenerBag = getClass 'pud.kit.ListenerBag'
local property = require 'pud.component.property'
local message = require 'pud.component.message'
local match = string.match
-- CollisionSystem
--
local CollisionSystem = Class{name='CollisionSystem',
function(self, level)
self._registered = ListenerBag()
self._level = level
end
}
-- destructor
function CollisionSystem:destroy()
self._registered:destroy()
self._registered = nil
self._level = nil
end
-- register an object
function CollisionSystem:register(comp)
local obj = comp:getMediator()
assert(obj, 'Could not register component: %s', tostring(comp))
self._registered:push(obj)
end
-- unregister an object
function CollisionSystem:unregister(comp)
local obj = comp:getMediator()
self._registered:pop(obj)
end
-- check for collision between the given object and position
function CollisionSystem:check(obj, pos)
local collision = false
local oldpos = obj:query(property('Position'))
local entities = self._level:getEntitiesAtLocation(pos)
local collideEnemy = message('COLLIDE_ENEMY')
local collideHero = message('COLLIDE_HERO')
if entities then
local numEntities = #entities
for i=1,numEntities do
local otherEntity = entities[i]
if otherEntity ~= obj and self._registered:exists(otherEntity) then
local otherEntityType = otherEntity:getType()
if otherEntityType == 'enemy' then
obj:send(collideEnemy, otherEntity)
collision = true
elseif otherEntityType == 'hero' then
obj:send(collideHero, otherEntity)
collision = true
end
end
end
end
if not collision then
local node = self._level:getMapNode(pos)
local blocked = false
local mapType = node:getMapType()
local variant = mapType:getVariant()
local mt = match(tostring(mapType.__class), '^(%w+)MapType')
if mt then
blocked = obj:query(property('BlockedBy'), function(t)
for _,p in pairs(t) do
if p[mt] and (variant == p[mt] or p[mt] == 'ALL') then
return true
end
end
return false
end)
end
if blocked then
obj:send(message('COLLIDE_BLOCKED'), node)
collision = true
end
end
if not collision then
obj:send(message('COLLIDE_NONE'), pos, oldpos)
end
return collision
end
-- the class
return CollisionSystem
|
fix CollisionSystem to register a component's mediator
|
fix CollisionSystem to register a component's mediator
instead of the component itself. This is probably wrong.
|
Lua
|
mit
|
scottcs/wyx
|
2c4886d598b26771a65122abe39937ec0e434e83
|
vrp/modules/survival.lua
|
vrp/modules/survival.lua
|
local lang = vRP.lang
local Survival = class("Survival", vRP.Extension)
-- SUBCLASS
Survival.User = class("User")
-- return vital value (0-1) or nil
function Survival.User:getVital(name)
return self.cdata.vitals[name]
end
-- set vital
-- value: 0-1
function Survival.User:setVital(name, value)
if vRP.EXT.Survival.vitals[name] then -- exists
local overflow
-- clamp
if value < 0 then
value = 0
overflow = value
elseif value > 1 then
value = 1
overflow = value-1
end
-- set
local pvalue = self.cdata.vitals[name]
self.cdata.vitals[name] = value
if pvalue ~= value then
vRP:triggerEvent("playerVitalChange", self, name)
end
if overflow then
vRP:triggerEvent("playerVitalOverflow", self, name, overflow)
end
end
end
function Survival.User:varyVital(name, value)
self:setVital(name, self:getVital(name)+value)
end
-- METHODS
function Survival:__construct()
vRP.Extension.__construct(self)
self.cfg = module("cfg/survival")
self.vitals = {} -- registered vitals, map of name => {default_value}
self:registerVital("water", 1)
self:registerVital("food", 0.75)
-- items
vRP.EXT.Inventory:defineItem("medkit", lang.item.medkit.name(), lang.item.medkit.description(), nil, 0.5)
-- water/food task increase
local function task_update()
SetTimeout(60000, task_update)
for id,user in pairs(vRP.users) do
if user:isReady() then
user:varyVital("water", -self.cfg.water_per_minute)
user:varyVital("food", -self.cfg.food_per_minute)
end
end
end
task_update()
-- menu
-- EMERGENCY
local revive_seq = {
{"amb@medic@standing@kneel@enter","enter",1},
{"amb@medic@standing@kneel@idle_a","idle_a",1},
{"amb@medic@standing@kneel@exit","exit",1}
}
local function m_revive(menu)
local user = menu.user
local nuser
local nplayer = vRP.EXT.Base.remote.getNearestPlayer(user.source,10)
if nplayer then nuser = vRP.users_by_source[nplayer] end
if nuser then
if self.remote.isInComa(nuser.source) then
if user:tryTakeItem("medkit",1) then
vRP.EXT.Base.remote._playAnim(user.source,false,revive_seq,false) -- anim
SetTimeout(15000, function()
self.remote._varyHealth(nuser.source,50) -- heal 50
end)
end
else
vRP.EXT.Base.remote._notify(user.source,lang.emergency.menu.revive.not_in_coma())
end
else
vRP.EXT.Base.remote._notify(user.source,lang.common.no_player_near())
end
end
-- add choices to the main menu (emergency)
vRP.EXT.GUI:registerMenuBuilder("main", function(menu)
if menu.user:hasPermission("emergency.revive") then
menu:addOption(lang.emergency.menu.revive.title(), m_revive, lang.emergency.menu.revive.description())
end
end)
end
-- default_value: (optional) default vital value, 0 by default
function Survival:registerVital(name, default_value)
self.vitals[name] = {default_value or 0}
end
-- EVENT
Survival.event = {}
function Survival.event:characterLoad(user)
-- init vitals
if not user.cdata.vitals then
user.cdata.vitals = {}
end
for name,vital in pairs(self.vitals) do
if not user.cdata.vitals[name] then
user.cdata.vitals[name] = vital[1]
end
end
end
function Survival.event:playerSpawn(user, first_spawn)
if first_spawn then
self.remote._setPolice(user.source, self.cfg.police)
self.remote._setFriendlyFire(user.source, self.cfg.pvp)
if self.cfg.vital_display then
local GUI = vRP.EXT.GUI
local water = user:getVital("water")
local food = user:getVital("food")
GUI.remote._setProgressBar(user.source,"vRP:Survival:food","minimap",(food == 0) and lang.survival.starving() or "",255,153,0,food)
GUI.remote._setProgressBar(user.source,"vRP:Survival:water","minimap",(water == 0) and lang.survival.thirsty() or "",0,125,255,water)
end
end
end
function Survival.event:playerStateLoaded(user)
-- kill if in coma
self.remote._killComa(user.source)
end
function Survival.event:playerDeath(user)
-- reset vitals
for name,vital in pairs(self.vitals) do
user:setVital(name, vital[1])
end
end
function Survival.event:playerVitalChange(user, vital)
if self.cfg.vital_display then
local GUI = vRP.EXT.GUI
if vital == "water" then
local value = user:getVital(vital)
GUI.remote._setProgressBarValue(user.source, "vRP:Survival:water", value)
GUI.remote._setProgressBarText(user.source, "vRP:Survival:water", (water == 0) and lang.survival.thirsty() or "")
elseif vital == "food" then
local value = user:getVital(vital)
GUI.remote._setProgressBarValue(user.source, "vRP:Survival:food", value)
GUI.remote._setProgressBarText(user.source, "vRP:Survival:food", (food == 0) and lang.survival.starving() or "")
end
end
end
function Survival.event:playerVitalOverflow(user, vital, overflow)
if vital == "water" or vital == "food" then
if overflow < 0 then
self.remote._varyHealth(user.source, -overflow*100*self.cfg.overflow_damage_factor)
end
end
end
-- TUNNEL
Survival.tunnel = {}
function Survival.tunnel:consume(water, food)
local user = vRP.users_by_source[source]
if user and user:isReady() then
if water then
user:varyVital("water", -water)
end
if food then
user:varyVital("food", -food)
end
end
end
vRP:registerExtension(Survival)
|
local lang = vRP.lang
local Survival = class("Survival", vRP.Extension)
-- SUBCLASS
Survival.User = class("User")
-- return vital value (0-1) or nil
function Survival.User:getVital(name)
return self.cdata.vitals[name]
end
-- set vital
-- value: 0-1
function Survival.User:setVital(name, value)
if vRP.EXT.Survival.vitals[name] then -- exists
local overflow
-- clamp
if value < 0 then
overflow = value
value = 0
elseif value > 1 then
overflow = value-1
value = 1
end
-- set
local pvalue = self.cdata.vitals[name]
self.cdata.vitals[name] = value
if pvalue ~= value then
vRP:triggerEvent("playerVitalChange", self, name)
end
if overflow then
vRP:triggerEvent("playerVitalOverflow", self, name, overflow)
end
end
end
function Survival.User:varyVital(name, value)
self:setVital(name, self:getVital(name)+value)
end
-- METHODS
function Survival:__construct()
vRP.Extension.__construct(self)
self.cfg = module("cfg/survival")
self.vitals = {} -- registered vitals, map of name => {default_value}
self:registerVital("water", 1)
self:registerVital("food", 0.75)
-- items
vRP.EXT.Inventory:defineItem("medkit", lang.item.medkit.name(), lang.item.medkit.description(), nil, 0.5)
-- water/food task increase
local function task_update()
SetTimeout(60000, task_update)
for id,user in pairs(vRP.users) do
if user:isReady() then
user:varyVital("water", -self.cfg.water_per_minute)
user:varyVital("food", -self.cfg.food_per_minute)
end
end
end
task_update()
-- menu
-- EMERGENCY
local revive_seq = {
{"amb@medic@standing@kneel@enter","enter",1},
{"amb@medic@standing@kneel@idle_a","idle_a",1},
{"amb@medic@standing@kneel@exit","exit",1}
}
local function m_revive(menu)
local user = menu.user
local nuser
local nplayer = vRP.EXT.Base.remote.getNearestPlayer(user.source,10)
if nplayer then nuser = vRP.users_by_source[nplayer] end
if nuser then
if self.remote.isInComa(nuser.source) then
if user:tryTakeItem("medkit",1) then
vRP.EXT.Base.remote._playAnim(user.source,false,revive_seq,false) -- anim
SetTimeout(15000, function()
self.remote._varyHealth(nuser.source,50) -- heal 50
end)
end
else
vRP.EXT.Base.remote._notify(user.source,lang.emergency.menu.revive.not_in_coma())
end
else
vRP.EXT.Base.remote._notify(user.source,lang.common.no_player_near())
end
end
-- add choices to the main menu (emergency)
vRP.EXT.GUI:registerMenuBuilder("main", function(menu)
if menu.user:hasPermission("emergency.revive") then
menu:addOption(lang.emergency.menu.revive.title(), m_revive, lang.emergency.menu.revive.description())
end
end)
end
-- default_value: (optional) default vital value, 0 by default
function Survival:registerVital(name, default_value)
self.vitals[name] = {default_value or 0}
end
-- EVENT
Survival.event = {}
function Survival.event:characterLoad(user)
-- init vitals
if not user.cdata.vitals then
user.cdata.vitals = {}
end
for name,vital in pairs(self.vitals) do
if not user.cdata.vitals[name] then
user.cdata.vitals[name] = vital[1]
end
end
end
function Survival.event:playerSpawn(user, first_spawn)
if first_spawn then
self.remote._setPolice(user.source, self.cfg.police)
self.remote._setFriendlyFire(user.source, self.cfg.pvp)
if self.cfg.vital_display then
local GUI = vRP.EXT.GUI
local water = user:getVital("water")
local food = user:getVital("food")
GUI.remote._setProgressBar(user.source,"vRP:Survival:food","minimap",(food == 0) and lang.survival.starving() or "",255,153,0,food)
GUI.remote._setProgressBar(user.source,"vRP:Survival:water","minimap",(water == 0) and lang.survival.thirsty() or "",0,125,255,water)
end
end
end
function Survival.event:playerStateLoaded(user)
-- kill if in coma
self.remote._killComa(user.source)
end
function Survival.event:playerDeath(user)
-- reset vitals
for name,vital in pairs(self.vitals) do
user:setVital(name, vital[1])
end
end
function Survival.event:playerVitalChange(user, vital)
if self.cfg.vital_display then
local GUI = vRP.EXT.GUI
if vital == "water" then
local value = user:getVital(vital)
GUI.remote._setProgressBarValue(user.source, "vRP:Survival:water", value)
GUI.remote._setProgressBarText(user.source, "vRP:Survival:water", (value == 0) and lang.survival.thirsty() or "")
elseif vital == "food" then
local value = user:getVital(vital)
GUI.remote._setProgressBarValue(user.source, "vRP:Survival:food", value)
GUI.remote._setProgressBarText(user.source, "vRP:Survival:food", (value == 0) and lang.survival.starving() or "")
end
end
end
function Survival.event:playerVitalOverflow(user, vital, overflow)
if vital == "water" or vital == "food" then
if overflow < 0 then
self.remote._varyHealth(user.source, overflow*100*self.cfg.overflow_damage_factor)
end
end
end
-- TUNNEL
Survival.tunnel = {}
function Survival.tunnel:consume(water, food)
local user = vRP.users_by_source[source]
if user and user:isReady() then
if water then
user:varyVital("water", -water)
end
if food then
user:varyVital("food", -food)
end
end
end
vRP:registerExtension(Survival)
|
Fix survival display and overflow issues.
|
Fix survival display and overflow issues.
|
Lua
|
mit
|
ImagicTheCat/vRP,ImagicTheCat/vRP
|
6697ecb8d0dc8fa2ad1710f8d97a6e5a17f78f34
|
src/cqueues.lua
|
src/cqueues.lua
|
local loader = function(loader, ...)
local core = require"_cqueues"
local errno = require"_cqueues.errno"
local monotime = core.monotime
local running = core.running
local strerror = errno.strerror
-- lazily load auxlib to prevent circular or unused dependencies
local auxlib = setmetatable({}, { __index = function (t, k)
local v = require"cqueues.auxlib"[k]
rawset(t, k, v)
return v
end })
-- load deprecated APIs into shadow table to keep hidden unless used
local notsupp = {}
setmetatable(core, { __index = notsupp })
--
-- core.poll
--
-- Wrap the cqueues yield protocol to support polling across
-- multilevel resume/yield. Requires explicit or implicit use
-- (through monkey patching of coroutine.resume and coroutine.wrap)
-- of auxlib.resume or auxlib.wrap.
--
-- Also supports polling from outside of a running event loop using
-- a cheap hack. NOT RECOMMENDED.
--
local _POLL = core._POLL
local yield = coroutine.yield
local poller
function core.poll(...)
local yes, main = running()
if yes then
if main then
return yield(...)
else
return yield(_POLL, ...)
end
else
local tuple
poller = poller or auxlib.assert3(core.new())
poller:wrap(function (...)
tuple = { core.poll(...) }
end, ...)
auxlib.assert3(poller:step())
if tuple then
return table.unpack(tuple)
end
end
end -- core.poll
--
-- core.sleep
--
-- Sleep primitive.
--
function core.sleep(timeout)
core.poll(timeout)
end -- core.sleep
--
-- core:step
--
-- Wrap the low-level :step interface to make managing event loops
-- slightly easier.
--
local step; step = core.interpose("step", function (self, timeout)
if core.running() then
core.poll(self, timeout)
return step(self, 0.0)
else
return step(self, timeout)
end
end) -- core:step
--
-- core:loop
--
-- Step until an error is encountered.
--
core.interpose("loop", function (self, timeout)
local ok, why
if timeout then
local curtime = monotime()
local deadline = curtime + timeout
repeat
ok, why = self:step(deadline - curtime)
curtime = monotime()
until not ok or deadline <= curtime or self:empty()
else
repeat
ok, why = self:step()
until not ok or self:empty()
end
return ok, why
end) -- core:loop
--
-- core:errors
--
-- Return iterator over core:loop.
--
core.interpose("errors", function (self, timeout)
if timeout then
local deadline = monotime() + timeout
return function ()
local curtime = monotime()
if curtime < deadline then
local ok, why = self:loop(deadline - curtime)
if not ok then
return why
end
end
return --> nothing, to end for loop
end
else
return function ()
local ok, why = self:loop()
if not ok then
return why
end
return --> nothing, to end for loop
end
end
end) -- core:errors
--
-- core.assert
--
-- DEPRECATED. See auxlib.assert.
--
function notsupp.assert(...)
return auxlib.assert(...)
end -- notsupp.assert
--
-- core.resume
--
-- DEPRECATED. See auxlib.resume.
--
function notsupp.resume(...)
return auxlib.resume(...)
end -- notsupp.resume
--
-- core.wrap
--
-- DEPRECATED. See auxlib.wrap.
--
function notsupp.wrap(...)
return auxlib.wrap(...)
end -- notsupp.wrap
core.loader = loader
return core
end -- loader
return loader(loader, ...)
|
local loader = function(loader, ...)
local core = require"_cqueues"
local errno = require"_cqueues.errno"
local monotime = core.monotime
local running = core.running
local strerror = errno.strerror
-- lazily load auxlib to prevent circular or unused dependencies
local auxlib = setmetatable({}, { __index = function (t, k)
local v = require"cqueues.auxlib"[k]
rawset(t, k, v)
return v
end })
-- load deprecated APIs into shadow table to keep hidden unless used
local notsupp = {}
setmetatable(core, { __index = notsupp })
--
-- core.poll
--
-- Wrap the cqueues yield protocol to support polling across
-- multilevel resume/yield. Requires explicit or implicit use
-- (through monkey patching of coroutine.resume and coroutine.wrap)
-- of auxlib.resume or auxlib.wrap.
--
-- Also supports polling from outside of a running event loop using
-- a cheap hack. NOT RECOMMENDED.
--
local _POLL = core._POLL
local yield = coroutine.yield
local poller
function core.poll(...)
local yes, main = running()
if yes then
if main then
return yield(...)
else
return yield(_POLL, ...)
end
else
local tuple
poller = poller or auxlib.assert3(core.new())
poller:wrap(function (...)
tuple = { core.poll(...) }
end, ...)
-- NOTE: must step twice, once to call poll and
-- again to wake up
auxlib.assert3(poller:step())
auxlib.assert3(poller:step())
return table.unpack(tuple or {})
end
end -- core.poll
--
-- core.sleep
--
-- Sleep primitive.
--
function core.sleep(timeout)
core.poll(timeout)
end -- core.sleep
--
-- core:step
--
-- Wrap the low-level :step interface to make managing event loops
-- slightly easier.
--
local step; step = core.interpose("step", function (self, timeout)
if core.running() then
core.poll(self, timeout)
return step(self, 0.0)
else
return step(self, timeout)
end
end) -- core:step
--
-- core:loop
--
-- Step until an error is encountered.
--
core.interpose("loop", function (self, timeout)
local ok, why
if timeout then
local curtime = monotime()
local deadline = curtime + timeout
repeat
ok, why = self:step(deadline - curtime)
curtime = monotime()
until not ok or deadline <= curtime or self:empty()
else
repeat
ok, why = self:step()
until not ok or self:empty()
end
return ok, why
end) -- core:loop
--
-- core:errors
--
-- Return iterator over core:loop.
--
core.interpose("errors", function (self, timeout)
if timeout then
local deadline = monotime() + timeout
return function ()
local curtime = monotime()
if curtime < deadline then
local ok, why = self:loop(deadline - curtime)
if not ok then
return why
end
end
return --> nothing, to end for loop
end
else
return function ()
local ok, why = self:loop()
if not ok then
return why
end
return --> nothing, to end for loop
end
end
end) -- core:errors
--
-- core.assert
--
-- DEPRECATED. See auxlib.assert.
--
function notsupp.assert(...)
return auxlib.assert(...)
end -- notsupp.assert
--
-- core.resume
--
-- DEPRECATED. See auxlib.resume.
--
function notsupp.resume(...)
return auxlib.resume(...)
end -- notsupp.resume
--
-- core.wrap
--
-- DEPRECATED. See auxlib.wrap.
--
function notsupp.wrap(...)
return auxlib.wrap(...)
end -- notsupp.wrap
core.loader = loader
return core
end -- loader
return loader(loader, ...)
|
another fix to our non-coroutine cqueues.poll hack
|
another fix to our non-coroutine cqueues.poll hack
|
Lua
|
mit
|
daurnimator/cqueues,bigcrush/cqueues,wahern/cqueues,daurnimator/cqueues,bigcrush/cqueues,wahern/cqueues
|
4b99130f3d585e1928a12e85d6fe699c653608aa
|
config/sipi.init-knora-test.lua
|
config/sipi.init-knora-test.lua
|
--
-- Copyright © 2016 Lukas Rosenthaler, Andrea Bianco, Benjamin Geer,
-- Ivan Subotic, Tobias Schweizer, André Kilchenmann, and André Fatton.
-- This file is part of Sipi.
-- Sipi 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.
-- Sipi 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.
-- Additional permission under GNU AGPL version 3 section 7:
-- If you modify this Program, or any covered work, by linking or combining
-- it with Kakadu (or a modified version of that library), containing parts
-- covered by the terms of the Kakadu Software Licence, the licensors of this
-- Program grant you additional permission to convey the resulting work.
-- 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 Sipi. If not, see <http://www.gnu.org/licenses/>.
-------------------------------------------------------------------------------
-- This function is being called from sipi before the file is served
-- Knora is called to ask for the user's permissions on the file
-- Parameters:
-- prefix: This is the prefix that is given on the IIIF url
-- identifier: the identifier for the image
-- cookie: The cookie that may be present
--
-- Returns:
-- permission:
-- 'allow' : the view is allowed with the given IIIF parameters
-- 'restrict:watermark=<path-to-watermark>' : Add a watermark
-- 'restrict:size=<iiif-size-string>' : reduce size/resolution
-- 'deny' : no access!
-- filepath: server-path where the master file is located
-------------------------------------------------------------------------------
function pre_flight(prefix,identifier,cookie)
--
-- For Knora Sipi integration testing
-- Always the same test file is served
-- Make sure that this image file exists in config.imgroot
--
filepath = config.imgroot .. '/' .. 'Leaves.jpg'
if prefix == "thumbs" then
-- always allow thumbnails
return 'allow', filepath
end
if prefix == "tmp" then
-- always deny access to tmp folder
return 'deny'
end
-- comment this in if you do not want to do a preflight request
-- print("ignoring permissions")
-- do return 'allow', filepath end
knora_cookie_header = nil
if cookie ~='' then
-- tries to extract the Knora session id from the cookie:
-- gets the digits between "sid=" and the closing ";" (only given in case of several key value pairs)
-- returns nil if it cannot find it
session_id = string.match(cookie, "sid=(%d+);?")
if session_id == nil then
-- no session_id could be extracted
print("cookie key is invalid")
else
knora_cookie_header = { Cookie = "KnoraAuthentication=" .. session_id }
end
end
knora_url = 'http://' .. config.knora_path .. ':' .. config.knora_port .. '/v1/files/' .. identifier
success, result = server.http("GET", knora_url, knora_cookie_header, 5000)
if not success then
server.log("server.http() failed: " .. result, server.loglevel.ERROR)
return 'deny'
end
if result.status_code ~= 200 then
server.log("Knora returned HTTP status code " .. result.status_code)
server.log(result.body)
return 'deny'
end
success, response_json = server.json_to_table(result.body)
if not success then
server.log("server.json_to_table() failed: " .. response_json, server.loglevel.ERROR)
return 'deny'
end
if response_json.status ~= 0 then
-- something went wrong with the request, Knora returned a non zero status
return 'deny'
end
if response_json.permissionCode == 0 then
-- no view permission on file
return 'deny'
elseif response_json.permissionCode == 1 then
-- restricted view permission on file
-- either watermark or size (depends on project, should be returned with permission code by Sipi responder)
return 'restrict:size=' .. config.thumb_size, filepath
elseif response_json.permissionCode >= 2 then
-- full view permissions on file
return 'allow', filepath
else
-- invalid permission code
return 'deny'
end
end
-------------------------------------------------------------------------------
|
--
-- Copyright © 2016 Lukas Rosenthaler, Andrea Bianco, Benjamin Geer,
-- Ivan Subotic, Tobias Schweizer, André Kilchenmann, and André Fatton.
-- This file is part of Sipi.
-- Sipi 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.
-- Sipi 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.
-- Additional permission under GNU AGPL version 3 section 7:
-- If you modify this Program, or any covered work, by linking or combining
-- it with Kakadu (or a modified version of that library), containing parts
-- covered by the terms of the Kakadu Software Licence, the licensors of this
-- Program grant you additional permission to convey the resulting work.
-- 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 Sipi. If not, see <http://www.gnu.org/licenses/>.
-------------------------------------------------------------------------------
-- This function is being called from sipi before the file is served
-- Knora is called to ask for the user's permissions on the file
-- Parameters:
-- prefix: This is the prefix that is given on the IIIF url
-- identifier: the identifier for the image
-- cookie: The cookie that may be present
--
-- Returns:
-- permission:
-- 'allow' : the view is allowed with the given IIIF parameters
-- 'restrict:watermark=<path-to-watermark>' : Add a watermark
-- 'restrict:size=<iiif-size-string>' : reduce size/resolution
-- 'deny' : no access!
-- filepath: server-path where the master file is located
-------------------------------------------------------------------------------
function pre_flight(prefix,identifier,cookie)
--
-- For Knora Sipi integration testing
-- Always the same test file is served
-- Make sure that this image file exists in config.imgroot
--
if config.prefix_as_path then
filepath = config.imgroot .. '/' .. prefix .. '/' .. 'Leaves.jpg'
else
filepath = config.imgroot .. '/' .. 'Leaves.jpg'
end
if prefix == "thumbs" then
-- always allow thumbnails
return 'allow', filepath
end
if prefix == "tmp" then
-- always deny access to tmp folder
return 'deny'
end
-- comment this in if you do not want to do a preflight request
-- print("ignoring permissions")
-- do return 'allow', filepath end
knora_cookie_header = nil
if cookie ~='' then
-- tries to extract the Knora session id from the cookie:
-- gets the digits between "sid=" and the closing ";" (only given in case of several key value pairs)
-- returns nil if it cannot find it
session_id = string.match(cookie, "sid=(%d+);?")
if session_id == nil then
-- no session_id could be extracted
print("cookie key is invalid")
else
knora_cookie_header = { Cookie = "KnoraAuthentication=" .. session_id }
end
end
knora_url = 'http://' .. config.knora_path .. ':' .. config.knora_port .. '/v1/files/' .. identifier
success, result = server.http("GET", knora_url, knora_cookie_header, 5000)
if not success then
server.log("server.http() failed: " .. result, server.loglevel.ERROR)
return 'deny'
end
if result.status_code ~= 200 then
server.log("Knora returned HTTP status code " .. result.status_code)
server.log(result.body)
return 'deny'
end
success, response_json = server.json_to_table(result.body)
if not success then
server.log("server.json_to_table() failed: " .. response_json, server.loglevel.ERROR)
return 'deny'
end
if response_json.status ~= 0 then
-- something went wrong with the request, Knora returned a non zero status
return 'deny'
end
if response_json.permissionCode == 0 then
-- no view permission on file
return 'deny'
elseif response_json.permissionCode == 1 then
-- restricted view permission on file
-- either watermark or size (depends on project, should be returned with permission code by Sipi responder)
return 'restrict:size=' .. config.thumb_size, filepath
elseif response_json.permissionCode >= 2 then
-- full view permissions on file
return 'allow', filepath
else
-- invalid permission code
return 'deny'
end
end
-------------------------------------------------------------------------------
|
fix: Use prefix if provided in sipi.init-knora-test.lua.
|
fix: Use prefix if provided in sipi.init-knora-test.lua.
|
Lua
|
agpl-3.0
|
dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi,dhlab-basel/Sipi
|
de032f448758a5f29a800a94e689105084cc6db9
|
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
|
applications/luci-ddns/luasrc/model/cbi/ddns/ddns.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local is_mini = (luci.dispatcher.context.path[1] == "mini")
m = Map("ddns", translate("Dynamic DNS"),
translate("Dynamic DNS allows that your router can be reached with " ..
"a fixed hostname while having a dynamically changing " ..
"IP address."))
s = m:section(TypedSection, "service", "")
s.addremove = true
s.anonymous = false
s:option(Flag, "enabled", translate("Enable"))
svc = s:option(ListValue, "service_name", translate("Service"))
svc.rmempty = true
local services = { }
local fd = io.open("/usr/lib/ddns/services", "r")
if fd then
local ln
repeat
ln = fd:read("*l")
local s = ln and ln:match('^%s*"([^"]+)"')
if s then services[#services+1] = s end
until not ln
fd:close()
end
local v
for _, v in luci.util.vspairs(services) do
svc:value(v)
end
svc:value("", "-- "..translate("custom").." --")
url = s:option(Value, "update_url", translate("Custom update-URL"))
url:depends("service_name", "")
url.rmempty = true
s:option(Value, "domain", translate("Hostname")).rmempty = true
s:option(Value, "username", translate("Username")).rmempty = true
pw = s:option(Value, "password", translate("Password"))
pw.rmempty = true
pw.password = true
if is_mini then
s.defaults.ip_source = "network"
s.defaults.ip_network = "wan"
else
require("luci.tools.webadmin")
src = s:option(ListValue, "ip_source",
translate("Source of IP address"))
src:value("network", translate("network"))
src:value("interface", translate("interface"))
src:value("web", translate("URL"))
iface = s:option(ListValue, "ip_network", translate("Network"))
iface:depends("ip_source", "network")
iface.rmempty = true
luci.tools.webadmin.cbi_add_networks(iface)
iface = s:option(ListValue, "ip_interface", translate("Interface"))
iface:depends("ip_source", "interface")
iface.rmempty = true
for k, v in pairs(luci.sys.net.devices()) do
iface:value(v)
end
web = s:option(Value, "ip_url", translate("URL"))
web:depends("ip_source", "web")
web.rmempty = true
end
s:option(Value, "check_interval",
translate("Check for changed IP every")).default = 10
unit = s:option(ListValue, "check_unit", translate("Check-time unit"))
unit.default = "minutes"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
s:option(Value, "force_interval", translate("Force update every")).default = 72
unit = s:option(ListValue, "force_unit", translate("Force-time unit"))
unit.default = "hours"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local is_mini = (luci.dispatcher.context.path[1] == "mini")
m = Map("ddns", translate("Dynamic DNS"),
translate("Dynamic DNS allows that your router can be reached with " ..
"a fixed hostname while having a dynamically changing " ..
"IP address."))
s = m:section(TypedSection, "service", "")
s.addremove = true
s.anonymous = false
s:option(Flag, "enabled", translate("Enable"))
svc = s:option(ListValue, "service_name", translate("Service"))
svc.rmempty = false
local services = { }
local fd = io.open("/usr/lib/ddns/services", "r")
if fd then
local ln
repeat
ln = fd:read("*l")
local s = ln and ln:match('^%s*"([^"]+)"')
if s then services[#services+1] = s end
until not ln
fd:close()
end
local v
for _, v in luci.util.vspairs(services) do
svc:value(v)
end
function svc.cfgvalue(...)
local v = Value.cfgvalue(...)
if not v or #v == 0 then
return "-"
else
return v
end
end
function svc.write(self, section, value)
if value == "-" then
m.uci:delete("ddns", section, self.option)
else
Value.write(self, section, value)
end
end
svc:value("-", "-- "..translate("custom").." --")
url = s:option(Value, "update_url", translate("Custom update-URL"))
url:depends("service_name", "-")
url.rmempty = true
s:option(Value, "domain", translate("Hostname")).rmempty = true
s:option(Value, "username", translate("Username")).rmempty = true
pw = s:option(Value, "password", translate("Password"))
pw.rmempty = true
pw.password = true
if is_mini then
s.defaults.ip_source = "network"
s.defaults.ip_network = "wan"
else
require("luci.tools.webadmin")
src = s:option(ListValue, "ip_source",
translate("Source of IP address"))
src:value("network", translate("network"))
src:value("interface", translate("interface"))
src:value("web", translate("URL"))
iface = s:option(ListValue, "ip_network", translate("Network"))
iface:depends("ip_source", "network")
iface.rmempty = true
luci.tools.webadmin.cbi_add_networks(iface)
iface = s:option(ListValue, "ip_interface", translate("Interface"))
iface:depends("ip_source", "interface")
iface.rmempty = true
for k, v in pairs(luci.sys.net.devices()) do
iface:value(v)
end
web = s:option(Value, "ip_url", translate("URL"))
web:depends("ip_source", "web")
web.rmempty = true
end
s:option(Value, "check_interval",
translate("Check for changed IP every")).default = 10
unit = s:option(ListValue, "check_unit", translate("Check-time unit"))
unit.default = "minutes"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
s:option(Value, "force_interval", translate("Force update every")).default = 72
unit = s:option(ListValue, "force_unit", translate("Force-time unit"))
unit.default = "hours"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
return m
|
applications/luci-ddns: fix selection of custom update_url
|
applications/luci-ddns: fix selection of custom update_url
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6588 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI,mzguanglin/LuCI
|
0e35a9bd38304b23fe866acd3ab4900fcc94df0d
|
lua/entities/gmod_wire_expression2/core/selfaware.lua
|
lua/entities/gmod_wire_expression2/core/selfaware.lua
|
/******************************************************************************\
Selfaware support
\******************************************************************************/
__e2setcost(1) -- temporary
e2function entity entity()
return self.entity
end
e2function entity owner()
return self.player
end
__e2setcost(nil) -- temporary
e2function void selfDestruct()
self.entity:Remove()
end
e2function void selfDestructAll()
for k,v in pairs(constraint.GetAllConstrainedEntities(self.entity)) do
if(getOwner(self,v)==self.player) then
v:Remove()
end
end
//constraint.RemoveAll(self.entity)
self.entity:Remove()
end
/******************************************************************************/
-- i/o functions
__e2setcost(10)
-- Returns an array of all entities wired to the output
e2function array ioOutputEntities( string output )
local ret = {}
if (self.entity.Outputs[output]) then
local tbl = self.entity.Outputs[output].Connected
for i=1,#tbl do if (IsValid(tbl[i].Entity)) then ret[#ret+1] = tbl[i].Entity end end
self.prf = self.prf + #ret
end
return ret
end
-- Returns the entity the input is wired to
e2function entity ioInputEntity( string input )
if (self.entity.Inputs[input] and self.entity.Inputs[input].Src and IsValid(self.entity.Inputs[input].Src)) then return self.entity.Inputs[input].Src end
end
local function setOutput( self, args, Type )
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self,op1), op2[1](self,op2)
if (self.entity.Outputs[rv1] and self.entity.Outputs[rv1].Type == Type) then
self.GlobalScope[rv1] = rv2
self.GlobalScope.vclk[rv1] = true
end
end
local function getInput( self, args, default, Type )
local op1 = args[2]
local rv1 = op1[1](self,op1)
if istable(default) then default = table.Copy(default) end
if (self.entity.Inputs[rv1] and self.entity.Inputs[rv1].Type == Type) then
return self.GlobalScope[rv1] or default
end
return default
end
local excluded_types = {
xgt = true,
}
local function upperfirst( word )
return word:Left(1):upper() .. word:Right(-2):lower()
end
__e2setcost(5)
registerCallback("postinit",function()
for k,v in pairs( wire_expression_types ) do
local short = v[1]
if (!excluded_types[short]) then
registerFunction("ioSetOutput","s"..short,""..short,function(self,args) return setOutput(self,args,k) end)
registerFunction("ioGetInput"..upperfirst(k == "NORMAL" and "NUMBER" or k),"s",short,function(self,args) return getInput(self,args,v[2],k) end)
end
end
end)
/******************************************************************************/
-- Name functions
-- Set the name of the E2 itself
e2function void setName( string name )
local e = self.entity
if (e.name == name) then return end
if (name == "generic" or name == "") then
name = "generic"
e.WireDebugName = "Expression 2"
else
e.WireDebugName = "E2 - " .. name
end
e.name = name
e:SetNWString( "name", e.name )
e:SetOverlayText(name)
end
-- Get the name of another E2
e2function string entity:getName()
if IsValid(this) and this.GetGateName then
return this:GetGateName() or ""
end
return ""
end
/******************************************************************************/
registerCallback("construct", function(self)
self.data.changed = {}
end)
__e2setcost(1)
-- This is the prototype for everything that can be compared using the == operator
e2function number changed(value)
local chg = self.data.changed
if value == chg[args] then return 0 end
chg[args] = value
return 1
end
-- vectors can be of gmod type Vector, so we need to treat them separately
e2function number changed(vector value)
local chg = self.data.changed
local this_chg = chg[args]
if not this_chg then
chg[args] = value
return 1
end
if this_chg
and value[1] == this_chg[1]
and value[2] == this_chg[2]
and value[3] == this_chg[3]
then return 0 end
chg[args] = value
return 1
end
-- This is the prototype for all table types.
e2function number changed(angle value)
local chg = self.data.changed
local this_chg = chg[args]
if not this_chg then
chg[args] = value
return 1
end
for i,v in pairs(value) do
if v ~= this_chg[i] then
chg[args] = value
return 1
end
end
return 0
end
local excluded_types = {
n = true,
v = true,
a = true,
r = true,
t = true,
}
local comparable_types = {
s = true,
e = true,
xwl = true,
b = true,
}
registerCallback("postinit", function()
-- generate this function for all types
for typeid,_ in pairs(wire_expression_types2) do
if not excluded_types[typeid] then
if comparable_types[typeid] then
registerFunction("changed", typeid, "n", e2_changed_n)
else
registerFunction("changed", typeid, "n", e2_changed_a)
end
end
end
end)
/******************************************************************************/
__e2setcost( 5 )
local getHash = E2Lib.getHash
e2function number hash()
return getHash( self, self.entity.original )
end
e2function number hashNoComments()
return getHash( self, self.entity.buffer )
end
e2function number hash( string str )
return getHash( self, str )
end
|
/******************************************************************************\
Selfaware support
\******************************************************************************/
__e2setcost(1) -- temporary
e2function entity entity()
return self.entity
end
e2function entity owner()
return self.player
end
__e2setcost(nil) -- temporary
e2function void selfDestruct()
self.entity:Remove()
end
e2function void selfDestructAll()
for k,v in pairs(constraint.GetAllConstrainedEntities(self.entity)) do
if(getOwner(self,v)==self.player) then
v:Remove()
end
end
//constraint.RemoveAll(self.entity)
self.entity:Remove()
end
/******************************************************************************/
-- i/o functions
__e2setcost(10)
-- Returns an array of all entities wired to the output
e2function array ioOutputEntities( string output )
local ret = {}
if (self.entity.Outputs[output]) then
local tbl = self.entity.Outputs[output].Connected
for i=1,#tbl do if (IsValid(tbl[i].Entity)) then ret[#ret+1] = tbl[i].Entity end end
self.prf = self.prf + #ret
end
return ret
end
-- Returns the entity the input is wired to
e2function entity ioInputEntity( string input )
if (self.entity.Inputs[input] and self.entity.Inputs[input].Src and IsValid(self.entity.Inputs[input].Src)) then return self.entity.Inputs[input].Src end
end
local function setOutput( self, args, Type )
local op1, op2 = args[2], args[3]
local rv1, rv2 = op1[1](self,op1), op2[1](self,op2)
if (self.entity.Outputs[rv1] and self.entity.Outputs[rv1].Type == Type) then
self.GlobalScope[rv1] = rv2
self.GlobalScope.vclk[rv1] = true
end
end
local function getInput( self, args, default, Type )
local op1 = args[2]
local rv1 = op1[1](self,op1)
if istable(default) then default = table.Copy(default) end
if (self.entity.Inputs[rv1] and self.entity.Inputs[rv1].Type == Type) then
return self.GlobalScope[rv1] or default
end
return default
end
local excluded_types = {
xgt = true,
}
local function upperfirst( word )
return word:Left(1):upper() .. word:Right(-2):lower()
end
__e2setcost(5)
registerCallback("postinit",function()
for k,v in pairs( wire_expression_types ) do
local short = v[1]
if (!excluded_types[short]) then
registerFunction("ioSetOutput","s"..short,""..short,function(self,args) return setOutput(self,args,k) end)
registerFunction("ioGetInput"..upperfirst(k == "NORMAL" and "NUMBER" or k),"s",short,function(self,args) return getInput(self,args,v[2],k) end)
end
end
end)
/******************************************************************************/
-- Name functions
-- Set the name of the E2 itself
e2function void setName( string name )
local e = self.entity
if( #name > 12000 ) then
name = string.sub( name, 1, 12000 )
end
if (e.name == name) then return end
if (name == "generic" or name == "") then
name = "generic"
e.WireDebugName = "Expression 2"
else
e.WireDebugName = "E2 - " .. name
end
e.name = name
e:SetNWString( "name", e.name )
e:SetOverlayText(name)
end
-- Get the name of another E2
e2function string entity:getName()
if IsValid(this) and this.GetGateName then
return this:GetGateName() or ""
end
return ""
end
/******************************************************************************/
registerCallback("construct", function(self)
self.data.changed = {}
end)
__e2setcost(1)
-- This is the prototype for everything that can be compared using the == operator
e2function number changed(value)
local chg = self.data.changed
if value == chg[args] then return 0 end
chg[args] = value
return 1
end
-- vectors can be of gmod type Vector, so we need to treat them separately
e2function number changed(vector value)
local chg = self.data.changed
local this_chg = chg[args]
if not this_chg then
chg[args] = value
return 1
end
if this_chg
and value[1] == this_chg[1]
and value[2] == this_chg[2]
and value[3] == this_chg[3]
then return 0 end
chg[args] = value
return 1
end
-- This is the prototype for all table types.
e2function number changed(angle value)
local chg = self.data.changed
local this_chg = chg[args]
if not this_chg then
chg[args] = value
return 1
end
for i,v in pairs(value) do
if v ~= this_chg[i] then
chg[args] = value
return 1
end
end
return 0
end
local excluded_types = {
n = true,
v = true,
a = true,
r = true,
t = true,
}
local comparable_types = {
s = true,
e = true,
xwl = true,
b = true,
}
registerCallback("postinit", function()
-- generate this function for all types
for typeid,_ in pairs(wire_expression_types2) do
if not excluded_types[typeid] then
if comparable_types[typeid] then
registerFunction("changed", typeid, "n", e2_changed_n)
else
registerFunction("changed", typeid, "n", e2_changed_a)
end
end
end
end)
/******************************************************************************/
__e2setcost( 5 )
local getHash = E2Lib.getHash
e2function number hash()
return getHash( self, self.entity.original )
end
e2function number hashNoComments()
return getHash( self, self.entity.buffer )
end
e2function number hash( string str )
return getHash( self, str )
end
|
setName character limit
|
setName character limit
Fixes some issues with net messages and server freezes due to large strings ( over 300 million characters ). Sets a limit of 12,000 characters.
|
Lua
|
apache-2.0
|
dvdvideo1234/wire,Grocel/wire,wiremod/wire,bigdogmat/wire,thegrb93/wire,sammyt291/wire,garrysmodlua/wire,NezzKryptic/Wire
|
0900aeb9b3ec21026705918d1bc591bbfb18012a
|
MMOCoreORB/bin/scripts/mobile/dantooine/serverobjects.lua
|
MMOCoreORB/bin/scripts/mobile/dantooine/serverobjects.lua
|
includeFile("dantooine/abandoned_rebel_private.lua")
includeFile("dantooine/adwan_turoldine.lua")
includeFile("dantooine/ancient_graul.lua")
includeFile("dantooine/baby_bol.lua")
includeFile("dantooine/bek_rabor.lua")
includeFile("dantooine/bile_drenched_quenker.lua")
includeFile("dantooine/bol_be.lua")
includeFile("dantooine/bol.lua")
includeFile("dantooine/bol_pack_runner.lua")
includeFile("dantooine/bors_teraud.lua")
includeFile("dantooine/computer_scientist.lua")
includeFile("dantooine/crazed_scientist.lua")
includeFile("dantooine/cyborg_bol.lua")
includeFile("dantooine/cyborg_dune_lizard.lua")
includeFile("dantooine/cyborg_huurton.lua")
includeFile("dantooine/cyborg_slice_hound.lua")
includeFile("dantooine/cyborg_tusk_cat.lua")
includeFile("dantooine/daiv_dekven.lua")
includeFile("dantooine/dantari_battlelord.lua")
includeFile("dantooine/dantari_chief.lua")
includeFile("dantooine/dantari_raider.lua")
includeFile("dantooine/dantari_strategist.lua")
includeFile("dantooine/dark_side_savage.lua")
includeFile("dantooine/dine_lizard.lua")
includeFile("dantooine/dirk_maggin.lua")
includeFile("dantooine/doctor_knag.lua")
includeFile("dantooine/domestic_bol_mount.lua")
includeFile("dantooine/drakka_judarrl.lua")
includeFile("dantooine/enraged_defender.lua")
includeFile("dantooine/feral_force_wielder.lua")
includeFile("dantooine/fern_yarrow.lua")
includeFile("dantooine/fierce_huurton.lua")
includeFile("dantooine/fierce_piket_protector.lua")
includeFile("dantooine/force_crystal_hunter.lua")
includeFile("dantooine/force_sensitive_crypt_crawler.lua")
includeFile("dantooine/force_sensitive_renegade.lua")
includeFile("dantooine/force_trained_archaist.lua")
includeFile("dantooine/forsaken_force_drifter.lua")
includeFile("dantooine/frenzied_graul.lua")
includeFile("dantooine/grassland_voritor_tracker.lua")
includeFile("dantooine/graul_be.lua")
includeFile("dantooine/graul.lua")
includeFile("dantooine/graul_marauder.lua")
includeFile("dantooine/graul_mangler.lua")
includeFile("dantooine/graul_mauler.lua")
includeFile("dantooine/horned_voritor_lizard.lua")
includeFile("dantooine/hostile_huurton.lua")
includeFile("dantooine/hostile_thune_mother.lua")
includeFile("dantooine/huurton_be.lua")
includeFile("dantooine/huurton_bloodhunter.lua")
includeFile("dantooine/huurton_howler.lua")
includeFile("dantooine/huurton_huntress.lua")
includeFile("dantooine/huurton.lua")
includeFile("dantooine/huurton_matron.lua")
includeFile("dantooine/huurton_pup.lua")
includeFile("dantooine/huurton_reaper.lua")
includeFile("dantooine/huurton_stalker.lua")
includeFile("dantooine/infant_graul.lua")
includeFile("dantooine/insurgent.lua")
includeFile("dantooine/jan_dodonna.lua")
includeFile("dantooine/janta_clan_leader.lua")
includeFile("dantooine/janta_harvester.lua")
includeFile("dantooine/janta_herbalist.lua")
includeFile("dantooine/janta_hunter.lua")
includeFile("dantooine/janta_loreweaver.lua")
includeFile("dantooine/janta_primalist.lua")
includeFile("dantooine/janta_rockshaper.lua")
includeFile("dantooine/janta_scout.lua")
includeFile("dantooine/janta_shaman.lua")
includeFile("dantooine/janta_soothsayer.lua")
includeFile("dantooine/janta_tribesman.lua")
includeFile("dantooine/janta_warrior.lua")
includeFile("dantooine/jatrian_lytus.lua")
includeFile("dantooine/juntah_herm.lua")
includeFile("dantooine/kelvus_naria.lua")
includeFile("dantooine/kess_yarrow.lua")
includeFile("dantooine/kunga_clan_leader.lua")
includeFile("dantooine/kunga_clan_primalist.lua")
includeFile("dantooine/kunga_harvester.lua")
includeFile("dantooine/kunga_herbalist.lua")
includeFile("dantooine/kunga_hunter.lua")
includeFile("dantooine/kunga_loreweaver.lua")
includeFile("dantooine/kunga_rockshaper.lua")
includeFile("dantooine/kunga_scout.lua")
includeFile("dantooine/kunga_shaman.lua")
includeFile("dantooine/kunga_soothsayer.lua")
includeFile("dantooine/kunga_tribe_member.lua")
includeFile("dantooine/kunga_warrior.lua")
includeFile("dantooine/lesser_plains_bol.lua")
includeFile("dantooine/luthik_uwyr.lua")
includeFile("dantooine/lx_466.lua")
includeFile("dantooine/mammoth_thune.lua")
includeFile("dantooine/manx_try.lua")
includeFile("dantooine/mine_rat.lua")
includeFile("dantooine/mirla.lua")
includeFile("dantooine/mokk_clan_leader.lua")
includeFile("dantooine/mokk_clan_primalist.lua")
includeFile("dantooine/mokk_harvester.lua")
includeFile("dantooine/mokk_herbalist.lua")
includeFile("dantooine/mokk_hunter.lua")
includeFile("dantooine/mokk_loreweaver.lua")
includeFile("dantooine/mokk_rockshaper.lua")
includeFile("dantooine/mokk_scout.lua")
includeFile("dantooine/mokk_shaman.lua")
includeFile("dantooine/mokk_soothsayer.lua")
includeFile("dantooine/mokk_tribesman.lua")
includeFile("dantooine/mokk_warrior.lua")
includeFile("dantooine/novice_force_mystic.lua")
includeFile("dantooine/piket_be.lua")
includeFile("dantooine/piket_longhorn_female.lua")
includeFile("dantooine/piket_longhorn.lua")
includeFile("dantooine/piket.lua")
includeFile("dantooine/piket_plains_walker.lua")
includeFile("dantooine/quenker.lua")
includeFile("dantooine/quenker_ravager.lua")
includeFile("dantooine/quenker_relic_reaper.lua")
includeFile("dantooine/quich_marae.lua")
includeFile("dantooine/rane_yarrow.lua")
includeFile("dantooine/savage_huurton.lua")
includeFile("dantooine/savage_quenker.lua")
includeFile("dantooine/seething_bol_crusher.lua")
includeFile("dantooine/sg_567.lua")
includeFile("dantooine/slinking_voritor_hunter.lua")
includeFile("dantooine/spiked_slasher.lua")
includeFile("dantooine/stoos_olko.lua")
includeFile("dantooine/stranded_rebel_scout.lua")
includeFile("dantooine/swift_charging_bol.lua")
includeFile("dantooine/teraud_loyalist_commander.lua")
includeFile("dantooine/teraud_loyalist_cyborg.lua")
includeFile("dantooine/teraud_loyalist.lua")
includeFile("dantooine/terrible_quenker.lua")
includeFile("dantooine/theme_park_rebel_bothan_spy.lua")
includeFile("dantooine/theme_park_rebel_disgruntled_citizen.lua")
includeFile("dantooine/theme_park_rebel_jeremes_kelton.lua")
includeFile("dantooine/theme_park_rebel_teria_alessie.lua")
includeFile("dantooine/thune_be.lua")
includeFile("dantooine/thune_grassland_guardian.lua")
includeFile("dantooine/thune_herd_leader.lua")
includeFile("dantooine/thune.lua")
includeFile("dantooine/untrained_wielder_of_the_dark_side.lua")
includeFile("dantooine/ussox.lua")
includeFile("dantooine/warren_agro_droid_boss.lua")
includeFile("dantooine/warren_agro_droid.lua")
includeFile("dantooine/warren_altered_atst.lua")
includeFile("dantooine/warren_imperial_officer.lua")
includeFile("dantooine/warren_imperial_worker.lua")
includeFile("dantooine/warren_irradiated_worker.lua")
includeFile("dantooine/warren_scientist.lua")
includeFile("dantooine/warren_stormtrooper.lua")
includeFile("dantooine/xaan_talmaron.lua")
includeFile("dantooine/yras_shen_jen.lua")
includeFile("dantooine/ytzosh.lua")
|
includeFile("dantooine/abandoned_rebel_private.lua")
includeFile("dantooine/adwan_turoldine.lua")
includeFile("dantooine/ancient_graul.lua")
includeFile("dantooine/baby_bol.lua")
includeFile("dantooine/bek_rabor.lua")
includeFile("dantooine/bile_drenched_quenker.lua")
includeFile("dantooine/bol_be.lua")
includeFile("dantooine/bol.lua")
includeFile("dantooine/bol_pack_runner.lua")
includeFile("dantooine/bors_teraud.lua")
includeFile("dantooine/computer_scientist.lua")
includeFile("dantooine/crazed_scientist.lua")
includeFile("dantooine/cyborg_bol.lua")
includeFile("dantooine/cyborg_dune_lizard.lua")
includeFile("dantooine/cyborg_huurton.lua")
includeFile("dantooine/cyborg_slice_hound.lua")
includeFile("dantooine/cyborg_tusk_cat.lua")
includeFile("dantooine/daiv_dekven.lua")
includeFile("dantooine/dantari_battlelord.lua")
includeFile("dantooine/dantari_chief.lua")
includeFile("dantooine/dantari_raider.lua")
includeFile("dantooine/dantari_strategist.lua")
includeFile("dantooine/dark_side_savage.lua")
includeFile("dantooine/dine_lizard.lua")
includeFile("dantooine/dirk_maggin.lua")
includeFile("dantooine/doctor_knag.lua")
includeFile("dantooine/domestic_bol_mount.lua")
includeFile("dantooine/drakka_judarrl.lua")
includeFile("dantooine/enraged_defender.lua")
includeFile("dantooine/feral_force_wielder.lua")
includeFile("dantooine/fern_yarrow.lua")
includeFile("dantooine/fierce_huurton.lua")
includeFile("dantooine/fierce_piket_protector.lua")
includeFile("dantooine/force_crystal_hunter.lua")
includeFile("dantooine/force_sensitive_crypt_crawler.lua")
includeFile("dantooine/force_sensitive_renegade.lua")
includeFile("dantooine/force_trained_archaist.lua")
includeFile("dantooine/forsaken_force_drifter.lua")
includeFile("dantooine/frenzied_graul.lua")
includeFile("dantooine/grassland_voritor_tracker.lua")
includeFile("dantooine/graul_be.lua")
includeFile("dantooine/graul.lua")
includeFile("dantooine/graul_marauder.lua")
includeFile("dantooine/graul_mangler.lua")
includeFile("dantooine/graul_mauler.lua")
includeFile("dantooine/horned_voritor_lizard.lua")
includeFile("dantooine/hostile_huurton.lua")
includeFile("dantooine/hostile_thune_mother.lua")
includeFile("dantooine/huurton_be.lua")
includeFile("dantooine/huurton_bloodhunter.lua")
includeFile("dantooine/huurton_howler.lua")
includeFile("dantooine/huurton_huntress.lua")
includeFile("dantooine/huurton.lua")
includeFile("dantooine/huurton_matron.lua")
includeFile("dantooine/huurton_pup.lua")
includeFile("dantooine/huurton_reaper.lua")
includeFile("dantooine/huurton_stalker.lua")
includeFile("dantooine/infant_graul.lua")
includeFile("dantooine/insurgent.lua")
includeFile("dantooine/jan_dodonna.lua")
includeFile("dantooine/janta_clan_leader.lua")
includeFile("dantooine/janta_harvester.lua")
includeFile("dantooine/janta_herbalist.lua")
includeFile("dantooine/janta_hunter.lua")
includeFile("dantooine/janta_loreweaver.lua")
includeFile("dantooine/janta_primalist.lua")
includeFile("dantooine/janta_rockshaper.lua")
includeFile("dantooine/janta_scout.lua")
includeFile("dantooine/janta_shaman.lua")
includeFile("dantooine/janta_soothsayer.lua")
includeFile("dantooine/janta_tribesman.lua")
includeFile("dantooine/janta_warrior.lua")
includeFile("dantooine/jatrian_lytus.lua")
includeFile("dantooine/juntah_herm.lua")
includeFile("dantooine/kelvus_naria.lua")
includeFile("dantooine/kess_yarrow.lua")
includeFile("dantooine/kunga_clan_leader.lua")
includeFile("dantooine/kunga_clan_primalist.lua")
includeFile("dantooine/kunga_harvester.lua")
includeFile("dantooine/kunga_herbalist.lua")
includeFile("dantooine/kunga_hunter.lua")
includeFile("dantooine/kunga_loreweaver.lua")
includeFile("dantooine/kunga_rockshaper.lua")
includeFile("dantooine/kunga_scout.lua")
includeFile("dantooine/kunga_shaman.lua")
includeFile("dantooine/kunga_soothsayer.lua")
includeFile("dantooine/kunga_tribe_member.lua")
includeFile("dantooine/kunga_warrior.lua")
includeFile("dantooine/lesser_plains_bol.lua")
includeFile("dantooine/luthik_uwyr.lua")
includeFile("dantooine/lx_466.lua")
includeFile("dantooine/mammoth_thune.lua")
includeFile("dantooine/manx_try.lua")
includeFile("dantooine/mine_rat.lua")
includeFile("dantooine/mirla.lua")
includeFile("dantooine/mokk_clan_leader.lua")
includeFile("dantooine/mokk_clan_primalist.lua")
includeFile("dantooine/mokk_harvester.lua")
includeFile("dantooine/mokk_herbalist.lua")
includeFile("dantooine/mokk_hunter.lua")
includeFile("dantooine/mokk_loreweaver.lua")
includeFile("dantooine/mokk_rockshaper.lua")
includeFile("dantooine/mokk_scout.lua")
includeFile("dantooine/mokk_shaman.lua")
includeFile("dantooine/mokk_soothsayer.lua")
includeFile("dantooine/mokk_tribesman.lua")
includeFile("dantooine/mokk_warrior.lua")
includeFile("dantooine/novice_force_mystic.lua")
includeFile("dantooine/piket_be.lua")
includeFile("dantooine/piket_longhorn_female.lua")
includeFile("dantooine/piket_longhorn.lua")
includeFile("dantooine/piket.lua")
includeFile("dantooine/piket_plains_walker.lua")
includeFile("dantooine/quenker.lua")
includeFile("dantooine/quenker_ravager.lua")
includeFile("dantooine/quenker_relic_reaper.lua")
includeFile("dantooine/quich_marae.lua")
includeFile("dantooine/rane_yarrow.lua")
includeFile("dantooine/savage_huurton.lua")
includeFile("dantooine/savage_quenker.lua")
includeFile("dantooine/seething_bol_crusher.lua")
includeFile("dantooine/sg_567.lua")
includeFile("dantooine/slinking_voritor_hunter.lua")
includeFile("dantooine/spiked_slasher.lua")
includeFile("dantooine/stoos_olko.lua")
includeFile("dantooine/stranded_rebel_scout.lua")
includeFile("dantooine/swift_charging_bol.lua")
includeFile("dantooine/teraud_loyalist_commander.lua")
includeFile("dantooine/teraud_loyalist_cyborg.lua")
includeFile("dantooine/teraud_loyalist.lua")
includeFile("dantooine/terrible_quenker.lua")
includeFile("dantooine/theme_park_imperial_engineer.lua")
includeFile("dantooine/theme_park_rebel_bothan_spy.lua")
includeFile("dantooine/theme_park_rebel_disgruntled_citizen.lua")
includeFile("dantooine/theme_park_rebel_jeremes_kelton.lua")
includeFile("dantooine/theme_park_rebel_teria_alessie.lua")
includeFile("dantooine/thune_be.lua")
includeFile("dantooine/thune_grassland_guardian.lua")
includeFile("dantooine/thune_herd_leader.lua")
includeFile("dantooine/thune.lua")
includeFile("dantooine/untrained_wielder_of_the_dark_side.lua")
includeFile("dantooine/ussox.lua")
includeFile("dantooine/warren_agro_droid_boss.lua")
includeFile("dantooine/warren_agro_droid.lua")
includeFile("dantooine/warren_altered_atst.lua")
includeFile("dantooine/warren_imperial_officer.lua")
includeFile("dantooine/warren_imperial_worker.lua")
includeFile("dantooine/warren_irradiated_worker.lua")
includeFile("dantooine/warren_scientist.lua")
includeFile("dantooine/warren_stormtrooper.lua")
includeFile("dantooine/xaan_talmaron.lua")
includeFile("dantooine/yras_shen_jen.lua")
includeFile("dantooine/ytzosh.lua")
|
(unstable) [fixed] missing npc template for mon mothma mission 4.
|
(unstable) [fixed] missing npc template for mon mothma mission 4.
git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5948 c3d1530f-68f5-4bd0-87dc-8ef779617e40
|
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,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
|
a7bcddaaacb1dfc040ed61ac0fa4028680088e9f
|
frlib/loaders/meshes.lua
|
frlib/loaders/meshes.lua
|
-- Import relevant base types.
local types = require "base.types"
require "base.vec2"
require "base.vec3"
require "base.vec4"
-- Import utility functions.
local transform = require "base.transform"
-- Module aliases.
local vec2 = types.vec2
local vec3 = types.vec3
local vec4 = types.vec4
local scale = transform.scale
local translate = transform.translate
-- Cache for OBJ models.
local obj_cache = {}
-- Loads a mesh in OBJ format, caching it for later reloading.
local function obj(filename, adjust)
if obj_cache[filename] then
return obj_cache[filename]
end
adjust = adjust or false
local vertices = {}
local normals = {}
local texcoords = {}
local faces = {}
local translator = {}
local vert_num = 0
local f = assert(io.open(filename, "r"))
local line = f:read("*l")
while line ~= nil do
if string.len(line) == 0 or string.sub(line, 1, 1) == "#" then
-- Ignore, blank line or comment.
else
-- Match vertex definitions.
local v1, v2, v3 = string.match(line, "v%s+([%d%-%.]+)%s+([%d%-%.]+)%s+([%d%-%.]+)")
if v1 ~= nil and v2 ~= nil and v3 ~= nil then
table.insert(vertices, vec3(tonumber(v1), tonumber(v2), tonumber(v3)))
else
-- Match normal definitions.
local n1, n2, n3 = string.match(line, "vn%s+([%d%-%.]+)%s+([%d%-%.]+)%s+([%d%-%.]+)")
if n1 ~= nil and n2 ~= nil and n3 ~= nil then
table.insert(normals, vec3(tonumber(n1), tonumber(n2), tonumber(n3)))
else
-- Match texcoord definitions.
local t1, t2 = string.match(line, "vt%s+([%d%-%.]+)%s+([%d%-%.]+)")
if t1 ~= nil and t2 ~= nil then
table.insert(texcoords, vec2(tonumber(t1), tonumber(t2)))
else
-- Match face definitions.
local oneV, oneT, oneN, twoV, twoT, twoN, threeV, threeT, threeN = string.match(line, "f%s+(%d+)/(%d*)/(%d+)%s+(%d+)/(%d*)/(%d+)%s+(%d+)/(%d*)/(%d+)")
if oneV ~= nil and oneT ~= nil and oneN ~= nil and twoV ~= nil and twoT ~= nil and twoN ~= nil and threeV ~= nil and threeT ~= nil and threeN ~= nil then
if oneT == "" then oneT = "-1" end
if twoT == "" then twoT = "-2" end
if threeT == "" then threeT = "-3" end
table.insert(faces, {
{tonumber(oneV), tonumber(oneT), tonumber(oneN)},
{tonumber(twoV), tonumber(twoT), tonumber(twoN)},
{tonumber(threeV), tonumber(threeT), tonumber(threeN)}
})
end
end
end
end
end
-- Read next line.
line = f:read("*l")
end
f:close()
if adjust then
-- Find the centroid and the min Y.
local centroid = vec3(0, 0, 0)
local minY = vertices[1].y
for _, vertex in ipairs(vertices) do
if vertex.y < minY then
minY = vertex.y
end
centroid = centroid + vertex
end
centroid = centroid / #vertices
local xform = scale(1 / (centroid.y - minY)) * translate(-centroid)
local adjusted = {}
for _, vertex in ipairs(vertices) do
table.insert(adjusted, vec3(xform * vec4(vertex, 1)))
end
vertices = adjusted
end
local mesh = function()
for _, face in ipairs(faces) do
local v1 = translator[face[1][1]]
if v1 == nil then
vertex {
v = vertices[face[1][1]],
n = normals[face[1][1]]
}
v1 = vert_num
vert_num = vert_num + 1
translator[face[1][1]] = v1
end
local v2 = translator[face[2][1]]
if v2 == nil then
vertex {
v = vertices[face[2][1]],
n = normals[face[2][1]]
}
v2 = vert_num
vert_num = vert_num + 1
translator[face[2][1]] = v2
end
local v3 = translator[face[3][1]]
if v3 == nil then
vertex {
v = vertices[face[3][1]],
n = normals[face[3][1]]
}
v3 = vert_num
vert_num = vert_num + 1
translator[face[3][1]] = v3
end
triangle {v1, v2, v3}
end
end
obj_cache[filename] = mesh
return mesh
end
-- Module exports.
return {
obj = obj
}
|
-- Import relevant base types.
local types = require "base.types"
require "base.vec2"
require "base.vec3"
require "base.vec4"
-- Import utility functions.
local transform = require "base.transform"
-- Module aliases.
local vec2 = types.vec2
local vec3 = types.vec3
local vec4 = types.vec4
local scale = transform.scale
local translate = transform.translate
-- Cache for OBJ models.
local obj_cache = {}
-- Loads a mesh in OBJ format, caching it for later reloading.
local function obj(filename, adjust)
if obj_cache[filename] then
return obj_cache[filename]
end
adjust = adjust or false
local vertices = {}
local normals = {}
local texcoords = {}
local faces = {}
local f = assert(io.open(filename, "r"))
local line = f:read("*l")
while line ~= nil do
if string.len(line) == 0 or string.sub(line, 1, 1) == "#" then
-- Ignore, blank line or comment.
else
-- Match vertex definitions.
local v1, v2, v3 = string.match(line, "v%s+([%d%-%.]+)%s+([%d%-%.]+)%s+([%d%-%.]+)")
if v1 ~= nil and v2 ~= nil and v3 ~= nil then
table.insert(vertices, vec3(tonumber(v1), tonumber(v2), tonumber(v3)))
else
-- Match normal definitions.
local n1, n2, n3 = string.match(line, "vn%s+([%d%-%.]+)%s+([%d%-%.]+)%s+([%d%-%.]+)")
if n1 ~= nil and n2 ~= nil and n3 ~= nil then
table.insert(normals, vec3(tonumber(n1), tonumber(n2), tonumber(n3)))
else
-- Match texcoord definitions.
local t1, t2 = string.match(line, "vt%s+([%d%-%.]+)%s+([%d%-%.]+)")
if t1 ~= nil and t2 ~= nil then
table.insert(texcoords, vec2(tonumber(t1), tonumber(t2)))
else
-- Match face definitions.
local oneV, oneT, oneN, twoV, twoT, twoN, threeV, threeT, threeN = string.match(line, "f%s+(%d+)/(%d*)/(%d+)%s+(%d+)/(%d*)/(%d+)%s+(%d+)/(%d*)/(%d+)")
if oneV ~= nil and oneT ~= nil and oneN ~= nil and twoV ~= nil and twoT ~= nil and twoN ~= nil and threeV ~= nil and threeT ~= nil and threeN ~= nil then
if oneT == "" then oneT = "-1" end
if twoT == "" then twoT = "-2" end
if threeT == "" then threeT = "-3" end
table.insert(faces, {
{tonumber(oneV), tonumber(oneT), tonumber(oneN)},
{tonumber(twoV), tonumber(twoT), tonumber(twoN)},
{tonumber(threeV), tonumber(threeT), tonumber(threeN)}
})
end
end
end
end
end
-- Read next line.
line = f:read("*l")
end
f:close()
if adjust then
-- Find the centroid and the min Y.
local centroid = vec3(0, 0, 0)
local minY = vertices[1].y
for _, vertex in ipairs(vertices) do
if vertex.y < minY then
minY = vertex.y
end
centroid = centroid + vertex
end
centroid = centroid / #vertices
local xform = scale(1 / (centroid.y - minY)) * translate(-centroid)
local adjusted = {}
for _, vertex in ipairs(vertices) do
table.insert(adjusted, vec3(xform * vec4(vertex, 1)))
end
vertices = adjusted
end
local mesh = function()
for i, vert in ipairs(vertices) do
vertex {
v = vertices[i],
n = normals[i],
t = texcoords[i]
}
end
for _, face in ipairs(faces) do
local v1 = face[1][1] - 1
local v2 = face[2][1] - 1
local v3 = face[3][1] - 1
triangle {v1, v2, v3}
end
end
obj_cache[filename] = mesh
return mesh
end
-- Module exports.
return {
obj = obj
}
|
Fixed OBJ loading for indexed face sets. Makes some assumptions about the format of the OBJ file.
|
Fixed OBJ loading for indexed face sets. Makes some assumptions about the format of the OBJ file.
|
Lua
|
mit
|
bobsomers/flexrender,bobsomers/flexrender
|
5a244f631846b42306213bb43397ff41d98fbc00
|
.config/nvim/lua/user/cmp.lua
|
.config/nvim/lua/user/cmp.lua
|
local cmp_status_ok, cmp = pcall(require, "cmp")
if not cmp_status_ok then
return
end
local luasnip_ok, luasnip = pcall(require, "luasnip")
if not luasnip_ok then
return
end
local lspkind_ok, lspkind = pcall(require, "lspkind")
if not lspkind_ok then
return
end
-- https://github.com/LunarVim/Neovim-from-scratch/blob/2683495c3df5ee7d3682897e0d47b0facb3cedc9/lua/user/cmp.lua#L13-L16
local check_backspace = function()
local col = vim.fn.col(".") - 1
return col == 0 or vim.fn.getline("."):sub(col, col):match("%s")
end
cmp.setup({
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body)
end,
},
formatting = {
format = lspkind.cmp_format({ preset = "codicons" }),
},
mapping = {
["<C-b>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), { "i", "c" }),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(4), { "i", "c" }),
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
["<C-y>"] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping.
["<C-e>"] = cmp.mapping({
i = cmp.mapping.abort(),
c = cmp.mapping.close(),
}),
["<CR>"] = cmp.mapping.confirm({ select = true }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items.
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expandable() then
luasnip.expand()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif check_backspace() then
fallback()
else
fallback()
end
end, { "i", "s" }),
["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, { "i", "s" }),
},
sources = {
{ name = "nvim_lsp" },
{ name = "nvim_lua" },
{ name = "luasnip" },
{ name = "buffer" },
{ name = "cmp_git" },
{ name = "path" },
},
window = {
documentation = {
border = { "╭", "─", "╮", "│", "╯", "─", "╰", "│" },
}
},
})
local completion_ok, cmp_autopairs = pcall(require, "nvim-autopairs.completion.cmp")
if completion_ok then
cmp.event:on("confirm_done", cmp_autopairs.on_confirm_done({ map_char = { tex = "" } }))
else
return
end
require("cmp_git").setup()
local colors = require("user.utils.colors")
if not colors.loaded then
return
end
-- https://github.com/hrsh7th/nvim-cmp/wiki/Menu-Appearance#how-to-add-visual-studio-code-dark-theme-colors-to-the-menu
--
-- gray
vim.cmd([[highlight! CmpItemAbbrDeprecated guibg=NONE gui=strikethrough guifg=]] .. colors.base03)
-- blue
vim.cmd([[highlight! CmpItemAbbrMatch guibg=NONE guifg=]] .. colors.base0D)
vim.cmd([[highlight! CmpItemAbbrMatchFuzzy guibg=NONE guifg=]] .. colors.base0D)
-- cyan
vim.cmd([[highlight! CmpItemKindVariable guibg=NONE guifg=]] .. colors.base0C)
vim.cmd([[highlight! CmpItemKindInterface guibg=NONE guifg=]] .. colors.base0C)
vim.cmd([[highlight! CmpItemKindText guibg=NONE guifg=]] .. colors.base0C)
-- magenta
vim.cmd([[highlight! CmpItemKindFunction guibg=NONE guifg=]] .. colors.base0E)
vim.cmd([[highlight! CmpItemKindMethod guibg=NONE guifg=]] .. colors.base0E)
-- front
vim.cmd([[highlight! CmpItemKindKeyword guibg=NONE guifg=]] .. colors.base06)
vim.cmd([[highlight! CmpItemKindProperty guibg=NONE guifg=]] .. colors.base06)
vim.cmd([[highlight! CmpItemKindUnit guibg=NONE guifg=]] .. colors.base06)
|
local cmp_status_ok, cmp = pcall(require, "cmp")
if not cmp_status_ok then
return
end
local luasnip_ok, luasnip = pcall(require, "luasnip")
if not luasnip_ok then
return
end
local lspkind_ok, lspkind = pcall(require, "lspkind")
if not lspkind_ok then
return
end
-- https://github.com/LunarVim/Neovim-from-scratch/blob/2683495c3df5ee7d3682897e0d47b0facb3cedc9/lua/user/cmp.lua#L13-L16
local check_backspace = function()
local col = vim.fn.col(".") - 1
return col == 0 or vim.fn.getline("."):sub(col, col):match("%s")
end
cmp.setup({
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body)
end,
},
formatting = {
format = lspkind.cmp_format({ preset = "codicons" }),
},
mapping = cmp.mapping.preset.insert({
["<C-b>"] = cmp.mapping.scroll_docs(-4),
["<C-f>"] = cmp.mapping.scroll_docs(4),
["<C-Space>"] = cmp.mapping.complete(),
["<C-y>"] = cmp.config.disable,
["<CR>"] = cmp.mapping.confirm({ select = true }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items.
["<Tab>"] = function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expandable() then
luasnip.expand()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif check_backspace() then
fallback()
else
fallback()
end
end,
["<S-Tab>"] = function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end
}),
sources = {
{ name = "nvim_lsp" },
{ name = "nvim_lua" },
{ name = "luasnip" },
{ name = "buffer" },
{ name = "cmp_git" },
{ name = "path" },
},
window = {
documentation = {
border = { "╭", "─", "╮", "│", "╯", "─", "╰", "│" },
}
},
})
local completion_ok, cmp_autopairs = pcall(require, "nvim-autopairs.completion.cmp")
if completion_ok then
cmp.event:on("confirm_done", cmp_autopairs.on_confirm_done({ map_char = { tex = "" } }))
else
return
end
require("cmp_git").setup()
local colors = require("user.utils.colors")
if not colors.loaded then
return
end
-- https://github.com/hrsh7th/nvim-cmp/wiki/Menu-Appearance#how-to-add-visual-studio-code-dark-theme-colors-to-the-menu
--
-- gray
vim.cmd([[highlight! CmpItemAbbrDeprecated guibg=NONE gui=strikethrough guifg=]] .. colors.base03)
-- blue
vim.cmd([[highlight! CmpItemAbbrMatch guibg=NONE guifg=]] .. colors.base0D)
vim.cmd([[highlight! CmpItemAbbrMatchFuzzy guibg=NONE guifg=]] .. colors.base0D)
-- cyan
vim.cmd([[highlight! CmpItemKindVariable guibg=NONE guifg=]] .. colors.base0C)
vim.cmd([[highlight! CmpItemKindInterface guibg=NONE guifg=]] .. colors.base0C)
vim.cmd([[highlight! CmpItemKindText guibg=NONE guifg=]] .. colors.base0C)
-- magenta
vim.cmd([[highlight! CmpItemKindFunction guibg=NONE guifg=]] .. colors.base0E)
vim.cmd([[highlight! CmpItemKindMethod guibg=NONE guifg=]] .. colors.base0E)
-- front
vim.cmd([[highlight! CmpItemKindKeyword guibg=NONE guifg=]] .. colors.base06)
vim.cmd([[highlight! CmpItemKindProperty guibg=NONE guifg=]] .. colors.base06)
vim.cmd([[highlight! CmpItemKindUnit guibg=NONE guifg=]] .. colors.base06)
|
Fix https://github.com/hrsh7th/nvim-cmp/issues/231#issuecomment-1098175017
|
Fix https://github.com/hrsh7th/nvim-cmp/issues/231#issuecomment-1098175017
|
Lua
|
isc
|
tarebyte/dotfiles,tarebyte/dotfiles
|
fc4535f7b43defdadffe6c787248cd3f772221fe
|
hammerspoon/tap-modifier-for-hotkey.lua
|
hammerspoon/tap-modifier-for-hotkey.lua
|
local eventtap = require('hs.eventtap')
local events = eventtap.event.types
local modal={}
-- Return an object whose behavior is inspired by hs.hotkey.modal. In this case,
-- the modal state is entered when the specified modifier key is tapped (i.e.,
-- pressed and then released in quick succession).
modal.new = function(modifier)
local instance = {
modifier = modifier,
modalStateTimeoutInSeconds = 1.0,
modalKeybindings = {},
inModalState = false,
reset = function(self)
-- Keep track of the last flags from the three most recent flagsChanged
-- events.
self.flagsHistory = { {}, {}, {} }
self.flagsHistory.push = function(self, flags)
self[1] = self[2]
self[2] = self[3]
self[3] = flags
end
return self
end,
-- Enable the modal
--
-- Mimics hs.modal:enable()
enable = function(self)
self.watcher:start()
end,
-- Disable the modal
--
-- Mimics hs.modal:disable()
disable = function(self)
self.watcher:stop()
self.watcher:reset()
end,
-- Temporarily enter the modal state in which the modal's hotkeys are
-- active. The modal state will terminate after `modalStateTimeoutInSeconds`
-- or after the first keydown event, whichever comes first.
--
-- Mimics hs.modal.modal:enter()
enter = function(self)
self.inModalState = true
self:entered()
self.autoExitTimer:setNextTrigger(self.modalStateTimeoutInSeconds)
end,
-- Exit the modal state in which the modal's hotkey are active
--
-- Mimics hs.modal.modal:exit()
exit = function(self)
if not self.inModalState then return end
self.autoExitTimer:stop()
self.inModalState = false
self:reset()
self:exited()
end,
-- Optional callback for when modal state is entered
--
-- Mimics hs.modal.modal:entered()
entered = function(self) end,
-- Optional callback for when modal state is exited
--
-- Mimics hs.modal.modal:exited()
exited = function(self) end,
-- Bind hotkey that will be enabled/disabled as modal state is
-- entered/exited
bind = function(self, key, fn)
self.modalKeybindings[key] = fn
end,
}
isNoModifiers = function(flags)
local isFalsey = function(value)
return not value
end
return hs.fnutils.every(flags, isFalsey)
end
isOnlyModifier = function(flags)
isPrimaryModiferDown = flags[modifier]
areOtherModifiersDown = hs.fnutils.some(flags, function(isDown, modifierName)
local isPrimaryModifier = modifierName == modifier
return isDown and not isPrimaryModifier
end)
return isPrimaryModiferDown and not areOtherModifiersDown
end
onModifierChange = function(event)
instance.flagsHistory:push(event:getFlags())
local flags3 = instance.flagsHistory[3] -- the current flags
local flags2 = instance.flagsHistory[2] -- the previous flags
local flags1 = instance.flagsHistory[1] -- the flags before the previous flags
-- If we've transitioned from 1) no modifiers being pressed to 2) just the
-- modifier that we care about being pressed, to 3) no modifiers being
-- pressed, then enter the modal state.
if isNoModifiers(flags1) and isOnlyModifier(flags2) and isNoModifiers(flags3) then
instance:enter()
end
-- Allow the event to propagate
return false
end
onKeyDown = function(event)
if instance.inModalState then
local fn = instance.modalKeybindings[event:getCharacters():lower()]
-- Some actions may take a while to perform (e.g., opening Slack when it's
-- not yet running). We don't want to keep the modal state active while we
-- wait for a long-running action to complete. So, we schedule the action
-- to run in the background so that we can exit the modal state and let
-- the user go on about their business.
local delayInSeconds = 0.001 -- 1 millisecond
hs.timer.doAfter(delayInSeconds, function()
if fn then fn() end
end)
instance:exit()
-- Delete the event so that we're the sole consumer of it
return true
else
-- Since we're not in the modal state, this event isn't part of a sequence
-- of events that represents the modifier being tapped, so start over.
instance:reset()
-- Allow the event to propagate
return false
end
end
instance.autoExitTimer = hs.timer.new(0, function() instance:exit() end)
instance.watcher = eventtap.new({events.flagsChanged, events.keyDown},
function(event)
if event:getType() == events.flagsChanged then
return onModifierChange(event)
else
return onKeyDown(event)
end
end
)
return instance:reset()
end
return modal
|
local eventtap = require('hs.eventtap')
local events = eventtap.event.types
local modal={}
-- Return an object whose behavior is inspired by hs.hotkey.modal. In this case,
-- the modal state is entered when the specified modifier key is tapped (i.e.,
-- pressed and then released in quick succession).
modal.new = function(modifier)
local instance = {
modifier = modifier,
modalStateTimeoutInSeconds = 1.0,
modalKeybindings = {},
inModalState = false,
reset = function(self)
-- Keep track of the three most recent events.
self.eventHistory = {
fetch = function(self, index)
if self[index] then
return eventtap.event.newEventFromData(self[index])
end
end,
push = function(self, event)
self[3] = self[2]
self[2] = self[1]
self[1] = event:asData()
end
}
return self
end,
-- Enable the modal
--
-- Mimics hs.modal:enable()
enable = function(self)
self.watcher:start()
end,
-- Disable the modal
--
-- Mimics hs.modal:disable()
disable = function(self)
self.watcher:stop()
self.watcher:reset()
end,
-- Temporarily enter the modal state in which the modal's hotkeys are
-- active. The modal state will terminate after `modalStateTimeoutInSeconds`
-- or after the first keydown event, whichever comes first.
--
-- Mimics hs.modal.modal:enter()
enter = function(self)
self.inModalState = true
self:entered()
self.autoExitTimer:setNextTrigger(self.modalStateTimeoutInSeconds)
end,
-- Exit the modal state in which the modal's hotkey are active
--
-- Mimics hs.modal.modal:exit()
exit = function(self)
if not self.inModalState then return end
self.autoExitTimer:stop()
self.inModalState = false
self:reset()
self:exited()
end,
-- Optional callback for when modal state is entered
--
-- Mimics hs.modal.modal:entered()
entered = function(self) end,
-- Optional callback for when modal state is exited
--
-- Mimics hs.modal.modal:exited()
exited = function(self) end,
-- Bind hotkey that will be enabled/disabled as modal state is
-- entered/exited
bind = function(self, key, fn)
self.modalKeybindings[key] = fn
end,
}
isNoModifiers = function(flags)
local isFalsey = function(value)
return not value
end
return hs.fnutils.every(flags, isFalsey)
end
isOnlyModifier = function(flags)
isPrimaryModiferDown = flags[modifier]
areOtherModifiersDown = hs.fnutils.some(flags, function(isDown, modifierName)
local isPrimaryModifier = modifierName == modifier
return isDown and not isPrimaryModifier
end)
return isPrimaryModiferDown and not areOtherModifiersDown
end
isFlagsChangedEvent = function(event)
return event and event:getType() == events.flagsChanged
end
isFlagsChangedEventWithNoModifiers = function(event)
return isFlagsChangedEvent(event) and isNoModifiers(event:getFlags())
end
isFlagsChangedEventWithOnlyModifier = function(event)
return isFlagsChangedEvent(event) and isOnlyModifier(event:getFlags())
end
instance.autoExitTimer = hs.timer.new(0, function() instance:exit() end)
instance.watcher = eventtap.new({events.flagsChanged, events.keyDown},
function(event)
-- If we're in the modal state, and we got a keydown event, then trigger
-- the function associated with the key.
if (event:getType() == events.keyDown and instance.inModalState) then
local fn = instance.modalKeybindings[event:getCharacters():lower()]
-- Some actions may take a while to perform (e.g., opening Slack when
-- it's not yet running). We don't want to keep the modal state active
-- while we wait for a long-running action to complete. So, we schedule
-- the action to run in the background so that we can exit the modal
-- state and let the user go on about their business.
local delayInSeconds = 0.001 -- 1 millisecond
hs.timer.doAfter(delayInSeconds, function()
if fn then fn() end
end)
instance:exit()
-- Delete the event so that we're the sole consumer of it
return true
end
-- Otherwise, determine if this event should cause us to enter the modal
-- state.
local currentEvent = event
local lastEvent = instance.eventHistory:fetch(1)
local secondToLastEvent = instance.eventHistory:fetch(2)
instance.eventHistory:push(currentEvent)
-- If we've observed the following sequence of events, then enter the
-- modal state:
--
-- 1. No modifiers are down
-- 2. Modifiers changed, and now only the primary modifier is down
-- 3. Modifiers changed, and now no modifiers are down
if (secondToLastEvent == nil or isNoModifiers(secondToLastEvent:getFlags())) and
isFlagsChangedEventWithOnlyModifier(lastEvent) and
isFlagsChangedEventWithNoModifiers(currentEvent) then
instance:enter()
end
-- Let the event propagate
return false
end
)
return instance:reset()
end
return modal
|
🐛 Fix bug where certain sequence would wrongly enter Hyper Mode
|
🐛 Fix bug where certain sequence would wrongly enter Hyper Mode
Fixes the following bug:
1. Hold down option+shift
2. Press left arrow
3. Release shift
4. Release option
5. Observe that it wrongly enters Hyper Mode
|
Lua
|
mit
|
jasonrudolph/keyboard,jasonrudolph/keyboard
|
8b3aafa658610e2f6ecccf3fe4d61ea33c5a202c
|
applications/luci-firewall/luasrc/model/cbi/firewall/zone-details.lua
|
applications/luci-firewall/luasrc/model/cbi/firewall/zone-details.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local ds = require "luci.dispatcher"
local ut = require "luci.util"
local m, p, i, v
local s, name, net, family, msrc, mdest, log, lim
local s2, out, inp
m = Map("firewall", translate("Firewall - Zone Settings"))
m.redirect = luci.dispatcher.build_url("admin/network/firewall/zones")
fw.init(m.uci)
nw.init(m.uci)
local zone = fw:get_zone(arg[1])
if not zone then
luci.http.redirect(dsp.build_url("admin/network/firewall/zones"))
return
else
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", zone:name() or "?")
}
end
s = m:section(NamedSection, zone.sid, "zone",
translatef("Zone %q", zone:name()),
translatef("This section defines common properties of %q. \
The <em>input</em> and <em>output</em> options set the default \
policies for traffic entering and leaving this zone while the \
<em>forward</em> option describes the policy for forwarded traffic \
between different networks within the zone. \
<em>Covered networks</em> specifies which available networks are \
member of this zone.", zone:name()))
s.anonymous = true
s.addremove = false
m.on_commit = function(map)
local zone = fw:get_zone(arg[1])
if zone then
s.section = zone.sid
s2.section = zone.sid
end
end
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
name = s:taboption("general", Value, "name", translate("Name"))
name.optional = false
name.forcewrite = true
name.datatype = "uciname"
function name.write(self, section, value)
if zone:name() ~= value then
fw:rename_zone(zone:name(), value)
out.exclude = value
inp.exclude = value
end
m.redirect = ds.build_url("admin/network/firewall/zones", value)
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", value or "?")
}
end
p = {
s:taboption("general", ListValue, "input", translate("Input")),
s:taboption("general", ListValue, "output", translate("Output")),
s:taboption("general", ListValue, "forward", translate("Forward"))
}
for i, v in ipairs(p) do
v:value("REJECT", translate("reject"))
v:value("DROP", translate("drop"))
v:value("ACCEPT", translate("accept"))
end
s:taboption("general", Flag, "masq", translate("Masquerading"))
s:taboption("general", Flag, "mtu_fix", translate("MSS clamping"))
net = s:taboption("general", Value, "network", translate("Covered networks"))
net.template = "cbi/network_netlist"
net.widget = "checkbox"
net.cast = "string"
function net.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function net.cfgvalue(self, section)
return Value.cfgvalue(self, section) or name:cfgvalue(section)
end
function net.write(self, section, value)
zone:clear_networks()
local n
for n in ut.imatch(value) do
zone:add_network(n)
end
end
family = s:taboption("advanced", ListValue, "family",
translate("Restrict to address family"))
family.rmempty = true
family:value("", translate("IPv4 and IPv6"))
family:value("ipv4", translate("IPv4 only"))
family:value("ipv6", translate("IPv6 only"))
msrc = s:taboption("advanced", DynamicList, "masq_src",
translate("Restrict Masquerading to given source subnets"))
msrc.optional = true
msrc.datatype = "neg_network_ip4addr"
msrc.placeholder = "0.0.0.0/0"
msrc:depends("family", "")
msrc:depends("family", "ipv4")
mdest = s:taboption("advanced", DynamicList, "masq_dest",
translate("Restrict Masquerading to given destination subnets"))
mdest.optional = true
mdest.datatype = "neg_network_ip4addr"
mdest.placeholder = "0.0.0.0/0"
mdest:depends("family", "")
mdest:depends("family", "ipv4")
s:taboption("advanced", Flag, "conntrack",
translate("Force connection tracking"))
log = s:taboption("advanced", Flag, "log",
translate("Enable logging on this zone"))
log.rmempty = true
log.enabled = "1"
lim = s:taboption("advanced", Value, "log_limit",
translate("Limit log messages"))
lim.placeholder = "10/minute"
lim:depends("log", "1")
s2 = m:section(NamedSection, zone.sid, "fwd_out",
translate("Inter-Zone Forwarding"),
translatef("The options below control the forwarding policies between \
this zone (%s) and other zones. <em>Destination zones</em> cover \
forwarded traffic <strong>originating from %q</strong>. \
<em>Source zones</em> match forwarded traffic from other zones \
<strong>targeted at %q</strong>. The forwarding rule is \
<em>unidirectional</em>, e.g. a forward from lan to wan does \
<em>not</em> imply a permission to forward from wan to lan as well.",
zone:name(), zone:name(), zone:name()
))
out = s2:option(Value, "out",
translate("Allow forward to <em>destination zones</em>:"))
out.nocreate = true
out.widget = "checkbox"
out.exclude = zone:name()
out.template = "cbi/firewall_zonelist"
inp = s2:option(Value, "in",
translate("Allow forward from <em>source zones</em>:"))
inp.nocreate = true
inp.widget = "checkbox"
inp.exclude = zone:name()
inp.template = "cbi/firewall_zonelist"
function out.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("src")) do
v[#v+1] = f:dest()
end
return table.concat(v, " ")
end
function inp.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("dest")) do
v[#v+1] = f:src()
end
return v
end
function out.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function inp.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function out.write(self, section, value)
zone:del_forwardings_by("src")
local f
for f in ut.imatch(value) do
zone:add_forwarding_to(f)
end
end
function inp.write(self, section, value)
zone:del_forwardings_by("dest")
local f
for f in ut.imatch(value) do
zone:add_forwarding_from(f)
end
end
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local ds = require "luci.dispatcher"
local ut = require "luci.util"
local m, p, i, v
local s, name, net, family, msrc, mdest, log, lim
local s2, out, inp
m = Map("firewall", translate("Firewall - Zone Settings"))
m.redirect = luci.dispatcher.build_url("admin/network/firewall/zones")
fw.init(m.uci)
nw.init(m.uci)
local zone = fw:get_zone(arg[1])
if not zone then
luci.http.redirect(dsp.build_url("admin/network/firewall/zones"))
return
else
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", zone:name() or "?")
}
end
s = m:section(NamedSection, zone.sid, "zone",
translatef("Zone %q", zone:name()),
translatef("This section defines common properties of %q. \
The <em>input</em> and <em>output</em> options set the default \
policies for traffic entering and leaving this zone while the \
<em>forward</em> option describes the policy for forwarded traffic \
between different networks within the zone. \
<em>Covered networks</em> specifies which available networks are \
member of this zone.", zone:name()))
s.anonymous = true
s.addremove = false
m.on_commit = function(map)
local zone = fw:get_zone(arg[1])
if zone then
s.section = zone.sid
s2.section = zone.sid
end
end
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
name = s:taboption("general", Value, "name", translate("Name"))
name.optional = false
name.forcewrite = true
name.datatype = "uciname"
function name.write(self, section, value)
if zone:name() ~= value then
fw:rename_zone(zone:name(), value)
out.exclude = value
inp.exclude = value
end
m.redirect = ds.build_url("admin/network/firewall/zones", value)
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", value or "?")
}
end
p = {
s:taboption("general", ListValue, "input", translate("Input")),
s:taboption("general", ListValue, "output", translate("Output")),
s:taboption("general", ListValue, "forward", translate("Forward"))
}
for i, v in ipairs(p) do
v:value("REJECT", translate("reject"))
v:value("DROP", translate("drop"))
v:value("ACCEPT", translate("accept"))
end
s:taboption("general", Flag, "masq", translate("Masquerading"))
s:taboption("general", Flag, "mtu_fix", translate("MSS clamping"))
net = s:taboption("general", Value, "network", translate("Covered networks"))
net.template = "cbi/network_netlist"
net.widget = "checkbox"
net.cast = "string"
function net.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function net.cfgvalue(self, section)
return Value.cfgvalue(self, section) or name:cfgvalue(section)
end
function net.write(self, section, value)
zone:clear_networks()
local n
for n in ut.imatch(value) do
zone:add_network(n)
end
end
family = s:taboption("advanced", ListValue, "family",
translate("Restrict to address family"))
family.rmempty = true
family:value("", translate("IPv4 and IPv6"))
family:value("ipv4", translate("IPv4 only"))
family:value("ipv6", translate("IPv6 only"))
msrc = s:taboption("advanced", DynamicList, "masq_src",
translate("Restrict Masquerading to given source subnets"))
msrc.optional = true
msrc.datatype = "list(neg,network)"
msrc.placeholder = "0.0.0.0/0"
msrc:depends("family", "")
msrc:depends("family", "ipv4")
mdest = s:taboption("advanced", DynamicList, "masq_dest",
translate("Restrict Masquerading to given destination subnets"))
mdest.optional = true
mdest.datatype = "list(neg,network)"
mdest.placeholder = "0.0.0.0/0"
mdest:depends("family", "")
mdest:depends("family", "ipv4")
s:taboption("advanced", Flag, "conntrack",
translate("Force connection tracking"))
log = s:taboption("advanced", Flag, "log",
translate("Enable logging on this zone"))
log.rmempty = true
log.enabled = "1"
lim = s:taboption("advanced", Value, "log_limit",
translate("Limit log messages"))
lim.placeholder = "10/minute"
lim:depends("log", "1")
s2 = m:section(NamedSection, zone.sid, "fwd_out",
translate("Inter-Zone Forwarding"),
translatef("The options below control the forwarding policies between \
this zone (%s) and other zones. <em>Destination zones</em> cover \
forwarded traffic <strong>originating from %q</strong>. \
<em>Source zones</em> match forwarded traffic from other zones \
<strong>targeted at %q</strong>. The forwarding rule is \
<em>unidirectional</em>, e.g. a forward from lan to wan does \
<em>not</em> imply a permission to forward from wan to lan as well.",
zone:name(), zone:name(), zone:name()
))
out = s2:option(Value, "out",
translate("Allow forward to <em>destination zones</em>:"))
out.nocreate = true
out.widget = "checkbox"
out.exclude = zone:name()
out.template = "cbi/firewall_zonelist"
inp = s2:option(Value, "in",
translate("Allow forward from <em>source zones</em>:"))
inp.nocreate = true
inp.widget = "checkbox"
inp.exclude = zone:name()
inp.template = "cbi/firewall_zonelist"
function out.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("src")) do
v[#v+1] = f:dest()
end
return table.concat(v, " ")
end
function inp.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("dest")) do
v[#v+1] = f:src()
end
return v
end
function out.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function inp.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function out.write(self, section, value)
zone:del_forwardings_by("src")
local f
for f in ut.imatch(value) do
zone:add_forwarding_to(f)
end
end
function inp.write(self, section, value)
zone:del_forwardings_by("dest")
local f
for f in ut.imatch(value) do
zone:add_forwarding_from(f)
end
end
return m
|
applications/luci-firewall: fix datatype validation for masq src/dest; allow list of negated ucinames, hostnames, ip-ranges or -addresses
|
applications/luci-firewall: fix datatype validation for masq src/dest; allow list of negated ucinames, hostnames, ip-ranges or -addresses
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci
|
e17b5ef40f5b5e386363ea0db38d888552a5f6de
|
MMOCoreORB/bin/scripts/screenplays/poi/naboo_gungan_temple.lua
|
MMOCoreORB/bin/scripts/screenplays/poi/naboo_gungan_temple.lua
|
GunganTempleScreenPlay = ScreenPlay:new {
numberOfActs = 1,
screenplayName = "GunganTempleScreenPlay",
lootContainers = {
6336300,
261337,
261336
},
lootLevel = 17,
lootGroups = {
{
groups = {
{group = "junk", chance = 8600000},
{group = "rifles", chance = 500000},
{group = "pistols", chance = 500000},
{group = "clothing_attachments", chance = 100000},
{group = "armor_attachments", chance = 100000}
},
lootChance = 8000000
}
},
lootContainerRespawn = 1800 -- 30 minutes
}
registerScreenPlay("GunganTempleScreenPlay", true)
function GunganTempleScreenPlay:start()
if (isZoneEnabled("naboo")) then
self:spawnMobiles()
self:initializeLootContainers()
end
end
function GunganTempleScreenPlay:spawnMobiles()
--Exterior of double Wall NW (4)
spawnMobile("naboo", "gungan_scout",210,-313.1,10.1,2861.2,-24,0)
spawnMobile("naboo", "gungan_scout",210,-309.3,10.4,2868.8,0,0)
spawnMobile("naboo", "gungan_scout",210,-314.9,10.9,2860,-144,0)
spawnMobile("naboo", "gungan_scout",210,-315.3,10.3,2861.1,-99,0)
--Exterior of double Wall N W.Side (4)
spawnMobile("naboo", "gungan_scout",210,-299.7,10.7,2864.1,-20,0)
spawnMobile("naboo", "gungan_scout",210,-291.9,11.1,2864.4,-38,0)
spawnMobile("naboo", "gungan_scout",210,-284.3,11.2,2866.4,-6,0)
spawnMobile("naboo", "gungan_scout",210,-282.3,11.4,2865.2,21,0)
--Exterior of double Wall Center Entrance (3)
spawnMobile("naboo", "gungan_captain",210,-267.3,12.2,2858.4,0,0)
spawnMobile("naboo", "gungan_guard",210,-269.1,11.9,2862.3,-3,0)
spawnMobile("naboo", "gungan_guard",210,-263.8,12.0,2862.0,8,0)
--Exterior of double Wall N E.Side (3)
spawnMobile("naboo", "gungan_scout",210,-255.4,12.0,2862.9,-9,0)
spawnMobile("naboo", "gungan_scout",210,-246.7,11.7,2867.9,-38,0)
spawnMobile("naboo", "gungan_scout",210,-243.0,11.9,2864.1,12,0)
--Exterior of double Wall NE (4)
spawnMobile("naboo", "gungan_scout",210,-214.6,11.6,2864.2,-74,0)
spawnMobile("naboo", "gungan_scout",210,-211.8,11.5,2866.5,10,0)
spawnMobile("naboo", "gungan_scout",210,-206.7,11.7,2862.5,130,0)
spawnMobile("naboo", "gungan_scout",210,-207.9,11.7,2859.1,162,0)
--Exterior of Double Wall E Gaps (5)
spawnMobile("naboo", "gungan_scout",210,-208.0,12.1,2844.0,110,0)
spawnMobile("naboo", "gungan_scout",210,-206.9,15.1,2836.2,51,0)
spawnMobile("naboo", "gungan_scout",210,-208.6,11.0,2808.4,56,0)
spawnMobile("naboo", "gungan_scout",210,-205.4,7.1,2802.9,70,0)
spawnMobile("naboo", "gungan_scout",210,-205.7,10.4,2792.2,121,0)
--Exterior of double Wall SE (4)
spawnMobile("naboo", "gungan_scout",210,-208.7,10.0,2763.1,32,0)
spawnMobile("naboo", "gungan_scout",210,-205.4,9.9,2764.1,73,0)
spawnMobile("naboo", "gungan_scout",210,-209.8,9.9,2757.9,-144,0)
spawnMobile("naboo", "gungan_scout",210,-206.2,9.8,2757.4,102,0)
--Exterior of double Wall SW (3)
spawnMobile("naboo", "gungan_scout",210,-313.7,13.5,2768.3,-50,0)
spawnMobile("naboo", "gungan_scout",210,-307.2,12.8,2758.5,120,0)
spawnMobile("naboo", "gungan_scout",210,-314.4,13.2,2755.7,-113,0)
-- Double Wall N (3)
spawnMobile("naboo", "gungan_scout",210,-305.5,11.0,2857.3,90,0)
spawnMobile("naboo", "gungan_scout",210,-281.8,12.0,2856.3,-91,0)
spawnMobile("naboo", "gungan_scout",210,-230.1,12.3,2856.1,1,0)
-- Double Wall E (3)
spawnMobile("naboo", "gungan_scout",210,-216.4,12.4,2843.2,90,0)
spawnMobile("naboo", "gungan_scout",210,-216.9,8.2,2792.7,31,0)
spawnMobile("naboo", "gungan_scout",210,-216.8,10.4,2770.4,-8,0)
-- Double Wall S (3)
spawnMobile("naboo", "gungan_scout",210,-233.3,10.8,2768.0,157,0)
spawnMobile("naboo", "gungan_scout",210,-259.5,11.3,2764.6,65,0)
spawnMobile("naboo", "gungan_scout",210,-278.7,11.7,2766.6,175,0)
-- Double Wall W (3)
spawnMobile("naboo", "gungan_scout",210,-303.5,12.8,2767.6,49,0)
spawnMobile("naboo", "gungan_scout",210,-305.2,12.9,2807.9,-95,0)
spawnMobile("naboo", "gungan_scout",210,-303.5,11.9,2839.6,-179,0)
-- Inside Double Wall NW (3)
spawnMobile("naboo", "gungan_guard",210,-291.4,12.2,2844.8,-3,0)
spawnMobile("naboo", "gungan_guard",210,-276.7,12.7,2840.3,32,0)
spawnMobile("naboo", "gungan_guard",210,-281.4,12.8,2826.0,160,0)
-- Inside Double Wall NE (3)
spawnMobile("naboo", "gungan_guard",210,-229.5,12.6,2846.8,89,0)
spawnMobile("naboo", "gungan_guard",210,-227.3,12.6,2833.3,170,0)
spawnMobile("naboo", "gungan_guard",210,-249.2,12.9,2840.9,-34,0)
-- Inside Double Wall SW (3)
spawnMobile("naboo", "gungan_guard",210,-275.1,12.0,2778.9,-80,0)
spawnMobile("naboo", "gungan_guard",210,-296.4,12.8,2779.6,-165,0)
spawnMobile("naboo", "gungan_guard",210,-285.7,12.6,2789.3,172,0)
-- Inside Double Wall SE (3)
spawnMobile("naboo", "gungan_guard",210,-221.2,10.7,2777.6,126,0)
spawnMobile("naboo", "gungan_guard",210,-235.9,7.8,2774.4,-143,0)
spawnMobile("naboo", "gungan_guard",210,-245.8,11.5,2781.0,34,0)
-- Top Of Temple (4)
spawnMobile("naboo", "gungan_guard",210,-259.9,28.2,2800.9,-47,0)
spawnMobile("naboo", "gungan_guard",210,-268.3,28.2,2800.8,39,0)
spawnMobile("naboo", "gungan_priest",210,-264.4,28.2,2795.1,-46,0)
spawnMobile("naboo", "gungan_captain",210,-264.1,28.2,2803.1,-4,0)
-- Front of Temple Gungan Defenders TODO AI(Future Defenders)
spawnMobile("naboo", "gungan_captain",210,-265.4,13.0,2833.1,1,0)
spawnMobile("naboo", "gungan_boss",210,-262.5,13.0,2833.1,0,0)
spawnMobile("naboo", "gungan_captain",210,-259.7,13.0,2833.1,-6,0)
spawnMobile("naboo", "gungan_guard",150,-262.9,12.9,2840.3,-2,0)
spawnMobile("naboo", "gungan_guard",140,-258.6,12.9,2844.1,-15,0)
spawnMobile("naboo", "gungan_guard",130,-261.9,12.9,2843.9,-2,0)
spawnMobile("naboo", "gungan_guard",150,-266.1,12.9,2843.1,4,0)
spawnMobile("naboo", "gungan_guard",150,-269.3,12.6,2849.1,5,0)
spawnMobile("naboo", "gungan_guard",130,-265.5,12.7,2848.8,8,0)
spawnMobile("naboo", "gungan_guard",130,-260.8,12.8,2848.5,-12,0)
--Imperial troops Outside Attackers TODO AI(future Attackers)
spawnMobile("naboo", "imperial_corporal",210,-276.4,10.0,2881.3,170,0)
spawnMobile("naboo", "imperial_corporal",210,-260.3,11.0,2875.2,-167,0)
spawnMobile("naboo", "imperial_army_captain",180,-270.7,8.6,2892.6,172,0)
spawnMobile("naboo", "imperial_trooper",150,-277.1,10.3,2878.8,171,0)
spawnMobile("naboo", "imperial_trooper",150,-271.5,10.4,2879.3,168,0)
spawnMobile("naboo", "imperial_trooper",150,-266.3,10.4,2874.4,-169,0)
spawnMobile("naboo", "imperial_trooper",150,-261.9,10.4,2880.7,-169,0)
spawnMobile("naboo", "imperial_trooper",150,-265.5,10.0,2883.7,-169,0)
spawnMobile("naboo", "imperial_trooper",150,-270.7,9.9,2882.9,0,0)
spawnMobile("naboo", "imperial_trooper",150,-273.9,10.0,2882.1,168,0)
end
|
GunganTempleScreenPlay = ScreenPlay:new {
numberOfActs = 1,
screenplayName = "GunganTempleScreenPlay",
lootContainers = {
6336300,
261337,
261336
},
lootLevel = 17,
lootGroups = {
{
groups = {
{group = "color_crystals", chance = 3500000},
{group = "junk", chance = 3500000},
{group = "rifles", chance = 1000000},
{group = "pistols", chance = 1000000},
{group = "clothing_attachments", chance = 500000},
{group = "armor_attachments", chance = 500000}
},
lootChance = 8000000
}
},
lootContainerRespawn = 1800 -- 30 minutes
}
registerScreenPlay("GunganTempleScreenPlay", true)
function GunganTempleScreenPlay:start()
if (isZoneEnabled("naboo")) then
self:spawnMobiles()
self:initializeLootContainers()
end
end
function GunganTempleScreenPlay:spawnMobiles()
--Exterior of double Wall NW (4)
spawnMobile("naboo", "gungan_scout",210,-313.1,10.1,2861.2,-24,0)
spawnMobile("naboo", "gungan_scout",210,-309.3,10.4,2868.8,0,0)
spawnMobile("naboo", "gungan_scout",210,-314.9,10.9,2860,-144,0)
spawnMobile("naboo", "gungan_scout",210,-315.3,10.3,2861.1,-99,0)
--Exterior of double Wall N W.Side (4)
spawnMobile("naboo", "gungan_scout",210,-299.7,10.7,2864.1,-20,0)
spawnMobile("naboo", "gungan_scout",210,-291.9,11.1,2864.4,-38,0)
spawnMobile("naboo", "gungan_scout",210,-284.3,11.2,2866.4,-6,0)
spawnMobile("naboo", "gungan_scout",210,-282.3,11.4,2865.2,21,0)
--Exterior of double Wall Center Entrance (3)
spawnMobile("naboo", "gungan_captain",210,-267.3,12.2,2858.4,0,0)
spawnMobile("naboo", "gungan_guard",210,-269.1,11.9,2862.3,-3,0)
spawnMobile("naboo", "gungan_guard",210,-263.8,12.0,2862.0,8,0)
--Exterior of double Wall N E.Side (3)
spawnMobile("naboo", "gungan_scout",210,-255.4,12.0,2862.9,-9,0)
spawnMobile("naboo", "gungan_scout",210,-246.7,11.7,2867.9,-38,0)
spawnMobile("naboo", "gungan_scout",210,-243.0,11.9,2864.1,12,0)
--Exterior of double Wall NE (4)
spawnMobile("naboo", "gungan_scout",210,-214.6,11.6,2864.2,-74,0)
spawnMobile("naboo", "gungan_scout",210,-211.8,11.5,2866.5,10,0)
spawnMobile("naboo", "gungan_scout",210,-206.7,11.7,2862.5,130,0)
spawnMobile("naboo", "gungan_scout",210,-207.9,11.7,2859.1,162,0)
--Exterior of Double Wall E Gaps (5)
spawnMobile("naboo", "gungan_scout",210,-208.0,12.1,2844.0,110,0)
spawnMobile("naboo", "gungan_scout",210,-206.9,15.1,2836.2,51,0)
spawnMobile("naboo", "gungan_scout",210,-208.6,11.0,2808.4,56,0)
spawnMobile("naboo", "gungan_scout",210,-205.4,7.1,2802.9,70,0)
spawnMobile("naboo", "gungan_scout",210,-205.7,10.4,2792.2,121,0)
--Exterior of double Wall SE (4)
spawnMobile("naboo", "gungan_scout",210,-208.7,10.0,2763.1,32,0)
spawnMobile("naboo", "gungan_scout",210,-205.4,9.9,2764.1,73,0)
spawnMobile("naboo", "gungan_scout",210,-209.8,9.9,2757.9,-144,0)
spawnMobile("naboo", "gungan_scout",210,-206.2,9.8,2757.4,102,0)
--Exterior of double Wall SW (3)
spawnMobile("naboo", "gungan_scout",210,-313.7,13.5,2768.3,-50,0)
spawnMobile("naboo", "gungan_scout",210,-307.2,12.8,2758.5,120,0)
spawnMobile("naboo", "gungan_scout",210,-314.4,13.2,2755.7,-113,0)
-- Double Wall N (3)
spawnMobile("naboo", "gungan_scout",210,-305.5,11.0,2857.3,90,0)
spawnMobile("naboo", "gungan_scout",210,-281.8,12.0,2856.3,-91,0)
spawnMobile("naboo", "gungan_scout",210,-230.1,12.3,2856.1,1,0)
-- Double Wall E (3)
spawnMobile("naboo", "gungan_scout",210,-216.4,12.4,2843.2,90,0)
spawnMobile("naboo", "gungan_scout",210,-216.9,8.2,2792.7,31,0)
spawnMobile("naboo", "gungan_scout",210,-216.8,10.4,2770.4,-8,0)
-- Double Wall S (3)
spawnMobile("naboo", "gungan_scout",210,-233.3,10.8,2768.0,157,0)
spawnMobile("naboo", "gungan_scout",210,-259.5,11.3,2764.6,65,0)
spawnMobile("naboo", "gungan_scout",210,-278.7,11.7,2766.6,175,0)
-- Double Wall W (3)
spawnMobile("naboo", "gungan_scout",210,-303.5,12.8,2767.6,49,0)
spawnMobile("naboo", "gungan_scout",210,-305.2,12.9,2807.9,-95,0)
spawnMobile("naboo", "gungan_scout",210,-303.5,11.9,2839.6,-179,0)
-- Inside Double Wall NW (3)
spawnMobile("naboo", "gungan_guard",210,-291.4,12.2,2844.8,-3,0)
spawnMobile("naboo", "gungan_guard",210,-276.7,12.7,2840.3,32,0)
spawnMobile("naboo", "gungan_guard",210,-281.4,12.8,2826.0,160,0)
-- Inside Double Wall NE (3)
spawnMobile("naboo", "gungan_guard",210,-229.5,12.6,2846.8,89,0)
spawnMobile("naboo", "gungan_guard",210,-227.3,12.6,2833.3,170,0)
spawnMobile("naboo", "gungan_guard",210,-249.2,12.9,2840.9,-34,0)
-- Inside Double Wall SW (3)
spawnMobile("naboo", "gungan_guard",210,-275.1,12.0,2778.9,-80,0)
spawnMobile("naboo", "gungan_guard",210,-296.4,12.8,2779.6,-165,0)
spawnMobile("naboo", "gungan_guard",210,-285.7,12.6,2789.3,172,0)
-- Inside Double Wall SE (3)
spawnMobile("naboo", "gungan_guard",210,-221.2,10.7,2777.6,126,0)
spawnMobile("naboo", "gungan_guard",210,-235.9,7.8,2774.4,-143,0)
spawnMobile("naboo", "gungan_guard",210,-245.8,11.5,2781.0,34,0)
-- Top Of Temple (4)
spawnMobile("naboo", "gungan_guard",210,-259.9,28.2,2800.9,-47,0)
spawnMobile("naboo", "gungan_guard",210,-268.3,28.2,2800.8,39,0)
spawnMobile("naboo", "gungan_priest",210,-264.4,28.2,2795.1,-46,0)
spawnMobile("naboo", "gungan_captain",210,-264.1,28.2,2803.1,-4,0)
-- Front of Temple Gungan Defenders TODO AI(Future Defenders)
spawnMobile("naboo", "gungan_captain",210,-265.4,13.0,2833.1,1,0)
spawnMobile("naboo", "gungan_boss",210,-262.5,13.0,2833.1,0,0)
spawnMobile("naboo", "gungan_captain",210,-259.7,13.0,2833.1,-6,0)
spawnMobile("naboo", "gungan_guard",150,-262.9,12.9,2840.3,-2,0)
spawnMobile("naboo", "gungan_guard",140,-258.6,12.9,2844.1,-15,0)
spawnMobile("naboo", "gungan_guard",130,-261.9,12.9,2843.9,-2,0)
spawnMobile("naboo", "gungan_guard",150,-266.1,12.9,2843.1,4,0)
spawnMobile("naboo", "gungan_guard",150,-269.3,12.6,2849.1,5,0)
spawnMobile("naboo", "gungan_guard",130,-265.5,12.7,2848.8,8,0)
spawnMobile("naboo", "gungan_guard",130,-260.8,12.8,2848.5,-12,0)
--Imperial troops Outside Attackers TODO AI(future Attackers)
spawnMobile("naboo", "imperial_corporal",210,-276.4,10.0,2881.3,170,0)
spawnMobile("naboo", "imperial_corporal",210,-260.3,11.0,2875.2,-167,0)
spawnMobile("naboo", "imperial_army_captain",180,-270.7,8.6,2892.6,172,0)
spawnMobile("naboo", "imperial_trooper",150,-277.1,10.3,2878.8,171,0)
spawnMobile("naboo", "imperial_trooper",150,-271.5,10.4,2879.3,168,0)
spawnMobile("naboo", "imperial_trooper",150,-266.3,10.4,2874.4,-169,0)
spawnMobile("naboo", "imperial_trooper",150,-261.9,10.4,2880.7,-169,0)
spawnMobile("naboo", "imperial_trooper",150,-265.5,10.0,2883.7,-169,0)
spawnMobile("naboo", "imperial_trooper",150,-270.7,9.9,2882.9,0,0)
spawnMobile("naboo", "imperial_trooper",150,-273.9,10.0,2882.1,168,0)
end
|
[Fixed] Naboo Gungan Temple lootgroups.
|
[Fixed] Naboo Gungan Temple lootgroups.
Change-Id: I26b84bd2003bef3a1c940bba2d962d202b5ba85f
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/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,Tatwi/legend-of-hondo
|
39000670269bcdc02d6d1069b58477ff0c6e3755
|
lualib/skynet/cluster.lua
|
lualib/skynet/cluster.lua
|
local skynet = require "skynet"
local clusterd
local cluster = {}
local sender = {}
local task_queue = {}
local function request_sender(q, node)
local ok, c = pcall(skynet.call, clusterd, "lua", "sender", node)
if not ok then
skynet.error(c)
c = nil
end
-- run tasks in queue
local confirm = coroutine.running()
q.confirm = confirm
q.sender = c
for _, task in ipairs(q) do
if type(task) == "table" then
if c then
skynet.send(c, "lua", "push", task[1], skynet.pack(table.unpack(task,2,task.n)))
end
else
skynet.wakeup(task)
skynet.wait(confirm)
end
end
task_queue[node] = nil
sender[node] = c
end
local function get_queue(t, node)
local q = {}
t[node] = q
skynet.fork(request_sender, q, node)
return q
end
setmetatable(task_queue, { __index = get_queue } )
local function get_sender(node)
local s = sender[node]
if not s then
local q = task_queue[node]
local task = coroutine.running()
table.insert(q, task)
skynet.wait(task)
skynet.wakeup(q.confirm)
return q.sender
end
return s
end
function cluster.call(node, address, ...)
-- skynet.pack(...) will free by cluster.core.packrequest
return skynet.call(get_sender(node), "lua", "req", address, skynet.pack(...))
end
function cluster.send(node, address, ...)
-- push is the same with req, but no response
local s = sender[node]
if not s then
table.insert(task_queue[node], table.pack(address, ...))
else
skynet.send(sender[node], "lua", "push", address, skynet.pack(...))
end
end
function cluster.open(port)
if type(port) == "string" then
skynet.call(clusterd, "lua", "listen", port)
else
skynet.call(clusterd, "lua", "listen", "0.0.0.0", port)
end
end
function cluster.reload(config)
skynet.call(clusterd, "lua", "reload", config)
end
function cluster.proxy(node, name)
return skynet.call(clusterd, "lua", "proxy", node, name)
end
function cluster.snax(node, name, address)
local snax = require "skynet.snax"
if not address then
address = cluster.call(node, ".service", "QUERY", "snaxd" , name)
end
local handle = skynet.call(clusterd, "lua", "proxy", node, address)
return snax.bind(handle, name)
end
function cluster.register(name, addr)
assert(type(name) == "string")
assert(addr == nil or type(addr) == "number")
return skynet.call(clusterd, "lua", "register", name, addr)
end
function cluster.query(node, name)
return skynet.call(get_sender(node), "lua", "req", 0, skynet.pack(name))
end
skynet.init(function()
clusterd = skynet.uniqueservice("clusterd")
end)
return cluster
|
local skynet = require "skynet"
local clusterd
local cluster = {}
local sender = {}
local task_queue = {}
local function repack(address, ...)
return address, skynet.pack(...)
end
local function request_sender(q, node)
local ok, c = pcall(skynet.call, clusterd, "lua", "sender", node)
if not ok then
skynet.error(c)
c = nil
end
-- run tasks in queue
local confirm = coroutine.running()
q.confirm = confirm
q.sender = c
for _, task in ipairs(q) do
if type(task) == "string" then
if c then
skynet.send(c, "lua", "push", repack(skynet.unpack(task)))
end
else
skynet.wakeup(task)
skynet.wait(confirm)
end
end
task_queue[node] = nil
sender[node] = c
end
local function get_queue(t, node)
local q = {}
t[node] = q
skynet.fork(request_sender, q, node)
return q
end
setmetatable(task_queue, { __index = get_queue } )
local function get_sender(node)
local s = sender[node]
if not s then
local q = task_queue[node]
local task = coroutine.running()
table.insert(q, task)
skynet.wait(task)
skynet.wakeup(q.confirm)
return q.sender
end
return s
end
function cluster.call(node, address, ...)
-- skynet.pack(...) will free by cluster.core.packrequest
local s = sender[node]
if not s then
local task = skynet.packstring(address, ...)
return skynet.call(get_sender(node), "lua", "req", repack(skynet.unpack(task)))
end
return skynet.call(s, "lua", "req", address, skynet.pack(...))
end
function cluster.send(node, address, ...)
-- push is the same with req, but no response
local s = sender[node]
if not s then
table.insert(task_queue[node], skynet.packstring(address, ...))
else
skynet.send(sender[node], "lua", "push", address, skynet.pack(...))
end
end
function cluster.open(port)
if type(port) == "string" then
skynet.call(clusterd, "lua", "listen", port)
else
skynet.call(clusterd, "lua", "listen", "0.0.0.0", port)
end
end
function cluster.reload(config)
skynet.call(clusterd, "lua", "reload", config)
end
function cluster.proxy(node, name)
return skynet.call(clusterd, "lua", "proxy", node, name)
end
function cluster.snax(node, name, address)
local snax = require "skynet.snax"
if not address then
address = cluster.call(node, ".service", "QUERY", "snaxd" , name)
end
local handle = skynet.call(clusterd, "lua", "proxy", node, address)
return snax.bind(handle, name)
end
function cluster.register(name, addr)
assert(type(name) == "string")
assert(addr == nil or type(addr) == "number")
return skynet.call(clusterd, "lua", "register", name, addr)
end
function cluster.query(node, name)
return skynet.call(get_sender(node), "lua", "req", 0, skynet.pack(name))
end
skynet.init(function()
clusterd = skynet.uniqueservice("clusterd")
end)
return cluster
|
bugfix:params changed when cluster sender is connecting (#1420)
|
bugfix:params changed when cluster sender is connecting (#1420)
Co-authored-by: LiuYang <85643b79448ff954b27e65db9f04fb610bf84c45@alibaba-inc.com>
|
Lua
|
mit
|
xjdrew/skynet,xjdrew/skynet,cloudwu/skynet,wangyi0226/skynet,korialuo/skynet,cloudwu/skynet,hongling0/skynet,sanikoyes/skynet,hongling0/skynet,korialuo/skynet,cloudwu/skynet,icetoggle/skynet,wangyi0226/skynet,icetoggle/skynet,sanikoyes/skynet,sanikoyes/skynet,xjdrew/skynet,icetoggle/skynet,korialuo/skynet,wangyi0226/skynet,hongling0/skynet
|
6c10d80dcfa1318aeb1f64a97bfd28caa06f4761
|
src/core.lua
|
src/core.lua
|
-- return truthy if we're in a coroutine
local function in_coroutine()
local current_routine, main = coroutine.running()
-- need check to the main variable for 5.2, it's nil for 5.1
return current_routine and (main == nil or main == false)
end
local busted = {
root_context = { type = "describe", description = "global" },
options = {},
__call = function(self)
self.output = self.options.output
--run test
local function test(description, callback)
local debug_info = debug.getinfo(callback)
local info = {
source = debug_info.source,
short_src = debug_info.short_src,
linedefined = debug_info.linedefined,
}
local stack_trace = ""
local function err_handler(err)
stack_trace = debug.traceback("", 4)
return err
end
local status, err = xpcall(callback, err_handler)
local test_status = {}
if not status then
test_status = { type = "failure", description = description, info = info, trace = stack_trace, err = err }
else
test_status = { type = "success", description = description, info = info }
end
if not self.options.defer_print then
self.output.currently_executing(test_status, self.options)
end
return test_status
end
-- run setup/teardown
local function run_setup(context, stype)
if not context[stype] then
return true
else
local result = test("Failed running test initializer '"..stype.."'", context[stype])
return (result.type == "success"), result
end
end
--run test case
local function run_context(context)
local match = false
if self.options.tags and #self.options.tags > 0 then
for i,t in ipairs(self.options.tags) do
if context.description:find("#"..t) then
match = true
end
end
else
match = true
end
local status = { description = context.description, type = "description", run = match }
local setup_ok, setup_error
setup_ok, setup_error = run_setup(context, "setup")
if setup_ok then
for i,v in ipairs(context) do
setup_ok, setup_error = run_setup(context, "before_each")
if not setup_ok then break end
if v.type == "test" then
table.insert(status, test(v.description, v.callback))
elseif v.type == "describe" then
table.insert(status, coroutine.create(function() run_context(v) end))
elseif v.type == "pending" then
local pending_test_status = { type = "pending", description = v.description, info = v.info }
v.callback(pending_test_status)
table.insert(status, pending_test_status)
end
setup_ok, setup_error = run_setup(context, "after_each")
if not setup_ok then break end
end
end
if setup_ok then setup_ok, setup_error = run_setup(context, "teardown") end
if not setup_ok then table.insert(status, setup_error) end
if in_coroutine() then
coroutine.yield(status)
else
return true, status
end
end
local play_sound = function(failures)
math.randomseed(os.time())
if self.options.failure_messages and #self.options.failure_messages > 0 and
self.options.success_messages and #self.options.success_messages > 0 then
if failures and failures > 0 then
io.popen("say \""..failure_messages[math.random(1, #failure_messages)]:format(failures).."\"")
else
io.popen("say \""..success_messages[math.random(1, #success_messages)].."\"")
end
end
end
local ms = os.clock()
if not self.options.defer_print then
print(self.output.header(self.root_context))
end
--fire off tests, return status list
local function get_statuses(done, list)
local ret = {}
for i,v in pairs(list) do
local vtype = type(v)
if vtype == "thread" then
local res = get_statuses(coroutine.resume(v))
for key,value in pairs(res) do
table.insert(ret, value)
end
elseif vtype == "table" then
table.insert(ret, v)
end
end
return ret
end
local statuses = get_statuses(run_context(self.root_context))
--final run time
ms = os.clock() - ms
if self.options.defer_print then
print(self.output.header(self.root_context))
end
local status_string = self.output.formatted_status(statuses, self.options, ms)
if self.options.sound then
play_sound(failures)
end
return status_string
end
}
return setmetatable(busted, busted)
|
-- return truthy if we're in a coroutine
local function in_coroutine()
local current_routine, main = coroutine.running()
-- need check to the main variable for 5.2, it's nil for 5.1
return current_routine and (main == nil or main == false)
end
local busted = {
root_context = { type = "describe", description = "global" },
options = {},
__call = function(self)
self.output = self.options.output
--run test
local function test(description, callback, no_output)
local debug_info = debug.getinfo(callback)
local info = {
source = debug_info.source,
short_src = debug_info.short_src,
linedefined = debug_info.linedefined,
}
local stack_trace = ""
local function err_handler(err)
stack_trace = debug.traceback("", 4)
return err
end
local status, err = xpcall(callback, err_handler)
local test_status = {}
if not status then
test_status = { type = "failure", description = description, info = info, trace = stack_trace, err = err }
else
test_status = { type = "success", description = description, info = info }
end
if not no_output and not self.options.defer_print then
self.output.currently_executing(test_status, self.options)
end
return test_status
end
-- run setup/teardown
local function run_setup(context, stype)
if not context[stype] then
return true
else
local result = test("Failed running test initializer '"..stype.."'", context[stype], true)
return (result.type == "success"), result
end
end
--run test case
local function run_context(context)
local match = false
if self.options.tags and #self.options.tags > 0 then
for i,t in ipairs(self.options.tags) do
if context.description:find("#"..t) then
match = true
end
end
else
match = true
end
local status = { description = context.description, type = "description", run = match }
local setup_ok, setup_error
setup_ok, setup_error = run_setup(context, "setup")
if setup_ok then
for i,v in ipairs(context) do
setup_ok, setup_error = run_setup(context, "before_each")
if not setup_ok then break end
if v.type == "test" then
table.insert(status, test(v.description, v.callback))
elseif v.type == "describe" then
table.insert(status, coroutine.create(function() run_context(v) end))
elseif v.type == "pending" then
local pending_test_status = { type = "pending", description = v.description, info = v.info }
v.callback(pending_test_status)
table.insert(status, pending_test_status)
end
setup_ok, setup_error = run_setup(context, "after_each")
if not setup_ok then break end
end
end
if setup_ok then setup_ok, setup_error = run_setup(context, "teardown") end
if not setup_ok then table.insert(status, setup_error) end
if in_coroutine() then
coroutine.yield(status)
else
return true, status
end
end
local play_sound = function(failures)
math.randomseed(os.time())
if self.options.failure_messages and #self.options.failure_messages > 0 and
self.options.success_messages and #self.options.success_messages > 0 then
if failures and failures > 0 then
io.popen("say \""..failure_messages[math.random(1, #failure_messages)]:format(failures).."\"")
else
io.popen("say \""..success_messages[math.random(1, #success_messages)].."\"")
end
end
end
local ms = os.clock()
if not self.options.defer_print then
print(self.output.header(self.root_context))
end
--fire off tests, return status list
local function get_statuses(done, list)
local ret = {}
for i,v in pairs(list) do
local vtype = type(v)
if vtype == "thread" then
local res = get_statuses(coroutine.resume(v))
for key,value in pairs(res) do
table.insert(ret, value)
end
elseif vtype == "table" then
table.insert(ret, v)
end
end
return ret
end
local statuses = get_statuses(run_context(self.root_context))
--final run time
ms = os.clock() - ms
if self.options.defer_print then
print(self.output.header(self.root_context))
end
local status_string = self.output.formatted_status(statuses, self.options, ms)
if self.options.sound then
play_sound(failures)
end
return status_string
end
}
return setmetatable(busted, busted)
|
fix: setup log info showed up in output, even in case of success
|
fix: setup log info showed up in output, even in case of success
|
Lua
|
mit
|
sobrinho/busted,o-lim/busted,DorianGray/busted,istr/busted,xyliuke/busted,Olivine-Labs/busted,leafo/busted,mpeterv/busted,azukiapp/busted,nehz/busted,ryanplusplus/busted
|
1bb887b550a8c61128c0504cebd00024de5c086c
|
luapak/luarocks/init.lua
|
luapak/luarocks/init.lua
|
---------
-- Facade for interaction with LuaRocks.
----
require 'luapak.luarocks.site_config'
require 'luapak.luarocks.cfg_extra'
package.loaded['luarocks.build.builtin'] = require 'luapak.build.builtin'
local cfg = require 'luarocks.cfg'
local build = require 'luarocks.build'
local fetch = require 'luarocks.fetch'
local fs = require 'luarocks.fs'
local path = require 'luarocks.path'
local util = require 'luarocks.util'
local const = require 'luapak.luarocks.constants'
local function run_in_dir (dir, func, ...)
local old_pwd = fs.current_dir()
if dir then fs.change_dir(dir) end
local result = { func(...) }
if dir then fs.change_dir(old_pwd) end
-- XXX: Workaround for incorrect behaviour of unpack on sparse tables.
return result[1], result[2], result[3], result[4]
end
local M = {}
--- The configuration table.
M.cfg = cfg
--- Do we run on Windows?
M.is_windows = cfg.platforms.windows
--- Builds and installs local rock specified by the rockspec.
--
-- @tparam string rockspec_file Path of the rockspec file.
-- @tparam string proj_dir The base directory with the rock's sources.
function M.build_and_install_rockspec (rockspec_file, proj_dir)
return run_in_dir(proj_dir,
build.build_rockspec, rockspec_file, false, true, 'one', false)
end
--- Changes the target Lua version.
--
-- @tparam string api_ver The Lua API version in format `x.y` (e.g. 5.1).
-- @tparam ?string luajit_ver The LuaJIT version, or nil if target is not LuaJIT.
function M.change_target_lua (api_ver, luajit_ver)
cfg.lua_version = api_ver
cfg.luajit_version = luajit_ver
cfg.rocks_provided.lua = api_ver..'-1'
if api_ver == '5.2' then
cfg.rocks_provided.bit32 = '5.2-1'
elseif api_ver == '5.3' then
cfg.rocks_provided.utf8 = '5.3-1'
end
if luajit_ver then
cfg.rocks_provided.luabitop = luajit_ver:gsub('%-', '')..'-1'
if cfg.is_platform('macosx') then
-- See http://luajit.org/install.html#embed.
local ldflags = cfg.variables.LDFLAGS or ''
cfg.variables.LDFLAGS = '-pagezero_size 10000 -image_base 100000000 '..ldflags
end
else
cfg.rocks_provided.luabitop = nil
end
end
--- Looks for the default rockspec file in the project's directory.
--
-- @tparam string proj_dir The project's base directory.
-- @treturn[1] string An absolute path of the found rockspec file.
-- @treturn[2] nil
-- @treturn[2] string An error message.
function M.find_default_rockspec (proj_dir)
local filename, err = run_in_dir(proj_dir, util.get_default_rockspec)
if not filename then
return nil, err
end
return fs.absolute_name(filename)
end
--- Gets LuaRocks variable from `cfg.variables` table.
function M.get_variable (name)
return cfg.variables[name]
end
--- Loads the specified rockspec into a table.
--
-- @tparam string rockspec_file Path of the rockspec file.
-- @treturn[1] table A rockspec's table.
-- @treturn[2] nil
-- @treturn[2] string An error message.
function M.load_rockspec (rockspec_file)
return fetch.load_rockspec(rockspec_file)
end
--- Switches LuaRocks to use static or dynamic linking.
--
-- @tparam bool enabled true to use static linking, false to use
-- dynamic linking.
function M.set_link_static (enabled)
if enabled then
cfg.link_static = true
cfg.lib_extension = cfg.static_lib_extension
else
cfg.link_static = false
cfg.lib_extension = cfg.shared_lib_extension
end
if cfg.variables.LUALIB then
cfg.variables.LUALIB = cfg.variables.LUALIB:gsub('%.[^.]+$', '.'..cfg.lib_extension)
end
cfg.variables.LIB_EXTENSION = cfg.lib_extension
end
--- Sets LuaRocks variable into `cfg.variables` table.
function M.set_variable (name, value)
cfg.variables[name] = value
end
---
-- @tparam string dirname Path of the directory.
function M.use_tree (dirname)
local old_root_dir = cfg.root_dir
local prefix = cfg.variables.LUAROCKS_PREFIX
dirname = fs.absolute_name(dirname)
path.use_tree(dirname)
if prefix == old_root_dir or prefix == const.LUAROCKS_FAKE_PREFIX then
cfg.variables.LUAROCKS_PREFIX = dirname
end
end
return M
|
---------
-- Facade for interaction with LuaRocks.
----
require 'luapak.luarocks.site_config'
require 'luapak.luarocks.cfg_extra'
package.loaded['luarocks.build.builtin'] = require 'luapak.build.builtin'
local cfg = require 'luarocks.cfg'
local build = require 'luarocks.build'
local fetch = require 'luarocks.fetch'
local fs = require 'luarocks.fs'
local path = require 'luarocks.path'
local util = require 'luarocks.util'
local const = require 'luapak.luarocks.constants'
local function run_in_dir (dir, func, ...)
local old_pwd = fs.current_dir()
if dir then fs.change_dir(dir) end
local result = { func(...) }
if dir then fs.change_dir(old_pwd) end
-- XXX: Workaround for incorrect behaviour of unpack on sparse tables.
return result[1], result[2], result[3], result[4]
end
local M = {}
--- The configuration table.
M.cfg = cfg
--- Do we run on Windows?
M.is_windows = cfg.platforms.windows
--- Builds and installs local rock specified by the rockspec.
--
-- @tparam string rockspec_file Path of the rockspec file.
-- @tparam string proj_dir The base directory with the rock's sources.
function M.build_and_install_rockspec (rockspec_file, proj_dir)
return run_in_dir(proj_dir,
build.build_rockspec, rockspec_file, false, true, 'one', false)
end
--- Changes the target Lua version.
--
-- @tparam string api_ver The Lua API version in format `x.y` (e.g. 5.1).
-- @tparam ?string luajit_ver The LuaJIT version, or nil if target is not LuaJIT.
function M.change_target_lua (api_ver, luajit_ver)
cfg.lua_version = api_ver
cfg.luajit_version = luajit_ver
cfg.rocks_provided.lua = api_ver..'-1'
if api_ver == '5.2' then
cfg.rocks_provided.bit32 = '5.2-1'
elseif api_ver == '5.3' then
cfg.rocks_provided.utf8 = '5.3-1'
end
if luajit_ver then
cfg.rocks_provided.luabitop = luajit_ver:gsub('%-', '')..'-1'
if cfg.is_platform('macosx') then
-- See http://luajit.org/install.html#embed.
local ldflags = cfg.variables.LDFLAGS or ''
cfg.variables.LDFLAGS = const.LUAJIT_MACOS_LDFLAGS..' '..ldflags
end
else
cfg.rocks_provided.luabitop = nil
end
end
--- Looks for the default rockspec file in the project's directory.
--
-- @tparam string proj_dir The project's base directory.
-- @treturn[1] string An absolute path of the found rockspec file.
-- @treturn[2] nil
-- @treturn[2] string An error message.
function M.find_default_rockspec (proj_dir)
local filename, err = run_in_dir(proj_dir, util.get_default_rockspec)
if not filename then
return nil, err
end
return fs.absolute_name(filename)
end
--- Gets LuaRocks variable from `cfg.variables` table.
function M.get_variable (name)
return cfg.variables[name]
end
--- Loads the specified rockspec into a table.
--
-- @tparam string rockspec_file Path of the rockspec file.
-- @treturn[1] table A rockspec's table.
-- @treturn[2] nil
-- @treturn[2] string An error message.
function M.load_rockspec (rockspec_file)
return fetch.load_rockspec(rockspec_file)
end
--- Switches LuaRocks to use static or dynamic linking.
--
-- @tparam bool enabled true to use static linking, false to use
-- dynamic linking.
function M.set_link_static (enabled)
if enabled then
cfg.link_static = true
cfg.lib_extension = cfg.static_lib_extension
else
cfg.link_static = false
cfg.lib_extension = cfg.shared_lib_extension
end
if cfg.variables.LUALIB then
cfg.variables.LUALIB = cfg.variables.LUALIB:gsub('%.[^.]+$', '.'..cfg.lib_extension)
end
cfg.variables.LIB_EXTENSION = cfg.lib_extension
end
--- Sets LuaRocks variable into `cfg.variables` table.
function M.set_variable (name, value)
cfg.variables[name] = value
end
---
-- @tparam string dirname Path of the directory.
function M.use_tree (dirname)
local old_root_dir = cfg.root_dir
local prefix = cfg.variables.LUAROCKS_PREFIX
dirname = fs.absolute_name(dirname)
path.use_tree(dirname)
if prefix == old_root_dir or prefix == const.LUAROCKS_FAKE_PREFIX then
cfg.variables.LUAROCKS_PREFIX = dirname
end
end
return M
|
Fix duplication of LUAJIT_MACOS_LDFLAGS
|
Fix duplication of LUAJIT_MACOS_LDFLAGS
|
Lua
|
mit
|
jirutka/luapak,jirutka/luapak
|
153ca3e83eee84e48da0eddd2451f10282fa5bc2
|
plugins/database.lua
|
plugins/database.lua
|
local function callback_group_database(extra, success, result)
local database = extra.database
local chat_id = result.peer_id
-- save group info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. result.print_name:gsub("_"," "),
long_id = result.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = result.print_name:gsub("_"," "),
long_id = result.id
}
end
-- save users info
for k, v in pairs(result.members) do
if database["users"][tostring(v.peer_id)] then
if not database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] then
database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id)
end
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
database["users"][tostring(v.peer_id)]["groups"] = { }
database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id)
end
end
save_data(_config.database.db, database)
send_large_msg(extra.receiver, langs[get_lang(result.peer_id)].dataLeaked)
end
local function callback_supergroup_database(extra, success, result)
local database = extra.database
local chat_id = string.match(extra.receiver, '%d+')
-- save supergroup info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. extra.print_name:gsub("_"," "),
old_usernames = database["groups"][tostring(chat_id)].old_usernames .. ' ### ' ..(extra.username or 'NOUSER'),
long_id = extra.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = extra.print_name:gsub("_"," "),
old_usernames = extra.username or 'NOUSER',
long_id = extra.id
}
end
-- save users info
for k, v in pairsByKeys(result) do
if database["users"][tostring(v.peer_id)] then
if not database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] then
database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id)
end
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
database["users"][tostring(v.peer_id)]["groups"] = { }
database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id)
end
end
save_data(_config.database.db, database)
send_large_msg(extra.receiver, langs[get_lang(string.match(extra.receiver, '%d+'))].dataLeaked)
end
local function run(msg, matches)
if is_sudo(msg) then
if matches[1]:lower() == 'createdatabase' then
local f = io.open(_config.database.db, 'w+')
f:write('{"groups":{},"users":{}}')
f:close()
reply_msg(msg.id, langs[msg.lang].dbCreated, ok_cb, false)
return
end
local database = load_data(_config.database.db)
if matches[1]:lower() == 'database' or matches[1]:lower() == 'sasha database' then
local receiver = get_receiver(msg)
if msg.to.type == 'channel' then
channel_get_users(receiver, callback_supergroup_database, { receiver = receiver, database = database, print_name = msg.to.print_name, username = (msg.to.username or nil), id = msg.to.peer_id })
elseif msg.to.type == 'chat' then
chat_info(receiver, callback_group_database, { receiver = receiver, database = database })
else
return
end
end
else
return langs[msg.lang].require_sudo
end
end
return {
description = "DATABASE",
patterns =
{
"^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
"^[#!/]([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
-- database
"^([Ss][Aa][Ss][Hh][Aa] [Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
},
run = run,
min_rank = 5
-- usage
-- SUDO
-- #createdatabase
-- (#database|[sasha] database)
}
|
local function callback_group_database(extra, success, result)
local database = extra.database
local chat_id = result.peer_id
-- save group info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. result.print_name:gsub("_"," "),
long_id = result.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = result.print_name:gsub("_"," "),
long_id = result.id
}
end
save_data(_config.database.db, database)
-- save users info
for k, v in pairs(result.members) do
if database["users"][tostring(v.peer_id)] then
if not database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] then
database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id)
end
save_data(_config.database.db, database)
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
save_data(_config.database.db, database)
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
save_data(_config.database.db, database)
database["users"][tostring(v.peer_id)]["groups"] = { }
save_data(_config.database.db, database)
database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id)
save_data(_config.database.db, database)
end
end
send_large_msg(extra.receiver, langs[get_lang(result.peer_id)].dataLeaked)
end
local function callback_supergroup_database(extra, success, result)
local database = extra.database
local chat_id = string.match(extra.receiver, '%d+')
-- save supergroup info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. extra.print_name:gsub("_"," "),
old_usernames = database["groups"][tostring(chat_id)].old_usernames .. ' ### ' ..(extra.username or 'NOUSER'),
long_id = extra.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = extra.print_name:gsub("_"," "),
old_usernames = extra.username or 'NOUSER',
long_id = extra.id
}
end
save_data(_config.database.db, database)
-- save users info
for k, v in pairsByKeys(result) do
if database["users"][tostring(v.peer_id)] then
if not database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] then
database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id)
end
save_data(_config.database.db, database)
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
save_data(_config.database.db, database)
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
save_data(_config.database.db, database)
database["users"][tostring(v.peer_id)]["groups"] = { }
save_data(_config.database.db, database)
database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id)
save_data(_config.database.db, database)
end
end
send_large_msg(extra.receiver, langs[get_lang(string.match(extra.receiver, '%d+'))].dataLeaked)
end
local function run(msg, matches)
if is_sudo(msg) then
if matches[1]:lower() == 'createdatabase' then
local f = io.open(_config.database.db, 'w+')
f:write('{"groups":{},"users":{}}')
f:close()
reply_msg(msg.id, langs[msg.lang].dbCreated, ok_cb, false)
return
end
local database = load_data(_config.database.db)
if matches[1]:lower() == 'database' or matches[1]:lower() == 'sasha database' then
local receiver = get_receiver(msg)
if msg.to.type == 'channel' then
channel_get_users(receiver, callback_supergroup_database, { receiver = receiver, database = database, print_name = msg.to.print_name, username = (msg.to.username or nil), id = msg.to.peer_id })
elseif msg.to.type == 'chat' then
chat_info(receiver, callback_group_database, { receiver = receiver, database = database })
else
return
end
end
else
return langs[msg.lang].require_sudo
end
end
return {
description = "DATABASE",
patterns =
{
"^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
"^[#!/]([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
-- database
"^([Ss][Aa][Ss][Hh][Aa] [Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
},
run = run,
min_rank = 5
-- usage
-- SUDO
-- #createdatabase
-- (#database|[sasha] database)
}
|
fix database
|
fix database
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
e35cad3053cd68e6bf64c19f93090f711f974e49
|
lualib/http/tlshelper.lua
|
lualib/http/tlshelper.lua
|
local socket = require "http.sockethelper"
local c = require "ltls.c"
local tlshelper = {}
function tlshelper.init_requestfunc(fd, tls_ctx)
local readfunc = socket.readfunc(fd)
local writefunc = socket.writefunc(fd)
return function ()
local ds1 = tls_ctx:handshake()
writefunc(ds1)
while not tls_ctx:finished() do
local ds2 = readfunc()
local ds3 = tls_ctx:handshake(ds2)
if ds3 then
writefunc(ds3)
end
end
end
end
function tlshelper.init_responsefunc(fd, tls_ctx)
local readfunc = socket.readfunc(fd)
local writefunc = socket.writefunc(fd)
return function ()
while not tls_ctx:finished() do
local ds1 = readfunc()
local ds2 = tls_ctx:handshake(ds1)
if ds2 then
writefunc(ds2)
end
end
local ds3 = tls_ctx:write()
writefunc(ds3)
end
end
function tlshelper.closefunc(tls_ctx)
return function ()
tls_ctx:close()
end
end
function tlshelper.readfunc(fd, tls_ctx)
local readfunc = socket.readfunc(fd)
local read_buff = ""
return function (sz)
if not sz then
local s = ""
if #read_buff == 0 then
local ds = readfunc(sz)
s = tls_ctx:read(ds)
end
s = read_buff .. s
read_buff = ""
return s
else
while #read_buff < sz do
local ds = readfunc()
local s = tls_ctx:read(ds)
read_buff = read_buff .. s
end
local s = string.sub(read_buff, 1, sz)
read_buff = string.sub(read_buff, sz+1, #read_buff)
return s
end
end
end
function tlshelper.writefunc(fd, tls_ctx)
local writefunc = socket.writefunc(fd)
return function (s)
local ds = tls_ctx:write(s)
return writefunc(ds)
end
end
function tlshelper.readallfunc(fd, tls_ctx)
return function ()
local ds = socket.readall(fd)
local s = tls_ctx:read(ds)
return s
end
end
function tlshelper.newctx()
return c.newctx()
end
function tlshelper.newtls(method, ssl_ctx, hostname)
return c.newtls(method, ssl_ctx, hostname)
end
return tlshelper
|
local socket = require "http.sockethelper"
local c = require "ltls.c"
local tlshelper = {}
function tlshelper.init_requestfunc(fd, tls_ctx)
local readfunc = socket.readfunc(fd)
local writefunc = socket.writefunc(fd)
return function ()
local ds1 = tls_ctx:handshake()
writefunc(ds1)
while not tls_ctx:finished() do
local ds2 = readfunc()
local ds3 = tls_ctx:handshake(ds2)
if ds3 then
writefunc(ds3)
end
end
end
end
function tlshelper.init_responsefunc(fd, tls_ctx)
local readfunc = socket.readfunc(fd)
local writefunc = socket.writefunc(fd)
return function ()
while not tls_ctx:finished() do
local ds1 = readfunc()
local ds2 = tls_ctx:handshake(ds1)
if ds2 then
writefunc(ds2)
end
end
local ds3 = tls_ctx:write()
writefunc(ds3)
end
end
function tlshelper.closefunc(tls_ctx)
return function ()
tls_ctx:close()
end
end
function tlshelper.readfunc(fd, tls_ctx)
local function readfunc()
readfunc = socket.readfunc(fd)
return ""
end
local read_buff = ""
return function (sz)
if not sz then
local s = ""
if #read_buff == 0 then
local ds = readfunc()
s = tls_ctx:read(ds)
end
s = read_buff .. s
read_buff = ""
return s
else
while #read_buff < sz do
local ds = readfunc()
local s = tls_ctx:read(ds)
read_buff = read_buff .. s
end
local s = string.sub(read_buff, 1, sz)
read_buff = string.sub(read_buff, sz+1, #read_buff)
return s
end
end
end
function tlshelper.writefunc(fd, tls_ctx)
local writefunc = socket.writefunc(fd)
return function (s)
local ds = tls_ctx:write(s)
return writefunc(ds)
end
end
function tlshelper.readallfunc(fd, tls_ctx)
return function ()
local ds = socket.readall(fd)
local s = tls_ctx:read(ds)
return s
end
end
function tlshelper.newctx()
return c.newctx()
end
function tlshelper.newtls(method, ssl_ctx, hostname)
return c.newtls(method, ssl_ctx, hostname)
end
return tlshelper
|
fix #1494 socket read阻塞问题 (#1495)
|
fix #1494 socket read阻塞问题 (#1495)
* fix #1494 socket read阻塞问题
* 优化readfunc
Co-authored-by: zixun <1c4f76f41f033c1ac87f9def94f616e7a591e78d@alibaba-inc.com>
|
Lua
|
mit
|
wangyi0226/skynet,xjdrew/skynet,cloudwu/skynet,korialuo/skynet,xjdrew/skynet,sanikoyes/skynet,wangyi0226/skynet,cloudwu/skynet,korialuo/skynet,sanikoyes/skynet,wangyi0226/skynet,korialuo/skynet,cloudwu/skynet,sanikoyes/skynet,xjdrew/skynet
|
cee11c7d2bb2b57449bbdd62abf261a988b04d6a
|
hammerspoon/init.lua
|
hammerspoon/init.lua
|
local log = hs.logger.new('init.lua', 'debug')
keyUpDown = function(modifiers, key)
log.d('Sending keystroke:', hs.inspect(modifiers), key)
hs.eventtap.event.newKeyEvent(modifiers, key, true):post()
hs.eventtap.event.newKeyEvent(modifiers, key, false):post()
end
-- Subscribe to the necessary events on the given window filter such that the
-- given hotkey is enabled for windows that match the window filter and disabled
-- for windows that don't match the window filter.
--
-- windowFilter - An hs.window.filter object describing the windows for which
-- the hotkey should be enabled.
-- hotkey - The hs.hotkey object to enable/disable.
--
-- Returns nothing.
enableHotkeyForWindowsMatchingFilter = function(windowFilter, hotkey)
windowFilter:subscribe(hs.window.filter.windowFocused, function()
hotkey:enable()
end)
windowFilter:subscribe(hs.window.filter.windowUnfocused, function()
hotkey:disable()
end)
end
require('control-escape')
require('delete-words')
require('hyper')
require('markdown')
require('panes')
require('super')
require('windows')
-- Use Control+` to reload Hammerspoon config
hs.hotkey.bind({'ctrl'}, '`', nil, function()
hs.reload()
end)
hs.notify.new({title='Hammerspoon', informativeText='Ready to rock 🤘'}):send()
|
local log = hs.logger.new('init.lua', 'debug')
-- Use Control+` to reload Hammerspoon config
hs.hotkey.bind({'ctrl'}, '`', nil, function()
hs.reload()
end)
keyUpDown = function(modifiers, key)
log.d('Sending keystroke:', hs.inspect(modifiers), key)
hs.eventtap.event.newKeyEvent(modifiers, key, true):post()
hs.eventtap.event.newKeyEvent(modifiers, key, false):post()
end
-- Subscribe to the necessary events on the given window filter such that the
-- given hotkey is enabled for windows that match the window filter and disabled
-- for windows that don't match the window filter.
--
-- windowFilter - An hs.window.filter object describing the windows for which
-- the hotkey should be enabled.
-- hotkey - The hs.hotkey object to enable/disable.
--
-- Returns nothing.
enableHotkeyForWindowsMatchingFilter = function(windowFilter, hotkey)
windowFilter:subscribe(hs.window.filter.windowFocused, function()
hotkey:enable()
end)
windowFilter:subscribe(hs.window.filter.windowUnfocused, function()
hotkey:disable()
end)
end
require('control-escape')
require('delete-words')
require('hyper')
require('markdown')
require('panes')
require('super')
require('windows')
hs.notify.new({title='Hammerspoon', informativeText='Ready to rock 🤘'}):send()
|
Define keybinding earlier
|
Define keybinding earlier
When working on these configs, if there's an error in the code, it
will prevent the subsequent code from getting executed. In those cases,
we need to fix the issue and reload the config. To make it easier to
reload the config, it's helpful to bind the hotkey for reloading the
config *before* any of the other config code.
|
Lua
|
mit
|
jasonrudolph/keyboard,jasonrudolph/keyboard
|
af20bba3469a18802d29481ef0a14668c3c14cc7
|
lua/geohash.lua
|
lua/geohash.lua
|
local GeoHash = {}
--[[
-- Private Attributes
]]--
local _map = {}
_map['0'] = '00000'
_map['1'] = '00001'
_map['2'] = '00010'
_map['3'] = '00011'
_map['4'] = '00100'
_map['5'] = '00101'
_map['6'] = '00110'
_map['7'] = '00111'
_map['8'] = '01000'
_map['9'] = '01001'
_map['b'] = '01010'
_map['c'] = '01011'
_map['d'] = '01100'
_map['e'] = '01101'
_map['f'] = '01110'
_map['g'] = '01111'
_map['h'] = '10000'
_map['j'] = '10001'
_map['k'] = '10010'
_map['m'] = '10011'
_map['n'] = '10100'
_map['p'] = '10101'
_map['q'] = '10110'
_map['r'] = '10111'
_map['s'] = '11000'
_map['t'] = '11001'
_map['u'] = '11010'
_map['v'] = '11011'
_map['w'] = '11100'
_map['x'] = '11101'
_map['y'] = '11110'
_map['z'] = '11111'
local _precision = nil
local _digits = 0
--[[
-- Private Methods
]]--
local function _decode(coord, min, max)
local mid = 0.0
local val = 0.0
local c = ''
for i = 1, #coord do
c = coord:sub(i, i)
if c == '1' then
min = mid
val = (mid + max) / 2
mid = val
else
max = mid
val = (mid + min) / 2
mid = val
end
end
-- We want number of decimals according to hash length
val = tonumber(string.format("%.".. (#coord / 5) .. "f", val))
return val
end
local function _encode(coord, min, max)
local mid = 0.0
local x = 0.0
local y = 0.0
local p = ((_precision or _digits) * 5)
local result = ''
for i = 1, p do
if coord <= max and coord >= mid then
result = result .. '1'
x = mid
y = max
else
result = result .. '0'
x = min
y = mid
end
min = x
mid = x + ((y - x) / 2)
max = y
end
return result
end
local function _merge(latbin, longbin)
local res = ''
for i = 1, #latbin do
res = res .. longbin:sub(i, i) .. latbin:sub(i, i)
end
return res
end
local function _swap(tbl)
local table = {}
for key, val in pairs(tbl) do
table[val] = key
end
return table
end
local function _translate(bstr)
local hash = ''
local t = _swap(_map)
for i = 1, #bstr, 5 do
hash = hash .. t[bstr:sub(i, i + 4)]
end
return hash
end
local function _decimals(lat, long)
local d1 = tostring(string.match(tostring(lat), "%d+.(%d+)"))
local d2 = tostring(string.match(tostring(long), "%d+.(%d+)"))
local ret = #d2
if #d1 > #d2 then
ret = #d1
end
return ret
end
--[[
-- Public Methods
]]--
function GeoHash.decode(hash)
local bin = ''
local long = ''
local lat = ''
local c = ''
-- Convert hash to binary string
for i = 1, #hash do
c = hash:sub(i, i)
bin = bin .. _map[c]
end
-- Split binary string into latitude and longitude parts
for i = 1, #bin do
c = bin:sub(i, i)
if i % 2 == 0 then
lat = lat .. c
else
long = long .. c
end
end
return _decode(lat, -90.0, 90.0), _decode(long, -180.0, 180.0)
end
function GeoHash.encode(lat, long)
-- Find precision
_digits = _decimals(lat, long)
-- Translate coordinates to binary string format
local a = _encode(lat, -90.0, 90.0)
local b = _encode(long, -180.0, 180.0)
-- Merge the two binary string
local binstr = _merge(a, b)
-- Calculate GeoHash for binary string
return _translate(binstr)
end
function GeoHash.precision(p)
_precision = p
end
return GeoHash
|
local GeoHash = {}
--[[
-- Private Attributes
]]--
local _map = {}
_map['0'] = '00000'
_map['1'] = '00001'
_map['2'] = '00010'
_map['3'] = '00011'
_map['4'] = '00100'
_map['5'] = '00101'
_map['6'] = '00110'
_map['7'] = '00111'
_map['8'] = '01000'
_map['9'] = '01001'
_map['b'] = '01010'
_map['c'] = '01011'
_map['d'] = '01100'
_map['e'] = '01101'
_map['f'] = '01110'
_map['g'] = '01111'
_map['h'] = '10000'
_map['j'] = '10001'
_map['k'] = '10010'
_map['m'] = '10011'
_map['n'] = '10100'
_map['p'] = '10101'
_map['q'] = '10110'
_map['r'] = '10111'
_map['s'] = '11000'
_map['t'] = '11001'
_map['u'] = '11010'
_map['v'] = '11011'
_map['w'] = '11100'
_map['x'] = '11101'
_map['y'] = '11110'
_map['z'] = '11111'
local _precision = nil
local _digits = 0
--[[
-- Private Methods
]]--
local function _decode(coord, min, max)
local mid = 0.0
local val = 0.0
local c = ''
for i = 1, #coord do
c = coord:sub(i, i)
if c == '1' then
min = mid
val = (mid + max) / 2
mid = val
else
max = mid
val = (mid + min) / 2
mid = val
end
end
-- We want number of decimals according to hash length
val = tonumber(string.format("%.".. (#coord / 5) .. "f", val))
return val
end
local function _encode(coord, min, max)
local mid = 0.0
local x = 0.0
local y = 0.0
local p = ((_precision or _digits) * 5)
local result = ''
for i = 1, p do
if coord <= max and coord >= mid then
result = result .. '1'
x = mid
y = max
else
result = result .. '0'
x = min
y = mid
end
min = x
mid = x + ((y - x) / 2)
max = y
end
return result
end
local function _merge(latbin, longbin)
local res = ''
for i = 1, #latbin do
res = res .. longbin:sub(i, i) .. latbin:sub(i, i)
end
return res
end
local function _swap(tbl)
local table = {}
for key, val in pairs(tbl) do
table[val] = key
end
return table
end
local function _translate(bstr)
local hash = ''
local t = _swap(_map)
for i = 1, #bstr, 5 do
hash = hash .. t[bstr:sub(i, i + 4)]
end
return hash
end
local function _decimals(lat, long)
local d1 = tostring(string.match(tostring(lat), "%d+.(%d+)") or '')
local d2 = tostring(string.match(tostring(long), "%d+.(%d+)") or '')
local ret = #d2
if #d1 > #d2 then
ret = #d1
elseif #d1 == 0 and #d2 == 0 then
-- if no digits default to 2
ret = 2
end
return ret
end
--[[
-- Public Methods
]]--
function GeoHash.decode(hash)
local bin = ''
local long = ''
local lat = ''
local c = ''
-- Convert hash to binary string
for i = 1, #hash do
c = hash:sub(i, i)
bin = bin .. _map[c]
end
-- Split binary string into latitude and longitude parts
for i = 1, #bin do
c = bin:sub(i, i)
if i % 2 == 0 then
lat = lat .. c
else
long = long .. c
end
end
return _decode(lat, -90.0, 90.0), _decode(long, -180.0, 180.0)
end
function GeoHash.encode(lat, long)
-- Find precision
_digits = _decimals(lat, long)
-- Translate coordinates to binary string format
local a = _encode(lat, -90.0, 90.0)
local b = _encode(long, -180.0, 180.0)
-- Merge the two binary string
local binstr = _merge(a, b)
-- Calculate GeoHash for binary string
return _translate(binstr)
end
function GeoHash.precision(p)
_precision = p
end
return GeoHash
|
Fixed issue when lat, long has no decimals
|
Fixed issue when lat, long has no decimals
Fx. the lat, long coordinate (55, 12)
|
Lua
|
mit
|
dauer/geohash,irr/geohash,dauer/geohash,irr/geohash
|
06fd2351546f74f679a1f06aa001cbee141bf802
|
agents/monitoring/lua/lib/client/connection_stream.lua
|
agents/monitoring/lua/lib/client/connection_stream.lua
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local Emitter = require('core').Emitter
local math = require('math')
local timer = require('timer')
local fmt = require('string').format
local async = require('async')
local AgentClient = require('./client').AgentClient
local ConnectionMessages = require('./connection_messages').ConnectionMessages
local logging = require('logging')
local misc = require('../util/misc')
local fmt = require('string').format
local CONNECT_TIMEOUT = 6000
local ConnectionStream = Emitter:extend()
function ConnectionStream:initialize(id, token)
self._id = id
self._token = token
self._clients = {}
self._unauthedClients = {}
self._delays = {}
self._messages = ConnectionMessages:new(self)
end
--[[
Create and establish a connection to the multiple endpoints.
addresses - An Array of ip:port pairs
callback - Callback called with (err) when all the connections have been
established.
--]]
function ConnectionStream:createConnections(addresses, callback)
async.series({
-- connect
function(callback)
async.forEach(addresses, function(address, callback)
local split, client, options
split = misc.splitAddress(address)
options = {}
options.host = split[1]
options.port = split[2]
options.datacenter = address
self:createConnection(options, callback)
end)
end
}, callback)
end
function ConnectionStream:_setDelay(datacenter)
local maxDelay = 5 * 60 * 1000 -- max connection delay in ms
local jitter = 7000 -- jitter in ms
local previousDelay = self._delays[datacenter]
local delay
if previousDelay == nil then
self._delays[datacenter] = 0
previousDelay = 0
end
delay = math.min(previousDelay, maxDelay) + (jitter * math.random())
self._delays[datacenter] = delay
return delay
end
--[[
Retry a connection to the endpoint.
options - datacenter, host, port
datacenter - Datacenter name / host alias.
host - Hostname.
port - Port.
callback - Callback called with (err)
]]--
function ConnectionStream:reconnect(options, callback)
local datacenter = options.datacenter
local delay = self:_setDelay(datacenter)
logging.log(logging.INFO, fmt('%s:%d -> Retrying connection in %dms', options.host, options.port, delay))
timer.setTimeout(delay, function()
self:createConnection(options, callback)
end)
end
function ConnectionStream:getClient()
local client, min_latency = 2147483647, latency
for k, v in pairs(self._clients) do
latency = self._clients[k]:getLatency()
if latency == nil or min_latency > latency then
client = self._clients[k]
end
min_latency = latency
end
return client
end
--[[
Move an unauthenticated client to the list of clients that have been authenticated.
client - the client.
]]--
function ConnectionStream:_promoteClient(client)
local datacenter = client:getDatacenter()
client:log(logging.INFO, fmt('Connection has been authenticated to %s', datacenter))
self._clients[datacenter] = client
self._unauthedClients[datacenter] = nil
end
--[[
Create and establish a connection to the endpoint.
datacenter - Datacenter name / host alias.
host - Hostname.
port - Port.
callback - Callback called with (err)
]]--
function ConnectionStream:createConnection(options, callback)
local opts = misc.merge({
id = self._id,
token = self._token,
timeout = CONNECT_TIMEOUT
}, options)
local client = AgentClient:new(opts)
client:on('error', function(err)
err.host = opts.host
err.port = opts.port
err.datacenter = opts.datacenter
client:destroy()
self:reconnect(opts, callback)
if err then
self:emit('error', err)
end
end)
client:on('timeout', function()
logging.log(logging.DEBUG, fmt('%s:%d -> Client Timeout', opts.host, opts.port))
client:destroy()
self:reconnect(opts, callback)
end)
client:on('end', function()
self:emit('client_end', client)
logging.log(logging.DEBUG, fmt('%s:%d -> Remote endpoint closed the connection', opts.host, opts.port))
client:destroy()
self:reconnect(opts, callback)
end)
client:on('handshake_success', function()
self:_promoteClient(client)
self._delays[options.datacenter] = 0
client:startPingInterval()
self._messages:emit('handshake_success', client)
end)
client:on('message', function(msg)
self._messages:emit('message', client, msg)
end)
client:connect(function(err)
if err then
client:destroy()
self:reconnect(opts, callback)
callback(err)
return
end
client.datacenter = datacenter
self._unauthedClients[datacenter] = client
callback();
end)
return client
end
local exports = {}
exports.ConnectionStream = ConnectionStream
return exports
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local Emitter = require('core').Emitter
local math = require('math')
local timer = require('timer')
local fmt = require('string').format
local async = require('async')
local AgentClient = require('./client').AgentClient
local ConnectionMessages = require('./connection_messages').ConnectionMessages
local logging = require('logging')
local misc = require('../util/misc')
local fmt = require('string').format
local CONNECT_TIMEOUT = 6000
local ConnectionStream = Emitter:extend()
function ConnectionStream:initialize(id, token)
self._id = id
self._token = token
self._clients = {}
self._unauthedClients = {}
self._delays = {}
self._messages = ConnectionMessages:new(self)
end
--[[
Create and establish a connection to the multiple endpoints.
addresses - An Array of ip:port pairs
callback - Callback called with (err) when all the connections have been
established.
--]]
function ConnectionStream:createConnections(addresses, callback)
async.series({
-- connect
function(callback)
async.forEach(addresses, function(address, callback)
local split, client, options
split = misc.splitAddress(address)
options = {}
options.host = split[1]
options.port = split[2]
options.datacenter = address
self:createConnection(options, callback)
end)
end
}, callback)
end
function ConnectionStream:_setDelay(datacenter)
local maxDelay = 5 * 60 * 1000 -- max connection delay in ms
local jitter = 7000 -- jitter in ms
local previousDelay = self._delays[datacenter]
local delay
if previousDelay == nil then
self._delays[datacenter] = 0
previousDelay = 0
end
delay = math.min(previousDelay, maxDelay) + (jitter * math.random())
self._delays[datacenter] = delay
return delay
end
--[[
Retry a connection to the endpoint.
options - datacenter, host, port
datacenter - Datacenter name / host alias.
host - Hostname.
port - Port.
callback - Callback called with (err)
]]--
function ConnectionStream:reconnect(options, callback)
local datacenter = options.datacenter
local delay = self:_setDelay(datacenter)
logging.log(logging.INFO, fmt('%s:%d -> Retrying connection in %dms', options.host, options.port, delay))
timer.setTimeout(delay, function()
self:createConnection(options, callback)
end)
end
function ConnectionStream:getClient()
local client, min_latency = 2147483647, latency
for k, v in pairs(self._clients) do
latency = self._clients[k]:getLatency()
if latency == nil then
client = self._clients[k]
elseif min_latency > latency then
client = self._clients[k]
min_latency = latency
end
end
return client
end
--[[
Move an unauthenticated client to the list of clients that have been authenticated.
client - the client.
]]--
function ConnectionStream:_promoteClient(client)
local datacenter = client:getDatacenter()
client:log(logging.INFO, fmt('Connection has been authenticated to %s', datacenter))
self._clients[datacenter] = client
self._unauthedClients[datacenter] = nil
end
--[[
Create and establish a connection to the endpoint.
datacenter - Datacenter name / host alias.
host - Hostname.
port - Port.
callback - Callback called with (err)
]]--
function ConnectionStream:createConnection(options, callback)
local opts = misc.merge({
id = self._id,
token = self._token,
timeout = CONNECT_TIMEOUT
}, options)
local client = AgentClient:new(opts)
client:on('error', function(err)
err.host = opts.host
err.port = opts.port
err.datacenter = opts.datacenter
client:destroy()
self:reconnect(opts, callback)
if err then
self:emit('error', err)
end
end)
client:on('timeout', function()
logging.log(logging.DEBUG, fmt('%s:%d -> Client Timeout', opts.host, opts.port))
client:destroy()
self:reconnect(opts, callback)
end)
client:on('end', function()
self:emit('client_end', client)
logging.log(logging.DEBUG, fmt('%s:%d -> Remote endpoint closed the connection', opts.host, opts.port))
client:destroy()
self:reconnect(opts, callback)
end)
client:on('handshake_success', function()
self:_promoteClient(client)
self._delays[options.datacenter] = 0
client:startPingInterval()
self._messages:emit('handshake_success', client)
end)
client:on('message', function(msg)
self._messages:emit('message', client, msg)
end)
client:connect(function(err)
if err then
client:destroy()
self:reconnect(opts, callback)
callback(err)
return
end
client.datacenter = datacenter
self._unauthedClients[datacenter] = client
callback();
end)
return client
end
local exports = {}
exports.ConnectionStream = ConnectionStream
return exports
|
fix getLatency
|
fix getLatency
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
e1473139468da410b2e6b964c098399bdcac261d
|
hymn/spawnportal.lua
|
hymn/spawnportal.lua
|
local Building = require "shared.building"
local LogicCore = require "hymn.logiccore"
local EntityStatics = require "hymn.staticdata.entitystatics"
local SpawnPortal = Building:subclass("SpawnPortal")
function SpawnPortal:initialize(entityStatic, player)
Building.initialize(self, entityStatic, player)
self:setPlayer(player)
self:setAnimation("images/buildings/constructionsite.png", 1)
self.timeSinceLastSpawn = 0
self.path = {}
end
local themes = {
"frost",
"lava",
}
function SpawnPortal:setPlayer(player)
self.player = player
self.theme = themes[player.playerId] or themes[1]
-- self:setAnimation("images/buildings/" .. self.theme .. "/portal.png", 0.1)
end
function SpawnPortal:addPathPoint(position)
self.path[#self.path + 1] = position
end
function SpawnPortal:spawnInterval()
return self.player.resource / 100
end
function SpawnPortal:update(dt)
Building.update(self, dt)
if not self.constructing then
local entityManager = LogicCore.entityManager
self.timeSinceLastSpawn = self.timeSinceLastSpawn + dt
local spawnInterval = self:spawnInterval()
if self.timeSinceLastSpawn >= spawnInterval then
-- SPAWN
local spawn = entityManager:spawnFromEntityStatic(self.spawnEntityStatics, self.player)
spawn:setPosition(self.position.x, self.position.y)
spawn.userPath = {}
for k, v in pairs(self.path) do
spawn.userPath[k] = v:copy()
end
self.timeSinceLastSpawn = self.timeSinceLastSpawn - spawnInterval
self.hasSpawned = true
end
end
end
function SpawnPortal:clearPath()
self.path = {}
end
return SpawnPortal
|
local Building = require "shared.building"
local LogicCore = require "hymn.logiccore"
local EntityStatics = require "hymn.staticdata.entitystatics"
local SpawnPortal = Building:subclass("SpawnPortal")
function SpawnPortal:initialize(entityStatic, player)
Building.initialize(self, entityStatic, player)
self:setPlayer(player)
self:setAnimation("images/buildings/constructionsite.png", 1)
self.timeSinceLastSpawn = 0
self.path = {}
end
function SpawnPortal:setPlayer(player)
self.player = player
self.theme = player:theme()
-- self:setAnimation("images/buildings/" .. self.theme .. "/portal.png", 0.1)
end
function SpawnPortal:addPathPoint(position)
self.path[#self.path + 1] = position
end
function SpawnPortal:spawnInterval()
return 400/self.player.resource
end
function SpawnPortal:update(dt)
Building.update(self, dt)
if not self.constructing then
local entityManager = LogicCore.entityManager
self.timeSinceLastSpawn = self.timeSinceLastSpawn + dt
local spawnInterval = self:spawnInterval()
if self.timeSinceLastSpawn >= spawnInterval then
-- SPAWN
local spawn = entityManager:spawnFromEntityStatic(self.spawnEntityStatics, self.player)
spawn:setPosition(self.position.x, self.position.y)
spawn.userPath = {}
for k, v in pairs(self.path) do
spawn.userPath[k] = v:copy()
end
self.timeSinceLastSpawn = self.timeSinceLastSpawn - spawnInterval
self.hasSpawned = true
end
end
end
function SpawnPortal:clearPath()
self.path = {}
end
return SpawnPortal
|
Fix: more resources == faster spawn
|
Fix: more resources == faster spawn
|
Lua
|
mit
|
ExcelF/project-navel
|
44d7d6cd2963d58168e2dcd84f3fe81d1e6336e5
|
inputbox.lua
|
inputbox.lua
|
require "rendertext"
require "keys"
require "graphics"
InputBox = {
-- Class vars:
h = 100,
input_slot_w = nil,
input_start_x = 145,
input_start_y = nil,
input_cur_x = nil, -- points to the start of next input pos
input_bg = 0,
input_string = "",
shiftmode = false,
altmode = false,
cursor = nil,
-- font for displaying input content
-- we have to use mono here for better distance controlling
face = freetype.newBuiltinFace("mono", 25),
fhash = "m25",
fheight = 25,
fwidth = 15,
}
function InputBox:refreshText()
-- clear previous painted text
fb.bb:paintRect(140, self.input_start_y-19,
self.input_slot_w, self.fheight, self.input_bg)
-- paint new text
renderUtf8Text(fb.bb, self.input_start_x, self.input_start_y,
self.face, self.fhash,
self.input_string, 0)
end
function InputBox:addChar(char)
self.cursor:clear()
-- draw new text
local cur_index = (self.cursor.x_pos + 3 - self.input_start_x)
/ self.fwidth
self.input_string = self.input_string:sub(0,cur_index)..char..
self.input_string:sub(cur_index+1)
self:refreshText()
self.input_cur_x = self.input_cur_x + self.fwidth
-- draw new cursor
self.cursor:moveHorizontal(self.fwidth)
self.cursor:draw()
fb:refresh(1, self.input_start_x-5, self.input_start_y-25,
self.input_slot_w, self.h-25)
end
function InputBox:delChar()
if self.input_start_x == self.input_cur_x then
return
end
self.cursor:clear()
-- draw new text
local cur_index = (self.cursor.x_pos + 3 - self.input_start_x)
/ self.fwidth
self.input_string = self.input_string:sub(0,cur_index-1)..
self.input_string:sub(cur_index+1, -1)
self:refreshText()
self.input_cur_x = self.input_cur_x - self.fwidth
-- draw new cursor
self.cursor:moveHorizontal(-self.fwidth)
self.cursor:draw()
fb:refresh(1, self.input_start_x-5, self.input_start_y-25,
self.input_slot_w, self.h-25)
end
function InputBox:clearText()
self.cursor:clear()
self.input_string = ""
self:refreshText()
self.cursor.x_pos = self.input_start_x - 3
self.cursor:draw()
fb:refresh(1, self.input_start_x-5, self.input_start_y-25,
self.input_slot_w, self.h-25)
end
function InputBox:drawBox(ypos, w, h, title)
-- draw input border
fb.bb:paintRect(20, ypos, w, h, 5)
-- draw input slot
fb.bb:paintRect(140, ypos + 10, w - 130, h - 20, self.input_bg)
-- draw input title
renderUtf8Text(fb.bb, 35, self.input_start_y, self.face, self.fhash,
title, true)
end
----------------------------------------------------------------------
-- InputBox:input()
--
-- @title: input prompt for the box
-- @d_text: default to nil (used to set default text in input slot)
----------------------------------------------------------------------
function InputBox:input(ypos, height, title, d_text)
-- do some initilization
self.h = height
self.input_start_y = ypos + 35
self.input_cur_x = self.input_start_x
self.input_slot_w = fb.bb:getWidth() - 170
self.cursor = Cursor:new {
x_pos = self.input_start_x - 3,
y_pos = ypos + 13,
h = 30,
}
-- draw box and content
w = fb.bb:getWidth() - 40
h = height - 45
self:drawBox(ypos, w, h, title)
if d_text then
self.input_string = d_text
self.input_cur_x = self.input_cur_x + (self.fwidth * d_text:len())
self.cursor.x_pos = self.cursor.x_pos + (self.fwidth * d_text:len())
self:refreshText()
end
self.cursor:draw()
fb:refresh(1, 20, ypos, w, h)
while true do
local ev = input.waitForEvent()
ev.code = adjustKeyEvents(ev)
if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then
--local secs, usecs = util.gettime()
if ev.code == KEY_FW_UP then
elseif ev.code == KEY_FW_DOWN then
elseif ev.code == KEY_A then
self:addChar("a")
elseif ev.code == KEY_B then
self:addChar("b")
elseif ev.code == KEY_C then
self:addChar("c")
elseif ev.code == KEY_D then
self:addChar("d")
elseif ev.code == KEY_E then
self:addChar("e")
elseif ev.code == KEY_F then
self:addChar("f")
elseif ev.code == KEY_G then
self:addChar("g")
elseif ev.code == KEY_H then
self:addChar("h")
elseif ev.code == KEY_I then
self:addChar("i")
elseif ev.code == KEY_J then
self:addChar("j")
elseif ev.code == KEY_K then
self:addChar("k")
elseif ev.code == KEY_L then
self:addChar("l")
elseif ev.code == KEY_M then
self:addChar("m")
elseif ev.code == KEY_N then
self:addChar("n")
elseif ev.code == KEY_O then
self:addChar("o")
elseif ev.code == KEY_P then
self:addChar("p")
elseif ev.code == KEY_Q then
self:addChar("q")
elseif ev.code == KEY_R then
self:addChar("r")
elseif ev.code == KEY_S then
self:addChar("s")
elseif ev.code == KEY_T then
self:addChar("t")
elseif ev.code == KEY_U then
self:addChar("u")
elseif ev.code == KEY_V then
self:addChar("v")
elseif ev.code == KEY_W then
self:addChar("w")
elseif ev.code == KEY_X then
self:addChar("x")
elseif ev.code == KEY_Y then
self:addChar("y")
elseif ev.code == KEY_Z then
self:addChar("z")
elseif ev.code == KEY_1 then
self:addChar("1")
elseif ev.code == KEY_2 then
self:addChar("2")
elseif ev.code == KEY_3 then
self:addChar("3")
elseif ev.code == KEY_4 then
self:addChar("4")
elseif ev.code == KEY_5 then
self:addChar("5")
elseif ev.code == KEY_6 then
self:addChar("6")
elseif ev.code == KEY_7 then
self:addChar("7")
elseif ev.code == KEY_8 then
self:addChar("8")
elseif ev.code == KEY_9 then
self:addChar("9")
elseif ev.code == KEY_0 then
self:addChar("0")
elseif ev.code == KEY_SPACE then
self:addChar(" ")
elseif ev.code == KEY_PGFWD then
elseif ev.code == KEY_PGBCK then
elseif ev.code == KEY_FW_LEFT then
if (self.cursor.x_pos + 3) > self.input_start_x then
self.cursor:moveHorizontalAndDraw(-self.fwidth)
fb:refresh(1, self.input_start_x-5, ypos,
self.input_slot_w, h)
end
elseif ev.code == KEY_FW_RIGHT then
if (self.cursor.x_pos + 3) < self.input_cur_x then
self.cursor:moveHorizontalAndDraw(self.fwidth)
fb:refresh(1,self.input_start_x-5, ypos,
self.input_slot_w, h)
end
elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then
if self.input_string == "" then
self.input_string = nil
end
break
elseif ev.code == KEY_DEL then
if Keys.shiftmode then
self:clearText()
else
self:delChar()
end
elseif ev.code == KEY_BACK or ev.code == KEY_HOME then
self.input_string = nil
break
end
--local nsecs, nusecs = util.gettime()
--local dur = (nsecs - secs) * 1000000 + nusecs - usecs
--print("E: T="..ev.type.." V="..ev.value.." C="..ev.code.." DUR="..dur)
end -- if
end -- while
local return_str = self.input_string
self.input_string = ""
return return_str
end
|
require "rendertext"
require "keys"
require "graphics"
InputBox = {
-- Class vars:
h = 100,
input_slot_w = nil,
input_start_x = 145,
input_start_y = nil,
input_cur_x = nil, -- points to the start of next input pos
input_bg = 0,
input_string = "",
shiftmode = false,
altmode = false,
cursor = nil,
-- font for displaying input content
-- we have to use mono here for better distance controlling
face = freetype.newBuiltinFace("mono", 25),
fhash = "m25",
fheight = 25,
fwidth = 15,
}
function InputBox:refreshText()
-- clear previous painted text
fb.bb:paintRect(140, self.input_start_y-19,
self.input_slot_w, self.fheight, self.input_bg)
-- paint new text
renderUtf8Text(fb.bb, self.input_start_x, self.input_start_y,
self.face, self.fhash,
self.input_string, 0)
end
function InputBox:addChar(char)
self.cursor:clear()
-- draw new text
local cur_index = (self.cursor.x_pos + 3 - self.input_start_x)
/ self.fwidth
self.input_string = self.input_string:sub(0,cur_index)..char..
self.input_string:sub(cur_index+1)
self:refreshText()
self.input_cur_x = self.input_cur_x + self.fwidth
-- draw new cursor
self.cursor:moveHorizontal(self.fwidth)
self.cursor:draw()
fb:refresh(1, self.input_start_x-5, self.input_start_y-25,
self.input_slot_w, self.h-25)
end
function InputBox:delChar()
if self.input_start_x == self.input_cur_x then
return
end
local cur_index = (self.cursor.x_pos + 3 - self.input_start_x)
/ self.fwidth
if cur_index == 0 then return end
self.cursor:clear()
-- draw new text
self.input_string = self.input_string:sub(0,cur_index-1)..
self.input_string:sub(cur_index+1, -1)
self:refreshText()
self.input_cur_x = self.input_cur_x - self.fwidth
-- draw new cursor
self.cursor:moveHorizontal(-self.fwidth)
self.cursor:draw()
fb:refresh(1, self.input_start_x-5, self.input_start_y-25,
self.input_slot_w, self.h-25)
end
function InputBox:clearText()
self.cursor:clear()
self.input_string = ""
self:refreshText()
self.cursor.x_pos = self.input_start_x - 3
self.cursor:draw()
fb:refresh(1, self.input_start_x-5, self.input_start_y-25,
self.input_slot_w, self.h-25)
end
function InputBox:drawBox(ypos, w, h, title)
-- draw input border
fb.bb:paintRect(20, ypos, w, h, 5)
-- draw input slot
fb.bb:paintRect(140, ypos + 10, w - 130, h - 20, self.input_bg)
-- draw input title
renderUtf8Text(fb.bb, 35, self.input_start_y, self.face, self.fhash,
title, true)
end
----------------------------------------------------------------------
-- InputBox:input()
--
-- @title: input prompt for the box
-- @d_text: default to nil (used to set default text in input slot)
----------------------------------------------------------------------
function InputBox:input(ypos, height, title, d_text)
-- do some initilization
self.h = height
self.input_start_y = ypos + 35
self.input_cur_x = self.input_start_x
self.input_slot_w = fb.bb:getWidth() - 170
self.cursor = Cursor:new {
x_pos = self.input_start_x - 3,
y_pos = ypos + 13,
h = 30,
}
-- draw box and content
w = fb.bb:getWidth() - 40
h = height - 45
self:drawBox(ypos, w, h, title)
if d_text then
self.input_string = d_text
self.input_cur_x = self.input_cur_x + (self.fwidth * d_text:len())
self.cursor.x_pos = self.cursor.x_pos + (self.fwidth * d_text:len())
self:refreshText()
end
self.cursor:draw()
fb:refresh(1, 20, ypos, w, h)
while true do
local ev = input.waitForEvent()
ev.code = adjustKeyEvents(ev)
if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then
--local secs, usecs = util.gettime()
if ev.code == KEY_FW_UP then
elseif ev.code == KEY_FW_DOWN then
elseif ev.code == KEY_A then
self:addChar("a")
elseif ev.code == KEY_B then
self:addChar("b")
elseif ev.code == KEY_C then
self:addChar("c")
elseif ev.code == KEY_D then
self:addChar("d")
elseif ev.code == KEY_E then
self:addChar("e")
elseif ev.code == KEY_F then
self:addChar("f")
elseif ev.code == KEY_G then
self:addChar("g")
elseif ev.code == KEY_H then
self:addChar("h")
elseif ev.code == KEY_I then
self:addChar("i")
elseif ev.code == KEY_J then
self:addChar("j")
elseif ev.code == KEY_K then
self:addChar("k")
elseif ev.code == KEY_L then
self:addChar("l")
elseif ev.code == KEY_M then
self:addChar("m")
elseif ev.code == KEY_N then
self:addChar("n")
elseif ev.code == KEY_O then
self:addChar("o")
elseif ev.code == KEY_P then
self:addChar("p")
elseif ev.code == KEY_Q then
self:addChar("q")
elseif ev.code == KEY_R then
self:addChar("r")
elseif ev.code == KEY_S then
self:addChar("s")
elseif ev.code == KEY_T then
self:addChar("t")
elseif ev.code == KEY_U then
self:addChar("u")
elseif ev.code == KEY_V then
self:addChar("v")
elseif ev.code == KEY_W then
self:addChar("w")
elseif ev.code == KEY_X then
self:addChar("x")
elseif ev.code == KEY_Y then
self:addChar("y")
elseif ev.code == KEY_Z then
self:addChar("z")
elseif ev.code == KEY_1 then
self:addChar("1")
elseif ev.code == KEY_2 then
self:addChar("2")
elseif ev.code == KEY_3 then
self:addChar("3")
elseif ev.code == KEY_4 then
self:addChar("4")
elseif ev.code == KEY_5 then
self:addChar("5")
elseif ev.code == KEY_6 then
self:addChar("6")
elseif ev.code == KEY_7 then
self:addChar("7")
elseif ev.code == KEY_8 then
self:addChar("8")
elseif ev.code == KEY_9 then
self:addChar("9")
elseif ev.code == KEY_0 then
self:addChar("0")
elseif ev.code == KEY_SPACE then
self:addChar(" ")
elseif ev.code == KEY_PGFWD then
elseif ev.code == KEY_PGBCK then
elseif ev.code == KEY_FW_LEFT then
if (self.cursor.x_pos + 3) > self.input_start_x then
self.cursor:moveHorizontalAndDraw(-self.fwidth)
fb:refresh(1, self.input_start_x-5, ypos,
self.input_slot_w, h)
end
elseif ev.code == KEY_FW_RIGHT then
if (self.cursor.x_pos + 3) < self.input_cur_x then
self.cursor:moveHorizontalAndDraw(self.fwidth)
fb:refresh(1,self.input_start_x-5, ypos,
self.input_slot_w, h)
end
elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then
if self.input_string == "" then
self.input_string = nil
end
break
elseif ev.code == KEY_DEL then
if Keys.shiftmode then
self:clearText()
else
self:delChar()
end
elseif ev.code == KEY_BACK or ev.code == KEY_HOME then
self.input_string = nil
break
end
--local nsecs, nusecs = util.gettime()
--local dur = (nsecs - secs) * 1000000 + nusecs - usecs
--print("E: T="..ev.type.." V="..ev.value.." C="..ev.code.." DUR="..dur)
end -- if
end -- while
local return_str = self.input_string
self.input_string = ""
return return_str
end
|
fix: handle -1 index when deleting characters in inputbox
|
fix: handle -1 index when deleting characters in inputbox
|
Lua
|
agpl-3.0
|
Hzj-jie/koreader-base,apletnev/koreader-base,houqp/koreader-base,koreader/koreader-base,frankyifei/koreader-base,NiLuJe/koreader,NiLuJe/koreader-base,chrox/koreader,Hzj-jie/koreader-base,poire-z/koreader,houqp/koreader-base,ashhher3/koreader,frankyifei/koreader-base,koreader/koreader-base,houqp/koreader-base,Frenzie/koreader,frankyifei/koreader-base,mwoz123/koreader,NiLuJe/koreader-base,frankyifei/koreader,Frenzie/koreader-base,frankyifei/koreader-base,koreader/koreader-base,robert00s/koreader,Hzj-jie/koreader,ashang/koreader,apletnev/koreader-base,Frenzie/koreader,NickSavage/koreader,chihyang/koreader,Hzj-jie/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,NiLuJe/koreader,NiLuJe/koreader-base,mihailim/koreader,lgeek/koreader,Markismus/koreader,koreader/koreader,Frenzie/koreader-base,noname007/koreader,koreader/koreader,koreader/koreader-base,Hzj-jie/koreader-base,apletnev/koreader-base,houqp/koreader-base,apletnev/koreader-base,poire-z/koreader,pazos/koreader,houqp/koreader,apletnev/koreader
|
6f33ff6515128a3a0b5a3d94d525e5cc5ca2555c
|
lua/rima/operators/pow.lua
|
lua/rima/operators/pow.lua
|
-- Copyright (c) 2009-2011 Incremental IP Limited
-- see LICENSE for license information
local math = require("math")
local error, type = error, type
local object = require("rima.lib.object")
local proxy = require("rima.lib.proxy")
local lib = require("rima.lib")
local core = require("rima.core")
local expression = require("rima.expression")
local mul = require("rima.operators.mul")
local rima = rima
module(...)
-- Exponentiation --------------------------------------------------------------
local pow = expression:new_type(_M, "pow")
pow.precedence = 0
-- String Representation -------------------------------------------------------
function pow.__repr(args, format)
args = proxy.O(args)
local base, exponent = args[1], args[2]
local repr = lib.repr
local paren = core.parenthise
local prec = pow.precedence
local ff = format.format
if ff == "dump" then
return "^("..repr(base, format)..", "..repr(exponent, format)..")"
elseif ff == "latex" then
return "{"..paren(base, format, prec).."}^{"..repr(exponent, format).."}"
else
return paren(base, format, prec).."^"..paren(exponent, format, prec)
end
end
-- Evaluation ------------------------------------------------------------------
function pow.__eval(args_in, S)
local args = proxy.O(args_in)
local base, exponent = core.eval(args[1], S), core.eval(args[2], S)
local base_is_number = type(base) == "number"
if base_is_number then
if base == 0 then
return 0
elseif base == 1 then
return 1
end
end
if type(exponent) == "number" then
if exponent == 0 then
return 1
elseif exponent == 1 then
return base
elseif not_base_is_number then
return expression:new(mul, {exponent, base})
else -- base is a number
return base ^ exponent
end
end
if base == args[1] and exponent == args[2] then
return args_in
else
return base ^ exponent
end
end
-- Automatic differentiation ---------------------------------------------------
function pow.__diff(args, v)
args = proxy.O(args)
local base, exponent = args[1], args[2]
local base_is_number = type(base) == "number"
if type(exponent) == "number" then
if base_is_number then return 0 end
return core.diff(base, v) * exponent * base ^ (exponent - 1)
end
if base_is_number then
return core.diff(exponent, v) * math.log(base) * base ^ exponent
end
return core.diff(exponent * rima.log(base), v) * base ^ exponent
end
-- EOF -------------------------------------------------------------------------
|
-- Copyright (c) 2009-2011 Incremental IP Limited
-- see LICENSE for license information
local math = require("math")
local error, require, type =
error, require, type
local object = require("rima.lib.object")
local proxy = require("rima.lib.proxy")
local lib = require("rima.lib")
local core = require("rima.core")
local expression = require("rima.expression")
local mul = require("rima.operators.mul")
local rima = rima
module(...)
require("rima.operators.math")
-- Exponentiation --------------------------------------------------------------
local pow = expression:new_type(_M, "pow")
pow.precedence = 0
-- String Representation -------------------------------------------------------
function pow.__repr(args, format)
args = proxy.O(args)
local base, exponent = args[1], args[2]
local repr = lib.repr
local paren = core.parenthise
local prec = pow.precedence
local ff = format.format
if ff == "dump" then
return "^("..repr(base, format)..", "..repr(exponent, format)..")"
elseif ff == "latex" then
return "{"..paren(base, format, prec).."}^{"..repr(exponent, format).."}"
else
return paren(base, format, prec).."^"..paren(exponent, format, prec)
end
end
-- Evaluation ------------------------------------------------------------------
function pow.__eval(args_in, S)
local args = proxy.O(args_in)
local base, exponent = core.eval(args[1], S), core.eval(args[2], S)
local base_is_number = type(base) == "number"
if base_is_number then
if base == 0 then
return 0
elseif base == 1 then
return 1
end
end
if type(exponent) == "number" then
if exponent == 0 then
return 1
elseif exponent == 1 then
return base
elseif not_base_is_number then
return expression:new(mul, {exponent, base})
else -- base is a number
return base ^ exponent
end
end
if base == args[1] and exponent == args[2] then
return args_in
else
return base ^ exponent
end
end
-- Automatic differentiation ---------------------------------------------------
function pow.__diff(args, v)
args = proxy.O(args)
local base, exponent = args[1], args[2]
local base_is_number = type(base) == "number"
if type(exponent) == "number" then
if base_is_number then return 0 end
return core.diff(base, v) * exponent * base ^ (exponent - 1)
end
if base_is_number then
return core.diff(exponent, v) * math.log(base) * base ^ exponent
end
return core.diff(exponent * rima.log(base), v) * base ^ exponent
end
-- EOF -------------------------------------------------------------------------
|
fixed a bug in pow.lua - it needed to require rima.operators.math to use rima.log
|
fixed a bug in pow.lua - it needed to require rima.operators.math to use rima.log
|
Lua
|
mit
|
geoffleyland/rima,geoffleyland/rima,geoffleyland/rima
|
28d636c474d6076d2d394e3fe9f420b2fa93ff02
|
spec/spec_helper.lua
|
spec/spec_helper.lua
|
--- nasty monkey patch to create new notification for the whole it block
--- busted does not have builtin way of having a hook around a test with its before/after hooks
do
local function getlocal(fn, var)
local i = 1
while true do
local name, val = debug.getlocal(fn + 1, i)
if name == var then
return val
elseif not name then
break
end
i = i + 1
end
end
local function getupvalue(fn, var)
local i = 1
while true do
local name, val = debug.getupvalue(fn, i)
if name == var then
return val
elseif not name then
break
end
i = i + 1
end
end
--- busted/runner.lua:147 is 5 stacks above
-- https://github.com/Olivine-Labs/busted/blob/v2.0.rc12-1/busted/runner.lua#L147
local busted = getlocal(5, 'busted')
--- busted/core.lua:240 has "executors" upvalue available
-- https://github.com/Olivine-Labs/busted/blob/v2.0.rc12-1/busted/core.lua#L240
local executors = getupvalue(busted.register, 'executors')
--- busted/init.lua:20 defines the "it" method we want to wrap around
-- https://github.com/Olivine-Labs/busted/blob/v2.0.rc12-1/busted/init.lua#L20
local it = executors.it
busted.register('it', function(element)
local parent = busted.context.parent(element)
if busted.safe_publish('it', { 'it', 'start' }, element, parent) then
it(element)
end
busted.safe_publish('it', { 'it', 'end' }, element, parent)
end)
end
require 'luassert_helper'
require 'ngx_helper'
require 'jwt_helper'
local busted = require('busted')
local env = require('resty.env')
local previous_env = {}
local set = env.set
local null = {'null'}
-- override resty.env.set with custom function that remembers previous values
env.set = function(name, ...)
local previous = set(name, ...)
if not previous_env[name] then
previous_env[name] = previous or null
end
return previous
end
-- so they can be reset back to the values before the test run
local function reset()
for name, value in pairs(previous_env) do
if value == null then
value = nil
end
set(name, value)
end
previous_env = {}
env.reset()
-- To make sure that we are using valid policy configs in the tests.
set('APICAST_VALIDATE_POLICY_CONFIGS', true)
end
busted.before_each(reset)
busted.after_each(reset)
local resty_proxy = require('resty.http.proxy')
busted.before_each(function()
resty_proxy:reset()
end)
local resty_resolver = require 'resty.resolver'
busted.before_each(resty_resolver.reset)
busted.subscribe({ 'file', 'start' }, function ()
require('apicast.loader')
return nil, true -- needs to return true as second return value to continue executing the chain
end)
busted.subscribe({ 'file', 'end' }, function ()
collectgarbage()
return nil, true
end)
do
-- busted does auto-insulation and tries to reload all files for every test file
-- that breaks ffi.cdef as it can't be called several times with the same argument
-- backports https://github.com/Olivine-Labs/busted/commit/db6d8b4be8fd099ab387efeb8232cfd905912abb
local ffi = require('ffi')
local cdef = ffi.cdef
local cdef_cache = {}
function ffi.cdef(def)
if not cdef_cache[def] then
cdef(def)
cdef_cache[def] = true
end
end
end
_G.fixture = function (...)
local path = require('pl.path')
local file = require('pl.file')
return file.read(path.join('spec', 'fixtures', ...))
end
do -- stub http_ng
local http_ng = require('resty.http_ng')
local test_backend_client = require 'resty.http_ng.backend.test'
local test_backend
local stub = require('luassert.stub')
local stubbed
busted.before_each(function()
test_backend = test_backend_client.new()
stubbed = stub(http_ng, 'backend', test_backend)
end)
busted.after_each(function()
test_backend.verify_no_outstanding_expectations()
stubbed:revert()
end)
end
|
--- nasty monkey patch to create new notification for the whole it block
--- busted does not have builtin way of having a hook around a test with its before/after hooks
do
local function getlocal(fn, var)
local i = 1
while true do
local name, val = debug.getlocal(fn + 1, i)
if name == var then
return val
elseif not name then
break
end
i = i + 1
end
end
local function getupvalue(fn, var)
local i = 1
while true do
local name, val = debug.getupvalue(fn, i)
if name == var then
return val
elseif not name then
break
end
i = i + 1
end
end
--- busted/runner.lua:147 is 5 stacks above
-- https://github.com/Olivine-Labs/busted/blob/v2.0.rc12-1/busted/runner.lua#L147
local busted = getlocal(5, 'busted')
--- busted/core.lua:240 has "executors" upvalue available
-- https://github.com/Olivine-Labs/busted/blob/v2.0.rc12-1/busted/core.lua#L240
local executors = getupvalue(busted.register, 'executors')
--- busted/init.lua:20 defines the "it" method we want to wrap around
-- https://github.com/Olivine-Labs/busted/blob/v2.0.rc12-1/busted/init.lua#L20
local it = executors.it
busted.register('it', function(element)
local parent = busted.context.parent(element)
if busted.safe_publish('it', { 'it', 'start' }, element, parent) then
it(element)
end
busted.safe_publish('it', { 'it', 'end' }, element, parent)
end)
end
require 'luassert_helper'
require 'ngx_helper'
require 'jwt_helper'
local busted = require('busted')
local env = require('resty.env')
local previous_env = {}
local set = env.set
local null = {'null'}
-- override resty.env.set with custom function that remembers previous values
env.set = function(name, ...)
local previous = set(name, ...)
if not previous_env[name] then
previous_env[name] = previous or null
end
return previous
end
-- so they can be reset back to the values before the test run
local function reset()
for name, value in pairs(previous_env) do
if value == null then
value = nil
end
set(name, value)
end
previous_env = {}
env.reset()
-- To make sure that we are using valid policy configs in the tests.
set('APICAST_VALIDATE_POLICY_CONFIGS', true)
end
busted.before_each(reset)
busted.after_each(reset)
local resty_proxy = require('resty.http.proxy')
busted.before_each(function()
resty_proxy:reset()
end)
local resty_resolver = require 'resty.resolver'
busted.before_each(resty_resolver.reset)
busted.subscribe({ 'file', 'start' }, function ()
require('apicast.loader')
return nil, true -- needs to return true as second return value to continue executing the chain
end)
busted.subscribe({ 'file', 'end' }, function ()
collectgarbage()
return nil, true
end)
do
-- busted does auto-insulation and tries to reload all files for every test file
-- that breaks ffi.cdef as it can't be called several times with the same argument
-- backports https://github.com/Olivine-Labs/busted/commit/db6d8b4be8fd099ab387efeb8232cfd905912abb
local ffi = require('ffi')
local cdef = ffi.cdef
local cdef_cache = {}
function ffi.cdef(def)
if not cdef_cache[def] then
cdef(def)
cdef_cache[def] = true
end
end
end
_G.fixture = function (...)
local path = require('pl.path')
local file = require('pl.file')
return file.read(path.join('spec', 'fixtures', ...)) or file.read(path.join('t', 'fixtures', ...))
end
do -- stub http_ng
local http_ng = require('resty.http_ng')
local test_backend_client = require 'resty.http_ng.backend.test'
local test_backend
local stub = require('luassert.stub')
local stubbed
busted.before_each(function()
test_backend = test_backend_client.new()
stubbed = stub(http_ng, 'backend', test_backend)
end)
busted.after_each(function()
test_backend.verify_no_outstanding_expectations()
stubbed:revert()
end)
end
|
[busted] load integration fixtures too
|
[busted] load integration fixtures too
|
Lua
|
mit
|
3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/apicast
|
fb65fc13cd59784b0acf2e7468e6e9ff8cb388a2
|
packages/ubus-lime-utils/tests/test_hotspot_wwan.lua
|
packages/ubus-lime-utils/tests/test_hotspot_wwan.lua
|
local utils = require "lime.utils"
local test_utils = require "tests.utils"
local config = require 'lime.config'
local hotspot_wwan = require "lime.hotspot_wwan"
local iwinfo = require "iwinfo"
local uci
stub(hotspot_wwan, "_apply_change", function () return '' end)
function config_uci_hotspot_radio()
uci:set('wireless', 'radio0', 'wifi-device')
uci:set('wireless', 'radio0', 'type', 'mac80211')
uci:set('wireless', 'radio0', 'channel', '4')
uci:set('wireless', 'radio0', 'hwmode', '11a')
uci:set('wireless', 'radio0', 'macaddr', '01:23:45:67:89:AB')
uci:set('wireless', 'radio0', 'disabled', '0')
uci:set('wireless', 'lm_client_wwan', 'wifi-iface')
uci:set('wireless', 'lm_client_wwan', 'device', 'radio0')
uci:set('wireless', 'lm_client_wwan', 'network', 'lm_client_wwan')
uci:set('wireless', 'lm_client_wwan', 'mode', 'sta')
uci:set('wireless', 'lm_client_wwan', 'ifname', 'client-wan')
uci:commit('wireless')
end
describe('hotspot_wwan tests #hotspot_wwan', function()
local snapshot -- to revert luassert stubs and spies
it('test enable default args', function()
local status = hotspot_wwan.status('radio1')
assert.is_false(status.enabled)
hotspot_wwan.enable()
uci:load('wireless')
local expected = {
'wireless.radio0.disabled=0',
'wireless.radio0.channel=auto',
'wireless.lm_client_wwan=wifi-iface',
'wireless.lm_client_wwan.device=radio0',
'wireless.lm_client_wwan.network=lm_client_wwan',
'wireless.lm_client_wwan.mode=sta',
'wireless.lm_client_wwan.ifname=client-wwan',
'wireless.lm_client_wwan.ssid=internet',
'wireless.lm_client_wwan.encryption=psk2',
'wireless.lm_client_wwan.key=internet',
'network.lm_client_wwan=interface',
'network.lm_client_wwan.proto=dhcp',
}
assert.is.equal("generic_uci_config", uci:get(config.UCI_NODE_NAME, 'hotspot_wwan'))
assert.are.same(expected, uci:get(config.UCI_NODE_NAME, 'hotspot_wwan', 'uci_set'))
hotspot_wwan.disable()
assert.is_nil(uci:get(config.UCI_NODE_NAME, 'hotspot_wwan'))
end)
it('test hotspot_wwan_enable with args', function()
local status
local retval = hotspot_wwan.enable(nil, 'mypass', nil, 'radio1')
assert.is_true(retval)
assert.is.equal("generic_uci_config", uci:get(config.UCI_NODE_NAME, 'hotspot_wwan'))
status = hotspot_wwan.status('radio1')
assert.is_true(status.enabled)
retval = hotspot_wwan.disable('radio1')
assert.is_true(retval)
assert.is_nil(uci:get(config.UCI_NODE_NAME, 'hotspot_wwan'))
status = hotspot_wwan.status('radio1')
assert.is_false(status.enabled)
end)
it('test hotspot_wwan_get_status when not connected', function()
local status = hotspot_wwan.status('radio1')
assert.is_false(status.connected)
end)
it('test hotspot_wwan_is_connected when connected', function()
local sta = iwinfo.fake.gen_assoc_station("HT20", "HT40", -66, 50, 10000, 300, 120)
local assoclist = {['AA:BB:CC:DD:EE:FF'] = sta}
iwinfo.fake.set_assoclist(hotspot_wwan.IFACE_NAME, assoclist)
local status = hotspot_wwan.status('radio1')
assert.is_true(status.connected)
assert.is.equal(-66, status.signal)
end)
it('test is_safe is false when no mesh ifaces configured', function()
uci:set('wireless', 'radio0', 'wifi-device')
uci:set('wireless', 'radio0', 'type', 'mac80211')
uci:set('wireless', 'radio0', 'channel', '4')
uci:set('wireless', 'radio0', 'hwmode', '11a')
uci:set('wireless', 'radio0', 'macaddr', '01:23:45:67:89:AB')
uci:set('wireless', 'radio0', 'disabled', '0')
uci:commit('wireless')
local is_safe = hotspot_wwan._is_safe('internet', 'psk2', 'radio0')
assert.is_true(is_safe)
end)
it('test is_safe is false when mesh ifaces configured', function()
uci:set('wireless', 'radio0', 'wifi-device')
uci:set('wireless', 'radio0', 'type', 'mac80211')
uci:set('wireless', 'radio0', 'channel', '4')
uci:set('wireless', 'radio0', 'hwmode', '11a')
uci:set('wireless', 'radio0', 'macaddr', '01:23:45:67:89:AB')
uci:set('wireless', 'radio0', 'disabled', '0')
uci:set('wireless', 'lm_client_wwan', 'wifi-iface')
uci:set('wireless', 'lm_client_wwan', 'device', 'radio0')
uci:set('wireless', 'lm_client_wwan', 'network', 'lm_client_wwan')
uci:set('wireless', 'lm_client_wwan', 'mode', 'sta')
uci:set('wireless', 'lm_client_wwan', 'ifname', 'client-wan')
uci:commit('wireless')
local is_safe = hotspot_wwan._is_safe('internet', 'psk2', 'radio0')
assert.is_false(is_safe)
end)
it('test is_safe', function()
config_uci_hotspot_radio()
local ap = {
["encryption"] = {["enabled"] = true, ["wpa"] = 2},
["ssid"] = 'internet',
["mode"] = "Master",
}
iwinfo.fake.set_scanlist('client-wan', {ap})
local is_safe = hotspot_wwan._is_safe('internet', 'psk2', 'radio0')
assert.is_true(is_safe)
end)
it('test is_safe is false when encryption does not match', function()
config_uci_hotspot_radio()
local ap = {
["encryption"] = {["enabled"] = false, ["wpa"] = 0},
["ssid"] = 'internet',
["mode"] = "Master",
}
iwinfo.fake.set_scanlist('client-wan', {ap})
local is_safe = hotspot_wwan._is_safe('internet', 'psk2', 'radio0')
assert.is_false(is_safe)
end)
it('test hotspot_wwan_is_safe when no ifaces configured', function()
local is_safe = hotspot_wwan._is_safe('internet', 'internet', 'psk2')
assert.is_true(is_safe)
end)
before_each('', function()
snapshot = assert:snapshot()
uci = test_utils.setup_test_uci()
end)
after_each('', function()
snapshot:revert()
test_utils.teardown_test_uci(uci)
end)
end)
|
local utils = require "lime.utils"
local test_utils = require "tests.utils"
local config = require 'lime.config'
local hotspot_wwan = require "lime.hotspot_wwan"
local iwinfo = require "iwinfo"
local uci
stub(hotspot_wwan, "_apply_change", function () return '' end)
function config_uci_hotspot_radio()
uci:set('wireless', 'radio0', 'wifi-device')
uci:set('wireless', 'radio0', 'type', 'mac80211')
uci:set('wireless', 'radio0', 'channel', '4')
uci:set('wireless', 'radio0', 'hwmode', '11a')
uci:set('wireless', 'radio0', 'macaddr', '01:23:45:67:89:AB')
uci:set('wireless', 'radio0', 'disabled', '0')
uci:set('wireless', 'lm_client_wwan', 'wifi-iface')
uci:set('wireless', 'lm_client_wwan', 'device', 'radio0')
uci:set('wireless', 'lm_client_wwan', 'network', 'lm_client_wwan')
uci:set('wireless', 'lm_client_wwan', 'mode', 'sta')
uci:set('wireless', 'lm_client_wwan', 'ifname', 'client-wan')
uci:commit('wireless')
end
describe('hotspot_wwan tests #hotspot_wwan', function()
local snapshot -- to revert luassert stubs and spies
it('test enable default args', function()
local status = hotspot_wwan.status('radio1')
assert.is_false(status.enabled)
hotspot_wwan.enable()
uci:load('wireless')
local expected = {
'wireless.radio0.disabled=0',
'wireless.radio0.channel=auto',
'wireless.lm_client_wwan=wifi-iface',
'wireless.lm_client_wwan.device=radio0',
'wireless.lm_client_wwan.network=lm_client_wwan',
'wireless.lm_client_wwan.mode=sta',
'wireless.lm_client_wwan.ifname=client-wwan',
'wireless.lm_client_wwan.ssid=internet',
'wireless.lm_client_wwan.encryption=psk2',
'wireless.lm_client_wwan.key=internet',
'network.lm_client_wwan=interface',
'network.lm_client_wwan.proto=dhcp',
}
assert.is.equal("generic_uci_config", uci:get(config.UCI_NODE_NAME, 'hotspot_wwan'))
assert.are.same(expected, uci:get(config.UCI_NODE_NAME, 'hotspot_wwan', 'uci_set'))
hotspot_wwan.disable()
assert.is_nil(uci:get(config.UCI_NODE_NAME, 'hotspot_wwan'))
end)
it('test hotspot_wwan_enable with args', function()
local status
local retval = hotspot_wwan.enable(nil, 'mypass', nil, 'radio1')
assert.is_true(retval)
assert.is.equal("generic_uci_config", uci:get(config.UCI_NODE_NAME, 'hotspot_wwan'))
status = hotspot_wwan.status('radio1')
assert.is_true(status.enabled)
retval = hotspot_wwan.disable('radio1')
assert.is_true(retval)
assert.is_nil(uci:get(config.UCI_NODE_NAME, 'hotspot_wwan'))
status = hotspot_wwan.status('radio1')
assert.is_false(status.enabled)
end)
it('test hotspot_wwan_get_status when not connected', function()
local status = hotspot_wwan.status('radio1')
assert.is_false(status.connected)
end)
it('test hotspot_wwan_is_connected when connected', function()
local sta = iwinfo.fake.gen_assoc_station("HT20", "HT40", -66, 50, 10000, 300, 120)
local assoclist = {['AA:BB:CC:DD:EE:FF'] = sta}
iwinfo.fake.set_assoclist(hotspot_wwan.IFACE_NAME, assoclist)
local status = hotspot_wwan.status('radio1')
assert.is_true(status.connected)
assert.is.equal(-66, status.signal)
end)
it('test is_safe is true when no mesh ifaces configured', function()
uci:set('wireless', 'radio0', 'wifi-device')
uci:set('wireless', 'radio0', 'type', 'mac80211')
uci:set('wireless', 'radio0', 'channel', '4')
uci:set('wireless', 'radio0', 'hwmode', '11a')
uci:set('wireless', 'radio0', 'macaddr', '01:23:45:67:89:AB')
uci:set('wireless', 'radio0', 'disabled', '0')
uci:commit('wireless')
local is_safe = hotspot_wwan._is_safe('internet', 'psk2', 'radio0')
assert.is_true(is_safe)
end)
it('test is_safe is false when mesh ifaces configured', function()
uci:set('wireless', 'radio0', 'wifi-device')
uci:set('wireless', 'radio0', 'type', 'mac80211')
uci:set('wireless', 'radio0', 'channel', '4')
uci:set('wireless', 'radio0', 'hwmode', '11a')
uci:set('wireless', 'radio0', 'macaddr', '01:23:45:67:89:AB')
uci:set('wireless', 'radio0', 'disabled', '0')
uci:set('wireless', 'lm_wlan0_mesh_radio', 'wifi-iface')
uci:set('wireless', 'lm_wlan0_mesh_radio', 'device', 'radio0')
uci:set('wireless', 'lm_wlan0_mesh_radio', 'network', 'lm_net_wlan0_mesh')
uci:set('wireless', 'lm_wlan0_mesh_radio', 'mode', 'mesh')
uci:set('wireless', 'lm_wlan0_mesh_radio', 'ifname', 'wlan0-mesh')
uci:set('wireless', 'lm_wlan0_mesh_radio', 'mesh_id', 'LiMe')
uci:commit('wireless')
local is_safe = hotspot_wwan._is_safe('internet', 'psk2', 'radio0')
assert.is_false(is_safe)
end)
it('test is_safe', function()
config_uci_hotspot_radio()
local ap = {
["encryption"] = {["enabled"] = true, ["wpa"] = 2},
["ssid"] = 'internet',
["mode"] = "Master",
}
iwinfo.fake.set_scanlist('client-wan', {ap})
local is_safe = hotspot_wwan._is_safe('internet', 'psk2', 'radio0')
assert.is_true(is_safe)
end)
it('test is_safe is false when encryption does not match', function()
config_uci_hotspot_radio()
local ap = {
["encryption"] = {["enabled"] = false, ["wpa"] = 0},
["ssid"] = 'internet',
["mode"] = "Master",
}
iwinfo.fake.set_scanlist('client-wan', {ap})
local is_safe = hotspot_wwan._is_safe('internet', 'psk2', 'radio0')
assert.is_false(is_safe)
end)
it('test hotspot_wwan_is_safe when no ifaces configured', function()
local is_safe = hotspot_wwan._is_safe('internet', 'internet', 'psk2')
assert.is_true(is_safe)
end)
before_each('', function()
snapshot = assert:snapshot()
uci = test_utils.setup_test_uci()
end)
after_each('', function()
snapshot:revert()
test_utils.teardown_test_uci(uci)
end)
end)
|
hotspot-wwan: fix tests
|
hotspot-wwan: fix tests
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
|
48199b8357e6f8d29157a89a68eca45a2b46c507
|
modules/atf/util.lua
|
modules/atf/util.lua
|
local utils = require("atf.stdlib.argument_parser")
config = require('config')
xmlReporter = require("reporter")
local module = { }
local script_files = {}
RequiredArgument = utils.RequiredArgument
OptionalArgument = utils.OptionalArgument
NoArgument = utils.NoArgument
function table2str(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. table2str(v) .. ','
end
return s .. '} \n'
end
return tostring(o)
end
function print_table(t,... )
if (type(t) == 'table' ) then
print(table2str(t).. table2str(table.pack(...)))
else
print(tostring(t).. table2str(table.pack(...)))
end
end
function is_file_exists(name)
local f = io.open(name,"r")
if f ~=nil then io.close(f) return true else return false end
end
function table.removeKey(t, k)
local i = 0
local keys, values = {},{}
for k,v in pairs(t) do
i = i + 1
keys[i] = k
values[i] = v
end
while i>0 do
if keys[i] == k then
table.remove(keys, i)
table.remove(values, i)
break
end
i = i - 1
end
local a = {}
for i = 1,#keys do
a[keys[i]] = values[i]
end
return a
end
function print_startscript(script_name)
print("==============================")
print(string.format("Start '%s'",script_name))
print("==============================")
end
function print_stopscript(script_name)
print("==============================")
print(string.format("Finish '%s'",script_name or script_files[1]))
print("==============================")
end
function compareValues(a, b, name)
local function iter(a, b, name, msg)
if type(a) == 'table' and type(b) == 'table' then
local res = true
for k, v in pairs(a) do
res = res and iter(v, b[k], name .. "." .. k, msg)
end
return res
else
if (type(a) ~= type(b)) then
if (type(a) == 'string' and type(b) == 'number') then
b = tostring(b)
else
table.insert(msg, string.format("type of data %s: expected %s, actual type: %s", name, type(a), type(b)))
return false
end
end
if a == b then
return true
else
table.insert(msg, string.format("%s: expected: %s, actual value: %s", name, a, b))
return false
end
end
end
local message = { }
local res = iter(a, b, name, message)
return res, table.concat(message, '\n')
end
--------------------------------------------------
-- parsing commad line part
function module.config_file(config_file)
if (is_file_exists(config_file)) then
config_file = config_file:gsub('%.', " ")
config_file = config_file:gsub("/", ".")
config_file = config_file:gsub("[%s]lua$", "")
config = require(tostring(config_file))
else
print("Incorrect config file type")
print("Uses default config")
print("==========================")
end
end
function module.mobile_connection(str)
config.mobileHost = str
end
function module.mobile_connection_port(src)
config.mobilePort= src
end
function module.hmi_connection(str)
config.hmiUrl = str
end
function module.hmi_connection_port(src)
config.hmiPort = src
end
function module.perflog_connection(str)
config.perflogConnection=str
end
function module.perflog_connection_port(str)
config.perflogConnectionPort=str
end
function module.report_path(str)
config.reportPath=str
end
function module.report_mark(str)
config.reportMark=str
end
function module.add_script(src)
table.insert(script_files,src)
end
function module.storeFullSDLLogs(str)
config.storeFullSDLLogs=str
end
function module.heartbeat(str)
config.heartbeatTimeout=str
end
function module.sdl_core(str)
if (not is_file_exists(str.."smartDeviceLinkCore")) then
error("SDL is not accessible at the specified path: "..str)
os.exit(1)
end
config.pathToSDL = str
end
function parse_cmdl()
arguments = utils.getopt(argv, opts)
if (arguments) then
if (arguments['config-file']) then module.config_file(arguments['config-file']) end
for k,v in pairs(arguments) do
if (type(k) ~= 'number') then
if ( k ~= 'config-file') then
k = (k):gsub ("%W", "_")
module[k](v)
end
else
if k >= 2 and v ~= "modules/launch.lua" then
module.add_script(v)
end
end
end
end
return script_files
end
function PrintUsage()
utils.PrintUsage()
end
function declare_opt(...)
utils.declare_opt(...)
end
function declare_long_opt(...)
utils.declare_long_opt(...)
end
function declare_short_opt(...)
utils.declare_short_opt(...)
end
function script_execute(script_name)
xmlReporter = xmlReporter.init(tostring(script_name))
dofile(script_name)
end
|
local utils = require("atf.stdlib.argument_parser")
config = require('config')
xmlReporter = require("reporter")
local module = { }
local script_files = {}
RequiredArgument = utils.RequiredArgument
OptionalArgument = utils.OptionalArgument
NoArgument = utils.NoArgument
function table2str(o)
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. table2str(v) .. ','
end
return s .. '} \n'
end
return tostring(o)
end
function print_table(t,... )
if (type(t) == 'table' ) then
print(table2str(t).. table2str(table.pack(...)))
else
print(tostring(t).. table2str(table.pack(...)))
end
end
function is_file_exists(name)
local f = io.open(name,"r")
if f ~=nil then io.close(f) return true else return false end
end
function table.removeKey(t, k)
local i = 0
local keys, values = {},{}
for k,v in pairs(t) do
i = i + 1
keys[i] = k
values[i] = v
end
while i>0 do
if keys[i] == k then
table.remove(keys, i)
table.remove(values, i)
break
end
i = i - 1
end
local a = {}
for i = 1,#keys do
a[keys[i]] = values[i]
end
return a
end
function print_startscript(script_name)
print("==============================")
print(string.format("Start '%s'",script_name))
print("==============================")
end
function print_stopscript(script_name)
print("==============================")
print(string.format("Finish '%s'",script_name or script_files[1]))
print("==============================")
end
function compareValues(a, b, name)
local function iter(a, b, name, msg)
if type(a) == 'table' and type(b) == 'table' then
local res = true
for k, v in pairs(a) do
res = res and iter(v, b[k], name .. "." .. k, msg)
end
return res
else
if (type(a) ~= type(b)) then
if (type(a) == 'string' and type(b) == 'number') then
b = tostring(b)
else
table.insert(msg, string.format("type of data %s: expected %s, actual type: %s", name, type(a), type(b)))
return false
end
end
if a == b then
return true
else
table.insert(msg, string.format("%s: expected: %s, actual value: %s", name, a, b))
return false
end
end
end
local message = { }
local res = iter(a, b, name, message)
return res, table.concat(message, '\n')
end
--------------------------------------------------
-- parsing commad line part
function module.config_file(config_file)
if (is_file_exists(config_file)) then
config_file = config_file:gsub('%.', " ")
config_file = config_file:gsub("/", ".")
config_file = config_file:gsub("[%s]lua$", "")
config = require(tostring(config_file))
else
print("Incorrect config file type")
print("Uses default config")
print("==========================")
end
end
function module.mobile_connection(str)
config.mobileHost = str
end
function module.mobile_connection_port(src)
config.mobilePort= src
end
function module.hmi_connection(str)
config.hmiUrl = str
end
function module.hmi_connection_port(src)
config.hmiPort = src
end
function module.perflog_connection(str)
config.perflogConnection=str
end
function module.perflog_connection_port(str)
config.perflogConnectionPort=str
end
function module.report_path(str)
config.reportPath=str
end
function module.report_mark(str)
config.reportMark=str
end
function module.add_script(src)
table.insert(script_files,src)
end
function module.storeFullSDLLogs(str)
config.storeFullSDLLogs=str
end
function module.heartbeat(str)
config.heartbeatTimeout=str
end
function module.sdl_core(str)
if (not is_file_exists(str.."smartDeviceLinkCore")) and
(not is_file_exists(str.."/smartDeviceLinkCore")) then
error("SDL is not accessible at the specified path: "..str)
os.exit(1)
end
config.pathToSDL = str
end
function parse_cmdl()
arguments = utils.getopt(argv, opts)
if (arguments) then
if (arguments['config-file']) then module.config_file(arguments['config-file']) end
for k,v in pairs(arguments) do
if (type(k) ~= 'number') then
if ( k ~= 'config-file') then
k = (k):gsub ("%W", "_")
module[k](v)
end
else
if k >= 2 and v ~= "modules/launch.lua" then
module.add_script(v)
end
end
end
end
return script_files
end
function PrintUsage()
utils.PrintUsage()
end
function declare_opt(...)
utils.declare_opt(...)
end
function declare_long_opt(...)
utils.declare_long_opt(...)
end
function declare_short_opt(...)
utils.declare_short_opt(...)
end
function script_execute(script_name)
xmlReporter = xmlReporter.init(tostring(script_name))
dofile(script_name)
end
|
Fix path to sdl Now after starting with flag it will find and execute SDL bin
|
Fix path to sdl
Now after starting with flag it will find and execute SDL bin
Relates to APPLINK-23697
|
Lua
|
bsd-3-clause
|
aderiabin/sdl_atf,aderiabin/sdl_atf,aderiabin/sdl_atf
|
af5e309e47292da83473ee8d2da231d01921a1c4
|
spec/helper.lua
|
spec/helper.lua
|
local helper = {}
local dir_sep = package.config:sub(1, 1)
-- Return path to root directory when run from `path`.
local function antipath(path)
local _, level = path:gsub(dir_sep, "")
return (".."..dir_sep):rep(level)
end
function helper.luacov_config(prefix)
return {
statsfile = prefix.."luacov.stats.out",
modules = {
luacheck = "src/luacheck/init.lua",
["luacheck.*"] = "src"
},
exclude = {
"bin/luacheck$",
"luacheck/argparse$"
}
}
end
local luacov = package.loaded.luacov or package.loaded["luacov.runner"]
-- Returns command that runs `luacheck` executable from `loc_path`.
function helper.luacheck_command(loc_path)
loc_path = loc_path or "."
local prefix = antipath(loc_path)
local cmd = ("cd %s && lua"):format(loc_path)
-- Extend package.path to allow loading this helper and luacheck modules.
cmd = cmd..(" -e 'package.path=[[%s?.lua;%ssrc%s?.lua;%ssrc%s?%sinit.lua;]]..package.path'"):format(
prefix, prefix, dir_sep, prefix, dir_sep, dir_sep)
if luacov then
-- Launch luacov.
cmd = cmd..(" -e 'require[[luacov.runner]](require[[spec.helper]].luacov_config([[%s]]))'"):format(prefix)
end
return ("%s %sbin%sluacheck.lua"):format(cmd, prefix, dir_sep)
end
function helper.before_command()
if luacov then
luacov.pause()
end
end
function helper.after_command()
if luacov then
luacov.resume()
end
end
return helper
|
local helper = {}
local dir_sep = package.config:sub(1, 1)
-- Return path to root directory when run from `path`.
local function antipath(path)
local _, level = path:gsub(dir_sep, "")
return (".."..dir_sep):rep(level)
end
function helper.luacov_config(prefix)
return {
statsfile = prefix.."luacov.stats.out",
modules = {
luacheck = "src/luacheck/init.lua",
["luacheck.*"] = "src"
},
exclude = {
"bin/luacheck$",
"luacheck/argparse$"
}
}
end
local luacov = package.loaded["luacov.runner"]
-- Returns command that runs `luacheck` executable from `loc_path`.
function helper.luacheck_command(loc_path)
loc_path = loc_path or "."
local prefix = antipath(loc_path)
local cmd = ("cd %s && lua"):format(loc_path)
-- Extend package.path to allow loading this helper and luacheck modules.
cmd = cmd..(' -e "package.path=[[%s?.lua;%ssrc%s?.lua;%ssrc%s?%sinit.lua;]]..package.path"'):format(
prefix, prefix, dir_sep, prefix, dir_sep, dir_sep)
if luacov then
-- Launch luacov.
cmd = cmd..(' -e "require[[luacov.runner]](require[[spec.helper]].luacov_config([[%s]]))"'):format(prefix)
end
return ("%s %sbin%sluacheck.lua"):format(cmd, prefix, dir_sep)
end
function helper.before_command()
if luacov then
luacov.pause()
end
end
function helper.after_command()
if luacov then
luacov.resume()
end
end
return helper
|
Fix Windows compat in spec/helper
|
Fix Windows compat in spec/helper
Have to use double quotes.
|
Lua
|
mit
|
mpeterv/luacheck,xpol/luacheck,mpeterv/luacheck,xpol/luacheck,mpeterv/luacheck,xpol/luacheck,linuxmaniac/luacheck,linuxmaniac/luacheck
|
d3e1d17893243ae3b3f0c9e65ce6d79da96eaf71
|
spec/helper.lua
|
spec/helper.lua
|
local helper = {}
local function get_lua()
local index = -1
local res = "lua"
while arg[index] do
res = arg[index]
index = index - 1
end
return res
end
local lua = get_lua()
local dir_sep = package.config:sub(1, 1)
-- Return path to root directory when run from `path`.
local function antipath(path)
local _, level = path:gsub("[/\\]", "")
return (".."..dir_sep):rep(level)
end
function helper.luacov_config(prefix)
return {
statsfile = prefix.."luacov.stats.out",
modules = {
luacheck = "src/luacheck/init.lua",
["luacheck.*"] = "src"
},
exclude = {
"bin/luacheck$",
"luacheck/argparse$"
}
}
end
local luacov = package.loaded["luacov.runner"]
-- Returns command that runs `luacheck` executable from `loc_path`.
function helper.luacheck_command(loc_path)
loc_path = loc_path or "."
local prefix = antipath(loc_path)
local cmd = ("cd %s && %s"):format(loc_path, lua)
-- Extend package.path to allow loading this helper and luacheck modules.
cmd = cmd..(' -e "package.path=[[%s?.lua;%ssrc%s?.lua;%ssrc%s?%sinit.lua;]]..package.path"'):format(
prefix, prefix, dir_sep, prefix, dir_sep, dir_sep)
if luacov then
-- Launch luacov.
cmd = cmd..(' -e "require[[luacov.runner]](require[[spec.helper]].luacov_config([[%s]]))"'):format(prefix)
end
return ("%s %sbin%sluacheck.lua"):format(cmd, prefix, dir_sep)
end
return helper
|
local helper = {}
local function get_lua()
local index = -1
local res = "lua"
while arg[index] do
res = arg[index]
index = index - 1
end
return res
end
local dir_sep = package.config:sub(1, 1)
-- Return path to root directory when run from `path`.
local function antipath(path)
local _, level = path:gsub("[/\\]", "")
return (".."..dir_sep):rep(level)
end
function helper.luacov_config(prefix)
return {
statsfile = prefix.."luacov.stats.out",
modules = {
luacheck = "src/luacheck/init.lua",
["luacheck.*"] = "src"
},
exclude = {
"bin/luacheck$",
"luacheck/argparse$"
}
}
end
local luacov = package.loaded["luacov.runner"]
local lua
-- Returns command that runs `luacheck` executable from `loc_path`.
function helper.luacheck_command(loc_path)
lua = lua or get_lua()
loc_path = loc_path or "."
local prefix = antipath(loc_path)
local cmd = ("cd %s && %s"):format(loc_path, lua)
-- Extend package.path to allow loading this helper and luacheck modules.
cmd = cmd..(' -e "package.path=[[%s?.lua;%ssrc%s?.lua;%ssrc%s?%sinit.lua;]]..package.path"'):format(
prefix, prefix, dir_sep, prefix, dir_sep, dir_sep)
if luacov then
-- Launch luacov.
cmd = cmd..(' -e "require[[luacov.runner]](require[[spec.helper]].luacov_config([[%s]]))"'):format(prefix)
end
return ("%s %sbin%sluacheck.lua"):format(cmd, prefix, dir_sep)
end
return helper
|
Fix busted failing when collecting coverage
|
Fix busted failing when collecting coverage
|
Lua
|
mit
|
mpeterv/luacheck,mpeterv/luacheck,xpol/luacheck,xpol/luacheck,mpeterv/luacheck,xpol/luacheck
|
c9d88a1e09b41d21d626aaa1a744856713e46946
|
lua/entities/gmod_wire_turret.lua
|
lua/entities/gmod_wire_turret.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Turret"
ENT.WireDebugName = "Turret"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:DrawShadow( false )
self:SetCollisionGroup( COLLISION_GROUP_WEAPON )
local phys = self:GetPhysicsObject()
if (phys:IsValid()) then
phys:Wake()
end
self.Firing = false
self.NextShot = 0
self.Inputs = Wire_CreateInputs(self, { "Fire" })
end
function ENT:FireShot()
if ( self.NextShot > CurTime() ) then return end
self.NextShot = CurTime() + self.delay
-- Make a sound if you want to.
if self.sound then
self:EmitSound(self.sound)
end
-- Get the muzzle attachment (this is pretty much always 1)
local Attachment = self:GetAttachment( 1 )
-- Get the shot angles and stuff.
local shootOrigin = Attachment.Pos
local shootAngles = self:GetAngles()
-- Shoot a bullet
local bullet = {}
bullet.Num = self.numbullets
bullet.Src = shootOrigin
bullet.Dir = shootAngles:Forward()
bullet.Spread = self.spread
bullet.Tracer = self.tracernum
bullet.TracerName = self.tracer
bullet.Force = self.force
bullet.Damage = self.damage
bullet.Attacker = self:GetPlayer()
self:FireBullets( bullet )
-- Make a muzzle flash
local effectdata = EffectData()
effectdata:SetOrigin( shootOrigin )
effectdata:SetAngles( shootAngles )
effectdata:SetScale( 1 )
util.Effect( "MuzzleEffect", effectdata )
end
function ENT:OnTakeDamage( dmginfo )
self:TakePhysicsDamage( dmginfo )
end
function ENT:Think()
self.BaseClass.Think(self)
if( self.Firing ) then
self:FireShot()
end
self:NextThink(CurTime())
return true
end
function ENT:TriggerInput(iname, value)
if (iname == "Fire") then
self.Firing = value > 0
end
end
local ValidTracers = {
["Tracer"]=true,
["AR2Tracer"]=true,
["AirboatGunHeavyTracer"]=true,
["LaserTracer"]=true,
[""]=true,
}
function ENT:Setup(delay, damage, force, sound, numbullets, spread, tracer, tracernum)
self.delay = delay
self.damage = damage
self.force = force
-- Preventing client crashes
if string.find(sound, '["?]') then
self.sound = ""
else
self.sound = sound
end
self.numbullets = numbullets
self.spread = Vector(spread, spread, 0)
self.tracer = ValidTracers[string.Trim(tracer)] and string.Trim(tracer) or ""
self.tracernum = tracernum or 1
end
duplicator.RegisterEntityClass( "gmod_wire_turret", WireLib.MakeWireEnt, "Data", "delay", "damage", "force", "sound", "numbullets", "spread", "tracer", "tracernum" )
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Turret"
ENT.WireDebugName = "Turret"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:DrawShadow( false )
self:SetCollisionGroup( COLLISION_GROUP_WEAPON )
local phys = self:GetPhysicsObject()
if (phys:IsValid()) then
phys:Wake()
end
self.Firing = false
self.NextShot = 0
self.Inputs = Wire_CreateInputs(self, { "Fire" })
end
function ENT:FireShot()
if ( self.NextShot > CurTime() ) then return end
self.NextShot = CurTime() + self.delay
-- Make a sound if you want to.
if self.sound then
self:EmitSound(self.sound)
end
-- Get the muzzle attachment (this is pretty much always 1)
local Attachment = self:GetAttachment( 1 )
-- Get the shot angles and stuff.
local shootOrigin = Attachment.Pos
local shootAngles = self:GetAngles()
-- Shoot a bullet
local bullet = {}
bullet.Num = self.numbullets
bullet.Src = shootOrigin
bullet.Dir = shootAngles:Forward()
bullet.Spread = self.spreadvector
bullet.Tracer = self.tracernum
bullet.TracerName = self.tracer
bullet.Force = self.force
bullet.Damage = self.damage
bullet.Attacker = self:GetPlayer()
self:FireBullets( bullet )
-- Make a muzzle flash
local effectdata = EffectData()
effectdata:SetOrigin( shootOrigin )
effectdata:SetAngles( shootAngles )
effectdata:SetScale( 1 )
util.Effect( "MuzzleEffect", effectdata )
end
function ENT:OnTakeDamage( dmginfo )
self:TakePhysicsDamage( dmginfo )
end
function ENT:Think()
self.BaseClass.Think(self)
if( self.Firing ) then
self:FireShot()
end
self:NextThink(CurTime())
return true
end
function ENT:TriggerInput(iname, value)
if (iname == "Fire") then
self.Firing = value > 0
end
end
local ValidTracers = {
["Tracer"]=true,
["AR2Tracer"]=true,
["AirboatGunHeavyTracer"]=true,
["LaserTracer"]=true,
[""]=true,
}
function ENT:Setup(delay, damage, force, sound, numbullets, spread, tracer, tracernum)
if not game.SinglePlayer() then
self.delay = math.max(delay,0.05) -- clamp delay if it's not single player
end
self.damage = damage
self.force = force
-- Preventing client crashes
if string.find(sound, '["?]') then
self.sound = ""
else
self.sound = sound
end
if not game.SinglePlayer() then
self.numbullets = math.Clamp( numbullets, 1, 10 ) -- clamp num bullets if it's not single player
end
self.spread = spread -- for duplication
self.spreadvector = Vector(spread,spread,0)
self.tracer = ValidTracers[string.Trim(tracer)] and string.Trim(tracer) or ""
self.tracernum = tracernum or 1
end
duplicator.RegisterEntityClass( "gmod_wire_turret", WireLib.MakeWireEnt, "Data", "delay", "damage", "force", "sound", "numbullets", "spread", "tracer", "tracernum" )
|
Fixed wire turret's spread not duplicating
|
Fixed wire turret's spread not duplicating
Fixes #657
|
Lua
|
apache-2.0
|
garrysmodlua/wire,rafradek/wire,sammyt291/wire,NezzKryptic/Wire,thegrb93/wire,mitterdoo/wire,notcake/wire,wiremod/wire,mms92/wire,bigdogmat/wire,Python1320/wire,dvdvideo1234/wire,plinkopenguin/wiremod,immibis/wiremod,CaptainPRICE/wire,Grocel/wire
|
2062188a2a0455ee0b35d827c97f2294a06d06b8
|
src/cosy/loader.lua
|
src/cosy/loader.lua
|
local version = tonumber (_VERSION:match "Lua%s*(%d%.%d)")
if version < 5.1
or (version == 5.1 and type (_G.jit) ~= "table") then
error "Cosy requires Luajit >= 2 or Lua >= 5.2 to run."
end
local Loader = {}
local loader = {}
if _G.js then
_G.loadhttp = function (url)
local co = coroutine.running ()
local request = _G.js.new (_G.js.global.XMLHttpRequest)
request:open ("GET", url, true)
request.onreadystatechange = function (event)
if request.readyState == 4 then
if request.status == 200 then
coroutine.resume (co, request.responseText)
else
coroutine.resume (co, nil, event.target.status)
end
end
end
request:send (nil)
local result, err = coroutine.yield ()
if result then
return result
else
error (err)
end
end
_G.require = function (mod_name)
local loaded = package.loaded [mod_name]
if loaded then
return loaded
end
local preloaded = package.preload [mod_name]
if preloaded then
local result = preloaded (mod_name)
package.loaded [mod_name] = result
return result
end
local url = "/lua/" .. mod_name
local result, err
result, err = _G.loadhttp (url)
if not result then
error (err)
end
result, err = load (result, url)
if not result then
error (err)
end
result = result (mod_name)
package.loaded [mod_name] = result
return result
end
loader.hotswap = require
else
local ev = require "ev"
loader.scheduler = require "copas.ev"
loader.scheduler.make_default ()
loader.hotswap = require "hotswap.ev" .new {
loop = loader.scheduler._loop
}
loader.hotswap "cosy.string"
end
Loader.__index = function (loader, key)
return loader.hotswap ("cosy." .. tostring (key))
end
Loader.__call = function (loader, key)
return loader.hotswap (key)
end
package.preload.bit32 = function ()
loader.logger.warning {
_ = "fixme",
message = "global bit32 is created for lua-websockets",
}
_G.bit32 = require "bit"
_G.bit32.lrotate = _G.bit32.rol
_G.bit32.rrotate = _G.bit32.ror
return _G.bit32
end
return setmetatable (loader, Loader)
|
local version = tonumber (_VERSION:match "Lua%s*(%d%.%d)")
if version < 5.1
or (version == 5.1 and type (_G.jit) ~= "table") then
error "Cosy requires Luajit >= 2 or Lua >= 5.2 to run."
end
local Loader = {}
Loader.__index = function (loader, key)
return loader.hotswap ("cosy." .. tostring (key))
end
Loader.__call = function (loader, key)
return loader.hotswap (key)
end
local loader = setmetatable ({}, Loader)
if _G.js then
_G.loadhttp = function (url)
local co = coroutine.running ()
local request = _G.js.new (_G.js.global.XMLHttpRequest)
request:open ("GET", url, true)
request.onreadystatechange = function (event)
if request.readyState == 4 then
if request.status == 200 then
coroutine.resume (co, request.responseText)
else
coroutine.resume (co, nil, event.target.status)
end
end
end
request:send (nil)
local result, err = coroutine.yield ()
if result then
return result
else
error (err)
end
end
_G.require = function (mod_name)
local loaded = package.loaded [mod_name]
if loaded then
return loaded
end
local preloaded = package.preload [mod_name]
if preloaded then
local result = preloaded (mod_name)
package.loaded [mod_name] = result
return result
end
local url = "/lua/" .. mod_name
local result, err
result, err = _G.loadhttp (url)
if not result then
error (err)
end
result, err = load (result, url)
if not result then
error (err)
end
result = result (mod_name)
package.loaded [mod_name] = result
return result
end
loader.hotswap = require
else
loader.scheduler = require "copas.ev"
loader.scheduler.make_default ()
loader.hotswap = require "hotswap.ev" .new {
loop = loader.scheduler._loop
}
loader.hotswap "cosy.string"
end
package.preload.bit32 = function ()
loader.logger.warning {
_ = "fixme",
message = "global bit32 is created for lua-websockets",
}
_G.bit32 = require "bit"
_G.bit32.lrotate = _G.bit32.rol
_G.bit32.rrotate = _G.bit32.ror
return _G.bit32
end
return loader
|
Fix warnings.
|
Fix warnings.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
6d45bc1e01025dd04a150fbdfb38efd227258932
|
remote/ping.lua
|
remote/ping.lua
|
local ffi = require 'ffi'
local uv = require 'uv'
local getaddrinfo = require('./utils').getaddrinfo
local AF_INET = 2
local AF_INET6 = jit.os == "OSX" and 30 or
jit.os == "Linux" and 10 or error("Unknown OS")
local SOCK_RAW = 3
local IPPROTO_ICMP = 1
local IPPROTO_ICMP6 = 58
ffi.cdef[[
int socket(int socket_family, int socket_type, int protocol);
]]
local band = bit.band
local bor = bit.bor
local bnot = bit.bnot
local lshift = bit.lshift
local rshift = bit.rshift
local byte = string.byte
local char = string.char
local sub = string.sub
local e4payload = "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" ..
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" ..
"\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f" ..
"\x30\x31\x32\x33\x34\x35\x36\x37"
local e6payload = "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" ..
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" ..
"\x20\x21\x22\x23"
-- Calculate 16-bit one's complement of the one's complement sum
local function checksum(buffer)
local sum = 0
for i = 1, #buffer, 2 do
local word = bor(lshift(byte(buffer, i), 8), byte(buffer, i + 1))
sum = sum + word
if sum > 0xffff then
sum = sum - 0xffff -- remove carry bit and add 1
end
end
-- Take complement
sum = band(bnot(sum), 0xffff)
-- Return as 2-byte string in network byte order
return char(rshift(sum, 8), band(sum, 0xff))
end
local waiting = {}
local function processMessage(err, data, address)
assert(not err, err)
if not data then
-- empty event, ignore.
return
end
local first = byte(data, 1)
if first == 128 then
-- ICMP6 request, ignore these.
return
elseif first == 129 then
-- ICMP6 response, leave along, it's good.
elseif rshift(first, 4) == 4 then
-- IPv4 IP header detected, strip it by reading length
data = sub(data, band(byte(data, 1), 0xf) * 4 + 1)
end
local rseq = bor(lshift(byte(data, 7), 8), byte(data, 8))
local thread = waiting[rseq]
if thread then
waiting[rseq] = nil
return assert(coroutine.resume(thread, sub(data, 9)))
end
end
local id = math.random(0x10000) % 0x10000
local next_seq = 0
--[[------------------------------- Attributes ---------------------------------
target: String
hostname or ip address
timeout: Uint32
timeout in ms
resolver: Optional (IPv4, IPv6) case insensitive
Determines how to resolve the check target.
--------------------------------- Config Params --------------------------------
count: Optional whole number (1..15)
Number of pings to send within a single check
------------------------------------- Metrics ----------------------------------
available: Double
The whole number representing the percent of pings that returned back for a remote.ping check.
average: Double
The average response time in milliseconds for all ping packets sent out and later retrieved.
count: Int32
The number of pings (ICMP packets) sent.
maximum: Double
The maximum roundtrip time in milliseconds of an ICMP packet.
minimum: Double
The minimum roundtrip time in milliseconds of an ICMP packet.
----------------------------------------------------------------------------]]--
return function (attributes, config, register, set)
local start = uv.now()
local delay = config.delay or 2000
-- Resolve hostname and record time spent
local family
local resolver = attributes.resolver and attributes.resolver:lower()
if resolver == "ipv4" then
family = "inet"
elseif resolver == "ipv6" then
family = "inet6"
end
local ip = assert(getaddrinfo(attributes.target, 0, family))
set("tt_resolve", uv.now() - start)
set("ip", ip)
local results = {}
local payload
local top, sock, sockfd
if ip:match("^%d+%.%d+%.%d+%.%d+$") then
top = "\x08\x00"
payload = e4payload
sockfd = ffi.C.socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)
else
top = "\x80\x00"
payload = e6payload
sockfd = ffi.C.socket(AF_INET6, SOCK_RAW, IPPROTO_ICMP6)
end
assert(sockfd >= 0, "Failed to create socket")
sock = uv.new_udp()
assert(sock:open(sockfd))
sock:recv_start(processMessage)
local timer = uv.new_timer()
local count = config.count or 5
for i = 1, count do
local seq = next_seq
next_seq = seq + 1
local begin = uv.now()
local bottom = char(
band(rshift(id, 8), 0xff), band(id, 0xff), -- id
band(rshift(seq, 8), 0xff), band(seq, 0xff), -- seq
-- Timestamp
band(rshift(begin, 24), 0xff), band(rshift(begin, 16), 0xff),
band(rshift(begin, 8), 0xff), band(begin, 0xff)
) .. payload
print("Pinging", ip)
sock:send(top .. checksum(top .. "\x00\x00" .. bottom) .. bottom, ip, 0)
local thread = coroutine.running()
waiting[seq] = thread
local message, err
local delta
timer:start(delay, 0, function ()
results[#results + 1] = delta
assert(coroutine.resume(thread))
end)
message, err = coroutine.yield()
if message then
local rbegin = bor(
lshift(byte(message, 1), 24), lshift(byte(message, 2), 16),
lshift(byte(message, 3), 8), byte(message, 4))
assert(rbegin == begin, "echo reply timestamp mistmach")
assert(message:sub(5) == payload, "echo reply body mismatch")
delta = uv.now() - begin
print(delta .. "ms")
coroutine.yield()
end
end
timer:close()
sock:close()
local pass = 0
local high
local sum = 0
local low
for i = 1, count do
local ms = results[i]
if ms then
pass = pass + 1
if not high or ms > high then high = ms end
if not low or ms < low then low = ms end
sum = sum + ms
end
end
set("duration", uv.now() - start)
set("available", pass / count)
set("average", sum / pass)
set("count", count)
set("maximum", high)
set("minimum", low)
end
|
local ffi = require 'ffi'
local uv = require 'uv'
local getaddrinfo = require('./utils').getaddrinfo
local AF_INET = 2
local AF_INET6 = jit.os == "OSX" and 30 or
jit.os == "Linux" and 10 or error("Unknown OS")
local SOCK_RAW = 3
local IPPROTO_ICMP = 1
local IPPROTO_ICMP6 = 58
ffi.cdef[[
int socket(int socket_family, int socket_type, int protocol);
]]
local band = bit.band
local bor = bit.bor
local bnot = bit.bnot
local lshift = bit.lshift
local rshift = bit.rshift
local byte = string.byte
local char = string.char
local sub = string.sub
local e4payload = "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" ..
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" ..
"\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f" ..
"\x30\x31\x32\x33\x34\x35\x36\x37"
local e6payload = "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" ..
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" ..
"\x20\x21\x22\x23"
-- Calculate 16-bit one's complement of the one's complement sum
local function checksum(buffer)
local sum = 0
for i = 1, #buffer, 2 do
local word = bor(lshift(byte(buffer, i), 8), byte(buffer, i + 1))
sum = sum + word
if sum > 0xffff then
sum = sum - 0xffff -- remove carry bit and add 1
end
end
-- Take complement
sum = band(bnot(sum), 0xffff)
-- Return as 2-byte string in network byte order
return char(rshift(sum, 8), band(sum, 0xff))
end
local waiting = {}
local function processMessage(err, data, address)
assert(not err, err)
if not data then
-- empty event, ignore.
return
end
local first = byte(data, 1)
if first == 128 then
-- ICMP6 request, ignore these.
return
elseif rshift(first, 4) == 4 then
-- IPv4 IP header detected, strip it by reading length
data = sub(data, band(byte(data, 1), 0xf) * 4 + 1)
end
local rseq = bor(lshift(byte(data, 7), 8), byte(data, 8))
local thread = waiting[rseq]
if thread then
waiting[rseq] = nil
return assert(coroutine.resume(thread, sub(data, 9)))
end
end
local id = math.random(0x10000) % 0x10000
local next_seq = 0
--[[------------------------------- Attributes ---------------------------------
target: String
hostname or ip address
timeout: Uint32
timeout in ms
resolver: Optional (IPv4, IPv6) case insensitive
Determines how to resolve the check target.
--------------------------------- Config Params --------------------------------
count: Optional whole number (1..15)
Number of pings to send within a single check
------------------------------------- Metrics ----------------------------------
available: Double
The whole number representing the percent of pings that returned back for a remote.ping check.
average: Double
The average response time in milliseconds for all ping packets sent out and later retrieved.
count: Int32
The number of pings (ICMP packets) sent.
maximum: Double
The maximum roundtrip time in milliseconds of an ICMP packet.
minimum: Double
The minimum roundtrip time in milliseconds of an ICMP packet.
----------------------------------------------------------------------------]]--
return function (attributes, config, register, set)
local start = uv.now()
local delay = config.delay or 2000
-- Resolve hostname and record time spent
local family
local resolver = attributes.resolver and attributes.resolver:lower()
if resolver == "ipv4" then
family = "inet"
elseif resolver == "ipv6" then
family = "inet6"
end
local ip = assert(getaddrinfo(attributes.target, 0, family))
set("tt_resolve", uv.now() - start)
set("ip", ip)
local results = {}
local payload
local top, sock, sockfd
if ip:match("^%d+%.%d+%.%d+%.%d+$") then
top = "\x08\x00"
payload = e4payload
sockfd = ffi.C.socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)
else
top = "\x80\x00"
payload = e6payload
sockfd = ffi.C.socket(AF_INET6, SOCK_RAW, IPPROTO_ICMP6)
end
assert(sockfd >= 0, "Failed to create socket")
sock = uv.new_udp()
assert(sock:open(sockfd))
sock:recv_start(processMessage)
local timer = uv.new_timer()
local count = config.count or 5
for i = 1, count do
local seq = next_seq
next_seq = seq + 1
local begin = uv.now()
local bottom = char(
band(rshift(id, 8), 0xff), band(id, 0xff), -- id
band(rshift(seq, 8), 0xff), band(seq, 0xff), -- seq
-- Timestamp
band(rshift(begin, 24), 0xff), band(rshift(begin, 16), 0xff),
band(rshift(begin, 8), 0xff), band(begin, 0xff)
) .. payload
print("Pinging", ip)
sock:send(top .. checksum(top .. "\x00\x00" .. bottom) .. bottom, ip, 0)
local thread = coroutine.running()
waiting[seq] = thread
local message
local delta
timer:start(delay, 0, function ()
results[#results + 1] = delta
assert(coroutine.resume(thread))
end)
message = coroutine.yield()
if message then
local rbegin = bor(
lshift(byte(message, 1), 24), lshift(byte(message, 2), 16),
lshift(byte(message, 3), 8), byte(message, 4))
assert(rbegin == begin, "echo reply timestamp mistmach")
assert(message:sub(5) == payload, "echo reply body mismatch")
delta = uv.now() - begin
print(delta .. "ms")
coroutine.yield()
end
end
timer:close()
sock:close()
local pass = 0
local high
local sum = 0
local low
for i = 1, count do
local ms = results[i]
if ms then
pass = pass + 1
if not high or ms > high then high = ms end
if not low or ms < low then low = ms end
sum = sum + ms
end
end
set("duration", uv.now() - start)
set("available", pass / count)
set("average", sum / pass)
set("count", count)
set("maximum", high)
set("minimum", low)
end
|
Lint fixes
|
Lint fixes
|
Lua
|
apache-2.0
|
virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
|
703f7a0b23ddcd7d9cd122fa3a50ce109788d2a3
|
GameServer/Content/Data/LeagueSandbox-Default/Champions/Graves/E.lua
|
GameServer/Content/Data/LeagueSandbox-Default/Champions/Graves/E.lua
|
Vector2 = require 'Vector2' -- include 2d vector lib
function onFinishCasting()
addParticleTarget("Graves_Move_OnBuffActivate.troy", getOwner())
local current = Vector2:new(getOwnerX(), getOwnerY())
local to = (Vector2:new(getSpellToX(), getSpellToY()) - current):normalize()
local range = to * 425
local trueCoords = current + range
dashTo(getOwner(), trueCoords.x, trueCoords.y, 1200, 0, "Spell3")
end
function applyEffects()
end
|
Vector2 = require 'Vector2' -- include 2d vector lib
function onFinishCasting()
local current = Vector2:new(getOwnerX(), getOwnerY())
local to = (Vector2:new(getSpellToX(), getSpellToY()) - current):normalize()
local range = to * 425
local trueCoords = current + range
dashTo(getOwner(), trueCoords.x, trueCoords.y, 1200, 0, "Spell3")
addParticleTarget(getOwner(), "Graves_Move_OnBuffActivate.troy", getOwner())
end
function applyEffects()
end
|
A little fix
|
A little fix
|
Lua
|
agpl-3.0
|
LeagueSandbox/GameServer
|
7eb57d58026b171e8b08799126a631c67aba7649
|
modules/outfit/outfit.lua
|
modules/outfit/outfit.lua
|
Outfit = {}
-- private variables
local window = nil
local m_creature = nil
local m_outfit = nil
local m_outfits = nil
local m_currentOutfit = 1
local m_currentColor = nil
local m_currentClothe = nil
-- private functions
local function onAddonCheckChange(addon, value)
if addon:isChecked() then
m_outfit.addons = m_outfit.addons + value
else
m_outfit.addons = m_outfit.addons - value
end
m_creature:setOutfit(m_outfit)
end
local function onColorCheckChange(color)
if color == m_currentColor then
color.onCheckChange = nil
color:setChecked(true)
color.onCheckChange = function() onColorCheckChange(color) end
else
m_currentColor.onCheckChange = nil
m_currentColor:setChecked(false)
local color2 = m_currentColor
m_currentColor.onCheckChange = function() onColorCheckChange(color2) end
m_currentColor = color
if m_currentClothe:getId() == 'head' then
m_outfit.head = m_currentColor.colorId
elseif m_currentClothe:getId() == 'primary' then
m_outfit.body = m_currentColor.colorId
elseif m_currentClothe:getId() == 'secondary' then
m_outfit.legs = m_currentColor.colorId
elseif m_currentClothe:getId() == 'detail' then
m_outfit.feet = m_currentColor.colorId
end
m_creature:setOutfit(m_outfit)
end
end
local function onClotheCheckChange(clothe)
if clothe == m_currentClothe then
clothe.onCheckChange = nil
clothe:setChecked(true)
clothe.onCheckChange = function() onClotheCheckChange(clothe) end
else
m_currentClothe.onCheckChange = nil
m_currentClothe:setChecked(false)
local clothe2 = m_currentClothe
m_currentClothe.onCheckChange = function() onClotheCheckChange(clothe2) end
m_currentClothe = clothe
local color = 0
if m_currentClothe:getId() == 'head' then
color = m_outfit.head
elseif m_currentClothe:getId() == 'primary' then
color = m_outfit.body
elseif m_currentClothe:getId() == 'secondary' then
color = m_outfit.legs
elseif m_currentClothe:getId() == 'detail' then
color = m_outfit.feet
end
window:getChildById('color' .. color):setChecked(true)
end
end
local function update()
local nameWidget = window:getChildById('name')
nameWidget:setText(m_outfits[currentOutfit][2])
local availableAddons = m_outfits[currentOutfit][3]
local addon1 = window:getChildById('addon1')
local addon2 = window:getChildById('addon2')
local addon3 = window:getChildById('addon3')
addon1.onCheckChange = function() onAddonCheckChange(addon1, 1) end
addon2.onCheckChange = function() onAddonCheckChange(addon2, 2) end
addon3.onCheckChange = function() onAddonCheckChange(addon3, 4) end
addon1:setChecked(false)
addon2:setChecked(false)
addon3:setChecked(false)
addon1:setEnabled(false)
addon2:setEnabled(false)
addon3:setEnabled(false)
-- Maybe rework this someday
if availableAddons == 1 then
addon1:setEnabled(true)
elseif availableAddons == 2 then
addon2:setEnabled(true)
elseif availableAddons == 3 then
addon1:setEnabled(true)
addon2:setEnabled(true)
elseif availableAddons == 4 then
addon3:setEnabled(true)
elseif availableAddons == 5 then
addon1:setEnabled(true)
addon3:setEnabled(true)
elseif availableAddons == 6 then
addon2:setEnabled(true)
addon3:setEnabled(true)
elseif availableAddons == 7 then
addon1:setEnabled(true)
addon2:setEnabled(true)
addon3:setEnabled(true)
end
m_outfit.type = m_outfits[currentOutfit][1]
m_outfit.addons = 0
m_creature:setOutfit(m_outfit)
end
-- public functions
function Outfit.test()
local button = UIButton.create()
UI.root:addChild(button)
button:setText('Set Outfit')
button:setStyle('Button')
button:moveTo({x = 0, y = 100})
button:setWidth('100')
button:setHeight('30')
button.onClick = function() Game.openOutfitWindow() end
end
function Outfit.create(creature, outfitList)
Outfit.destroy()
window = UI.display('outfit.otui', { parent = UI.root })
window:lock()
m_outfit = creature:getOutfit()
m_currentClothe = window:getChildById('head')
local head = window:getChildById('head')
local primary = window:getChildById('primary')
local secondary = window:getChildById('secondary')
local detail = window:getChildById('detail')
head.onCheckChange = function() onClotheCheckChange(head) end
primary.onCheckChange = function() onClotheCheckChange(primary) end
secondary.onCheckChange = function() onClotheCheckChange(secondary) end
detail.onCheckChange = function() onClotheCheckChange(detail) end
local creatureWidget = window:getChildById('creature')
creatureWidget:setCreature(creature)
for i=0,18 do
for j=0,6 do
local color = UICheckBox.create()
window:addChild(color)
local outfitColor = getOufitColor(j*19 + i)
color:setId('color' .. j*19+i)
color.colorId = j*19 + i
color:setStyle('Color')
color:setBackgroundColor(outfitColor)
color:setMarginTop(j * 3 + j * 14)
color:setMarginLeft(10 + i * 3 + i * 14)
if j*19 + i == m_outfit.head then
m_currentColor = color
color:setChecked(true)
end
color.onCheckChange = function() onColorCheckChange(color) end
end
end
m_creature = creature
m_outfits = outfitList
currentOutfit = 1
for i=1,#outfitList do
if outfitList[i][1] == m_outfit.type then
currentOutfit = i
break
end
end
update()
end
function Outfit.destroy()
if window ~= nil then
window:destroy()
window = nil
end
end
function Outfit.accept()
Game.setOutfit(m_outfit)
Outfit.destroy()
end
function Outfit.nextType()
currentOutfit = currentOutfit + 1
if currentOutfit > #m_outfits then
currentOutfit = 1
end
update()
end
function Outfit.previousType()
currentOutfit = currentOutfit - 1
if currentOutfit <= 0 then
currentOutfit = #m_outfits
end
update()
end
-- hooked events
connect(Game, { onOpenOutfitWindow = Outfit.create,
onLogout = Outfit.destroy })
connect(Game, { onLogin = Outfit.test })
|
Outfit = {}
-- private variables
local window = nil
local m_creature = nil
local m_outfit = nil
local m_outfits = nil
local m_currentOutfit = 1
local m_currentColor = nil
local m_currentClothe = nil
-- private functions
local function onAddonCheckChange(addon, value)
if addon:isChecked() then
m_outfit.addons = m_outfit.addons + value
else
m_outfit.addons = m_outfit.addons - value
end
m_creature:setOutfit(m_outfit)
end
local function onColorCheckChange(color)
if color == m_currentColor then
color.onCheckChange = nil
color:setChecked(true)
color.onCheckChange = onColorCheckChange
else
m_currentColor.onCheckChange = nil
m_currentColor:setChecked(false)
m_currentColor.onCheckChange = onColorCheckChange
m_currentColor = color
if m_currentClothe:getId() == 'head' then
m_outfit.head = m_currentColor.colorId
elseif m_currentClothe:getId() == 'primary' then
m_outfit.body = m_currentColor.colorId
elseif m_currentClothe:getId() == 'secondary' then
m_outfit.legs = m_currentColor.colorId
elseif m_currentClothe:getId() == 'detail' then
m_outfit.feet = m_currentColor.colorId
end
m_creature:setOutfit(m_outfit)
end
end
local function onClotheCheckChange(clothe)
if clothe == m_currentClothe then
clothe.onCheckChange = nil
clothe:setChecked(true)
clothe.onCheckChange = onClotheCheckChange
else
m_currentClothe.onCheckChange = nil
m_currentClothe:setChecked(false)
m_currentClothe.onCheckChange = onClotheCheckChange
m_currentClothe = clothe
local color = 0
if m_currentClothe:getId() == 'head' then
color = m_outfit.head
elseif m_currentClothe:getId() == 'primary' then
color = m_outfit.body
elseif m_currentClothe:getId() == 'secondary' then
color = m_outfit.legs
elseif m_currentClothe:getId() == 'detail' then
color = m_outfit.feet
end
window:getChildById('color' .. color):setChecked(true)
end
end
local function update()
local nameWidget = window:getChildById('name')
nameWidget:setText(m_outfits[m_currentOutfit][2])
local availableAddons = m_outfits[m_currentOutfit][3]
local addon1 = window:getChildById('addon1')
local addon2 = window:getChildById('addon2')
local addon3 = window:getChildById('addon3')
addon1:setChecked(false)
addon2:setChecked(false)
addon3:setChecked(false)
addon1.onCheckChange = function(self) onAddonCheckChange(self, 1) end
addon2.onCheckChange = function(self) onAddonCheckChange(self, 2) end
addon3.onCheckChange = function(self) onAddonCheckChange(self, 4) end
addon1:setEnabled(false)
addon2:setEnabled(false)
addon3:setEnabled(false)
-- Maybe rework this someday
if availableAddons == 1 then
addon1:setEnabled(true)
elseif availableAddons == 2 then
addon2:setEnabled(true)
elseif availableAddons == 3 then
addon1:setEnabled(true)
addon2:setEnabled(true)
elseif availableAddons == 4 then
addon3:setEnabled(true)
elseif availableAddons == 5 then
addon1:setEnabled(true)
addon3:setEnabled(true)
elseif availableAddons == 6 then
addon2:setEnabled(true)
addon3:setEnabled(true)
elseif availableAddons == 7 then
addon1:setEnabled(true)
addon2:setEnabled(true)
addon3:setEnabled(true)
end
m_outfit.type = m_outfits[m_currentOutfit][1]
m_outfit.addons = 0
m_creature:setOutfit(m_outfit)
end
-- public functions
function Outfit.test()
local button = UIButton.create()
UI.root:addChild(button)
button:setText('Set Outfit')
button:setStyle('Button')
button:moveTo({x = 0, y = 100})
button:setWidth('100')
button:setHeight('30')
button.onClick = function() Game.openOutfitWindow() end
end
function Outfit.create(creature, outfitList)
Outfit.destroy()
window = UI.display('outfit.otui', { parent = UI.root })
window:lock()
m_outfit = creature:getOutfit()
m_currentClothe = window:getChildById('head')
window:getChildById('head').onCheckChange = onClotheCheckChange
window:getChildById('primary').onCheckChange = onClotheCheckChange
window:getChildById('secondary').onCheckChange = onClotheCheckChange
window:getChildById('detail').onCheckChange = onClotheCheckChange
local creatureWidget = window:getChildById('creature')
creatureWidget:setCreature(creature)
for i=0,18 do
for j=0,6 do
local color = UICheckBox.create()
window:addChild(color)
local outfitColor = getOufitColor(j*19 + i)
color:setId('color' .. j*19+i)
color.colorId = j*19 + i
color:setStyle('Color')
color:setBackgroundColor(outfitColor)
color:setMarginTop(j * 3 + j * 14)
color:setMarginLeft(10 + i * 3 + i * 14)
if j*19 + i == m_outfit.head then
m_currentColor = color
color:setChecked(true)
end
color.onCheckChange = onColorCheckChange
end
end
m_creature = creature
m_outfits = outfitList
m_currentOutfit = 1
for i=1,#outfitList do
if outfitList[i][1] == m_outfit.type then
m_currentOutfit = i
break
end
end
update()
end
function Outfit.destroy()
if window ~= nil then
window:destroy()
window = nil
end
end
function Outfit.accept()
Game.setOutfit(m_outfit)
Outfit.destroy()
end
function Outfit.nextType()
m_currentOutfit = m_currentOutfit + 1
if m_currentOutfit > #m_outfits then
m_currentOutfit = 1
end
update()
end
function Outfit.previousType()
m_currentOutfit = m_currentOutfit - 1
if m_currentOutfit <= 0 then
m_currentOutfit = #m_outfits
end
update()
end
-- hooked events
connect(Game, { onOpenOutfitWindow = Outfit.create,
onLogout = Outfit.destroy })
connect(Game, { onLogin = Outfit.test })
|
outfit fixes
|
outfit fixes
|
Lua
|
mit
|
EvilHero90/otclient,Cavitt/otclient_mapgen,Radseq/otclient,gpedro/otclient,Cavitt/otclient_mapgen,dreamsxin/otclient,gpedro/otclient,Radseq/otclient,gpedro/otclient,kwketh/otclient,dreamsxin/otclient,kwketh/otclient,dreamsxin/otclient,EvilHero90/otclient
|
559c0c6eeaf45115cdbe477b23659fdcac078ead
|
plugins/database.lua
|
plugins/database.lua
|
local function callback_group_database(extra, success, result)
local database = extra.database
local chat_id = result.peer_id
-- save group info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. result.print_name:gsub("_"," "),
long_id = result.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = result.print_name:gsub("_"," "),
long_id = result.id
}
end
-- save users info
for k, v in pairs(result.members) do
if database["users"][tostring(v.peer_id)] then
if not database["users"][tostring(v.peer_id)].groups then
database["users"][tostring(v.peer_id)].groups = { }
end
if not database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] then
database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id)
end
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
database["users"][tostring(v.peer_id)].groups = { }
database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id)
end
end
save_data(_config.database.db, database)
send_large_msg(extra.receiver, langs[get_lang(result.peer_id)].dataLeaked)
end
local function callback_supergroup_database(extra, success, result)
local database = extra.database
local chat_id = string.match(extra.receiver, '%d+')
-- save supergroup info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. extra.print_name:gsub("_"," "),
old_usernames = database["groups"][tostring(chat_id)].old_usernames .. ' ### ' ..(extra.username or 'NOUSER'),
long_id = extra.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = extra.print_name:gsub("_"," "),
old_usernames = extra.username or 'NOUSER',
long_id = extra.id
}
end
-- save users info
for k, v in pairsByKeys(result) do
if database["users"][tostring(v.peer_id)] then
if not database["users"][tostring(v.peer_id)].groups then
database["users"][tostring(v.peer_id)].groups = { }
end
if not database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] then
database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id)
end
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
database["users"][tostring(v.peer_id)].groups = { }
database["users"][tostring(v.peer_id)].groups[tostring(chat_id)] = tonumber(chat_id)
end
end
save_data(_config.database.db, database)
send_large_msg(extra.receiver, langs[get_lang(string.match(extra.receiver, '%d+'))].dataLeaked)
end
local function run(msg, matches)
if is_sudo(msg) then
if matches[1]:lower() == 'createdatabase' then
local f = io.open(_config.database.db, 'w+')
f:write('{"groups":{},"users":{}}')
f:close()
reply_msg(msg.id, langs[msg.lang].dbCreated, ok_cb, false)
return
end
local database = load_data(_config.database.db)
if matches[1]:lower() == 'database' or matches[1]:lower() == 'sasha database' then
local receiver = get_receiver(msg)
if msg.to.type == 'channel' then
channel_get_users(receiver, callback_supergroup_database, { receiver = receiver, database = database, print_name = msg.to.print_name, username = (msg.to.username or nil), id = msg.to.peer_id })
elseif msg.to.type == 'chat' then
chat_info(receiver, callback_group_database, { receiver = receiver, database = database })
else
return
end
end
else
return langs[msg.lang].require_sudo
end
end
return {
description = "DATABASE",
patterns =
{
"^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
"^[#!/]([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
-- database
"^([Ss][Aa][Ss][Hh][Aa] [Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
},
run = run,
min_rank = 5
-- usage
-- SUDO
-- #createdatabase
-- (#database|[sasha] database)
}
|
local function callback_group_database(extra, success, result)
local database = extra.database
local chat_id = result.peer_id
-- save group info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. result.print_name:gsub("_"," "),
long_id = result.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = result.print_name:gsub("_"," "),
lang = get_lang(result.peer_id),
old_print_names = result.print_name:gsub("_"," "),
long_id = result.id
}
end
-- save users info
for k, v in pairs(result.members) do
if database["users"][tostring(v.peer_id)] then
if not database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] then
database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id)
end
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
database["users"][tostring(v.peer_id)]["groups"] = { }
database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id)
end
end
save_data(_config.database.db, database)
send_large_msg(extra.receiver, langs[get_lang(result.peer_id)].dataLeaked)
end
local function callback_supergroup_database(extra, success, result)
local database = extra.database
local chat_id = string.match(extra.receiver, '%d+')
-- save supergroup info
if database["groups"][tostring(chat_id)] then
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = database["groups"][tostring(chat_id)].old_print_names .. ' ### ' .. extra.print_name:gsub("_"," "),
old_usernames = database["groups"][tostring(chat_id)].old_usernames .. ' ### ' ..(extra.username or 'NOUSER'),
long_id = extra.id
}
else
database["groups"][tostring(chat_id)] = {
print_name = extra.print_name:gsub("_"," "),
username = extra.username or 'NOUSER',
lang = get_lang(string.match(extra.receiver,'%d+')),
old_print_names = extra.print_name:gsub("_"," "),
old_usernames = extra.username or 'NOUSER',
long_id = extra.id
}
end
-- save users info
for k, v in pairsByKeys(result) do
if database["users"][tostring(v.peer_id)] then
if not database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] then
database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id)
end
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = database["users"][tostring(v.peer_id)].old_print_names .. ' ### ' .. v.print_name:gsub("_"," "),
old_usernames = database["users"][tostring(v.peer_id)].old_usernames .. ' ### ' ..(v.username or 'NOUSER'),
long_id = v.id
}
else
database["users"][tostring(v.peer_id)] = {
print_name = v.print_name:gsub("_"," "),
username = v.username or 'NOUSER',
old_print_names = v.print_name:gsub("_"," "),
old_usernames = v.username or 'NOUSER',
long_id = v.id
}
database["users"][tostring(v.peer_id)]["groups"] = { }
database["users"][tostring(v.peer_id)]["groups"][tostring(chat_id)] = tonumber(chat_id)
end
end
save_data(_config.database.db, database)
send_large_msg(extra.receiver, langs[get_lang(string.match(extra.receiver, '%d+'))].dataLeaked)
end
local function run(msg, matches)
if is_sudo(msg) then
if matches[1]:lower() == 'createdatabase' then
local f = io.open(_config.database.db, 'w+')
f:write('{"groups":{},"users":{}}')
f:close()
reply_msg(msg.id, langs[msg.lang].dbCreated, ok_cb, false)
return
end
local database = load_data(_config.database.db)
if matches[1]:lower() == 'database' or matches[1]:lower() == 'sasha database' then
local receiver = get_receiver(msg)
if msg.to.type == 'channel' then
channel_get_users(receiver, callback_supergroup_database, { receiver = receiver, database = database, print_name = msg.to.print_name, username = (msg.to.username or nil), id = msg.to.peer_id })
elseif msg.to.type == 'chat' then
chat_info(receiver, callback_group_database, { receiver = receiver, database = database })
else
return
end
end
else
return langs[msg.lang].require_sudo
end
end
return {
description = "DATABASE",
patterns =
{
"^[#!/]([Cc][Rr][Ee][Aa][Tt][Ee][Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
"^[#!/]([Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
-- database
"^([Ss][Aa][Ss][Hh][Aa] [Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee])$",
},
run = run,
min_rank = 5
-- usage
-- SUDO
-- #createdatabase
-- (#database|[sasha] database)
}
|
fix database
|
fix database
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
d55ea181d4fa2763a3192584bbc43f6969f18e91
|
game_view.lua
|
game_view.lua
|
-- imports
grid_state = require 'grid_state'
glitch_gen = require 'glitchGen'
directions = require 'directions'
glider = require 'glider'
watcher = require 'watcher'
player_state = require 'player_state'
stack_trace = require 'stackTrace'
active_screen = require 'active_screen'
game_over_view = require 'game_over_view'
grid_normal_color = {180, 230, 255}
grid_block_color = {100, 200, 250}
grid_line_width = 0.5
grid_unit_size = 32
grid_big_border = 5
-- mouse variables
mouse_x = 0;
mouse_y = 0;
-- glider variables
rectanglesToDraw = {}
-- grid state
MODE_SIGNAL = 'signal'
MODE_EVOLUTION = 'evolution'
evolution_phases = 5
-- visual glitch state
glitchUpdateTimer = 0.5
function draw_line(grid_num, x1, y1, x2, y2)
local is_main = grid_num % grid_big_border == 0
local color = is_main and grid_block_color or grid_normal_color
local width = grid_line_width
love.graphics.setLineWidth(width)
love.graphics.setColor(color[1], color[2], color[3])
love.graphics.line(x1, y1, x2, y2)
end
function exports(round_num)
local instance = {}
local mouseClicked = false;
local lastFrameMouseClicked = true;
local block_size = grid_unit_size * grid_big_border
available_width = 1280 - 250
local xoffsets = available_width % block_size
if xoffsets == 0 then
xoffsets = block_size
end
local xoffset = xoffsets / 2
local xcount = (available_width - xoffsets) / grid_unit_size
local available_height = 720 - 20
local yoffsets = available_height % block_size
local yoffset = yoffsets / 2 + 20
local ycount = (available_height - yoffsets) / grid_unit_size
instance.grid_state = grid_state(xcount, ycount)
instance.grid_state.mode = MODE_SIGNAL
local function gliderClicked()
lastGlider.direction = directions.rotate_clockwise(lastGlider.direction)
end
local function processGoButtonClicked(grid_state, player_state)
player_state:endRound()
gliderPlaced = false
instance.grid_state.mode = MODE_EVOLUTION
tick_time = 0
evolution_phase = 1
end
instance.player_state = player_state(round_num)
for watcherI=1,5 do
instance.grid_state:add_object(watcher(math.random(1,xcount), math.random(1,ycount), directions.DOWN))
end
instance.goButtonImage = love.graphics.newImage( "placeholders/goButton.png" )
local goButtonX = love.window.getWidth()-225
local goButtonY = love.window.getHeight()-yoffset-50
local goButtonWidth = 150
local goButtonHeight = 50
local background = love.graphics.newImage('background/background_light.png')
instance.roundImage = love.graphics.newImage("placeholders/round.png")
local roundX = (xcount-0.7) * grid_unit_size + xoffset
local roundY = 0.4 * grid_unit_size
local roundWidth = 24
local signalImage = love.graphics.newImage('header/signal.png')
local processingImage = love.graphics.newImage('header/processing.png')
function instance:draw()
love.graphics.setColor(255,255,255)
love.graphics.draw(background, 0, 0)
if instance.grid_state.mode == MODE_SIGNAL then
love.graphics.draw(signalImage, xoffset, 17)
else
love.graphics.draw(processingImage, xoffset, 17)
end
-- Draw Grid
local current_x = xoffset
local grid_num = 0
while grid_num <= xcount do
draw_line(grid_num, current_x, yoffset, current_x, yoffset + ycount * grid_unit_size)
if mouse_x >= current_x and mouse_x < current_x + grid_unit_size then
drawGliderX = grid_num
end
current_x = current_x + grid_unit_size
grid_num = grid_num + 1
end
local current_y = yoffset
grid_num = 0
while grid_num <= ycount do
draw_line(grid_num, xoffset, current_y, xoffset + xcount * grid_unit_size, current_y)
if mouse_y >= current_y and mouse_y < current_y + grid_unit_size then
drawGliderY = grid_num
end
current_y = current_y + grid_unit_size
grid_num = grid_num + 1
end
stack_trace.draw_stack(self.grid_state, love.window.getWidth()-250, 100,love.mouse.getX(),love.mouse.getY(),xoffset,yoffset,current_object)
if glitchUpdateTimer > 0.2 then
glitchUpdate = true
glitchUpdateTimer = glitchUpdateTimer - 0.2
end
for i,rect in ipairs(rectanglesToDraw) do
glitch_gen.drawGlich(rect["x"], rect["y"], xcount, glitchUpdate)
end
for x = 1, xcount, 1 do
for y = 1, ycount, 1 do
if self.grid_state:get_space_at(x, y) then
glitch_gen.drawGlich( (x-1) * grid_unit_size + xoffset, (y-1) * grid_unit_size + yoffset, xcount, glitchUpdate)
end
end
end
self.grid_state:draw_objects(xoffset, yoffset)
glitchUpdate = false
if self.grid_state.mode == MODE_SIGNAL then
-- Button Go to Evolution mode
love.graphics.setColor(255, 255, 255)
love.graphics.draw(self.goButtonImage, goButtonX, goButtonY)
end
-- rounds
for i = 1, self.player_state.numberOfRounds, 1 do
love.graphics.draw(self.roundImage, roundX - (roundWidth+2)*(i-1),roundY)
end
end
function instance:update()
if self.player_state.gameOver then
active_screen.set(game_over_view())
return
end
if self.grid_state.mode == MODE_SIGNAL then
mouse_x, mouse_y = love.mouse.getPosition()
lastFrameMouseClicked = mouseClicked
mouseClicked = love.mouse.isDown("l")
if mouseClicked then
target_x = math.floor((mouse_x - xoffset) / grid_unit_size) + 1
target_y = math.floor((mouse_y - yoffset) / grid_unit_size) + 1
if self.grid_state:in_grid(target_x, target_y) and
not self.grid_state:get_space_at(target_x, target_y) then
if gliderPlaced then
if lastGlider.x == target_x and lastGlider.y == target_y and not lastFrameMouseClicked then
gliderClicked()
elseif self.grid_state:get_object_at(target_x, target_y) == nil then
lastGlider.x = target_x
lastGlider.y = target_y
end
elseif self.grid_state:get_object_at(target_x, target_y) == nil then
lastGlider = glider(target_x, target_y, directions.DOWN)
self.grid_state:add_object(lastGlider)
gliderPlaced = true
end
elseif mouse_x > goButtonX and mouse_x <= goButtonX + goButtonWidth and mouse_y > goButtonY and mouse_y <= goButtonY + goButtonHeight and not lastFrameMouseClicked then
processGoButtonClicked(self.grid_state, self.player_state)
end
end
else
if tick_time >= 3 then
tick_time = 0
if evolution_phase > evolution_phases then
self.grid_state.mode = MODE_SIGNAL
current_object = nil
else
if current_object == nil then
current_object = self.grid_state.first_object
end
if current_object ~= nil then
current_object:update(self.grid_state)
current_object = current_object.next
if current_object == nil then
evolution_phase = evolution_phase + 1
end
end
end
else
tick_time = tick_time + 1
end
end
glitchUpdateTimer = glitchUpdateTimer + 1/60
end
return instance
end
return exports
|
-- imports
grid_state = require 'grid_state'
glitch_gen = require 'glitchGen'
directions = require 'directions'
glider = require 'glider'
watcher = require 'watcher'
player_state = require 'player_state'
stack_trace = require 'stackTrace'
active_screen = require 'active_screen'
game_over_view = require 'game_over_view'
grid_normal_color = {180, 230, 255}
grid_block_color = {100, 200, 250}
grid_line_width = 0.5
grid_unit_size = 32
grid_big_border = 5
-- mouse variables
mouse_x = 0;
mouse_y = 0;
-- glider variables
rectanglesToDraw = {}
-- grid state
MODE_SIGNAL = 'signal'
MODE_EVOLUTION = 'evolution'
evolution_phases = 5
-- visual glitch state
glitchUpdateTimer = 0.5
function draw_line(grid_num, x1, y1, x2, y2)
local is_main = grid_num % grid_big_border == 0
local color = is_main and grid_block_color or grid_normal_color
local width = grid_line_width
love.graphics.setLineWidth(width)
love.graphics.setColor(color[1], color[2], color[3])
love.graphics.line(x1, y1, x2, y2)
end
function exports(round_num)
local instance = {}
local mouseClicked = false;
local lastFrameMouseClicked = true;
local block_size = grid_unit_size * grid_big_border
available_width = 1280 - 250
local xoffsets = available_width % block_size
if xoffsets == 0 then
xoffsets = block_size
end
local xoffset = xoffsets / 2
local xcount = (available_width - xoffsets) / grid_unit_size
local available_height = 720 - 20
local yoffsets = available_height % block_size
local yoffset = yoffsets / 2 + 20
local ycount = (available_height - yoffsets) / grid_unit_size
local gliderPlaced = false
instance.grid_state = grid_state(xcount, ycount)
instance.grid_state.mode = MODE_SIGNAL
local function gliderClicked()
lastGlider.direction = directions.rotate_clockwise(lastGlider.direction)
end
local function processGoButtonClicked(grid_state, player_state)
player_state:endRound()
gliderPlaced = false
instance.grid_state.mode = MODE_EVOLUTION
tick_time = 0
evolution_phase = 1
end
instance.player_state = player_state(round_num)
for watcherI=1,5 do
instance.grid_state:add_object(watcher(math.random(1,xcount), math.random(1,ycount), directions.DOWN))
end
instance.goButtonImage = love.graphics.newImage( "placeholders/goButton.png" )
local goButtonX = love.window.getWidth()-225
local goButtonY = love.window.getHeight()-yoffset-50
local goButtonWidth = 150
local goButtonHeight = 50
local background = love.graphics.newImage('background/background_light.png')
instance.roundImage = love.graphics.newImage("placeholders/round.png")
local roundX = (xcount-0.7) * grid_unit_size + xoffset
local roundY = 0.4 * grid_unit_size
local roundWidth = 24
local signalImage = love.graphics.newImage('header/signal.png')
local processingImage = love.graphics.newImage('header/processing.png')
function instance:draw()
love.graphics.setColor(255,255,255)
love.graphics.draw(background, 0, 0)
if instance.grid_state.mode == MODE_SIGNAL then
love.graphics.draw(signalImage, xoffset, 17)
else
love.graphics.draw(processingImage, xoffset, 17)
end
-- Draw Grid
local current_x = xoffset
local grid_num = 0
while grid_num <= xcount do
draw_line(grid_num, current_x, yoffset, current_x, yoffset + ycount * grid_unit_size)
if mouse_x >= current_x and mouse_x < current_x + grid_unit_size then
drawGliderX = grid_num
end
current_x = current_x + grid_unit_size
grid_num = grid_num + 1
end
local current_y = yoffset
grid_num = 0
while grid_num <= ycount do
draw_line(grid_num, xoffset, current_y, xoffset + xcount * grid_unit_size, current_y)
if mouse_y >= current_y and mouse_y < current_y + grid_unit_size then
drawGliderY = grid_num
end
current_y = current_y + grid_unit_size
grid_num = grid_num + 1
end
stack_trace.draw_stack(self.grid_state, love.window.getWidth()-250, 100,love.mouse.getX(),love.mouse.getY(),xoffset,yoffset,current_object)
if glitchUpdateTimer > 0.2 then
glitchUpdate = true
glitchUpdateTimer = glitchUpdateTimer - 0.2
end
for i,rect in ipairs(rectanglesToDraw) do
glitch_gen.drawGlich(rect["x"], rect["y"], xcount, glitchUpdate)
end
for x = 1, xcount, 1 do
for y = 1, ycount, 1 do
if self.grid_state:get_space_at(x, y) then
glitch_gen.drawGlich( (x-1) * grid_unit_size + xoffset, (y-1) * grid_unit_size + yoffset, xcount, glitchUpdate)
end
end
end
self.grid_state:draw_objects(xoffset, yoffset)
glitchUpdate = false
if self.grid_state.mode == MODE_SIGNAL then
-- Button Go to Evolution mode
love.graphics.setColor(255, 255, 255)
love.graphics.draw(self.goButtonImage, goButtonX, goButtonY)
end
-- rounds
for i = 1, self.player_state.numberOfRounds, 1 do
love.graphics.draw(self.roundImage, roundX - (roundWidth+2)*(i-1),roundY)
end
end
function instance:update()
mouse_x, mouse_y = love.mouse.getPosition()
local wasClicked = mouseClicked
mouseClicked = love.mouse.isDown("l")
if self.grid_state.mode == MODE_SIGNAL then
if mouseClicked then
target_x = math.floor((mouse_x - xoffset) / grid_unit_size) + 1
target_y = math.floor((mouse_y - yoffset) / grid_unit_size) + 1
if self.grid_state:in_grid(target_x, target_y) and
not self.grid_state:get_space_at(target_x, target_y) then
if gliderPlaced then
if lastGlider.x == target_x and lastGlider.y == target_y and not lastFrameMouseClicked then
print('rotate')
gliderClicked()
elseif self.grid_state:get_object_at(target_x, target_y) == nil then
print('move')
lastGlider.x = target_x
lastGlider.y = target_y
end
elseif self.grid_state:get_object_at(target_x, target_y) == nil and not lastFrameMouseClicked then
print('place')
lastGlider = glider(target_x, target_y, directions.DOWN)
self.grid_state:add_object(lastGlider)
gliderPlaced = true
end
elseif mouse_x > goButtonX and mouse_x <= goButtonX + goButtonWidth and mouse_y > goButtonY and mouse_y <= goButtonY + goButtonHeight and not lastFrameMouseClicked then
processGoButtonClicked(self.grid_state, self.player_state)
end
end
if self.player_state.gameOver then
active_screen.set(game_over_view())
return
end
else
if tick_time >= 3 then
tick_time = 0
if evolution_phase > evolution_phases then
self.grid_state.mode = MODE_SIGNAL
current_object = nil
else
if current_object == nil then
current_object = self.grid_state.first_object
end
if current_object ~= nil then
current_object:update(self.grid_state)
current_object = current_object.next
if current_object == nil then
evolution_phase = evolution_phase + 1
end
end
end
else
tick_time = tick_time + 1
end
end
lastFrameMouseClicked = mouseClicked
glitchUpdateTimer = glitchUpdateTimer + 1/60
end
return instance
end
return exports
|
Fixed glider placement bug
|
Fixed glider placement bug
Glider was automatically placed at the beginning, but not anymore.
|
Lua
|
mit
|
NamefulTeam/PortoGameJam2015
|
ee9bef10231e85b47266b87da6a60c6a03052fb5
|
mrimoff.lua
|
mrimoff.lua
|
-- mrimoff.lua
--
-- Stored procedures for Mail.Ru Agent offline messages storage.
--
--
-- index0 - { userid, msgid } (TREE, unique)
--
local function get_key_cardinality_and_max_msgid(index_no, ...)
local key = ...
-- TODO: optimize (replace by calculation cardinality of a key in the index)
local data = { box.select(0, index_no, key) }
local n = #data
if n == 0 then
return 0, 0
end
return n, box.unpack('i', data[n][1])
end
--
-- Add offline message @msg for user @userid.
-- If storage already contains @limit messages do nothing.
-- Returns tuple { "number of messages for this user", "id for added message" }
-- "id for added message" == 0 if no message was added.
--
function mrim_add(userid, msg)
-- client sends integers encoded as BER-strings
userid = box.unpack('i', userid)
local limit = 1000
local n_msgs, max_msgid = get_key_cardinality_and_max_msgid(0, userid)
if n_msgs >= limit then
return { box.pack('i', n_msgs), box.pack('i', 0) }
end
local msgid = max_msgid + 1
box.insert(0, userid, msgid, msg)
return { box.pack('i', n_msgs + 1), box.pack('i', msgid) }
end
--
-- Delete offline message with id @msgid for user @userid.
-- Returns flag of deletion success.
--
function mrim_del(userid, msgid)
-- client sends integers encoded as BER-strings
userid = box.unpack('i', userid)
msgid = box.unpack('i', msgid)
local del = box.delete(0, userid, msgid)
if del ~= nil then
return box.pack('i', 1)
end
return box.pack('i', 0)
end
--
-- Delete all offline messages for user @userid.
-- Returns flag of deletion success.
--
function mrim_del_all(userid)
-- client sends integers encoded as BER-strings
userid = box.unpack('i', userid)
local msgs = { box.select(0, 0, userid) }
for _, msg in ipairs(msgs) do
box.delete(0, msg[0], msg[1])
end
return box.pack('i', #msgs)
end
--
-- Get no more then @limit messages for user @userid
-- sorted ascending by addition order.
-- Returns tuple { "total number of messages for user" }
-- followed by tuples with requested user messages.
--
function mrim_get(userid, limit)
-- client sends integers encoded as BER-strings
userid = box.unpack('i', userid)
limit = box.unpack('i', limit)
-- TODO: use one select request for calculation of n_msgs and getting no more then @limit msgs
local n_msgs, _ = get_key_cardinality_and_max_msgid(0, userid)
return box.pack('i', n_msgs), box.select_limit(0, 0, 0, limit, userid)
end
|
-- mrimoff.lua
--
-- Stored procedures for Mail.Ru Agent offline messages storage.
--
--
-- index0 - { userid, msgid } (TREE, unique)
--
local function get_key_cardinality_and_max_msgid(index_no, ...)
local key = ...
-- TODO: optimize (replace by calculation cardinality of a key in the index)
local data = { box.select(0, index_no, key) }
local n = #data
if n == 0 then
return 0, 0
end
return n, box.unpack('i', data[n][1])
end
--
-- Add offline message @msg for user @userid.
-- If storage already contains @limit messages do nothing.
-- Returns tuple { "number of messages for this user", "id for added message" }
-- "id for added message" == 0 if no message was added.
--
function mrim_add(userid, msg)
-- client sends integers encoded as BER-strings
userid = box.unpack('i', userid)
local limit = 1000
while true do
local n_msgs, max_msgid = get_key_cardinality_and_max_msgid(0, userid)
if n_msgs >= limit then
return { box.pack('i', n_msgs), box.pack('i', 0) }
end
local msgid = max_msgid + 1
local status, result = pcall(box.insert, 0, userid, msgid, msg)
if status then
return { box.pack('i', n_msgs + 1), box.pack('i', msgid) }
else
--exception
box.fiber.sleep(0.001)
end
end
end
--
-- Delete offline message with id @msgid for user @userid.
-- Returns flag of deletion success.
--
function mrim_del(userid, msgid)
-- client sends integers encoded as BER-strings
userid = box.unpack('i', userid)
msgid = box.unpack('i', msgid)
local del = box.delete(0, userid, msgid)
if del ~= nil then
return box.pack('i', 1)
end
return box.pack('i', 0)
end
--
-- Delete all offline messages for user @userid.
-- Returns flag of deletion success.
--
function mrim_del_all(userid)
-- client sends integers encoded as BER-strings
userid = box.unpack('i', userid)
local msgs = { box.select(0, 0, userid) }
for _, msg in pairs(msgs) do
box.delete(0, msg[0], msg[1])
end
return box.pack('i', #msgs)
end
--
-- Get no more then @limit messages for user @userid
-- sorted ascending by addition order.
-- Returns tuple { "total number of messages for user" }
-- followed by tuples with requested user messages.
--
function mrim_get(userid, limit)
-- client sends integers encoded as BER-strings
userid = box.unpack('i', userid)
limit = box.unpack('i', limit)
-- TODO: use one select request for calculation of n_msgs and getting no more then @limit msgs
local n_msgs, _ = get_key_cardinality_and_max_msgid(0, userid)
return box.pack('i', n_msgs), box.select_limit(0, 0, 0, limit, userid)
end
|
mrimoff.lua: fix race condition on mrim_add
|
mrimoff.lua: fix race condition on mrim_add
|
Lua
|
bsd-2-clause
|
derElektrobesen/tntlua,grechkin-pogrebnyakov/tntlua,spectrec/tntlua,mailru/tntlua,BHYCHIK/tntlua
|
61a3593e2d9a4ebcab388fd204bec025836a1a6a
|
packages/luci-mod-status/files/usr/lib/lua/luci/controller/status/bmx6.lua
|
packages/luci-mod-status/files/usr/lib/lua/luci/controller/status/bmx6.lua
|
--[[
Copyright (C) 2011 Pau Escrich <pau@dabax.net>
Contributors Jo-Philipp Wich <xm@subsignal.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
--]]
local bmx6json = require("luci.model.bmx6json")
module("luci.controller.status.bmx6", package.seeall)
function index()
local place = {}
local ucim = require "luci.model.uci"
local uci = ucim.cursor()
require("nixio.fs")
-- checking if luci-app-bmx6 is installed
if not nixio.fs.stat(luci.util.libpath() .. "/controller/bmx6.lua") then
return nil
end
-- default values
place = {"status", "bmx6"}
---------------------------
-- Starting with the pages
---------------------------
--- status (default)
entry(place,call("action_nodes_j"),"BMX6",11)
-- not visible
table.insert(place,"nodes_nojs")
entry(place, call("action_nodes"), nil)
table.remove(place)
--- nodes
table.insert(place,"Nodes")
entry(place,call("action_nodes_j"),"Nodes",0)
table.remove(place)
table.insert(place,"Status")
entry(place,call("action_status_j"),"Status",1)
table.remove(place)
--- links
table.insert(place,"Links")
entry(place,call("action_links"),"Links",2).leaf = true
table.remove(place)
-- Tunnels
table.insert(place,"Tunnels")
entry(place,call("action_tunnels_j"), "Tunnels", 3).leaf = true
table.remove(place)
--- Graph
table.insert(place,"Graph")
entry(place, template("bmx6/graph"), "Graph",4)
table.remove(place)
--- Topology (hidden)
table.insert(place,"topology")
entry(place, call("action_topology"), nil)
table.remove(place)
table.remove(place)
end
function action_status()
local status = bmx6json.get("status").status or nil
local interfaces = bmx6json.get("interfaces").interfaces or nil
if status == nil or interfaces == nil then
luci.template.render("bmx6/error", {txt="Cannot fetch data from bmx6 json"})
else
luci.template.render("bmx6/status", {status=status,interfaces=interfaces})
end
end
function action_status_j()
luci.template.render("bmx6/status_j", {})
end
function action_nodes()
local orig_list = bmx6json
orig_list = bmx6json.get("originators")
luci.template.render("bmx6/error", {txt="Cannot fetch data from bmx6 json"..orig_list})
end
function action_nodesx()
local orig_list = bmx6json
orig_list = bmx6json.get("originators")
luci.template.render("bmx6/error", {txt="Cannot fetch data from bmx6 json"..orig_list})
orig_list = bmx6json.get("originators").originators or nil
if orig_list == nil then
luci.template.render("bmx6/error", {txt="Cannot fetch data from bmx6 json"})
return nil
end
local originators = {}
local desc = nil
local orig = nil
local name = ""
local ipv4 = ""
for _,o in ipairs(orig_list) do
orig = bmx6json.get("originators/"..o.name) or {}
desc = bmx6json.get("descriptions/"..o.name) or {}
if string.find(o.name,'.') then
name = luci.util.split(o.name,'.')[1]
else
name = o.name
end
table.insert(originators,{name=name,orig=orig,desc=desc})
end
luci.template.render("bmx6/nodes", {originators=originators})
end
function action_nodes_j()
local http = require "luci.http"
local link_non_js = "/cgi-bin/luci" .. http.getenv("PATH_INFO") .. '/nodes_nojs'
luci.template.render("bmx6/nodes_j", {link_non_js=link_non_js})
end
function action_gateways_j()
luci.template.render("bmx6/gateways_j", {})
end
function action_tunnels_j()
luci.template.render("bmx6/tunnels_j", {})
end
function action_links(host)
local links = bmx6json.get("links", host)
local devlinks = {}
local _,l
if links ~= nil then
links = links.links
for _,l in ipairs(links) do
devlinks[l.viaDev] = {}
end
for _,l in ipairs(links) do
l.name = luci.util.split(l.name,'.')[1]
table.insert(devlinks[l.viaDev],l)
end
end
luci.template.render("bmx6/links", {links=devlinks})
end
function action_topology()
local originators = bmx6json.get("originators/all")
local o,i,l,i2
local first = true
local topology = '[ '
local cache = '/tmp/bmx6-topology.json'
local offset = 60
local cachefd = io.open(cache,r)
local update = false
if cachefd ~= nil then
local lastupdate = tonumber(cachefd:read("*line")) or 0
if os.time() >= lastupdate + offset then
update = true
else
topology = cachefd:read("*all")
end
cachefd:close()
end
if cachefd == nil or update then
for i,o in ipairs(originators) do
local links = bmx6json.get("links",o.primaryIp)
if links then
if first then
first = false
else
topology = topology .. ', '
end
topology = topology .. '{ "name": "%s", "links": [' %o.name
local first2 = true
for i2,l in ipairs(links.links) do
if first2 then
first2 = false
else
topology = topology .. ', '
end
name = l.name or l.llocalIp or "unknown"
topology = topology .. '{ "name": "%s", "rxRate": %s, "txRate": %s }'
%{ name, l.rxRate, l.txRate }
end
topology = topology .. ']}'
end
end
topology = topology .. ' ]'
-- Upgrading the content of the cache file
cachefd = io.open(cache,'w+')
cachefd:write(os.time()..'\n')
cachefd:write(topology)
cachefd:close()
end
luci.http.prepare_content("application/json")
luci.http.write(topology)
end
|
--[[
Copyright (C) 2011 Pau Escrich <pau@dabax.net>
Contributors Jo-Philipp Wich <xm@subsignal.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
--]]
module("luci.controller.status.bmx6", package.seeall)
local fs = require("nixio.fs")
local bmx6json
-- check if luci-app-bmx6 is installed
if fs.stat(luci.util.libpath() .. "/model/bmx6json.lua") then
bmx6json = require("luci.model.bmx6json")
end
function index()
local place = {}
local ucim = require "luci.model.uci"
local uci = ucim.cursor()
local fs = require("nixio.fs")
-- checking if luci-app-bmx6 is installed
if not fs.stat(luci.util.libpath() .. "/controller/bmx6.lua") then
return nil
end
-- default values
place = {"status", "bmx6"}
---------------------------
-- Starting with the pages
---------------------------
--- status (default)
entry(place,call("action_nodes_j"),"BMX6",11)
-- not visible
table.insert(place,"nodes_nojs")
entry(place, call("action_nodes"), nil)
table.remove(place)
--- nodes
table.insert(place,"Nodes")
entry(place,call("action_nodes_j"),"Nodes",0)
table.remove(place)
table.insert(place,"Status")
entry(place,call("action_status_j"),"Status",1)
table.remove(place)
--- links
table.insert(place,"Links")
entry(place,call("action_links"),"Links",2).leaf = true
table.remove(place)
-- Tunnels
table.insert(place,"Tunnels")
entry(place,call("action_tunnels_j"), "Tunnels", 3).leaf = true
table.remove(place)
--- Graph
table.insert(place,"Graph")
entry(place, template("bmx6/graph"), "Graph",4)
table.remove(place)
--- Topology (hidden)
table.insert(place,"topology")
entry(place, call("action_topology"), nil)
table.remove(place)
table.remove(place)
end
function action_status()
local status = bmx6json.get("status").status or nil
local interfaces = bmx6json.get("interfaces").interfaces or nil
if status == nil or interfaces == nil then
luci.template.render("bmx6/error", {txt="Cannot fetch data from bmx6 json"})
else
luci.template.render("bmx6/status", {status=status,interfaces=interfaces})
end
end
function action_status_j()
luci.template.render("bmx6/status_j", {})
end
function action_nodes()
local orig_list = bmx6json
orig_list = bmx6json.get("originators")
luci.template.render("bmx6/error", {txt="Cannot fetch data from bmx6 json"..orig_list})
end
function action_nodesx()
local orig_list = bmx6json
orig_list = bmx6json.get("originators")
luci.template.render("bmx6/error", {txt="Cannot fetch data from bmx6 json"..orig_list})
orig_list = bmx6json.get("originators").originators or nil
if orig_list == nil then
luci.template.render("bmx6/error", {txt="Cannot fetch data from bmx6 json"})
return nil
end
local originators = {}
local desc = nil
local orig = nil
local name = ""
local ipv4 = ""
for _,o in ipairs(orig_list) do
orig = bmx6json.get("originators/"..o.name) or {}
desc = bmx6json.get("descriptions/"..o.name) or {}
if string.find(o.name,'.') then
name = luci.util.split(o.name,'.')[1]
else
name = o.name
end
table.insert(originators,{name=name,orig=orig,desc=desc})
end
luci.template.render("bmx6/nodes", {originators=originators})
end
function action_nodes_j()
local http = require "luci.http"
local link_non_js = "/cgi-bin/luci" .. http.getenv("PATH_INFO") .. '/nodes_nojs'
luci.template.render("bmx6/nodes_j", {link_non_js=link_non_js})
end
function action_gateways_j()
luci.template.render("bmx6/gateways_j", {})
end
function action_tunnels_j()
luci.template.render("bmx6/tunnels_j", {})
end
function action_links(host)
local links = bmx6json.get("links", host)
local devlinks = {}
local _,l
if links ~= nil then
links = links.links
for _,l in ipairs(links) do
devlinks[l.viaDev] = {}
end
for _,l in ipairs(links) do
l.name = luci.util.split(l.name,'.')[1]
table.insert(devlinks[l.viaDev],l)
end
end
luci.template.render("bmx6/links", {links=devlinks})
end
function action_topology()
local originators = bmx6json.get("originators/all")
local o,i,l,i2
local first = true
local topology = '[ '
local cache = '/tmp/bmx6-topology.json'
local offset = 60
local cachefd = io.open(cache,r)
local update = false
if cachefd ~= nil then
local lastupdate = tonumber(cachefd:read("*line")) or 0
if os.time() >= lastupdate + offset then
update = true
else
topology = cachefd:read("*all")
end
cachefd:close()
end
if cachefd == nil or update then
for i,o in ipairs(originators) do
local links = bmx6json.get("links",o.primaryIp)
if links then
if first then
first = false
else
topology = topology .. ', '
end
topology = topology .. '{ "name": "%s", "links": [' %o.name
local first2 = true
for i2,l in ipairs(links.links) do
if first2 then
first2 = false
else
topology = topology .. ', '
end
name = l.name or l.llocalIp or "unknown"
topology = topology .. '{ "name": "%s", "rxRate": %s, "txRate": %s }'
%{ name, l.rxRate, l.txRate }
end
topology = topology .. ']}'
end
end
topology = topology .. ' ]'
-- Upgrading the content of the cache file
cachefd = io.open(cache,'w+')
cachefd:write(os.time()..'\n')
cachefd:write(topology)
cachefd:close()
end
luci.http.prepare_content("application/json")
luci.http.write(topology)
end
|
fixup 'pull controller/bmx6.lua', check if bmx6json.lua exists before trying to require it
|
fixup 'pull controller/bmx6.lua', check if bmx6json.lua exists before trying to require it
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,libremesh/lime-packages,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
|
e63918f99050d4b0601294e06c9fc3f92d1fa704
|
otouto/plugins/admin/setrules.lua
|
otouto/plugins/admin/setrules.lua
|
--[[
setrules.lua
Copyright 2018 topkecleon <drew@otou.to>
This code is licensed under the GNU AGPLv3. See /LICENSE for details.
]]--
local utilities = require('otouto.utilities')
local P = {}
function P:init(bot)
self.triggers = utilities.triggers(bot.info.username, bot.config.cmd_pat)
:t('setrules?', true):t('changerules?', true)
:t('addrules?', true):t('delrules?', true).table
self.command = 'setrules <subcommand>'
-- luacheck: push no max string line length
self.doc = [[
change [i]
Changes an existing rule or rules, starting at $i. If $i is unspecified, all rules will be overwritten.
Alias: /changerule
add [i]
Adds a new rule or rules, inserted starting at $i. If $i is unspecified, the new rule or rules will be added to the end of the list.
Alias: /addrule
del [i]
Deletes a rule. If $i is unspecified, all rules will be deleted.
Alias: /delrule
Examples:
• Set all the rules for a group.
/changerules
First rule.
Second rule.
...
• Change rule 4.
/changerule 4
Changed fourth rule.
[Changed fifth rule.]
• Add a rule or rules between 2 and 3.
/addrule 3
New third rule.
[New fourth rule.]
]]
-- luacheck: pop
self.privilege = 3
self.administration = true
end
function P:action(bot, msg, group)
local subc, idx
-- "/changerule ..." -> "/setrules change ..."
local c = '^' .. bot.config.cmd_pat
if msg.text_lower:match(c..'changerule') then
subc = 'change'
idx = msg.text_lower:match(c..'changerules?%s+(%d+)')
elseif msg.text_lower:match(c..'addrule') then
subc = 'add'
idx = msg.text_lower:match(c..'addrules?%s+(%d+)')
elseif msg.text_lower:match(c..'delrule') then
subc = 'del'
idx = msg.text_lower:match(c..'delrules?%s+(%d+)')
else
subc, idx = msg.text_lower:match(c..'setrules?%s+(%a+)%s*(%d*)')
end
local nrules = msg.text:match('^.-\n+(.+)$') or msg.reply_to_message and
msg.reply_to_message.text
local new_rules = {}
if nrules then
for s in string.gmatch(nrules..'\n', '(.-)\n') do
table.insert(new_rules, s)
end
end
local output
if self.subcommands[subc] then
output = self.subcommands[subc](self, group, new_rules, tonumber(idx))
else
output = 'Invalid subcommand. See /help setrules.'
end
utilities.send_reply(msg, output, 'html')
end
P.subcommands = {
change = function (super, group, new_rules, idx)
local admin = group.data.admin
if #new_rules == 0 then
return 'Please specify the new rule or rules.'
elseif not idx then -- /setrules
admin.rules = new_rules
local output = '<b>Rules for ' .. utilities.html_escape(admin.name) ..
':</b>'
for i, rule in ipairs(admin.rules) do
output = output .. '\n<b>' .. i .. '.</b> ' .. rule
end
return output
elseif idx < 1 then
return 'Invalid index.'
elseif idx > #admin.rules then
return super.subcommands.add(group, new_rules, idx)
else -- /changerule i
local output = ''
for i = 1, #new_rules do
admin.rules[idx+i-1] = new_rules[i]
output = output .. '\n<b>' .. idx+i-1 .. '.</b> ' .. new_rules[i]
end
return output
end
end,
add = function (_super, group, new_rules, idx)
local admin = group.data.admin
if #new_rules == 0 then
return 'Please specify the new rule or rules.'
elseif not idx or idx > #admin.rules then -- /addrule
local output = ''
for i = 1, #new_rules do
table.insert(admin.rules, new_rules[i])
output = output .. '\n<b>' .. #admin.rules .. '.</b> ' .. new_rules[i]
end
return output
elseif idx < 1 then
return 'Invalid index.'
else -- /addrule i
local output = ''
for i = 1, #new_rules do
table.insert(admin.rules, idx+i-1, new_rules[i])
output = output .. '\n<b>' .. idx+i-1 .. '.</b> ' .. new_rules[i]
end
return output
end
end,
del = function (_super, group, _new_rules, idx)
local admin = group.data.admin
if not idx then -- /setrules --
admin.rules = {}
return 'The rules have been deleted.'
elseif idx > #admin.rules or idx < 0 then
return 'Invalid index.'
else -- /changerule i --
table.remove(admin.rules, idx)
return 'Rule ' .. idx .. ' has been deleted.'
end
end,
}
return P
|
--[[
setrules.lua
Copyright 2018 topkecleon <drew@otou.to>
This code is licensed under the GNU AGPLv3. See /LICENSE for details.
]]--
local utilities = require('otouto.utilities')
local P = {}
function P:init(bot)
self.triggers = utilities.triggers(bot.info.username, bot.config.cmd_pat)
:t('setrules?', true):t('changerules?', true)
:t('addrules?', true):t('delrules?', true).table
self.command = 'setrules <subcommand>'
-- luacheck: push no max string line length
self.doc = [[
change [i]
Changes an existing rule or rules, starting at $i. If $i is unspecified, all rules will be overwritten.
Alias: /changerule
add [i]
Adds a new rule or rules, inserted starting at $i. If $i is unspecified, the new rule or rules will be added to the end of the list.
Alias: /addrule
del [i]
Deletes a rule. If $i is unspecified, all rules will be deleted.
Alias: /delrule
Examples:
• Set all the rules for a group.
/changerules
First rule.
Second rule.
...
• Change rule 4.
/changerule 4
Changed fourth rule.
[Changed fifth rule.]
• Add a rule or rules between 2 and 3.
/addrule 3
New third rule.
[New fourth rule.]
]]
-- luacheck: pop
self.privilege = 3
self.administration = true
end
function P:action(bot, msg, group)
local subc, idx
-- "/changerule ..." -> "/setrules change ..."
local c = '^' .. bot.config.cmd_pat
if msg.text_lower:match(c..'changerule') then
subc = 'change'
idx = msg.text_lower:match(c..'changerules?%s+(%d+)')
elseif msg.text_lower:match(c..'addrule') then
subc = 'add'
idx = msg.text_lower:match(c..'addrules?%s+(%d+)')
elseif msg.text_lower:match(c..'delrule') then
subc = 'del'
idx = msg.text_lower:match(c..'delrules?%s+(%d+)')
else
subc, idx = msg.text_lower:match(c..'setrules?%s+(%a+)%s*(%d*)')
end
local nrules = msg.text:match('^.-\n+(.+)$') or msg.reply_to_message and
msg.reply_to_message.text
local new_rules = {}
if nrules then
for s in string.gmatch(nrules..'\n', '(.-)\n') do
table.insert(new_rules, s)
end
end
local output
if self.subcommands[subc] then
output = self.subcommands[subc](self, group, new_rules, tonumber(idx))
else
output = 'Invalid subcommand. See /help setrules.'
end
utilities.send_reply(msg, output, 'html')
end
P.subcommands = {
change = function (super, group, new_rules, idx)
local admin = group.data.admin
if #new_rules == 0 then
return 'Please specify the new rule or rules.'
elseif not idx then -- /setrules
admin.rules = new_rules
local output = '<b>Rules for ' .. utilities.html_escape(
utilities.format_name(group.info)) .. ':</b>'
for i, rule in ipairs(admin.rules) do
output = output .. '\n<b>' .. i .. '.</b> ' .. rule
end
return output
elseif idx < 1 then
return 'Invalid index.'
elseif idx > #admin.rules then
return super.subcommands.add(group, new_rules, idx)
else -- /changerule i
local output = ''
for i = 1, #new_rules do
admin.rules[idx+i-1] = new_rules[i]
output = output .. '\n<b>' .. idx+i-1 .. '.</b> ' .. new_rules[i]
end
return output
end
end,
add = function (_super, group, new_rules, idx)
local admin = group.data.admin
if #new_rules == 0 then
return 'Please specify the new rule or rules.'
elseif not idx or idx > #admin.rules then -- /addrule
local output = ''
for i = 1, #new_rules do
table.insert(admin.rules, new_rules[i])
output = output .. '\n<b>' .. #admin.rules .. '.</b> ' .. new_rules[i]
end
return output
elseif idx < 1 then
return 'Invalid index.'
else -- /addrule i
local output = ''
for i = 1, #new_rules do
table.insert(admin.rules, idx+i-1, new_rules[i])
output = output .. '\n<b>' .. idx+i-1 .. '.</b> ' .. new_rules[i]
end
return output
end
end,
del = function (_super, group, _new_rules, idx)
local admin = group.data.admin
if not idx then -- /setrules --
admin.rules = {}
return 'The rules have been deleted.'
elseif idx > #admin.rules or idx < 0 then
return 'Invalid index.'
else -- /changerule i --
table.remove(admin.rules, idx)
return 'Rule ' .. idx .. ' has been deleted.'
end
end,
}
return P
|
setrules bugfix
|
setrules bugfix
|
Lua
|
agpl-3.0
|
topkecleon/otouto
|
61cb343d98df74f4dfd28b566aad3fccc30e2cd0
|
state/load-libraries.lua
|
state/load-libraries.lua
|
local Node = require "node.Node"
local Directory = require "node.Directory"
local function liberror(message)
local node = new "node.Node" { name = message }
node.icon = emufun.images.error
node:add_command("Quit EmuFun", emufun.quit)
return node
end
local root = new "node.Node" { name = "EmuFun" }
root.icon = emufun.images.directory
local getfenv = getfenv
local _config = emufun.config._library_config_fn
function root:config()
return _config(getfenv())
end
local library = new "node.Node" {
name = "Media Library";
parent = root;
icon = emufun.images.directory;
}
function library:run()
return unpack(self)
end
function library:path()
return ""
end
root:add(library)
local configs = new "node.Directory" {
name = "Emufun Configuration";
parent = root;
path = function(self, name)
return love.filesystem.getSaveDirectory().."/config/"..(name or "");
end;
}
-- TODO: add a "text" file type, with appropriate default editor and icon, and
-- add a library rule for editing files of that type.
configs.config = loadstring [[
name_matches "%.cfg" {
hidden = false;
execute = emufun.config.editor.." ${path}";
}
]]
root:add(configs)
for _,path in ipairs(emufun.config.library_paths) do
local lib = new "node.Directory" { name = path, parent = library }
lib:populate()
if lib[1] then
library:add(lib)
end
end
if #library == 0 then
library:add(liberror("Media library is empty!"))
end
return state "gamelist" (root, library)
|
local Node = require "node.Node"
local Directory = require "node.Directory"
local function liberror(message)
local node = new "node.Node" { name = message }
node.icon = emufun.images.error
node:add_command {
name = "Quit Emufun";
run = emufun.quit;
}
return node
end
local root = new "node.Node" { name = "EmuFun" }
root.icon = emufun.images.directory
local getfenv = getfenv
local _config = emufun.config._library_config_fn
function root:config()
return _config(getfenv())
end
local library = new "node.Node" {
name = "Media Library";
parent = root;
icon = emufun.images.directory;
}
function library:run()
return unpack(self)
end
function library:path()
return ""
end
root:add(library)
local configs = new "node.Directory" {
name = "Emufun Configuration";
parent = root;
path = function(self, name)
return love.filesystem.getSaveDirectory().."/config/"..(name or "");
end;
}
-- TODO: add a "text" file type, with appropriate default editor and icon, and
-- add a library rule for editing files of that type.
configs.config = loadstring [[
name_matches "%.cfg" {
hidden = false;
execute = emufun.config.editor.." ${path}";
}
]]
root:add(configs)
for _,path in ipairs(emufun.config.library_paths) do
local lib = new "node.Directory" { name = path, parent = library }
lib:populate()
if lib[1] then
library:add(lib)
end
end
if #library == 0 then
library:add(liberror("Media library is empty!"))
end
return state "gamelist" (root, library)
|
Fix error message when no media libraries could be opened
|
Fix error message when no media libraries could be opened
|
Lua
|
mit
|
ToxicFrog/EmuFun
|
79ff21798a52922175122e2425c36a5e12827629
|
api.lua
|
api.lua
|
local api = {}
local http = require("socket.http")
local https = require("ssl.https")
local ltn12 = require("ltn12")
local cjson = require("cjson")
local encode = require("multipart-post").encode
https.TIMEOUT = 5
local utils = require("utils")
---@param method string
---@param parameters table
function api.makeRequest(method, parameters)
local response = {}
empty = true
for k, v in pairs(parameters) do
if type(v) == "number" or type(v) == "boolean" then
parameters[k] = tostring(v)
end
empty = false
end
logger:debug("call " .. method .. " with " .. utils.encode(parameters))
local success, code, headers, status
if empty then
success, code, headers, status = https.request{
url = "https://api.telegram.org/bot" .. config.token .. "/" .. method,
method = "GET",
sink = ltn12.sink.table(response),
}
else
local body, boundary = encode(parameters)
success, code, headers, status = https.request{
url = "https://api.telegram.org/bot" .. config.token .. "/" .. method,
method = "POST",
headers = {
["Content-Type"] = "multipart/form-data; boundary=" .. boundary,
["Content-Length"] = string.len(body),
},
source = ltn12.source.string(body),
sink = ltn12.sink.table(response),
}
end
if success then
local status, msg = pcall(cjson.decode, table.concat(response))
if status then
logger:debug("response " .. utils.encode(msg))
return msg
else
logger:error("failed to decode: " .. msg)
end
else
logger:error("failed to request: " .. code)
end
end
function api.fetch()
logger:info("fetching latest API ...")
local html = utils.curl("https://core.telegram.org/bots/api"):match("Available methods(.+)$")
html = utils.htmlDecode(html)
local apis = {}
for method, content in html:gsub("<h4>", "<h4><h4>"):gmatch('<h4>[^\n]-</i></a>([a-z]%S-)</h4>(.-)<h4>') do
local t = {
parameters = {},
order = {}
}
setmetatable(t, {
__call = function(...)
local args = {...}
local body = {}
local named = (#args == 1 and type(args[1]) == "table")
for i = 1, #t.order do
body[t.order[i]] = named and args[1][t.order[i]] or args[i]
if (t.parameters[t.order[i]].required and not body[t.order[i]]) then
logger:error("method " .. method .. " missing parameter " .. t.order[i])
return false
end
end
return api.makeRequest(method, body)
end,
__tostring = function()
return table.concat({
"[method] ", method, "\n",
"[description] ", t.description, "\n",
"[parameters] ", table.concat(t.order, ", "),
})
end
})
local description, parameter
if content:find("table") then
description, parameter = content:match('%s*(.-)%s*<table class="table">.-</tr>(.-)</table>')
else
description = content:match("^%s*(.-)%s*$")
parameter = ""
end
t.description = description:gsub("<.->", ""):gsub("\n\n", "\n")
for name, var, req, des in parameter:gmatch('<tr>%s*<td>(.-)</td>%s*<td>(.-)</td>%s*<td>(.-)</td>%s*<td>(.-)</td>%s*</tr>') do
table.insert(t.order, name)
t.parameters[name] = {
type = var:gsub("<.->", ""),
required = req == "Yes",
description = des:gsub("<.->", "")
}
end
apis[method] = t
end
return apis
end
return api
|
local api = {}
local http = require("socket.http")
local https = require("ssl.https")
local ltn12 = require("ltn12")
local cjson = require("cjson")
local encode = require("multipart-post").encode
https.TIMEOUT = 5
local utils = require("utils")
---@param method string
---@param parameters table
function api.makeRequest(method, parameters)
local response = {}
empty = true
for k, v in pairs(parameters) do
parameters[k] = tostring(v)
empty = false
end
logger:debug("call " .. method .. " with " .. utils.encode(parameters))
local success, code, headers, status
if empty then
success, code, headers, status = https.request{
url = "https://api.telegram.org/bot" .. config.token .. "/" .. method,
method = "GET",
sink = ltn12.sink.table(response),
}
else
local body, boundary = encode(parameters)
success, code, headers, status = https.request{
url = "https://api.telegram.org/bot" .. config.token .. "/" .. method,
method = "POST",
headers = {
["Content-Type"] = "multipart/form-data; boundary=" .. boundary,
["Content-Length"] = string.len(body),
},
source = ltn12.source.string(body),
sink = ltn12.sink.table(response),
}
end
if success then
local status, msg = pcall(cjson.decode, table.concat(response))
if status then
logger:debug("response " .. utils.encode(msg))
return msg
else
logger:error("failed to decode: " .. msg)
end
else
logger:error("failed to request: " .. code)
end
end
function api.fetch()
logger:info("fetching latest API ...")
local html = utils.curl("https://core.telegram.org/bots/api")
html = html:match("Available methods(.+)$")
html = utils.htmlDecode(html)
local apis = {}
for method, content in html:gsub("<h4>", "<h4><h4>"):gmatch('<h4>[^\n]-</i></a>([a-z]%S-)</h4>(.-)<h4>') do
local t = {
parameters = {},
order = {}
}
setmetatable(t, {
__call = function(t, ...)
local args = {...}
local body = {}
local named = (#args == 1 and type(args[1]) == "table")
for i = 1, #t.order do
body[t.order[i]] = named and args[1][t.order[i]] or args[i]
if (t.parameters[t.order[i]].required and not body[t.order[i]]) then
logger:error("method " .. method .. " missing parameter " .. t.order[i])
return false
end
end
return api.makeRequest(method, body)
end,
__tostring = function()
return table.concat({
"[method] ", method, "\n",
"[description] ", t.description, "\n",
"[parameters] ", table.concat(t.order, ", "),
})
end
})
local description, parameter
if content:find("table") then
description, parameter = content:match('%s*(.-)%s*<table class="table">.-</tr>(.-)</table>')
else
description = content:match("^%s*(.-)%s*$")
parameter = ""
end
t.description = description:gsub("<.->", ""):gsub("\n\n", "\n")
for name, var, req, des in parameter:gmatch('<tr>%s*<td>(.-)</td>%s*<td>(.-)</td>%s*<td>(.-)</td>%s*<td>(.-)</td>%s*</tr>') do
table.insert(t.order, name)
t.parameters[name] = {
type = var:gsub("<.->", ""),
required = req == "Yes",
description = des:gsub("<.->", "")
}
end
apis[method] = t
end
return apis
end
return api
|
fix: wrong metatable function paramaeters
|
fix: wrong metatable function paramaeters
|
Lua
|
apache-2.0
|
SJoshua/Project-Small-R
|
f1c9fd4895fe107683488c501bc07d4e22f46a4f
|
spec/config_spec.lua
|
spec/config_spec.lua
|
local test_env = require("test/test_environment")
local lfs = require("lfs")
local run = test_env.run
local testing_paths = test_env.testing_paths
local env_variables = test_env.env_variables
local site_config
test_env.unload_luarocks()
describe("LuaRocks config tests #blackbox #b_config", function()
before_each(function()
test_env.setup_specs()
test_env.unload_luarocks() -- need to be required here, because site_config is created after first loading of specs
site_config = require("luarocks.site_config")
end)
describe("LuaRocks config - basic tests", function()
it("LuaRocks config with no flags/arguments", function()
assert.is_false(run.luarocks_bool("config"))
end)
it("LuaRocks config include dir", function()
local output = run.luarocks("config --lua-incdir")
if test_env.TEST_TARGET_OS == "windows" then
assert.are.same(output, site_config.LUA_INCDIR:gsub("\\","/"))
else
assert.are.same(output, site_config.LUA_INCDIR)
end
end)
it("LuaRocks config library dir", function()
local output = run.luarocks("config --lua-libdir")
if test_env.TEST_TARGET_OS == "windows" then
assert.are.same(output, site_config.LUA_LIBDIR:gsub("\\","/"))
else
assert.are.same(output, site_config.LUA_LIBDIR)
end
end)
it("LuaRocks config lua version", function()
local output = run.luarocks("config --lua-ver")
local lua_version = _VERSION:gsub("Lua ", "")
if test_env.LUAJIT_V then
lua_version = "5.1"
end
assert.are.same(output, lua_version)
end)
it("LuaRocks config rock trees", function()
assert.is_true(run.luarocks_bool("config --rock-trees"))
end)
it("LuaRocks config user config", function()
local user_config_path = run.luarocks("config --user-config")
assert.is.truthy(lfs.attributes(user_config_path))
end)
it("LuaRocks config missing user config", function()
assert.is_false(run.luarocks_bool("config --user-config", {LUAROCKS_CONFIG = "missing_file.lua"}))
end)
end)
describe("LuaRocks config - more complex tests", function()
local scdir = testing_paths.testing_lrprefix .. "/etc/luarocks"
local versioned_scname = scdir .. "/config-" .. env_variables.LUA_VERSION .. ".lua"
local scname = scdir .. "/config.lua"
local configfile
if test_env.TEST_TARGET_OS == "windows" then
configfile = versioned_scname
else
configfile = scname
end
it("LuaRocks fail system config", function()
os.rename(versioned_scname, versioned_scname .. ".bak")
assert.is_false(run.luarocks_bool("config --system-config"))
os.rename(versioned_scname .. ".bak", versioned_scname)
end)
it("LuaRocks system config", function()
lfs.mkdir(testing_paths.testing_lrprefix)
lfs.mkdir(testing_paths.testing_lrprefix .. "/etc/")
lfs.mkdir(scdir)
if test_env.TEST_TARGET_OS == "windows" then
local output = run.luarocks("config --system-config")
assert.are.same(output, versioned_scname)
else
sysconfig = io.open(scname, "w+")
sysconfig:write(" ")
sysconfig:close()
local output = run.luarocks("config --system-config")
assert.are.same(output, scname)
os.remove(scname)
end
end)
it("LuaRocks fail system config invalid", function()
lfs.mkdir(testing_paths.testing_lrprefix)
lfs.mkdir(testing_paths.testing_lrprefix .. "/etc/")
lfs.mkdir(scdir)
if test_env.TEST_TARGET_OS == "windows" then
test_env.copy(versioned_scname, "versioned_scname_temp")
sysconfig = io.open(versioned_scname, "w+")
sysconfig:write("if if if")
sysconfig:close()
assert.is_false(run.luarocks_bool("config --system-config"))
test_env.copy("versioned_scname_temp", versioned_scname)
else
sysconfig = io.open(scname, "w+")
sysconfig:write("if if if")
sysconfig:close()
assert.is_false(run.luarocks_bool("config --system-config"))
os.remove(scname)
end
end)
end)
end)
|
local test_env = require("test/test_environment")
local lfs = require("lfs")
local run = test_env.run
local testing_paths = test_env.testing_paths
local env_variables = test_env.env_variables
local site_config
test_env.unload_luarocks()
describe("LuaRocks config tests #blackbox #b_config", function()
before_each(function()
test_env.setup_specs()
test_env.unload_luarocks() -- need to be required here, because site_config is created after first loading of specs
site_config = require("luarocks.site_config")
end)
describe("LuaRocks config - basic tests", function()
it("LuaRocks config with no flags/arguments", function()
assert.is_false(run.luarocks_bool("config"))
end)
it("LuaRocks config include dir", function()
local output = run.luarocks("config --lua-incdir")
if test_env.TEST_TARGET_OS == "windows" then
assert.are.same(output, site_config.LUA_INCDIR:gsub("\\","/"))
else
assert.are.same(output, site_config.LUA_INCDIR)
end
end)
it("LuaRocks config library dir", function()
local output = run.luarocks("config --lua-libdir")
if test_env.TEST_TARGET_OS == "windows" then
assert.are.same(output, site_config.LUA_LIBDIR:gsub("\\","/"))
else
assert.are.same(output, site_config.LUA_LIBDIR)
end
end)
it("LuaRocks config lua version", function()
local output = run.luarocks("config --lua-ver")
local lua_version = _VERSION:gsub("Lua ", "")
if test_env.LUAJIT_V then
lua_version = "5.1"
end
assert.are.same(output, lua_version)
end)
it("LuaRocks config rock trees", function()
assert.is_true(run.luarocks_bool("config --rock-trees"))
end)
it("LuaRocks config user config", function()
local user_config_path = run.luarocks("config --user-config")
assert.is.truthy(lfs.attributes(user_config_path))
end)
it("LuaRocks config missing user config", function()
assert.is_false(run.luarocks_bool("config --user-config", {LUAROCKS_CONFIG = "missing_file.lua"}))
end)
end)
describe("LuaRocks config - more complex tests #special", function()
local scdir = testing_paths.testing_lrprefix .. "/etc/luarocks"
local versioned_scname = scdir .. "/config-" .. env_variables.LUA_VERSION .. ".lua"
local scname = scdir .. "/config.lua"
local configfile
if test_env.TEST_TARGET_OS == "windows" then
configfile = versioned_scname
else
configfile = scname
end
it("LuaRocks fail system config", function()
os.rename(configfile, configfile .. ".bak")
assert.is_false(run.luarocks_bool("config --system-config"))
os.rename(configfile .. ".bak", configfile)
end)
it("LuaRocks system config", function()
lfs.mkdir(testing_paths.testing_lrprefix)
lfs.mkdir(testing_paths.testing_lrprefix .. "/etc/")
lfs.mkdir(scdir)
-- if test_env.TEST_TARGET_OS == "windows" then
-- local output = run.luarocks("config --system-config")
-- assert.are.same(output, versioned_scname)
-- else
local sysconfig = io.open(configfile, "w+")
test_env.copy(configfile, "configfile_temp")
sysconfig:write(" ")
sysconfig:close()
local output = run.luarocks("config --system-config")
assert.are.same(output, configfile)
test_env.copy("configfile_temp", configfile)
os.remove("configfile_temp")
-- end
end)
it("LuaRocks fail system config invalid", function()
lfs.mkdir(testing_paths.testing_lrprefix)
lfs.mkdir(testing_paths.testing_lrprefix .. "/etc/")
lfs.mkdir(scdir)
-- if test_env.TEST_TARGET_OS == "windows" then
sysconfig = io.open(configfile, "w+")
test_env.copy(configfile, "configfile_temp")
sysconfig:write("if if if")
sysconfig:close()
assert.is_false(run.luarocks_bool("config --system-config"))
test_env.copy("configfile_temp", configfile)
os.remove("configfile_temp")
-- else
-- sysconfig = io.open(scname, "w+")
-- sysconfig:write("if if if")
-- sysconfig:close()
-- assert.is_false(run.luarocks_bool("config --system-config"))
-- os.remove(scname)
-- end
end)
end)
end)
|
Fix of config test
|
Fix of config test
|
Lua
|
mit
|
tarantool/luarocks,luarocks/luarocks,xpol/luainstaller,robooo/luarocks,xpol/luainstaller,xpol/luainstaller,keplerproject/luarocks,xpol/luavm,xpol/luavm,xpol/luainstaller,keplerproject/luarocks,xpol/luavm,robooo/luarocks,keplerproject/luarocks,xpol/luarocks,xpol/luavm,xpol/luarocks,luarocks/luarocks,tarantool/luarocks,xpol/luavm,robooo/luarocks,robooo/luarocks,tarantool/luarocks,xpol/luarocks,luarocks/luarocks,xpol/luarocks,keplerproject/luarocks
|
2f00aed95de616e2f0bb3d6ec5d845d42eb451cd
|
themes/eigengrau.lua
|
themes/eigengrau.lua
|
local view, colors, styles = view, lexer.colors, lexer.styles
-- required colors
colors.yellow = 0x66bab2 -- highlight color from editing.lua
colors.orange = 0x222222 -- highlight color from editing.lua
colors.red = 0x6161c2 -- diff lexer
colors.green = 0x81cc81 -- diff lexer
colors.base0 = 0x1d1616
colors.base1 = 0x544f4f
colors.base2 = 0x8c8484
colors.base3 = 0xc4b9b9
colors.base4 = 0xf0e1e1
colors.blue1 = 0xceb49b
colors.green1 = 0x93cc93
colors.magenta1 = 0xa680ce
colors.magenta2 = 0xce86ce
colors.orange1 = 0x6192c2
colors.red1 = 0x6161c2
colors.teal1 = 0xcece69
colors.teal2 = 0x999900
colors.yellow1 = 0x66bab2
-- Default font.
font = 'Fira Code'
size = 11
if WIN32 then
font = 'Consolas'
elseif OSX then
font = 'Monaco'
end
-- Predefined styles.
styles.default = {font = font, size = size, fore = colors.base4, back = colors.base0}
styles.line_number = {fore = colors.base2, back = colors.base0}
styles.brace_light = {fore = colors.base2, back = colors.green1, bold = true}
styles.brace_bad = {fore = colors.text0, back = colors.red1, bold = true}
styles.indent_guide = {fore = colors.base1}
styles.call_tip = {fore = colors.base4, back = colors.base0}
-- Token styles.
styles.nothing = {}
styles.class = {fore = colors.yellow1}
styles.comment = {fore = colors.base2, italics = true}
styles.constant = {fore= colors.magenta2, bold = true}
styles.error = {fore = colors.red1, italics = true, bold = true, underline = true}
styles['function'] = {fore = colors.blue1}
styles.keyword = {fore = colors.green1, bold = true}
styles.label = {fore = colors.base3}
styles.number = {fore = colors.teal2}
styles.operator = {fore = colors.base3, bold = true}
styles.regex = {fore = colors.teal1}
styles.string = {fore = colors.teal1}
styles.preprocessor = {fore = colors.magenta1}
styles.type = {fore = colors.orange1, bold = true}
styles.variable = {fore = colors.base3, italics = true}
styles.whitespace = {}
styles.embedded = {back = colors.base2}
styles.identifier = {}
-- Caret and Selection Styles.
view:set_sel_fore(true, colors.base0)
view:set_sel_back(true, colors.base2)
view.caret_fore = colors.base4
view.caret_line_back = colors.base3
view.caret_line_back_alpha = 32
-- Fold Margin.
view:set_fold_margin_color(true, colors.base1)
view:set_fold_margin_hi_color(true, colors.base1)
-- Markers.
view.marker_fore[textadept.bookmarks.MARK_BOOKMARK] = colors.base4
view.marker_back[textadept.bookmarks.MARK_BOOKMARK] = colors.dark_blue
view.marker_fore[textadept.run.MARK_WARNING] = colors.base4
view.marker_back[textadept.run.MARK_WARNING] = colors.light_yellow
view.marker_fore[textadept.run.MARK_ERROR] = colors.base4
view.marker_back[textadept.run.MARK_ERROR] = colors.light_red
for i = buffer.MARKNUM_FOLDEREND, buffer.MARKNUM_FOLDEROPEN do -- fold margin
view.marker_fore[i] = colors.base4
view.marker_back[i] = colors.base1
view.marker_back_selected[i] = colors.grey_black
end
-- Long Lines.
view.edge_color = colors.base1
view.indic_fore[ui.find.INDIC_FIND] = colors.yellow
view.indic_alpha[ui.find.INDIC_FIND] = 128
view.indic_fore[textadept.editing.INDIC_BRACEMATCH] = colors.grey
view.indic_fore[textadept.editing.INDIC_HIGHLIGHT] = colors.orange
view.indic_alpha[textadept.editing.INDIC_HIGHLIGHT] = 128
view.indic_fore[textadept.snippets.INDIC_PLACEHOLDER] = colors.grey_black
|
local view, colors, styles = view, lexer.colors, lexer.styles
-- required colors
colors.yellow = 0x66bab2 -- highlight color from editing.lua
colors.orange = 0x222222 -- highlight color from editing.lua
colors.red = 0x6161c2 -- diff lexer
colors.green = 0x81cc81 -- diff lexer
colors.base0 = 0x1d1616
colors.base1 = 0x544f4f
colors.base2 = 0x8c8484
colors.base3 = 0xc4b9b9
colors.base4 = 0xf0e1e1
colors.blue1 = 0xceb49b
colors.green1 = 0x93cc93
colors.magenta1 = 0xa680ce
colors.magenta2 = 0xce86ce
colors.orange1 = 0x6192c2
colors.red1 = 0x6161c2
colors.teal1 = 0xcece69
colors.teal2 = 0x999900
colors.yellow1 = 0x66bab2
-- Default font.
--font = 'Fira Code'
font = 'Jetbrains Mono'
size = 12
if WIN32 then
font = 'Consolas'
elseif OSX then
font = 'Monaco'
end
-- Predefined styles.
styles.default = {font = font, size = size, fore = colors.base4, back = colors.base0}
styles.line_number = {fore = colors.base2, back = colors.base0}
styles.brace_light = {fore = colors.base2, back = colors.green1, bold = true}
styles.brace_bad = {fore = colors.text0, back = colors.red1, bold = true}
styles.indent_guide = {fore = colors.base1}
styles.call_tip = {fore = colors.base4, back = colors.base0}
-- Token styles.
styles.nothing = {}
styles.class = {fore = colors.yellow1}
styles.comment = {fore = colors.base2, italics = true}
styles.constant = {fore= colors.magenta2, bold = true}
styles.error = {fore = colors.red1, italics = true, bold = true, underline = true}
styles['function'] = {fore = colors.blue1}
styles.keyword = {fore = colors.green1, bold = true}
styles.label = {fore = colors.base3}
styles.number = {fore = colors.teal2}
styles.operator = {fore = colors.base3, bold = true}
styles.regex = {fore = colors.teal1}
styles.string = {fore = colors.teal1}
styles.preprocessor = {fore = colors.magenta1}
styles.type = {fore = colors.orange1, bold = true}
styles.variable = {fore = colors.base3, italics = true}
styles.whitespace = {}
styles.embedded = {back = colors.base2}
styles.identifier = {}
-- Caret and Selection Styles.
view:set_sel_fore(true, colors.base0)
view:set_sel_back(true, colors.base2)
view.caret_fore = colors.base4
view.caret_line_back = colors.base3
view.caret_line_back_alpha = 32
-- Fold Margin.
view:set_fold_margin_color(true, colors.base1)
view:set_fold_margin_hi_color(true, colors.base1)
-- Markers.
view.marker_fore[textadept.bookmarks.MARK_BOOKMARK] = colors.base4
view.marker_back[textadept.bookmarks.MARK_BOOKMARK] = colors.blue1
view.marker_fore[textadept.run.MARK_WARNING] = colors.base4
view.marker_back[textadept.run.MARK_WARNING] = colors.yellow1
view.marker_fore[textadept.run.MARK_ERROR] = colors.base4
view.marker_back[textadept.run.MARK_ERROR] = colors.red1
for i = buffer.MARKNUM_FOLDEREND, buffer.MARKNUM_FOLDEROPEN do -- fold margin
view.marker_fore[i] = colors.base4
view.marker_back[i] = colors.base1
view.marker_back_selected[i] = colors.base2
end
-- Long Lines.
view.edge_color = colors.base1
view.indic_fore[ui.find.INDIC_FIND] = colors.yellow
view.indic_alpha[ui.find.INDIC_FIND] = 128
view.indic_fore[textadept.editing.INDIC_BRACEMATCH] = colors.base2
view.indic_fore[textadept.editing.INDIC_HIGHLIGHT] = colors.orange
view.indic_alpha[textadept.editing.INDIC_HIGHLIGHT] = 128
view.indic_fore[textadept.snippets.INDIC_PLACEHOLDER] = colors.base2
|
Fix refrences to colors that were not defined
|
Fix refrences to colors that were not defined
|
Lua
|
mit
|
Hackerpilot/TextadeptModules
|
5816ba68bdd9875844c045872c41954be877fdeb
|
src/ui/MainMenuView.lua
|
src/ui/MainMenuView.lua
|
local class = require 'lib/30log'
local GameObject = require 'src/GameObject'
local Transform = require 'src/component/Transform'
local Renderable = require 'src/component/Renderable'
local Interfaceable = require 'src/component/Interfaceable'
local Polygon = require 'src/datatype/Polygon'
local TouchDelegate = require 'src/datatype/TouchDelegate'
local MainMenuView = class("MainMenuView", {
root = nil,
is_attached = false,
scenegraph = nil
})
function MainMenuView:init (registry, scenegraph)
self.root = registry:add(GameObject:new("mmv_root", {
Transform:new(0,0)
}))
self.scenegraph = scenegraph
self.registry = registry
local save_button_handler = TouchDelegate:new()
save_button_handler:setHandler('onTouch', function(this, x, y)
print('Button pressed: save')
end)
local load_button_handler = TouchDelegate:new()
load_button_handler:setHandler('onTouch', function(this, x, y)
print('Button pressed: load. Loading disabled for the moment')
self:hide()
end)
local return_button_handler = TouchDelegate:new()
return_button_handler:setHandler('onTouch', function(this, x, y)
self.scenegraph:detach(self.root)
self.is_attached = false
print('Button pressed: return')
end)
local quit_button_handler = TouchDelegate:new()
quit_button_handler:setHandler('onTouch', function(this, x, y)
love.event.quit()
end)
local switch_next_handler = TouchDelegate:new()
switch_next_handler:setHandler('onTouch', function(this, x, y)
registry:publish("ui/debug_nextscene")
self:hide()
end)
local switch_prev_handler = TouchDelegate:new()
switch_prev_handler:setHandler('onTouch', function(this, x, y)
registry:publish("ui/debug_prevscene")
self:hide()
end)
local Block_Below_Delegate = TouchDelegate:new()
Block_Below_Delegate:setHandler('onTouch', function(this, x, y)
print('Blocking event')
return true
end)
local windowW = love.graphics:getWidth()
local windowH = love.graphics:getHeight()
local gray_out = registry:add(GameObject:new("mmv_grayout", {
Transform:new(0,0),
Renderable:new(
Polygon:new({w = windowW, h = windowH}),
nil,
{0,0,0,128},
math.floor(math.random()*100000)),
Interfaceable:new(
Polygon:new({w = windowW, h = windowH}),
Block_Below_Delegate)
}))
local panelW = 400
local panelH = 600
local panelX = ( windowW - panelW ) / 2
local panelY = ( windowH - panelH ) / 2
local margin = 10
local bg_rect = registry:add(GameObject:new("mmv_bgrect", {
Transform:new(panelX,panelY),
Renderable:new(
Polygon:new({w = panelW, h = panelH}),
nil,
{128, 60, 128})
}))
local subPanelW = panelW - 2 * margin
local buttonW = subPanelW - 2 * margin
local titleH = 40
local title_panel = registry:add(GameObject:new("mmv_title",{
Transform:new(margin,margin),
Renderable:new(
Polygon:new({w = subPanelW, h = titleH}),
nil,
{200,100,200},
"HELIOS 2400 DEBUG MENU")
}))
local saveLoadY = titleH + 2 * margin
local buttonH = 30
local bigMargin = 40
local saveLoadH = buttonH * 4 + margin * 4 + bigMargin
local saveload_panel = registry:add(GameObject:new("mmv_saveloadpanel",{
Transform:new(margin,saveLoadY),
Renderable:new(
Polygon:new({w = subPanelW, h = saveLoadH}),
nil,
{200,100,200})
}))
local save_btn = registry:add(GameObject:new("mmv_save_btn",{
Transform:new(margin, margin),
Renderable:new(
Polygon:new({w = buttonW, h = buttonH}),
nil,
{150,100,180},
"Save Game"),
Interfaceable:new(
Polygon:new({w = buttonW, h = buttonH}),
save_button_handler)
}))
local load_btn = registry:add(GameObject:new("mmv_load_btn",{
Transform:new(margin, margin + buttonH + margin),
Renderable:new(
Polygon:new({w = buttonW, h = buttonH}),
nil,
{150,100,180},
"Load Game"),
Interfaceable:new(
Polygon:new({w = buttonW, h = buttonH}),
load_button_handler)
}))
local quit_btn = registry:add(GameObject:new("mmv_quit_btn",{
Transform:new(margin , margin + (buttonH + margin) * 2),
Renderable:new(
Polygon:new({w = buttonW, h = buttonH}),
nil,
{150,100,180},
"Quit Game"),
Interfaceable:new(
Polygon:new({w = buttonW, h = buttonH}),
quit_button_handler)
}))
local return_btn = registry:add(GameObject:new("mmv_return_btn",{
Transform:new(margin , margin + buttonH * 3 + margin * 2 + bigMargin),
Renderable:new(
Polygon:new({w = buttonW, h = buttonH}),
nil,
{150,100,180},
"Return (or press Escape)"),
Interfaceable:new(
Polygon:new({w = buttonW, h = buttonH}),
return_button_handler)
}))
local view_switcher_panelH = buttonH + 2 * margin
local view_switcher_panelY = saveLoadY + saveLoadH + margin
local view_switcher_panel = registry:add(GameObject:new("mmv_switcher_panel",{
Transform:new(margin,view_switcher_panelY),
Renderable:new(
Polygon:new({w = subPanelW, h = view_switcher_panelH}),
nil,
{200,100,200},
nil)
}))
local switch_prev_btn = registry:add(GameObject:new("mmv_switchprev_btn",{
Transform:new(10,10),
Renderable:new(
Polygon:new({0,15 , 30,-5 , 30,0 , 135,0 , 135,30 , 30,30 , 30,35}),
nil,
{150,100,180},
"Previous View"),
Interfaceable:new(
Polygon:new({0,15 , 30,-5 , 30,0 , 135,0 , 135,30 , 30,30 , 30,35}),
switch_prev_handler)
}))
local switch_next_btn = registry:add(GameObject:new("mmv_switchnext_btn",{
Transform:new(155,10),
Renderable:new(
Polygon:new({0,0 , 105,0 , 105,-5 , 135,15 , 105,35 , 105,30 , 0,30}),
nil,
{150,100,180},
"Next View"),
Interfaceable:new(
Polygon:new({0,0 , 105,0 , 105,-5 , 135,15 , 105,35 , 105,30 , 0,30}),
switch_next_handler)
}))
self.scenegraph:attach(self.root, nil)
self.scenegraph:attachAll({gray_out, bg_rect}, self.root)
self.scenegraph:attachAll({title_panel, saveload_panel, view_switcher_panel}, bg_rect)
self.scenegraph:attachAll({save_btn, load_btn, return_btn, quit_btn}, saveload_panel)
self.scenegraph:attachAll({switch_next_btn, switch_prev_btn}, view_switcher_panel)
self.scenegraph:detach(self.root)
end
function MainMenuView:show( attachTo )
if not self.is_attached then
self.scenegraph:attach(self.root, attachTo)
self.is_attached = true
end
end
function MainMenuView:hide()
if self.is_attached then
self.scenegraph:detach(self.root)
self.is_attached = false
end
end
return MainMenuView
|
local class = require 'lib/30log'
local GameObject = require 'src/GameObject'
local Transform = require 'src/component/Transform'
local Renderable = require 'src/component/Renderable'
local Interfaceable = require 'src/component/Interfaceable'
local Polygon = require 'src/datatype/Polygon'
local TouchDelegate = require 'src/datatype/TouchDelegate'
local MainMenuView = class("MainMenuView", {
root = nil,
is_attached = false,
scenegraph = nil
})
function MainMenuView:init (registry, scenegraph)
self.root = registry:add(GameObject:new("mmv_root", {
Transform:new(0,0)
}))
self.scenegraph = scenegraph
self.registry = registry
local save_button_handler = TouchDelegate:new()
save_button_handler:setHandler('onTouch', function(this, x, y)
print('Button pressed: save')
end)
local load_button_handler = TouchDelegate:new()
load_button_handler:setHandler('onTouch', function(this, x, y)
print('Button pressed: load. Loading disabled for the moment')
self:hide()
end)
local return_button_handler = TouchDelegate:new()
return_button_handler:setHandler('onTouch', function(this, x, y)
self.scenegraph:detach(self.root)
self.is_attached = false
print('Button pressed: return')
end)
local quit_button_handler = TouchDelegate:new()
quit_button_handler:setHandler('onTouch', function(this, x, y)
love.event.quit()
end)
local switch_next_handler = TouchDelegate:new()
switch_next_handler:setHandler('onTouch', function(this, x, y)
registry:publish("ui/debug_nextscene")
self:hide()
end)
local switch_prev_handler = TouchDelegate:new()
switch_prev_handler:setHandler('onTouch', function(this, x, y)
registry:publish("ui/debug_prevscene")
self:hide()
end)
local Block_Below_Delegate = TouchDelegate:new()
Block_Below_Delegate:setHandler('onTouch', function(this, x, y)
print('Blocking event')
return true
end)
local windowW = love.graphics:getWidth()
local windowH = love.graphics:getHeight()
local gray_out = registry:add(GameObject:new("mmv_grayout", {
Transform:new(0,0),
Renderable:new(
Polygon:new({w = windowW, h = windowH}),
nil,
{0,0,0,128},
math.floor(math.random()*100000)),
Interfaceable:new(
Polygon:new({w = windowW, h = windowH}),
Block_Below_Delegate)
}))
local panelW = 400
local panelH = 600
local panelX = ( windowW - panelW ) / 2
local panelY = ( windowH - panelH ) / 2
local margin = 10
local bg_rect = registry:add(GameObject:new("mmv_bgrect", {
Transform:new(panelX,panelY),
Renderable:new(
Polygon:new({w = panelW, h = panelH}),
nil,
{128, 60, 128})
}))
local subPanelW = panelW - 2 * margin
local buttonW = subPanelW - 2 * margin
local titleH = 40
local title_panel = registry:add(GameObject:new("mmv_title",{
Transform:new(margin,margin),
Renderable:new(
Polygon:new({w = subPanelW, h = titleH}),
nil,
{200,100,200},
"HELIOS 2400 DEBUG MENU")
}))
local saveLoadY = titleH + 2 * margin
local buttonH = 30
local bigMargin = 40
local saveLoadH = buttonH * 4 + margin * 4 + bigMargin
local saveload_panel = registry:add(GameObject:new("mmv_saveloadpanel",{
Transform:new(margin,saveLoadY),
Renderable:new(
Polygon:new({w = subPanelW, h = saveLoadH}),
nil,
{200,100,200})
}))
local save_btn = registry:add(GameObject:new("mmv_save_btn",{
Transform:new(margin, margin),
Renderable:new(
Polygon:new({w = buttonW, h = buttonH}),
nil,
{150,100,180},
"Save Game"),
Interfaceable:new(
Polygon:new({w = buttonW, h = buttonH}),
save_button_handler)
}))
local load_btn = registry:add(GameObject:new("mmv_load_btn",{
Transform:new(margin, margin + buttonH + margin),
Renderable:new(
Polygon:new({w = buttonW, h = buttonH}),
nil,
{150,100,180},
"Load Game"),
Interfaceable:new(
Polygon:new({w = buttonW, h = buttonH}),
load_button_handler)
}))
local quit_btn = registry:add(GameObject:new("mmv_quit_btn",{
Transform:new(margin , margin + (buttonH + margin) * 2),
Renderable:new(
Polygon:new({w = buttonW, h = buttonH}),
nil,
{150,100,180},
"Quit Game"),
Interfaceable:new(
Polygon:new({w = buttonW, h = buttonH}),
quit_button_handler)
}))
local return_btn = registry:add(GameObject:new("mmv_return_btn",{
Transform:new(margin , margin + buttonH * 3 + margin * 2 + bigMargin),
Renderable:new(
Polygon:new({w = buttonW, h = buttonH}),
nil,
{150,100,180},
"Return (or press Escape)"),
Interfaceable:new(
Polygon:new({w = buttonW, h = buttonH}),
return_button_handler)
}))
local switchButtonH = 60
local view_switcher_panelH = switchButtonH + 2 * margin
local view_switcher_panelY = saveLoadY + saveLoadH + margin
local view_switcher_panel = registry:add(GameObject:new("mmv_switcher_panel",{
Transform:new(margin,view_switcher_panelY),
Renderable:new(
Polygon:new({w = subPanelW, h = view_switcher_panelH}),
nil,
{200,100,200},
nil)
}))
local switchButtonW = (subPanelW - margin) / 2
local AHO = switchButtonH/4
local AHW = switchButtonW/4
local switch_prev_btn = registry:add(GameObject:new("mmv_switchprev_btn",{
Transform:new(margin,margin),
Renderable:new(
Polygon:new({
0,switchButtonH/2,
AHW,0,
AHW,AHO,
switchButtonW,AHO,
switchButtonW,switchButtonH-AHO,
AHW,switchButtonH-AHO,
AHW,switchButtonH}
),
nil,
{150,100,180},
"Previous View"),
Interfaceable:new(
Polygon:new({0,15 , 30,-5 , 30,0 , 135,0 , 135,30 , 30,30 , 30,35}),
switch_prev_handler)
}))
local switch_next_btn = registry:add(GameObject:new("mmv_switchnext_btn",{
Transform:new(2 * margin + switchButtonW,margin),
Renderable:new(
Polygon:new({0,0 , 105,0 , 105,-5 , 135,15 , 105,35 , 105,30 , 0,30}),
nil,
{150,100,180},
"Next View"),
Interfaceable:new(
Polygon:new({0,0 , 105,0 , 105,-5 , 135,15 , 105,35 , 105,30 , 0,30}),
switch_next_handler)
}))
self.scenegraph:attach(self.root, nil)
self.scenegraph:attachAll({gray_out, bg_rect}, self.root)
self.scenegraph:attachAll({title_panel, saveload_panel, view_switcher_panel}, bg_rect)
self.scenegraph:attachAll({save_btn, load_btn, return_btn, quit_btn}, saveload_panel)
self.scenegraph:attachAll({switch_next_btn, switch_prev_btn}, view_switcher_panel)
self.scenegraph:detach(self.root)
end
function MainMenuView:show( attachTo )
if not self.is_attached then
self.scenegraph:attach(self.root, attachTo)
self.is_attached = true
end
end
function MainMenuView:hide()
if self.is_attached then
self.scenegraph:detach(self.root)
self.is_attached = false
end
end
return MainMenuView
|
fixed scaling on left arrow
|
fixed scaling on left arrow
|
Lua
|
mit
|
Sewerbird/Helios2400,Sewerbird/Helios2400,Sewerbird/Helios2400
|
5be3c72a23c3236f30ee17aa5c6aeb24cdf09a8f
|
premake5.lua
|
premake5.lua
|
newoption {
trigger = "inst_prefix",
value = "PATH",
description = "[inst_prefix]/(bin or include or lib)"
}
local instPrefix = _OPTIONS["inst_prefix"] or ""
--[[
newoption {
trigger = "inst_bin_suffix",
value = "PATH",
description = "/bin[inst_bin_suffix]"
}
local instBinSuffix = _OPTIONS["inst_bin_suffix"] or ""
]]
newoption {
trigger = "inst_inc_suffix",
value = "PATH",
description = "/include[inst_inc_suffix]"
}
local instIncSuffix = _OPTIONS["inst_inc_suffix"] or ""
newoption {
trigger = "inst_lib_suffix",
value = "PATH",
description = "/lib[inst_lib_suffix]"
}
local instLibSuffix = _OPTIONS["inst_lib_suffix"] or ""
newaction {
trigger = "install",
description = "Install files.",
execute = function ()
if instPrefix == "" then
if os.is("windows") then
MSYSTEM = os.getenv("MSYSTEM")
if MSYSTEM == "MINGW32" then
instPrefix = "/mingw32"
elseif MSYSTEM == "MINGW64" then
instPrefix = "/mingw64"
end
else
instPrefix = "/usr/local"
end
end
--cp_file("bin/*", "/bin" .. instBinSuffix)
cp_file("include/*.h", "/include" .. instIncSuffix)
cp_file("lib/*.a", "/lib" .. instLibSuffix)
end
}
function cp_file (file, dest)
local fs = os.matchfiles(file)
if #fs > 0 then
os.execute("sh -c \"cp -fvu " .. file .. " '" .. instPrefix .. dest .."/'\"")
end
end
---------------------------------------------------------------------------
workspace "UBWindow"
location ( "build" )
configurations { "Debug", "Release" }
platforms {"native", "x64", "x32"}
project "ubwindow"
language "C"
includedirs { "src", "include" }
files { "src/*.c" }
kind "StaticLib"
targetdir("lib")
configuration {"windows", "gmake" }
targetprefix "lib"
targetextension ".a"
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols", "ExtraWarnings"}
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize", "ExtraWarnings"}
project "demo_blank"
language "C"
includedirs { "include" }
libdirs { "lib" }
files { "demo/blank.c" }
targetdir("bin")
configuration "windows"
kind "WindowedApp"
links { "ubwindow" }
--[[configuration "macosx"
kind "WindowedApp"
links { "ubwindow" }
linkoptions { "-framework Cocoa" }]]
configuration "linux"
kind "ConsoleApp"
links { "ubwindow", "X11" }
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols", "ExtraWarnings"}
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize", "ExtraWarnings"}
|
newoption {
trigger = "inst_prefix",
value = "PATH",
description = "[inst_prefix]/(bin or include or lib)"
}
local instPrefix = _OPTIONS["inst_prefix"] or ""
--[[
newoption {
trigger = "inst_bin_suffix",
value = "PATH",
description = "/bin[inst_bin_suffix]"
}
local instBinSuffix = _OPTIONS["inst_bin_suffix"] or ""
]]
newoption {
trigger = "inst_inc_suffix",
value = "PATH",
description = "/include[inst_inc_suffix]"
}
local instIncSuffix = _OPTIONS["inst_inc_suffix"] or ""
newoption {
trigger = "inst_lib_suffix",
value = "PATH",
description = "/lib[inst_lib_suffix]"
}
local instLibSuffix = _OPTIONS["inst_lib_suffix"] or ""
newaction {
trigger = "install",
description = "Install files.",
execute = function ()
if instPrefix == "" then
if os.is("windows") then
MSYSTEM = os.getenv("MSYSTEM")
if MSYSTEM == "MINGW32" then
instPrefix = "/mingw32"
elseif MSYSTEM == "MINGW64" then
instPrefix = "/mingw64"
end
else
instPrefix = "/usr/local"
end
end
--cp_file("bin/*", "/bin" .. instBinSuffix)
cp_file("include/*.h", "/include" .. instIncSuffix)
cp_file("lib/*.a", "/lib" .. instLibSuffix)
end
}
function cp_file (file, dest)
local fs = os.matchfiles(file)
if #fs > 0 then
os.execute("sh -c \"cp -fvu " .. file .. " '" .. instPrefix .. dest .."/'\"")
end
end
---------------------------------------------------------------------------
workspace "UBWindow"
location ( "build" )
configurations { "Debug", "Release" }
platforms {"native", "x64", "x32"}
project "ubwindow"
language "C"
includedirs { "src", "include" }
files { "src/*.c" }
kind "StaticLib"
targetdir("lib")
warnings "Extra"
configuration {"windows", "gmake" }
targetprefix "lib"
targetextension ".a"
configuration "Debug"
defines { "DEBUG" }
--symbols "On"
flags { "Symbols" }
configuration "Release"
defines { "NDEBUG" }
optimize "Speed"
project "demo_blank"
language "C"
includedirs { "include" }
libdirs { "lib" }
files { "demo/blank.c" }
targetdir("bin")
warnings "Extra"
configuration "windows"
kind "WindowedApp"
links { "ubwindow" }
--[[configuration "macosx"
kind "WindowedApp"
links { "ubwindow" }
linkoptions { "-framework Cocoa" }]]
configuration "linux"
kind "ConsoleApp"
links { "ubwindow", "X11" }
configuration "Debug"
defines { "DEBUG" }
--symbols "On"
flags { "Symbols" }
configuration "Release"
defines { "NDEBUG" }
optimize "Speed"
|
Fixed premake5.lua
|
Fixed premake5.lua
|
Lua
|
mit
|
yulon/pwre
|
4a91d8f19403e54a151bfa9706c05534e84c70fc
|
premake5.lua
|
premake5.lua
|
workspace "Cerberus"
configurations { "Debug", "Release" }
filter "language:C++"
buildoptions "-std=c++11"
project "Cerberus"
kind "ConsoleApp"
language "C++"
targetdir "bin/%{cfg.buildcfg}"
files { "*.h", "*.c", "*.cpp" }
includedirs { "Utils", "Engine" }
links { "Engine", "Utils" }
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
project "Engine"
kind "StaticLib"
language "C++"
files { "Engine/**.h", "Engine/**.c", "Engine/**.cpp" }
includedirs { "Utils", "C:/VulkanSDK/1.0.46.0/Include" }
libdirs { os.findlib("Vulkan") }
links { "Utils" }
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
project "Utils"
kind "StaticLib"
language "C++"
files { "Utils/**.h", "Utils/**.c", "Utils/**.cpp" }
includedirs { "thirdparty" }
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
|
workspace "Cerberus"
configurations { "Debug", "Release" }
filter "language:C++"
buildoptions "-std=c++11"
targetdir "bin/%{cfg.buildcfg}"
project "Cerberus"
kind "ConsoleApp"
language "C++"
files { "*.h", "*.c", "*.cpp" }
includedirs { "Utils", "Engine" }
libdirs { "$(VK_SDK_PATH)/Lib" }
links { "Engine", "Utils", "SDL2", "SDL2main" }
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
project "Engine"
kind "StaticLib"
language "C++"
files { "Engine/**.h", "Engine/**.c", "Engine/**.cpp" }
includedirs { "Utils", "$(VK_SDK_PATH)/Include" }
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
project "Utils"
kind "StaticLib"
language "C++"
files { "Utils/**.h", "Utils/**.c", "Utils/**.cpp" }
includedirs { "thirdparty" }
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
|
Fixed premake file so it can compile the project
|
Fixed premake file so it can compile the project
|
Lua
|
mit
|
ebithril/Cerberus,ebithril/Cerberus
|
30e498b39bb7cb6a01b8ddfc7a00006093f9ff43
|
dotfiles/config/nvim/lua/colorscheme.lua
|
dotfiles/config/nvim/lua/colorscheme.lua
|
vim.g["nightflyUnderlineMatchParen"] = 1
vim.cmd("colorscheme nightfly")
vim.api.nvim_set_hl(0, "CustomModifiedFlag", {bg = "Red", fg = "White"})
vim.api.nvim_set_hl(0, "Pmenu", {fg = 0, bg = 13, fg = "fg", bg = "#1d3b53"})
-- For focused windows, use the "default" background color (from tmux). This
-- means the current Vim window will be highlighted only if the tmux pane that
-- vim is running in is also currently active.
vim.api.nvim_set_hl(0, "Normal", {fg = "fg", bg = "NONE"})
-- Unfocused background color duplicated in tmux config
vim.api.nvim_set_hl(0, "NormalNC", {bg = "#000a13"})
|
vim.g["nightflyUnderlineMatchParen"] = 1
vim.cmd("colorscheme nightfly")
vim.api.nvim_set_hl(0, "CustomModifiedFlag", {bg = "Red", fg = "White"})
vim.api.nvim_set_hl(0, "Pmenu", {bg = "#1d3b53"})
-- For focused windows, use the "default" background color (from tmux). This
-- means the current Vim window will be highlighted only if the tmux pane that
-- vim is running in is also currently active.
vim.api.nvim_set_hl(0, "Normal", {bg = "NONE"})
-- Unfocused background color duplicated in tmux config
vim.api.nvim_set_hl(0, "NormalNC", {bg = "#000a13"})
|
Fix duplicate key in colorscheme
|
Fix duplicate key in colorscheme
|
Lua
|
mit
|
davidxmoody/dotfiles,davidxmoody/dotfiles,davidxmoody/dotfiles,davidxmoody/dotfiles
|
02de943b727ae3101f42cb96f91c013af85c6b51
|
mod_statistics/prosodytop.lua
|
mod_statistics/prosodytop.lua
|
local curses = require "curses";
local server = require "net.server_select";
local timer = require "util.timer";
assert(curses.timeout, "Incorrect version of curses library. Try 'sudo luarocks install luaposix'");
local top = require "top";
function main()
local stdscr = curses.stdscr() -- it's a userdatum
--stdscr:clear();
local view = top.new({
stdscr = stdscr;
prosody = { up_since = os.time() };
conn_list = {};
});
timer.add_task(0.01, function ()
local ch = stdscr:getch();
if ch then
if stdscr:getch() == 410 then
view:resized();
else
curses.ungetch(ch);
end
end
return 0.2;
end);
timer.add_task(0, function ()
view:draw();
return 1;
end);
--[[
posix.signal(28, function ()
table.insert(view.conn_list, { jid = "WINCH" });
--view:draw();
end);
]]
-- Fake socket object around stdin
local stdin = {
getfd = function () return 0; end;
dirty = function (self) return false; end;
settimeout = function () end;
send = function (_, d) return #d, 0; end;
close = function () end;
receive = function (_, patt)
local ch = stdscr:getch();
if ch >= 0 and ch <=255 then
return string.char(ch);
elseif ch == 410 then
view:resized();
else
table.insert(view.conn_list, { jid = tostring(ch) }); --FIXME
end
return "";
end
};
local function on_incoming(stdin, text)
-- TODO: Handle keypresses
if text:lower() == "q" then os.exit(); end
end
stdin = server.wrapclient(stdin, "stdin", 0, {
onincoming = on_incoming, ondisconnect = function () end
}, "*a");
local function handle_line(line)
local e = {
STAT = function (name) return function (value)
view:update_stat(name, value);
end end;
SESS = function (id) return function (jid) return function (stats)
view:update_session(id, jid, stats);
end end end;
};
local chunk = assert(loadstring(line));
setfenv(chunk, e);
chunk();
end
local stats_listener = {};
function stats_listener.onconnect(conn)
--stdscr:mvaddstr(6, 0, "CONNECTED");
end
local partial;
function stats_listener.onincoming(conn, data)
--print("DATA", data)
if partial then
partial, data = nil, partial..data;
end
if not data:match("\n") then
partial = data;
return;
end
local lastpos = 1;
for line, pos in data:gmatch("([^\n]+)\n()") do
lastpos = pos;
handle_line(line);
end
if lastpos == #data then
partial = nil;
else
partial = data:sub(lastpos);
end
end
function stats_listener.ondisconnect(conn, err)
stdscr:mvaddstr(6, 0, "DISCONNECTED: "..(err or "unknown"));
end
local conn = require "socket".tcp();
assert(conn:connect("localhost", 5782));
handler = server.wrapclient(conn, "localhost", 5279, stats_listener, "*a");
end
return {
run = function ()
--os.setlocale("UTF-8", "all")
curses.initscr()
curses.cbreak()
curses.echo(false) -- not noecho !
curses.nl(false) -- not nonl !
curses.timeout(0);
local ok, err = pcall(main);
--while true do stdscr:getch() end
--stdscr:endwin()
if ok then
ok, err = xpcall(server.loop, debug.traceback);
end
curses.endwin();
--stdscr:refresh();
if not ok then
print(err);
end
print"DONE"
end;
};
|
local curses = require "curses";
local server = require "net.server_select";
local timer = require "util.timer";
assert(curses.timeout, "Incorrect version of curses library. Try 'sudo luarocks install luaposix'");
local top = require "top";
function main()
local stdscr = curses.stdscr() -- it's a userdatum
--stdscr:clear();
local view = top.new({
stdscr = stdscr;
prosody = { up_since = os.time() };
conn_list = {};
});
timer.add_task(0.01, function ()
local ch = stdscr:getch();
if ch then
if stdscr:getch() == 410 then
view:resized();
else
curses.ungetch(ch);
end
end
return 0.2;
end);
timer.add_task(0, function ()
view:draw();
return 1;
end);
--[[
posix.signal(28, function ()
table.insert(view.conn_list, { jid = "WINCH" });
--view:draw();
end);
]]
-- Fake socket object around stdin
local stdin = {
getfd = function () return 0; end;
dirty = function (self) return false; end;
settimeout = function () end;
send = function (_, d) return #d, 0; end;
close = function () end;
receive = function (_, patt)
local ch = stdscr:getch();
if ch >= 0 and ch <=255 then
return string.char(ch);
elseif ch == 410 then
view:resized();
else
table.insert(view.conn_list, { jid = tostring(ch) }); --FIXME
end
return "";
end
};
local function on_incoming(stdin, text)
-- TODO: Handle keypresses
if text:lower() == "q" then os.exit(); end
end
stdin = server.wrapclient(stdin, "stdin", 0, {
onincoming = on_incoming, ondisconnect = function () end
}, "*a");
local function handle_line(line)
local e = {
STAT = function (name) return function (value)
view:update_stat(name, value);
end end;
SESS = function (id) return function (jid) return function (stats)
view:update_session(id, jid, stats);
end end end;
};
local chunk = assert(loadstring(line));
setfenv(chunk, e);
chunk();
end
local stats_listener = {};
function stats_listener.onconnect(conn)
--stdscr:mvaddstr(6, 0, "CONNECTED");
end
local partial = "";
function stats_listener.onincoming(conn, data)
--print("DATA", data)
data = partial..data;
local lastpos = 1;
for line, pos in data:gmatch("([^\n]+)\n()") do
lastpos = pos;
handle_line(line);
end
partial = data:sub(lastpos);
end
function stats_listener.ondisconnect(conn, err)
stdscr:mvaddstr(6, 0, "DISCONNECTED: "..(err or "unknown"));
end
local conn = require "socket".tcp();
assert(conn:connect("localhost", 5782));
handler = server.wrapclient(conn, "localhost", 5279, stats_listener, "*a");
end
return {
run = function ()
--os.setlocale("UTF-8", "all")
curses.initscr()
curses.cbreak()
curses.echo(false) -- not noecho !
curses.nl(false) -- not nonl !
curses.timeout(0);
local ok, err = pcall(main);
--while true do stdscr:getch() end
--stdscr:endwin()
if ok then
ok, err = xpcall(server.loop, debug.traceback);
end
curses.endwin();
--stdscr:refresh();
if not ok then
print(err);
end
print"DONE"
end;
};
|
mod_statistics/prosodytop.lua: Simplify and fix buffering and line separation (thanks Ge0rG)
|
mod_statistics/prosodytop.lua: Simplify and fix buffering and line separation (thanks Ge0rG)
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
6f2569306ce83afd36b7d6f95b4342f50015e344
|
shared/cm/config.lua
|
shared/cm/config.lua
|
-- This is a partly implemented next step in the channel manager to
-- make an object which can load and save a configuration file so that
-- we don't need to edit the source code of the channel manager to show
-- the configuration directory.
-- We're using some fancy parts of Lua called metatables which give us
-- the hooks to do object orientated programming in Lua.
if not cm then cm = {} end
if not cm.config then cm.config = {} end
local function ConfigName()
return iguana.workingDir()..'/IguanaRepo.cfg'
end
local function DefaultRepoLocation()
if os.isWindows() then
return "C:/iguana-web-apps/"
else
return "~/iguana-web-apps/"
end
end
local function ConfigDefault()
return {repo={DefaultRepoLocation()}}
end
local method = {}
local meta={__index=method}
local function ConvertOldFormat(S)
if(S.config.repo)then
for i=1, #S.config.repo do
local Temp = {}
Temp.Name = "Repository "..i
Temp.Dir = os.fs.name.toNative(S.config.repo[i])
S.config.locations[#S.config.locations +1] = Temp
end
S.config.repo = nil
end
return S
end
function method.load(S)
local Name = ConfigName()
if not os.fs.access(Name) then
S.config = ConfigDefault()
return
end
local Json = os.fs.readFile(Name)
if #Json == 0 then
S.config = ConfigDefault();
return
end
S.config = json.parse{data=Json}
if not S.config.locations then
S.config.locations = {}
end
ConvertOldFormat(S)
end
function method.addRepo(S, Name, Path)
S.config.repo[#S.config.locations+1] = {name=Name, path=Path}
end
function method.save(S)
local Content = json.serialize{data=S.config}
os.fs.writeFile(ConfigName(), Content)
end
function method.clear(S)
S.config.locations = {}
end
function method.repoList(S)
return S.config.locations
end
function cm.config.open()
local T = {}
setmetatable(T, meta)
T:load()
return T
end
|
-- This is a partly implemented next step in the channel manager to
-- make an object which can load and save a configuration file so that
-- we don't need to edit the source code of the channel manager to show
-- the configuration directory.
-- We're using some fancy parts of Lua called metatables which give us
-- the hooks to do object orientated programming in Lua.
if not cm then cm = {} end
if not cm.config then cm.config = {} end
local function ConfigName()
return iguana.workingDir()..'/IguanaRepo.cfg'
end
local function DefaultRepoLocation()
if os.isWindows() then
return {Name="default", Dir="C:/iguana-web-apps/"}
else
return {Name="default", Dir="~/iguana-web-apps/"}
end
end
local function ConfigDefault()
return {locations={DefaultRepoLocation()}}
end
local method = {}
local meta={__index=method}
local function ConvertOldFormat(S)
if(S.config.repo)then
for i=1, #S.config.repo do
local Temp = {}
Temp.Name = "Repository "..i
Temp.Dir = os.fs.name.toNative(S.config.repo[i])
S.config.locations[#S.config.locations +1] = Temp
end
S.config.repo = nil
end
return S
end
function method.load(S)
local Name = ConfigName()
if not os.fs.access(Name) then
S.config = ConfigDefault()
return
end
local Json = os.fs.readFile(Name)
if #Json == 0 then
S.config = ConfigDefault();
return
end
S.config = json.parse{data=Json}
if not S.config.locations then
S.config.locations = {}
end
ConvertOldFormat(S)
end
function method.addRepo(S, Name, Path)
S.config.locations[#S.config.locations+1] = {name=Name, path=Path}
end
function method.save(S)
local Content = json.serialize{data=S.config}
os.fs.writeFile(ConfigName(), Content)
end
function method.clear(S)
S.config.locations = {}
end
function method.repoList(S)
return S.config.locations
end
function cm.config.open()
local T = {}
setmetatable(T, meta)
T:load()
return T
end
|
Fix by Wade to when the config file does not exist.
|
Fix by Wade to when the config file does not exist.
|
Lua
|
mit
|
interfaceware/iguana-web-apps,interfaceware/iguana-web-apps
|
c8b7fd521845d4082985c4a8a38bbaf23b497f6c
|
examples/graphics/bmfont-graphic-design/DisplayBmtext.lua
|
examples/graphics/bmfont-graphic-design/DisplayBmtext.lua
|
local DisplayObject = DisplayObject
local DisplayImage = DisplayImage
local Image = Image
local Xfs = Xfs
local M = Class(DisplayObject)
local function startsWith(str1, str2)
return str1:sub(1, #str2) == str2
end
local function lineToTable(line)
local result = {}
for pair in line:gmatch("%a+=[-%d]+") do
local key = pair:match("%a+")
local value = pair:match("[-%d]+")
result[key] = tonumber(value)
end
return result
end
function M:init(fontpng, fonttxt, text)
self.super:init()
self.image = Image.new(fontpng)
self.chars = {}
local file = Xfs.open(fonttxt, "r")
for line in file:lines() do
if startsWith(line, "char ") then
local c = lineToTable(line)
self.chars[c.id] = c
end
end
file:close()
self:setText(text)
end
function M:setText(text)
self:removeChildren()
local x = 0
local y = 0
for i = 1, #text do
local c = self.chars[text:byte(i)]
if c ~= nil then
local t = self.image:clone(c.x, c.y, c.width, c.height)
local bitmap = DisplayImage.new(t):setPosition(x + c.xoffset, y + c.yoffset)
self:addChild(bitmap)
x = x + c.xadvance
end
end
self:setSize(x, 50)
return self
end
return M
|
local DisplayObject = DisplayObject
local DisplayImage = DisplayImage
local Image = Image
local Xfs = Xfs
local M = Class(DisplayObject)
local function startsWith(str1, str2)
return str1:sub(1, #str2) == str2
end
local function lineToTable(line)
local result = {}
for pair in line:gmatch("%a+=[-%d]+") do
local key = pair:match("%a+")
local value = pair:match("[-%d]+")
result[key] = tonumber(value)
end
return result
end
function M:init(fontpng, fonttxt, text)
self.super:init()
self.image = Image.new(fontpng)
self.chars = {}
local file = Xfs.open(fonttxt, "r")
for line in file:lines() do
if startsWith(line, "char ") then
local c = lineToTable(line)
self.chars[c.id] = c
end
end
file:close()
self:setText(text)
end
function M:setText(text)
self:removeChildren()
local x = 0
local y = 0
for i = 1, #text do
local c = self.chars[text:byte(i)]
if c ~= nil then
if c.width == 0 and c.height == 0 then
c.width = 1
c.height = 1
end
local t = self.image:clone(c.x, c.y, c.width, c.height)
local bitmap = DisplayImage.new(t):setPosition(x + c.xoffset, y + c.yoffset)
self:addChild(bitmap)
x = x + c.xadvance
end
end
self:setSize(x, 50)
return self
end
return M
|
[bmfont-graphic-design]fix bmfont-graphic-design
|
[bmfont-graphic-design]fix bmfont-graphic-design
|
Lua
|
mit
|
xboot/xboot,xboot/xboot
|
6be767cc00a01b144b0d1cc0c5f609c47f982075
|
generator/json-generator.lua
|
generator/json-generator.lua
|
local json = require 'dkjson'
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local OUTPUT_FILE = 'love-completions.json'
local WIKI_URL = 'https://love2d.org/wiki/'
local LOVE_MODULE_STRING = 'love.'
-- JSON Output control
local DEBUG = false
local KEY_ORDER = {
'luaVersion',
'packagePath',
'global',
'namedTypes',
'type',
'description',
'fields',
'args',
'returnTypes',
'link'
}
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Generates a sequence containing subtables of all the arguments
--
local function createArguments( args, includeDummy )
local arguments = {}
-- Includes a dummy "self" variant, because apparently love-autocomplete-lua
-- automatically omits the first argument of methods preceeded by the : operator.
if includeDummy then
arguments[#arguments + 1] = {}
arguments[#arguments].name = 'self'
end
for _, v in ipairs( args ) do
arguments[#arguments + 1] = {}
arguments[#arguments].name = v.name
-- Use [foo] notation as display name for optional arguments.
if v.default then
arguments[#arguments].displayName = string.format( '[%s]', v.name )
end
end
return arguments
end
local function getType( type )
if type == 'string'
or type == 'number'
or type == 'table'
or type == 'boolean'
or type == 'function' then
return { type = type }
end
return { type = 'ref', name = type }
end
local function createReturnTypes( returns )
local returnTypes = {}
for i, v in ipairs( returns ) do
returnTypes[i] = getType( v.type )
end
return returnTypes
end
-- TODO handle functions with neither args nor return variables.
local function createVariant( vdef, includeDummy )
local variant = {}
if vdef.description then
variant.description = vdef.description
end
if vdef.arguments then
variant.args = createArguments( vdef.arguments, includeDummy )
end
return variant
end
local function createFunction( f, parent, moduleString, includeDummy )
local name = f.name
parent[name] = {}
parent[name].type = 'function'
parent[name].link = string.format( "%s%s%s", WIKI_URL, moduleString, name )
-- NOTE Currently atom-autocomplete-lua doesn't support return types which
-- have been defined inside of variants. So for now we only use the
-- return types of the first variant.
-- @see https://github.com/dapetcu21/atom-autocomplete-lua/issues/15
if f.variants[1].returns then
parent[name].returnTypes = createReturnTypes( f.variants[1].returns )
end
-- Create normal function if there is just one variant.
if #f.variants == 1 then
local v = createVariant( f.variants[1], includeDummy )
parent[name].description = f.description
parent[name].args = v.args
return
end
-- Generate multiple variants.
parent[name].variants = {}
for i, v in ipairs( f.variants ) do
local variant = createVariant( v, includeDummy )
-- Use default description if there is no specific variant description.
if not variant.description then
variant.description = f.description
end
parent[name].variants[i] = variant
end
end
local function createLoveFunctions( functions, parent )
for _, f in pairs( functions ) do
createFunction( f, parent, LOVE_MODULE_STRING )
end
end
local function createLoveModuleFunctions( modules, parent )
for _, m in pairs( modules ) do
local name = m.name
parent[name] = {}
parent[name].type = 'table'
parent[name].description = m.description
parent[name].link = string.format( "%s%s%s", WIKI_URL, LOVE_MODULE_STRING, name )
parent[name].fields = {}
for _, f in pairs( m.functions ) do
createFunction( f, parent[name].fields, string.format( '%s%s.', LOVE_MODULE_STRING, name ))
end
end
end
local function createGlobals( api, global )
global.type = 'table'
global.fields = {}
global.fields.love = {}
global.fields.love.type = 'table'
global.fields.love.fields = {}
createLoveFunctions( api.functions, global.fields.love.fields )
createLoveFunctions( api.callbacks, global.fields.love.fields )
createLoveModuleFunctions( api.modules, global.fields.love.fields )
end
-- ------------------------------------------------
-- Creation methods for named types
-- ------------------------------------------------
local function collectTypes( api )
local types = {}
for _, type in pairs( api.types ) do
assert( not types[type.name] )
types[type.name] = type
end
for _, module in pairs( api.modules ) do
if module.types then -- Not all modules define types.
for _, type in pairs( module.types ) do
assert( not types[type.name] )
types[type.name] = type
end
end
end
return types
end
local function createTypes( types, namedTypes )
for name, type in pairs( types ) do
print( ' ' .. name )
namedTypes[name] = {}
namedTypes[name].type = 'table'
namedTypes[name].fields = {}
if type.functions then
for _, f in pairs( type.functions ) do
createFunction( f, namedTypes[name].fields, name .. ':', true )
end
end
if type.supertypes then
namedTypes[name].metatable = {}
namedTypes[name].metatable.type = 'table'
namedTypes[name].metatable.fields = {
__index = {
type = 'ref',
name = type.parenttype
}
}
end
end
end
local function createJSON()
print( 'Generating LOVE snippets ... ' )
-- Load the LÖVE api files.
local api = require( 'api.love_api' )
assert( api, 'No api file found!' )
print( 'Found API file for LÖVE version ' .. api.version )
-- Create main table.
local output = {
global = {},
namedTypes = {},
packagePath = "./?.lua,./?/init.lua"
}
print( 'Generating functions ...' )
createGlobals( api, output.global )
print( 'Generating types ...' )
local types = collectTypes( api )
createTypes( types, output.namedTypes )
local jsonString = json.encode( output, { indent = DEBUG, keyorder = KEY_ORDER })
local file = io.open( OUTPUT_FILE, 'w' )
assert( file, "ERROR: Can't write file: " .. OUTPUT_FILE )
file:write( jsonString )
print( 'DONE!' )
end
createJSON()
|
local json = require 'dkjson'
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local OUTPUT_FILE = 'love-completions.json'
local WIKI_URL = 'https://love2d.org/wiki/'
local LOVE_MODULE_STRING = 'love.'
-- JSON Output control
local DEBUG = false
local KEY_ORDER = {
'luaVersion',
'packagePath',
'global',
'namedTypes',
'type',
'description',
'fields',
'args',
'returnTypes',
'link'
}
local NOARGS = {}
-- ------------------------------------------------
-- Local Functions
-- ------------------------------------------------
---
-- Generates a sequence containing subtables of all the arguments
--
local function createArguments( args, isMethod )
local arguments = {}
-- Include a "self" argument for methods, since autocomplete-lua and Lua itself
-- omits the first argument of methods preceeded by the : operator
if isMethod then
arguments[#arguments + 1] = {}
arguments[#arguments].name = 'self'
end
for _, v in ipairs( args or NOARGS ) do
arguments[#arguments + 1] = {}
arguments[#arguments].name = v.name
-- Use [foo] notation as display name for optional arguments.
if v.default then
arguments[#arguments].displayName = string.format( '[%s]', v.name )
end
end
return arguments
end
local function getType( type )
if type == 'string'
or type == 'number'
or type == 'table'
or type == 'boolean'
or type == 'function' then
return { type = type }
end
return { type = 'ref', name = type }
end
local function createReturnTypes( returns )
local returnTypes = {}
for i, v in ipairs( returns ) do
returnTypes[i] = getType( v.type )
end
return returnTypes
end
-- TODO handle functions with neither args nor return variables.
local function createVariant( vdef, isMethod )
local variant = {}
variant.description = vdef.description
variant.args = createArguments( vdef.arguments, isMethod )
return variant
end
local function createFunction( f, parent, moduleString, isMethod )
local name = f.name
parent[name] = {}
parent[name].type = 'function'
parent[name].link = string.format( "%s%s%s", WIKI_URL, moduleString, name )
-- NOTE Currently atom-autocomplete-lua doesn't support return types which
-- have been defined inside of variants. So for now we only use the
-- return types of the first variant.
-- @see https://github.com/dapetcu21/atom-autocomplete-lua/issues/15
if f.variants[1].returns then
parent[name].returnTypes = createReturnTypes( f.variants[1].returns )
end
-- Create normal function if there is just one variant.
if #f.variants == 1 then
local v = createVariant( f.variants[1], isMethod )
parent[name].description = f.description
parent[name].args = v.args
return
end
-- Generate multiple variants.
parent[name].variants = {}
for i, v in ipairs( f.variants ) do
local variant = createVariant( v, isMethod )
-- Use default description if there is no specific variant description.
if not variant.description then
variant.description = f.description
end
parent[name].variants[i] = variant
end
end
local function createLoveFunctions( functions, parent )
for _, f in pairs( functions ) do
createFunction( f, parent, LOVE_MODULE_STRING )
end
end
local function createLoveModuleFunctions( modules, parent )
for _, m in pairs( modules ) do
local name = m.name
parent[name] = {}
parent[name].type = 'table'
parent[name].description = m.description
parent[name].link = string.format( "%s%s%s", WIKI_URL, LOVE_MODULE_STRING, name )
parent[name].fields = {}
for _, f in pairs( m.functions ) do
createFunction( f, parent[name].fields, string.format( '%s%s.', LOVE_MODULE_STRING, name ))
end
end
end
local function createGlobals( api, global )
global.type = 'table'
global.fields = {}
global.fields.love = {}
global.fields.love.type = 'table'
global.fields.love.fields = {}
createLoveFunctions( api.functions, global.fields.love.fields )
createLoveFunctions( api.callbacks, global.fields.love.fields )
createLoveModuleFunctions( api.modules, global.fields.love.fields )
end
-- ------------------------------------------------
-- Creation methods for named types
-- ------------------------------------------------
local function collectTypes( api )
local types = {}
for _, type in pairs( api.types ) do
assert( not types[type.name] )
types[type.name] = type
end
for _, module in pairs( api.modules ) do
if module.types then -- Not all modules define types.
for _, type in pairs( module.types ) do
assert( not types[type.name] )
types[type.name] = type
end
end
end
return types
end
local function createTypes( types, namedTypes )
for name, type in pairs( types ) do
print( ' ' .. name )
namedTypes[name] = {}
namedTypes[name].type = 'table'
namedTypes[name].fields = {}
if type.functions then
for _, f in pairs( type.functions ) do
createFunction( f, namedTypes[name].fields, name .. ':', true )
end
end
if type.supertypes then
namedTypes[name].metatable = {}
namedTypes[name].metatable.type = 'table'
namedTypes[name].metatable.fields = {
__index = {
type = 'ref',
name = type.parenttype
}
}
end
end
end
local function createJSON()
print( 'Generating LOVE snippets ... ' )
-- Load the LÖVE api files.
local api = require( 'api.love_api' )
assert( api, 'No api file found!' )
print( 'Found API file for LÖVE version ' .. api.version )
-- Create main table.
local output = {
global = {},
namedTypes = {},
packagePath = "./?.lua,./?/init.lua"
}
print( 'Generating functions ...' )
createGlobals( api, output.global )
print( 'Generating types ...' )
local types = collectTypes( api )
createTypes( types, output.namedTypes )
local jsonString = json.encode( output, { indent = DEBUG, keyorder = KEY_ORDER })
local file = io.open( OUTPUT_FILE, 'w' )
assert( file, "ERROR: Can't write file: " .. OUTPUT_FILE )
file:write( jsonString )
print( 'DONE!' )
end
createJSON()
|
Fix methods with no arguments (#18)
|
Fix methods with no arguments (#18)
* Fix methods with no arguments
Methods with no arguments should still have an argument table which only has self included. Fixes #16.
Renamed includeDummy to isMethod in the process
* Remove unnecessary if checks
createArguments doesn't need to check if the description is nil
Also having an empty args tables for functions that don't take arguments is more explicit than having no args table at all
|
Lua
|
mit
|
rm-code/love-atom,rm-code/love-atom
|
90af6a9ecbff915a88d22886f6c76a1ad6ff6945
|
spec/02-integration/09-hybrid_mode/02-start_stop_spec.lua
|
spec/02-integration/09-hybrid_mode/02-start_stop_spec.lua
|
local helpers = require "spec.helpers"
local confs = helpers.get_clustering_protocols()
for cluster_protocol, conf in pairs(confs) do
describe("invalid config are rejected, protocol " .. cluster_protocol, function()
describe("role is control_plane", function()
it("can not disable admin_listen", function()
local ok, err = helpers.start_kong({
role = "control_plane",
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
admin_listen = "off",
})
assert.False(ok)
assert.matches("Error: admin_listen must be specified when role = \"control_plane\"", err, nil, true)
end)
it("can not disable cluster_listen", function()
local ok, err = helpers.start_kong({
role = "control_plane",
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
cluster_listen = "off",
})
assert.False(ok)
assert.matches("Error: cluster_listen must be specified when role = \"control_plane\"", err, nil, true)
end)
it("can not use DB-less mode", function()
local ok, err = helpers.start_kong({
role = "control_plane",
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
database = "off",
})
assert.False(ok)
assert.matches("Error: in-memory storage can not be used when role = \"control_plane\"", err, nil, true)
end)
it("must define cluster_ca_cert", function()
local ok, err = helpers.start_kong({
role = "control_plane",
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
cluster_mtls = "pki",
})
assert.False(ok)
assert.matches("Error: cluster_ca_cert must be specified when cluster_mtls = \"pki\"", err, nil, true)
end)
end)
describe("role is proxy", function()
it("can not disable proxy_listen", function()
local ok, err = helpers.start_kong({
role = "data_plane",
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
proxy_listen = "off",
})
assert.False(ok)
assert.matches("Error: proxy_listen must be specified when role = \"data_plane\"", err, nil, true)
end)
it("can not use DB mode", function()
local ok, err = helpers.start_kong({
role = "data_plane",
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
})
assert.False(ok)
assert.matches("Error: only in-memory storage can be used when role = \"data_plane\"\n" ..
"Hint: set database = off in your kong.conf", err, nil, true)
end)
end)
for _, param in ipairs({ { "control_plane", "postgres" }, { "data_plane", "off" }, }) do
describe("role is " .. param[1], function()
it("errors if cluster certificate is not found", function()
local ok, err = helpers.start_kong({
role = param[1],
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
database = param[2],
prefix = "servroot2",
})
assert.False(ok)
assert.matches("Error: cluster certificate and key must be provided to use Hybrid mode", err, nil, true)
end)
it("errors if cluster certificate key is not found", function()
local ok, err = helpers.start_kong({
role = param[1],
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
database = param[2],
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
})
assert.False(ok)
assert.matches("Error: cluster certificate and key must be provided to use Hybrid mode", err, nil, true)
end)
end)
end
end)
end
-- note that lagacy modes still error when CP exits
describe("when CP exits DP does not error #t", function()
local need_exit = true
setup(function()
assert(helpers.start_kong({
role = "control_plane",
prefix = "servroot1",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
cluster_listen = "127.0.0.1:9005",
}))
assert(helpers.start_kong({
role = "data_plane",
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
cluster_control_plane = "127.0.0.1:9005",
proxy_listen = "0.0.0.0:9002",
database = "off",
}))
end)
teardown(function()
if need_exit then
helpers.stop_kong("servroot1")
end
helpers.stop_kong("servroot2")
end)
it("", function ()
assert(helpers.stop_kong("servroot1"))
need_exit = false
assert.logfile("servroot2/logs/error.log").has.no.line("[error]", true)
end)
end)
|
local helpers = require "spec.helpers"
local confs = helpers.get_clustering_protocols()
for cluster_protocol, conf in pairs(confs) do
describe("invalid config are rejected, protocol " .. cluster_protocol, function()
describe("role is control_plane", function()
it("can not disable admin_listen", function()
local ok, err = helpers.start_kong({
role = "control_plane",
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
admin_listen = "off",
})
assert.False(ok)
assert.matches("Error: admin_listen must be specified when role = \"control_plane\"", err, nil, true)
end)
it("can not disable cluster_listen", function()
local ok, err = helpers.start_kong({
role = "control_plane",
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
cluster_listen = "off",
})
assert.False(ok)
assert.matches("Error: cluster_listen must be specified when role = \"control_plane\"", err, nil, true)
end)
it("can not use DB-less mode", function()
local ok, err = helpers.start_kong({
role = "control_plane",
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
database = "off",
})
assert.False(ok)
assert.matches("Error: in-memory storage can not be used when role = \"control_plane\"", err, nil, true)
end)
it("must define cluster_ca_cert", function()
local ok, err = helpers.start_kong({
role = "control_plane",
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
cluster_mtls = "pki",
})
assert.False(ok)
assert.matches("Error: cluster_ca_cert must be specified when cluster_mtls = \"pki\"", err, nil, true)
end)
end)
describe("role is proxy", function()
it("can not disable proxy_listen", function()
local ok, err = helpers.start_kong({
role = "data_plane",
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
proxy_listen = "off",
})
assert.False(ok)
assert.matches("Error: proxy_listen must be specified when role = \"data_plane\"", err, nil, true)
end)
it("can not use DB mode", function()
local ok, err = helpers.start_kong({
role = "data_plane",
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
})
assert.False(ok)
assert.matches("Error: only in-memory storage can be used when role = \"data_plane\"\n" ..
"Hint: set database = off in your kong.conf", err, nil, true)
end)
end)
for _, param in ipairs({ { "control_plane", "postgres" }, { "data_plane", "off" }, }) do
describe("role is " .. param[1], function()
it("errors if cluster certificate is not found", function()
local ok, err = helpers.start_kong({
role = param[1],
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
database = param[2],
prefix = "servroot2",
})
assert.False(ok)
assert.matches("Error: cluster certificate and key must be provided to use Hybrid mode", err, nil, true)
end)
it("errors if cluster certificate key is not found", function()
local ok, err = helpers.start_kong({
role = param[1],
legacy_hybrid_protocol = (cluster_protocol == "json (by switch)"),
nginx_conf = conf,
database = param[2],
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
})
assert.False(ok)
assert.matches("Error: cluster certificate and key must be provided to use Hybrid mode", err, nil, true)
end)
end)
end
end)
end
-- note that lagacy modes still error when CP exits
describe("when CP exits DP does not error", function()
local need_exit = true
setup(function()
assert(helpers.start_kong({
role = "control_plane",
prefix = "servroot1",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
cluster_listen = "127.0.0.1:9005",
}))
assert(helpers.start_kong({
role = "data_plane",
prefix = "servroot2",
cluster_cert = "spec/fixtures/kong_clustering.crt",
cluster_cert_key = "spec/fixtures/kong_clustering.key",
cluster_control_plane = "127.0.0.1:9005",
proxy_listen = "0.0.0.0:9002",
database = "off",
}))
end)
teardown(function()
if need_exit then
helpers.stop_kong("servroot1")
end
helpers.stop_kong("servroot2")
end)
it("", function ()
helpers.clean_logfile("servroot2/logs/error.log")
assert(helpers.stop_kong("servroot1"))
need_exit = false
assert.logfile("servroot2/logs/error.log").has.no.line("[error]", true)
end)
end)
|
fix test
|
fix test
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
ff4dbfe45e1273dcfc3c5870c65120fda865d439
|
src/json/decode.lua
|
src/json/decode.lua
|
--[[
Licensed according to the included 'LICENSE' document
Author: Thomas Harning Jr <harningt@gmail.com>
]]
local lpeg = require("lpeg")
local jsonutil = require("json.util")
local error = error
local number = require("json.decode.number")
local strings = require("json.decode.strings")
local object = require("json.decode.object")
local array = require("json.decode.array")
local util = require("json.decode.util")
local setmetatable, getmetatable = setmetatable, getmetatable
local assert = assert
local print = print
local tonumber = tonumber
local ipairs = ipairs
local string = string
local tostring = tostring
module("json.decode")
local nullValue = jsonutil.null
local undefinedValue = jsonutil.null
local ignored = util.ignored
local VALUE, TABLE, ARRAY = util.VALUE, util.TABLE, util.ARRAY
-- For null and undefined, use the util.null value to preserve null-ness
local booleanCapture =
lpeg.P("true") * lpeg.Cc(true)
+ lpeg.P("false") * lpeg.Cc(false)
local nullCapture = lpeg.P("null") * lpeg.Cc(nullValue)
local undefinedCapture = lpeg.P("undefined") * lpeg.Cc(undefinedValue)
default = {
object = object.default,
array = array.default,
number = number.default,
string = strings.default,
allowUndefined = true
}
strict = {
object = object.strict,
array = array.strict,
number = number.strict,
string = strings.strict,
initialObject = true
}
local function buildDecoder(mode)
local arrayCapture = array.buildCapture(mode.array)
local objectCapture = object.buildCapture(mode.object)
local numberCapture = number.buildCapture(mode.number)
local stringCapture = strings.buildCapture(mode.string)
local valueCapture = (
stringCapture
+ numberCapture
+ booleanCapture
+ nullCapture
)
if mode.allowUndefined then
valueCapture = valueCapture + undefinedCapture
end
valueCapture = valueCapture + lpeg.V(TABLE) + lpeg.V(ARRAY)
valueCapture = ignored * valueCapture * ignored
local grammar = lpeg.P({
[1] = mode.initialObject and (lpeg.V(TABLE) + lpeg.V(ARRAY)) or lpeg.V(VALUE),
[VALUE] = valueCapture,
[TABLE] = objectCapture,
[ARRAY] = arrayCapture
}) * ignored * -1
return function(data)
util.doInit()
return assert(lpeg.match(grammar, data), "Invalid JSON data")
end
end
local strictDecoder, defaultDecoder = buildDecoder(strict), buildDecoder(default)
--[[
Options:
number => number decode options
string => string decode options
array => array decode options
object => object decode options
initialObject => whether or not to require the initial object to be a table/array
allowUndefined => whether or not to allow undefined values
]]
function getDecoder(mode)
if mode == strict and strictDecoder then
return strictDecoder
elseif mode == default and defaultDecoder then
return defaultDecoder
end
return buildDecoder(mode)
end
function decode(data, strictOrMode)
local mode = strictOrMode == true and strict or strictOrMode or default
local decoder = getDecoder(mode)
return decoder(data)
end
local mt = getmetatable(_M) or {}
mt.__call = function(self, ...)
return decode(...)
end
setmetatable(_M, mt)
|
--[[
Licensed according to the included 'LICENSE' document
Author: Thomas Harning Jr <harningt@gmail.com>
]]
local lpeg = require("lpeg")
local jsonutil = require("json.util")
local error = error
local number = require("json.decode.number")
local strings = require("json.decode.strings")
local object = require("json.decode.object")
local array = require("json.decode.array")
local util = require("json.decode.util")
local setmetatable, getmetatable = setmetatable, getmetatable
local assert = assert
local print = print
local tonumber = tonumber
local ipairs = ipairs
local string = string
local tostring = tostring
module("json.decode")
local nullValue = jsonutil.null
local undefinedValue = jsonutil.null
local ignored = util.ignored
local VALUE, TABLE, ARRAY = util.VALUE, util.TABLE, util.ARRAY
-- For null and undefined, use the util.null value to preserve null-ness
local booleanCapture =
lpeg.P("true") * lpeg.Cc(true)
+ lpeg.P("false") * lpeg.Cc(false)
local nullCapture = lpeg.P("null") * lpeg.Cc(nullValue)
local undefinedCapture = lpeg.P("undefined") * lpeg.Cc(undefinedValue)
default = {
object = object.default,
array = array.default,
number = number.default,
string = strings.default,
allowUndefined = true
}
strict = {
object = object.strict,
array = array.strict,
number = number.strict,
string = strings.strict,
initialObject = true
}
local function buildDecoder(mode)
local arrayCapture = array.buildCapture(mode.array)
local objectCapture = object.buildCapture(mode.object)
local numberCapture = number.buildCapture(mode.number)
local stringCapture = strings.buildCapture(mode.string)
local valueCapture = (
stringCapture
+ numberCapture
+ booleanCapture
+ nullCapture
)
if mode.allowUndefined then
valueCapture = valueCapture + undefinedCapture
end
valueCapture = valueCapture + lpeg.V(TABLE) + lpeg.V(ARRAY)
valueCapture = ignored * valueCapture * ignored
local grammar = lpeg.P({
[1] = mode.initialObject and (lpeg.V(TABLE) + lpeg.V(ARRAY)) or lpeg.V(VALUE),
[VALUE] = valueCapture,
[TABLE] = objectCapture,
[ARRAY] = arrayCapture
}) * ignored * -1
return function(data)
util.doInit()
return assert(lpeg.match(grammar, data), "Invalid JSON data")
end
end
local strictDecoder, defaultDecoder = buildDecoder(strict), buildDecoder(default)
--[[
Options:
number => number decode options
string => string decode options
array => array decode options
object => object decode options
initialObject => whether or not to require the initial object to be a table/array
allowUndefined => whether or not to allow undefined values
]]
function getDecoder(mode)
mode = mode == true and strict or strictOrMode or default
if mode == strict and strictDecoder then
return strictDecoder
elseif mode == default and defaultDecoder then
return defaultDecoder
end
return buildDecoder(mode)
end
function decode(data, strictOrMode)
local decoder = getDecoder(mode)
return decoder(data)
end
local mt = getmetatable(_M) or {}
mt.__call = function(self, ...)
return decode(...)
end
setmetatable(_M, mt)
|
decoder: Fixed decoder generation to return cached versions
|
decoder: Fixed decoder generation to return cached versions
|
Lua
|
mit
|
renchunxiao/luajson
|
81950fbc46a009e24257ef5d742475c9858a3684
|
item/id_310_mug_with_lid.lua
|
item/id_310_mug_with_lid.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/>.
]]
local lookat = require("base.lookat")
local M = {}
local mugs = {}
local validMugIds = {}
-- the mug on NPC Borgate's counter
local BORGATES_MUG_POS = position(709, 313, 0)
function M.getRandomMugId()
return validMugIds[Random.uniform(1, #validMugIds)]
end
function M.dropMugByChance(dropLocation,chance)
chance = chance or 1
if #validMugIds > 0 and chance >= Random.uniform(1,100) then
world:createItemFromId(310, 1, dropLocation, true, 999, {mugId = M.getRandomMugId()})
end
end
local function addMug(mugId, titleDe, titleEn, pictureDe, pictureEn)
mugs[mugId] = {titleDe = titleDe, titleEn = titleEn, pictureDe = pictureDe, pictureEn = pictureEn}
table.insert(validMugIds, mugId)
end
function M.LookAtItem(User, Item)
-- NPC Borgate uses a different mug each day
if Item.pos == BORGATES_MUG_POS then
local today = world:getTime("day")
if Item:getData("day") ~= today then
Item:setData("day", today)
Item:setData("mugId", M.getRandomMugId())
world:changeItem(Item)
end
end
if Item:getData("mugId") == "random" then
Item:setData("mugId", M.getRandomMugId())
world:changeItem(Item)
end
local mugId = tonumber(Item:getData("mugId"))
if mugId and mugs[mugId] then
lookat.SetSpecialName(Item,"Verzierter Humpen","Decorated Mug")
lookat.SetSpecialDescription(Item,"Der Humpen zeigt folgendes Bild: ".. mugs[mugId]["pictureDe"] .." Unter dem Bild befindet sich eine Gravur: ".. mugs[mugId]["titleDe"], "The mug shows the following picture: ".. mugs[mugId]["pictureEn"] .." There is an engraving beneath the picture: ".. mugs[mugId]["titleEn"])
end
return lookat.GenerateLookAt(User, Item, lookat.NONE)
end
-- Series: Sleeping Dwarf
addMug(1,
"Schlafender Zwerg I",
"Sleeping Dwarf I",
"Ein schlafender Zwerg liegt vor einem Bierfass.",
"A sleeping dwarf is lying infront of a beer barrel."
)
addMug(2,
"Schlafender Zwerg II",
"Sleeping Dwarf II",
"Ein schlafender Zwerg liegt mit einer Spitzhacke in der Hand in einer Miene.",
"Holding a pick-axe in his hands, a sleeping dwarf is lying in a mine."
)
addMug(3,
"Schlafender Zwerg III",
"Sleeping Dwarf III",
"Ein schlafender Zwerg liegt unter einem Tisch in einer Taverne.",
"A sleeping dwarf is lying under a table in a tavern."
)
addMug(4,
"Schlafender Zwerg IV",
"Sleeping Dwarf IV",
"Ein schlafender Zwerg liegt in einem Haufen von Wrstchen und Schinken.",
"A sleeping dwarf is lying on a pile of sausages and hams."
)
addMug(5,
"Schlafender Zwerg V",
"Sleeping Dwarf V",
"Ein schlafender Zwerg liegt mit zufriedenem Lcheln in einem Bett. Er ist umrundet von Unmengen an Gold und Bierflaschen.",
"Surrounded by a huge pile of gold and beer bottles, a dwarf is sleeping with a content smile on his lips in a bed."
)
-- Series: Elf Playing Music
addMug(6,
"Musizierender Elf I",
"Elf Playing Music I",
"Ein Elf sitzt auf einem Ast einer majesttischen Eiche und spielt Flte.",
"An elf sits on a branch of a majestic oak and plays the flute."
)
addMug(7,
"Musizierender Elf II",
"Elf Playing Music II",
"Ein Elf sitzt an einem Feuer und schlgt auf eine Trommel.",
"An elf sits in front of a fire and plays the drums."
)
addMug(8,
"Musizierender Elf III",
"Elf Playing Music III",
"Ein Elf steht in einer Horde grlender und feiernder Zwerg und spielt seelenruhig auf einer Laute.",
"An elf is playing unperterbed on his lute while being in the middle of a bunch of rambunctious, celebrating dwarves."
)
addMug(9,
"Musizierender Elf IV",
"Elf Playing Music IV",
"Ein Elf sitzt auf einer blumigen Wiese und spielt auf einer Harfe.",
"An elf is sitting on a flowery green field and plays the harp."
)
addMug(10,
"Musizierender Elf V",
"Elf Playing Music V",
"Ein Elf blst auf der Spitze eines Berges in ein Horn.",
"An elf blows into a horn on the top of a mountain."
)
-- Series: Baking Halfling
addMug(11,
"Backender Halbling I",
"Baking Halfling I",
"Ein Halbling schttet Mehl in eine Schssel. Auf dem Tisch neben ihm stehen allerlei Zutaten.",
"A halfling puts flour into a bowl. On the table next to him, one can see all kinds of ingredients."
)
addMug(12,
"Backender Halbling II",
"Baking Halfling II",
"Ein Halbling rhrt energisch mit einem groen Lffel in einer Schssel.",
"A halfling energetically stirs with a big spoon in a bowl."
)
addMug(13,
"Backender Halbling III",
"Baking Halfling III",
"Ein Halbling fllt eine Menge Teig aus einer Schssel in eine groe Backform.",
"A halfling pours a lot of dough from a bowl into a big cake pan."
)
addMug(14,
"Backender Halbling IV",
"Baking Halfling IV",
"Ein Halbling schiebt eine groe Backform in einen kleinen, zierlichen Backofen.",
"A halfling puts a big cake pan into a small, diminutive baking oven."
)
addMug(15,
"Backender Halbling IV",
"Baking Halfling IV",
"Ein Halbling sitzt mit einem breiten Grinsen vor einem Tisch, auf dem ein groer, dampfender Kuchen steht.",
"A hafling sits with a broad grin on his lips in front of a table with a big, steaming cake on it."
)
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/>.
]]
local lookat = require("base.lookat")
local M = {}
local mugs = {}
local validMugIds = {}
-- the mug on NPC Borgate's counter
local BORGATES_MUG_POS = position(709, 313, 0)
function M.getRandomMugId()
return validMugIds[Random.uniform(1, #validMugIds)]
end
function M.dropMugByChance(dropLocation,chance)
chance = chance or 1
if #validMugIds > 0 and chance >= Random.uniform(1,100) then
world:createItemFromId(310, 1, dropLocation, true, 999, {mugId = M.getRandomMugId()})
end
end
local function addMug(mugId, titleDe, titleEn, pictureDe, pictureEn)
mugs[mugId] = {titleDe = titleDe, titleEn = titleEn, pictureDe = pictureDe, pictureEn = pictureEn}
table.insert(validMugIds, mugId)
end
function M.LookAtItem(User, Item)
-- NPC Borgate uses a different mug each day
if Item.pos == BORGATES_MUG_POS and Item.wear == 255 then
local today = world:getTime("day")
if tonumber(Item:getData("day")) ~= today then
Item:setData("day", today)
Item:setData("mugId", M.getRandomMugId())
world:changeItem(Item)
end
end
if Item:getData("mugId") == "random" then
Item:setData("mugId", M.getRandomMugId())
world:changeItem(Item)
end
local mugId = tonumber(Item:getData("mugId"))
if mugId and mugs[mugId] then
lookat.SetSpecialName(Item,"Verzierter Humpen","Decorated Mug")
lookat.SetSpecialDescription(Item,"Der Humpen zeigt folgendes Bild: ".. mugs[mugId]["pictureDe"] .." Unter dem Bild befindet sich eine Gravur: ".. mugs[mugId]["titleDe"], "The mug shows the following picture: ".. mugs[mugId]["pictureEn"] .." There is an engraving beneath the picture: ".. mugs[mugId]["titleEn"])
end
return lookat.GenerateLookAt(User, Item, lookat.NONE)
end
-- Series: Sleeping Dwarf
addMug(1,
"Schlafender Zwerg I",
"Sleeping Dwarf I",
"Ein schlafender Zwerg liegt vor einem Bierfass.",
"A sleeping dwarf is lying infront of a beer barrel."
)
addMug(2,
"Schlafender Zwerg II",
"Sleeping Dwarf II",
"Ein schlafender Zwerg liegt mit einer Spitzhacke in der Hand in einer Miene.",
"Holding a pick-axe in his hands, a sleeping dwarf is lying in a mine."
)
addMug(3,
"Schlafender Zwerg III",
"Sleeping Dwarf III",
"Ein schlafender Zwerg liegt unter einem Tisch in einer Taverne.",
"A sleeping dwarf is lying under a table in a tavern."
)
addMug(4,
"Schlafender Zwerg IV",
"Sleeping Dwarf IV",
"Ein schlafender Zwerg liegt in einem Haufen von Wrstchen und Schinken.",
"A sleeping dwarf is lying on a pile of sausages and hams."
)
addMug(5,
"Schlafender Zwerg V",
"Sleeping Dwarf V",
"Ein schlafender Zwerg liegt mit zufriedenem Lcheln in einem Bett. Er ist umrundet von Unmengen an Gold und Bierflaschen.",
"Surrounded by a huge pile of gold and beer bottles, a dwarf is sleeping with a content smile on his lips in a bed."
)
-- Series: Elf Playing Music
addMug(6,
"Musizierender Elf I",
"Elf Playing Music I",
"Ein Elf sitzt auf einem Ast einer majesttischen Eiche und spielt Flte.",
"An elf sits on a branch of a majestic oak and plays the flute."
)
addMug(7,
"Musizierender Elf II",
"Elf Playing Music II",
"Ein Elf sitzt an einem Feuer und schlgt auf eine Trommel.",
"An elf sits in front of a fire and plays the drums."
)
addMug(8,
"Musizierender Elf III",
"Elf Playing Music III",
"Ein Elf steht in einer Horde grlender und feiernder Zwerg und spielt seelenruhig auf einer Laute.",
"An elf is playing unperterbed on his lute while being in the middle of a bunch of rambunctious, celebrating dwarves."
)
addMug(9,
"Musizierender Elf IV",
"Elf Playing Music IV",
"Ein Elf sitzt auf einer blumigen Wiese und spielt auf einer Harfe.",
"An elf is sitting on a flowery green field and plays the harp."
)
addMug(10,
"Musizierender Elf V",
"Elf Playing Music V",
"Ein Elf blst auf der Spitze eines Berges in ein Horn.",
"An elf blows into a horn on the top of a mountain."
)
-- Series: Baking Halfling
addMug(11,
"Backender Halbling I",
"Baking Halfling I",
"Ein Halbling schttet Mehl in eine Schssel. Auf dem Tisch neben ihm stehen allerlei Zutaten.",
"A halfling puts flour into a bowl. On the table next to him, one can see all kinds of ingredients."
)
addMug(12,
"Backender Halbling II",
"Baking Halfling II",
"Ein Halbling rhrt energisch mit einem groen Lffel in einer Schssel.",
"A halfling energetically stirs with a big spoon in a bowl."
)
addMug(13,
"Backender Halbling III",
"Baking Halfling III",
"Ein Halbling fllt eine Menge Teig aus einer Schssel in eine groe Backform.",
"A halfling pours a lot of dough from a bowl into a big cake pan."
)
addMug(14,
"Backender Halbling IV",
"Baking Halfling IV",
"Ein Halbling schiebt eine groe Backform in einen kleinen, zierlichen Backofen.",
"A halfling puts a big cake pan into a small, diminutive baking oven."
)
addMug(15,
"Backender Halbling IV",
"Baking Halfling IV",
"Ein Halbling sitzt mit einem breiten Grinsen vor einem Tisch, auf dem ein groer, dampfender Kuchen steht.",
"A hafling sits with a broad grin on his lips in front of a table with a big, steaming cake on it."
)
return M
|
fix borgates mug
|
fix borgates mug
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content
|
9d00cb585ee2dc606909d7c33ce6815761b796a3
|
share/lua/sd/librivox.lua
|
share/lua/sd/librivox.lua
|
--[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Rémi Duraffort <ivoire at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
require "simplexml"
function descriptor()
return { title = 'librivox' }
end
-- Transform a duration 'mm:ss' or 'hh::mm::ss' into an integer
function string_2_duration(str)
local index = string.find( str, ':' )
if( index == nil ) then return str
else
local index2 = string.find( str, ':', index + 1 )
if( index2 == nil ) then
return string.sub( str, 0, index - 1 ) * 60 + string.sub( str, index + 1 )
else
return string.sub( str, 0, index - 1 ) * 3600 + string.sub( str, index + 1, index2 - 1 ) * 60 + string.sub( str, index2 + 1 )
end
end
end
function main()
local podcast = simplexml.parse_url( 'http://librivox.org/podcast.xml' )
simplexml.add_name_maps( podcast )
local channel = podcast.children_map['channel'][1]
local arturl = ''
local books = {}
for _, item in ipairs( channel.children ) do
if( item.name == 'item' ) then
simplexml.add_name_maps( item )
-- If the book title is unknown, create a node for it in the sd
local book_title = item.children_map['itunes:subtitle'][1].children[1]
if( books[book_title] == nil ) then
books[book_title] = vlc.sd.add_node( { title = book_title,
arturl = arturl } )
end
-- Add the new chapter to the book
books[book_title]:add_subitem( { path = item.children_map['link'][1].children[1],
title = item.children_map['title'][1].children[1],
album = item.children_map['itunes:subtitle'][1].children[1],
artist = item.children_map['itunes:author'][1].children[1],
duration = string_2_duration( item.children_map['itunes:duration'][1].children[1] ),
arturl = arturl } )
elseif( item.name == 'itunes:image' ) then
arturl = item.attributes['href']
end
end
end
|
--[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Rémi Duraffort <ivoire at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
require "simplexml"
function descriptor()
return { title = 'librivox' }
end
-- Transform a duration 'mm:ss' or 'hh::mm::ss' into an integer
function string_2_duration(str)
local index = string.find( str, ':' )
if( index == nil ) then return str
else
if( index == 1 ) then
return string.sub( str, 2 )
end
local index2 = string.find( str, ':', index + 1 )
if( index2 == nil ) then
return string.sub( str, 0, index - 1 ) * 60 + string.sub( str, index + 1 )
else
return string.sub( str, 0, index - 1 ) * 3600 + string.sub( str, index + 1, index2 - 1 ) * 60 + string.sub( str, index2 + 1 )
end
end
end
function main()
local podcast = simplexml.parse_url( 'http://librivox.org/podcast.xml' )
simplexml.add_name_maps( podcast )
local channel = podcast.children_map['channel'][1]
local arturl = ''
local books = {}
for _, item in ipairs( channel.children ) do
if( item.name == 'item' ) then
simplexml.add_name_maps( item )
-- If the book title is unknown, create a node for it in the sd
local book_title = item.children_map['itunes:subtitle'][1].children[1]
if( books[book_title] == nil ) then
books[book_title] = vlc.sd.add_node( { title = book_title,
arturl = arturl } )
end
-- Add the new chapter to the book
books[book_title]:add_subitem( { path = item.children_map['link'][1].children[1],
title = item.children_map['title'][1].children[1],
album = item.children_map['itunes:subtitle'][1].children[1],
artist = item.children_map['itunes:author'][1].children[1],
duration = string_2_duration( item.children_map['itunes:duration'][1].children[1] ),
arturl = arturl } )
elseif( item.name == 'itunes:image' ) then
arturl = item.attributes['href']
end
end
end
|
LUA SD: Fix Librivox duration parser.
|
LUA SD: Fix Librivox duration parser.
|
Lua
|
lgpl-2.1
|
xkfz007/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,shyamalschandra/vlc,xkfz007/vlc,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,krichter722/vlc,krichter722/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,xkfz007/vlc,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,xkfz007/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc
|
5fc292a3a20f18c1bd18e3ea836443add03c17af
|
.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
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 screen = win:screen()
local max = screen:frame()
win:setFrame(max)
end)
-- Move current window one screen East
hs.hotkey.bind({"shift", "ctrl"}, "L", function ()
local win = hs.window.focusedWindow()
if not win then
alertShowCannotMoveWindow()
return
end
win:moveOneScreenEast()
end)
-- Move current window one screen West
hs.hotkey.bind({"shift", "ctrl"}, "H", function ()
local win = hs.window.focusedWindow()
if not win then
alertShowCannotMoveWindow()
return
end
win:moveOneScreenWest()
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)
hs.hotkey.bind({"ctrl", "shift"}, "]", function()
hs.spotify.next()
end)
hs.hotkey.bind({"ctrl", "shift"}, "[", function()
hs.spotify.previous()
end)
-- [[
-- Caffeine/Caffeinate/Amphetamine/KeepingYouAwake Replacement
-- TODO:
-- - Try to get SVG/path icons rather than files
-- - Support a right click menu with "Turn On for Duration"
-- - Support toggling it off at a certain battery percentage
-- Icons from Gloria Kang: https://dribbble.com/shots/2049777-Retina-Caffeine-Menubar-Icons
-- ]]
local caffeine = {}
caffeine.menu = hs.menubar.new()
caffeine.iconOn = 'icons/caffeinate-on.png'
caffeine.iconOff = 'icons/caffeinate-off.png'
local function setIcon(state)
caffeine.menu:setIcon(state and caffeine.iconOn or caffeine.iconOff)
end
caffeine.menu:setClickCallback(function()
setIcon(hs.caffeinate.toggle("displayIdle"))
end)
setIcon(hs.caffeinate.get("displayIdle"))
|
-- [[
-- 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
reloadHammerspoon()
end
end
function reloadHammerspoon()
if caffeine then exitCaffeine() end
hs.reload()
end
hs.hotkey.bind({"cmd", "ctrl"}, "R", function()
reloadHammerspoon()
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 screen = win:screen()
local max = screen:frame()
win:setFrame(max)
end)
-- Move current window one screen East
hs.hotkey.bind({"shift", "ctrl"}, "L", function ()
local win = hs.window.focusedWindow()
if not win then
alertShowCannotMoveWindow()
return
end
win:moveOneScreenEast()
end)
-- Move current window one screen West
hs.hotkey.bind({"shift", "ctrl"}, "H", function ()
local win = hs.window.focusedWindow()
if not win then
alertShowCannotMoveWindow()
return
end
win:moveOneScreenWest()
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)
hs.hotkey.bind({"ctrl", "shift"}, "]", function()
hs.spotify.next()
end)
hs.hotkey.bind({"ctrl", "shift"}, "[", function()
hs.spotify.previous()
end)
-- [[
-- Caffeine/Caffeinate/Amphetamine/KeepingYouAwake Replacement
-- TODO:
-- - Try to get SVG/path icons rather than files
-- - Support a right click menu with "Turn On for Duration"
-- - Support toggling it off at a certain battery percentage
-- Icons from Gloria Kang: https://dribbble.com/shots/2049777-Retina-Caffeine-Menubar-Icons
-- ]]
caffeine = {}
caffeine.menu = hs.menubar.new(false)
caffeine.iconOn = 'icons/caffeinate-on.png'
caffeine.iconOff = 'icons/caffeinate-off.png'
function exitCaffeine()
caffeine.menu:delete()
caffeine = nil
end
function setIcon(state)
caffeine.menu:setIcon(state and caffeine.iconOn or caffeine.iconOff)
end
caffeine.menu:setClickCallback(function()
setIcon(hs.caffeinate.toggle("displayIdle"))
end)
setIcon(hs.caffeinate.get("displayIdle"))
caffeine.menu:returnToMenuBar()
|
Fix: Better caffeine reloading with hammerspoon
|
Fix: Better caffeine reloading with hammerspoon
|
Lua
|
mit
|
tscheffe/dotfiles,tscheffe/dotfiles,tscheffe/dotfiles
|
7db57350dff1e6b79aded20628b7447738fb8dcb
|
tests/dbus.lua
|
tests/dbus.lua
|
di.load_plugin("./plugins/dbus/di_dbus.so")
di.env.DBUS_SESSION_BUS_PID = nil
di.env.DBUS_SESSION_BUS_ADDRESS = nil
local dbusl = di.spawn.run({"dbus-daemon", "--print-address=1", "--print-pid=2", "--session", "--fork"}, false)
dbusl.on("stdout_line", function(l)
print(l)
di.env.DBUS_SESSION_BUS_ADDRESS = l
end)
dbusl.on("stderr_line", function(l)
print(l)
di.env.DBUS_SESSION_BUS_PID = l
end)
dbusl.on("exit", function()
b = di.dbus.session_bus
if b.errmsg then
print(b.errmsg)
di.exit(1)
end
di.dbus.session_bus.get("org.freedesktop.DBus", "/org/freedesktop/DBus").Introspect().on("reply", function(s)
print(s)
collectgarbage()
end)
end)
|
di.load_plugin("./plugins/dbus/di_dbus.so")
di.env.DBUS_SESSION_BUS_PID = nil
di.env.DBUS_SESSION_BUS_ADDRESS = nil
di.env.DISPLAY = nil
local dbusl = di.spawn.run({"dbus-daemon", "--print-address=1", "--print-pid=2", "--session", "--fork"}, false)
dbusl.on("stdout_line", function(l)
-- remove new line
if l == "" then
return
end
print(l)
di.env.DBUS_SESSION_BUS_ADDRESS = l
end)
dbusl.on("stderr_line", function(l)
if l == "" then
return
end
print(l)
di.env.DBUS_SESSION_BUS_PID = l
end)
dbusl.on("exit", function()
b = di.dbus.session_bus
if b.errmsg then
print(b.errmsg)
di.exit(1)
end
di.dbus.session_bus.get("org.freedesktop.DBus", "/org/freedesktop/DBus").Introspect().on("reply", function(s)
print(s)
collectgarbage()
end)
end)
|
Fix dbus ci test
|
Fix dbus ci test
|
Lua
|
mpl-2.0
|
yshui/deai,yshui/deai,yshui/deai
|
36a5673651f800eb2d18085fc65edccc71ea9f6a
|
src/extensions/cp/apple/finalcutpro/ids/v/10.4.0.lua
|
src/extensions/cp/apple/finalcutpro/ids/v/10.4.0.lua
|
return {
Inspector = {
DetailsPanel = "_NS:139",
},
LogicPlugins = {
PitchShifter = "Pitch Shifter",
},
EffectsBrowser = {
Sidebar = "_NS:90",
Contents = "_NS:53",
Sidebar = "_NS:90",
},
TimelineAppearance = {
ClipHeight = "_NS:62",
},
ColorBoard = {
ColorBoard = "Color Inspector",
ChooseColorCorrectorsBar = "_NS:9",
ColorBoardGroup = "_NS:41",
ColorSatExp = "_NS:77",
ColorReset = "_NS:246",
ColorGlobalPuck = "_NS:104",
ColorShadowsPuck = "_NS:240",
ColorMidtonesPuck = "_NS:124",
ColorHighlightsPuck = "_NS:117",
SatReset = "_NS:246",
SatGlobalPuck = "_NS:104",
SatShadowsPuck = "_NS:240",
SatMidtonesPuck = "_NS:124",
SatHighlightsPuck = "_NS:117",
ExpReset = "_NS:246",
ExpGlobalPuck = "_NS:104",
ExpShadowsPuck = "_NS:240",
ExpMidtonesPuck = "_NS:124",
ExpHighlightsPuck = "_NS:117",
ColorGlobalPct = "_NS:48",
ColorGlobalAngle = "_NS:9",
ColorShadowsPct = "_NS:28",
ColorShadowsAngle = "_NS:21",
ColorMidtonesPct = "_NS:54",
ColorMidtonesAngle = "_NS:41",
ColorHighlightsPct = "_NS:34",
ColorHighlightsAngle = "_NS:60",
SatGlobalPct = "_NS:48",
SatShadowsPct = "_NS:28",
SatMidtonesPct = "_NS:54",
SatHighlightsPct = "_NS:34",
ExpGlobalPct = "_NS:48",
ExpShadowsPct = "_NS:28",
ExpMidtonesPct = "_NS:54",
ExpHighlightsPct = "_NS:34",
},
}
|
return {
Inspector = {
DetailsPanel = "_NS:139",
},
LogicPlugins = {
PitchShifter = "Pitch Shifter",
},
EffectsBrowser = {
Sidebar = "_NS:90",
Contents = "_NS:53",
Sidebar = "_NS:90",
},
LibrariesBrowser = {
ToggleViewMode = "_NS:89",
AppearanceAndFiltering = "_NS:75",
SearchToggle = "_NS:99",
FilterToggle = "_NS:9",
},
TimelineAppearance = {
ClipHeight = "_NS:62",
},
ColorBoard = {
ColorBoard = "Color Inspector",
ChooseColorCorrectorsBar = "_NS:9",
ColorBoardGroup = "_NS:41",
ColorSatExp = "_NS:77",
ColorReset = "_NS:246",
ColorGlobalPuck = "_NS:104",
ColorShadowsPuck = "_NS:240",
ColorMidtonesPuck = "_NS:124",
ColorHighlightsPuck = "_NS:117",
SatReset = "_NS:246",
SatGlobalPuck = "_NS:104",
SatShadowsPuck = "_NS:240",
SatMidtonesPuck = "_NS:124",
SatHighlightsPuck = "_NS:117",
ExpReset = "_NS:246",
ExpGlobalPuck = "_NS:104",
ExpShadowsPuck = "_NS:240",
ExpMidtonesPuck = "_NS:124",
ExpHighlightsPuck = "_NS:117",
ColorGlobalPct = "_NS:48",
ColorGlobalAngle = "_NS:9",
ColorShadowsPct = "_NS:28",
ColorShadowsAngle = "_NS:21",
ColorMidtonesPct = "_NS:54",
ColorMidtonesAngle = "_NS:41",
ColorHighlightsPct = "_NS:34",
ColorHighlightsAngle = "_NS:60",
SatGlobalPct = "_NS:48",
SatShadowsPct = "_NS:28",
SatMidtonesPct = "_NS:54",
SatHighlightsPct = "_NS:34",
ExpGlobalPct = "_NS:48",
ExpShadowsPct = "_NS:28",
ExpMidtonesPct = "_NS:54",
ExpHighlightsPct = "_NS:34",
},
}
|
#869 Fixed som 10.4 `_NS:ID` values.
|
#869 Fixed som 10.4 `_NS:ID` values.
|
Lua
|
mit
|
fcpxhacks/fcpxhacks,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,cailyoung/CommandPost,cailyoung/CommandPost,cailyoung/CommandPost
|
abf52784c253fbf70efd64a73686fd152301be71
|
resource-count_0.0.1/control.lua
|
resource-count_0.0.1/control.lua
|
require "defines"
script.on_init(function()
initPlayers()
end)
script.on_event(defines.events.on_player_created, function(event)
playerCreated(event)
end)
script.on_event(defines.events.on_tick, function(event)
if event.tick % 10 ~= 0 then
return
end
for index, player in ipairs(game.players) do
showResourceCount(player)
end
end)
function showResourceCount(player)
if (player.selected == nil) or (player.selected.prototype.type ~= "resource") then
player.gui.top.resource_total.caption = ""
return
end
local count = floodCount({}, player.selected)
player.gui.top.resource_total.caption = player.selected.name .. ": " .. count.total .. " in " .. count.count .. " tiles"
end
function initPlayers()
for _, player in ipairs(game.players) do
initPlayer(player)
end
end
function playerCreated(event)
local player = game.players[event.player_index]
initPlayer(player)
end
function initPlayer(player)
player.gui.top.add{type="label", name="resource_total", caption=""}
end
function floodCount(checked, entity)
local name = entity.name
local pos = entity.position
local key = pos.x .. "," .. pos.y
if checked[key] then
return {total = 0, count = 0}
end
checked[key] = true
local total = entity.amount
local count = 1
for y = -1, 1 do
for x = -1, 1 do
if (x ~= 0 or y ~= 0) then
local xx = pos.x + x
local yy = pos.y + y
local neighbor = entity.surface.find_entity(name, { xx, yy })
if neighbor ~= nil then
local neighborStats = floodCount(checked, neighbor)
total = total + neighborStats.total
count = count + neighborStats.count
end
end
end
end
return {total = total, count = count}
end
|
require "defines"
script.on_init(function()
initPlayers()
end)
script.on_event(defines.events.on_player_created, function(event)
playerCreated(event)
end)
script.on_event(defines.events.on_tick, function(event)
if event.tick % 10 ~= 0 then
return
end
for index, player in ipairs(game.players) do
showResourceCount(player)
end
end)
function showResourceCount(player)
if (player.selected == nil) or (player.selected.prototype.type ~= "resource") then
player.gui.top.resource_total.caption = ""
return
end
local resources = floodFindResources(player.selected)
local count = sumResources(resources)
player.gui.top.resource_total.caption = player.selected.name .. ": " .. count.total .. " in " .. count.count .. " tiles"
end
function initPlayers()
for _, player in ipairs(game.players) do
initPlayer(player)
end
end
function playerCreated(event)
local player = game.players[event.player_index]
initPlayer(player)
end
function initPlayer(player)
player.gui.top.add{type="label", name="resource_total", caption=""}
end
function sumResources(resources)
local total = 0
local count = 0
for key, resource in pairs(resources) do
total = total + resource.amount
count = count + 1
end
return {total = total, count = count}
end
function floodFindResources(entity)
local found = {}
floodCount(found, entity)
return found
end
function floodCount(found, entity)
local name = entity.name
local pos = entity.position
local key = pos.x .. "," .. pos.y
if found[key] then
return
end
found[key] = entity
local RANGE = 2.2
local surface = entity.surface
local area = {{pos.x - RANGE, pos.y - RANGE}, {pos.x + RANGE, pos.y + RANGE}}
for _, res in pairs(surface.find_entities_filtered { area = area, name = entity.name}) do
local key2 = res.position.x .. "," .. res.position.y
if not found[key2] then
floodCount(found, res)
end
end
end
|
Fix #12 Resources should be connected but aren't considered as such
|
Fix #12 Resources should be connected but aren't considered as such
|
Lua
|
mit
|
Zomis/FactorioMods
|
24e916440676a24de6915d5ed078950cb5156175
|
skillfeed.lua
|
skillfeed.lua
|
dofile("urlcode.lua")
dofile("table_show.lua")
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
local addedtolist = {}
downloaded["https://fast.wistia.com/btnfr'.indexOf(c)>-1)d+=l[c],r++;else if(c=="] = true
downloaded["https://fast.wistia.com/g,"] = true
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local html = urlpos["link_expect_html"]
if downloaded[url] == true or addedtolist[url] == true then
return false
end
if (downloaded[url] ~= true or addedtolist[url] ~= true) then
if (downloaded[url] ~= true and addedtolist[url] ~= true) and ((string.match(url, "[^0-9]"..item_value) and not string.match(url, "[^0-9]"..item_value.."[0-9]")) or string.match(url, "^https?://fast%.wistia%.com/") or string.match(url, "^https?://distillery%.wistia%.com/") or string.match(url, "^https?://embed%-ssl%.wistia%.com/") or html == 0) then
addedtolist[url] = true
return true
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
local function check(url)
if (downloaded[url] ~= true and addedtolist[url] ~= true) and ((string.match(url, "[^0-9]"..item_value) and not string.match(url, "[^0-9]"..item_value.."[0-9]")) or string.match(url, "^https?://fast%.wistia%.com/") or string.match(url, "^https?://distillery%.wistia%.com/") or string.match(url, "^https?://pipedream%.wistia%.com/") or string.match(url, "^https?://embed%-ssl%.wistia%.com/") or string.match(url, "cloudfront%.net") or string.match(url, "optimizely%.com") or string.match(url, "amazonaws%.com")) then
if string.match(url, "&") then
table.insert(urls, { url=string.gsub(url, "&", "&") })
addedtolist[url] = true
addedtolist[string.gsub(url, "&", "&")] = true
else
table.insert(urls, { url=url })
addedtolist[url] = true
end
end
end
local function checknewurl(newurl, url)
if string.match(newurl, "^https?://") then
check(newurl)
elseif string.match(newurl, "^//") then
check(string.gsub(newurl, "//", "http://"))
elseif string.match(newurl, "^/") then
check(string.match(url, "^(https?://[^/]+)")..newurl)
end
end
if (string.match(url, "[^0-9]"..item_value) and not string.match(url, "[^0-9]"..item_value.."[0-9]")) or string.match(url, "^https?://fast%.wistia%.com/") then
html = read_file(file)
for newurl in string.gmatch(html, '"([^"]+)"') do
checknewurl(newurl, url)
end
for newurl in string.gmatch(html, "'([^']+)'") do
checknewurl(newurl, url)
end
if string.match(html, "Wistia%.embed%(") then
check("https://fast.wistia.com/embed/medias/"..string.match(html, 'Wistia%.embed%("([^"]+)",')..".json?callback=wistiajson1")
check("https://fast.wistia.com/embed/medias/"..string.match(html, 'Wistia%.embed%("([^"]+)",')..".json")
check("https://fast.wistia.com/embed/iframe/"..string.match(html, 'Wistia%.embed%("([^"]+)",'))
end
for datapart in string.gmatch(html, "{([^{]-)}") do
if string.match(datapart, '"ext":"([^"]+)"') == "mp4" and not (string.match(datapart, '"slug":"([^"]+)"') == "original" or string.match(datapart, '"type":"([^"]+)"') == "preview" or string.match(datapart, '"type":"([^"]+)"') == "original") then
check(string.match(datapart, '"url":"(https?://.-)%.bin"').."/file.mp4")
elseif string.match(datapart, '"ext":"([^"]+)"') == "jpg" then
check(string.match(datapart, '"url":"(https?://.-)%.bin"')..".jpg")
check(string.match(datapart, '"url":"(https?://.-)%.bin"')..".jpg?image_crop_resized=640x360")
check(string.match(datapart, '"url":"(https?://.-)%.bin"')..".jpg?image_crop_resized=960x540")
check(string.match(datapart, '"url":"(https?://.-)%.bin"')..".jpg?image_crop_resized=1280x720")
end
end
end
return urls
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) then
if string.match(url.url, "https://") then
local newurl = string.gsub(url.url, "https://", "http://")
downloaded[newurl] = true
else
downloaded[url.url] = true
end
end
local function errorcode(sleep, numtries, action)
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep "..tostring(sleep))
tries = tries + 1
if tries >= numtries then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
tries = 0
if action == "abort" then
return wget.actions.ABORT
elseif action == "exit" then
return wget.actions.EXIT
end
else
return wget.actions.CONTINUE
end
end
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403 and status_code ~= 400) then
errorcode(1, 5, "abort")
elseif status_code == 0 then
errorcode(10, 5, "abort")
end
tries = 0
local sleep_time = 0
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
dofile("urlcode.lua")
dofile("table_show.lua")
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
local addedtolist = {}
downloaded["https://fast.wistia.com/btnfr'.indexOf(c)>-1)d+=l[c],r++;else if(c=="] = true
downloaded["https://fast.wistia.com/g,"] = true
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local html = urlpos["link_expect_html"]
if downloaded[url] == true or addedtolist[url] == true then
return false
end
if (downloaded[url] ~= true or addedtolist[url] ~= true) then
if (downloaded[url] ~= true and addedtolist[url] ~= true) and ((string.match(url, "/courses/"..item_value) and not string.match(url, "/courses/"..item_value.."[0-9]")) or string.match(url, "^https?://fast%.wistia%.com/") or string.match(url, "^https?://distillery%.wistia%.com/") or string.match(url, "^https?://embed%-ssl%.wistia%.com/") or html == 0) then
addedtolist[url] = true
return true
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
local function check(url)
if (downloaded[url] ~= true and addedtolist[url] ~= true) and ((string.match(url, "/courses/"..item_value) and not string.match(url, "/courses/"..item_value.."[0-9]")) or string.match(url, "^https?://fast%.wistia%.com/") or string.match(url, "^https?://distillery%.wistia%.com/") or string.match(url, "^https?://pipedream%.wistia%.com/") or string.match(url, "^https?://embed%-ssl%.wistia%.com/") or string.match(url, "cloudfront%.net") or string.match(url, "optimizely%.com") or string.match(url, "amazonaws%.com")) then
if string.match(url, "&") then
table.insert(urls, { url=string.gsub(url, "&", "&") })
addedtolist[url] = true
addedtolist[string.gsub(url, "&", "&")] = true
else
table.insert(urls, { url=url })
addedtolist[url] = true
end
end
end
local function checknewurl(newurl, url)
if string.match(newurl, "^https?://") then
check(newurl)
elseif string.match(newurl, "^//") then
check("http:"..newurl)
elseif string.match(newurl, "^/") then
check(string.match(url, "^(https?://[^/]+)")..newurl)
end
end
if (string.match(url, "/courses/"..item_value) and not string.match(url, "/courses/"..item_value.."[0-9]")) or string.match(url, "^https?://fast%.wistia%.com/") then
html = read_file(file)
for newurl in string.gmatch(html, '"([^"]+)"') do
checknewurl(newurl, url)
end
for newurl in string.gmatch(html, "'([^']+)'") do
checknewurl(newurl, url)
end
if string.match(html, "Wistia%.embed%(") then
check("https://fast.wistia.com/embed/medias/"..string.match(html, 'Wistia%.embed%("([^"]+)",')..".json?callback=wistiajson1")
check("https://fast.wistia.com/embed/medias/"..string.match(html, 'Wistia%.embed%("([^"]+)",')..".json")
check("https://fast.wistia.com/embed/iframe/"..string.match(html, 'Wistia%.embed%("([^"]+)",'))
end
for datapart in string.gmatch(html, "{([^{]-)}") do
if string.match(datapart, '"ext":"([^"]+)"') == "mp4" and not (string.match(datapart, '"slug":"([^"]+)"') == "original" or string.match(datapart, '"type":"([^"]+)"') == "preview" or string.match(datapart, '"type":"([^"]+)"') == "original") then
check(string.match(datapart, '"url":"(https?://.-)%.bin"').."/file.mp4")
elseif string.match(datapart, '"ext":"([^"]+)"') == "jpg" then
check(string.match(datapart, '"url":"(https?://.-)%.bin"')..".jpg")
check(string.match(datapart, '"url":"(https?://.-)%.bin"')..".jpg?image_crop_resized=640x360")
check(string.match(datapart, '"url":"(https?://.-)%.bin"')..".jpg?image_crop_resized=960x540")
check(string.match(datapart, '"url":"(https?://.-)%.bin"')..".jpg?image_crop_resized=1280x720")
end
end
end
return urls
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) then
if string.match(url.url, "https://") then
local newurl = string.gsub(url.url, "https://", "http://")
downloaded[newurl] = true
else
downloaded[url.url] = true
end
end
local function errorcode(sleep, numtries, action)
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep "..tostring(sleep))
tries = tries + 1
if tries >= numtries then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
tries = 0
if action == "abort" then
return wget.actions.ABORT
elseif action == "exit" then
return wget.actions.EXIT
end
else
return wget.actions.CONTINUE
end
end
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403 and status_code ~= 400) then
errorcode(1, 5, "abort")
elseif status_code == 0 then
errorcode(10, 5, "abort")
end
tries = 0
local sleep_time = 0
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
skillfeed.lua: important fix
|
skillfeed.lua: important fix
|
Lua
|
unlicense
|
ArchiveTeam/skillfeed-grab,ArchiveTeam/skillfeed-grab
|
f7c0b0d49aa6fe8e5e5fe73eccb9c8cfb73c0694
|
lua/starfall/libs_sh/net.lua
|
lua/starfall/libs_sh/net.lua
|
-------------------------------------------------------------------------------
-- Networking library.
-------------------------------------------------------------------------------
local net = net
--- Net message library. Used for sending data from the server to the client and back
local net_library, _ = SF.Libraries.Register("net")
local function can_send( instance, noupdate )
if instance.data.net.lasttime < CurTime() - 1 then
if not noupdate then
instance.data.net.lasttime = CurTime()
end
return true
else
return false
end
end
local function write( instance, type, value, setting )
instance.data.net.data[#instance.data.net.data+1] = { "Write" .. type, value, setting }
end
SF.Libraries.AddHook( "initialize", function( instance )
instance.data.net = {
started = false,
lasttime = 0,
data = {},
}
end)
SF.Libraries.AddHook( "deinitialize", function( instance )
if instance.data.net.started then
instance.data.net.started = false
end
end)
if SERVER then
util.AddNetworkString( "SF_netmessage" )
local function checktargets( target )
if target then
if SF.GetType(target) == "table" then
local newtarget = {}
for i=1,#target do
SF.CheckType( SF.Entities.Unwrap(target[i]), "Player", 1 )
newtarget[i] = SF.Entities.Unwrap(target[i])
end
return net.Send, newtarget
else
SF.CheckType( SF.Entities.Unwrap(target), "Player", 1 ) -- TODO: unhacky this
return net.Send, SF.Entities.Unwrap(target)
end
else
return net.Broadcast
end
end
function net_library.send( target )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
local sendfunc, newtarget = checktargets( target )
local data = instance.data.net.data
if #data == 0 then return false end
net.Start( "SF_netmessage" )
for i=1,#data do
local writefunc = data[i][1]
local writevalue = data[i][2]
local writesetting = data[i][3]
net[writefunc]( writevalue, writesetting )
end
sendfunc( newtarget )
end
else
function net_library.send()
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
local data = instance.data.net.data
if #data == 0 then return false end
net.Start( "SF_netmessage" )
for i=1,#data do
local writefunc = data[i][1]
local writevalue = data[i][2]
local writesetting = data[i][3]
net[writefunc]( writevalue, writesetting )
end
net.SendToServer()
end
end
function net_library.start( name )
SF.CheckType( name, "string" )
local instance = SF.instance
if not can_send( instance ) then return error("can't send net messages that often",2) end
instance.data.net.started = true
instance.data.net.data = {}
write( instance, "String", name )
end
function net_library.writeTable( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "table" )
write( instance, "Table", SF.Unsanitize(t) )
return true
end
function net_library.readTable()
return SF.Sanitize(net.ReadTable())
end
function net_library.writeString( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "string" )
write( instance, "String", t )
return true
end
function net_library.readString()
return net.ReadString()
end
function net_library.writeInt( t, n )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
SF.CheckType( n, "number" )
write( instance, "Int", t, n )
return true
end
function net_library.readInt(n)
SF.CheckType( n, "number" )
return net.ReadInt(n)
end
function net_library.writeUInt( t, n )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
SF.CheckType( n, "number" )
write( instance, "UInt", t, n )
return true
end
function net_library.readUInt(n)
SF.CheckType( n, "number" )
return net.ReadUInt(n)
end
function net_library.writeBit( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "boolean" )
write( instance, "Bit", t )
return true
end
function net_library.readBit()
return net.ReadBit()
end
function net_library.writeDouble( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "Double", t )
return true
end
function net_library.readDouble()
return net.ReadDouble()
end
function net_library.writeFloat( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "Float", t )
return true
end
function net_library.readFloat()
return net.ReadFloat()
end
function net_library.bytesWritten()
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
return net.BytesWritten()
end
function net_library.canSend()
return can_send(SF.instance, true)
end
net.Receive( "SF_netmessage", function( len, ply )
SF.RunScriptHook( "net", net.ReadString(), len, ply and SF.WrapObject( ply ) )
end)
|
-------------------------------------------------------------------------------
-- Networking library.
-------------------------------------------------------------------------------
local net = net
--- Net message library. Used for sending data from the server to the client and back
local net_library, _ = SF.Libraries.Register("net")
local function can_send( instance, noupdate )
if instance.data.net.burst > 0 then
if not noupdate then instance.data.net.burst = instance.data.net.burst - 1 end
return true
else
return false
end
end
local function write( instance, type, value, setting )
instance.data.net.data[#instance.data.net.data+1] = { "Write" .. type, value, setting }
end
local instances = {}
SF.Libraries.AddHook( "initialize", function( instance )
instance.data.net = {
started = false,
burst = 10,
data = {},
}
instances[instance] = true
end)
SF.Libraries.AddHook( "deinitialize", function( instance )
if instance.data.net.started then
instance.data.net.started = false
end
instances[instance] = nil
end)
timer.Create( "SF_Net_BurstCounter", 0.5, 0, function()
for instance, b in pairs( instances ) do
if instance.data.net.burst < 10 then
instance.data.net.burst = instance.data.net.burst + 1
end
end
end)
if SERVER then
util.AddNetworkString( "SF_netmessage" )
local function checktargets( target )
if target then
if SF.GetType(target) == "table" then
local newtarget = {}
for i=1,#target do
SF.CheckType( SF.Entities.Unwrap(target[i]), "Player", 1 )
newtarget[i] = SF.Entities.Unwrap(target[i])
end
return net.Send, newtarget
else
SF.CheckType( SF.Entities.Unwrap(target), "Player", 1 ) -- TODO: unhacky this
return net.Send, SF.Entities.Unwrap(target)
end
else
return net.Broadcast
end
end
function net_library.send( target )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
local sendfunc, newtarget = checktargets( target )
local data = instance.data.net.data
if #data == 0 then return false end
net.Start( "SF_netmessage" )
for i=1,#data do
local writefunc = data[i][1]
local writevalue = data[i][2]
local writesetting = data[i][3]
net[writefunc]( writevalue, writesetting )
end
sendfunc( newtarget )
end
else
function net_library.send()
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
local data = instance.data.net.data
if #data == 0 then return false end
net.Start( "SF_netmessage" )
for i=1,#data do
local writefunc = data[i][1]
local writevalue = data[i][2]
local writesetting = data[i][3]
net[writefunc]( writevalue, writesetting )
end
net.SendToServer()
end
end
function net_library.start( name )
SF.CheckType( name, "string" )
local instance = SF.instance
if not can_send( instance ) then return error("can't send net messages that often",2) end
instance.data.net.started = true
instance.data.net.data = {}
write( instance, "String", name )
end
function net_library.writeTable( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "table" )
write( instance, "Table", SF.Unsanitize(t) )
return true
end
function net_library.readTable()
return SF.Sanitize(net.ReadTable())
end
function net_library.writeString( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "string" )
write( instance, "String", t )
return true
end
function net_library.readString()
return net.ReadString()
end
function net_library.writeInt( t, n )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
SF.CheckType( n, "number" )
write( instance, "Int", t, n )
return true
end
function net_library.readInt(n)
SF.CheckType( n, "number" )
return net.ReadInt(n)
end
function net_library.writeUInt( t, n )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
SF.CheckType( n, "number" )
write( instance, "UInt", t, n )
return true
end
function net_library.readUInt(n)
SF.CheckType( n, "number" )
return net.ReadUInt(n)
end
function net_library.writeBit( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "boolean" )
write( instance, "Bit", t )
return true
end
function net_library.readBit()
return net.ReadBit()
end
function net_library.writeDouble( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "Double", t )
return true
end
function net_library.readDouble()
return net.ReadDouble()
end
function net_library.writeFloat( t )
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
SF.CheckType( t, "number" )
write( instance, "Float", t )
return true
end
function net_library.readFloat()
return net.ReadFloat()
end
function net_library.bytesWritten()
local instance = SF.instance
if not instance.data.net.started then error("net message not started",2) end
return net.BytesWritten()
end
function net_library.canSend()
return can_send(SF.instance, true)
end
net.Receive( "SF_netmessage", function( len, ply )
SF.RunScriptHook( "net", net.ReadString(), len, ply and SF.WrapObject( ply ) )
end)
|
[Changed] Net messages now have a burst instead of a fixed timer
|
[Changed] Net messages now have a burst instead of a fixed timer
Before, you could send 1 net message per second. End of story.
Now, it uses a "burst" instead. This means that every time you send a
net message, your counter decreases by one. When it reaches 0, you can't
send any messages. Every 0.5 seconds, all SF chips's burst amounts are
increased by one, back up to a cap of 10.
|
Lua
|
bsd-3-clause
|
Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,Xandaros/Starfall,INPStarfall/Starfall,INPStarfall/Starfall
|
8ae475efe2ccc5563e7846976c9ba69624c8e8b5
|
nonsence/log.lua
|
nonsence/log.lua
|
--[[
Nonsence Asynchronous event based Lua Web server.
Author: John Abrahamsen < JhnAbrhmsn@gmail.com >
This module "IOLoop" is a part of the Nonsence Web server.
< https://github.com/JohnAbrahamsen/nonsence-ng/ >
Nonsence is licensed under the MIT license < http://www.opensource.org/licenses/mit-license.php >:
"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 log = {}
log.dump = function(stuff, description)
-- Usefull table printer for debug.
print(_dump(stuff, description))
end
log.warning = function(str)
-- Prints a warning to stdout.
print("[" .. os.date("%X", os.time()) .. '] Warning: ' .. str)
end
log.notice = function(str)
-- Prints a notice to stdout.
print("[" .. os.date("%X", os.time()) .. '] Notice: ' .. str)
end
log.error = function(str)
-- Running log.error means throwing a error.
-- It will stop execution if not caught by either pcall
-- or xpcall.
error(str)
end
local _dump = function (t, name, indent)
local cart -- a container
local autoref -- for self references
local function isemptytable(t) return next(t) == nil end
local function basicSerialize (o)
local so = tostring(o)
if type(o) == "function" then
local info = debug.getinfo(o, "S")
-- info.name is nil because o is not a calling level
if info.what == "C" then
return string.format("%q", so .. ", C function")
else
-- the information is defined through lines
return string.format("%q", so .. ", defined in (" ..
info.linedefined .. "-" .. info.lastlinedefined ..
")" .. info.source)
end
elseif type(o) == "number" or type(o) == "boolean" then
return so
else
return string.format("%q", so)
end
end
local function addtocart (value, name, indent, saved, field)
indent = indent or ""
saved = saved or {}
field = field or name
cart = cart .. indent .. field
if type(value) ~= "table" then
cart = cart .. " = " .. basicSerialize(value) .. ";\n"
else
if saved[value] then
cart = cart .. " = {}; -- " .. saved[value]
.. " (self reference)\n"
autoref = autoref .. name .. " = " .. saved[value] .. ";\n"
else
saved[value] = name
--if tablecount(value) == 0 then
if isemptytable(value) then
cart = cart .. " = {};\n"
else
cart = cart .. " = {\n"
for k, v in pairs(value) do
k = basicSerialize(k)
local fname = string.format("%s[%s]", name, k)
field = string.format("[%s]", k)
-- three spaces between levels
addtocart(v, fname, indent .. " ", saved, field)
end
cart = cart .. indent .. "};\n"
end
end
end
end
name = name or "__unnamed__"
if type(t) ~= "table" then
return name .. " = " .. basicSerialize(t)
end
cart, autoref = "", ""
addtocart(t, name, indent)
return cart .. autoref
end
return log
|
--[[
Nonsence Asynchronous event based Lua Web server.
Author: John Abrahamsen < JhnAbrhmsn@gmail.com >
This module "IOLoop" is a part of the Nonsence Web server.
< https://github.com/JohnAbrahamsen/nonsence-ng/ >
Nonsence is licensed under the MIT license < http://www.opensource.org/licenses/mit-license.php >:
"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 log = {}
log.dump = function(stuff, description)
-- Usefull table printer for debug.
local _dump = function (t, name, indent)
local cart -- a container
local autoref -- for self references
local function isemptytable(t) return next(t) == nil end
local function basicSerialize (o)
local so = tostring(o)
if type(o) == "function" then
local info = debug.getinfo(o, "S")
-- info.name is nil because o is not a calling level
if info.what == "C" then
return string.format("%q", so .. ", C function")
else
-- the information is defined through lines
return string.format("%q", so .. ", defined in (" ..
info.linedefined .. "-" .. info.lastlinedefined ..
")" .. info.source)
end
elseif type(o) == "number" or type(o) == "boolean" then
return so
else
return string.format("%q", so)
end
end
local function addtocart (value, name, indent, saved, field)
indent = indent or ""
saved = saved or {}
field = field or name
cart = cart .. indent .. field
if type(value) ~= "table" then
cart = cart .. " = " .. basicSerialize(value) .. ";\n"
else
if saved[value] then
cart = cart .. " = {}; -- " .. saved[value]
.. " (self reference)\n"
autoref = autoref .. name .. " = " .. saved[value] .. ";\n"
else
saved[value] = name
--if tablecount(value) == 0 then
if isemptytable(value) then
cart = cart .. " = {};\n"
else
cart = cart .. " = {\n"
for k, v in pairs(value) do
k = basicSerialize(k)
local fname = string.format("%s[%s]", name, k)
field = string.format("[%s]", k)
-- three spaces between levels
addtocart(v, fname, indent .. " ", saved, field)
end
cart = cart .. indent .. "};\n"
end
end
end
end
name = name or "__unnamed__"
if type(t) ~= "table" then
return name .. " = " .. basicSerialize(t)
end
cart, autoref = "", ""
addtocart(t, name, indent)
return cart .. autoref
end
print(_dump(stuff, description))
end
log.warning = function(str)
-- Prints a warning to stdout.
print("[" .. os.date("%X", os.time()) .. '] Warning: ' .. str)
end
log.notice = function(str)
-- Prints a notice to stdout.
print("[" .. os.date("%X", os.time()) .. '] Notice: ' .. str)
end
log.error = function(str)
-- Running log.error means throwing a error.
-- It will stop execution if not caught by either pcall
-- or xpcall.
error(str)
end
return log
|
Opps, bug there.
|
Opps, bug there.
|
Lua
|
apache-2.0
|
kernelsauce/turbo,YuanPeir-Chen/turbo-support-mipsel,ddysher/turbo,luastoned/turbo,luastoned/turbo,zcsteele/turbo,YuanPeir-Chen/turbo-support-mipsel,zcsteele/turbo,mniestroj/turbo,ddysher/turbo
|
bbe7261f70e0082d70b98f8df24f2557d54d5065
|
src/dao/cassandra/plugins.lua
|
src/dao/cassandra/plugins.lua
|
local constants = require "kong.constants"
local BaseDao = require "kong.dao.cassandra.base_dao"
local cjson = require "cjson"
local function load_value_schema(plugin_t)
local status, plugin_schema = pcall(require, "kong.plugins."..plugin_t.name..".schema")
if not status then
return nil, "Plugin \""..plugin_t.name.."\" not found"
end
return plugin_schema
end
local SCHEMA = {
id = { type = constants.DATABASE_TYPES.ID },
api_id = { type = constants.DATABASE_TYPES.ID, required = true, foreign = true, queryable = true },
application_id = { type = constants.DATABASE_TYPES.ID, foreign = true, queryable = true, default = constants.DATABASE_NULL_ID },
name = { type = "string", required = true, queryable = true, immutable = true },
value = { type = "table", required = true, schema = load_value_schema },
enabled = { type = "boolean", default = true },
created_at = { type = constants.DATABASE_TYPES.TIMESTAMP }
}
local Plugins = BaseDao:extend()
function Plugins:new(properties)
self._entity = "Plugin"
self._schema = SCHEMA
self._queries = {
insert = {
params = { "id", "api_id", "application_id", "name", "value", "enabled", "created_at" },
query = [[ INSERT INTO plugins(id, api_id, application_id, name, value, enabled, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?); ]]
},
update = {
params = { "api_id", "application_id", "value", "enabled", "created_at", "id", "name" },
query = [[ UPDATE plugins SET api_id = ?, application_id = ?, value = ?, enabled = ?, created_at = ? WHERE id = ? AND name = ?; ]]
},
select = {
query = [[ SELECT * FROM plugins %s; ]]
},
select_one = {
params = { "id" },
query = [[ SELECT * FROM plugins WHERE id = ?; ]]
},
delete = {
params = { "id" },
query = [[ DELETE FROM plugins WHERE id = ?; ]]
},
__unique = {
self = {
params = { "api_id", "application_id", "name" },
query = [[ SELECT * FROM plugins WHERE api_id = ? AND application_id = ? AND name = ? ALLOW FILTERING; ]]
}
},
__foreign = {
api_id = {
params = { "api_id" },
query = [[ SELECT id FROM apis WHERE id = ?; ]]
},
application_id = {
params = { "application_id" },
query = [[ SELECT id FROM applications WHERE id = ?; ]]
}
}
}
Plugins.super.new(self, properties)
end
-- @override
function Plugins:_marshall(t)
if type(t.value) == "table" then
t.value = cjson.encode(t.value)
end
return t
end
-- @override
function Plugins:_unmarshall(t)
-- deserialize values (tables) string to json
if type(t.value) == "string" then
t.value = cjson.decode(t.value)
end
-- remove application_id if null uuid
if t.application_id == constants.DATABASE_NULL_ID then
t.application_id = nil
end
return t
end
function Plugins:find_distinct()
-- Open session
local session, err = Plugins.super._open_session(self)
if err then
return nil, err
end
-- Execute query
local distinct_names = {}
for _, rows, page, err in session:execute(self._statements.select.query, nil, {auto_paging=true}) do
if err then
return nil, err
end
for _, v in ipairs(rows) do
-- Rows also contains other properites, so making sure it's a plugin
if v.name then
distinct_names[v.name] = true
end
end
end
-- Close session
local socket_err = Plugins.super._close_session(self, session)
if socket_err then
return nil, socket_err
end
local result = {}
for k,_ in pairs(distinct_names) do
table.insert(result, k)
end
return result, nil
end
return Plugins
|
local constants = require "kong.constants"
local BaseDao = require "kong.dao.cassandra.base_dao"
local cjson = require "cjson"
local function load_value_schema(plugin_t)
if plugin_t.name then
local status, plugin_schema = pcall(require, "kong.plugins."..plugin_t.name..".schema")
if status then
return plugin_schema
end
end
return nil, "Plugin \""..(plugin_t.name and plugin_t.name or "").."\" not found"
end
local SCHEMA = {
id = { type = constants.DATABASE_TYPES.ID },
api_id = { type = constants.DATABASE_TYPES.ID, required = true, foreign = true, queryable = true },
application_id = { type = constants.DATABASE_TYPES.ID, foreign = true, queryable = true, default = constants.DATABASE_NULL_ID },
name = { type = "string", required = true, queryable = true, immutable = true },
value = { type = "table", required = true, schema = load_value_schema },
enabled = { type = "boolean", default = true },
created_at = { type = constants.DATABASE_TYPES.TIMESTAMP }
}
local Plugins = BaseDao:extend()
function Plugins:new(properties)
self._entity = "Plugin"
self._schema = SCHEMA
self._queries = {
insert = {
params = { "id", "api_id", "application_id", "name", "value", "enabled", "created_at" },
query = [[ INSERT INTO plugins(id, api_id, application_id, name, value, enabled, created_at)
VALUES(?, ?, ?, ?, ?, ?, ?); ]]
},
update = {
params = { "api_id", "application_id", "value", "enabled", "created_at", "id", "name" },
query = [[ UPDATE plugins SET api_id = ?, application_id = ?, value = ?, enabled = ?, created_at = ? WHERE id = ? AND name = ?; ]]
},
select = {
query = [[ SELECT * FROM plugins %s; ]]
},
select_one = {
params = { "id" },
query = [[ SELECT * FROM plugins WHERE id = ?; ]]
},
delete = {
params = { "id" },
query = [[ DELETE FROM plugins WHERE id = ?; ]]
},
__unique = {
self = {
params = { "api_id", "application_id", "name" },
query = [[ SELECT * FROM plugins WHERE api_id = ? AND application_id = ? AND name = ? ALLOW FILTERING; ]]
}
},
__foreign = {
api_id = {
params = { "api_id" },
query = [[ SELECT id FROM apis WHERE id = ?; ]]
},
application_id = {
params = { "application_id" },
query = [[ SELECT id FROM applications WHERE id = ?; ]]
}
}
}
Plugins.super.new(self, properties)
end
-- @override
function Plugins:_marshall(t)
if type(t.value) == "table" then
t.value = cjson.encode(t.value)
end
return t
end
-- @override
function Plugins:_unmarshall(t)
-- deserialize values (tables) string to json
if type(t.value) == "string" then
t.value = cjson.decode(t.value)
end
-- remove application_id if null uuid
if t.application_id == constants.DATABASE_NULL_ID then
t.application_id = nil
end
return t
end
function Plugins:find_distinct()
-- Open session
local session, err = Plugins.super._open_session(self)
if err then
return nil, err
end
-- Execute query
local distinct_names = {}
for _, rows, page, err in session:execute(self._statements.select.query, nil, {auto_paging=true}) do
if err then
return nil, err
end
for _, v in ipairs(rows) do
-- Rows also contains other properites, so making sure it's a plugin
if v.name then
distinct_names[v.name] = true
end
end
end
-- Close session
local socket_err = Plugins.super._close_session(self, session)
if socket_err then
return nil, socket_err
end
local result = {}
for k,_ in pairs(distinct_names) do
table.insert(result, k)
end
return result, nil
end
return Plugins
|
Fixing nil concatenation in Plugins
|
Fixing nil concatenation in Plugins
|
Lua
|
apache-2.0
|
kyroskoh/kong,Kong/kong,ccyphers/kong,rafael/kong,smanolache/kong,beauli/kong,Vermeille/kong,ind9/kong,isdom/kong,vzaramel/kong,streamdataio/kong,xvaara/kong,ejoncas/kong,ejoncas/kong,li-wl/kong,icyxp/kong,kyroskoh/kong,vzaramel/kong,ajayk/kong,isdom/kong,rafael/kong,jebenexer/kong,akh00/kong,jerizm/kong,streamdataio/kong,shiprabehera/kong,ind9/kong,Mashape/kong,salazar/kong,Kong/kong,Kong/kong
|
a979e88c1c7ba8b2fe9e220c53a681a081b951bb
|
src/system/RenderableSystem.lua
|
src/system/RenderableSystem.lua
|
--RenderableSystem.lua
--[[
The RenderableSystem maintains references to several game-objects, each called a Scene.
This facilitates the swapping of viewscreens such as different maps, interface screens, and so on.
The RenderableSystem draws the root game object, then its children in sequence, recursively
]]--
local System = require 'src/System'
local Stack = require 'src/structure/Stack'
local RenderableSystem = System:extend("RenderableSystem",{
renderable_cache = nil,
last_publish_count = nil,
dirty = 10000,
font = nil,
planet_width = 1512
})
function RenderableSystem:init ( registry, targetCollection )
RenderableSystem.super.init(self, registry, targetCollection)
self.renderable_cache = {translation = {x = Stack:new(),y = Stack:new()}}
--love.graphics.setNewFont("assets/InputSansNarrow-Light.ttf",12)
end
function RenderableSystem:update( dt )
local function updateHeirarchy ( root , dt)
local renderable = root:getComponent('Renderable')
if renderable ~= nil then
if renderable.render ~= nil then
if renderable.render.rtype == "animation" then
renderable.render.ani:update(dt)
end
end
end
--Update children
for i, gid in ipairs(self.targetCollection:getChildren(root.uid)) do
updateHeirarchy(self.registry:get(gid), dt)
end
end
updateHeirarchy(self.registry:get(self.targetCollection:getRoot()), dt)
end
function RenderableSystem:renderComponent ( cached )
--Pop the coordinate system
local delta = cached.t
if cached.r == "PLZ_PUSH" and delta then
love.graphics.push()
self.renderable_cache.translation.x:push(delta.x)
self.renderable_cache.translation.y:push(delta.y)
love.graphics.translate(delta.x, delta.y)
end
--Do draw
--Renderable
local renderable = cached
if renderable ~= nil and cached.r ~= "PLZ_PUSH" and cached.r ~= "PLZ_POP" then
local xOffset = self.planet_width * self:getScreenWidthOffsets(renderable)
love.graphics.push()
love.graphics.translate(xOffset,0)
if renderable.render ~= nil then
if renderable.render.rtype == "sprite" then
love.graphics.draw(renderable.render.img, renderable.render.quad)
elseif renderable.render.rtype == "animation" then
renderable.render.ani:draw(renderable.render.sprite)
end
elseif renderable.polygon ~= nil then
local r, g, b, a = love.graphics.getColor()
love.graphics.setColor(renderable.backgroundcolor)
love.graphics.setLineWidth(3)
local tris = love.math.triangulate(renderable.polygon.vertices)
for i, v in ipairs(tris) do
love.graphics.polygon('fill', v)
end
love.graphics.setColor({r,g,b,a})
end
if renderable.text ~= nil then
if renderable.polygon then
love.graphics.printf(renderable.text,
renderable.polygon.vertices[1],
renderable.polygon.vertices[2],
renderable.polygon.vertices[3],'center')
else
love.graphics.print(renderable.text)
end
end
love.graphics.pop()
end
if cached.r == "PLZ_POP" and delta == "PLOXPOPIT" then
love.graphics.pop()
self.renderable_cache.translation.x:pop()
self.renderable_cache.translation.y:pop()
end
end
function RenderableSystem:getScreenWidthOffsets(renderable)
if not renderable then return 0 end
local tx = (self.renderable_cache.translation.x:total() or 0) *-1
local rw = 0
if renderable.polygon then
rw = renderable.polygon:getDimensions().w
elseif renderable.render then
if renderable.render.rtype == "sprite" then
_, _, rw = renderable.render.quad:getViewport()
elseif renderable.render.rtype == "animation" then
rw = renderable.render.ani.frameWidth
end
end
tx = tx - rw
return math.ceil(tx/ self.planet_width)
end
function RenderableSystem:drawHeirarchy ( root, big_list )
--Pop the coordinate system
local delta
if root:hasComponent('Transform') then
delta = root:getComponent('Transform')
if delta.x == 0 and delta.y == 0 then
delta = nil
else
table.insert(big_list, {r = "PLZ_PUSH", t = delta})
love.graphics.push()
love.graphics.translate(delta.x, delta.y)
end
end
--Do draw
--Renderable
local renderable = root:getComponent('Renderable')
if renderable ~= nil then
if renderable.render ~= nil then
if renderable.render.rtype == "sprite" then
love.graphics.draw(renderable.render.img, renderable.render.quad)
elseif renderable.render.rtype == "animation" then
renderable.render.ani:draw(renderable.render.sprite)
end
elseif renderable.polygon ~= nil then
local r, g, b, a = love.graphics.getColor()
love.graphics.setColor(renderable.backgroundcolor)
love.graphics.setLineWidth(3)
local tris = love.math.triangulate(renderable.polygon.vertices)
for i, v in ipairs(tris) do
love.graphics.polygon('fill', v)
end
love.graphics.setColor({r,g,b,a})
end
if renderable.text ~= nil then
if renderable.polygon then
love.graphics.printf(renderable.text,
renderable.polygon.vertices[1],
renderable.polygon.vertices[2],
renderable.polygon.vertices[3],'center')
else
love.graphics.print(renderable.text)
end
end
end
table.insert(big_list, renderable )
--Draw children
for i, gid in ipairs(self.targetCollection:getChildren(root.uid)) do
self:drawHeirarchy(self.registry:get(gid), big_list)
end
--Unpop the coordinate system
if delta ~= nil then
love.graphics.pop()
table.insert(big_list, {r = "PLZ_POP", t = "PLOXPOPIT"})
end
return big_list
end
function RenderableSystem:draw ()
if self.dirty > 10 then
self.cache = self:drawHeirarchy(self.registry:get(self.targetCollection:getRoot()), {})
self.dirty = 0
else
for i = 1, #self.cache do
self:renderComponent(self.cache[i])
end
self.dirty = self.dirty + 1
--if math.random() > 0.99 then self.dirty = true end
end
end
return RenderableSystem
|
--RenderableSystem.lua
--[[
The RenderableSystem maintains references to several game-objects, each called a Scene.
This facilitates the swapping of viewscreens such as different maps, interface screens, and so on.
The RenderableSystem draws the root game object, then its children in sequence, recursively
]]--
local System = require 'src/System'
local Stack = require 'src/structure/Stack'
local RenderableSystem = System:extend("RenderableSystem",{
renderable_cache = nil,
last_publish_count = nil,
dirty = 10000,
font = nil,
planet_width = 1512
})
function RenderableSystem:init ( registry, targetCollection )
RenderableSystem.super.init(self, registry, targetCollection)
self.renderable_cache = {translation = {x = Stack:new(),y = Stack:new()}}
--love.graphics.setNewFont("assets/InputSansNarrow-Light.ttf",12)
end
function RenderableSystem:update( dt )
local function updateHeirarchy ( root , dt)
local renderable = root:getComponent('Renderable')
if renderable ~= nil then
if renderable.render ~= nil then
if renderable.render.rtype == "animation" then
renderable.render.ani:update(dt)
end
end
end
--Update children
for i, gid in ipairs(self.targetCollection:getChildren(root.uid)) do
updateHeirarchy(self.registry:get(gid), dt)
end
end
updateHeirarchy(self.registry:get(self.targetCollection:getRoot()), dt)
end
function RenderableSystem:renderComponent ( cached )
--Pop the coordinate system
local delta = cached.t
if cached.r == "PLZ_PUSH" and delta then
love.graphics.push()
self.renderable_cache.translation.x:push(delta.x)
self.renderable_cache.translation.y:push(delta.y)
love.graphics.translate(delta.x, delta.y)
end
--Do draw
--Renderable
local renderable = cached
if renderable ~= nil and cached.r ~= "PLZ_PUSH" and cached.r ~= "PLZ_POP" then
local xOffset = self.planet_width * self:getScreenWidthOffsets(renderable)
love.graphics.push()
love.graphics.translate(xOffset,0)
if renderable.render ~= nil then
if renderable.render.rtype == "sprite" then
love.graphics.draw(renderable.render.img, renderable.render.quad)
elseif renderable.render.rtype == "animation" then
renderable.render.ani:draw(renderable.render.sprite)
end
elseif renderable.polygon ~= nil then
local r, g, b, a = love.graphics.getColor()
love.graphics.setColor(renderable.backgroundcolor)
love.graphics.setLineWidth(3)
local tris = love.math.triangulate(renderable.polygon.vertices)
for i, v in ipairs(tris) do
love.graphics.polygon('fill', v)
end
love.graphics.setColor({r,g,b,a})
end
if renderable.text ~= nil then
if renderable.polygon then
love.graphics.printf(renderable.text,
renderable.polygon.vertices[1],
renderable.polygon.vertices[2],
renderable.polygon.vertices[3],'center')
else
love.graphics.print(renderable.text)
end
end
love.graphics.pop()
end
if cached.r == "PLZ_POP" and delta == "PLOXPOPIT" then
love.graphics.pop()
self.renderable_cache.translation.x:pop()
self.renderable_cache.translation.y:pop()
end
end
function RenderableSystem:getScreenWidthOffsets(renderable)
if not renderable then return 0 end
local tx = (self.renderable_cache.translation.x:total() or 0) *-1
local rw = 0
if renderable.polygon then
rw = renderable.polygon:getDimensions().w
elseif renderable.render then
if renderable.render.rtype == "sprite" then
_, _, rw = renderable.render.quad:getViewport()
elseif renderable.render.rtype == "animation" then
rw = renderable.render.ani.frameWidth
end
end
tx = tx - rw
return math.ceil(tx/ self.planet_width)
end
function RenderableSystem:drawHeirarchy ( root, big_list )
--Pop the coordinate system
local delta
if root:hasComponent('Transform') then
delta = root:getComponent('Transform')
if delta.x == 0 and delta.y == 0 then
delta = nil
else
table.insert(big_list, {r = "PLZ_PUSH", t = delta})
love.graphics.push()
love.graphics.translate(delta.x, delta.y)
end
end
--Do draw
--Renderable
local renderable = root:getComponent('Renderable')
if renderable ~= nil then
if renderable.render ~= nil then
if renderable.render.rtype == "sprite" then
love.graphics.draw(renderable.render.img, renderable.render.quad)
elseif renderable.render.rtype == "animation" then
renderable.render.ani:draw(renderable.render.sprite)
end
elseif renderable.polygon ~= nil then
local r, g, b, a = love.graphics.getColor()
love.graphics.setColor(renderable.backgroundcolor)
love.graphics.setLineWidth(3)
local tris = love.math.triangulate(renderable.polygon.vertices)
for i, v in ipairs(tris) do
love.graphics.polygon('fill', v)
end
love.graphics.setColor({r,g,b,a})
end
if renderable.text ~= nil then
if renderable.polygon then
love.graphics.printf(renderable.text,
renderable.polygon.vertices[1],
renderable.polygon.vertices[2],
renderable.polygon.vertices[3],'center')
else
love.graphics.print(renderable.text)
end
end
end
table.insert(big_list, renderable )
--Draw children
for i, gid in ipairs(self.targetCollection:getChildren(root.uid)) do
self:drawHeirarchy(self.registry:get(gid), big_list)
end
--Unpop the coordinate system
if delta ~= nil then
love.graphics.pop()
table.insert(big_list, {r = "PLZ_POP", t = "PLOXPOPIT"})
end
return big_list
end
function RenderableSystem:draw ()
if self.cache == nil or self.dirty > 3 then
self.cache = self:drawHeirarchy(self.registry:get(self.targetCollection:getRoot()), {})
self.dirty = 0
end
for i = 1, #self.cache do
self:renderComponent(self.cache[i])
end
self.dirty = self.dirty + 1
end
return RenderableSystem
|
Fix flicker
|
Fix flicker
|
Lua
|
mit
|
Sewerbird/Helios2400,Sewerbird/Helios2400,Sewerbird/Helios2400
|
5b04475acdf2df5add895108247e2b13ec882ba1
|
src/nodes/floor.lua
|
src/nodes/floor.lua
|
local Floor = {}
Floor.__index = Floor
Floor.isFloor = true
function Floor.new(node, collider)
local floor = {}
setmetatable(floor, Floor)
--If the node is a polyline, we need to draw a polygon rather than rectangle
if node.polyline or node.polygon then
local polygon = node.polyline or node.polygon
local vertices = {}
for k,vertex in ipairs(polygon) do
-- Determine whether this is an X or Y coordinate
if k % 2 == 0 then
table.insert(vertices, vertex + node.y)
else
table.insert(vertices, vertex + node.x)
end
end
floor.bb = collider:addPolygon( unpack(vertices) )
-- Stash the polyline on the collider object for future reference
floor.bb.polyline = polygon
else
floor.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
floor.bb.polyline = nil
end
floor.node = node
floor.bb.node = floor
collider:setPassive(floor.bb)
floor.isSolid = true
floor.x = node.x
floor.y = node.y
floor.width = node.width
floor.height = node.height
return floor
end
function Floor:collide(node, dt, mtv_x, mtv_y)
if not (node.floor_pushback or node.wall_pushback) then return end
if node.velocity.y < 0 and mtv_x == 0 then
-- don't collide when the player is going upwards above the floor
-- This happens when enemies hit the player
return
end
local _, wy1, _, wy2 = self.bb:bbox()
local px1, py1, px2, py2 = node.bb:bbox()
local distance = math.abs(node.velocity.y * dt) + 0.10
if self.bb.polyline
and node.floor_pushback
and node.velocity.y >= 0
-- Prevent the player from being treadmilled through an object
and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then
-- Use the MTV to keep players feet on the ground,
-- fudge the Y a bit to prevent falling into steep angles
node:floor_pushback(self, (py1 - 4) + mtv_y)
return
end
if mtv_x ~= 0
and node.wall_pushback
and wy1 + 2 < node.position.y + node.height then
--prevent horizontal movement
node:wall_pushback(self, node.position.x + mtv_x)
end
if mtv_y < 0 and node.floor_pushback then
--push back up
node:floor_pushback(self, wy1 - node.height)
end
-- floor doesn't support a ceiling_pushback
end
return Floor
|
local Floor = {}
Floor.__index = Floor
Floor.isFloor = true
function Floor.new(node, collider)
local floor = {}
setmetatable(floor, Floor)
--If the node is a polyline, we need to draw a polygon rather than rectangle
if node.polyline or node.polygon then
local polygon = node.polyline or node.polygon
local vertices = {}
for k,vertex in ipairs(polygon) do
-- Determine whether this is an X or Y coordinate
if k % 2 == 0 then
table.insert(vertices, vertex + node.y)
else
table.insert(vertices, vertex + node.x)
end
end
floor.bb = collider:addPolygon( unpack(vertices) )
-- Stash the polyline on the collider object for future reference
floor.bb.polyline = polygon
else
floor.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
floor.bb.polyline = nil
end
floor.node = node
floor.bb.node = floor
collider:setPassive(floor.bb)
floor.isSolid = true
floor.x = node.x
floor.y = node.y
floor.width = node.width
floor.height = node.height
return floor
end
function Floor:collide(node, dt, mtv_x, mtv_y)
if not (node.floor_pushback or node.wall_pushback) then return end
if node.velocity.y < 0 and mtv_x == 0 then
-- don't collide when the player is going upwards above the floor
-- This happens when enemies hit the player
return
end
local _, wy1, _, wy2 = self.bb:bbox()
local px1, py1, px2, py2 = node.bb:bbox()
local distance = math.abs(node.velocity.y * dt) + 0.10
if self.bb.polyline
and node.floor_pushback
and node.velocity.y >= 0
-- Prevent the player from being treadmilled through an object
and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then
-- Use the MTV to keep players feet on the ground,
-- fudge the Y a bit to prevent falling into steep angles
node:floor_pushback(self, (py1 - 4) + mtv_y)
return
end
if mtv_x ~= 0
and node.wall_pushback
and wy1 + 2 < node.position.y + node.height then
--prevent horizontal movement
node:wall_pushback(self, node.position.x + mtv_x)
end
if mtv_y < 0 and node.floor_pushback then
--push back up
if node.position and math.abs(node.position.y- (wy1 - node.height))>100 then
print("Tried to set y:",node.position.y, " to y:", (wy1 - node.height), " this high a y change due to floor pushback is unlikely, dismissing")
else
node:floor_pushback(self, wy1 - node.height)
end
end
-- floor doesn't support a ceiling_pushback
end
return Floor
|
check if floorpushup is over 100 and ignore it, in case it is, DEBUG SOLUTION ONLY, NOT A REAL FIX
|
check if floorpushup is over 100 and ignore it, in case it is, DEBUG SOLUTION ONLY, NOT A REAL FIX
|
Lua
|
mit
|
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua
|
5661de59c6947c3b8a8c13d833f9138ef41ff8a8
|
plugins/mod_saslauth.lua
|
plugins/mod_saslauth.lua
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st = require "util.stanza";
local sm_bind_resource = require "core.sessionmanager".bind_resource;
local sm_make_authenticated = require "core.sessionmanager".make_authenticated;
local base64 = require "util.encodings".base64;
local nodeprep = require "util.encodings".stringprep.nodeprep;
local datamanager_load = require "util.datamanager".load;
local usermanager_validate_credentials = require "core.usermanager".validate_credentials;
local usermanager_get_supported_methods = require "core.usermanager".get_supported_methods;
local usermanager_user_exists = require "core.usermanager".user_exists;
local usermanager_get_password = require "core.usermanager".get_password;
local t_concat, t_insert = table.concat, table.insert;
local tostring = tostring;
local jid_split = require "util.jid".split
local md5 = require "util.hashes".md5;
local config = require "core.configmanager";
local secure_auth_only = config.get(module:get_host(), "core", "c2s_require_encryption") or config.get(module:get_host(), "core", "require_encryption");
local log = module._log;
local xmlns_sasl ='urn:ietf:params:xml:ns:xmpp-sasl';
local xmlns_bind ='urn:ietf:params:xml:ns:xmpp-bind';
local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas';
local new_sasl
if config.get(module:get_host(), "core", "cyrus_service_name") then
cyrus_new = require "util.sasl_cyrus".new;
new_sasl = function(realm)
return cyrus_new(realm, config.get(module:get_host(), "core", "cyrus_service_name"))
end
else
new_sasl = require "util.sasl".new;
end
default_authentication_profile = {
plain = function(username, realm)
local prepped_username = nodeprep(username);
if not prepped_username then
log("debug", "NODEprep failed on username: %s", username);
return "", nil;
end
local password = usermanager_get_password(prepped_username, realm);
if not password then
return "", nil;
end
return password, true;
end
};
anonymous_authentication_profile = {
anonymous = function(username, realm)
return true; -- for normal usage you should always return true here
end
}
local function build_reply(status, ret, err_msg)
local reply = st.stanza(status, {xmlns = xmlns_sasl});
if status == "challenge" then
log("debug", "%s", ret or "");
reply:text(base64.encode(ret or ""));
elseif status == "failure" then
reply:tag(ret):up();
if err_msg then reply:tag("text"):text(err_msg); end
elseif status == "success" then
log("debug", "%s", ret or "");
reply:text(base64.encode(ret or ""));
else
module:log("error", "Unknown sasl status: %s", status);
end
return reply;
end
local function handle_status(session, status)
if status == "failure" then
session.sasl_handler = session.sasl_handler:clean_clone();
elseif status == "success" then
local username = nodeprep(session.sasl_handler.username);
if not username then -- TODO move this to sessionmanager
module:log("warn", "SASL succeeded but we didn't get a username!");
session.sasl_handler = nil;
session:reset_stream();
return;
end
sm_make_authenticated(session, session.sasl_handler.username);
session.sasl_handler = nil;
session:reset_stream();
end
end
local function sasl_handler(session, stanza)
if stanza.name == "auth" then
-- FIXME ignoring duplicates because ejabberd does
if config.get(session.host or "*", "core", "anonymous_login") then
if stanza.attr.mechanism ~= "ANONYMOUS" then
return session.send(build_reply("failure", "invalid-mechanism"));
end
elseif stanza.attr.mechanism == "ANONYMOUS" then
return session.send(build_reply("failure", "mechanism-too-weak"));
end
local valid_mechanism = session.sasl_handler:select(stanza.attr.mechanism);
if not valid_mechanism then
return session.send(build_reply("failure", "invalid-mechanism"));
end
if secure_auth_only and not session.secure then
return session.send(build_reply("failure", "encryption-required"));
end
elseif not session.sasl_handler then
return; -- FIXME ignoring out of order stanzas because ejabberd does
end
local text = stanza[1];
if text then
text = base64.decode(text);
log("debug", "%s", text);
if not text then
session.sasl_handler = nil;
session.send(build_reply("failure", "incorrect-encoding"));
return;
end
end
local status, ret, err_msg = session.sasl_handler:process(text);
handle_status(session, status);
local s = build_reply(status, ret, err_msg);
log("debug", "sasl reply: %s", tostring(s));
session.send(s);
end
module:add_handler("c2s_unauthed", "auth", xmlns_sasl, sasl_handler);
module:add_handler("c2s_unauthed", "abort", xmlns_sasl, sasl_handler);
module:add_handler("c2s_unauthed", "response", xmlns_sasl, sasl_handler);
local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' };
local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' };
local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' };
module:add_event_hook("stream-features",
function (session, features)
if not session.username then
if secure_auth_only and not session.secure then
return;
end
if module:get_option("anonymous_login") then
session.sasl_handler = new_sasl(session.host, anonymous_authentication_profile);
else
session.sasl_handler = new_sasl(session.host, default_authentication_profile);
if not (module:get_option("allow_unencrypted_plain_auth")) and not session.secure then
session.sasl_handler:forbidden({"PLAIN"});
end
end
features:tag("mechanisms", mechanisms_attr);
for k, v in pairs(session.sasl_handler:mechanisms()) do
features:tag("mechanism"):text(v):up();
end
features:up();
else
features:tag("bind", bind_attr):tag("required"):up():up();
features:tag("session", xmpp_session_attr):tag("optional"):up():up();
end
end);
module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind",
function (session, stanza)
log("debug", "Client requesting a resource bind");
local resource;
if stanza.attr.type == "set" then
local bind = stanza.tags[1];
if bind and bind.attr.xmlns == xmlns_bind then
resource = bind:child_with_name("resource");
if resource then
resource = resource[1];
end
end
end
local success, err_type, err, err_msg = sm_bind_resource(session, resource);
if not success then
session.send(st.error_reply(stanza, err_type, err, err_msg));
else
session.send(st.reply(stanza)
:tag("bind", { xmlns = xmlns_bind})
:tag("jid"):text(session.full_jid));
end
end);
module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session",
function (session, stanza)
log("debug", "Client requesting a session");
session.send(st.reply(stanza));
end);
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local st = require "util.stanza";
local sm_bind_resource = require "core.sessionmanager".bind_resource;
local sm_make_authenticated = require "core.sessionmanager".make_authenticated;
local base64 = require "util.encodings".base64;
local nodeprep = require "util.encodings".stringprep.nodeprep;
local datamanager_load = require "util.datamanager".load;
local usermanager_validate_credentials = require "core.usermanager".validate_credentials;
local usermanager_get_supported_methods = require "core.usermanager".get_supported_methods;
local usermanager_user_exists = require "core.usermanager".user_exists;
local usermanager_get_password = require "core.usermanager".get_password;
local t_concat, t_insert = table.concat, table.insert;
local tostring = tostring;
local jid_split = require "util.jid".split
local md5 = require "util.hashes".md5;
local config = require "core.configmanager";
local secure_auth_only = config.get(module:get_host(), "core", "c2s_require_encryption") or config.get(module:get_host(), "core", "require_encryption");
local log = module._log;
local xmlns_sasl ='urn:ietf:params:xml:ns:xmpp-sasl';
local xmlns_bind ='urn:ietf:params:xml:ns:xmpp-bind';
local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas';
local new_sasl
if config.get(module:get_host(), "core", "cyrus_service_name") then
cyrus_new = require "util.sasl_cyrus".new;
new_sasl = function(realm)
return cyrus_new(realm, config.get(module:get_host(), "core", "cyrus_service_name"))
end
else
new_sasl = require "util.sasl".new;
end
default_authentication_profile = {
plain = function(username, realm)
local prepped_username = nodeprep(username);
if not prepped_username then
log("debug", "NODEprep failed on username: %s", username);
return "", nil;
end
local password = usermanager_get_password(prepped_username, realm);
if not password then
return "", nil;
end
return password, true;
end
};
anonymous_authentication_profile = {
anonymous = function(username, realm)
return true; -- for normal usage you should always return true here
end
}
local function build_reply(status, ret, err_msg)
local reply = st.stanza(status, {xmlns = xmlns_sasl});
if status == "challenge" then
log("debug", "%s", ret or "");
reply:text(base64.encode(ret or ""));
elseif status == "failure" then
reply:tag(ret):up();
if err_msg then reply:tag("text"):text(err_msg); end
elseif status == "success" then
log("debug", "%s", ret or "");
reply:text(base64.encode(ret or ""));
else
module:log("error", "Unknown sasl status: %s", status);
end
return reply;
end
local function handle_status(session, status)
if status == "failure" then
session.sasl_handler = session.sasl_handler:clean_clone();
elseif status == "success" then
local username = nodeprep(session.sasl_handler.username);
if not username then -- TODO move this to sessionmanager
module:log("warn", "SASL succeeded but we didn't get a username!");
session.sasl_handler = nil;
session:reset_stream();
return;
end
sm_make_authenticated(session, session.sasl_handler.username);
session.sasl_handler = nil;
session:reset_stream();
end
end
local function sasl_handler(session, stanza)
if stanza.name == "auth" then
-- FIXME ignoring duplicates because ejabberd does
if config.get(session.host or "*", "core", "anonymous_login") then
if stanza.attr.mechanism ~= "ANONYMOUS" then
return session.send(build_reply("failure", "invalid-mechanism"));
end
elseif stanza.attr.mechanism == "ANONYMOUS" then
return session.send(build_reply("failure", "mechanism-too-weak"));
end
local valid_mechanism = session.sasl_handler:select(stanza.attr.mechanism);
if not valid_mechanism then
return session.send(build_reply("failure", "invalid-mechanism"));
end
if secure_auth_only and not session.secure then
return session.send(build_reply("failure", "encryption-required"));
end
elseif not session.sasl_handler then
return; -- FIXME ignoring out of order stanzas because ejabberd does
end
local text = stanza[1];
if text then
text = base64.decode(text);
log("debug", "%s", text); -- FIXME: binary output will screw up the terminal
if not text then
session.sasl_handler = nil;
session.send(build_reply("failure", "incorrect-encoding"));
return;
end
end
local status, ret, err_msg = session.sasl_handler:process(text);
handle_status(session, status);
local s = build_reply(status, ret, err_msg);
log("debug", "sasl reply: %s", tostring(s));
session.send(s);
end
module:add_handler("c2s_unauthed", "auth", xmlns_sasl, sasl_handler);
module:add_handler("c2s_unauthed", "abort", xmlns_sasl, sasl_handler);
module:add_handler("c2s_unauthed", "response", xmlns_sasl, sasl_handler);
local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' };
local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' };
local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' };
module:add_event_hook("stream-features",
function (session, features)
if not session.username then
if secure_auth_only and not session.secure then
return;
end
if module:get_option("anonymous_login") then
session.sasl_handler = new_sasl(session.host, anonymous_authentication_profile);
else
session.sasl_handler = new_sasl(session.host, default_authentication_profile);
if not (module:get_option("allow_unencrypted_plain_auth")) and not session.secure then
session.sasl_handler:forbidden({"PLAIN"});
end
end
features:tag("mechanisms", mechanisms_attr);
for k, v in pairs(session.sasl_handler:mechanisms()) do
features:tag("mechanism"):text(v):up();
end
features:up();
else
features:tag("bind", bind_attr):tag("required"):up():up();
features:tag("session", xmpp_session_attr):tag("optional"):up():up();
end
end);
module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind",
function (session, stanza)
log("debug", "Client requesting a resource bind");
local resource;
if stanza.attr.type == "set" then
local bind = stanza.tags[1];
if bind and bind.attr.xmlns == xmlns_bind then
resource = bind:child_with_name("resource");
if resource then
resource = resource[1];
end
end
end
local success, err_type, err, err_msg = sm_bind_resource(session, resource);
if not success then
session.send(st.error_reply(stanza, err_type, err, err_msg));
else
session.send(st.reply(stanza)
:tag("bind", { xmlns = xmlns_bind})
:tag("jid"):text(session.full_jid));
end
end);
module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session",
function (session, stanza)
log("debug", "Client requesting a session");
session.send(st.reply(stanza));
end);
|
added comment to remind us to fix binary output breaking the terminal later
|
added comment to remind us to fix binary output breaking the terminal
later
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
cc036b1f829d762ce900570e80fdc0283e23c9a6
|
Peripherals/WEB/init.lua
|
Peripherals/WEB/init.lua
|
local perpath = select(1,...) --The path to the web folder
local bit = require("bit")
local events = require("Engine.events")
local json = require("Engine.JSON")
local thread = love.thread.newThread(perpath.."webthread.lua")
local to_channel = love.thread.getChannel("To_WebThread")
local from_channel = love.thread.getChannel("From_WebThread")
local to_counter = 0
local from_counter = 0
to_channel:clear()
from_channel:clear()
thread:start()
local function clearFuncsFromTable(t)
for k,v in pairs(t) do
if type(v) == "function" then
t[k] = nil
elseif type(v) == "table" then
clearFuncsFromTable(v)
end
end
end
return function(config) --A function that creates a new WEB peripheral.
local CPUKit = config.CPUKit
if not CPUKit then error("WEB Peripheral can't work without the CPUKit passed") end
local indirect = {} --List of functions that requires custom coroutine.resume
local devkit = {}
local WEB = {}
function WEB.send(url,args)
if type(url) ~= "string" then return false, "URL must be a string, provided: "..type(url) end
local args = args or {}
if type(args) ~= "table" then return false, "Args Must be a table or nil, provided: "..type(args) end
clearFuncsFromTable(args) --Since JSON can't encode functions !
args = json:encode(args)
to_channel:push({url,args})
to_counter = to_counter + 1
return true, to_counter --Return the request ID
end
--Taken from: https://github.com/dan200/ComputerCraft/blob/master/src/main/resources/assets/computercraft/lua/rom/apis/textutils.lua
function WEB.urlEncode(str)
if type(str) ~= "string" then return false, "STR must be a string, provided: "..type(str) end
str = string.gsub(str, "\n", "\r\n")
tr = string.gsub(str, "([^A-Za-z0-9 %-%_%.])", function(c)
local n = string.byte(c)
if n < 128 then
-- ASCII
return string.format("%%%02X", n)
else
-- Non-ASCII (encode as UTF-8)
return string.format("%%%02X", 192 + bit.band( bit.arshift(n,6), 31 )) ..
string.format("%%%02X", 128 + bit.band( n, 63 ))
end
end)
str = string.gsub(str, " ", "+")
return true,str
end
events:register("love:update",function(dt)
local result = from_channel:pop()
if result then
from_counter = from_counter +1
local data = json:decode(result)
CPUKit.triggerEvent("webrequest",from_counter,unpack(data))
end
end)
return WEB, devkit, indirect
end
|
local perpath = select(1,...) --The path to the web folder
local bit = require("bit")
local events = require("Engine.events")
local json = require("Engine.JSON")
local thread = love.thread.newThread(perpath.."webthread.lua")
local to_channel = love.thread.getChannel("To_WebThread")
local from_channel = love.thread.getChannel("From_WebThread")
local to_counter = 0
local from_counter = 0
to_channel:clear()
from_channel:clear()
thread:start()
local function clearFuncsFromTable(t)
for k,v in pairs(t) do
if type(v) == "function" then
t[k] = nil
elseif type(v) == "table" then
clearFuncsFromTable(v)
end
end
end
return function(config) --A function that creates a new WEB peripheral.
local CPUKit = config.CPUKit
if not CPUKit then error("WEB Peripheral can't work without the CPUKit passed") end
local indirect = {} --List of functions that requires custom coroutine.resume
local devkit = {}
local WEB = {}
function WEB.send(url,args)
if type(url) ~= "string" then return false, "URL must be a string, provided: "..type(url) end
local args = args or {}
if type(args) ~= "table" then return false, "Args Must be a table or nil, provided: "..type(args) end
clearFuncsFromTable(args) --Since JSON can't encode functions !
args = json:encode(args)
to_channel:push({url,args})
to_counter = to_counter + 1
return true, to_counter --Return the request ID
end
--Taken from: https://github.com/dan200/ComputerCraft/blob/master/src/main/resources/assets/computercraft/lua/rom/apis/textutils.lua
function WEB.urlEncode(str)
if type(str) ~= "string" then return false, "STR must be a string, provided: "..type(str) end
str = string.gsub(str, "\n", "\r\n")
str = string.gsub(str, "\r\r\n", "\r\n")
tr = string.gsub(str, "([^A-Za-z0-9 %-%_%.])", function(c)
local n = string.byte(c)
if n < 128 then
-- ASCII
return string.format("%%%02X", n)
else
-- Non-ASCII (encode as UTF-8)
return string.format("%%%02X", 192 + bit.band( bit.arshift(n,6), 31 )) ..
string.format("%%%02X", 128 + bit.band( n, 63 ))
end
end)
str = string.gsub(str, "%+", "%%2b")
str = string.gsub(str, " ", "+")
return true,str
end
events:register("love:update",function(dt)
local result = from_channel:pop()
if result then
from_counter = from_counter +1
local data = json:decode(result)
CPUKit.triggerEvent("webrequest",from_counter,unpack(data))
end
end)
return WEB, devkit, indirect
end
|
Bugfixed "+" is converted to a space when uploading to the internet
|
Bugfixed "+" is converted to a space when uploading to the internet
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
401f2ac0df05c9754bdc98cd99d25601eb4f289c
|
CCLib/src/java/lang/native/Computer.lua
|
CCLib/src/java/lang/native/Computer.lua
|
natives["cc.Computer"] = natives["cc.Computer"] or {}
natives["cc.Computer"]["shutdown()V"] = function()
os.shutdown()
end
natives["cc.Computer"]["restart()V"] = function()
os.restart()
end
natives["cc.Computer"]["sleep(D)V"] = function(s)
sleep(s)
end
natives["cc.Computer"]["isTurtle()Z"] = function()
return turtle ~= nil
end
natives["cc.Computer"]["getTime()I"] = function()
return os.time()
end
natives["cc.Computer"]["getClock()F"] = function()
return os.clock()
end
natives["cc.Computer"]["pullEvent()Lcc/Event;"] = function()
local typ, args
(function(t, arg0, ...)
typ = toJString(t)
args = { ... }
args.length = #args
args[1] = arg0
end)(os.pullEvent())
if args[1] then
local v = args[1]
if type(v) == "string" then
args[1] = toJString(v)
elseif type(v) == "number" then
args[1] = wrapPrimitive(v, "D")
end
args.length = args.length + 1
end
for i = 2, args.length do
local v = args[i]
if type(v) == "string" then
args[i] = toJString(v)
elseif type(v) == "number" then
args[i] = wrapPrimitive(v, "D")
end
end
local eventClass = classByName("cc.Event")
local event = newInstance(eventClass)
local argsRef = { #args, classByName("java.lang.Object"), args }
findMethod(eventClass, "<init>(Ljava/lang/String;[Ljava/lang/Object;)V")[1](event, typ, argsRef)
return event
end
natives["cc.Computer"]["pullEvent(Ljava/lang/String;)Lcc/Event;"] = function(filter)
local typ, args
(function(t, arg0, ...)
typ = toJString(t)
args = { ... }
args.length = #args
args[1] = arg0
end)(os.pullEvent(toLString(filter)))
if args[1] then
local v = args[1]
if type(v) == "string" then
args[1] = toJString(v)
elseif type(v) == "number" then
args[1] = wrapPrimitive(v, "D")
end
args.length = args.length + 1
end
for i = 2, args.length do
local v = args[i]
if type(v) == "string" then
args[i] = toJString(v)
elseif type(v) == "number" then
args[i] = wrapPrimitive(v, "D")
end
end
local eventClass = classByName("cc.Event")
local event = newInstance(eventClass)
local argsRef = { #args, classByName("java.lang.Object"), args }
findMethod(eventClass, "<init>(Ljava/lang/String;[Ljava/lang/Object;)V")[1](event, typ, argsRef)
return event
end
|
natives["cc.Computer"] = natives["cc.Computer"] or {}
natives["cc.Computer"]["shutdown()V"] = function()
os.shutdown()
end
natives["cc.Computer"]["restart()V"] = function()
os.restart()
end
natives["cc.Computer"]["sleep(D)V"] = function(s)
sleep(s)
end
natives["cc.Computer"]["isTurtle()Z"] = function()
return turtle ~= nil
end
natives["cc.Computer"]["getTime()I"] = function()
return os.time()
end
natives["cc.Computer"]["getClock()F"] = function()
return os.clock()
end
natives["cc.Computer"]["pullEvent()Lcc/Event;"] = function()
local typ, args
(function(t, arg0, ...)
typ = toJString(t)
args = { ... }
args.length = #args
args[1] = arg0
end)(os.pullEvent())
if args[1] then
local v = args[1]
if type(v) == "string" then
args[1] = toJString(v)
elseif type(v) == "number" then
args[1] = wrapPrimitive(v, "D")
end
args.length = args.length + 1
end
for i = 2, args.length do
local v = args[i]
if type(v) == "string" then
args[i] = toJString(v)
elseif type(v) == "number" then
args[i] = wrapPrimitive(v, "D")
end
end
local eventClass = classByName("cc.Event")
local event = newInstance(eventClass)
local argsRef = newArray(getArrayClass("[java.lang.Object;"), #args)
argsRef[5] = args
findMethod(eventClass, "<init>(Ljava/lang/String;[Ljava/lang/Object;)V")[1](event, typ, argsRef)
return event
end
natives["cc.Computer"]["pullEvent(Ljava/lang/String;)Lcc/Event;"] = function(filter)
local typ, args
(function(t, arg0, ...)
typ = toJString(t)
args = { ... }
args.length = #args
args[1] = arg0
end)(os.pullEvent(toLString(filter)))
if args[1] then
local v = args[1]
if type(v) == "string" then
args[1] = toJString(v)
elseif type(v) == "number" then
args[1] = wrapPrimitive(v, "D")
end
args.length = args.length + 1
end
for i = 2, args.length do
local v = args[i]
if type(v) == "string" then
args[i] = toJString(v)
elseif type(v) == "number" then
args[i] = wrapPrimitive(v, "D")
end
end
local eventClass = classByName("cc.Event")
local event = newInstance(eventClass)
local argsRef = { #args, classByName("java.lang.Object"), args }
findMethod(eventClass, "<init>(Ljava/lang/String;[Ljava/lang/Object;)V")[1](event, typ, argsRef)
return event
end
|
Fixed pullEvent
|
Fixed pullEvent
New array system, didn't see this.
|
Lua
|
mit
|
Team-CC-Corp/JVML-JIT,apemanzilla/JVML-JIT
|
2c21fecead35daf22107cc8f47c7ec510aced200
|
src/luarocks/doc.lua
|
src/luarocks/doc.lua
|
--- Module implementing the LuaRocks "doc" command.
-- Shows documentation for an installed rock.
module("luarocks.doc", package.seeall)
local util = require("luarocks.util")
local show = require("luarocks.show")
local path = require("luarocks.path")
local dir = require("luarocks.dir")
local fetch = require("luarocks.fetch")
local fs = require("luarocks.fs")
help_summary = "Shows documentation for an installed rock."
help = [[
<argument> is an existing package name.
Without any flags, tries to load the documentation
using a series of heuristics.
With these flags, return only the desired information:
--home Open the home page of project.
--list List documentation files only.
For more information about a rock, see the 'show' command.
]]
--- Driver function for "doc" command.
-- @param name or nil: an existing package name.
-- @param version string or nil: a version may also be passed.
-- @return boolean: True if succeeded, nil on errors.
function run(...)
local flags, name, version = util.parse_flags(...)
if not name then
return nil, "Argument missing. "..util.see_help("doc")
end
local repo
name, version, repo = show.pick_installed_rock(name, version, flags["tree"])
if not name then
return nil, version
end
local rockspec, err = fetch.load_local_rockspec(path.rockspec_file(name, version, repo))
if not rockspec then return nil,err end
local descript = rockspec.description or {}
if flags["home"] then
if not descript.homepage then
return nil, "No 'homepage' field in rockspec for "..name.." "..version
end
util.printout("Opening "..descript.homepage.." ...")
fs.browser(descript.homepage)
return true
end
local directory = path.install_dir(name,version,repo)
local docdir
local directories = { "doc", "docs" }
for _, d in ipairs(directories) do
local dirname = dir.path(directory, d)
if fs.is_dir(dirname) then
docdir = dirname
break
end
end
docdir = dir.normalize(docdir):gsub("/+", "/")
if not docdir then
if descript.homepage then
util.printout("Local documentation directory not found -- opening "..descript.homepage.." ...")
fs.browser(descript.homepage)
return true
end
return nil, "Documentation directory not found for "..name.." "..version
end
local files = fs.find(docdir)
local htmlpatt = "%.html?$"
local extensions = { htmlpatt, "%.md$", "%.txt$", "%.textile$", "" }
local basenames = { "index", "readme", "manual" }
local porcelain = flags["porcelain"]
if #files > 0 then
util.title("Documentation files for "..name.." "..version, porcelain)
if porcelain then
for _, file in ipairs(files) do
util.printout(docdir.."/"..file)
end
else
util.printout(docdir.."/")
for _, file in ipairs(files) do
util.printout("\t"..file)
end
end
end
if flags["list"] then
return true
end
for _, extension in ipairs(extensions) do
for _, basename in ipairs(basenames) do
local filename = basename..extension
local found
for _, file in ipairs(files) do
if file:lower():match(filename) and ((not found) or #file < #found) then
found = file
end
end
if found then
local pathname = dir.path(docdir, found)
util.printout()
util.printout("Opening "..pathname.." ...")
util.printout()
local ok = fs.browser(pathname)
if not ok and not pathname:match(htmlpatt) then
local fd = io.open(pathname, "r")
util.printout(fd:read("*a"))
fd:close()
end
return true
end
end
end
return true
end
|
--- Module implementing the LuaRocks "doc" command.
-- Shows documentation for an installed rock.
module("luarocks.doc", package.seeall)
local util = require("luarocks.util")
local show = require("luarocks.show")
local path = require("luarocks.path")
local dir = require("luarocks.dir")
local fetch = require("luarocks.fetch")
local fs = require("luarocks.fs")
help_summary = "Shows documentation for an installed rock."
help = [[
<argument> is an existing package name.
Without any flags, tries to load the documentation
using a series of heuristics.
With these flags, return only the desired information:
--home Open the home page of project.
--list List documentation files only.
For more information about a rock, see the 'show' command.
]]
--- Driver function for "doc" command.
-- @param name or nil: an existing package name.
-- @param version string or nil: a version may also be passed.
-- @return boolean: True if succeeded, nil on errors.
function run(...)
local flags, name, version = util.parse_flags(...)
if not name then
return nil, "Argument missing. "..util.see_help("doc")
end
local repo
name, version, repo = show.pick_installed_rock(name, version, flags["tree"])
if not name then
return nil, version
end
local rockspec, err = fetch.load_local_rockspec(path.rockspec_file(name, version, repo))
if not rockspec then return nil,err end
local descript = rockspec.description or {}
if flags["home"] then
if not descript.homepage then
return nil, "No 'homepage' field in rockspec for "..name.." "..version
end
util.printout("Opening "..descript.homepage.." ...")
fs.browser(descript.homepage)
return true
end
local directory = path.install_dir(name,version,repo)
local docdir
local directories = { "doc", "docs" }
for _, d in ipairs(directories) do
local dirname = dir.path(directory, d)
if fs.is_dir(dirname) then
docdir = dirname
break
end
end
if not docdir then
if descript.homepage and not flags["list"] then
util.printout("Local documentation directory not found -- opening "..descript.homepage.." ...")
fs.browser(descript.homepage)
return true
end
return nil, "Documentation directory not found for "..name.." "..version
end
docdir = dir.normalize(docdir):gsub("/+", "/")
local files = fs.find(docdir)
local htmlpatt = "%.html?$"
local extensions = { htmlpatt, "%.md$", "%.txt$", "%.textile$", "" }
local basenames = { "index", "readme", "manual" }
local porcelain = flags["porcelain"]
if #files > 0 then
util.title("Documentation files for "..name.." "..version, porcelain)
if porcelain then
for _, file in ipairs(files) do
util.printout(docdir.."/"..file)
end
else
util.printout(docdir.."/")
for _, file in ipairs(files) do
util.printout("\t"..file)
end
end
end
if flags["list"] then
return true
end
for _, extension in ipairs(extensions) do
for _, basename in ipairs(basenames) do
local filename = basename..extension
local found
for _, file in ipairs(files) do
if file:lower():match(filename) and ((not found) or #file < #found) then
found = file
end
end
if found then
local pathname = dir.path(docdir, found)
util.printout()
util.printout("Opening "..pathname.." ...")
util.printout()
local ok = fs.browser(pathname)
if not ok and not pathname:match(htmlpatt) then
local fd = io.open(pathname, "r")
util.printout(fd:read("*a"))
fd:close()
end
return true
end
end
end
return true
end
|
Fix bug when docs are missing
|
Fix bug when docs are missing
|
Lua
|
mit
|
keplerproject/luarocks,starius/luarocks,xpol/luainstaller,keplerproject/luarocks,aryajur/luarocks,tst2005/luarocks,ignacio/luarocks,lxbgit/luarocks,aryajur/luarocks,xiaq/luarocks,starius/luarocks,xpol/luainstaller,coderstudy/luarocks,ignacio/luarocks,xpol/luainstaller,xpol/luavm,keplerproject/luarocks,xpol/luainstaller,leafo/luarocks,xpol/luarocks,xpol/luavm,rrthomas/luarocks,xpol/luavm,xpol/luarocks,usstwxy/luarocks,rrthomas/luarocks,starius/luarocks,xpol/luarocks,ignacio/luarocks,aryajur/luarocks,lxbgit/luarocks,starius/luarocks,tarantool/luarocks,usstwxy/luarocks,usstwxy/luarocks,tst2005/luarocks,rrthomas/luarocks,xpol/luavm,xpol/luarocks,robooo/luarocks,xiaq/luarocks,lxbgit/luarocks,lxbgit/luarocks,tst2005/luarocks,luarocks/luarocks,keplerproject/luarocks,leafo/luarocks,xiaq/luarocks,xiaq/luarocks,luarocks/luarocks,robooo/luarocks,coderstudy/luarocks,usstwxy/luarocks,leafo/luarocks,robooo/luarocks,luarocks/luarocks,coderstudy/luarocks,tarantool/luarocks,xpol/luavm,tarantool/luarocks,robooo/luarocks,rrthomas/luarocks,tst2005/luarocks,coderstudy/luarocks,ignacio/luarocks,aryajur/luarocks
|
94487a3d3168ba69f2fff5c19ffd7de21534fef4
|
libs/core/luasrc/init.lua
|
libs/core/luasrc/init.lua
|
--[[
LuCI - Lua Configuration Interface
Description:
Main class
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 require = require
module "luci"
local v = require "luci.version"
__version__ = v.luciversion or "0.9"
__appname__ = v.luciname or "LuCI"
|
--[[
LuCI - Lua Configuration Interface
Description:
Main class
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 require = require
-- Make sure that bitlib is loaded
if not _G.bit then
_G.bit = require "bit"
end
module "luci"
local v = require "luci.version"
__version__ = v.luciversion or "0.9"
__appname__ = v.luciname or "LuCI"
|
libs/core: make sure that bitlib is loaded, fixes some sdk problems
|
libs/core: make sure that bitlib is loaded, fixes some sdk problems
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@4537 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
alxhh/piratenluci,vhpham80/luci,vhpham80/luci,gwlim/luci,vhpham80/luci,Canaan-Creative/luci,zwhfly/openwrt-luci,gwlim/luci,saraedum/luci-packages-old,vhpham80/luci,Flexibity/luci,ch3n2k/luci,Canaan-Creative/luci,saraedum/luci-packages-old,phi-psi/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,alxhh/piratenluci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,stephank/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,8devices/carambola2-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,stephank/luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,ch3n2k/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,Flexibity/luci,ReclaimYourPrivacy/cloak-luci,saraedum/luci-packages-old,saraedum/luci-packages-old,8devices/carambola2-luci,Flexibity/luci,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,jschmidlapp/luci,phi-psi/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,yeewang/openwrt-luci,gwlim/luci,stephank/luci,projectbismark/luci-bismark,Canaan-Creative/luci,projectbismark/luci-bismark,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,Flexibity/luci,8devices/carambola2-luci,freifunk-gluon/luci,saraedum/luci-packages-old,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,8devices/carambola2-luci,ThingMesh/openwrt-luci,freifunk-gluon/luci,8devices/carambola2-luci,alxhh/piratenluci,phi-psi/luci,zwhfly/openwrt-luci,gwlim/luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,8devices/carambola2-luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,gwlim/luci,freifunk-gluon/luci,stephank/luci,Canaan-Creative/luci,eugenesan/openwrt-luci,phi-psi/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,Canaan-Creative/luci,ch3n2k/luci,jschmidlapp/luci,Flexibity/luci,dtaht/cerowrt-luci-3.3,projectbismark/luci-bismark,ThingMesh/openwrt-luci,freifunk-gluon/luci,freifunk-gluon/luci,ch3n2k/luci,projectbismark/luci-bismark,ch3n2k/luci,Flexibity/luci,zwhfly/openwrt-luci,gwlim/luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,alxhh/piratenluci,Flexibity/luci,phi-psi/luci,jschmidlapp/luci,freifunk-gluon/luci,vhpham80/luci,yeewang/openwrt-luci,zwhfly/openwrt-luci,stephank/luci,yeewang/openwrt-luci,ch3n2k/luci,gwlim/luci,alxhh/piratenluci,stephank/luci,Canaan-Creative/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,alxhh/piratenluci,freifunk-gluon/luci,8devices/carambola2-luci,yeewang/openwrt-luci,saraedum/luci-packages-old,ch3n2k/luci,alxhh/piratenluci,projectbismark/luci-bismark,phi-psi/luci,Flexibity/luci,vhpham80/luci
|
005015bccd9f5110f8fd60e118e535fd31797581
|
UCDutil/confirmation_c.lua
|
UCDutil/confirmation_c.lua
|
function createConfirmationWindow(event, arg, isServerEvent, title, text)
local confirmation = {window={}, label={}, button={}}
local calledResource = tostring(Resource.getName(sourceResource))
-- Replace 'UCD' with blank and capitalise the first letter
if (not title) then
calledResource = calledResource:gsub("UCD", "")
calledResource = calledResource:gsub("^%l", string.upper)
title = "UCD | "..calledResource.." - Confirmation"
end
confirmation.window[1] = guiCreateWindow(819, 425, 282, 132, title, false)
guiWindowSetSizable(confirmation.window[1], false)
confirmation.label[1] = guiCreateLabel(10, 26, 262, 44, tostring(text), false, confirmation.window[1])
guiLabelSetHorizontalAlign(confirmation.label[1], "center", false)
confirmation.button[1] = guiCreateButton(47, 85, 76, 36, "Yes", false, confirmation.window[1])
confirmation.button[2] = guiCreateButton(164, 85, 76, 36, "No", false, confirmation.window[1])
showCursor(true)
-- The purchase house bit underneath is not part of this general function.
function confirmationWindowClick()
if (source == confirmation.button[1]) then
if (isElement(confirmation.window[1])) then
removeEventHandler("onClientGUIClick", confirmation.window[1], confirmationWindowClick)
confirmation.window[1]:destroy()
end
if (event) then
if (isServerEvent and isServerEvent ~= nil) then
triggerServerEvent(event, localPlayer, arg)
else
triggerEvent(event, localPlayer, arg)
end
end
showCursor(false)
return true
elseif (source == confirmation.button[2]) then
if (isElement(confirmation.window[1])) then
removeEventHandler("onClientGUIClick", confirmation.window[1], confirmationWindowClick)
confirmation.window[1]:destroy()
end
showCursor(false)
return false
end
end
addEventHandler("onClientGUIClick", confirmation.window[1], confirmationWindowClick)
if (confirmation.window[1] and isElement(confirmation.window[1])) then
return true
else
return false
end
end
--[[
-- CALLBACK STRING SHOULD BE IN FORM OF
-- "exports.resource:function(args)"
--]]
|
confirmation = {window={}, label={}, button={}}
confirmation.window[1] = nil
function createConfirmationWindow(event, arugment, serverOrClient, title, text)
calledResource = tostring(Resource.getName(sourceResource))
-- Replace 'UCD' with blank and capitalise the first letter
if (not title) then
calledResource = calledResource:gsub("UCD", "")
calledResource = calledResource:gsub("^%l", string.upper)
title = "UCD | "..calledResource.." - Confirmation"
end
if (confirmation.window[1] == nil) then
confirmation.window[1] = guiCreateWindow(819, 425, 282, 132, title, false)
guiWindowSetSizable(confirmation.window[1], false)
confirmation.label[1] = guiCreateLabel(10, 26, 262, 44, tostring(text), false, confirmation.window[1])
guiLabelSetHorizontalAlign(confirmation.label[1], "center", false)
confirmation.button[1] = guiCreateButton(47, 85, 76, 36, "Yes", false, confirmation.window[1])
confirmation.button[2] = guiCreateButton(164, 85, 76, 36, "No", false, confirmation.window[1])
end
action_ = event
isServerEvent = serverOrClient
arg = arugment
confirmation.window[1]:setVisible(true)
guiBringToFront(confirmation.window[1])
guiSetProperty(confirmation.window[1], "AlwaysOnTop", "true")
if (#getEventHandlers("onClientGUIClick", confirmation.window[1], clickConfirmationWindow) == 0) then
addEventHandler("onClientGUIClick", confirmation.window[1], clickConfirmationWindow)
end
end
function closeConfirmationWindow()
if (confirmation.window[1]) then
removeEventHandler("onClientGUIClick", confirmation.window[1], clickConfirmationWindow)
action_ = nil
confirmation.window[1]:destroy()
confirmation.window[1] = nil
var = {}
end
end
function clickConfirmationWindow(button)
if (button == "left") then
if (source == confirmation.button[1]) then
if (action_) then
if (isServerEvent and isServerEvent ~= nil) then
triggerServerEvent(action_, localPlayer, arg)
else
triggerEvent(action_, localPlayer, arg)
end
end
action_ = nil
closeConfirmationWindow()
elseif (source == confirmation.button[2]) then
action_ = nil
closeConfirmationWindow()
end
end
end
|
UCDutil
|
UCDutil
- Fixed confirmation window sometimes not responding or spawning multiple instances.
|
Lua
|
mit
|
nokizorque/ucd,nokizorque/ucd
|
33e088dd9d84edecca2df8d2682260d55ea9056a
|
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
|
protocols/6x4/luasrc/model/cbi/admin_network/proto_6to4.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ipaddr, adv_interface, adv_subnet
local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network"))
adv_interface.widget = "checkbox"
adv_interface.exclude = arg[1]
adv_interface.default = "lan"
adv_interface.template = "cbi/network_netlist"
adv_interface.nocreate = true
adv_interface.nobridges = true
adv_interface.novirtual = true
adv_subnet = section:taboption("general", Value, "adv_subnet",
translate("Advertised network ID"),
translate("Allowed range is 1 to 65535"))
adv_subnet.placeholder = "1"
adv_subnet.datatype = "range(1,65535)"
function adv_subnet.cfgvalue(self, section)
local v = Value.cfgvalue(self, section)
return v and tonumber(v, 16)
end
function adv_subnet .write(self, section, value)
value = tonumber(value) or 1
if value > 65535 then value = 65535
elseif value < 1 then value = 1 end
Value.write(self, section, "%X" % value)
end
adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime",
translate("Use valid lifetime"),
translate("Specifies the advertised valid prefix lifetime in seconds"))
adv_valid_lifetime.placeholder = "300"
adv_valid_lifetime.datatype = "uinteger"
adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime",
translate("Use preferred lifetime"),
translate("Specifies the advertised preferred prefix lifetime in seconds"))
adv_preferred_lifetime.placeholder = "120"
adv_preferred_lifetime.datatype = "uinteger"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(1500)"
|
--[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ipaddr, adv_interface, adv_subnet
local adv_valid_lifetime, adv_preferred_lifetime, defaultroute, metric, ttl, mtu
ipaddr = section:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
adv_interface = section:taboption("general", Value, "adv_interface", translate("Advertise IPv6 on network"))
adv_interface.widget = "checkbox"
adv_interface.exclude = arg[1]
adv_interface.default = "lan"
adv_interface.template = "cbi/network_netlist"
adv_interface.nocreate = true
adv_interface.nobridges = true
adv_interface.novirtual = true
function adv_interface.remove(self, section)
self:write(section, " ")
end
adv_subnet = section:taboption("general", Value, "adv_subnet",
translate("Advertised network ID"),
translate("Allowed range is 1 to 65535"))
adv_subnet.placeholder = "1"
adv_subnet.datatype = "range(1,65535)"
function adv_subnet.cfgvalue(self, section)
local v = Value.cfgvalue(self, section)
return v and tonumber(v, 16)
end
function adv_subnet .write(self, section, value)
value = tonumber(value) or 1
if value > 65535 then value = 65535
elseif value < 1 then value = 1 end
Value.write(self, section, "%X" % value)
end
adv_valid_lifetime = section:taboption("advanced", Value, "adv_valid_lifetime",
translate("Use valid lifetime"),
translate("Specifies the advertised valid prefix lifetime in seconds"))
adv_valid_lifetime.placeholder = "300"
adv_valid_lifetime.datatype = "uinteger"
adv_preferred_lifetime = section:taboption("advanced", Value, "adv_preferred_lifetime",
translate("Use preferred lifetime"),
translate("Specifies the advertised preferred prefix lifetime in seconds"))
adv_preferred_lifetime.placeholder = "120"
adv_preferred_lifetime.datatype = "uinteger"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(1500)"
|
protocols/6x4: fix turning off 6ro4 advertising on all interfaces
|
protocols/6x4: fix turning off 6ro4 advertising on all interfaces
|
Lua
|
apache-2.0
|
male-puppies/luci,tobiaswaldvogel/luci,Wedmer/luci,obsy/luci,thess/OpenWrt-luci,Sakura-Winkey/LuCI,ReclaimYourPrivacy/cloak-luci,shangjiyu/luci-with-extra,RuiChen1113/luci,sujeet14108/luci,ReclaimYourPrivacy/cloak-luci,maxrio/luci981213,palmettos/cnLuCI,urueedi/luci,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,openwrt-es/openwrt-luci,rogerpueyo/luci,taiha/luci,ff94315/luci-1,Noltari/luci,teslamint/luci,MinFu/luci,openwrt-es/openwrt-luci,tcatm/luci,oyido/luci,Kyklas/luci-proto-hso,chris5560/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,bittorf/luci,david-xiao/luci,palmettos/test,marcel-sch/luci,kuoruan/lede-luci,joaofvieira/luci,Sakura-Winkey/LuCI,oneru/luci,Noltari/luci,male-puppies/luci,marcel-sch/luci,palmettos/cnLuCI,db260179/openwrt-bpi-r1-luci,oneru/luci,marcel-sch/luci,shangjiyu/luci-with-extra,db260179/openwrt-bpi-r1-luci,nmav/luci,oneru/luci,forward619/luci,cappiewu/luci,aircross/OpenWrt-Firefly-LuCI,lcf258/openwrtcn,rogerpueyo/luci,Noltari/luci,cshore-firmware/openwrt-luci,ollie27/openwrt_luci,cshore/luci,NeoRaider/luci,artynet/luci,Kyklas/luci-proto-hso,florian-shellfire/luci,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,jlopenwrtluci/luci,lcf258/openwrtcn,slayerrensky/luci,zhaoxx063/luci,thess/OpenWrt-luci,bittorf/luci,nmav/luci,joaofvieira/luci,tobiaswaldvogel/luci,LazyZhu/openwrt-luci-trunk-mod,Sakura-Winkey/LuCI,aircross/OpenWrt-Firefly-LuCI,obsy/luci,dismantl/luci-0.12,deepak78/new-luci,openwrt/luci,zhaoxx063/luci,harveyhu2012/luci,thesabbir/luci,lcf258/openwrtcn,Wedmer/luci,aa65535/luci,openwrt/luci,Sakura-Winkey/LuCI,jchuang1977/luci-1,slayerrensky/luci,dismantl/luci-0.12,openwrt/luci,sujeet14108/luci,joaofvieira/luci,jlopenwrtluci/luci,obsy/luci,aa65535/luci,bright-things/ionic-luci,Noltari/luci,dwmw2/luci,LazyZhu/openwrt-luci-trunk-mod,tcatm/luci,Wedmer/luci,ollie27/openwrt_luci,palmettos/test,kuoruan/luci,chris5560/openwrt-luci,oyido/luci,Kyklas/luci-proto-hso,RuiChen1113/luci,Kyklas/luci-proto-hso,tobiaswaldvogel/luci,oneru/luci,cappiewu/luci,schidler/ionic-luci,opentechinstitute/luci,bright-things/ionic-luci,obsy/luci,MinFu/luci,nwf/openwrt-luci,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,thess/OpenWrt-luci,ff94315/luci-1,florian-shellfire/luci,dwmw2/luci,bittorf/luci,LuttyYang/luci,MinFu/luci,zhaoxx063/luci,nwf/openwrt-luci,teslamint/luci,Sakura-Winkey/LuCI,Kyklas/luci-proto-hso,RedSnake64/openwrt-luci-packages,fkooman/luci,cshore/luci,ReclaimYourPrivacy/cloak-luci,db260179/openwrt-bpi-r1-luci,jchuang1977/luci-1,cshore/luci,teslamint/luci,cappiewu/luci,RuiChen1113/luci,obsy/luci,jchuang1977/luci-1,Hostle/luci,Hostle/openwrt-luci-multi-user,schidler/ionic-luci,wongsyrone/luci-1,oyido/luci,wongsyrone/luci-1,rogerpueyo/luci,marcel-sch/luci,daofeng2015/luci,dismantl/luci-0.12,LazyZhu/openwrt-luci-trunk-mod,ReclaimYourPrivacy/cloak-luci,maxrio/luci981213,Hostle/luci,deepak78/new-luci,male-puppies/luci,shangjiyu/luci-with-extra,david-xiao/luci,jorgifumi/luci,kuoruan/lede-luci,slayerrensky/luci,lcf258/openwrtcn,keyidadi/luci,nwf/openwrt-luci,artynet/luci,lcf258/openwrtcn,sujeet14108/luci,nwf/openwrt-luci,thesabbir/luci,dwmw2/luci,hnyman/luci,Hostle/openwrt-luci-multi-user,hnyman/luci,tcatm/luci,kuoruan/lede-luci,remakeelectric/luci,keyidadi/luci,db260179/openwrt-bpi-r1-luci,zhaoxx063/luci,981213/luci-1,nwf/openwrt-luci,deepak78/new-luci,NeoRaider/luci,jchuang1977/luci-1,florian-shellfire/luci,palmettos/cnLuCI,keyidadi/luci,nwf/openwrt-luci,Sakura-Winkey/LuCI,Wedmer/luci,thesabbir/luci,bittorf/luci,teslamint/luci,deepak78/new-luci,zhaoxx063/luci,cshore/luci,Kyklas/luci-proto-hso,ollie27/openwrt_luci,schidler/ionic-luci,marcel-sch/luci,urueedi/luci,mumuqz/luci,kuoruan/luci,deepak78/new-luci,harveyhu2012/luci,artynet/luci,fkooman/luci,NeoRaider/luci,LuttyYang/luci,palmettos/cnLuCI,dismantl/luci-0.12,fkooman/luci,lcf258/openwrtcn,thess/OpenWrt-luci,kuoruan/lede-luci,RuiChen1113/luci,florian-shellfire/luci,chris5560/openwrt-luci,Noltari/luci,chris5560/openwrt-luci,NeoRaider/luci,Noltari/luci,harveyhu2012/luci,aa65535/luci,fkooman/luci,LuttyYang/luci,zhaoxx063/luci,dismantl/luci-0.12,harveyhu2012/luci,dwmw2/luci,keyidadi/luci,zhaoxx063/luci,Hostle/luci,urueedi/luci,RedSnake64/openwrt-luci-packages,fkooman/luci,jorgifumi/luci,cappiewu/luci,male-puppies/luci,NeoRaider/luci,tcatm/luci,LuttyYang/luci,bittorf/luci,bright-things/ionic-luci,david-xiao/luci,maxrio/luci981213,teslamint/luci,male-puppies/luci,harveyhu2012/luci,dismantl/luci-0.12,bittorf/luci,thesabbir/luci,aa65535/luci,palmettos/cnLuCI,jlopenwrtluci/luci,nmav/luci,david-xiao/luci,marcel-sch/luci,nwf/openwrt-luci,marcel-sch/luci,chris5560/openwrt-luci,shangjiyu/luci-with-extra,ff94315/luci-1,remakeelectric/luci,Sakura-Winkey/LuCI,schidler/ionic-luci,jorgifumi/luci,daofeng2015/luci,RuiChen1113/luci,opentechinstitute/luci,LazyZhu/openwrt-luci-trunk-mod,jlopenwrtluci/luci,thess/OpenWrt-luci,RuiChen1113/luci,sujeet14108/luci,palmettos/test,oneru/luci,db260179/openwrt-bpi-r1-luci,schidler/ionic-luci,tobiaswaldvogel/luci,bittorf/luci,aircross/OpenWrt-Firefly-LuCI,sujeet14108/luci,nwf/openwrt-luci,taiha/luci,artynet/luci,Wedmer/luci,Hostle/luci,oneru/luci,kuoruan/luci,forward619/luci,dwmw2/luci,db260179/openwrt-bpi-r1-luci,slayerrensky/luci,jorgifumi/luci,opentechinstitute/luci,rogerpueyo/luci,remakeelectric/luci,daofeng2015/luci,mumuqz/luci,tcatm/luci,urueedi/luci,thess/OpenWrt-luci,openwrt-es/openwrt-luci,Hostle/openwrt-luci-multi-user,aa65535/luci,ff94315/luci-1,RuiChen1113/luci,RedSnake64/openwrt-luci-packages,urueedi/luci,obsy/luci,tcatm/luci,dwmw2/luci,aa65535/luci,palmettos/test,Noltari/luci,openwrt/luci,ollie27/openwrt_luci,joaofvieira/luci,chris5560/openwrt-luci,MinFu/luci,bright-things/ionic-luci,rogerpueyo/luci,oneru/luci,bittorf/luci,david-xiao/luci,wongsyrone/luci-1,Wedmer/luci,hnyman/luci,MinFu/luci,cshore-firmware/openwrt-luci,openwrt-es/openwrt-luci,rogerpueyo/luci,lbthomsen/openwrt-luci,teslamint/luci,oyido/luci,palmettos/cnLuCI,ReclaimYourPrivacy/cloak-luci,dwmw2/luci,teslamint/luci,LuttyYang/luci,male-puppies/luci,Hostle/luci,remakeelectric/luci,wongsyrone/luci-1,cshore/luci,lbthomsen/openwrt-luci,Hostle/openwrt-luci-multi-user,Hostle/openwrt-luci-multi-user,harveyhu2012/luci,maxrio/luci981213,LuttyYang/luci,aircross/OpenWrt-Firefly-LuCI,mumuqz/luci,mumuqz/luci,LazyZhu/openwrt-luci-trunk-mod,joaofvieira/luci,oneru/luci,shangjiyu/luci-with-extra,981213/luci-1,hnyman/luci,urueedi/luci,urueedi/luci,shangjiyu/luci-with-extra,lbthomsen/openwrt-luci,artynet/luci,shangjiyu/luci-with-extra,obsy/luci,opentechinstitute/luci,ollie27/openwrt_luci,kuoruan/lede-luci,keyidadi/luci,oyido/luci,nmav/luci,Sakura-Winkey/LuCI,Noltari/luci,rogerpueyo/luci,deepak78/new-luci,daofeng2015/luci,sujeet14108/luci,ReclaimYourPrivacy/cloak-luci,maxrio/luci981213,kuoruan/lede-luci,slayerrensky/luci,schidler/ionic-luci,kuoruan/luci,palmettos/cnLuCI,maxrio/luci981213,harveyhu2012/luci,jorgifumi/luci,schidler/ionic-luci,tcatm/luci,cshore-firmware/openwrt-luci,forward619/luci,taiha/luci,Wedmer/luci,bright-things/ionic-luci,RedSnake64/openwrt-luci-packages,jlopenwrtluci/luci,kuoruan/luci,chris5560/openwrt-luci,joaofvieira/luci,981213/luci-1,lbthomsen/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,wongsyrone/luci-1,LuttyYang/luci,jlopenwrtluci/luci,NeoRaider/luci,981213/luci-1,openwrt/luci,oyido/luci,shangjiyu/luci-with-extra,cshore-firmware/openwrt-luci,cappiewu/luci,openwrt-es/openwrt-luci,ff94315/luci-1,male-puppies/luci,florian-shellfire/luci,deepak78/new-luci,taiha/luci,lcf258/openwrtcn,cshore-firmware/openwrt-luci,artynet/luci,mumuqz/luci,lcf258/openwrtcn,Hostle/luci,keyidadi/luci,sujeet14108/luci,openwrt/luci,remakeelectric/luci,oyido/luci,florian-shellfire/luci,openwrt-es/openwrt-luci,ff94315/luci-1,cappiewu/luci,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,jorgifumi/luci,forward619/luci,nmav/luci,Noltari/luci,remakeelectric/luci,opentechinstitute/luci,openwrt/luci,MinFu/luci,ff94315/luci-1,joaofvieira/luci,LuttyYang/luci,lbthomsen/openwrt-luci,tcatm/luci,forward619/luci,cshore-firmware/openwrt-luci,keyidadi/luci,NeoRaider/luci,ff94315/luci-1,forward619/luci,jlopenwrtluci/luci,opentechinstitute/luci,cshore/luci,dwmw2/luci,artynet/luci,fkooman/luci,cshore-firmware/openwrt-luci,hnyman/luci,lcf258/openwrtcn,slayerrensky/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,tobiaswaldvogel/luci,thess/OpenWrt-luci,cappiewu/luci,daofeng2015/luci,remakeelectric/luci,slayerrensky/luci,chris5560/openwrt-luci,bright-things/ionic-luci,thess/OpenWrt-luci,palmettos/test,slayerrensky/luci,rogerpueyo/luci,ReclaimYourPrivacy/cloak-luci,jchuang1977/luci-1,ollie27/openwrt_luci,schidler/ionic-luci,RuiChen1113/luci,cshore/luci,jchuang1977/luci-1,fkooman/luci,hnyman/luci,wongsyrone/luci-1,thesabbir/luci,taiha/luci,Kyklas/luci-proto-hso,lbthomsen/openwrt-luci,nmav/luci,Hostle/luci,urueedi/luci,981213/luci-1,jorgifumi/luci,oyido/luci,jchuang1977/luci-1,openwrt/luci,palmettos/test,Hostle/openwrt-luci-multi-user,jchuang1977/luci-1,sujeet14108/luci,cshore/luci,RedSnake64/openwrt-luci-packages,tobiaswaldvogel/luci,florian-shellfire/luci,aircross/OpenWrt-Firefly-LuCI,artynet/luci,jlopenwrtluci/luci,taiha/luci,zhaoxx063/luci,wongsyrone/luci-1,MinFu/luci,thesabbir/luci,florian-shellfire/luci,wongsyrone/luci-1,palmettos/cnLuCI,thesabbir/luci,thesabbir/luci,lbthomsen/openwrt-luci,lcf258/openwrtcn,kuoruan/luci,forward619/luci,teslamint/luci,opentechinstitute/luci,marcel-sch/luci,Hostle/luci,palmettos/test,palmettos/test,LazyZhu/openwrt-luci-trunk-mod,981213/luci-1,daofeng2015/luci,bright-things/ionic-luci,daofeng2015/luci,obsy/luci,taiha/luci,db260179/openwrt-bpi-r1-luci,taiha/luci,Hostle/openwrt-luci-multi-user,Wedmer/luci,kuoruan/lede-luci,remakeelectric/luci,mumuqz/luci,aa65535/luci,artynet/luci,LazyZhu/openwrt-luci-trunk-mod,maxrio/luci981213,david-xiao/luci,nmav/luci,ollie27/openwrt_luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,david-xiao/luci,maxrio/luci981213,981213/luci-1,dismantl/luci-0.12,daofeng2015/luci,mumuqz/luci,NeoRaider/luci,MinFu/luci,david-xiao/luci,tobiaswaldvogel/luci,hnyman/luci,mumuqz/luci,keyidadi/luci,nmav/luci,RedSnake64/openwrt-luci-packages,male-puppies/luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,RedSnake64/openwrt-luci-packages,nmav/luci,deepak78/new-luci,fkooman/luci,forward619/luci,kuoruan/luci,aa65535/luci,joaofvieira/luci,cappiewu/luci,openwrt-es/openwrt-luci,kuoruan/luci
|
390cc935dce9080c9b186fab9c9c7443bc4f62aa
|
core/world/Actor.lua
|
core/world/Actor.lua
|
local assert = assert
local class = require 'middleclass'
local Object = class.Object
local Control = require 'core/Control'
local Controllable = require 'core/Controllable'
local WorldObject = require 'core/world/WorldObject'
local CameraManifold = require 'core/graphics/CameraManifold'
local EgoCameraController = require 'core/EgoCameraController'
local DefaultFoV = math.rad(80)
local ZoomedFoV = math.rad(10)
--- Things that the player can take control of.
local Actor = class('core/world/Actor', WorldObject)
Actor:include(Controllable)
function Actor:initialize( renderTarget )
WorldObject.initialize(self)
Control.pushControllable(self)
self.egoCameraController = EgoCameraController()
Control.pushControllable(self.egoCameraController)
local function onOrientationUpdated( self, orientation )
self.cameraManifold:setViewTransformation(orientation:toMatrix())
end
self.egoCameraController:addEventTarget('orientation-updated', self, onOrientationUpdated)
self.cameraManifold = CameraManifold(renderTarget)
self.cameraManifold:setFieldOfView(DefaultFoV)
end
function Actor:destroy()
Control.popControllable(self.egoCameraController)
Control.popControllable(self)
self.cameraManifold:destroy()
WorldObject.destroy(self)
end
Actor:mapControl('zoom', function( self, absolute, delta )
if delta > 0 then
self.cameraManifold:setFieldOfView(ZoomedFoV)
else
self.cameraManifold:setFieldOfView(DefaultFoV)
end
end)
return Actor
|
local assert = assert
local class = require 'middleclass'
local Object = class.Object
local Vec = require 'core/Vector'
local Control = require 'core/Control'
local Controllable = require 'core/Controllable'
local WorldObject = require 'core/world/WorldObject'
local CameraManifold = require 'core/graphics/CameraManifold'
local EgoCameraController = require 'core/EgoCameraController'
local DefaultFoV = math.rad(80)
local ZoomedFoV = math.rad(10)
--- Things that the player can take control of.
local Actor = class('core/world/Actor', WorldObject)
Actor:include(Controllable)
function Actor:initialize( renderTarget )
WorldObject.initialize(self)
Control.pushControllable(self)
self.cameraManifold = CameraManifold(renderTarget)
self.cameraManifold:setFieldOfView(DefaultFoV)
self.egoCameraController = EgoCameraController()
Control.pushControllable(self.egoCameraController)
local function onOrientationUpdated( self, orientation )
local transformation = orientation:toMatrix():scale(Vec(1,1,-1))
-- Invert Z axis to remain in right-handed system.
self.cameraManifold:setViewTransformation(transformation)
end
self.egoCameraController:addEventTarget('orientation-updated', self, onOrientationUpdated)
onOrientationUpdated(self, self.egoCameraController:getOrientation())
end
function Actor:destroy()
Control.popControllable(self.egoCameraController)
Control.popControllable(self)
self.cameraManifold:destroy()
WorldObject.destroy(self)
end
Actor:mapControl('zoom', function( self, absolute, delta )
if delta > 0 then
self.cameraManifold:setFieldOfView(ZoomedFoV)
else
self.cameraManifold:setFieldOfView(DefaultFoV)
end
end)
return Actor
|
Fixed camera view transformation.
|
Fixed camera view transformation.
|
Lua
|
mit
|
henry4k/apoapsis,henry4k/konstrukt,henry4k/konstrukt,henry4k/apoapsis,henry4k/apoapsis,henry4k/konstrukt
|
296f4bacbeb18093842f308da104e65f9439e282
|
genie/assimp.lua
|
genie/assimp.lua
|
--
-- Copyright (c) 2015 Jonathan Howard
-- MIT License
--
function assimp_library()
project "assimp"
-- location (build_dir)
-- targetdir (lib_dir)
targetname "assimp"
language "C++"
kind "StaticLib"
includedirs
{
ASSIMP_DIR .. "include/",
ASSIMP_DIR .. "code/BoostWorkaround",
}
files
{
ASSIMP_DIR .. "code/**.cpp",
ASSIMP_DIR .. "contrib/clipper/clipper.hpp",
ASSIMP_DIR .. "contrib/clipper/clipper.cpp",
ASSIMP_DIR .. "contrib/ConvertUTF/ConvertUTF.h",
ASSIMP_DIR .. "contrib/ConvertUTF/ConvertUTF.c",
ASSIMP_DIR .. "contrib/irrXML/**.h",
ASSIMP_DIR .. "contrib/irrXML/**.cpp",
ASSIMP_DIR .. "contrib/poly2tri/poly2tri/common/**.h",
ASSIMP_DIR .. "contrib/poly2tri/poly2tri/common/**.cc",
ASSIMP_DIR .. "contrib/poly2tri/poly2tri/sweep/**.h",
ASSIMP_DIR .. "contrib/poly2tri/poly2tri/sweep/**.cc",
ASSIMP_DIR .. "contrib/poly2tri/poly2tri/poly2tri.h",
ASSIMP_DIR .. "contrib/unzip/**.h",
ASSIMP_DIR .. "contrib/unzip/**.c",
ASSIMP_DIR .. "contrib/zlib/**.h",
ASSIMP_DIR .. "contrib/zlib/**.c",
ASSIMP_DIR .. "include/assimp/**.hpp",
ASSIMP_DIR .. "include/assimp/**.h"
}
configuration "windows"
links
{
"ole32"
}
configuration "linux"
links
{
"dl"
}
configuration "macosx"
links
{
"CoreServices.framework"
}
end
|
--
-- Copyright (c) 2015 Jonathan Howard
-- MIT License
--
function assimp_library()
project "assimp"
-- location (build_dir)
-- targetdir (lib_dir)
targetname "assimp"
language "C++"
kind "StaticLib"
removeflags { "NoExceptions", "NoRTTI" }
includedirs
{
ASSIMP_DIR .. "include/",
ASSIMP_DIR .. "code/BoostWorkaround",
}
files
{
ASSIMP_DIR .. "code/**.cpp",
ASSIMP_DIR .. "contrib/clipper/clipper.hpp",
ASSIMP_DIR .. "contrib/clipper/clipper.cpp",
ASSIMP_DIR .. "contrib/ConvertUTF/ConvertUTF.h",
ASSIMP_DIR .. "contrib/ConvertUTF/ConvertUTF.c",
ASSIMP_DIR .. "contrib/irrXML/**.h",
ASSIMP_DIR .. "contrib/irrXML/**.cpp",
ASSIMP_DIR .. "contrib/poly2tri/poly2tri/common/**.h",
ASSIMP_DIR .. "contrib/poly2tri/poly2tri/common/**.cc",
ASSIMP_DIR .. "contrib/poly2tri/poly2tri/sweep/**.h",
ASSIMP_DIR .. "contrib/poly2tri/poly2tri/sweep/**.cc",
ASSIMP_DIR .. "contrib/poly2tri/poly2tri/poly2tri.h",
ASSIMP_DIR .. "contrib/unzip/**.h",
ASSIMP_DIR .. "contrib/unzip/**.c",
ASSIMP_DIR .. "contrib/zlib/**.h",
ASSIMP_DIR .. "contrib/zlib/**.c",
ASSIMP_DIR .. "include/assimp/**.hpp",
ASSIMP_DIR .. "include/assimp/**.h"
}
configuration "windows"
links
{
"ole32"
}
configuration "linux"
links
{
"dl"
}
configuration "macosx"
links
{
"CoreServices.framework"
}
end
|
Fixed assimp build on OS X...why didn't this break on Windows?
|
Fixed assimp build on OS X...why didn't this break on Windows?
|
Lua
|
mit
|
v3n/altertum,v3n/altertum,NathanaelThompson/altertum,v3n/altertum,NathanaelThompson/altertum,NathanaelThompson/altertum
|
f7142cfcbec27362a61ca65ede573e282f9574fd
|
frontend/ui/widget/filechooser.lua
|
frontend/ui/widget/filechooser.lua
|
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Menu = require("ui/widget/menu")
local Screen = require("device").screen
local Device = require("device")
local util = require("ffi/util")
local DEBUG = require("dbg")
local _ = require("gettext")
local ffi = require("ffi")
ffi.cdef[[
int strcoll (const char *str1, const char *str2);
]]
-- string sort function respecting LC_COLLATE
local function strcoll(str1, str2)
return ffi.C.strcoll(str1, str2) < 0
end
local FileChooser = Menu:extend{
no_title = true,
path = lfs.currentdir(),
parent = nil,
show_hidden = nil,
filter = function(filename) return true end,
exclude_dirs = {"%.sdr$"},
strcoll = strcoll,
collate = "strcoll", -- or collate = "access",
reverse_collate = false,
path_items = {}, -- store last browsed location(item index) for each path
}
function FileChooser:init()
self.width = Screen:getWidth()
-- common dir filter
self.dir_filter = function(dirname)
for _, pattern in ipairs(self.exclude_dirs) do
if dirname:match(pattern) then return end
end
return true
end
-- circumvent string collating in Kobo devices. See issue koreader/koreader#686
if Device:isKobo() then
self.strcoll = function(a, b) return a < b end
end
self.item_table = self:genItemTableFromPath(self.path)
Menu.init(self) -- call parent's init()
end
function FileChooser:genItemTableFromPath(path)
local dirs = {}
local files = {}
-- lfs.dir directory without permission will give error
local ok, iter, dir_obj = pcall(lfs.dir, self.path)
if ok then
for f in iter, dir_obj do
if self.show_hidden or not string.match(f, "^%.[^.]") then
local filename = self.path.."/"..f
local attributes = lfs.attributes(filename)
if attributes.mode == "directory" and f ~= "." and f~=".." then
if self.dir_filter(filename) then
table.insert(dirs, {name = f, attr = attributes})
end
elseif attributes.mode == "file" then
if self.file_filter(filename) then
table.insert(files, {name = f, attr = attributes})
end
end
end
end
end
local sorting = nil
local reverse = self.reverse_collate
if self.collate == "strcoll" then
if DALPHA_SORT_CASE_INSENSITIVE then
sorting = function(a, b)
return self.strcoll(string.lower(a.name), string.lower(b.name)) == not reverse
end
else
sorting = function(a, b)
return self.strcoll(a.name, b.name) == not reverse
end
end
elseif self.collate == "access" then
sorting = function(a, b)
if reverse then
return a.attr.access < b.attr.access
else
return a.attr.access > b.attr.access
end
end
end
table.sort(dirs, sorting)
if path ~= "/" then table.insert(dirs, 1, {name = ".."}) end
table.sort(files, sorting)
local item_table = {}
for i, dir in ipairs(dirs) do
local path = self.path.."/"..dir.name
local items = 0
local ok, iter, dir_obj = pcall(lfs.dir, path)
if ok then
for f in iter, dir_obj do
items = items + 1
end
-- exclude "." and ".."
items = items - 2
end
local istr = util.template(
items == 0 and _("0 items")
or items == 1 and _("1 item")
or _("%1 items"), items)
table.insert(item_table, {
text = dir.name.."/",
mandatory = istr,
path = path
})
end
for _, file in ipairs(files) do
local full_path = self.path.."/"..file.name
local file_size = lfs.attributes(full_path, "size") or 0
local sstr = ""
if file_size > 1024*1024 then
sstr = string.format("%4.1f MB", file_size/1024/1024)
elseif file_size > 1024 then
sstr = string.format("%4.1f KB", file_size/1024)
else
sstr = string.format("%d B", file_size)
end
table.insert(item_table, {
text = file.name,
mandatory = sstr,
path = full_path
})
end
-- lfs.dir iterated node string may be encoded with some weird codepage on Windows
-- we need to encode them to utf-8
if ffi.os == "Windows" then
for k, v in pairs(item_table) do
if v.text then
v.text = util.multiByteToUTF8(v.text) or ""
end
end
end
return item_table
end
function FileChooser:updateItems(select_number)
Menu.updateItems(self, select_number) -- call parent's updateItems()
self.path_items[self.path] = (self.page - 1) * self.perpage + (select_number or 1)
end
function FileChooser:refreshPath()
self:swithItemTable(nil, self:genItemTableFromPath(self.path), self.path_items[self.path])
end
function FileChooser:changeToPath(path)
path = util.realpath(path)
self.path = path
self:refreshPath()
end
function FileChooser:toggleHiddenFiles()
self.show_hidden = not self.show_hidden
self:refreshPath()
end
function FileChooser:setCollate(collate)
self.collate = collate
self:refreshPath()
end
function FileChooser:toggleReverseCollate()
self.reverse_collate = not self.reverse_collate
self:refreshPath()
end
function FileChooser:onMenuSelect(item)
-- parent directory of dir without permission get nil mode
-- we need to change to parent path in this case
if lfs.attributes(item.path, "mode") == "file" then
self:onFileSelect(item.path)
else
self:changeToPath(item.path)
end
return true
end
function FileChooser:onMenuHold(item)
self:onFileHold(item.path)
return true
end
function FileChooser:onFileSelect(file)
UIManager:close(self)
return true
end
function FileChooser:onFileHold(file)
return true
end
return FileChooser
|
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Menu = require("ui/widget/menu")
local Screen = require("device").screen
local Device = require("device")
local util = require("ffi/util")
local DEBUG = require("dbg")
local _ = require("gettext")
local ffi = require("ffi")
ffi.cdef[[
int strcoll (const char *str1, const char *str2);
]]
-- string sort function respecting LC_COLLATE
local function strcoll(str1, str2)
return ffi.C.strcoll(str1, str2) < 0
end
local FileChooser = Menu:extend{
no_title = true,
path = lfs.currentdir(),
parent = nil,
show_hidden = nil,
filter = function(filename) return true end,
exclude_dirs = {"%.sdr$"},
strcoll = strcoll,
collate = "strcoll", -- or collate = "access",
reverse_collate = false,
path_items = {}, -- store last browsed location(item index) for each path
}
function FileChooser:init()
self.width = Screen:getWidth()
-- common dir filter
self.dir_filter = function(dirname)
for _, pattern in ipairs(self.exclude_dirs) do
if dirname:match(pattern) then return end
end
return true
end
-- circumvent string collating in Kobo devices. See issue koreader/koreader#686
if Device:isKobo() then
self.strcoll = function(a, b) return a < b end
end
self.item_table = self:genItemTableFromPath(self.path)
Menu.init(self) -- call parent's init()
end
function FileChooser:genItemTableFromPath(path)
local dirs = {}
local files = {}
-- lfs.dir directory without permission will give error
local ok, iter, dir_obj = pcall(lfs.dir, self.path)
if ok then
for f in iter, dir_obj do
if self.show_hidden or not string.match(f, "^%.[^.]") then
local filename = self.path.."/"..f
local attributes = lfs.attributes(filename)
if attributes ~= nil then
if attributes.mode == "directory" and f ~= "." and f~=".." then
if self.dir_filter(filename) then
table.insert(dirs, {name = f, attr = attributes})
end
elseif attributes.mode == "file" then
if self.file_filter(filename) then
table.insert(files, {name = f, attr = attributes})
end
end
end
end
end
end
local sorting = nil
local reverse = self.reverse_collate
if self.collate == "strcoll" then
if DALPHA_SORT_CASE_INSENSITIVE then
sorting = function(a, b)
return self.strcoll(string.lower(a.name), string.lower(b.name)) == not reverse
end
else
sorting = function(a, b)
return self.strcoll(a.name, b.name) == not reverse
end
end
elseif self.collate == "access" then
sorting = function(a, b)
if reverse then
return a.attr.access < b.attr.access
else
return a.attr.access > b.attr.access
end
end
end
table.sort(dirs, sorting)
if path ~= "/" then table.insert(dirs, 1, {name = ".."}) end
table.sort(files, sorting)
local item_table = {}
for i, dir in ipairs(dirs) do
local path = self.path.."/"..dir.name
local items = 0
local ok, iter, dir_obj = pcall(lfs.dir, path)
if ok then
for f in iter, dir_obj do
items = items + 1
end
-- exclude "." and ".."
items = items - 2
end
local istr = util.template(
items == 0 and _("0 items")
or items == 1 and _("1 item")
or _("%1 items"), items)
table.insert(item_table, {
text = dir.name.."/",
mandatory = istr,
path = path
})
end
for _, file in ipairs(files) do
local full_path = self.path.."/"..file.name
local file_size = lfs.attributes(full_path, "size") or 0
local sstr = ""
if file_size > 1024*1024 then
sstr = string.format("%4.1f MB", file_size/1024/1024)
elseif file_size > 1024 then
sstr = string.format("%4.1f KB", file_size/1024)
else
sstr = string.format("%d B", file_size)
end
table.insert(item_table, {
text = file.name,
mandatory = sstr,
path = full_path
})
end
-- lfs.dir iterated node string may be encoded with some weird codepage on Windows
-- we need to encode them to utf-8
if ffi.os == "Windows" then
for k, v in pairs(item_table) do
if v.text then
v.text = util.multiByteToUTF8(v.text) or ""
end
end
end
return item_table
end
function FileChooser:updateItems(select_number)
Menu.updateItems(self, select_number) -- call parent's updateItems()
self.path_items[self.path] = (self.page - 1) * self.perpage + (select_number or 1)
end
function FileChooser:refreshPath()
self:swithItemTable(nil, self:genItemTableFromPath(self.path), self.path_items[self.path])
end
function FileChooser:changeToPath(path)
path = util.realpath(path)
self.path = path
self:refreshPath()
end
function FileChooser:toggleHiddenFiles()
self.show_hidden = not self.show_hidden
self:refreshPath()
end
function FileChooser:setCollate(collate)
self.collate = collate
self:refreshPath()
end
function FileChooser:toggleReverseCollate()
self.reverse_collate = not self.reverse_collate
self:refreshPath()
end
function FileChooser:onMenuSelect(item)
-- parent directory of dir without permission get nil mode
-- we need to change to parent path in this case
if lfs.attributes(item.path, "mode") == "file" then
self:onFileSelect(item.path)
else
self:changeToPath(item.path)
end
return true
end
function FileChooser:onMenuHold(item)
self:onFileHold(item.path)
return true
end
function FileChooser:onFileSelect(file)
UIManager:close(self)
return true
end
function FileChooser:onFileHold(file)
return true
end
return FileChooser
|
fix filechooser crash on entering folder contains nil symlink
|
fix filechooser crash on entering folder contains nil symlink
|
Lua
|
agpl-3.0
|
apletnev/koreader,koreader/koreader,chrox/koreader,Hzj-jie/koreader,houqp/koreader,NiLuJe/koreader,ashhher3/koreader,mwoz123/koreader,ashang/koreader,NickSavage/koreader,chihyang/koreader,poire-z/koreader,poire-z/koreader,noname007/koreader,robert00s/koreader,lgeek/koreader,Frenzie/koreader,koreader/koreader,Markismus/koreader,mihailim/koreader,pazos/koreader,NiLuJe/koreader,Frenzie/koreader,frankyifei/koreader
|
cb15dabd04d75c268ebe74135c7faf7898f2f922
|
hammerspoon/apps/iterm.lua
|
hammerspoon/apps/iterm.lua
|
local tmux_prefix = {{'ctrl'}, 'c'}
local function isTmuxWindow()
return function ()
hs.window.focusedWindow():title():find("tmux")
end
end
local function tmuxpresskey(mod, key)
if isTmuxWindow() then
hs.eventtap.keyStroke({'ctrl'}, 'c')
hs.eventtap.keyStroke(mod, key)
return true
end
return false
end
-- App settings
local iterm2
App.new("iTerm2")
.onLaunched(function (self, app)
-- cmd+N for switching tmux windows
for i = 1,9 do
i = tostring(i)
self.bind({'cmd'}, i, function()
if isTmuxWindow() then
os.execute("/usr/local/bin/tmux select-window -t " .. i)
end
end)
end
-- new window
self.bind({'cmd'}, 'n', function()
if not tmuxpresskey({}, 'c') then
app:selectMenuItem({"Shell", "New Window"})
end
end)
-- close pane/window
self.bind({'cmd'}, 'w', function()
if not tmuxpresskey({}, 'x') then
app:selectMenuItem({"Shell", "Close"})
end
end)
end)
.bind({'cmd', 'shift'}, 'w', util.call(hs.window, 'close')) -- close pane/window
|
local tmux_prefix = {{'ctrl'}, 'c'}
-- Helpers
local function isTmuxWindow()
local win = hs.window.focusedWindow()
if win then
return win:title():find("tmux")
end
return false
end
local function tmuxPressKey(mod, key)
if isTmuxWindow() then
hs.eventtap.keyStroke({'ctrl'}, 'c')
hs.eventtap.keyStroke(mod, key)
return true
end
return false
end
-- App settings
local iterm2
App.new("iTerm2")
.onLaunched(function (self, app)
-- cmd+N for switching tmux windows
for i = 1,9 do
i = tostring(i)
self.bind({'cmd'}, i, function()
if isTmuxWindow() then
os.execute("/usr/local/bin/tmux select-window -t " .. i)
end
end)
end
-- new tmux window
self.bind({'cmd'}, 'n', function()
if not tmuxPressKey({}, 'c') then
App.find("iTerm2"):selectMenuItem({"Shell", "New Window"})
end
end)
-- new window
self.bind({'cmd', 'shift'}, 'n', function()
App.find("iTerm2"):selectMenuItem({"Shell", "New Window"})
end)
-- close pane/window
self.bind({'cmd'}, 'w', function()
if not tmuxPressKey({}, 'x') then
App.find("iTerm2"):selectMenuItem({"Shell", "Close"})
end
end)
-- detach tmux before quitting iterm
self.bind({'cmd'}, 'q', function()
if not tmuxPressKey({}, 'd') then
App.find("iTerm2"):kill()
end
end)
end)
.bind({'cmd', 'shift'}, 'w', util.call(hs.window, 'close')) -- close pane/window
|
hs: fix iterm/tmux keybinds
|
hs: fix iterm/tmux keybinds
|
Lua
|
mit
|
hlissner/dotfiles,cthachuk/dotfiles,hlissner/dotfiles,hlissner/dotfiles,hlissner/dotfiles,hlissner/dotfiles,cthachuk/dotfiles
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.