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
|
---|---|---|---|---|---|---|---|---|---|
81f734343bf1f54cd9eafe677c1cfbe484d45ab5
|
Resources/Scripts/Modes/Demo4.lua
|
Resources/Scripts/Modes/Demo4.lua
|
import('Actions')
import('ObjectLoad')
import('GlobalVars')
import('Math')
import('Scenarios')
import('PrintRecursive')
import('KeyboardControl')
local playerShip = nil
function init()
physics.open(0.6)
start_time = mode_manager.time()
last_time = mode_manager.time()
loadingEntities = true
scen = LoadScenario(2)
loadingEntities = false
for obId = 0, #scen.objects - 1 do
printTable(scen.objects[obId])
if scen.objects[obId].name == "Cruiser" and scen.objects[obId].race == 100 then
scen.objects[obId].velocity = { x = 0, y = 0 }
scen.objects[obId].angular_velocity = 0
playerShip = scen.objects[obId]
end
end
end
local camera = {w = 3000.0, h = 3000.0}
local shipAdjust = 0
function key( k )
if --[[k == "q" or]] k == "escape" then
mode_manager.switch("MainMenu")
elseif k == "=" then
camera.w = camera.w * 2
camera.h = camera.h * 2
elseif k == "-" then
camera.w = camera.w / 2
camera.h = camera.h / 2
else
KeyActivate(k)
end
end
function keyup(k)
KeyDeactivate(k)
end
normal_key = key
normal_keyup = keyup
function update()
local newTime = mode_manager.time()
dt = newTime - last_time
last_time = newTime
--[[------------------
Movement
------------------]]--
if keyboard[1][4].active == true then
if key_press_f6 ~= true then
playerShip.physics.angular_velocity = 1.0 -- [HARDCODE]
else
playerShip.physics.angular_velocity = 0.1 -- [HARDCODE]
end
elseif keyboard[1][5].active == true then
if key_press_f6 ~= true then
playerShip.physics.angular_velocity = -1.0 -- [HARDCODE]
else
playerShip.physics.angular_velocity = -0.1 -- [HARDCODE]
end
else
playerShip.physics.angular_velocity = 0
end
if keyboard[1][2].active == true then
-- apply a forward force in the direction the ship is facing
local angle = playerShip.physics.angle
local thrust = playerShip["max-thrust"] * 10000
local force = { x = thrust * math.cos(angle), y = thrust * math.sin(angle) }
playerShip.physics:apply_force(force)
elseif keyboard[1][3].active == true then
-- apply a reverse force in the direction opposite the direction the ship is MOVING
local thrust = playerShip["max-thrust"] * 10000
local force = playerShip.physics.velocity
if force.x ~= 0 or force.y ~= 0 then
if hypot(playerShip.physics.velocity.x, playerShip.physics.velocity.y) <= 10 then
playerShip.physics.velocity = { x = 0, y = 0 }
else
local velocityMag = hypot1(force)
force.x = -force.x / velocityMag
force.y = -force.y / velocityMag
force.x = force.x * thrust
force.y = force.y * thrust
if hypot1(force) > hypot1(playerShip.physics.velocity) then
playerShip.physics.velocity = { x = 0, y = 0 }
else
playerShip.physics:apply_force(force)
end
end
end
end
physics.update(dt)
end
function render()
graphics.begin_frame()
graphics.set_camera(-scen.playerShip.physics.position.x + shipAdjust - (camera.w / 2.0), -scen.playerShip.physics.position.y - (camera.h / 2.0), -scen.playerShip.physics.position.x + shipAdjust + (camera.w / 2.0), -scen.playerShip.physics.position.y + (camera.h / 2.0))
if scen ~= nil and scen.objects ~= nil then
for obId = 0, #scen.objects-1 do
local o = scen.objects[obId]
if shipAdjust < 1.0 then
graphics.draw_sprite("Id/"..o.sprite,
o.physics.position.x,
o.physics.position.y,
40,40,
o.physics.angle)
else
graphics.draw_rbox(o.physics.position.x, o.physics.position.y, 70)
end
end
end
graphics.draw_starfield(3.4)
graphics.draw_starfield(1.8)
graphics.draw_starfield(0.6)
graphics.draw_starfield(-0.3)
graphics.draw_starfield(-0.9)
graphics.end_frame()
end
function quit()
physics.close()
end
|
import('Actions')
import('ObjectLoad')
import('GlobalVars')
import('Math')
import('Scenarios')
import('PrintRecursive')
import('KeyboardControl')
local playerShip = nil
function init()
physics.open(0.6)
start_time = mode_manager.time()
last_time = mode_manager.time()
loadingEntities = true
scen = LoadScenario(2)
loadingEntities = false
for obId = 0, #scen.objects - 1 do
printTable(scen.objects[obId])
if scen.objects[obId].name == "Cruiser" and scen.objects[obId].race == 100 then
scen.objects[obId].velocity = { x = 0, y = 0 }
scen.objects[obId].angular_velocity = 0
playerShip = scen.objects[obId]
end
end
end
local camera = {w = 3000.0, h = 3000.0}
local shipAdjust = 0
function key( k )
if k == "q" or k == "escape" then
mode_manager.switch("MainMenu")
elseif k == "=" then
camera.w = camera.w / 2
camera.h = camera.h / 2
elseif k == "-" then
camera.w = camera.w * 2
camera.h = camera.h * 2
else
KeyActivate(k)
end
end
function keyup(k)
KeyDeactivate(k)
end
normal_key = key
normal_keyup = keyup
function update()
local newTime = mode_manager.time()
dt = newTime - last_time
last_time = newTime
--[[------------------
Movement
------------------]]--
if keyboard[1][4].active == true then
if key_press_f6 ~= true then
playerShip.physics.angular_velocity = 1.0 -- [HARDCODE]
else
playerShip.physics.angular_velocity = 0.1 -- [HARDCODE]
end
elseif keyboard[1][5].active == true then
if key_press_f6 ~= true then
playerShip.physics.angular_velocity = -1.0 -- [HARDCODE]
else
playerShip.physics.angular_velocity = -0.1 -- [HARDCODE]
end
else
playerShip.physics.angular_velocity = 0
end
if keyboard[1][2].active == true then
-- apply a forward force in the direction the ship is facing
local angle = playerShip.physics.angle
local thrust = playerShip["max-thrust"] * 10000
local force = { x = thrust * math.cos(angle), y = thrust * math.sin(angle) }
playerShip.physics:apply_force(force)
elseif keyboard[1][3].active == true then
-- apply a reverse force in the direction opposite the direction the ship is MOVING
local thrust = playerShip["max-thrust"] * 10000
local force = playerShip.physics.velocity
if force.x ~= 0 or force.y ~= 0 then
if hypot(playerShip.physics.velocity.x, playerShip.physics.velocity.y) <= 10 then
playerShip.physics.velocity = { x = 0, y = 0 }
else
local velocityMag = hypot1(force)
force.x = -force.x / velocityMag
force.y = -force.y / velocityMag
force.x = force.x * thrust
force.y = force.y * thrust
if hypot1(force) > hypot1(playerShip.physics.velocity) then
playerShip.physics.velocity = { x = 0, y = 0 }
else
playerShip.physics:apply_force(force)
end
end
end
end
physics.update(dt)
end
function render()
graphics.begin_frame()
graphics.set_camera(-scen.playerShip.physics.position.x + shipAdjust - (camera.w / 2.0), -scen.playerShip.physics.position.y - (camera.h / 2.0), -scen.playerShip.physics.position.x + shipAdjust + (camera.w / 2.0), -scen.playerShip.physics.position.y + (camera.h / 2.0))
graphics.draw_starfield(3.4)
graphics.draw_starfield(1.8)
graphics.draw_starfield(0.6)
graphics.draw_starfield(-0.3)
graphics.draw_starfield(-0.9)
if scen ~= nil and scen.objects ~= nil then
for obId = 0, #scen.objects-1 do
local o = scen.objects[obId]
if camera.w < 3000 then
graphics.draw_sprite("Id/"..o.sprite,
o.physics.position.x,
o.physics.position.y,
40,40,
o.physics.angle)
else
graphics.draw_rbox(o.physics.position.x, o.physics.position.y, 70)
end
end
end
graphics.end_frame()
end
function quit()
physics.close()
end
|
Fixed zooming and other small changes.
|
Fixed zooming and other small changes.
Signed-off-by: Adam Hintz <[email protected]>
|
Lua
|
mit
|
prophile/xsera,adam000/xsera,prophile/xsera,prophile/xsera,prophile/xsera,adam000/xsera,prophile/xsera,adam000/xsera,adam000/xsera
|
a3d34584d02a299340836ffecad61b5dfd4e4d30
|
modules/ansi_c/init.lua
|
modules/ansi_c/init.lua
|
-- Copyright 2007-2014 Mitchell mitchell.att.foicica.com. See LICENSE.
local M = {}
--[[ This comment is for LuaDoc.
---
-- The ansi_c module.
-- It provides utilities for editing C code.
--
-- ## Key Bindings
--
-- + `Ctrl+L, M` (`⌘L, M` on Mac OSX | `M-L, M` in curses)
-- Open this module for editing.
-- + `Shift+Enter` (`⇧↩` | `S-Enter`)
-- Add ';' to the end of the current line and insert a newline.
module('_M.ansi_c')]]
-- Autocompletion and documentation.
---
-- List of ctags files to use for autocompletion.
-- @class table
-- @name tags
M.tags = {_HOME..'/modules/ansi_c/tags', _USERHOME..'/modules/ansi_c/tags'}
local XPM = textadept.editing.XPM_IMAGES
local xpms = setmetatable({
c = XPM.CLASS, d = XPM.SLOT, e = XPM.VARIABLE, f = XPM.METHOD,
g = XPM.TYPEDEF, m = XPM.VARIABLE, s = XPM.STRUCT, t = XPM.TYPEDEF,
v = XPM.VARIABLE
}, {__index = function(t, k) return 0 end})
textadept.editing.autocompleters.ansi_c = function()
local list = {}
-- Retrieve the symbol behind the caret.
local line, pos = buffer:get_cur_line()
local symbol, op, part = line:sub(1, pos):match('([%w_]-)([%.%->]*)([%w_]*)$')
if symbol == '' and part == '' and op ~= '' then return nil end -- lone ., ->
if op ~= '' and op ~= '.' and op ~= '->' then return nil end
-- Attempt to identify the symbol type.
local buffer = buffer
local declaration = '([%w_]+)[%s%*&]+'..symbol:gsub('(%p)', '%%%1')..'[^%w_]'
for i = buffer:line_from_position(buffer.current_pos) - 1, 0, -1 do
local class = buffer:get_line(i):match(declaration)
if class then symbol = class break end
end
-- Search through ctags for completions for that symbol.
local name_patt = '^'..part
local sep = string.char(buffer.auto_c_type_separator)
for i = 1, #M.tags do
if lfs.attributes(M.tags[i]) then
for line in io.lines(M.tags[i]) do
local name = line:match('^%S+')
if name:find(name_patt) and not name:find('^!') and not list[name] then
local fields = line:match(';"\t(.*)$')
if (fields:match('class:(%S+)') or fields:match('enum:(%S+)') or
fields:match('struct:(%S+)') or fields:match('typedef:(%S+)') or
'') == symbol then
local k = xpms[fields:sub(1, 1)]
list[#list + 1] = ("%s%s%d"):format(name, sep, xpms[k])
list[name] = true
end
end
end
end
end
return #part, list
end
textadept.editing.api_files.ansi_c = {
_HOME..'/modules/ansi_c/api', _HOME..'/modules/ansi_c/lua_api',
_USERHOME..'/modules/ansi_c/api'
}
-- Commands.
---
-- Table of C-specific key bindings.
-- @class table
-- @name _G.keys.ansi_c
keys.ansi_c = {
[keys.LANGUAGE_MODULE_PREFIX] = {
m = {io.open_file, _HOME..'/modules/ansi_c/init.lua'},
},
['s\n'] = function()
buffer:line_end()
buffer:add_text(';')
buffer:new_line()
end,
}
-- Snippets.
---
-- Table of C-specific snippets.
-- @class table
-- @name _G.snippets.ansi_c
if type(snippets) == 'table' then
snippets.ansi_c = {
-- Lua snippets
lc = 'lua_call(%1(L), %2(nargs), %3(nresults))',
lcs = 'lua_checkstack(%1(L), %2(1))',
lf = 'static int %1(func)(lua_State *%2(L)) {\n\t%0\n\treturn %3(0);\n}',
lgf = 'lua_getfield(%1(L), %2(-1), %3(field))',
lgg = 'lua_getglobal(%1(L), %2(global))',
lgmt = 'lua_getmetatable(%1(L), %2(-1))',
lgt = 'lua_gettable(%1(L), %2(-2))',
ltop = 'lua_gettop(%1(L))',
lib = 'lua_isboolean(%1(L), %2(-1))',
licf = 'lua_iscfunction(%1(L), %2(-1))',
lif = 'lua_isfunction(%1(L), %2(-1))',
lilu = 'lua_islightuserdata(%1(L), %2(-1))',
linil = 'lua_isnil(%1(L), %2(-1))',
linone = 'lua_isnone(%1(L), %2(-1))',
linonen = 'lua_isnoneornil(%1(L), %2(-1))',
lin = 'lua_isnumber(%1(L), %2(-1))',
lis = 'lua_isstring(%1(L), %2(-1))',
lit = 'lua_istable(%1(L), %2(-1))',
liu = 'lua_isuserdata(%1(L), %2(-1))',
llen = 'lua_len(%1(L), %2(-1))',
lrlen = 'lua_rawlen(%1(L), %2(-1))',
lnt = 'lua_newtable(%1(L))',
lnu = '(%3 *)lua_newuserdata(%1(L), %2(sizeof(%3(struct))))',
ln = 'lua_next(%1(L), %2(-2))',
lpc = 'lua_pcall(%1(L), %2(nargs), %3(nresults), %4(msgh))',
lpop = 'lua_pop(%1(L), %2(1))',
lpb = 'lua_pushboolean(%1(L), %2(bool))',
lpcc = 'lua_pushcclosure(%1(L), %2(cfunc), %3(nvalues))',
lpcf = 'lua_pushcfunction(%1(L), %2(cfunc))',
lpi = 'lua_pushinteger(%1(L), %2(integer))',
lplu = 'lua_pushlightuserdata(%1(L), %2(pointer))',
lpnil = 'lua_pushnil(%1(L))',
lpn = 'lua_pushnumber(%1(L), %2(number))',
lps = 'lua_pushstring(%1(L), %2(string))',
lpls = 'lua_pushlstring(%1(L), %2(string), %3(len))',
lpv = 'lua_pushvalue(%1(L), %2(-1))',
lrg = 'lua_rawget(%1(L), %2(-2))',
lrgi = 'lua_rawgeti(%1(L), %2(-2), %3(1))',
lrs = 'lua_rawset(%1(L), %2(-3))',
lrsi = 'lua_rawseti(%1(L), %2(-2), %3(1))',
lr = 'lua_register(%1(L), %2(name), %3(cfunc))',
lsf = 'lua_setfield(%1(L), %2(-2), %3(field))',
lsg = 'lua_setglobal(%1(L), %2(global))',
lsmt = 'lua_setmetatable(%1(L), %2(-2))',
lst = 'lua_settable(%1(L), %2(-3))',
ltb = 'lua_toboolean(%1(L), %2(-1))',
lti = 'lua_tointeger(%1(L), %2(-1))',
ltn = 'lua_tonumber(%1(L), %2(-1))',
ltls = 'lua_tolstring(%1(L), %2(-1), &%3(int))',
lts = 'lua_tostring(%1(L), %2(-1))',
ltu = '(%3 *)lua_touserdata(%1(L), %2(-1))',
lt = 'lua_type(%1(L), %2(-1))',
llac = 'luaL_argcheck(%1(L), %2(expr), %3(1), %4(extramsg))',
llci = 'luaL_checkinteger(%1(L), %2(1))',
llcl = 'luaL_checklong(%1(L), %2(1))',
llcls = 'luaL_checklstring(%1(L), %2(1), &%3(int))',
llcn = 'luaL_checknumber(%1(L), %2(1))',
llcs = 'luaL_checkstring(%1(L), %2(1))',
llcu = '(%4 *)luaL_checkudata(%1(L), %2(1), %3(mt_name))',
llerr = 'luaL_error(%1(L), %2(message)%3(, %4(arg)))',
llgmt = 'luaL_getmetatable(%1(L), %2(mt_name))',
llnmt = 'luaL_newmetatable(%1(L), %2(mt_name))',
lloi = 'luaL_optinteger(%1(L), %2(1), %3(default))',
llol = 'luaL_optlong(%1(L), %2(1), %3(default))',
llon = 'luaL_optnumber(%1(L), %2(1), %3(default))',
llos = 'luaL_optstring(%1(L), %2(1), %3(default))',
llref = 'luaL_ref(%1(L), %2(LUA_REGISTRYINDEX))',
llsmt = 'luaL_setmetatable(%1(L), %2(mt_name))',
lluref = 'luaL_unref(%1(L), %2(LUA_REGISTRYINDEX), %3(ref))',
}
end
return M
|
-- Copyright 2007-2014 Mitchell mitchell.att.foicica.com. See LICENSE.
local M = {}
--[[ This comment is for LuaDoc.
---
-- The ansi_c module.
-- It provides utilities for editing C code.
--
-- ## Key Bindings
--
-- + `Ctrl+L, M` (`⌘L, M` on Mac OSX | `M-L, M` in curses)
-- Open this module for editing.
-- + `Shift+Enter` (`⇧↩` | `S-Enter`)
-- Add ';' to the end of the current line and insert a newline.
module('_M.ansi_c')]]
-- Autocompletion and documentation.
---
-- List of ctags files to use for autocompletion.
-- @class table
-- @name tags
M.tags = {_HOME..'/modules/ansi_c/tags', _USERHOME..'/modules/ansi_c/tags'}
local XPM = textadept.editing.XPM_IMAGES
local xpms = setmetatable({
c = XPM.CLASS, d = XPM.SLOT, e = XPM.VARIABLE, f = XPM.METHOD,
g = XPM.TYPEDEF, m = XPM.VARIABLE, s = XPM.STRUCT, t = XPM.TYPEDEF,
v = XPM.VARIABLE
}, {__index = function(t, k) return 0 end})
textadept.editing.autocompleters.ansi_c = function()
local list = {}
-- Retrieve the symbol behind the caret.
local line, pos = buffer:get_cur_line()
local symbol, op, part = line:sub(1, pos):match('([%w_]-)([%.%->]*)([%w_]*)$')
if symbol == '' and part == '' and op ~= '' then return nil end -- lone ., ->
if op ~= '' and op ~= '.' and op ~= '->' then return nil end
-- Attempt to identify the symbol type.
if symbol ~= '' then
local buffer = buffer
local declaration = '([%w_]+)[%s%*&]+'..symbol:gsub('(%p)', '%%%1')..'[^%w_]'
for i = buffer:line_from_position(buffer.current_pos) - 1, 0, -1 do
local class = buffer:get_line(i):match(declaration)
if class then symbol = class break end
end
end
-- Search through ctags for completions for that symbol.
local name_patt = '^'..part
local sep = string.char(buffer.auto_c_type_separator)
for i = 1, #M.tags do
if lfs.attributes(M.tags[i]) then
for line in io.lines(M.tags[i]) do
local name = line:match('^%S+')
if name:find(name_patt) and not name:find('^!') and not list[name] then
local fields = line:match(';"\t(.*)$')
if (fields:match('class:(%S+)') or fields:match('enum:(%S+)') or
fields:match('struct:(%S+)') or fields:match('typedef:(%S+)') or
'') == symbol then
local k = xpms[fields:sub(1, 1)]
list[#list + 1] = ("%s%s%d"):format(name, sep, xpms[k])
list[name] = true
end
end
end
end
end
return #part, list
end
textadept.editing.api_files.ansi_c = {
_HOME..'/modules/ansi_c/api', _HOME..'/modules/ansi_c/lua_api',
_USERHOME..'/modules/ansi_c/api'
}
-- Commands.
---
-- Table of C-specific key bindings.
-- @class table
-- @name _G.keys.ansi_c
keys.ansi_c = {
[keys.LANGUAGE_MODULE_PREFIX] = {
m = {io.open_file, _HOME..'/modules/ansi_c/init.lua'},
},
['s\n'] = function()
buffer:line_end()
buffer:add_text(';')
buffer:new_line()
end,
}
-- Snippets.
---
-- Table of C-specific snippets.
-- @class table
-- @name _G.snippets.ansi_c
if type(snippets) == 'table' then
snippets.ansi_c = {
-- Lua snippets
lc = 'lua_call(%1(L), %2(nargs), %3(nresults))',
lcs = 'lua_checkstack(%1(L), %2(1))',
lf = 'static int %1(func)(lua_State *%2(L)) {\n\t%0\n\treturn %3(0);\n}',
lgf = 'lua_getfield(%1(L), %2(-1), %3(field))',
lgg = 'lua_getglobal(%1(L), %2(global))',
lgmt = 'lua_getmetatable(%1(L), %2(-1))',
lgt = 'lua_gettable(%1(L), %2(-2))',
ltop = 'lua_gettop(%1(L))',
lib = 'lua_isboolean(%1(L), %2(-1))',
licf = 'lua_iscfunction(%1(L), %2(-1))',
lif = 'lua_isfunction(%1(L), %2(-1))',
lilu = 'lua_islightuserdata(%1(L), %2(-1))',
linil = 'lua_isnil(%1(L), %2(-1))',
linone = 'lua_isnone(%1(L), %2(-1))',
linonen = 'lua_isnoneornil(%1(L), %2(-1))',
lin = 'lua_isnumber(%1(L), %2(-1))',
lis = 'lua_isstring(%1(L), %2(-1))',
lit = 'lua_istable(%1(L), %2(-1))',
liu = 'lua_isuserdata(%1(L), %2(-1))',
llen = 'lua_len(%1(L), %2(-1))',
lrlen = 'lua_rawlen(%1(L), %2(-1))',
lnt = 'lua_newtable(%1(L))',
lnu = '(%3 *)lua_newuserdata(%1(L), %2(sizeof(%3(struct))))',
ln = 'lua_next(%1(L), %2(-2))',
lpc = 'lua_pcall(%1(L), %2(nargs), %3(nresults), %4(msgh))',
lpop = 'lua_pop(%1(L), %2(1))',
lpb = 'lua_pushboolean(%1(L), %2(bool))',
lpcc = 'lua_pushcclosure(%1(L), %2(cfunc), %3(nvalues))',
lpcf = 'lua_pushcfunction(%1(L), %2(cfunc))',
lpi = 'lua_pushinteger(%1(L), %2(integer))',
lplu = 'lua_pushlightuserdata(%1(L), %2(pointer))',
lpnil = 'lua_pushnil(%1(L))',
lpn = 'lua_pushnumber(%1(L), %2(number))',
lps = 'lua_pushstring(%1(L), %2(string))',
lpls = 'lua_pushlstring(%1(L), %2(string), %3(len))',
lpv = 'lua_pushvalue(%1(L), %2(-1))',
lrg = 'lua_rawget(%1(L), %2(-2))',
lrgi = 'lua_rawgeti(%1(L), %2(-2), %3(1))',
lrs = 'lua_rawset(%1(L), %2(-3))',
lrsi = 'lua_rawseti(%1(L), %2(-2), %3(1))',
lr = 'lua_register(%1(L), %2(name), %3(cfunc))',
lsf = 'lua_setfield(%1(L), %2(-2), %3(field))',
lsg = 'lua_setglobal(%1(L), %2(global))',
lsmt = 'lua_setmetatable(%1(L), %2(-2))',
lst = 'lua_settable(%1(L), %2(-3))',
ltb = 'lua_toboolean(%1(L), %2(-1))',
lti = 'lua_tointeger(%1(L), %2(-1))',
ltn = 'lua_tonumber(%1(L), %2(-1))',
ltls = 'lua_tolstring(%1(L), %2(-1), &%3(int))',
lts = 'lua_tostring(%1(L), %2(-1))',
ltu = '(%3 *)lua_touserdata(%1(L), %2(-1))',
lt = 'lua_type(%1(L), %2(-1))',
llac = 'luaL_argcheck(%1(L), %2(expr), %3(1), %4(extramsg))',
llci = 'luaL_checkinteger(%1(L), %2(1))',
llcl = 'luaL_checklong(%1(L), %2(1))',
llcls = 'luaL_checklstring(%1(L), %2(1), &%3(int))',
llcn = 'luaL_checknumber(%1(L), %2(1))',
llcs = 'luaL_checkstring(%1(L), %2(1))',
llcu = '(%4 *)luaL_checkudata(%1(L), %2(1), %3(mt_name))',
llerr = 'luaL_error(%1(L), %2(message)%3(, %4(arg)))',
llgmt = 'luaL_getmetatable(%1(L), %2(mt_name))',
llnmt = 'luaL_newmetatable(%1(L), %2(mt_name))',
lloi = 'luaL_optinteger(%1(L), %2(1), %3(default))',
llol = 'luaL_optlong(%1(L), %2(1), %3(default))',
llon = 'luaL_optnumber(%1(L), %2(1), %3(default))',
llos = 'luaL_optstring(%1(L), %2(1), %3(default))',
llref = 'luaL_ref(%1(L), %2(LUA_REGISTRYINDEX))',
llsmt = 'luaL_setmetatable(%1(L), %2(mt_name))',
lluref = 'luaL_unref(%1(L), %2(LUA_REGISTRYINDEX), %3(ref))',
}
end
return M
|
Fixed bug in ANSI C autocompletion; modules/ansi_c/init.lua
|
Fixed bug in ANSI C autocompletion; modules/ansi_c/init.lua
|
Lua
|
mit
|
rgieseke/textadept,rgieseke/textadept
|
dfc3b00abac21c0b39bc95896c4249707c5f33d2
|
Modules/Shared/IK/Torso/TorsoIKBase.lua
|
Modules/Shared/IK/Torso/TorsoIKBase.lua
|
--- Torso resources for IK
-- @classmod TorsoIKBase
-- @author Quenty
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local AccelTween = require("AccelTween")
local TorsoIKUtils = require("TorsoIKUtils")
local Signal = require("Signal")
local BaseObject = require("BaseObject")
local IKResource = require("IKResource")
local IKResourceUtils = require("IKResourceUtils")
local TorsoIKBase = setmetatable({}, BaseObject)
TorsoIKBase.__index = TorsoIKBase
TorsoIKBase.ClassName = "TorsoIKBase"
function TorsoIKBase.new(humanoid)
local self = setmetatable(BaseObject.new(), TorsoIKBase)
self._humanoid = humanoid or error("No humanoid")
self.Pointed = Signal.new() -- :Fire(position)
self._maid:GiveTask(self.Pointed)
self._resources = IKResource.new(IKResourceUtils.createResource({
name = "Character";
robloxName = self._humanoid.Parent.Name;
children = {
IKResourceUtils.createResource({
name = "RootPart";
robloxName = "HumanoidRootPart";
});
IKResourceUtils.createResource({
name = "LowerTorso";
robloxName = "LowerTorso";
});
IKResourceUtils.createResource({
name = "UpperTorso";
robloxName = "UpperTorso";
children = {
IKResourceUtils.createResource({
name = "Waist";
robloxName = "Waist";
});
};
});
IKResourceUtils.createResource({
name = "Head";
robloxName = "Head";
children = {
IKResourceUtils.createResource({
name = "Neck";
robloxName = "Neck";
});
};
});
}
}))
self._maid:GiveTask(self._resources)
self._resources:SetInstance(self._humanoid.Parent or error("No humanoid.Parent"))
self._waistY = AccelTween.new(40)
self._waistZ = AccelTween.new(30)
self._headY = AccelTween.new(60)
self._headZ = AccelTween.new(40)
self._maid:GiveTask(self._resources.ReadyChanged:Connect(function()
if self._resources:IsReady() then
self:_recordLastValidTransforms()
self:_updatePoint()
end
end))
if self._resources:IsReady() then
self:_recordLastValidTransforms()
end
return self
end
function TorsoIKBase:UpdateTransformOnly()
if not self._relWaistTransform or not self._relNeckTransform then
return
end
if not self._resources:IsReady() then
return
end
local waist = self._resources:Get("Waist")
local neck = self._resources:Get("Neck")
-- Waist:
local currentWaistTransform = waist.Transform
if self._lastWaistTransform ~= currentWaistTransform then
self._lastValidWaistTransform = currentWaistTransform
end
waist.Transform = self._lastValidWaistTransform * self._relWaistTransform
self._lastWaistTransform = waist.Transform -- NOTE: Have to read this from the weld, otherwise comparison is off
-- Neck:
local currentNeckTransform = neck.Transform
if self._lastNeckTransform ~= currentNeckTransform then
self._lastValidNeckTransform = currentNeckTransform
end
neck.Transform = self._lastValidNeckTransform * self._relNeckTransform
self._lastNeckTransform = neck.Transform -- NOTE: Have to read this from the weld, otherwise comparison is off
end
function TorsoIKBase:_recordLastValidTransforms()
assert(self._resources:IsReady())
local waist = self._resources:Get("Waist")
local neck = self._resources:Get("Neck")
self._lastValidWaistTransform = waist.Transform
self._lastWaistTransform = waist.Transform
self._lastValidNeckTransform = neck.Transform
self._lastNeckTransform = neck.Transform
end
function TorsoIKBase:Update()
self._relWaistTransform = CFrame.Angles(0, self._waistY.p, 0)
* CFrame.Angles(self._waistZ.p, 0, 0)
self._relNeckTransform = CFrame.Angles(0, self._headY.p, 0)
* CFrame.Angles(self._headZ.p, 0, 0)
self:UpdateTransformOnly()
end
function TorsoIKBase:GetTarget()
return self._target -- May return nil
end
function TorsoIKBase:Point(position)
self._target = position
if self._resources:IsReady() then
self:_updatePoint()
end
self.Pointed:Fire(self._target)
end
function TorsoIKBase:_updatePoint()
assert(self._resources:IsReady())
if self._target then
local rootPart = self._resources:Get("RootPart")
local waistY, headY, waistZ, headZ = TorsoIKUtils.getTargetAngles(rootPart, self._target)
self._waistY.t = waistY
self._headY.t = headY
self._waistZ.t = waistZ
self._headZ.t = headZ
else
self._waistY.t = 0
self._headY.t = 0
self._waistZ.t = 0
self._headZ.t = 0
end
end
--- Helper method used for other IK
function TorsoIKBase:GetTargetUpperTorsoCFrame()
if not self._resources:IsReady() then
return nil
end
local waist = self._resources:Get("Waist")
local lowerTorso = self._resources:Get("LowerTorso")
local estimated_transform = self._lastValidWaistTransform
* CFrame.Angles(0, self._waistYCalculator.Target, 0)
* CFrame.Angles(self._waistZCalculator.Target, 0, 0)
return lowerTorso.CFrame * waist.C0 * estimated_transform * waist.C1:inverse()
end
function TorsoIKBase:GetUpperTorsoCFrame()
if not self._resources:IsReady() then
return nil
end
local lowerTorso = self._resources:Get("LowerTorso")
return lowerTorso.CFrame
end
return TorsoIKBase
|
--- Torso resources for IK
-- @classmod TorsoIKBase
-- @author Quenty
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local AccelTween = require("AccelTween")
local TorsoIKUtils = require("TorsoIKUtils")
local Signal = require("Signal")
local BaseObject = require("BaseObject")
local IKResource = require("IKResource")
local IKResourceUtils = require("IKResourceUtils")
local TorsoIKBase = setmetatable({}, BaseObject)
TorsoIKBase.__index = TorsoIKBase
TorsoIKBase.ClassName = "TorsoIKBase"
function TorsoIKBase.new(humanoid)
local self = setmetatable(BaseObject.new(), TorsoIKBase)
self._humanoid = humanoid or error("No humanoid")
self.Pointed = Signal.new() -- :Fire(position)
self._maid:GiveTask(self.Pointed)
self._resources = IKResource.new(IKResourceUtils.createResource({
name = "Character";
robloxName = self._humanoid.Parent.Name;
children = {
IKResourceUtils.createResource({
name = "RootPart";
robloxName = "HumanoidRootPart";
});
IKResourceUtils.createResource({
name = "LowerTorso";
robloxName = "LowerTorso";
});
IKResourceUtils.createResource({
name = "UpperTorso";
robloxName = "UpperTorso";
children = {
IKResourceUtils.createResource({
name = "Waist";
robloxName = "Waist";
});
};
});
IKResourceUtils.createResource({
name = "Head";
robloxName = "Head";
children = {
IKResourceUtils.createResource({
name = "Neck";
robloxName = "Neck";
});
};
});
}
}))
self._maid:GiveTask(self._resources)
self._resources:SetInstance(self._humanoid.Parent or error("No humanoid.Parent"))
self._waistY = AccelTween.new(40)
self._waistZ = AccelTween.new(30)
self._headY = AccelTween.new(60)
self._headZ = AccelTween.new(40)
self._maid:GiveTask(self._resources.ReadyChanged:Connect(function()
if self._resources:IsReady() then
self:_recordLastValidTransforms()
self:_updatePoint()
end
end))
if self._resources:IsReady() then
self:_recordLastValidTransforms()
end
return self
end
function TorsoIKBase:UpdateTransformOnly()
if not self._relWaistTransform or not self._relNeckTransform then
return
end
if not self._resources:IsReady() then
return
end
local waist = self._resources:Get("Waist")
local neck = self._resources:Get("Neck")
-- Waist:
local currentWaistTransform = waist.Transform
if self._lastWaistTransform ~= currentWaistTransform then
self._lastValidWaistTransform = currentWaistTransform
end
waist.Transform = self._lastValidWaistTransform * self._relWaistTransform
self._lastWaistTransform = waist.Transform -- NOTE: Have to read this from the weld, otherwise comparison is off
-- Neck:
local currentNeckTransform = neck.Transform
if self._lastNeckTransform ~= currentNeckTransform then
self._lastValidNeckTransform = currentNeckTransform
end
neck.Transform = self._lastValidNeckTransform * self._relNeckTransform
self._lastNeckTransform = neck.Transform -- NOTE: Have to read this from the weld, otherwise comparison is off
end
function TorsoIKBase:_recordLastValidTransforms()
assert(self._resources:IsReady())
local waist = self._resources:Get("Waist")
local neck = self._resources:Get("Neck")
self._lastValidWaistTransform = waist.Transform
self._lastWaistTransform = waist.Transform
self._lastValidNeckTransform = neck.Transform
self._lastNeckTransform = neck.Transform
end
function TorsoIKBase:Update()
self._relWaistTransform = CFrame.Angles(0, self._waistY.p, 0)
* CFrame.Angles(self._waistZ.p, 0, 0)
self._relNeckTransform = CFrame.Angles(0, self._headY.p, 0)
* CFrame.Angles(self._headZ.p, 0, 0)
self:UpdateTransformOnly()
end
function TorsoIKBase:GetTarget()
return self._target -- May return nil
end
function TorsoIKBase:Point(position)
self._target = position
if self._resources:IsReady() then
self:_updatePoint()
end
self.Pointed:Fire(self._target)
end
function TorsoIKBase:_updatePoint()
assert(self._resources:IsReady())
if self._target then
local rootPart = self._resources:Get("RootPart")
local waistY, headY, waistZ, headZ = TorsoIKUtils.getTargetAngles(rootPart, self._target)
self._waistY.t = waistY
self._headY.t = headY
self._waistZ.t = waistZ
self._headZ.t = headZ
else
self._waistY.t = 0
self._headY.t = 0
self._waistZ.t = 0
self._headZ.t = 0
end
end
--- Helper method used for other IK
function TorsoIKBase:GetTargetUpperTorsoCFrame()
if not self._resources:IsReady() then
return nil
end
local waist = self._resources:Get("Waist")
local lowerTorso = self._resources:Get("LowerTorso")
local estimated_transform = self._lastValidWaistTransform
* CFrame.Angles(0, self._waistY.t, 0)
* CFrame.Angles(self._waistZ.t, 0, 0)
return lowerTorso.CFrame * waist.C0 * estimated_transform * waist.C1:inverse()
end
function TorsoIKBase:GetUpperTorsoCFrame()
if not self._resources:IsReady() then
return nil
end
local lowerTorso = self._resources:Get("LowerTorso")
return lowerTorso.CFrame
end
return TorsoIKBase
|
Fix inconsistency with TorsoIKBase
|
Fix inconsistency with TorsoIKBase
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
1cdc0118017894d17a7ee4de93ae4922091def5c
|
scen_edit/view/fields/numeric_field.lua
|
scen_edit/view/fields/numeric_field.lua
|
SB.Include(SB_VIEW_FIELDS_DIR .. "string_field.lua")
NumericField = StringField:extends{}
function NumericField:Update(source)
local v = string.format(self.format, self.value)
if source ~= self.editBox and not self.editBox.state.focused then
self.editBox:SetText(v)
end
if source ~= self.lblValue then
self.lblValue:SetCaption(v)
end
end
function NumericField:Validate(value)
local valid, value = self:super("Validate", tonumber(value))
if value then
if self.maxValue then
value = math.min(self.maxValue, value)
end
if self.minValue then
value = math.max(self.minValue, value)
end
return true, value
end
return nil
end
function NumericField:init(field)
self.decimals = 2
self.value = 0
StringField.init(self, field)
self.format = "%." .. tostring(self.decimals) .. "f"
if self.step == nil then
self.step = 1
if self.minValue and self.maxValue then
self.step = (self.maxValue - self.minValue) / 200
end
end
local v = string.format(self.format, self.value)
self.lblValue:SetCaption(v)
self.editBox:SetText(v)
self.button.OnMouseUp = {
function(...)
if not self.notClick then
return
end
SB.SetMouseCursor()
self.lblValue.font:SetColor(1, 1, 1, 1)
self.lblTitle.font:SetColor(1, 1, 1, 1)
self.lblTitle:Invalidate()
if self.startX and self.startY then
Spring.WarpMouse(self.startX, self.startY)
end
self.startX = nil
self.notClick = false
self.ev:_OnEndChange(self.name)
end
}
self.button.OnMouseMove = {
function(obj, x, y, dx, dy, btn, ...)
if btn == 1 then
local vsx, vsy = Spring.GetViewGeometry()
x, y = Spring.GetMouseState()
local _, _, _, shift = Spring.GetModKeyState()
if not self.startX then
self.startX = x
self.startY = y
self.currentX = x
self.lblValue.font:SetColor(0.96,0.83,0.09, 1)
self.lblTitle.font:SetColor(0.96,0.83,0.09, 1)
self.lblTitle:Invalidate()
end
self.currentX = x
if math.abs(x - self.startX) > 4 then
self.notClick = true
self.ev:_OnStartChange(self.name)
end
if self.notClick then
if shift then
dx = dx * 0.1
end
local value = self.value + dx * self.step
self:Set(value, obj)
end
-- FIXME: This -could- be Spring.WarpMouse(self.startX, self.startY) but it doesn't seem to work well
Spring.WarpMouse(vsx/2, vsy/2)
SB.SetMouseCursor("empty")
end
end
}
end
|
SB.Include(SB_VIEW_FIELDS_DIR .. "string_field.lua")
NumericField = StringField:extends{}
function NumericField:Update(source)
local v = string.format(self.format, self.value)
if source ~= self.editBox and not self.editBox.state.focused then
self.editBox:SetText(v)
end
if source ~= self.lblValue then
self.lblValue:SetCaption(v)
end
end
function NumericField:Validate(value)
local valid, value = self:super("Validate", tonumber(value))
if value then
if self.maxValue then
value = math.min(self.maxValue, value)
end
if self.minValue then
value = math.max(self.minValue, value)
end
return true, value
end
return nil
end
function NumericField:init(field)
self.decimals = 2
self.value = 0
StringField.init(self, field)
self.format = "%." .. tostring(self.decimals) .. "f"
if self.step == nil then
self.step = 1
if self.minValue and self.maxValue then
self.step = (self.maxValue - self.minValue) / 200
end
end
local v = string.format(self.format, self.value)
self.lblValue:SetCaption(v)
self.editBox:SetText(v)
self.button.OnMouseUp = {
function(...)
SB.SetMouseCursor()
if not self.notClick then
return
end
self.lblValue.font:SetColor(1, 1, 1, 1)
self.lblTitle.font:SetColor(1, 1, 1, 1)
self.lblTitle:Invalidate()
if self.startX and self.startY then
Spring.WarpMouse(self.startX, self.startY)
end
self.startX = nil
self.notClick = false
self.ev:_OnEndChange(self.name)
end
}
self.button.OnMouseMove = {
function(obj, x, y, dx, dy, btn, ...)
if btn ~= 1 then
return
end
local vsx, vsy = Spring.GetViewGeometry()
x, y = Spring.GetMouseState()
local _, _, _, shift = Spring.GetModKeyState()
if not self.startX then
self.startX = x
self.startY = y
self.currentX = x
self.lblValue.font:SetColor(0.96,0.83,0.09, 1)
self.lblTitle.font:SetColor(0.96,0.83,0.09, 1)
self.lblTitle:Invalidate()
end
self.currentX = x
if math.abs(x - self.startX) > 4 then
self.notClick = true
self.ev:_OnStartChange(self.name)
end
if self.notClick then
if shift then
dx = dx * 0.1
end
local value = self.value + dx * self.step
self:Set(value, obj)
-- FIXME: This -could- be but it doesn't seem to work well
-- Spring.Echo(self.startX, self.startY)
--Spring.WarpMouse(self.startX, self.startY)
Spring.WarpMouse(vsx/2, vsy/2)
SB.SetMouseCursor("empty")
end
end
}
end
|
maybe fix numeric field sometimes removing the mouse cursor
|
maybe fix numeric field sometimes removing the mouse cursor
|
Lua
|
mit
|
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
|
a9766d122e5c148f37f5bee7f8841b31393e6eec
|
state/uitest.lua
|
state/uitest.lua
|
--[[--
UI TEST STATE
----
Display some UI stuff.
--]]--
local st = RunState.new()
local Frame = getClass 'pud.ui.Frame'
local Text = getClass 'pud.ui.Text'
local Button = getClass 'pud.ui.Button'
local TextEntry = getClass 'pud.ui.TextEntry'
local Bar = getClass 'pud.ui.Bar'
local Style = getClass 'pud.ui.Style'
local n1Style = Style({font=GameFont.big, fgcolor=colors.WHITE, bgcolor=colors.DARKRED})
local h1Style = Style({font=GameFont.big, fgcolor=colors.WHITE, bgcolor=colors.LIGHTRED})
local a1Style = Style({font=GameFont.big, fgcolor=colors.WHITE, bgcolor=colors.RED})
local n2Style = Style({font=GameFont.small, fgcolor=colors.WHITE, bgcolor=colors.DARKORANGE})
local h2Style = Style({font=GameFont.small, fgcolor=colors.WHITE, bgcolor=colors.LIGHTORANGE})
local a2Style = Style({font=GameFont.small, fgcolor=colors.WHITE, bgcolor=colors.ORANGE})
local n3Style = Style({font=GameFont.small, fgcolor=colors.BLACK, bgcolor=colors.DARKYELLOW})
local h3Style = Style({font=GameFont.small, fgcolor=colors.BLACK, bgcolor=colors.LIGHTYELLOW})
local a3Style = Style({font=GameFont.small, fgcolor=colors.BLACK, bgcolor=colors.YELLOW})
local n4Style = Style({font=GameFont.verysmall, fgcolor=colors.WHITE, bgcolor=colors.DARKPURPLE})
local h4Style = Style({font=GameFont.verysmall, fgcolor=colors.WHITE, bgcolor=colors.LIGHTPURPLE})
local a4Style = Style({font=GameFont.verysmall, fgcolor=colors.WHITE, bgcolor=colors.PURPLE})
local nBarStyle = Style({font=GameFont.verysmall, fgcolor=colors.BLUE, bgcolor=colors.DARKBLUE})
local hBarStyle = Style({font=GameFont.verysmall, fgcolor=colors.LIGHTBLUE, bgcolor=colors.DARKBLUE})
function st:init()
UISystem = getClass('pud.system.UISystem')()
end
function st:enter(prevState, nextState, ...)
testFrame1 = Frame(20, 20, 600, 400)
testFrame1:setNormalStyle(n1Style)
testFrame1:setHoverStyle(h1Style)
testFrame1:setActiveStyle(a1Style)
testFrame2 = Frame(20, 450, WIDTH-40, 60)
testFrame3 = Text(20, 600, WIDTH-40, n1Style:getFont():getHeight() + 8)
testFrame3:setNormalStyle(n1Style)
testFrame3:setMargin(4)
local text1 = Text(20, 20, 560, 360)
text1:setNormalStyle(n2Style)
text1:setHoverStyle(h2Style)
text1:setActiveStyle(a2Style)
text1:setMargin(10)
text1:setMaxLines(10)
text1:setJustifyRight()
text1:setAlignCenter()
text1:setText({'UI TEST', 'Written by scx', 'for PUD'})
local button1 = Button(10, 10, 100, n4Style:getFont():getHeight() + 8)
button1:setNormalStyle(n4Style)
button1:setHoverStyle(h4Style)
button1:setActiveStyle(a4Style)
button1:setText('Button 1')
button1:setCallback('l', function(mods)
if mods.shift then testFrame3:setText('shift yeah!')
elseif mods.ctrl then testFrame3:setText('ctrl woo!')
else testFrame3:setText('yay!')
end
end)
local button2 = Button(10, 60, 100, n4Style:getFont():getHeight() + 8)
button2:setNormalStyle(n4Style)
button2:setHoverStyle(h4Style)
button2:setActiveStyle(a4Style)
button2:setText('Button 2')
button2:setCallback('l', function(mods)
if mods.shift then testFrame3:setText('it\'s-a-shift-a!')
elseif mods.ctrl then testFrame3:setText('ctrllllllllll!')
else testFrame3:setText('click!')
end
end)
local entry1 = TextEntry(10, 300, 300, n3Style:getFont():getHeight() + 8)
entry1:setNormalStyle(n3Style)
entry1:setHoverStyle(h3Style)
entry1:setActiveStyle(a3Style)
entry1:setMargin(4)
entry1:setText('EditBox')
local someval = 100
local text2 = Text(10, 120, 300, n4Style:getFont():getHeight() + 8)
text2:setNormalStyle(n4Style)
text2:setMargin(4)
text2:watch(function(s)
local text = entry1:getText() or {}
text[1] = (s or '')..(text[1] or '')
return text
end, 'Watched: ')
local bar1 = Bar(10, 180, 200, 20)
bar1:setNormalStyle(nBarStyle)
bar1:setHoverStyle(hBarStyle)
bar1:setLimits(0, 100)
bar1:setValue(someval)
bar1:watch(function()
someval = someval >= 0 and someval - 0.5 or 100
return someval
end)
text1:addChild(button1)
text1:addChild(button2)
text1:addChild(text2)
text1:addChild(entry1)
text1:addChild(bar1)
testFrame1:addChild(text1)
local cwidth = n3Style:getFont():getWidth('>') + 8
local cheight = n3Style:getFont():getHeight() + 8
local commandPrompt = Text(0, 0, cwidth, cheight)
commandPrompt:setNormalStyle(n3Style)
commandPrompt:setHoverStyle(h3Style)
commandPrompt:setActiveStyle(a3Style)
commandPrompt:setMargin(4)
commandPrompt:setText('>')
local commandEntry = TextEntry(cwidth, 0, WIDTH-(40+cwidth), cheight)
commandEntry:setNormalStyle(n3Style)
commandEntry:setHoverStyle(h3Style)
commandEntry:setActiveStyle(a3Style)
commandEntry:setMargin(4)
commandEntry:setCallback(function(e)
testFrame3:setText(table.concat(e:getText(), ' '))
e:clear()
end, commandEntry)
testFrame2:addChild(commandPrompt)
testFrame2:addChild(commandEntry)
UISystem:register(testFrame1)
UISystem:register(testFrame2)
UISystem:register(testFrame3)
end
function st:leave() end
function st:destroy()
UISystem:destroy()
UISystem = nil
end
function st:update(dt)
UISystem:update(dt)
end
function st:draw()
UISystem:draw()
end
function st:keypressed(key, unicode)
if key == 'q' then love.event.push('q') end
end
return st
|
--[[--
UI TEST STATE
----
Display some UI stuff.
--]]--
local st = RunState.new()
local Frame = getClass 'pud.ui.Frame'
local Text = getClass 'pud.ui.Text'
local Button = getClass 'pud.ui.Button'
local TextEntry = getClass 'pud.ui.TextEntry'
local Bar = getClass 'pud.ui.Bar'
local Style = getClass 'pud.ui.Style'
local n1Style = Style({font=GameFont.big, fgcolor=colors.WHITE, bgcolor=colors.DARKRED})
local h1Style = Style({font=GameFont.big, fgcolor=colors.WHITE, bgcolor=colors.LIGHTRED})
local a1Style = Style({font=GameFont.big, fgcolor=colors.WHITE, bgcolor=colors.RED})
local n2Style = Style({font=GameFont.small, fgcolor=colors.WHITE, bgcolor=colors.DARKORANGE})
local h2Style = Style({font=GameFont.small, fgcolor=colors.WHITE, bgcolor=colors.LIGHTORANGE})
local a2Style = Style({font=GameFont.small, fgcolor=colors.WHITE, bgcolor=colors.ORANGE})
local n3Style = Style({font=GameFont.small, fgcolor=colors.BLACK, bgcolor=colors.DARKYELLOW})
local h3Style = Style({font=GameFont.small, fgcolor=colors.BLACK, bgcolor=colors.LIGHTYELLOW})
local a3Style = Style({font=GameFont.small, fgcolor=colors.BLACK, bgcolor=colors.YELLOW})
local n4Style = Style({font=GameFont.verysmall, fgcolor=colors.WHITE, bgcolor=colors.DARKPURPLE})
local h4Style = Style({font=GameFont.verysmall, fgcolor=colors.WHITE, bgcolor=colors.LIGHTPURPLE})
local a4Style = Style({font=GameFont.verysmall, fgcolor=colors.WHITE, bgcolor=colors.PURPLE})
local nBarStyle = Style({font=GameFont.verysmall, fgcolor=colors.BLUE, bgcolor=colors.DARKBLUE})
local hBarStyle = Style({font=GameFont.verysmall, fgcolor=colors.LIGHTBLUE, bgcolor=colors.DARKBLUE})
function st:init()
UISystem = getClass('pud.system.UISystem')()
end
function st:enter(prevState, nextState, ...)
self._testFrame1 = Frame(20, 20, 600, 400)
self._testFrame1:setNormalStyle(n1Style)
self._testFrame1:setHoverStyle(h1Style)
self._testFrame1:setActiveStyle(a1Style)
self._testFrame2 = Frame(20, 450, WIDTH-40, 60)
self._testFrame3 = Text(20, 600, WIDTH-40, n1Style:getFont():getHeight() + 8)
self._testFrame3:setNormalStyle(n1Style)
self._testFrame3:setMargin(4)
local text1 = Text(20, 20, 560, 360)
text1:setNormalStyle(n2Style)
text1:setHoverStyle(h2Style)
text1:setActiveStyle(a2Style)
text1:setMargin(10)
text1:setMaxLines(10)
text1:setJustifyRight()
text1:setAlignCenter()
text1:setText({'UI TEST', 'Written by scx', 'for PUD'})
local button1 = Button(10, 10, 100, n4Style:getFont():getHeight() + 8)
button1:setNormalStyle(n4Style)
button1:setHoverStyle(h4Style)
button1:setActiveStyle(a4Style)
button1:setText('Button 1')
button1:setCallback('l', function(mods)
if mods.shift then self._testFrame3:setText('shift yeah!')
elseif mods.ctrl then self._testFrame3:setText('ctrl woo!')
else self._testFrame3:setText('yay!')
end
end)
local button2 = Button(10, 60, 100, n4Style:getFont():getHeight() + 8)
button2:setNormalStyle(n4Style)
button2:setHoverStyle(h4Style)
button2:setActiveStyle(a4Style)
button2:setText('Button 2')
button2:setCallback('l', function(mods)
if mods.shift then self._testFrame3:setText('it\'s-a-shift-a!')
elseif mods.ctrl then self._testFrame3:setText('ctrllllllllll!')
else self._testFrame3:setText('click!')
end
end)
local entry1 = TextEntry(10, 300, 300, n3Style:getFont():getHeight() + 8)
entry1:setNormalStyle(n3Style)
entry1:setHoverStyle(h3Style)
entry1:setActiveStyle(a3Style)
entry1:setMargin(4)
entry1:setText('EditBox')
local someval = 100
local text2 = Text(10, 120, 300, n4Style:getFont():getHeight() + 8)
text2:setNormalStyle(n4Style)
text2:setMargin(4)
text2:watch(function(s)
local text = entry1:getText() or {}
text[1] = (s or '')..(text[1] or '')
return text
end, 'Watched: ')
local bar1 = Bar(10, 180, 200, 20)
bar1:setNormalStyle(nBarStyle)
bar1:setHoverStyle(hBarStyle)
bar1:setLimits(0, 100)
bar1:setValue(someval)
bar1:watch(function()
someval = someval >= 0 and someval - 0.5 or 100
return someval
end)
text1:addChild(button1)
text1:addChild(button2)
text1:addChild(text2)
text1:addChild(entry1)
text1:addChild(bar1)
self._testFrame1:addChild(text1)
local cwidth = n3Style:getFont():getWidth('>') + 8
local cheight = n3Style:getFont():getHeight() + 8
local commandPrompt = Text(0, 0, cwidth, cheight)
commandPrompt:setNormalStyle(n3Style)
commandPrompt:setHoverStyle(h3Style)
commandPrompt:setActiveStyle(a3Style)
commandPrompt:setMargin(4)
commandPrompt:setText('>')
local commandEntry = TextEntry(cwidth, 0, WIDTH-(40+cwidth), cheight)
commandEntry:setNormalStyle(n3Style)
commandEntry:setHoverStyle(h3Style)
commandEntry:setActiveStyle(a3Style)
commandEntry:setMargin(4)
commandEntry:setCallback(function(e)
self._testFrame3:setText(table.concat(e:getText(), ' '))
e:clear()
end, commandEntry)
self._testFrame2:addChild(commandPrompt)
self._testFrame2:addChild(commandEntry)
UISystem:register(self._testFrame1)
UISystem:register(self._testFrame2)
UISystem:register(self._testFrame3)
end
function st:leave()
self._testFrame1:destroy()
self._testFrame1 = nil
self._testFrame2:destroy()
self._testFrame2 = nil
self._testFrame3:destroy()
self._testFrame3 = nil
end
function st:destroy()
UISystem:destroy()
UISystem = nil
end
function st:update(dt)
UISystem:update(dt)
end
function st:draw()
UISystem:draw()
end
function st:keypressed(key, unicode)
if key == 'q' then love.event.push('q') end
end
return st
|
fix uitest to keep references to frames
|
fix uitest to keep references to frames
ListenerBag has weak tables
|
Lua
|
mit
|
scottcs/wyx
|
a8bc48935c9775b014aad9ba49eec5acd3b22851
|
love2d/game.lua
|
love2d/game.lua
|
love.game = {}
require "world"
require "external/gui/gui"
function love.game.newGame()
local o = {}
o.state = 1
o.world = nil
o.version = "0.0.0"
o.x = 30
o.y = 20
o.xVel = 0.1
o.yVel = -0.1
o.init = function()
o.world = love.game.newWorld()
o.world.init()
o.menu = love.gui.newGui()
o.playButton = o.menu.newButton(5,5, 120, 20, "Play", nil)
o.creditsButton = o.menu.newButton(5,30, 120, 20, "Credits", nil)
o.exitButton = o.menu.newButton(5,55, 120, 20, "Exit", nil)
o.setState(states.MAIN_MENU) -- set the starting state (use e. g. MAIN_MENU if you work on the menus)
end
o.update = function(dt)
if o.state == states.MAIN_MENU then
if o.playButton.hit then
o.setState(states.GAME_PLAY)
elseif o.creditsButton.hit then
o.setState(states.CREDITS)
end
o.menu.update(dt)
elseif o.state == states.GAME_PLAY then
o.world.update(dt)
end
end
o.draw = function()
if o.state == states.MAIN_MENU then
--love.graphics.print("Main Menu!", o.x, o.y)
o.menu.draw()
elseif o.state == states.GAME_PLAY then
o.world.draw()
elseif o.state == states.CREDITS then
love.graphics.print("Credits!", o.x, o.y)
end
end
o.setState = function(state)
o.state = state
end
o.setVersion = function(version)
o.version = version
end
return o
end
|
love.game = {}
require "world"
require "external/gui/gui"
function love.game.newGame()
local o = {}
o.state = 1
o.world = nil
o.version = "0.0.0"
o.x = 30
o.y = 20
o.xVel = 0.1
o.yVel = -0.1
o.init = function()
o.world = love.game.newWorld()
o.world.init()
o.menu = love.gui.newGui()
o.playButton = o.menu.newButton(5, 5, 120, 20, "Play", nil)
o.creditsButton = o.menu.newButton(5, 30, 120, 20, "Credits", nil)
o.exitButton = o.menu.newButton(5, 55, 120, 20, "Exit", nil)
o.setState(states.MAIN_MENU) -- set the starting state (use e. g. MAIN_MENU if you work on the menus)
end
o.update = function(dt)
if o.state == states.MAIN_MENU then
if o.playButton.hit then
o.setState(states.GAME_PLAY)
elseif o.creditsButton.hit then
o.setState(states.CREDITS)
elseif o.exitButton.hit then
love.event.quit()
end
o.menu.update(dt)
elseif o.state == states.GAME_PLAY then
o.world.update(dt)
end
end
o.draw = function()
if o.state == states.MAIN_MENU then
o.menu.draw()
elseif o.state == states.GAME_PLAY then
o.world.draw()
elseif o.state == states.CREDITS then
love.graphics.print("Credits!", o.x, o.y)
end
end
o.setState = function(state)
o.state = state
end
o.setVersion = function(version)
o.version = version
end
return o
end
|
Added proper quit behaviour (and fixed tabs vs. whitespaces issue)
|
Added proper quit behaviour (and fixed tabs vs. whitespaces issue)
|
Lua
|
mit
|
nczempin/lizard-journey
|
d323776148266d3f8ad2e97d1fe191be25d65fda
|
Hydra/api.lua
|
Hydra/api.lua
|
doc.api.resourcesdir = {"api.resourcesdir -> string", "The location of the built-in lua source files."}
doc.api.userfile = {"api.userfile(name)", "Returns the full path to the file ~/.hydra/{name}.lua"}
function api.userfile(name)
return os.getenv("HOME") .. "/.hydra/" .. name .. ".lua"
end
doc.api.douserfile = {"api.douserfile(name)", "Convenience wrapper around dofile() and api.userfile(name)"}
function api.douserfile(name)
local userfile = api.userfile(name)
local exists, isdir = api.fileexists(userfile)
if exists and not isdir then
dofile(userfile)
else
api.notify.show("Hydra user-file missing", "", "Can't find file: " .. name, "")
end
end
local function load_default_config()
local defaultinit = dofile(api.resourcesdir .. "/defaultinit.lua")
defaultinit.run()
end
local function clear_old_state()
api.hotkey.disableall()
api.menu.hide()
api.pathwatcher.stopall()
api.timer.stopall()
api.textgrid.closeall()
api.notify.unregisterall()
end
doc.api.reload = {"api.reload()", "Reloads your init-file. Makes sure to clear any state that makes sense to clear (hotkeys, pathwatchers, etc)."}
function api.reload()
clear_old_state()
local userfile = os.getenv("HOME") .. "/.hydra/init.lua"
local exists, isdir = api.fileexists(userfile)
if exists and not isdir then
local ok, err = pcall(function() dofile(userfile) end)
if not ok then
api.notify.show("Hydra config error", "", err .. " -- Falling back to sample config.", "")
load_default_config()
end
else
-- don't say (via alert) anything more than what the default config already says
load_default_config()
end
end
doc.api.errorhandler = {"api.errorhandler = function(err)", "Error handler for api.call; intended for you to set, not for third party libs"}
function api.errorhandler(err)
print("Error: " .. err)
api.notify.show("Hydra Error", "", err, "error")
end
function api.tryhandlingerror(firsterr)
local ok, seconderr = pcall(function()
api.errorhandler(firsterr)
end)
if not ok then
api.notify.show("Hydra error", "", "Error while handling error: " .. seconderr .. " -- Original error: " .. firsterr, "")
end
end
doc.api.call = {"api.call(fn, ...) -> ...", "Just like pcall, except that failures are handled using api.errorhandler"}
function api.call(fn, ...)
local results = table.pack(pcall(fn, ...))
if not results[1] then
-- print(debug.traceback())
api.tryhandlingerror(results[2])
end
return table.unpack(results)
end
doc.api.uuid = {"api.uuid() -> string", "Returns a UUID as a string"}
function api.uuid()
local f = io.popen("uuidgen")
local str = f:read()
f:close()
return str
end
|
doc.api.resourcesdir = {"api.resourcesdir -> string", "The location of the built-in lua source files."}
doc.api.userfile = {"api.userfile(name)", "Returns the full path to the file ~/.hydra/{name}.lua"}
function api.userfile(name)
return os.getenv("HOME") .. "/.hydra/" .. name .. ".lua"
end
doc.api.douserfile = {"api.douserfile(name)", "Convenience wrapper around dofile() and api.userfile(name)"}
function api.douserfile(name)
local userfile = api.userfile(name)
local exists, isdir = api.fileexists(userfile)
if exists and not isdir then
dofile(userfile)
else
api.notify.show("Hydra user-file missing", "", "Can't find file: " .. tostring(name), "")
end
end
local function load_default_config()
local defaultinit = dofile(api.resourcesdir .. "/defaultinit.lua")
defaultinit.run()
end
local function clear_old_state()
api.hotkey.disableall()
api.menu.hide()
api.pathwatcher.stopall()
api.timer.stopall()
api.textgrid.closeall()
api.notify.unregisterall()
end
doc.api.reload = {"api.reload()", "Reloads your init-file. Makes sure to clear any state that makes sense to clear (hotkeys, pathwatchers, etc)."}
function api.reload()
clear_old_state()
local userfile = os.getenv("HOME") .. "/.hydra/init.lua"
local exists, isdir = api.fileexists(userfile)
if exists and not isdir then
local ok, err = pcall(function() dofile(userfile) end)
if not ok then
api.notify.show("Hydra config error", "", tostring(err) .. " -- Falling back to sample config.", "")
load_default_config()
end
else
-- don't say (via alert) anything more than what the default config already says
load_default_config()
end
end
doc.api.errorhandler = {"api.errorhandler = function(err)", "Error handler for api.call; intended for you to set, not for third party libs"}
function api.errorhandler(err)
print("Error: " .. err)
api.notify.show("Hydra Error", "", tostring(err), "error")
end
function api.tryhandlingerror(firsterr)
local ok, seconderr = pcall(function()
api.errorhandler(firsterr)
end)
if not ok then
api.notify.show("Hydra error", "", "Error while handling error: " .. tostring(seconderr) .. " -- Original error: " .. tostring(firsterr), "")
end
end
doc.api.call = {"api.call(fn, ...) -> ...", "Just like pcall, except that failures are handled using api.errorhandler"}
function api.call(fn, ...)
local results = table.pack(pcall(fn, ...))
if not results[1] then
-- print(debug.traceback())
api.tryhandlingerror(results[2])
end
return table.unpack(results)
end
doc.api.uuid = {"api.uuid() -> string", "Returns a UUID as a string"}
function api.uuid()
local f = io.popen("uuidgen")
local str = f:read()
f:close()
return str
end
|
Fixes error logging as part of #57, new bug mentioned in #61.
|
Fixes error logging as part of #57, new bug mentioned in #61.
|
Lua
|
mit
|
kkamdooong/hammerspoon,junkblocker/hammerspoon,chrisjbray/hammerspoon,tmandry/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,joehanchoi/hammerspoon,knl/hammerspoon,cmsj/hammerspoon,dopcn/hammerspoon,Hammerspoon/hammerspoon,dopcn/hammerspoon,Habbie/hammerspoon,hypebeast/hammerspoon,wvierber/hammerspoon,wvierber/hammerspoon,ocurr/hammerspoon,latenitefilms/hammerspoon,knu/hammerspoon,zzamboni/hammerspoon,emoses/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon,peterhajas/hammerspoon,Habbie/hammerspoon,wvierber/hammerspoon,Habbie/hammerspoon,heptal/hammerspoon,latenitefilms/hammerspoon,wsmith323/hammerspoon,zzamboni/hammerspoon,Stimim/hammerspoon,wsmith323/hammerspoon,kkamdooong/hammerspoon,latenitefilms/hammerspoon,TimVonsee/hammerspoon,Habbie/hammerspoon,joehanchoi/hammerspoon,junkblocker/hammerspoon,junkblocker/hammerspoon,hypebeast/hammerspoon,bradparks/hammerspoon,latenitefilms/hammerspoon,zzamboni/hammerspoon,trishume/hammerspoon,Stimim/hammerspoon,nkgm/hammerspoon,asmagill/hammerspoon,wvierber/hammerspoon,wsmith323/hammerspoon,peterhajas/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,joehanchoi/hammerspoon,CommandPost/CommandPost-App,knl/hammerspoon,knl/hammerspoon,Hammerspoon/hammerspoon,peterhajas/hammerspoon,lowne/hammerspoon,asmagill/hammerspoon,emoses/hammerspoon,junkblocker/hammerspoon,knu/hammerspoon,chrisjbray/hammerspoon,Hammerspoon/hammerspoon,bradparks/hammerspoon,Stimim/hammerspoon,asmagill/hammerspoon,bradparks/hammerspoon,hypebeast/hammerspoon,heptal/hammerspoon,wvierber/hammerspoon,CommandPost/CommandPost-App,dopcn/hammerspoon,bradparks/hammerspoon,peterhajas/hammerspoon,Stimim/hammerspoon,lowne/hammerspoon,ocurr/hammerspoon,ocurr/hammerspoon,chrisjbray/hammerspoon,latenitefilms/hammerspoon,joehanchoi/hammerspoon,TimVonsee/hammerspoon,chrisjbray/hammerspoon,zzamboni/hammerspoon,dopcn/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,emoses/hammerspoon,CommandPost/CommandPost-App,hypebeast/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,knu/hammerspoon,trishume/hammerspoon,knu/hammerspoon,kkamdooong/hammerspoon,emoses/hammerspoon,bradparks/hammerspoon,nkgm/hammerspoon,dopcn/hammerspoon,lowne/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,chrisjbray/hammerspoon,lowne/hammerspoon,peterhajas/hammerspoon,cmsj/hammerspoon,heptal/hammerspoon,hypebeast/hammerspoon,Stimim/hammerspoon,emoses/hammerspoon,TimVonsee/hammerspoon,trishume/hammerspoon,joehanchoi/hammerspoon,tmandry/hammerspoon,nkgm/hammerspoon,asmagill/hammerspoon,lowne/hammerspoon,wsmith323/hammerspoon,junkblocker/hammerspoon,kkamdooong/hammerspoon,knl/hammerspoon,knu/hammerspoon,CommandPost/CommandPost-App,tmandry/hammerspoon,wsmith323/hammerspoon,Habbie/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,Hammerspoon/hammerspoon,kkamdooong/hammerspoon,ocurr/hammerspoon,knl/hammerspoon,chrisjbray/hammerspoon,nkgm/hammerspoon,asmagill/hammerspoon,nkgm/hammerspoon,TimVonsee/hammerspoon,knu/hammerspoon,TimVonsee/hammerspoon,ocurr/hammerspoon
|
51a77b2424744ef97a70510d5597e44262721876
|
applications/luci-samba/luasrc/model/cbi/samba.lua
|
applications/luci-samba/luasrc/model/cbi/samba.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("samba")
s = m:section(TypedSection, "samba", "Samba")
s.anonymous = true
s:option(Value, "name")
s:option(Value, "description")
s:option(Value, "workgroup")
s:option(Flag, "homes")
s = m:section(TypedSection, "sambashare")
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "name", translate("name"))
s:option(Value, "path").titleref = luci.dispatcher.build_url("admin", "system", "fstab")
s:option(Value, "users").rmempty = true
ro = s:option(Flag, "read_only")
ro.enabled = "yes"
ro.disabled = "no"
go = s:option(Flag, "guest_ok")
go.enabled = "yes"
go.disabled = "no"
cm = s:option(Value, "create_mask")
cm.rmempty = true
cm.size = 4
dm = s:option(Value, "dir_mask")
dm.rmempty = true
dm.size = 4
return m
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Copyright 2008 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("samba")
s = m:section(TypedSection, "samba", "Samba")
s.anonymous = true
s:option(Value, "name")
s:option(Value, "description")
s:option(Value, "workgroup")
s:option(Flag, "homes")
s = m:section(TypedSection, "sambashare")
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "name", translate("name"))
s:option(Value, "path").titleref = luci.dispatcher.build_url("admin", "system", "fstab")
s:option(Value, "users").rmempty = true
ro = s:option(Flag, "read_only")
ro.rmempty = false
ro.enabled = "yes"
ro.disabled = "no"
go = s:option(Flag, "guest_ok")
go.rmempty = false
go.enabled = "yes"
go.disabled = "no"
cm = s:option(Value, "create_mask")
cm.rmempty = true
cm.size = 4
dm = s:option(Value, "dir_mask")
dm.rmempty = true
dm.size = 4
return m
|
Fix samba "read only" and "guest ok" settings not applied correctly.
|
Fix samba "read only" and "guest ok" settings not applied correctly.
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@3972 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
4f4e54616c063efcd603800c024ee8819e832765
|
modules/lua/init.lua
|
modules/lua/init.lua
|
-- Copyright 2007-2011 Mitchell mitchell<att>caladbolg.net. See LICENSE.
---
-- The lua module.
-- It provides utilities for editing Lua code.
-- User tags are loaded from _USERHOME/modules/lua/tags and user apis are loaded
-- from _USERHOME/modules/lua/api.
module('_m.lua', package.seeall)
-- Markdown:
-- ## Key Commands
--
-- + `Alt+L, M`: Open this module for editing.
-- + `Alt+L, G`: Goto file being 'require'd on the current line.
-- + `Shift+Return`: Try to autocomplete an `if`, `for`, etc. statement with
-- `end`.
-- + `.`: When to the right of a known symbol, show an autocompletion list of
-- fields and functions.
-- + `:`: When to the right of a known symbol, show an autocompletion list of
-- functions only.
-- + `Ctrl+I`: (Windows and Linux) Autocomplete symbol.
-- + `Ctrl+Esc`: (Mac OSX) Autocomplete symbol.
-- + `Ctrl+H`: Show documentation for the selected symbol or the symbol under
-- the caret.
--
-- ## Fields
--
-- * `sense`: The Lua [Adeptsense](_m.textadept.adeptsense.html).
local m_editing, m_run = _m.textadept.editing, _m.textadept.run
-- Comment string tables use lexer names.
m_editing.comment_string.lua = '--'
-- Compile and Run command tables use file extensions.
m_run.run_command.lua = 'lua %(filename)'
m_run.error_detail.lua = {
pattern = '^lua: (.-):(%d+): (.+)$',
filename = 1, line = 2, message = 3
}
---
-- Sets default buffer properties for Lua files.
function set_buffer_properties()
end
-- Adeptsense.
sense = _m.textadept.adeptsense.new('lua')
sense.syntax.class_definition = 'module%s*%(?%s*[\'"]([%w_%.]+)'
sense.syntax.symbol_chars = '[%w_%.:]'
sense.syntax.type_declarations = {}
sense.syntax.type_assignments = {
['^[\'"]'] = 'string', -- foo = 'bar' or foo = "bar"
['^([%w_%.]+)%s*$'] = '%1', -- foo = _m.textadept.adeptsense
['^(_m%.textadept%.adeptsense)%.new'] = '%1',
['require%s*%(?%s*(["\'])([%w_%.]+)%1%)?'] = '%2',
['^io%.p?open%s*%b()%s*$'] = 'file'
}
sense.api_files = { _HOME..'/modules/lua/api' }
sense:add_trigger('.')
sense:add_trigger(':', false, true)
-- script/update_doc generates a fake set of ctags used for autocompletion.
sense.ctags_kinds = {
f = 'functions',
F = 'fields',
m = 'classes',
t = 'fields',
}
sense:load_ctags(_HOME..'/modules/lua/tags', true)
-- Strips '_G' from symbols since it's implied.
function sense:get_class(symbol)
return self.super.get_class(self, symbol:gsub('_G%.?', ''))
end
-- Shows an autocompletion list for the symbol behind the caret.
-- If the symbol contains a ':', only display functions. Otherwise, display
-- both functions and fields.
function sense:complete(only_fields, only_functions)
local line, pos = buffer:get_cur_line()
local symbol = line:sub(1, pos):match(self.syntax.symbol_chars..'*$')
return self.super.complete(self, false, symbol:find(':'))
end
-- Load user tags and apidoc.
if lfs.attributes(_USERHOME..'/modules/lua/tags') then
sense:load_ctags(_USERHOME..'/modules/lua/tags')
end
if lfs.attributes(_USERHOME..'/modules/lua/api') then
sense.api_files[#sense.api_files + 1] = _USERHOME..'/modules/lua/api'
end
-- Commands.
---
-- Patterns for auto 'end' completion for control structures.
-- @class table
-- @name control_structure_patterns
-- @see try_to_autocomplete_end
local control_structure_patterns = {
'^%s*for', '^%s*function', '^%s*if', '^%s*repeat', '^%s*while',
'function%s*%b()%s*$', '^%s*local%s*function'
}
---
-- Tries to autocomplete Lua's 'end' keyword for control structures like 'if',
-- 'while', 'for', etc.
-- @see control_structure_patterns
function try_to_autocomplete_end()
local buffer = buffer
local line_num = buffer:line_from_position(buffer.current_pos)
local line = buffer:get_line(line_num)
local line_indentation = buffer.line_indentation
for _, patt in ipairs(control_structure_patterns) do
if line:find(patt) then
local indent = line_indentation[line_num]
buffer:begin_undo_action()
buffer:new_line()
buffer:new_line()
buffer:add_text(patt:find('repeat') and 'until' or 'end')
line_indentation[line_num + 1] = indent + buffer.indent
buffer:line_up()
buffer:line_end()
buffer:end_undo_action()
return true
end
end
return false
end
---
-- Determines the Lua file being 'require'd, searches through package.path for
-- that file, and opens it in Textadept.
function goto_required()
local line = buffer:get_cur_line()
local patterns = { 'require%s*(%b())', 'require%s*(([\'"])[^%2]+%2)' }
local file
for _, patt in ipairs(patterns) do
file = line:match(patt)
if file then break end
end
if not file then return end
file = file:sub(2, -2):gsub('%.', '/')
for path in package.path:gmatch('[^;]+') do
path = path:gsub('?', file)
if lfs.attributes(path) then
io.open_file(path:iconv('UTF-8', _CHARSET))
break
end
end
end
events.connect(events.FILE_AFTER_SAVE,
function() -- show syntax errors as annotations
if buffer:get_lexer() == 'lua' then
local buffer = buffer
buffer:annotation_clear_all()
local text = buffer:get_text()
text = text:gsub('^#![^\n]+', '') -- ignore shebang line
local _, err = loadstring(text)
if err then
local line, msg = err:match('^.-:(%d+):%s*(.+)$')
if line then
buffer.annotation_visible = 2
buffer:annotation_set_text(line - 1, msg)
buffer.annotation_style[line - 1] = 8 -- error style number
buffer:goto_line(line - 1)
end
end
end
end)
---
-- Container for Lua-specific key commands.
-- @class table
-- @name _G.keys.lua
keys.lua = {
al = {
m = { io.open_file,
(_HOME..'/modules/lua/init.lua'):iconv('UTF-8', _CHARSET) },
g = { goto_required },
},
['s\n'] = { try_to_autocomplete_end },
[not OSX and 'ci' or 'cesc'] = { sense.complete, sense },
ch = { sense.show_apidoc, sense },
}
-- Snippets.
if type(snippets) == 'table' then
---
-- Container for Lua-specific snippets.
-- @class table
-- @name _G.snippets.lua
snippets.lua = {
l = "local %1(expr)%2( = %3(value))",
p = "print(%0)",
f = "function %1(name)(%2(args))\n\t%0\nend",
['for'] = "for i = %1(1), %2(10)%3(, -1) do\n\t%0\nend",
fori = "for %1(i), %2(val) in ipairs(%3(table)) do\n\t%0\nend",
forp = "for %1(k), %2(v) in pairs(%3(table)) do\n\t%0\nend",
}
end
|
-- Copyright 2007-2011 Mitchell mitchell<att>caladbolg.net. See LICENSE.
---
-- The lua module.
-- It provides utilities for editing Lua code.
-- User tags are loaded from _USERHOME/modules/lua/tags and user apis are loaded
-- from _USERHOME/modules/lua/api.
module('_m.lua', package.seeall)
-- Markdown:
-- ## Key Commands
--
-- + `Alt+L, M`: Open this module for editing.
-- + `Alt+L, G`: Goto file being 'require'd on the current line.
-- + `Shift+Return`: Try to autocomplete an `if`, `for`, etc. statement with
-- `end`.
-- + `.`: When to the right of a known symbol, show an autocompletion list of
-- fields and functions.
-- + `:`: When to the right of a known symbol, show an autocompletion list of
-- functions only.
-- + `Ctrl+I`: (Windows and Linux) Autocomplete symbol.
-- + `Ctrl+Esc`: (Mac OSX) Autocomplete symbol.
-- + `Ctrl+H`: Show documentation for the selected symbol or the symbol under
-- the caret.
--
-- ## Fields
--
-- * `sense`: The Lua [Adeptsense](_m.textadept.adeptsense.html).
local m_editing, m_run = _m.textadept.editing, _m.textadept.run
-- Comment string tables use lexer names.
m_editing.comment_string.lua = '--'
-- Compile and Run command tables use file extensions.
m_run.run_command.lua = 'lua %(filename)'
m_run.error_detail.lua = {
pattern = '^lua: (.-):(%d+): (.+)$',
filename = 1, line = 2, message = 3
}
---
-- Sets default buffer properties for Lua files.
function set_buffer_properties()
end
-- Adeptsense.
sense = _m.textadept.adeptsense.new('lua')
sense.syntax.class_definition = 'module%s*%(?%s*[\'"]([%w_%.]+)'
sense.syntax.symbol_chars = '[%w_%.:]'
sense.syntax.type_declarations = {}
sense.syntax.type_assignments = {
['^[\'"]'] = 'string', -- foo = 'bar' or foo = "bar"
['^([%w_%.]+)%s*$'] = '%1', -- foo = _m.textadept.adeptsense
['^(_m%.textadept%.adeptsense)%.new'] = '%1',
['require%s*%(?%s*(["\'])([%w_%.]+)%1%)?'] = '%2',
['^io%.p?open%s*%b()%s*$'] = 'file'
}
sense.api_files = { _HOME..'/modules/lua/api' }
sense:add_trigger('.')
sense:add_trigger(':', false, true)
-- script/update_doc generates a fake set of ctags used for autocompletion.
sense.ctags_kinds = {
f = 'functions',
F = 'fields',
m = 'classes',
t = 'fields',
}
sense:load_ctags(_HOME..'/modules/lua/tags', true)
-- Strips '_G' from symbols since it's implied.
function sense:get_class(symbol)
if symbol:find('^_G') then
symbol = symbol:gsub('_G%.?', '')
if symbol == '' then return '' end
end
return self.super.get_class(self, symbol)
end
-- Shows an autocompletion list for the symbol behind the caret.
-- If the symbol contains a ':', only display functions. Otherwise, display
-- both functions and fields.
function sense:complete(only_fields, only_functions)
local line, pos = buffer:get_cur_line()
local symbol = line:sub(1, pos):match(self.syntax.symbol_chars..'*$')
return self.super.complete(self, false, symbol:find(':'))
end
-- Load user tags and apidoc.
if lfs.attributes(_USERHOME..'/modules/lua/tags') then
sense:load_ctags(_USERHOME..'/modules/lua/tags')
end
if lfs.attributes(_USERHOME..'/modules/lua/api') then
sense.api_files[#sense.api_files + 1] = _USERHOME..'/modules/lua/api'
end
-- Commands.
---
-- Patterns for auto 'end' completion for control structures.
-- @class table
-- @name control_structure_patterns
-- @see try_to_autocomplete_end
local control_structure_patterns = {
'^%s*for', '^%s*function', '^%s*if', '^%s*repeat', '^%s*while',
'function%s*%b()%s*$', '^%s*local%s*function'
}
---
-- Tries to autocomplete Lua's 'end' keyword for control structures like 'if',
-- 'while', 'for', etc.
-- @see control_structure_patterns
function try_to_autocomplete_end()
local buffer = buffer
local line_num = buffer:line_from_position(buffer.current_pos)
local line = buffer:get_line(line_num)
local line_indentation = buffer.line_indentation
for _, patt in ipairs(control_structure_patterns) do
if line:find(patt) then
local indent = line_indentation[line_num]
buffer:begin_undo_action()
buffer:new_line()
buffer:new_line()
buffer:add_text(patt:find('repeat') and 'until' or 'end')
line_indentation[line_num + 1] = indent + buffer.indent
buffer:line_up()
buffer:line_end()
buffer:end_undo_action()
return true
end
end
return false
end
---
-- Determines the Lua file being 'require'd, searches through package.path for
-- that file, and opens it in Textadept.
function goto_required()
local line = buffer:get_cur_line()
local patterns = { 'require%s*(%b())', 'require%s*(([\'"])[^%2]+%2)' }
local file
for _, patt in ipairs(patterns) do
file = line:match(patt)
if file then break end
end
if not file then return end
file = file:sub(2, -2):gsub('%.', '/')
for path in package.path:gmatch('[^;]+') do
path = path:gsub('?', file)
if lfs.attributes(path) then
io.open_file(path:iconv('UTF-8', _CHARSET))
break
end
end
end
events.connect(events.FILE_AFTER_SAVE,
function() -- show syntax errors as annotations
if buffer:get_lexer() == 'lua' then
local buffer = buffer
buffer:annotation_clear_all()
local text = buffer:get_text()
text = text:gsub('^#![^\n]+', '') -- ignore shebang line
local _, err = loadstring(text)
if err then
local line, msg = err:match('^.-:(%d+):%s*(.+)$')
if line then
buffer.annotation_visible = 2
buffer:annotation_set_text(line - 1, msg)
buffer.annotation_style[line - 1] = 8 -- error style number
buffer:goto_line(line - 1)
end
end
end
end)
---
-- Container for Lua-specific key commands.
-- @class table
-- @name _G.keys.lua
keys.lua = {
al = {
m = { io.open_file,
(_HOME..'/modules/lua/init.lua'):iconv('UTF-8', _CHARSET) },
g = { goto_required },
},
['s\n'] = { try_to_autocomplete_end },
[not OSX and 'ci' or 'cesc'] = { sense.complete, sense },
ch = { sense.show_apidoc, sense },
}
-- Snippets.
if type(snippets) == 'table' then
---
-- Container for Lua-specific snippets.
-- @class table
-- @name _G.snippets.lua
snippets.lua = {
l = "local %1(expr)%2( = %3(value))",
p = "print(%0)",
f = "function %1(name)(%2(args))\n\t%0\nend",
['for'] = "for i = %1(1), %2(10)%3(, -1) do\n\t%0\nend",
fori = "for %1(i), %2(val) in ipairs(%3(table)) do\n\t%0\nend",
forp = "for %1(k), %2(v) in pairs(%3(table)) do\n\t%0\nend",
}
end
|
Fixed bug introduced by stripping '_G' in Lua Adeptsense; modules/lua/init.lua
|
Fixed bug introduced by stripping '_G' in Lua Adeptsense; modules/lua/init.lua
|
Lua
|
mit
|
rgieseke/textadept,rgieseke/textadept
|
9db8b6f3fa34b18537e27106beed60c6b05d4a46
|
nodes/basic/node.lua
|
nodes/basic/node.lua
|
--RasPegacy v0.1
--Basic Round Gauge Child
gl.setup(720, 446)
--local res = util.auto_loader()
local gothic = resource.load_font "Exo2.otf"
util.resource_loader{
"needle.png",
}
local json = require "json"
util.file_watch("view.json", function(content)
view = json.decode(content)
cur = view.view
steps = string.format(cur.top .. cur.mid .. cur.color .. '.png')
res = resource.load_image(steps)
end)
local function gauge(conf)
local x = conf.x
local y = conf.y
local size = conf.size or 150
local value = 0
local needle_rot = 0
local function draw()
--print("rotate:" .. tostring(needle_rot))
res:draw(x-size/2, y-size/2, x+size/2, y+size/2)
gl.pushMatrix()
gl.translate(x+0.5, y+0.5)
gl.rotate(-135 + 271 * needle_rot, 0, 0, 1)
needle:draw(-size/2, -size/2, size/2, size/2,0.8)
gl.popMatrix()
gothic:write(x-12, y+(y/8), string.sub(value, 0, 4), 18, 1, 1, 1, 1)
end
local function set(new_value)
value = new_value
--print("value:" .. tostring(value))
end
local function needle_set(new_value)
needle_rot = new_value
end
return {
draw = draw;
set = set;
needle_set = needle_set;
}
end
node.alias("gauge")
local gauges = {
boost = gauge{
x = 120;
y = 200;
size = 240;
};
opress = gauge{
x = 360;
y = 200;
size = 240;
};
val1 = gauge{
x = 600;
y = 200;
size = 240;
};
}
util.data_mapper{
["(.*)/set"] = function(gauge, value)
gauges[gauge].set(tonumber(value))
end;
["(.*)/needle_rot"] = function(gauge, needle_rot)
gauges[gauge].needle_set(tonumber(needle_rot))
end;
}
function node.render()
gl.clear(0,0,0,0)
-- Static text
gothic:write(85, 20, "BOOST", 16, 1, 1, 1, 1)
gothic:write(30, 260, "-20", 14, 1, 1, 1, 1)
gothic:write(192, 260, "20", 14, 1, 1, 1, 1)
gothic:write(300, 20, "OIL PRESSURE", 16, 1, 1, 1, 1)
gothic:write(270, 260, "0", 14, 1, 1, 1, 1)
gothic:write(432, 260, "250", 14, 1, 1, 1, 1)
gothic:write(560, 20, "VAL1", 16, 1, 1, 1, 1)
gothic:write(515, 260, "0", 14, 1, 1, 1, 1)
gothic:write(675, 260, "YES", 14, 1, 1, 1, 1)
for _, gauge in pairs(gauges) do
gauge.draw()
end
end
|
--RasPegacy v0.1
--Basic Round Gauge Child
gl.setup(720, 446)
--local res = util.auto_loader()
local gothic = resource.load_font "Exo2.otf"
util.resource_loader{
"needle.png",
}
local json = require "json"
util.file_watch("view.json", function(content)
view = json.decode(content)
cur = view.view
steps = string.format(cur.top .. cur.mid .. cur.color .. '.png')
res = resource.load_image(steps)
end)
local function gauge(conf)
local x = conf.x
local y = conf.y
local size = conf.size or 150
local value = 0
local needle_rot = 0
local function draw()
--print("rotate:" .. tostring(needle_rot))
res:draw(x-size/2, y-size/2, x+size/2, y+size/2)
gl.pushMatrix()
gl.translate(x+0.5, y+0.5)
gl.rotate(-135 + 271 * needle_rot, 0, 0, 1)
needle:draw(-size/2, -size/2, size/2, size/2,0.8)
gl.popMatrix()
gothic:write(x-12, y+(y/8), string.sub(value, 0, 4), 18, 1, 1, 1, 1)
end
local function set(new_value)
value = new_value
--print("value:" .. tostring(value))
end
local function needle_set(new_value)
needle_rot = new_value
end
return {
draw = draw;
set = set;
needle_set = needle_set;
}
end
node.alias("gauge")
local gauges = {
boost = gauge{
x = 120;
y = 200;
size = 240;
};
opress = gauge{
x = 360;
y = 200;
size = 240;
};
val1 = gauge{
x = 600;
y = 200;
size = 240;
};
}
util.data_mapper{
["(.*)/set"] = function(gauge, value)
gauges[gauge].set(tonumber(value))
end;
["(.*)/needle_rot"] = function(gauge, needle_rot)
gauges[gauge].needle_set(tonumber(needle_rot))
end;
}
function node.render()
gl.clear(0,0,0,0)
-- Draw gauges
for _, gauge in pairs(gauges) do
gauge.draw()
end
-- Static text
gothic:write(85, 20, "BOOST", 16, 1, 1, 1, 1)
gothic:write(30, 260, "-20", 14, 1, 1, 1, 1)
gothic:write(192, 260, "20", 14, 1, 1, 1, 1)
gothic:write(300, 20, "OIL PRESSURE", 16, 1, 1, 1, 1)
gothic:write(270, 260, "0", 14, 1, 1, 1, 1)
gothic:write(432, 260, "250", 14, 1, 1, 1, 1)
gothic:write(560, 20, "VAL1", 16, 1, 1, 1, 1)
gothic:write(515, 260, "0", 14, 1, 1, 1, 1)
gothic:write(675, 260, "YES", 14, 1, 1, 1, 1)
end
|
move gauge draw
|
move gauge draw
static text was being "overwritten" when the gauges were drawn. moved gauge drawing before static text writes, to see if it fixes the problem.
|
Lua
|
apache-2.0
|
sommersoft/RasPegacy
|
35a1c34da6f7e15ea591705f38a67d1dffe9dc3c
|
codes/boss_kullerball.lua
|
codes/boss_kullerball.lua
|
--[[
Waffenboss Kullerball
Copyright by Prismatic-Network
Copyright by Fabian Fassott aka Psykko
ScriptComplete: 85%
boss_kullerbro script missing in Phase 2
]]--
-- Local
local kullerball_id = 60000
local spell2ziel = Unit:RandomPlayer(0)
local npc_buffs = {
["buffs"] = {48469,48161,20217,25898,56520}
}
local player_buffs = 69127
local SPELL_FLAMMENSTOSS = 62998
local SPELL_METEORSCHLAG = 75877
local SPELL_SCHMETTERN = 666683
local SPELL_WIRBELN = 67345
local SPELL_AATEM = 67345
local SPELL_KOPFSTOSS = 66770
local SPELL_HEILEN = 71131
local SPELL_KRAFT = 82396
-- ####### Haupt Codebox Start
-- Funktion "OnCombat"
function Kullerball_OnCombat(Unit, Event, pPlayer) -- Funktion bei Kampf beginn.
Unit:SendChatMessage(14, 0, "Endlich eine w\195\188rdige Herausforderung!")
for _, npcbuff in ipairs[npc_buffs.buffs] do
Unit:CastSpell(npcbuff)
pPlayer:CastSpell(69127)
end
Unit:RegisterEvent("Kullerball_Phase1", 5000, 0)
end
-- Funktion "Phase1"
-- Phase 1 Start
function Kullerball_Phase1(Unit, Event)
Unit:RemoveEvents()
Unit:RegisterEvent("Kullerball_Meteorschlag", 10000, 0)
Unit:RegisterEvent("Kullerball_Aatem", 15000, 0)
Unit:RegisterEvent("Kullerball_Kopfstoss", 5000, 0)
Unit:RegisterEvent("Kullerball_Flammenstoss", 7000, 0)
Unit:RegisterEvent("Kullerball_Schmettern", 12000, 0)
Unit:RegisterEvent("Kullerball_Wirbeln", 30000, 0)
Unit:RegisterEvent("Kullerball_Phase2", 50000, 0)
end
-- Funktion "Kullerball_Meteorschlag"
function Kullerball_Meteorschlag(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_METEORSCHLAG, spell2ziel)
Unit:SendChatMessage(12, "FEUER FREI!")
end
-- Funktion "Kullerball_Aatem"
function Kullerball_Aatem(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_AATEM, spell2ziel)
Unit:SendChatMessage(12, "Werdet zu Eis!")
end
-- Funktion "Kullerball_Kopfstoss"
function Kullerball_Kopfstoss(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_KOPFSTOSS, spell2ziel)
Unit:SendChatMessage(12, "Wie gefällt euch das?")
end
-- Funktion "Kullerball_Flammenstoss"
function Kullerball_Flammenstoss(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_FLAMMENSTOSS, spell2ziel)
Unit:SendChatMessage(12, "BRENNT!")
end
-- Funktion "Kullerball_Schmettern"
function Kullerball_Schmettern(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_SCHMETTERN, spell2ziel)
Unit:SendChatMessage(12, "HUAAH!")
end
-- Funktion "Kullerball_Wirbeln"
function Kullerball_Wirbeln(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_WIRBELN, spell2ziel)
Unit:SendChatMessage(12, "Weg von mir!")
end
-- Phase 1 Ende
-- Funktion "Phase2"
-- Phase 2 Start
function Kullerball_Phase2(Unit, Event)
if Unit:GetHealthPct () > 60 then
end
Unit:RemoveEvents()
Unit:SendChatMessage(12, "Argh, Ich muss mir Hilfe holen, Bruder komme und helfe mir! Halte diese Kreaturen von mir fern wärend ich mich Heile!")
Unit:SpawnCreature(60001, x , y, z, o, 16, 350000)
Unit:RegisterEvent("Kullerball_Heilen", 5000, 0)
end
-- Funktion "Kullerball_Heilen"
function Kullerball_Heilen(Unit, Event)
Unit:CastSpell(SPELL_HEILEN)
Unit:SendChatMessage(12, "Capernian gib mir Kraft!")
Unit:RegisterEvent("Kullerball_Phase3", 50000, 0)
end
-- Phase 2 Ende
-- Funktion "Phase3"
-- Phase 3 Start
function Kullerball_Phase3(Unit, Event)
if Unit:GetHealthPct () > 40 then
end
Unit:RemoveEvents()
Unit:SendChatMessage(12, "Argh, ich verliere! CAPERNIAN!? GIB MIR DEINE KRAFT!")
Unit:RegisterEvent("Kullerball_KRAFT", 20000, 0)
end
-- Funktion "Kullerball_Kraft"
function Kullerball_KRAFT(Unit, Event)
Unit:CastSpell(SPELL_HEILEN)
Unit:SendChatMessage(12, "Capernian gib mir Kraft!")
Unit:RegisterEvent("Kullerball_Phase4", 50000, 0)
end
-- Phase 3 Ende
-- Funktion "Phase4"
-- Phase 4 Start
function Kullerball_Phase3(Unit, Event)
if Unit:GetHealthPct () > 20 then
end
Unit:RemoveEvents()
Unit:SendChatMessage(12, "Es ist an der Zeit das ich Richtig austeile!")
end
Unit:RegisterEvent("Kullerball_Meteorschlag", 10000, 0)
Unit:RegisterEvent("Kullerball_Aatem", 15000, 0)
Unit:RegisterEvent("Kullerball_Kopfstoss", 5000, 0)
Unit:RegisterEvent("Kullerball_Flammenstoss", 7000, 0)
Unit:RegisterEvent("Kullerball_Schmettern", 12000, 0)
Unit:RegisterEvent("Kullerball_Wirbeln", 30000, 0)
Unit:RegisterEvent("Kullerball_Phase2", 50000, 0)
end
-- Funktion "Kullerball_Meteorschlag"
function Kullerball_Meteorschlag(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_METEORSCHLAG, spell2ziel)
Unit:SendChatMessage(12, "FEUER FREI!")
end
-- Funktion "Kullerball_Aatem"
function Kullerball_Aatem(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_AATEM, spell2ziel)
Unit:SendChatMessage(12, "Werdet zu Eis!")
end
-- Funktion "Kullerball_Kopfstoss"
function Kullerball_Kopfstoss(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_KOPFSTOSS, spell2ziel)
Unit:SendChatMessage(12, "Wie gefällt euch das?")
end
-- Funktion "Kullerball_Flammenstoss"
function Kullerball_Flammenstoss(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_FLAMMENSTOSS, spell2ziel)
Unit:SendChatMessage(12, "BRENNT!")
end
-- Funktion "Kullerball_Schmettern"
function Kullerball_Schmettern(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_SCHMETTERN, spell2ziel)
Unit:SendChatMessage(12, "HUAAH!")
end
-- Funktion "Kullerball_Wirbeln"
function Kullerball_Wirbeln(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_WIRBELN, spell2ziel)
Unit:SendChatMessage(12, "Weg von mir!")
end
-- Phase 4 Ende
-- Function "Kullerball_OnLeaveCombat"
function Kullerball_OnLeaveCombat(Unit, Event) -- Funktion beim Kampf verlassen.
Unit:SendChatMessage(14, 0, "Das war etwa alles? Ich hatte mir erhofft!")
end
-- Function "Kullerball_OnKilledTarget"
function Kullerball_OnKilledTarget(Unit, Event) -- Funktion beim Spieler Takedown.
Unit:SendChatMessage(14, 0, ""..pPlayer:GetName..", du bist zu schwach!")
end
-- Function "Kullerball_OnDied"
function Kullerball_OnDied(Unit, Event) -- Funktion beim Sterben.
Unit:SendChatMessage(14, 0, "Capernian wird mich Rächen!")
end
-- ####### Haupt Codebox Ende
-- Register
RegisterUnitEvent(kullerball_id, 1, "Kullerball_OnCombat")
RegisterUnitEvent(kullerball_id, 2, "Kullerball_OnLeaveCombat")
RegisterUnitEvent(kullerball_id, 3, "Kullerball_OnKilledTarget")
RegisterUnitEvent(kullerball_id, 4, "Kullerball_OnDied")
|
--[[
Waffenboss Kullerball
Copyright by Prismatic-Network
Copyright by Fabian Fassott aka Psykko
ScriptComplete: 85%
boss_kullerbro script missing in Phase 2
]]--
-- Local
local kullerball_id = 60000
local spell2ziel = Unit:GetRandomEnemy()
local npc_buffs = {
["buffs"] = {48469,48161,20217,25898,56520}
}
local player_buffs = 69127
local SPELL_FLAMMENSTOSS = 62998
local SPELL_METEORSCHLAG = 75877
local SPELL_SCHMETTERN = 666683
local SPELL_WIRBELN = 67345
local SPELL_AATEM = 67345
local SPELL_KOPFSTOSS = 66770
local SPELL_HEILEN = 71131
local SPELL_KRAFT = 82396
-- ####### Haupt Codebox Start
-- Funktion "OnCombat"
function Kullerball_OnCombat(Unit, Event, pPlayer) -- Funktion bei Kampf beginn.
Unit:SendChatMessage(14, 0, "Endlich eine w\195\188rdige Herausforderung!")
for _, npcbuff in ipairs[npc_buffs.buffs] do
Unit:CastSpell(npcbuff)
pPlayer:CastSpell(69127)
end
Unit:RegisterEvent("Kullerball_Phase1", 5000, 0)
end
-- Funktion "Phase1"
-- Phase 1 Start
function Kullerball_Phase1(Unit, Event)
Unit:RemoveEvents()
Unit:RegisterEvent("Kullerball_Meteorschlag", 10000, 0)
Unit:RegisterEvent("Kullerball_Aatem", 15000, 0)
Unit:RegisterEvent("Kullerball_Kopfstoss", 5000, 0)
Unit:RegisterEvent("Kullerball_Flammenstoss", 7000, 0)
Unit:RegisterEvent("Kullerball_Schmettern", 12000, 0)
Unit:RegisterEvent("Kullerball_Wirbeln", 30000, 0)
Unit:RegisterEvent("Kullerball_Phase2", 50000, 0)
end
-- Funktion "Kullerball_Meteorschlag"
function Kullerball_Meteorschlag(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_METEORSCHLAG, spell2ziel)
Unit:SendChatMessage(12, "FEUER FREI!")
end
-- Funktion "Kullerball_Aatem"
function Kullerball_Aatem(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_AATEM, spell2ziel)
Unit:SendChatMessage(12, "Werdet zu Eis!")
end
-- Funktion "Kullerball_Kopfstoss"
function Kullerball_Kopfstoss(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_KOPFSTOSS, spell2ziel)
Unit:SendChatMessage(12, "Wie gefällt euch das?")
end
-- Funktion "Kullerball_Flammenstoss"
function Kullerball_Flammenstoss(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_FLAMMENSTOSS, spell2ziel)
Unit:SendChatMessage(12, "BRENNT!")
end
-- Funktion "Kullerball_Schmettern"
function Kullerball_Schmettern(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_SCHMETTERN, spell2ziel)
Unit:SendChatMessage(12, "HUAAH!")
end
-- Funktion "Kullerball_Wirbeln"
function Kullerball_Wirbeln(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_WIRBELN, spell2ziel)
Unit:SendChatMessage(12, "Weg von mir!")
end
-- Phase 1 Ende
-- Funktion "Phase2"
-- Phase 2 Start
function Kullerball_Phase2(Unit, Event)
if Unit:GetHealthPct () > 60 then
end
Unit:RemoveEvents()
Unit:SendChatMessage(12, "Argh, Ich muss mir Hilfe holen, Bruder komme und helfe mir! Halte diese Kreaturen von mir fern wärend ich mich Heile!")
Unit:SpawnCreature(60001, x , y, z, o, 16, 350000)
Unit:RegisterEvent("Kullerball_Heilen", 5000, 0)
end
-- Funktion "Kullerball_Heilen"
function Kullerball_Heilen(Unit, Event)
Unit:CastSpell(SPELL_HEILEN)
Unit:SendChatMessage(12, "Capernian gib mir Kraft!")
Unit:RegisterEvent("Kullerball_Phase3", 50000, 0)
end
-- Phase 2 Ende
-- Funktion "Phase3"
-- Phase 3 Start
function Kullerball_Phase3(Unit, Event)
if Unit:GetHealthPct () > 40 then
end
Unit:RemoveEvents()
Unit:SendChatMessage(12, "Argh, ich verliere! CAPERNIAN!? GIB MIR DEINE KRAFT!")
Unit:RegisterEvent("Kullerball_KRAFT", 20000, 0)
end
-- Funktion "Kullerball_Kraft"
function Kullerball_KRAFT(Unit, Event)
Unit:CastSpell(SPELL_HEILEN)
Unit:SendChatMessage(12, "Capernian gib mir Kraft!")
Unit:RegisterEvent("Kullerball_Phase4", 50000, 0)
end
-- Phase 3 Ende
-- Funktion "Phase4"
-- Phase 4 Start
function Kullerball_Phase3(Unit, Event)
if Unit:GetHealthPct () > 20 then
end
Unit:RemoveEvents()
Unit:SendChatMessage(12, "Es ist an der Zeit das ich Richtig austeile!")
end
Unit:RegisterEvent("Kullerball_Meteorschlag", 10000, 0)
Unit:RegisterEvent("Kullerball_Aatem", 15000, 0)
Unit:RegisterEvent("Kullerball_Kopfstoss", 5000, 0)
Unit:RegisterEvent("Kullerball_Flammenstoss", 7000, 0)
Unit:RegisterEvent("Kullerball_Schmettern", 12000, 0)
Unit:RegisterEvent("Kullerball_Wirbeln", 30000, 0)
Unit:RegisterEvent("Kullerball_Phase2", 50000, 0)
-- Funktion "Kullerball_Meteorschlag"
function Kullerball_Meteorschlag(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_METEORSCHLAG, spell2ziel)
Unit:SendChatMessage(12, "FEUER FREI!")
end
-- Funktion "Kullerball_Aatem"
function Kullerball_Aatem(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_AATEM, spell2ziel)
Unit:SendChatMessage(12, "Werdet zu Eis!")
end
-- Funktion "Kullerball_Kopfstoss"
function Kullerball_Kopfstoss(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_KOPFSTOSS, spell2ziel)
Unit:SendChatMessage(12, "Wie gefällt euch das?")
end
-- Funktion "Kullerball_Flammenstoss"
function Kullerball_Flammenstoss(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_FLAMMENSTOSS, spell2ziel)
Unit:SendChatMessage(12, "BRENNT!")
end
-- Funktion "Kullerball_Schmettern"
function Kullerball_Schmettern(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_SCHMETTERN, spell2ziel)
Unit:SendChatMessage(12, "HUAAH!")
end
-- Funktion "Kullerball_Wirbeln"
function Kullerball_Wirbeln(Unit, Event)
Unit:FullCastSpellOnTarget(SPELL_WIRBELN, spell2ziel)
Unit:SendChatMessage(12, "Weg von mir!")
end
-- Phase 4 Ende
-- Function "Kullerball_OnLeaveCombat"
function Kullerball_OnLeaveCombat(Unit, Event) -- Funktion beim Kampf verlassen.
Unit:SendChatMessage(14, 0, "Das war etwa alles? Ich hatte mir erhofft!")
end
-- Function "Kullerball_OnKilledTarget"
function Kullerball_OnKilledTarget(Unit, Event) -- Funktion beim Spieler Takedown.
Unit:SendChatMessage(14, 0, "Schwach!")
end
-- Function "Kullerball_OnDied"
function Kullerball_OnDied(Unit, Event) -- Funktion beim Sterben.
Unit:SendChatMessage(14, 0, "Capernian wird mich Rächen!")
end
-- ####### Haupt Codebox Ende
-- Register
RegisterUnitEvent(kullerball_id, 1, "Kullerball_OnCombat")
RegisterUnitEvent(kullerball_id, 2, "Kullerball_OnLeaveCombat")
RegisterUnitEvent(kullerball_id, 3, "Kullerball_OnKilledTarget")
RegisterUnitEvent(kullerball_id, 4, "Kullerball_OnDied")
|
[27] - Fix Kullerball
|
[27] - Fix Kullerball
|
Lua
|
agpl-3.0
|
Erotix8210/FrozenCore,Erotix8210/FrozenCore,Erotix8210/FrozenCore,Erotix8210/FrozenCore,Erotix8210/FrozenCore
|
c718ce102425796d55be82c74faa28c68135399b
|
orange/plugins/balancer/handler.lua
|
orange/plugins/balancer/handler.lua
|
local BasePlugin = require("orange.plugins.base_handler")
local orange_db = require("orange.store.orange_db")
local balancer_execute = require("orange.utils.balancer").execute
local utils = require("orange.utils.utils")
local ngx_balancer = require "ngx.balancer"
local string_find = string.find
local get_last_failure = ngx_balancer.get_last_failure
local set_current_peer = ngx_balancer.set_current_peer
local set_timeouts = ngx_balancer.set_timeouts
local set_more_tries = ngx_balancer.set_more_tries
local function now()
return ngx.now() * 1000
end
local BalancerHandler = BasePlugin:extend()
-- set balancer priority to 1000 so that balancer's access will be called at last
BalancerHandler.PRIORITY = 1000
function BalancerHandler:new(store)
BalancerHandler.super.new(self, "Balancer-plugin")
self.store = store
end
function BalancerHandler:access(conf)
BalancerHandler.super.access(self)
local enable = orange_db.get("balancer.enable")
local meta = orange_db.get_json("balancer.meta")
local selectors = orange_db.get_json("balancer.selectors")
if not enable or enable ~= true or not meta or not selectors then
return
end
local upstream_url = ngx.var.upstream_url
ngx.log(ngx.INFO, "[upstream_url] ", upstream_url)
-- set ngx.var.target
local target = upstream_url
local schema, hostname
local balancer_addr
if string_find(upstream_url, "://") then
schema, hostname = upstream_url:match("^(.+)://(.+)$")
else
schema = "http"
hostname = upstream_url
end
ngx.log(ngx.INFO, "[scheme] ", scheme, "; [hostname] ", hostname)
-- check whether the hostname stored in db
if utils.hostname_type(hostname) == "name" then
local upstreams = selectors
local name, port
if string_find(hostname, ":") then
name, port = hostname:match("^(.-)%:*(%d*)$")
else
name, port = hostname, 80
end
if upstreams and type(upstreams) == "table" then
for _, upstream in pairs(upstreams) do
if name == upstream.name then
-- set target to orange_upstream
target = "http://orange_upstream"
-- set balancer_addr
balancer_addr = {
type = "name",
host = name,
port = port,
try_count = 0,
tries = {},
retries = upstream.retries or 0, -- number of retries for the balancer
connection_timeout = upstream.connection_timeout or 60000,
send_timeout = upstream.send_timeout or 60000,
read_timeout = upstream_read_timeout or 60000,
-- ip = nil, -- final target IP address
-- balancer = nil, -- the balancer object, in case of balancer
-- hostname = nil, -- the hostname belonging to the final target IP
}
break
end
end -- end for loop
end
end
-- run balancer_execute once before the `balancer` context
if balancer_addr then
local ok, err = balancer_execute(balancer_addr)
if not ok then
return ngx.exit(503)
end
ngx.ctx.balancer_address = balancer_addr
end
-- target is used by proxy_pass
ngx.var.target = target
ngx.log(ngx.INFO, "[target] ", target, "; [upstream_url] ", upstream_url)
end
function BalancerHandler:balancer(conf)
BalancerHandler.super.balancer(self)
local addr = ngx.ctx.balancer_address
local tries = addr.tries
local current_try = {}
addr.try_count = addr.try_count + 1
tries[addr.try_count] = current_try
current_try.balancer_start = now()
if addr.try_count > 1 then
-- only call balancer on retry, first one is done in `access` which runs
-- in the ACCESS context and hence has less limitations than this BALANCER
-- context where the retries are executed
-- record faliure data
local previous_try = tries[addr.try_count - 1]
previous_try.state, previous_try.code = get_last_failure()
local ok, err = balancer_execute(addr)
if not ok then
ngx.log(ngx.ERR, "failed to retry the dns/balancer resolver for ",
addr.host, "' with: ", tostring(err))
return ngx.exit(500)
end
else
-- first try, so set the max number of retries
local retries = addr.retries
if retries > 0 then
set_more_tries(retries)
end
end
current_try.ip = addr.ip
current_try.port = addr.port
-- set the targets as resolved
local ok, err = set_current_peer(addr.ip, addr.port)
if not ok then
ngx.log(ngx.ERR, "failed to set the current peer (address: ",
tostring(addr.ip), " port: ", tostring(addr.port), "): ",
tostring(err))
return ngx.exit(500)
end
ok, err = set_timeouts(addr.connection_timeout / 1000,
addr.send_timeout / 1000,
addr.read_timeout /1000)
if not ok then
ngx.log(ngx.ERR, "could not set upstream timeouts: ", err)
end
-- record try-latency
local try_latency = now() - current_try.balancer_start
current_try.balancer_latency = try_latency
current_try.balancer_start = nil
-- record overall latency
ngx.ctx.ORANGE_BALANCER_TIME = (ngx.ctx.ORANGE_BALANCER_TIME or 0) + try_latency
end
return BalancerHandler
|
local BasePlugin = require("orange.plugins.base_handler")
local orange_db = require("orange.store.orange_db")
local balancer_execute = require("orange.utils.balancer").execute
local utils = require("orange.utils.utils")
local ngx_balancer = require "ngx.balancer"
local string_find = string.find
local get_last_failure = ngx_balancer.get_last_failure
local set_current_peer = ngx_balancer.set_current_peer
local set_timeouts = ngx_balancer.set_timeouts
local set_more_tries = ngx_balancer.set_more_tries
local function now()
return ngx.now() * 1000
end
local BalancerHandler = BasePlugin:extend()
-- set balancer priority to 999 so that balancer's access will be called at last
BalancerHandler.PRIORITY = 999
function BalancerHandler:new(store)
BalancerHandler.super.new(self, "Balancer-plugin")
self.store = store
end
function BalancerHandler:access(conf)
BalancerHandler.super.access(self)
local enable = orange_db.get("balancer.enable")
local meta = orange_db.get_json("balancer.meta")
local selectors = orange_db.get_json("balancer.selectors")
if not enable or enable ~= true or not meta or not selectors then
ngx.var.target = ngx.var.upstream_url
return
end
local upstream_url = ngx.var.upstream_url
ngx.log(ngx.INFO, "[upstream_url] ", upstream_url)
-- set ngx.var.target
local target = upstream_url
local schema, hostname
local balancer_addr
if string_find(upstream_url, "://") then
schema, hostname = upstream_url:match("^(.+)://(.+)$")
else
schema = "http"
hostname = upstream_url
end
ngx.log(ngx.INFO, "[scheme] ", scheme, "; [hostname] ", hostname)
-- check whether the hostname stored in db
if utils.hostname_type(hostname) == "name" then
local upstreams = selectors
local name, port
if string_find(hostname, ":") then
name, port = hostname:match("^(.-)%:*(%d*)$")
else
name, port = hostname, 80
end
if upstreams and type(upstreams) == "table" then
for _, upstream in pairs(upstreams) do
if name == upstream.name then
-- set target to orange_upstream
target = "http://orange_upstream"
-- set balancer_addr
balancer_addr = {
type = "name",
host = name,
port = port,
try_count = 0,
tries = {},
retries = upstream.retries or 0, -- number of retries for the balancer
connection_timeout = upstream.connection_timeout or 60000,
send_timeout = upstream.send_timeout or 60000,
read_timeout = upstream_read_timeout or 60000,
-- ip = nil, -- final target IP address
-- balancer = nil, -- the balancer object, in case of balancer
-- hostname = nil, -- the hostname belonging to the final target IP
}
break
end
end -- end for loop
end
end
-- run balancer_execute once before the `balancer` context
if balancer_addr then
local ok, err = balancer_execute(balancer_addr)
if not ok then
return ngx.exit(503)
end
ngx.ctx.balancer_address = balancer_addr
end
-- target is used by proxy_pass
ngx.var.target = target
ngx.log(ngx.INFO, "[target] ", target, "; [upstream_url] ", upstream_url)
end
function BalancerHandler:balancer(conf)
BalancerHandler.super.balancer(self)
local addr = ngx.ctx.balancer_address
local tries = addr.tries
local current_try = {}
addr.try_count = addr.try_count + 1
tries[addr.try_count] = current_try
current_try.balancer_start = now()
if addr.try_count > 1 then
-- only call balancer on retry, first one is done in `access` which runs
-- in the ACCESS context and hence has less limitations than this BALANCER
-- context where the retries are executed
-- record faliure data
local previous_try = tries[addr.try_count - 1]
previous_try.state, previous_try.code = get_last_failure()
local ok, err = balancer_execute(addr)
if not ok then
ngx.log(ngx.ERR, "failed to retry the dns/balancer resolver for ",
addr.host, "' with: ", tostring(err))
return ngx.exit(500)
end
else
-- first try, so set the max number of retries
local retries = addr.retries
if retries > 0 then
set_more_tries(retries)
end
end
current_try.ip = addr.ip
current_try.port = addr.port
-- set the targets as resolved
local ok, err = set_current_peer(addr.ip, addr.port)
if not ok then
ngx.log(ngx.ERR, "failed to set the current peer (address: ",
tostring(addr.ip), " port: ", tostring(addr.port), "): ",
tostring(err))
return ngx.exit(500)
end
ok, err = set_timeouts(addr.connection_timeout / 1000,
addr.send_timeout / 1000,
addr.read_timeout /1000)
if not ok then
ngx.log(ngx.ERR, "could not set upstream timeouts: ", err)
end
-- record try-latency
local try_latency = now() - current_try.balancer_start
current_try.balancer_latency = try_latency
current_try.balancer_start = nil
-- record overall latency
ngx.ctx.ORANGE_BALANCER_TIME = (ngx.ctx.ORANGE_BALANCER_TIME or 0) + try_latency
end
return BalancerHandler
|
fix bug - invalid URL prefix in ""
|
fix bug - invalid URL prefix in ""
最开始写的时候没有给balancer开关,所以target一上来就会设置为ngx.var.upstream_url
后来加上了开关,当开关未打开的时候,target的值没有赋值,导致出现 invalid URL prefix in "" 错误
该 Patch 解决了这个问题
Signed-off-by: Zhao Junwang <[email protected]>
|
Lua
|
mit
|
sumory/orange,sumory/orange,sumory/orange
|
d9a2bfaae070143452ad9eca095168ef50748b69
|
core/componentmanager.lua
|
core/componentmanager.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 prosody = prosody;
local log = require "util.logger".init("componentmanager");
local configmanager = require "core.configmanager";
local modulemanager = require "core.modulemanager";
local jid_split = require "util.jid".split;
local fire_event = require "core.eventmanager".fire_event;
local events_new = require "util.events".new;
local st = require "util.stanza";
local hosts = hosts;
local pairs, type, tostring = pairs, type, tostring;
local components = {};
local disco_items = require "util.multitable".new();
local NULL = {};
module "componentmanager"
local function default_component_handler(origin, stanza)
log("warn", "Stanza being handled by default component, bouncing error");
if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
origin.send(st.error_reply(stanza, "wait", "service-unavailable", "Component unavailable"));
end
end
function load_enabled_components(config)
local defined_hosts = config or configmanager.getconfig();
for host, host_config in pairs(defined_hosts) do
if host ~= "*" and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then
hosts[host] = create_component(host);
hosts[host].connected = false;
components[host] = default_component_handler;
local ok, err = modulemanager.load(host, host_config.core.component_module);
if not ok then
log("error", "Error loading %s component %s: %s", tostring(host_config.core.component_module), tostring(host), tostring(err));
else
fire_event("component-activated", host, host_config);
log("debug", "Activated %s component: %s", host_config.core.component_module, host);
end
end
end
end
prosody.events.add_handler("server-starting", load_enabled_components);
function handle_stanza(origin, stanza)
local node, host = jid_split(stanza.attr.to);
local component = nil;
if host then
if node then component = components[node.."@"..host]; end -- hack to allow hooking node@server
if not component then component = components[host]; end
end
if component then
log("debug", "%s stanza being handled by component: %s", stanza.name, host);
component(origin, stanza, hosts[host]);
else
log("error", "Component manager recieved a stanza for a non-existing component: "..tostring(stanza));
end
end
function create_component(host, component, events)
-- TODO check for host well-formedness
return { type = "component", host = host, connected = true, s2sout = {}, events = events or events_new() };
end
function register_component(host, component, session)
if not hosts[host] or (hosts[host].type == 'component' and not hosts[host].connected) then
local old_events = hosts[host] and hosts[host].events;
components[host] = component;
hosts[host] = session or create_component(host, component, old_events);
-- Add events object if not already one
if not hosts[host].events then
hosts[host].events = old_events or events_new();
end
-- add to disco_items
if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then
disco_items:set(host:sub(host:find(".", 1, true)+1), host, true);
end
-- FIXME only load for a.b.c if b.c has dialback, and/or check in config
modulemanager.load(host, "dialback");
log("debug", "component added: "..host);
return session or hosts[host];
else
log("error", "Attempt to set component for existing host: "..host);
end
end
function deregister_component(host)
if components[host] then
modulemanager.unload(host, "dialback");
hosts[host].connected = nil;
local host_config = configmanager.getconfig()[host];
if host_config and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then
-- Set default handler
components[host] = default_component_handler;
else
-- Component not in config, or disabled, remove
hosts[host] = nil;
components[host] = nil;
end
-- remove from disco_items
if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then
disco_items:remove(host:sub(host:find(".", 1, true)+1), host);
end
log("debug", "component removed: "..host);
return true;
else
log("error", "Attempt to remove component for non-existing host: "..host);
end
end
function set_component_handler(host, handler)
components[host] = handler;
end
function get_children(host)
return disco_items:get(host) or NULL;
end
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local prosody = prosody;
local log = require "util.logger".init("componentmanager");
local configmanager = require "core.configmanager";
local modulemanager = require "core.modulemanager";
local jid_split = require "util.jid".split;
local fire_event = require "core.eventmanager".fire_event;
local events_new = require "util.events".new;
local st = require "util.stanza";
local hosts = hosts;
local pairs, type, tostring = pairs, type, tostring;
local components = {};
local disco_items = require "util.multitable".new();
local NULL = {};
module "componentmanager"
local function default_component_handler(origin, stanza)
log("warn", "Stanza being handled by default component, bouncing error");
if stanza.attr.type ~= "error" and stanza.attr.type ~= "result" then
origin.send(st.error_reply(stanza, "wait", "service-unavailable", "Component unavailable"));
end
end
function load_enabled_components(config)
local defined_hosts = config or configmanager.getconfig();
for host, host_config in pairs(defined_hosts) do
if host ~= "*" and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then
hosts[host] = create_component(host);
hosts[host].connected = false;
components[host] = default_component_handler;
local ok, err = modulemanager.load(host, host_config.core.component_module);
if not ok then
log("error", "Error loading %s component %s: %s", tostring(host_config.core.component_module), tostring(host), tostring(err));
else
fire_event("component-activated", host, host_config);
log("debug", "Activated %s component: %s", host_config.core.component_module, host);
end
end
end
end
prosody.events.add_handler("server-starting", load_enabled_components);
function handle_stanza(origin, stanza)
local node, host = jid_split(stanza.attr.to);
local component = nil;
if host then
if node then component = components[node.."@"..host]; end -- hack to allow hooking node@server
if not component then component = components[host]; end
end
if component then
log("debug", "%s stanza being handled by component: %s", stanza.name, host);
component(origin, stanza, hosts[host]);
else
log("error", "Component manager recieved a stanza for a non-existing component: "..tostring(stanza));
end
end
function create_component(host, component, events)
-- TODO check for host well-formedness
local ssl_ctx;
if host then
-- We need to find SSL context to use...
-- Discussion in prosody@ concluded that
-- 1 level back is usually enough by default
local base_host = host:gsub("^[^%.]+", "");
if hosts[base_host] then
ssl_ctx = hosts[base_host].ssl_ctx;
end
end
return { type = "component", host = host, connected = true, s2sout = {},
ssl_ctx = ssl_ctx, events = events or events_new() };
end
function register_component(host, component, session)
if not hosts[host] or (hosts[host].type == 'component' and not hosts[host].connected) then
local old_events = hosts[host] and hosts[host].events;
components[host] = component;
hosts[host] = session or create_component(host, component, old_events);
-- Add events object if not already one
if not hosts[host].events then
hosts[host].events = old_events or events_new();
end
-- add to disco_items
if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then
disco_items:set(host:sub(host:find(".", 1, true)+1), host, true);
end
-- FIXME only load for a.b.c if b.c has dialback, and/or check in config
modulemanager.load(host, "dialback");
log("debug", "component added: "..host);
return session or hosts[host];
else
log("error", "Attempt to set component for existing host: "..host);
end
end
function deregister_component(host)
if components[host] then
modulemanager.unload(host, "dialback");
hosts[host].connected = nil;
local host_config = configmanager.getconfig()[host];
if host_config and ((host_config.core.enabled == nil or host_config.core.enabled) and type(host_config.core.component_module) == "string") then
-- Set default handler
components[host] = default_component_handler;
else
-- Component not in config, or disabled, remove
hosts[host] = nil;
components[host] = nil;
end
-- remove from disco_items
if not(host:find("@", 1, true) or host:find("/", 1, true)) and host:find(".", 1, true) then
disco_items:remove(host:sub(host:find(".", 1, true)+1), host);
end
log("debug", "component removed: "..host);
return true;
else
log("error", "Attempt to remove component for non-existing host: "..host);
end
end
function set_component_handler(host, handler)
components[host] = handler;
end
function get_children(host)
return disco_items:get(host) or NULL;
end
return _M;
|
componentmanager: Use ssl_ctx of 'parent' host (should fix TLS for components)
|
componentmanager: Use ssl_ctx of 'parent' host (should fix TLS for components)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
8206cfb0d6f046079fe112bb6cf8a50f5ea82c09
|
CircuitsUI_0.1.0/signal_gui.lua
|
CircuitsUI_0.1.0/signal_gui.lua
|
local function out(txt)
debug = false
if debug then
game.print(txt)
end
end
function CreateSignalGuiPanel(parent, signals)
local gui = parent.add({type = "flow", direction = "horizontal", name = "signals"})
out("Create gui")
if signals ~= nil then
UpdateSignalGuiPanel(gui, signals)
end
return gui
end
local function UpdateSingleSignal(gui, signal)
local typename = signal.signal.type
if typename == "virtual" then
typename = "virtual-signal"
end
out("Updating: " .. typename .. "/" .. signal.signal.name .. " value " .. signal.count)
gui.icon.sprite = typename .. "/" .. signal.signal.name
gui.valueLabel.caption = tostring(signal.count) -- use pretty-printing, with k and M prefixes.
-- local prototypes = itemSelection_prototypesForGroup(typename)
-- gui.icon.tooltip = prototypes[signal.signal.name].localised_name -- signal.count
end
function DestroyExcessGui(gui, count)
while gui["signal" .. count] do
out("Destroying " .. count)
gui["signal" .. count].destroy()
count = count + 1
end
end
function UpdateSignalGuiPanel(gui, circuit_network)
if not gui then
out("No gui")
return
end
local count = 1
if not circuit_network or not circuit_network.signals then
out("No signals")
DestroyExcessGui(gui, count)
return
end
for k, v in pairs(circuit_network.signals) do
out("Signal " .. v.signal.name .. " has " .. v.count)
if not gui["signal" .. count] then
out("Creating " .. count)
local signalGUI = gui.add({type = "flow", direction = "vertical", name = "signal" .. count})
signalGUI.add({type = "sprite-button", name = "icon", style = "slot_button_style", sprite=""})
signalGUI.add({type = "label", name = "valueLabel"})
end
local signalUI = gui["signal" .. count]
UpdateSingleSignal(signalUI, v)
count = count + 1
end
DestroyExcessGui(gui, count)
end
|
local function out(txt)
debug = false
if debug then
game.print(txt)
end
end
function CreateSignalGuiPanel(parent, signals)
local gui = parent.add({type = "flow", direction = "horizontal", name = "signals"})
out("Create gui")
if signals ~= nil then
UpdateSignalGuiPanel(gui, signals)
end
return gui
end
local suffixChars = { "", "k", "M", "G", "T", "P", "E" }
function CountString(count)
local absValue = math.abs(count)
local prefix = ""
if count < 0 then
prefix = "-"
end
local suffix = 1
while absValue >= 1000 do
absValue = absValue / 1000
suffix = suffix + 1
end
local str = tostring(absValue)
if absValue < 10 then
return prefix .. string.sub(str, 1, 3) .. suffixChars[suffix]
end
if absValue < 100 then
return prefix .. string.sub(str, 1, 2) .. suffixChars[suffix]
end
return prefix .. string.sub(str, 1, 3) .. suffixChars[suffix]
end
local function UpdateSingleSignal(gui, signal)
local typename = signal.signal.type
if typename == "virtual" then
typename = "virtual-signal"
end
out("Updating: " .. typename .. "/" .. signal.signal.name .. " value " .. signal.count)
gui.icon.sprite = typename .. "/" .. signal.signal.name
gui.valueLabel.caption = CountString(signal.count)
-- local prototypes = itemSelection_prototypesForGroup(typename)
-- gui.icon.tooltip = prototypes[signal.signal.name].localised_name -- signal.count
end
function DestroyExcessGui(gui, count)
while gui["signal" .. count] do
out("Destroying " .. count)
gui["signal" .. count].destroy()
count = count + 1
end
end
function UpdateSignalGuiPanel(gui, circuit_network)
if not gui then
out("No gui")
return
end
local count = 1
if not circuit_network or not circuit_network.signals then
out("No signals")
DestroyExcessGui(gui, count)
return
end
for k, v in pairs(circuit_network.signals) do
out("Signal " .. v.signal.name .. " has " .. v.count)
if not gui["signal" .. count] then
out("Creating " .. count)
local signalGUI = gui.add({type = "flow", direction = "vertical", name = "signal" .. count})
signalGUI.add({type = "sprite-button", name = "icon", style = "slot_button_style", sprite=""})
signalGUI.add({type = "label", name = "valueLabel"})
end
local signalUI = gui["signal" .. count]
UpdateSingleSignal(signalUI, v)
count = count + 1
end
DestroyExcessGui(gui, count)
end
|
CircuitsUI: Format string counts with suffixes
|
CircuitsUI: Format string counts with suffixes
|
Lua
|
mit
|
Zomis/FactorioMods
|
f072b7407ebb4444480c0c1dc702267d091e89ee
|
hammerspoon/windows.lua
|
hammerspoon/windows.lua
|
hs.window.animationDuration = 0
-- +-----------------+
-- | | |
-- | HERE | |
-- | | |
-- +-----------------+
function hs.window.left(win)
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end
-- +-----------------+
-- | | |
-- | | HERE |
-- | | |
-- +-----------------+
function hs.window.right(win)
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x + (max.w / 2)
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end
-- +-----------------+
-- | HERE |
-- +-----------------+
-- | |
-- +-----------------+
function hs.window.up(win)
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.w = max.w
f.y = max.y
f.h = max.h / 2
win:setFrame(f)
end
-- +-----------------+
-- | |
-- +-----------------+
-- | HERE |
-- +-----------------+
function hs.window.down(win)
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.w = max.w
f.y = max.y + (max.h / 2)
f.h = max.h / 2
win:setFrame(f)
end
-- +-----------------+
-- | HERE | |
-- +--------+ |
-- | |
-- +-----------------+
function hs.window.upLeft(win)
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/2
win:setFrame(f)
end
-- +-----------------+
-- | |
-- +--------+ |
-- | HERE | |
-- +-----------------+
function hs.window.downLeft(win)
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/2
f.h = max.h/2
win:setFrame(f)
end
-- +-----------------+
-- | |
-- | +--------|
-- | | HERE |
-- +-----------------+
function hs.window.downRight(win)
local f = win:frame()
local screen = win:screen()
local max = screen:fullFrame()
f.x = max.x + (max.w / 2)
f.y = max.y + (max.h / 2)
f.w = max.w/2
f.h = max.h/2
win:setFrame(f)
end
-- +-----------------+
-- | | HERE |
-- | +--------|
-- | |
-- +-----------------+
function hs.window.upRight(win)
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/2
win:setFrame(f)
end
-- +--------------+
-- | | | |
-- | | HERE | |
-- | | | |
-- +---------------+
function hs.window.centerWithFullHeight(win)
local f = win:frame()
local screen = win:screen()
local max = screen:fullFrame()
f.x = max.x + (max.w / 10)
f.w = max.w * 4/5
f.y = max.y + (max.h / 10)
f.h = max.h * 4/5
win:setFrame(f)
end
-- +-----------------+
-- | | |
-- | HERE | |
-- | | |
-- +-----------------+
function hs.window.left40(win)
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w * 0.4
f.h = max.h
win:setFrame(f)
end
-- +-----------------+
-- | | |
-- | | HERE |
-- | | |
-- +-----------------+
function hs.window.right60(win)
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.w * 0.4
f.y = max.y
f.w = max.w * 0.6
f.h = max.h
win:setFrame(f)
end
function hs.window.nextScreen(win)
local currentScreen = win:screen()
local allScreens = hs.screen.allScreens()
currentScreenIndex = hs.fnutils.indexOf(allScreens, currentScreen)
nextScreenIndex = currentScreenIndex + 1
if allScreens[nextScreenIndex] then
win:moveToScreen(allScreens[nextScreenIndex])
else
win:moveToScreen(allScreens[1])
end
end
windowLayoutMode = hs.hotkey.modal.new({}, 'F16')
windowLayoutMode.entered = function()
windowLayoutMode.statusMessage:show()
end
windowLayoutMode.exited = function()
windowLayoutMode.statusMessage:hide()
end
-- Bind the given key to call the given function and exit WindowLayout mode
function windowLayoutMode.bindWithAutomaticExit(mode, modifiers, key, fn)
mode:bind(modifiers, key, function()
mode:exit()
fn()
end)
end
local status, windowMappings = pcall(require, 'windows-bindings')
if not status then
windowMappings = require('windows-bindings-defaults')
end
local modifiers = windowMappings.modifiers
local showHelp = windowMappings.showHelp
local trigger = windowMappings.trigger
local mappings = windowMappings.mappings
function getModifiersStr(modifiers)
local modMap = { shift = '⇧', ctrl = '⌃', alt = '⌥', cmd = '⌘' }
local retVal = ''
for i, v in ipairs(modifiers) do
retVal = retVal .. modMap[v]
end
return retVal
end
local msgStr = getModifiersStr(modifiers)
msgStr = 'Window Layout Mode (' .. msgStr .. (string.len(msgStr) > 0 and '+' or '') .. trigger .. ')'
for i, mapping in ipairs(mappings) do
local modifiers, trigger, winFunction = table.unpack(mapping)
local hotKeyStr = getModifiersStr(modifiers)
if showHelp == true then
if string.len(hotKeyStr) > 0 then
msgStr = msgStr .. (string.format('\n%10s+%s => %s', hotKeyStr, trigger, winFunction))
else
msgStr = msgStr .. (string.format('\n%11s => %s', trigger, winFunction))
end
end
windowLayoutMode:bindWithAutomaticExit(modifiers, trigger, function()
--example: hs.window.focusedWindow():upRight()
local fw = hs.window.focusedWindow()
fw[winFunction](fw)
end)
end
local message = require('status-message')
windowLayoutMode.statusMessage = message.new(msgStr)
-- Use modifiers+trigger to toggle WindowLayout Mode
hs.hotkey.bind(modifiers, trigger, function()
windowLayoutMode:enter()
end)
windowLayoutMode:bind(modifiers, trigger, function()
windowLayoutMode:exit()
end)
|
hs.window.animationDuration = 0
local windowMT = hs.getObjectMetatable("hs.window")
-- +-----------------+
-- | | |
-- | HERE | |
-- | | |
-- +-----------------+
function windowMT.left(win)
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end
-- +-----------------+
-- | | |
-- | | HERE |
-- | | |
-- +-----------------+
function windowMT.right(win)
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x + (max.w / 2)
f.y = max.y
f.w = max.w / 2
f.h = max.h
win:setFrame(f)
end
-- +-----------------+
-- | HERE |
-- +-----------------+
-- | |
-- +-----------------+
function windowMT.up(win)
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.w = max.w
f.y = max.y
f.h = max.h / 2
win:setFrame(f)
end
-- +-----------------+
-- | |
-- +-----------------+
-- | HERE |
-- +-----------------+
function windowMT.down(win)
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.w = max.w
f.y = max.y + (max.h / 2)
f.h = max.h / 2
win:setFrame(f)
end
-- +-----------------+
-- | HERE | |
-- +--------+ |
-- | |
-- +-----------------+
function windowMT.upLeft(win)
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/2
win:setFrame(f)
end
-- +-----------------+
-- | |
-- +--------+ |
-- | HERE | |
-- +-----------------+
function windowMT.downLeft(win)
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/2
f.h = max.h/2
win:setFrame(f)
end
-- +-----------------+
-- | |
-- | +--------|
-- | | HERE |
-- +-----------------+
function windowMT.downRight(win)
local f = win:frame()
local screen = win:screen()
local max = screen:fullFrame()
f.x = max.x + (max.w / 2)
f.y = max.y + (max.h / 2)
f.w = max.w/2
f.h = max.h/2
win:setFrame(f)
end
-- +-----------------+
-- | | HERE |
-- | +--------|
-- | |
-- +-----------------+
function windowMT.upRight(win)
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/2
win:setFrame(f)
end
-- +--------------+
-- | | | |
-- | | HERE | |
-- | | | |
-- +---------------+
function windowMT.centerWithFullHeight(win)
local f = win:frame()
local screen = win:screen()
local max = screen:fullFrame()
f.x = max.x + (max.w / 10)
f.w = max.w * 4/5
f.y = max.y + (max.h / 10)
f.h = max.h * 4/5
win:setFrame(f)
end
-- +-----------------+
-- | | |
-- | HERE | |
-- | | |
-- +-----------------+
function windowMT.left40(win)
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.x
f.y = max.y
f.w = max.w * 0.4
f.h = max.h
win:setFrame(f)
end
-- +-----------------+
-- | | |
-- | | HERE |
-- | | |
-- +-----------------+
function windowMT.right60(win)
local f = win:frame()
local screen = win:screen()
local max = screen:frame()
f.x = max.w * 0.4
f.y = max.y
f.w = max.w * 0.6
f.h = max.h
win:setFrame(f)
end
function windowMT.nextScreen(win)
local currentScreen = win:screen()
local allScreens = hs.screen.allScreens()
currentScreenIndex = hs.fnutils.indexOf(allScreens, currentScreen)
nextScreenIndex = currentScreenIndex + 1
if allScreens[nextScreenIndex] then
win:moveToScreen(allScreens[nextScreenIndex])
else
win:moveToScreen(allScreens[1])
end
end
windowLayoutMode = hs.hotkey.modal.new({}, 'F16')
windowLayoutMode.entered = function()
windowLayoutMode.statusMessage:show()
end
windowLayoutMode.exited = function()
windowLayoutMode.statusMessage:hide()
end
-- Bind the given key to call the given function and exit WindowLayout mode
function windowLayoutMode.bindWithAutomaticExit(mode, modifiers, key, fn)
mode:bind(modifiers, key, function()
mode:exit()
fn()
end)
end
local status, windowMappings = pcall(require, 'windows-bindings')
if not status then
windowMappings = require('windows-bindings-defaults')
end
local modifiers = windowMappings.modifiers
local showHelp = windowMappings.showHelp
local trigger = windowMappings.trigger
local mappings = windowMappings.mappings
function getModifiersStr(modifiers)
local modMap = { shift = '⇧', ctrl = '⌃', alt = '⌥', cmd = '⌘' }
local retVal = ''
for i, v in ipairs(modifiers) do
retVal = retVal .. modMap[v]
end
return retVal
end
local msgStr = getModifiersStr(modifiers)
msgStr = 'Window Layout Mode (' .. msgStr .. (string.len(msgStr) > 0 and '+' or '') .. trigger .. ')'
for i, mapping in ipairs(mappings) do
local modifiers, trigger, winFunction = table.unpack(mapping)
local hotKeyStr = getModifiersStr(modifiers)
if showHelp == true then
if string.len(hotKeyStr) > 0 then
msgStr = msgStr .. (string.format('\n%10s+%s => %s', hotKeyStr, trigger, winFunction))
else
msgStr = msgStr .. (string.format('\n%11s => %s', trigger, winFunction))
end
end
windowLayoutMode:bindWithAutomaticExit(modifiers, trigger, function()
--example: hs.window.focusedWindow():upRight()
local fw = hs.window.focusedWindow()
fw[winFunction](fw)
end)
end
local message = require('status-message')
windowLayoutMode.statusMessage = message.new(msgStr)
-- Use modifiers+trigger to toggle WindowLayout Mode
hs.hotkey.bind(modifiers, trigger, function()
windowLayoutMode:enter()
end)
windowLayoutMode:bind(modifiers, trigger, function()
windowLayoutMode:exit()
end)
|
Fix hammerspoon window config
|
Fix hammerspoon window config
|
Lua
|
mit
|
makenosound/dotfiles,makenosound/dotfiles
|
221cb9d619169e959cbc1f9ca5e9d579914a6c0e
|
lunamark/writer/html.lua
|
lunamark/writer/html.lua
|
-- (c) 2009-2011 John MacFarlane. Released under MIT license.
-- See the file LICENSE in the source for details.
--- HTML writer for lunamark.
-- Extends [lunamark.writer.xml].
local M = {}
local xml = require("lunamark.writer.xml")
local util = require("lunamark.util")
local gsub = string.gsub
local intersperse, map = util.intersperse, util.map
--- Return a new HTML writer.
-- For a list of all fields in the writer, see [lunamark.writer.generic].
--
--`options` is a table that can contain the following fields:
--
-- `containers`
-- : Put sections in `<div>` tags.
--
-- `slides`
-- : Do not allow containers to nest; when a subsection begins,
-- close the section's container and start a new one.
--
-- `layout`
-- : `minimize` removes semantically insignificant white space.
-- : `compact` removes unneeded blank lines.
-- : `default` puts blank lines between block elements.
function M.new(options)
local options = options or {}
local Html = xml.new(options)
local options = options or {}
local endnotes = {}
local containersep = Html.containersep
local interblocksep = Html.interblocksep
Html.container = "div"
Html.linebreak = "<br/>"
function Html.code(s)
return {"<code>", Html.string(s), "</code>"}
end
function Html.link(lab,src,tit)
local titattr
if type(tit) == "string" and #tit > 0
then titattr = " title=\"" .. Html.string(tit) .. "\""
else titattr = ""
end
return {"<a href=\"", Html.string(src), "\"", titattr, ">", lab, "</a>"}
end
function Html.image(lab,src,tit)
local titattr, altattr
if type(tit) == "string" and #tit > 0
then titattr = " title=\"" .. Html.string(tit) .. "\""
else titattr = ""
end
return {"<img src=\"", Html.string(src), "\" alt=\"", lab, "\"", titattr, " />"}
end
function Html.paragraph(s)
return {"<p>", s, "</p>"}
end
local function listitem(s)
return {"<li>", s, "</li>"}
end
function Html.bulletlist(items,tight)
return {"<ul>", containersep, intersperse(map(items, listitem), containersep), containersep, "</ul>"}
end
function Html.orderedlist(items,tight,startnum)
local start = ""
if startnum and startnum ~= 1 then
start = " start=\"" .. startnum .. "\""
end
return {"<ol", start, ">", containersep, intersperse(map(items, listitem), containersep), containersep, "</ol>"}
end
function Html.inline_html(s)
return s
end
function Html.display_html(s)
return s
end
function Html.emphasis(s)
return {"<em>", s, "</em>"}
end
function Html.strong(s)
return {"<strong>", s, "</strong>"}
end
function Html.blockquote(s)
return {"<blockquote>", containersep, s, containersep, "</blockquote>"}
end
function Html.verbatim(s)
return {"<pre><code>", Html.string(s), "</code></pre>"}
end
function Html.header(s,level)
local sep = ""
local stop
if options.slides or options.containers then
local lev = (options.slides and 1) or level
local stop = Html.stop_section(lev)
if stop ~= "" then
stop = stop .. Html.interblocksep
end
sep = stop .. Html.start_section(lev) .. Html.containersep
end
return {sep, "<h", level, ">", s, "</h", level, ">"}
end
Html.hrule = "<hr />"
function Html.note(contents)
local num = #endnotes + 1
local backref = ' <a href="#fnref' .. num .. '" class="footnoteBackLink">↩</a>'
if contents[#contents] == "</p>" then
table.insert(contents, backref, #contents - 1)
else
contents[#contents + 1] = backref
end
endnotes[num] = {'<li id="fn', num, '">', contents, '</li>', interblocksep}
return {'<sup><a href="#fn', num, '" class="footnoteRef" id="fnref', num, '">', num, '</a></sup>'}
end
function Html.start_document()
endnotes = {}
return ""
end
function Html.stop_document()
return function()
local stop = Html.stop_section(1) -- close section containers
if stop ~= "" then stop = Html.containersep .. stop end
if #endnotes == 0 then
return stop
else
return {stop, interblocksep, '<hr />', interblocksep, '<ol class="notes">',
containersep, endnotes, containersep, '</ol>'}
end
end
end
function Html.definitionlist(items, tight)
local buffer = {}
local sep
if tight then sep = "" else sep = Html.containersep end
for _,item in ipairs(items) do
local defs = {}
for _,def in ipairs(item.definitions) do
defs[#defs + 1] = {"<dd>", sep, def, sep, "</dd>"}
end
buffer[#buffer + 1] = {"<dt>", item.term, "</dt>", containersep, intersperse(defs, containersep)}
end
return {"<dl>", containersep, intersperse(buffer, containersep), containersep, "</dl>"}
end
Html.template = [[
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>$title</title>
</head>
<body>
$body
</body>
</html>
]]
return Html
end
return M
|
-- (c) 2009-2011 John MacFarlane. Released under MIT license.
-- See the file LICENSE in the source for details.
--- HTML writer for lunamark.
-- Extends [lunamark.writer.xml].
local M = {}
local xml = require("lunamark.writer.xml")
local util = require("lunamark.util")
local gsub = string.gsub
local flatten, intersperse, map = util.flatten, util.intersperse, util.map
--- Return a new HTML writer.
-- For a list of all fields in the writer, see [lunamark.writer.generic].
--
--`options` is a table that can contain the following fields:
--
-- `containers`
-- : Put sections in `<div>` tags.
--
-- `slides`
-- : Do not allow containers to nest; when a subsection begins,
-- close the section's container and start a new one.
--
-- `layout`
-- : `minimize` removes semantically insignificant white space.
-- : `compact` removes unneeded blank lines.
-- : `default` puts blank lines between block elements.
function M.new(options)
local options = options or {}
local Html = xml.new(options)
local options = options or {}
local endnotes = {}
local containersep = Html.containersep
local interblocksep = Html.interblocksep
Html.container = "div"
Html.linebreak = "<br/>"
function Html.code(s)
return {"<code>", Html.string(s), "</code>"}
end
function Html.link(lab,src,tit)
local titattr
if type(tit) == "string" and #tit > 0
then titattr = " title=\"" .. Html.string(tit) .. "\""
else titattr = ""
end
return {"<a href=\"", Html.string(src), "\"", titattr, ">", lab, "</a>"}
end
function Html.image(lab,src,tit)
local titattr, altattr
if type(tit) == "string" and #tit > 0
then titattr = " title=\"" .. Html.string(tit) .. "\""
else titattr = ""
end
return {"<img src=\"", Html.string(src), "\" alt=\"", lab, "\"", titattr, " />"}
end
function Html.paragraph(s)
return {"<p>", s, "</p>"}
end
local function listitem(s)
return {"<li>", s, "</li>"}
end
function Html.bulletlist(items,tight)
return {"<ul>", containersep, intersperse(map(items, listitem), containersep), containersep, "</ul>"}
end
function Html.orderedlist(items,tight,startnum)
local start = ""
if startnum and startnum ~= 1 then
start = " start=\"" .. startnum .. "\""
end
return {"<ol", start, ">", containersep, intersperse(map(items, listitem), containersep), containersep, "</ol>"}
end
function Html.inline_html(s)
return s
end
function Html.display_html(s)
return s
end
function Html.emphasis(s)
return {"<em>", s, "</em>"}
end
function Html.strong(s)
return {"<strong>", s, "</strong>"}
end
function Html.blockquote(s)
return {"<blockquote>", containersep, s, containersep, "</blockquote>"}
end
function Html.verbatim(s)
return {"<pre><code>", Html.string(s), "</code></pre>"}
end
function Html.header(s,level)
local sep = ""
local stop
if options.slides or options.containers then
local lev = (options.slides and 1) or level
local stop = Html.stop_section(lev)
if stop ~= "" then
stop = stop .. Html.interblocksep
end
sep = stop .. Html.start_section(lev) .. Html.containersep
end
return {sep, "<h", level, ">", s, "</h", level, ">"}
end
Html.hrule = "<hr />"
function Html.note(contents)
local num = #endnotes + 1
local backref = ' <a href="#fnref' .. num .. '" class="footnoteBackLink">↩</a>'
contentsf = flatten(contents)
if contentsf[#contentsf] == "</p>" then
table.insert(contentsf, #contentsf, backref)
else
contentsf[#contentsf + 1] = backref
end
endnotes[num] = {'<li id="fn', num, '">', contentsf, '</li>'}
return {'<sup><a href="#fn', num, '" class="footnoteRef" id="fnref', num, '">', num, '</a></sup>'}
end
function Html.start_document()
endnotes = {}
return ""
end
function Html.stop_document()
return function()
local stop = Html.stop_section(1) -- close section containers
if stop ~= "" then stop = Html.containersep .. stop end
if #endnotes == 0 then
return stop
else
return {stop, interblocksep, '<hr />', interblocksep, '<ol class="notes">',
containersep, intersperse(endnotes, interblocksep), containersep, '</ol>'}
end
end
end
function Html.definitionlist(items, tight)
local buffer = {}
local sep
if tight then sep = "" else sep = Html.containersep end
for _,item in ipairs(items) do
local defs = {}
for _,def in ipairs(item.definitions) do
defs[#defs + 1] = {"<dd>", sep, def, sep, "</dd>"}
end
buffer[#buffer + 1] = {"<dt>", item.term, "</dt>", containersep, intersperse(defs, containersep)}
end
return {"<dl>", containersep, intersperse(buffer, containersep), containersep, "</dl>"}
end
Html.template = [[
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>$title</title>
</head>
<body>
$body
</body>
</html>
]]
return Html
end
return M
|
Fixed footnotes.
|
Fixed footnotes.
|
Lua
|
mit
|
simoncozens/lunamark,tst2005/lunamark,tst2005/lunamark,jgm/lunamark,jgm/lunamark,tst2005/lunamark,simoncozens/lunamark,simoncozens/lunamark,jgm/lunamark
|
a760a533643f65eb463f94321432c7ed561c6879
|
durden/atypes/terminal.lua
|
durden/atypes/terminal.lua
|
--
-- Terminal archetype, settings and menus specific for terminal-
-- frameserver session (e.g. keymapping, state control)
--
local res = {
dispatch = {
-- add a sub- protocol for communicating cell dimensions, this is
-- used to cut down on resize calls (as they are ** expensive in
-- terminal land) vs just using shader based cropping.
message = function(wnd, source, tbl)
-- print("parse terminal font size from tbl", tbl.message);
end
},
-- actions are exposed as target- menu
actions = {},
-- labels is mapping between known symbol and string to forward
labels = {},
default_shader = {"simple", "crop"},
atype = "terminal",
props = {
scalemode = "stretch",
autocrop = true,
font_block = true,
filtermode = FILTER_NONE
}
};
-- globally listen for changes to the default opacity and forward
gconfig_listen("term_opa", "aterm",
function(id, newv)
for wnd in all_windows("terminal") do
if (valid_vid(wnd.external, TYPE_FRAMESERVER)) then
target_graphmode(wnd.external, 1, newv * 255.0);
end
end
local col = gconfig_get("term_bgcol");
shader_update_uniform("crop", "simple", "color",
{col[1], col[2], col[3], newv}, nil, "term-alpha");
end);
-- globally apply changes to terminal font and terminal font sz
gconfig_listen("term_font", "aterm",
function(id, newv)
for wnd in all_windows("terminal") do
if (valid_vid(wnd.external, TYPE_FRAMESERVER)) then
wnd:update_font(-1, -1, newv);
end
end
end);
gconfig_listen("term_font_sz", "aterm",
function(id, newv)
for wnd in all_windows("terminal") do
if (valid_vid(wnd.external, TYPE_FRAMESERVER)) then
wnd:update_font(tonumber(newv), -1);
end
end
end);
res.labels["LEFT"] = "LEFT";
res.labels["UP"] = "UP";
res.labels["DOWN"] = "DOWN";
res.labels["RIGHT"] = "RIGHT"
res.labels["lshift_UP"] = "SCROLL_UP";
res.labels["lshift_DOWN"] = "SCROLL_DOWN";
res.labels["PAGE_UP"] = "PAGE_UP";
res.labels["PAGE_DOWN"] = "PAGE_DOWN";
res.labels["lctrl_t"] = "SIGINFO";
res.labels["lctrl_m"] = "MUTE";
res.labels["lshift_F7"] = "FONTSZ_INC";
res.labels["lshift_F8"] = "FONTSZ_DEC";
return res;
|
--
-- Terminal archetype, settings and menus specific for terminal-
-- frameserver session (e.g. keymapping, state control)
--
local res = {
dispatch = {
-- add a sub- protocol for communicating cell dimensions, this is
-- used to cut down on resize calls (as they are ** expensive in
-- terminal land) vs just using shader based cropping.
message = function(wnd, source, tbl)
-- print("parse terminal font size from tbl", tbl.message);
end
},
-- actions are exposed as target- menu
actions = {},
-- labels is mapping between known symbol and string to forward
labels = {},
default_shader = {"simple", "crop"},
atype = "terminal",
props = {
scalemode = "stretch",
autocrop = true,
font_block = true,
filtermode = FILTER_NONE
}
};
-- globally listen for changes to the default opacity and forward
gconfig_listen("term_opa", "aterm",
function(id, newv)
for wnd in all_windows("terminal") do
if (valid_vid(wnd.external, TYPE_FRAMESERVER)) then
target_graphmode(wnd.external, 1, newv * 255.0);
end
end
local col = gconfig_get("term_bgcol");
shader_update_uniform("crop", "simple", "color",
{col[1], col[2], col[3], newv}, nil, "term-alpha");
end);
-- globally apply changes to terminal font and terminal font sz
gconfig_listen("term_font", "aterm",
function(id, newv)
for wnd in all_windows("terminal") do
wnd.font_block = false;
wnd:update_font(-1, -1, newv);
wnd.font_block = true;
end
end);
gconfig_listen("term_font_sz", "aterm",
function(id, newv)
for wnd in all_windows("terminal") do
wnd.font_block = false;
wnd:update_font(tonumber(newv), -1);
wnd.font_block = true;
end
end);
res.labels["LEFT"] = "LEFT";
res.labels["UP"] = "UP";
res.labels["DOWN"] = "DOWN";
res.labels["RIGHT"] = "RIGHT"
res.labels["lshift_UP"] = "SCROLL_UP";
res.labels["lshift_DOWN"] = "SCROLL_DOWN";
res.labels["PAGE_UP"] = "PAGE_UP";
res.labels["PAGE_DOWN"] = "PAGE_DOWN";
res.labels["lctrl_t"] = "SIGINFO";
res.labels["lctrl_m"] = "MUTE";
res.labels["lshift_F7"] = "FONTSZ_INC";
res.labels["lshift_F8"] = "FONTSZ_DEC";
return res;
|
terminal font synch fix
|
terminal font synch fix
|
Lua
|
bsd-3-clause
|
letoram/durden
|
f13eb3b1b9d282609b9066c8fb7e841b7d96b18e
|
quest/saren_eisenfaust_81_galmair.lua
|
quest/saren_eisenfaust_81_galmair.lua
|
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (81, 'quest.saren_eisenfaust_81_galmair');
require("base.common")
require("base.factions")
module("quest.saren_eisenfaust_81_galmair", package.seeall)
GERMAN = Player.german
ENGLISH = Player.english
-- Insert the quest title here, in both languages
Title = {}
Title[GERMAN] = "Der faule Schmied"
Title[ENGLISH] = "The lazy smith"
-- Insert an extensive description of each status here, in both languages
-- Make sure that the player knows exactly where to go and what to do
Description = {}
Description[GERMAN] = {}
Description[ENGLISH] = {}
Description[GERMAN][1] = "Bring 10 Kohlestcke, 10 Eisenerze und 1 Hammer zu Saren Eisenfaust."
Description[ENGLISH][1] = "Bring 10 pieces of coal, 10 pieces iron ore and 1 hammer to Saren Eisenfaust."
Description[GERMAN][2] = "Vielleicht solltest du Saren Eisenfaust nochmal ansprechen, er hat sicher noch mehr fr dich zu tun."
Description[ENGLISH][2] = "Perhaps you should talk to Saren Eisenfaust again, he is sure to have more for you to do."
Description[GERMAN][3] = "Bring 15 Kupfererze, 1 Tiegelzange, 1 Feinschmiedehammer und 5 Eisenbarren zu Saren Eisenfaust."
Description[ENGLISH][3] = "Bring 15 pieces of copper ore, 1 crucible-pincer, 1 finesmithing hammer and 5 iron ingots to Saren Eisenfaust."
Description[GERMAN][4] = "Vielleicht solltest du Saren Eisenfaust nochmal ansprechen, er hat sicher noch mehr fr dich zu tun."
Description[ENGLISH][4] = "Perhaps you should talk to Saren Eisenfaust again, he is sure to have more for you to do."
Description[GERMAN][5] = "Bring 10 Eisenbarren, 10 Goldbarren, 5 zwergische Metalhandschuhe und 4 Schwertgriffe zu Saren Eisenfaust."
Description[ENGLISH][5] = "Bring 10 iron ingots, 10 gold ingots, 5 dwarven metal gloves and 4 sword handles to Saren Eisenfaust"
Description[GERMAN][6] = "Vielleicht solltest du Saren Eisenfaust nochmal ansprechen, er hat sicher noch mehr fr dich zu tun."
Description[ENGLISH][6] = "Perhaps you should talk to Saren Eisenfaust again, he is sure to have more for you to do."
Description[GERMAN][7] = "Bring 15 Kupferbarren, 10 Kriegshmmer, 10 vergoldete Kriegsxte und 2 salkamaerische Rstungen zu Saren Eisenfaust."
Description[ENGLISH][7] = "Bring 15 copper ingots, 10 war hammer, 10 gilded battleaxes and 2 salkamaerian armours to Saren Eisenfaust"
Description[GERMAN][8] = "Du hast alle Aufgaben von Saren Eisenfaust erfllt."
Description[ENGLISH][8] = "You have fulfilled all tasks of Saren Eisenfaust."
-- Insert the position of the quest start here (probably the position of an NPC or item)
Start = {333, 258, 0}
-- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there
QuestTarget = {}
QuestTarget[1] = {333, 258, 0}
QuestTarget[3] = {333, 258, 0}
QuestTarget[5] = {333, 258, 0}
QuestTarget[7] = {333, 258, 0}
-- Insert the quest status which is reached at the end of the quest
FINAL_QUEST_STATUS = 8
function QuestTitle(user)
return base.common.GetNLS(user, Title[GERMAN], Title[ENGLISH])
end
function QuestDescription(user, status)
local german = Description[GERMAN][status] or ""
local english = Description[ENGLISH][status] or ""
return base.common.GetNLS(user, german, english)
end
function QuestStart()
return Start
end
function QuestTargets(user, status)
return QuestTarget[status]
end
function QuestFinalStatus()
return FINAL_QUEST_STATUS
end
function QuestAvailability(user, status)
if base.factions.isGalmairCitizen(user) and user:getSkill(Character.smithing) < 80 and status == 0 then
return Player.questAvailable
else
return Player.questNotAvailable
end
end
|
-- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (81, 'quest.saren_eisenfaust_81_galmair');
require("base.common")
require("base.factions")
module("quest.saren_eisenfaust_81_galmair", package.seeall)
GERMAN = Player.german
ENGLISH = Player.english
-- Insert the quest title here, in both languages
Title = {}
Title[GERMAN] = "Der faule Schmied"
Title[ENGLISH] = "The lazy smith"
-- Insert an extensive description of each status here, in both languages
-- Make sure that the player knows exactly where to go and what to do
Description = {}
Description[GERMAN] = {}
Description[ENGLISH] = {}
Description[GERMAN][1] = "Bring 10 Kohlestcke, 10 Eisenerze und 1 Hammer zu Saren Eisenfaust."
Description[ENGLISH][1] = "Bring 10 pieces of coal, 10 pieces iron ore and 1 hammer to Saren Eisenfaust."
Description[GERMAN][2] = "Vielleicht solltest du Saren Eisenfaust nochmal ansprechen, er hat sicher noch mehr fr dich zu tun."
Description[ENGLISH][2] = "Perhaps you should talk to Saren Eisenfaust again, he is sure to have more for you to do."
Description[GERMAN][3] = "Bring 15 Kupfererze, 1 Tiegelzange, 1 Feinschmiedehammer und 5 Eisenbarren zu Saren Eisenfaust."
Description[ENGLISH][3] = "Bring 15 pieces of copper ore, 1 crucible-pincer, 1 finesmithing hammer and 5 iron ingots to Saren Eisenfaust."
Description[GERMAN][4] = "Vielleicht solltest du Saren Eisenfaust nochmal ansprechen, er hat sicher noch mehr fr dich zu tun."
Description[ENGLISH][4] = "Perhaps you should talk to Saren Eisenfaust again, he is sure to have more for you to do."
Description[GERMAN][5] = "Bring 10 Eisenbarren, 10 Goldbarren, 5 zwergische Metallhandschuhe und 4 Schwertgriffe zu Saren Eisenfaust."
Description[ENGLISH][5] = "Bring 10 iron ingots, 10 gold ingots, 5 dwarven metal gloves and 4 sword handles to Saren Eisenfaust"
Description[GERMAN][6] = "Vielleicht solltest du Saren Eisenfaust nochmal ansprechen, er hat sicher noch mehr fr dich zu tun."
Description[ENGLISH][6] = "Perhaps you should talk to Saren Eisenfaust again, he is sure to have more for you to do."
Description[GERMAN][7] = "Bring 15 Kupferbarren, 10 Kriegshmmer, 10 Hellebarden und 2 salkamaerische Rstungen zu Saren Eisenfaust."
Description[ENGLISH][7] = "Bring 15 copper ingots, 10 warhammers, 10 halberds and 2 salkamaerian armours to Saren Eisenfaust"
Description[GERMAN][8] = "Du hast alle Aufgaben von Saren Eisenfaust erfllt."
Description[ENGLISH][8] = "You have fulfilled all tasks of Saren Eisenfaust."
-- Insert the position of the quest start here (probably the position of an NPC or item)
Start = {333, 258, 0}
-- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there
QuestTarget = {}
QuestTarget[1] = {333, 258, 0}
QuestTarget[3] = {333, 258, 0}
QuestTarget[5] = {333, 258, 0}
QuestTarget[7] = {333, 258, 0}
-- Insert the quest status which is reached at the end of the quest
FINAL_QUEST_STATUS = 8
function QuestTitle(user)
return base.common.GetNLS(user, Title[GERMAN], Title[ENGLISH])
end
function QuestDescription(user, status)
local german = Description[GERMAN][status] or ""
local english = Description[ENGLISH][status] or ""
return base.common.GetNLS(user, german, english)
end
function QuestStart()
return Start
end
function QuestTargets(user, status)
return QuestTarget[status]
end
function QuestFinalStatus()
return FINAL_QUEST_STATUS
end
function QuestAvailability(user, status)
if base.factions.isGalmairCitizen(user) and user:getSkill(Character.smithing) < 80 and status == 0 then
return Player.questAvailable
else
return Player.questNotAvailable
end
end
|
fix questlog for recently adjusted items (followup to Mantis:0009401 / cleaning up my mess :S)
|
fix questlog for recently adjusted items
(followup to Mantis:0009401 / cleaning up my mess :S)
|
Lua
|
agpl-3.0
|
vilarion/Illarion-Content,KayMD/Illarion-Content,LaFamiglia/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content
|
5fc12f0a8abe4a7e485b0fbeecb2fec778101774
|
lua/plugins/orgmode.lua
|
lua/plugins/orgmode.lua
|
local parser_config = require "nvim-treesitter.parsers".get_parser_configs()
parser_config.org = {
install_info = {
url = 'https://github.com/milisims/tree-sitter-org',
revision = 'main',
files = {'src/parser.c', 'src/scanner.cc'},
},
filetype = 'org',
}
require'nvim-treesitter.configs'.setup {
-- If TS highlights are not enabled at all, or disabled via `disable` prop, highlighting will fallback to default Vim syntax highlighting
highlight = {
enable = true,
disable = {'org'}, -- Remove this to use TS highlighter for some of the highlights (Experimental)
additional_vim_regex_highlighting = {'org'}, -- Required since TS highlighter doesn't support all syntax features (conceal)
},
ensure_installed = {'org'}, -- Or run :TSUpdate org
}
require('orgmode').setup({
org_agenda_files = {'~/Dropbox/org/*', '~/my-orgs/**/*'},
org_default_notes_file = '~/Dropbox/org/refile.org',
})
|
-- Load custom tree-sitter grammar for org filetype
require('orgmode').setup_ts_grammar()
local parser_config = require"nvim-treesitter.parsers".get_parser_configs()
parser_config.org = {
install_info = {url = 'https://github.com/milisims/tree-sitter-org', revision = 'main', files = {'src/parser.c', 'src/scanner.cc'}},
filetype = 'org'
}
require'nvim-treesitter.configs'.setup {
-- If TS highlights are not enabled at all, or disabled via `disable` prop, highlighting will fallback to default Vim syntax highlighting
highlight = {
enable = true,
disable = {'org'}, -- Remove this to use TS highlighter for some of the highlights (Experimental)
additional_vim_regex_highlighting = {'org'} -- Required since TS highlighter doesn't support all syntax features (conceal)
},
ensure_installed = {'org'} -- Or run :TSUpdate org
}
require('orgmode').setup({org_agenda_files = {'~/Dropbox/org/*', '~/my-orgs/**/*'}, org_default_notes_file = '~/Dropbox/org/refile.org'})
|
fix orgmode
|
fix orgmode
|
Lua
|
mit
|
shwsun/yavc,shwsun/yavc
|
7fd8f4d2f1141146d059052649d235e60b59104e
|
frontend/apps/reader/modules/readerfrontlight.lua
|
frontend/apps/reader/modules/readerfrontlight.lua
|
local InputContainer = require("ui/widget/container/inputcontainer")
local InputDialog = require("ui/widget/inputdialog")
local Notification = require("ui/widget/notification")
local GestureRange = require("ui/gesturerange")
local UIManager = require("ui/uimanager")
local Geom = require("ui/geometry")
local Screen = require("device").screen
local Device = require("device")
local DEBUG = require("dbg")
local _ = require("gettext")
local ReaderFrontLight = InputContainer:new{
steps = {0,1,1,1,1,2,2,2,3,4,5,6,7,8,9,10},
gestureScale = Screen:getWidth() * FRONTLIGHT_SENSITIVITY_DECREASE,
}
function ReaderFrontLight:init()
if Device:isTouchDevice() then
self.ges_events = {
Adjust = {
GestureRange:new{
ges = "two_finger_pan",
rate = Device.model ~= 'Kobo_phoenix' and 3.0 or nil,
}
},
PanRelease= {
GestureRange:new{
ges = "two_finger_pan_release",
}
},
Swipe = {
GestureRange:new{
ges = "two_finger_swipe",
}
},
}
end
end
function ReaderFrontLight:onAdjust(arg, ges)
local powerd = Device:getPowerDevice()
if powerd.flIntensity ~= nil then
DEBUG("frontlight intensity", powerd.flIntensity)
local step = math.ceil(#self.steps * ges.distance / self.gestureScale)
DEBUG("step = ", step)
local delta_int = self.steps[step] or self.steps[#self.steps]
DEBUG("delta_int = ", delta_int)
if ges.direction == "north" then
powerd:setIntensity(powerd.flIntensity + delta_int)
elseif ges.direction == "south" then
powerd:setIntensity(powerd.flIntensity - delta_int)
end
end
return true
end
function ReaderFrontLight:onShowIntensity()
local powerd = Device:getPowerDevice()
if powerd.flIntensity ~= nil then
UIManager:show(Notification:new{
text = T( _("Frontlight intensity is set to %1."), powerd.flIntensity),
timeout = 1.0,
})
end
return true
end
function ReaderFrontLight:onSwipe(arg, ges)
if ges.direction == "north" or ges.direction == "south" then
DEBUG("onSwipe activated")
return self:onShowIntensity()
end
end
function ReaderFrontLight:onPanRelease(arg, ges)
DEBUG("onPanRelease activated")
return self:onShowIntensity()
end
function ReaderFrontLight:onShowFlDialog()
local powerd = Device:getPowerDevice()
self.fl_dialog = InputDialog:new{
title = _("Frontlight level"),
input_hint = ("(%d - %d)"):format(powerd.fl_min, powerd.fl_max),
buttons = {
{
{
text = _("Toggle"),
enabled = true,
callback = function()
self.fl_dialog.input:setText("")
powerd:toggleFrontlight()
end,
},
{
text = _("Apply"),
enabled = true,
callback = function()
self:fldialIntensity()
end,
},
{
text = _("OK"),
enabled = true,
callback = function()
self:fldialIntensity()
self:close()
end,
},
},
},
input_type = "number",
width = Screen:getWidth() * 0.8,
height = Screen:getHeight() * 0.2,
}
self.fl_dialog:onShowKeyboard()
UIManager:show(self.fl_dialog)
end
function ReaderFrontLight:close()
self.fl_dialog:onClose()
G_reader_settings:saveSetting("frontlight_intensity", Device:getPowerDevice().flIntensity)
UIManager:close(self.fl_dialog)
end
function ReaderFrontLight:fldialIntensity()
local number = tonumber(self.fl_dialog:getInputText())
if number ~= nil then
Device:getPowerDevice():setIntensity(number)
end
end
return ReaderFrontLight
|
local InputContainer = require("ui/widget/container/inputcontainer")
local InputDialog = require("ui/widget/inputdialog")
local Notification = require("ui/widget/notification")
local GestureRange = require("ui/gesturerange")
local UIManager = require("ui/uimanager")
local Geom = require("ui/geometry")
local Screen = require("device").screen
local Device = require("device")
local DEBUG = require("dbg")
local T = require("ffi/util").template
local _ = require("gettext")
local ReaderFrontLight = InputContainer:new{
steps = {0,1,1,1,1,2,2,2,3,4,5,6,7,8,9,10},
gestureScale = Screen:getWidth() * FRONTLIGHT_SENSITIVITY_DECREASE,
}
function ReaderFrontLight:init()
if Device:isTouchDevice() then
self.ges_events = {
Adjust = {
GestureRange:new{
ges = "two_finger_pan",
rate = Device.model ~= 'Kobo_phoenix' and 3.0 or nil,
}
},
PanRelease= {
GestureRange:new{
ges = "two_finger_pan_release",
}
},
Swipe = {
GestureRange:new{
ges = "two_finger_swipe",
}
},
}
end
end
function ReaderFrontLight:onAdjust(arg, ges)
local powerd = Device:getPowerDevice()
if powerd.flIntensity ~= nil then
DEBUG("frontlight intensity", powerd.flIntensity)
local step = math.ceil(#self.steps * ges.distance / self.gestureScale)
DEBUG("step = ", step)
local delta_int = self.steps[step] or self.steps[#self.steps]
DEBUG("delta_int = ", delta_int)
if ges.direction == "north" then
powerd:setIntensity(powerd.flIntensity + delta_int)
elseif ges.direction == "south" then
powerd:setIntensity(powerd.flIntensity - delta_int)
end
end
return true
end
function ReaderFrontLight:onShowIntensity()
local powerd = Device:getPowerDevice()
if powerd.flIntensity ~= nil then
UIManager:show(Notification:new{
text = T( _("Frontlight intensity is set to %1."), powerd.flIntensity),
timeout = 1.0,
})
end
return true
end
function ReaderFrontLight:onSwipe(arg, ges)
if ges.direction == "north" or ges.direction == "south" then
DEBUG("onSwipe activated")
return self:onShowIntensity()
end
end
function ReaderFrontLight:onPanRelease(arg, ges)
DEBUG("onPanRelease activated")
return self:onShowIntensity()
end
function ReaderFrontLight:onShowFlDialog()
local powerd = Device:getPowerDevice()
self.fl_dialog = InputDialog:new{
title = _("Frontlight level"),
input_hint = ("(%d - %d)"):format(powerd.fl_min, powerd.fl_max),
buttons = {
{
{
text = _("Toggle"),
enabled = true,
callback = function()
self.fl_dialog.input:setText("")
powerd:toggleFrontlight()
end,
},
{
text = _("Apply"),
enabled = true,
callback = function()
self:fldialIntensity()
end,
},
{
text = _("OK"),
enabled = true,
callback = function()
self:fldialIntensity()
self:close()
end,
},
},
},
input_type = "number",
width = Screen:getWidth() * 0.8,
height = Screen:getHeight() * 0.2,
}
self.fl_dialog:onShowKeyboard()
UIManager:show(self.fl_dialog)
end
function ReaderFrontLight:close()
self.fl_dialog:onClose()
G_reader_settings:saveSetting("frontlight_intensity", Device:getPowerDevice().flIntensity)
UIManager:close(self.fl_dialog)
end
function ReaderFrontLight:fldialIntensity()
local number = tonumber(self.fl_dialog:getInputText())
if number ~= nil then
Device:getPowerDevice():setIntensity(number)
end
end
return ReaderFrontLight
|
Add missing util.template definition to readerfrontlight.lua
|
Add missing util.template definition to readerfrontlight.lua
Fixes #1302.
|
Lua
|
agpl-3.0
|
NiLuJe/koreader,mihailim/koreader,robert00s/koreader,Markismus/koreader,poire-z/koreader,chihyang/koreader,ashhher3/koreader,poire-z/koreader,chrox/koreader,NickSavage/koreader,NiLuJe/koreader,lgeek/koreader,Hzj-jie/koreader,Frenzie/koreader,noname007/koreader,apletnev/koreader,koreader/koreader,houqp/koreader,mwoz123/koreader,Frenzie/koreader,ashang/koreader,pazos/koreader,frankyifei/koreader,koreader/koreader
|
f295ac8003953e7e7588d9e61975df81b290fbae
|
nyagos.d/catalog/git.lua
|
nyagos.d/catalog/git.lua
|
share.git = {}
-- setup branch detector
local branchdetect = function()
local gitbranches = {}
local gitbranch_tmp = nyagos.eval('git for-each-ref --format="%(refname:short)" refs/heads/ 2> nul')
for line in gitbranch_tmp:gmatch('[^\n]+') do
table.insert(gitbranches,line)
end
return gitbranches
end
-- subcommands
local gitsubcommands={}
-- keyword
gitsubcommands["bisect"]={"start", "bad", "good", "skip", "reset", "visualize", "replay", "log", "run"}
gitsubcommands["notes"]={"add", "append", "copy", "edit", "list", "prune", "remove", "show"}
gitsubcommands["reflog"]={"show", "delete", "expire"}
gitsubcommands["rerere"]={"clear", "forget", "diff", "remaining", "status", "gc"}
gitsubcommands["stash"]={"save", "list", "show", "apply", "clear", "drop", "pop", "create", "branch"}
gitsubcommands["submodule"]={"add", "status", "init", "deinit", "update", "summary", "foreach", "sync"}
gitsubcommands["svn"]={"init", "fetch", "clone", "rebase", "dcommit", "log", "find-rev", "set-tree", "commit-diff", "info", "create-ignore", "propget", "proplist", "show-ignore", "show-externals", "branch", "tag", "blame", "migrate", "mkdirs", "reset", "gc"}
gitsubcommands["worktree"]={"add", "list", "lock", "prune", "unlock"}
-- branch
gitsubcommands["checkout"]=branchdetect
gitsubcommands["reset"]=branchdetect
gitsubcommands["merge"]=branchdetect
gitsubcommands["rebase"]=branchdetect
share.git.subcommand=gitsubcommands
share.git.branch = branchdetect
if share.maincmds then
if share.maincmds["git"] then
-- git command complementation exists.
local maincmds = share.maincmds
-- build
for key, cmds in pairs(gitsubcommands) do
local gitcommand="git "..key
maincmds[gitcommand]=cmds
end
-- replace
share.maincmds = maincmds
end
end
|
share.git = {}
-- setup branch detector
local branchdetect = function()
local gitbranches = {}
local gitbranch_tmp = nyagos.eval('git for-each-ref --format="%(refname:short)" refs/heads/ 2> nul')
for line in gitbranch_tmp:gmatch('[^\n]+') do
table.insert(gitbranches,line)
end
return gitbranches
end
-- subcommands
local gitsubcommands={}
-- keyword
gitsubcommands["bisect"]={"start", "bad", "good", "skip", "reset", "visualize", "replay", "log", "run"}
gitsubcommands["notes"]={"add", "append", "copy", "edit", "list", "prune", "remove", "show"}
gitsubcommands["reflog"]={"show", "delete", "expire"}
gitsubcommands["rerere"]={"clear", "forget", "diff", "remaining", "status", "gc"}
gitsubcommands["stash"]={"save", "list", "show", "apply", "clear", "drop", "pop", "create", "branch"}
gitsubcommands["submodule"]={"add", "status", "init", "deinit", "update", "summary", "foreach", "sync"}
gitsubcommands["svn"]={"init", "fetch", "clone", "rebase", "dcommit", "log", "find-rev", "set-tree", "commit-diff", "info", "create-ignore", "propget", "proplist", "show-ignore", "show-externals", "branch", "tag", "blame", "migrate", "mkdirs", "reset", "gc"}
gitsubcommands["worktree"]={"add", "list", "lock", "prune", "unlock"}
-- branch
gitsubcommands["checkout"]=branchdetect
gitsubcommands["reset"]=branchdetect
gitsubcommands["merge"]=branchdetect
gitsubcommands["rebase"]=branchdetect
local gitvar=share.git
gitvar.subcommand=gitsubcommands
gitvar.branch=branchdetect
share.git=gitvar
if share.maincmds then
if share.maincmds["git"] then
-- git command complementation exists.
local maincmds = share.maincmds
-- build
for key, cmds in pairs(gitsubcommands) do
local gitcommand="git "..key
maincmds[gitcommand]=cmds
end
-- replace
share.maincmds = maincmds
end
end
|
Fix git branch func registration
|
Fix git branch func registration
|
Lua
|
bsd-3-clause
|
tsuyoshicho/nyagos,tyochiai/nyagos,zetamatta/nyagos,nocd5/nyagos
|
350ba3e35fb313c7db305e0592ecaf87d22ec1ee
|
totem/asserts.lua
|
totem/asserts.lua
|
--[[ Test for tensor equality
Parameters:
- `ta` (tensor)
- `tb` (tensor)
- `condition` (number) maximum pointwise difference between `a` and `b`
Returns two values:
success (boolean), failure_message (string or nil)
Tests whether the maximum pointwise difference between `a` and `b` is less than
or equal to `condition`.
]]
function totem.areTensorsEq(ta, tb, condition, neg)
-- If neg is true, we invert success and failure
-- This allows to easily implement Tester:assertTensorNe
local invert = false
if neg == nil then
invert = false
else
invert = true
end
if ta:dim() ~= tb:dim() then
return false, 'The tensors have different dimensions'
end
local sizea = torch.DoubleTensor(ta:size():totable())
local sizeb = torch.DoubleTensor(tb:size():totable())
local sizediff = sizea:clone():add(-1, sizeb)
local sizeerr = sizediff:abs():max()
if sizeerr ~= 0 then
return false, 'The tensors have different sizes'
end
local function ensureHasAbs(t)
-- Byte, Char and Short Tensors don't have abs
if not t.abs then
return t:double()
else
return t
end
end
ta = ensureHasAbs(ta)
tb = ensureHasAbs(tb)
local diff = ta:clone():add(-1, tb)
local err = diff:abs():max()
local violation = invert and 'TensorNE(==)' or ' TensorEQ(==)'
local errMessage = string.format('%s violation: val=%s, condition=%s',
violation,
tostring(err),
tostring(condition))
local success = err <= condition
if invert then
success = not success
end
return success, (not success) and errMessage or nil
end
--[[ Assert tensor equality
Parameters:
- `ta` (tensor)
- `tb` (tensor)
- `condition` (number) maximum pointwise difference between `a` and `b`
Asserts that the maximum pointwise difference between `a` and `b` is less than
or equal to `condition`.
]]
function totem.assertTensorEq(ta, tb, condition)
return assert(totem.areTensorsEq(ta, tb, condition))
end
--[[ Test for tensor inequality
Parameters:
- `ta` (tensor)
- `tb` (tensor)
- `condition` (number)
The tensors are considered unequal if the maximum pointwise difference >= condition.
]]
function totem.areTensorsNe(ta, tb, condition)
return totem.areTensorsEq(ta, tb, condition, true)
end
--[[ Assert tensor inequality
Parameters:
- `ta` (tensor)
- `tb` (tensor)
- `condition` (number)
The tensors are considered unequal if the maximum pointwise difference >= condition.
]]
function totem.assertTensorNe(ta, tb, condition)
assert(totem.areTensorsNe(ta, tb, condition))
end
local function isIncludedIn(ta, tb)
if type(ta) ~= 'table' or type(tb) ~= 'table' then
return ta == tb
end
for k, v in pairs(tb) do
if not totem.assertTableEq(ta[k], v) then return false end
end
return true
end
--[[ Assert that two tables are equal (comparing values, recursively)
Parameters:
- `actual` (table)
- `expected` (table)
]]
function totem.assertTableEq(ta, tb)
return isIncludedIn(ta, tb) and isIncludedIn(tb, ta)
end
--[[ Assert that two tables are *not* equal (comparing values, recursively)
Parameters:
- `actual` (table)
- `expected` (table)
]]
function totem.assertTableNe(ta, tb)
return not totem.assertTableEq(ta, tb)
end
|
--[[ Test for tensor equality
Parameters:
- `ta` (tensor)
- `tb` (tensor)
- `condition` (number) maximum pointwise difference between `a` and `b`
Returns two values:
success (boolean), failure_message (string or nil)
Tests whether the maximum pointwise difference between `a` and `b` is less than
or equal to `condition`.
]]
function totem.areTensorsEq(ta, tb, condition, _negate)
-- If _negate is true, we invert success and failure
if _negate == nil then
_negate = false
end
if ta:dim() ~= tb:dim() then
return false, 'The tensors have different dimensions'
end
local sizea = torch.DoubleTensor(ta:size():totable())
local sizeb = torch.DoubleTensor(tb:size():totable())
local sizediff = sizea:clone():add(-1, sizeb)
local sizeerr = sizediff:abs():max()
if sizeerr ~= 0 then
return false, 'The tensors have different sizes'
end
local function ensureHasAbs(t)
-- Byte, Char and Short Tensors don't have abs
if not t.abs then
return t:double()
else
return t
end
end
ta = ensureHasAbs(ta)
tb = ensureHasAbs(tb)
local diff = ta:clone():add(-1, tb)
local err = diff:abs():max()
local violation = _negate and 'TensorNE(==)' or ' TensorEQ(==)'
local errMessage = string.format('%s violation: val=%s, condition=%s',
violation,
tostring(err),
tostring(condition))
local success = err <= condition
if _negate then
success = not success
end
return success, (not success) and errMessage or nil
end
--[[ Assert tensor equality
Parameters:
- `ta` (tensor)
- `tb` (tensor)
- `condition` (number) maximum pointwise difference between `a` and `b`
Asserts that the maximum pointwise difference between `a` and `b` is less than
or equal to `condition`.
]]
function totem.assertTensorEq(ta, tb, condition)
return assert(totem.areTensorsEq(ta, tb, condition))
end
--[[ Test for tensor inequality
Parameters:
- `ta` (tensor)
- `tb` (tensor)
- `condition` (number)
Returns two values:
success (boolean), failure_message (string or nil)
The tensors are considered unequal if the maximum pointwise difference >= condition.
]]
function totem.areTensorsNe(ta, tb, condition)
return totem.areTensorsEq(ta, tb, condition, true)
end
--[[ Assert tensor inequality
Parameters:
- `ta` (tensor)
- `tb` (tensor)
- `condition` (number)
The tensors are considered unequal if the maximum pointwise difference >= condition.
]]
function totem.assertTensorNe(ta, tb, condition)
assert(totem.areTensorsNe(ta, tb, condition))
end
local function isIncludedIn(ta, tb)
if type(ta) ~= 'table' or type(tb) ~= 'table' then
return ta == tb
end
for k, v in pairs(tb) do
if not totem.assertTableEq(ta[k], v) then return false end
end
return true
end
--[[ Assert that two tables are equal (comparing values, recursively)
Parameters:
- `actual` (table)
- `expected` (table)
]]
function totem.assertTableEq(ta, tb)
return isIncludedIn(ta, tb) and isIncludedIn(tb, ta)
end
--[[ Assert that two tables are *not* equal (comparing values, recursively)
Parameters:
- `actual` (table)
- `expected` (table)
]]
function totem.assertTableNe(ta, tb)
return not totem.assertTableEq(ta, tb)
end
|
Fixing some comments, renaming some variables.
|
Fixing some comments, renaming some variables.
|
Lua
|
bsd-3-clause
|
GeorgOstrovski/torch-totem,fzvinicius/torch-totem,yozw/torch-totem,mevGDM/torch-totem,dm-jrae/torch-totem,clementfarabet/torch-totem,fbesse/torch-totem,deepmind/torch-totem
|
5ac13e6c854b8b68044b6204aa910b622048e3b5
|
libs/weblit-router.lua
|
libs/weblit-router.lua
|
--[[lit-meta
name = "creationix/weblit-router"
version = "3.0.0"
dependencies = {
'luvit/[email protected]'
}
description = "Weblit is a webapp framework designed around routes and middleware layers."
tags = {"weblit", "router", "framework"}
license = "MIT"
author = { name = "Tim Caswell" }
homepage = "https://github.com/creationix/weblit/blob/master/libs/weblit-app.lua"
]]
local parseQuery = require('querystring').parse
local quotepattern = '(['..("%^$().[]*+-?"):gsub("(.)", "%%%1")..'])'
local function escape(str)
return str:gsub(quotepattern, "%%%1")
end
local function compileGlob(glob)
local parts = {"^"}
for a, b in glob:gmatch("([^*]*)(%**)") do
if #a > 0 then
parts[#parts + 1] = escape(a)
end
if #b > 0 then
parts[#parts + 1] = "(.*)"
end
end
parts[#parts + 1] = "$"
local pattern = table.concat(parts)
return function (string)
return string and string:match(pattern)
end
end
local function compileRoute(route)
local parts = {"^"}
local names = {}
for a, b, c, d in route:gmatch("([^:]*):([_%a][_%w]*)(:?)([^:]*)") do
if #a > 0 then
parts[#parts + 1] = escape(a)
end
if #c > 0 then
parts[#parts + 1] = "(.*)"
else
parts[#parts + 1] = "([^/]*)"
end
names[#names + 1] = b
if #d > 0 then
parts[#parts + 1] = escape(d)
end
end
if #parts == 1 then
return function (string)
if string == route then return {} end
end
end
parts[#parts + 1] = "$"
local pattern = table.concat(parts)
return function (string)
local matches = {string:match(pattern)}
if #matches > 0 then
local results = {}
for i = 1, #matches do
results[i] = matches[i]
results[names[i]] = matches[i]
end
return results
end
end
end
local function newRouter()
local handlers = {}
local router = {}
function router.use(handler)
handlers[#handlers + 1] = handler
return router
end
function router.route(options, handler)
local method = options.method
local path = options.path and compileRoute(options.path)
local host = options.host and compileGlob(options.host)
local filter = options.filter
router.use(function (req, res, go)
if method and req.method ~= method then return go() end
if host and not host(req.headers.host) then return go() end
if filter and not filter(req) then return go() end
local params
if path then
local pathname, query = req.path:match("^([^?]*)%??(.*)")
params = path(pathname)
if not params then return go() end
if #query > 0 then
req.query = parseQuery(query)
end
end
req.params = params or {}
return handler(req, res, go)
end)
return router
end
function router.run(req, res, go)
local len = #handlers
local function run(i)
return handlers[i](req, res,
i < len
and function () return run(i + 1) end
or go or function () end
)
end
run(1)
end
return router
end
return {
newRouter = newRouter,
escape, escape,
compileGlob, compileGlob,
compileRoute, compileRoute,
}
|
--[[lit-meta
name = "creationix/weblit-router"
version = "3.0.1"
dependencies = {
'luvit/[email protected]'
}
description = "Weblit is a webapp framework designed around routes and middleware layers."
tags = {"weblit", "router", "framework"}
license = "MIT"
author = { name = "Tim Caswell" }
homepage = "https://github.com/creationix/weblit/blob/master/libs/weblit-app.lua"
]]
local parseQuery = require('querystring').parse
local quotepattern = '(['..("%^$().[]*+-?"):gsub("(.)", "%%%1")..'])'
local function escape(str)
return str:gsub(quotepattern, "%%%1")
end
local function compileGlob(glob)
local parts = {"^"}
for a, b in glob:gmatch("([^*]*)(%**)") do
if #a > 0 then
parts[#parts + 1] = escape(a)
end
if #b > 0 then
parts[#parts + 1] = "(.*)"
end
end
parts[#parts + 1] = "$"
local pattern = table.concat(parts)
return function (string)
return string and string:match(pattern)
end
end
local function compileRoute(route)
local parts = {"^"}
local names = {}
for a, b, c, d in route:gmatch("([^:]*):([_%a][_%w]*)(:?)([^:]*)") do
if #a > 0 then
parts[#parts + 1] = escape(a)
end
if #c > 0 then
parts[#parts + 1] = "(.*)"
else
parts[#parts + 1] = "([^/]*)"
end
names[#names + 1] = b
if #d > 0 then
parts[#parts + 1] = escape(d)
end
end
if #parts == 1 then
return function (string)
if string == route then return {} end
end
end
parts[#parts + 1] = "$"
local pattern = table.concat(parts)
return function (string)
local matches = {string:match(pattern)}
if #matches > 0 then
local results = {}
for i = 1, #matches do
results[i] = matches[i]
results[names[i]] = matches[i]
end
return results
end
end
end
local function newRouter()
local handlers = {}
local router = {}
function router.use(handler)
handlers[#handlers + 1] = handler
return router
end
function router.route(options, handler)
local method = options.method
local path = options.path and compileRoute(options.path)
local host = options.host and compileGlob(options.host)
local filter = options.filter
router.use(function (req, res, go)
if method and req.method ~= method then return go() end
if host and not host(req.headers.host) then return go() end
if filter and not filter(req) then return go() end
local params
if path then
local pathname, query = req.path:match("^([^?]*)%??(.*)")
params = path(pathname)
if not params then return go() end
if #query > 0 then
req.query = parseQuery(query)
end
end
req.params = params or {}
return handler(req, res, go)
end)
return router
end
function router.run(req, res, go)
local len = #handlers
local function run(i)
if i > len then
return (go or function () end)()
end
return handlers[i](req, res, function ()
return run(i + 1)
end)
end
run(1)
end
return router
end
return {
newRouter = newRouter,
escape, escape,
compileGlob, compileGlob,
compileRoute, compileRoute,
}
|
Fix case for empty handlers list
|
Fix case for empty handlers list
|
Lua
|
mit
|
zhaozg/weblit
|
b7eaa851f89e7f26eaec3df13ff546dab246a36d
|
otouto/plugins/unrestrict.lua
|
otouto/plugins/unrestrict.lua
|
local bindings = require('otouto.bindings')
local utilities = require('otouto.utilities')
local autils = require('otouto.administration')
local P = {}
function P:init()
P.triggers = utilities.triggers(self.info.username, self.config.cmd_pat)
:t('unrestrict', true):t('unmute', true):t('unban', true).table
P.command = 'unrestrict'
P.doc = 'Unrestrict a user.\nAliases: ' .. self.config.cmd_pat .. 'unmute, '
.. self.config.cmd_pat .. 'unban'
P.privilege = 2
P.internal = true
P.targeting = true
end
function P:action(msg, group)
local targets = autils.targets(self, msg)
local output = {}
if targets then
for _, id in ipairs(targets) do
if tonumber(id) then
bindings.restrictChatMember{
chat_id = msg.chat.id,
user_id = id,
can_send_other_messages = true,
can_add_web_page_previews = true
}
self.database.administration.automoderation[tostring(msg.chat.id)][tostring(id)] = nil
if group.bans[tostring(id)] then
group.bans[tostring(id)] = nil
table.insert(output, utilities.format_name(self, id) ..
' has been unbanned and unrestricted.')
else
table.insert(output, utilities.format_name(self, id) ..
' has been unrestricted.')
end
else
table.insert(output, id)
end
end
else
table.insert(output, self.config.errors.specify_targets)
end
utilities.send_reply(msg, table.concat(output, '\n'), 'html')
end
return P
|
local bindings = require('otouto.bindings')
local utilities = require('otouto.utilities')
local autils = require('otouto.administration')
local P = {}
function P:init()
P.triggers = utilities.triggers(self.info.username, self.config.cmd_pat)
:t('unrestrict', true):t('unmute', true):t('unban', true).table
P.command = 'unrestrict'
P.doc = 'Unrestrict a user.\nAliases: ' .. self.config.cmd_pat .. 'unmute, '
.. self.config.cmd_pat .. 'unban'
P.privilege = 2
P.internal = true
P.targeting = true
end
function P:action(msg, group)
local targets = autils.targets(self, msg)
local output = {}
if targets then
for _, id in ipairs(targets) do
if tonumber(id) then
bindings.restrictChatMember{
chat_id = msg.chat.id,
user_id = id,
can_send_other_messages = true,
can_add_web_page_previews = true
}
if self.database.administration.automoderation[tostring(msg.chat.id)] then
self.database.administration.automoderation[tostring(msg.chat.id)][tostring(id)] = nil
end
if group.bans[tostring(id)] then
group.bans[tostring(id)] = nil
table.insert(output, utilities.format_name(self, id) ..
' has been unbanned and unrestricted.')
else
table.insert(output, utilities.format_name(self, id) ..
' has been unrestricted.')
end
else
table.insert(output, id)
end
end
else
table.insert(output, self.config.errors.specify_targets)
end
utilities.send_reply(msg, table.concat(output, '\n'), 'html')
end
return P
|
/unban bugfix
|
/unban bugfix
|
Lua
|
agpl-3.0
|
topkecleon/otouto
|
ab6322679a787f5e902137fe23748f667716703f
|
src_trunk/resources/global/admin_globals.lua
|
src_trunk/resources/global/admin_globals.lua
|
function getAdmins()
local players = exports.pool:getPoolElementsByType("player")
local admins = { }
local count = 1
for key, value in ipairs(players) do
local adminLevel = getElementData(value, "adminlevel")
if (adminLevel>0) then
admins[count] = value
count = count + 1
end
end
return admins
end
function isPlayerAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) or not (adminLevel) then
return false
elseif(adminLevel>=1) then
return true
end
end
function isPlayerFullAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) or not (adminLevel) then
return false
elseif(adminLevel>=2) then
return true
end
end
function isPlayerSuperAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) or not (adminLevel) then
return false
elseif(adminLevel>=3) then
return true
end
end
function isPlayerHeadAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) or not (adminLevel) then
return false
elseif(adminLevel>=5) then
return true
end
end
function isPlayerLeadAdmin(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
if(adminLevel==0) or not (adminLevel) then
return false
elseif(adminLevel>=4) then
return true
end
end
function getPlayerAdminLevel(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel"))
return adminLevel
end
local titles = { "Trial Admin", "Admin", "Super Admin", "Lead Admin", "Head Admin", "Owner" }
function getPlayerAdminTitle(thePlayer)
local adminLevel = tonumber(getElementData(thePlayer, "adminlevel")) or 0
local text = titles[adminLevel] or "Player"
local hiddenAdmin = getElementData(thePlayer, "hiddenadmin") or 0
if (hiddenAdmin==1) then
text = text .. " (Hidden)"
end
return text
end
local scripterAccounts = {
Daniels = true,
Chamberlain = true,
mabako = true,
Cazomino09 = true,
Serizzim = true,
Flobu = true,
ryden = true,
['Mr.Hankey'] = true
}
function isPlayerScripter(thePlayer)
if getElementType(thePlayer) == "console" or isPlayerHeadAdmin(thePlayer) or scripterAccounts[getElementData(thePlayer, "gameaccountusername")] then
return true
else
return false
end
end
|
function getAdmins()
local players = exports.pool:getPoolElementsByType("player")
local admins = { }
local count = 1
for key, value in ipairs(players) do
if isPlayerAdmin(value) then
admins[count] = value
count = count + 1
end
end
return admins
end
function isPlayerAdmin(thePlayer)
return getPlayerAdminLevel(thePlayer) >= 1
end
function isPlayerFullAdmin(thePlayer)
return getPlayerAdminLevel(thePlayer) >= 2
end
function isPlayerSuperAdmin(thePlayer)
return getPlayerAdminLevel(thePlayer) >= 3
end
function isPlayerHeadAdmin(thePlayer)
return getPlayerAdminLevel(thePlayer) >= 5
end
function isPlayerLeadAdmin(thePlayer)
return getPlayerAdminLevel(thePlayer) >= 4
end
function getPlayerAdminLevel(thePlayer)
return tonumber(getElementData(thePlayer, "adminlevel")) or 0
end
local titles = { "Trial Admin", "Admin", "Super Admin", "Lead Admin", "Head Admin", "Owner" }
function getPlayerAdminTitle(thePlayer)
local text = titles[getPlayerAdminLevel(thePlayer)] or "Player"
local hiddenAdmin = getElementData(thePlayer, "hiddenadmin") or 0
if (hiddenAdmin==1) then
text = text .. " (Hidden)"
end
return text
end
local scripterAccounts = {
Daniels = true,
Chamberlain = true,
mabako = true,
Cazomino09 = true,
Serizzim = true,
Flobu = true,
ryden = true,
['Mr.Hankey'] = true
}
function isPlayerScripter(thePlayer)
return getElementType(thePlayer) == "console" or isPlayerHeadAdmin(thePlayer) or scripterAccounts[getElementData(thePlayer, "gameaccountusername")]
end
|
proper version of r1663: Error fix for isPlayerXAdmin
|
proper version of r1663: Error fix for isPlayerXAdmin
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1677 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
c99b9b5f908fab63d8872263cd0ad3790102f206
|
devel/find-vector.lua
|
devel/find-vector.lua
|
function inRange(addr)
for _, r in pairs(dfhack.internal.getMemRanges()) do
if addr >= r.start_addr and addr < r.end_addr then
return true
end
end
return false
end
ms = require 'memscan'
data = ms.get_data_segment()
length = math.floor(tonumber(({...})[1])) or qerror('bad length!')
rawstr = ({...})[2]
if rawstr then
rawtbl = {}
for i = 1, #rawstr, 2 do
local s = rawstr:sub(i, i + 1)
table.insert(rawtbl, tonumber('0x' .. s) or qerror('bad hex: ' .. s))
end
raw = df.new('uint8_t', #rawtbl)
for i, v in ipairs(rawtbl) do
raw[i - 1] = v
end
end
uptr = data.uintptr_t
for i = 0, uptr.count - 3 do
if uptr.data[i] + length == uptr.data[i + 1] and uptr.data[i + 1] <= uptr.data[i + 2] then
for j = 0, 2 do
if not inRange(uptr.data[i + j]) then
goto next_vector
end
end
local addr = uptr.start + (i * uptr.esize)
if rawtbl then
local _, ptr = dfhack.internal.memscan(uptr.data[i], #rawtbl, 1, raw, #rawtbl)
if ptr ~= uptr.data[i] then
goto next_vector
end
end
print(('0x%x: start 0x%x, length %d, allocated %d'):format(
addr, uptr.data[i], length, uptr.data[i + 2] - uptr.data[i]))
end
::next_vector::
end
if raw then
df.delete(raw)
end
|
function inRange(addr)
for _, r in pairs(dfhack.internal.getMemRanges()) do
if addr >= r.start_addr and addr < r.end_addr then
return true
end
end
return false
end
ms = require 'memscan'
data = ms.get_data_segment()
length = math.floor(tonumber(({...})[1])) or qerror('bad length!')
raw = nil
rawstr = ({...})[2]
if rawstr then
rawtbl = {}
for i = 1, #rawstr, 2 do
local s = rawstr:sub(i, i + 1)
table.insert(rawtbl, tonumber('0x' .. s) or qerror('bad hex: ' .. s))
end
raw = df.new('uint8_t', #rawtbl)
for i, v in ipairs(rawtbl) do
raw[i - 1] = v
end
end
uptr = data.uintptr_t
for i = 0, uptr.count - 3 do
if uptr.data[i] + length == uptr.data[i + 1] and uptr.data[i + 1] <= uptr.data[i + 2] then
for j = 0, 2 do
if not inRange(uptr.data[i + j]) then
goto next_vector
end
end
local addr = uptr.start + (i * uptr.esize)
if rawtbl then
local _, ptr = dfhack.internal.memscan(uptr.data[i], #rawtbl, 1, raw, #rawtbl)
if ptr ~= uptr.data[i] then
goto next_vector
end
end
print(('0x%x: start 0x%x, length %d, allocated %d'):format(
addr, uptr.data[i], length, uptr.data[i + 2] - uptr.data[i]))
dfhack.run_command('vectors', ('0x%x'):format(addr), '24')
dfhack.run_command('memview', ('0x%x'):format(uptr.data[i]), '128')
print("")
end
::next_vector::
end
if raw then
df.delete(raw)
end
|
find-vector: fix initialization issue, run memview+vectors
|
find-vector: fix initialization issue, run memview+vectors
|
Lua
|
unlicense
|
lethosor/dfhack-scripts
|
3eb435d4ed312a033b4db6363814addad9c42a0b
|
item/rock.lua
|
item/rock.lua
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
require("base.common")
require("base.lookat")
require("alchemy.base.teacher")
require("content.gatheringcraft.mining")
module("item.rock", package.seeall)
-- UPDATE common SET com_script='item.rock' WHERE com_itemid IN (1246,1245,232,914,1273,1276,1250);
function UseItem(User, SourceItem, ltstate)
-- alchemy stuff
if SourceItem.pos == position(75,651,0) then
alchemy.base.teacher.UseItem(User, SourceItem, ltstate)
return
end
-- alchemy end
local areaId = content.gatheringcraft.mining.GetAreaId(User.pos);
if (areaId == nil) then
base.common.HighInformNLS(User,
"Die Gegend sieht nicht so aus, als knnte man hier etwas finden.",
"The area doesn't look like a good place to mine.");
return;
end
if (content.gatheringcraft.mining.isMinableRock(areaId, SourceItem) == false) then
base.common.HighInformNLS(User,
"Du musst neben einem Felsen stehen um Bergbau zu betreiben.",
"You have to stand next to a rock to mine.");
return
end
content.gatheringcraft.mining.StartGathering(User, SourceItem, ltstate);
end
function LookAtItem(User,Item)
-- alchemy stuff
if Item.pos == position(75,651,0) then
alchemy.base.teacher.LookAtItem(User, Item)
return
end
-- alchemy end
-- tbd: custom loockat for minable rocks
local lookAt = base.lookat.GenerateLookAt(User, Item)
world:itemInform(User, Item, lookAt)
end
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
require("base.common")
require("base.lookat")
require("alchemy.base.teacher")
require("content.gatheringcraft.mining")
module("item.rock", package.seeall)
-- UPDATE common SET com_script='item.rock' WHERE com_itemid IN (1246,1245,232,914,1273,1276,1250);
function UseItem(User, SourceItem, ltstate)
-- alchemy stuff
if SourceItem.pos == position(75,651,0) or SourceItem.pos == position(873,878,0) then
alchemy.base.teacher.UseItem(User, SourceItem, ltstate)
return
end
-- alchemy end
local areaId = content.gatheringcraft.mining.GetAreaId(User.pos);
if (areaId == nil) then
base.common.HighInformNLS(User,
"Die Gegend sieht nicht so aus, als knnte man hier etwas finden.",
"The area doesn't look like a good place to mine.");
return;
end
if (content.gatheringcraft.mining.isMinableRock(areaId, SourceItem) == false) then
base.common.HighInformNLS(User,
"Du musst neben einem Felsen stehen um Bergbau zu betreiben.",
"You have to stand next to a rock to mine.");
return
end
content.gatheringcraft.mining.StartGathering(User, SourceItem, ltstate);
end
function LookAtItem(User,Item)
-- alchemy stuff
if Item.pos == position(75,651,0) or Item.pos == position(873,878,0) then
alchemy.base.teacher.LookAtItem(User, Item)
return
end
-- alchemy end
-- tbd: custom loockat for minable rocks
local lookAt = base.lookat.GenerateLookAt(User, Item)
world:itemInform(User, Item, lookAt)
end
|
fix the Recognizing Spring alchemy teacher
|
fix the Recognizing Spring alchemy teacher
(#0010009)
|
Lua
|
agpl-3.0
|
vilarion/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content,KayMD/Illarion-Content
|
78efd42efc58c6361248d95ba698e10d531e87ef
|
entities/ui/map.lua
|
entities/ui/map.lua
|
local Map = Class('Map')
function Map:initialize(parent, props)
self.parent = parent
self.bgColor = {127, 127, 127}
self.inactiveColor = {255, 255, 255}
self.activeColor = {127, 127, 127}
self.position = Vector(0, 0)
self.width = 240
self.height = 240
self.tileWidth = 8
self.tileHeight = 8
self.mapWidth = 0
self.mapHeight = 0
self.onClicked = function() end
--[[ note that the tileWidth and tileHeight should multiply evenly
into the width and height based on the grid size]]
for k, prop in pairs(props) do
self[k] = prop
end
if self.game.grid then
self.mapWidth = #self.game.grid * self.tileWidth
self.mapHeight = #self.game.grid[1] * self.tileHeight
--error(self.mapWidth..' '..self.mapHeight)
end
self.isPressed = false
self.hoveredRoom = -1
end
function Map:getPressed(x, y)
return (x >= self.position.x - self.width/2 ) and
(x <= self.position.x + self.width/2 ) and
(y >= self.position.y - self.height/2) and
(y <= self.position.y + self.height/2)
end
function Map:screenToTile(x, y)
if (x >= self.position.x - self.width/2 ) and
(x <= self.position.x + self.width/2 ) and
(y >= self.position.y - self.height/2) and
(y <= self.position.y + self.height/2) then
local tileX, tileY = math.ceil(x / self.tileWidth), math.ceil(y / self.tileHeight)
return tileX, tileY
else
return nil, nil
end
end
function Map:mousepressed(x, y, mbutton)
end
function Map:mousemoved(x, y, dx, dy, istouch)
self.hoveredRoom = -1
local hoverX, hoverY = self:screenToTile(x, y)
if hoverX and hoverY then
local roomType = self.game.rooms[hoverX][hoverY]
if roomType ~= 0 then
self.hoveredRoom = roomType
end
end
end
function Map:mousereleased(x, y, mbutton)
self.hoveredRoom = -1
local hoverX, hoverY = self:screenToTile(x, y)
if hoverX and hoverY then
local roomType = self.game.rooms[hoverX][hoverY]
if roomType ~= 0 then
self.hoveredRoom = roomType
self.game.currentRoom = roomType
end
end
end
function Map:draw()
local power = self.parent.power
love.graphics.setColor(self.inactiveColor)
local margin = self.margin
local x, y, w, h = self.position.x, self.position.y, self.width, self.height
x, y = x - w/2, y - h/2
love.graphics.setColor(self.bgColor)
love.graphics.rectangle('fill', x, y, w, h)
love.graphics.setColor(self.inactiveColor)
--x, y, w, h = x + margin, y + margin, w - margin*2, h - margin*2
love.graphics.rectangle('line', x, y, w, h)
-- draw map tiles
--love.graphics.push()
--love.graphics.translate(w/2, h/2)
--love.graphics.translate(-self.mapWidth/2, -self.mapHeight/2)
local activeMinX, activeMinY, activeMaxX, activeMaxY = math.huge, math.huge, -1, -1
for ix = 1, #self.game.grid do
for iy = 1, #self.game.grid[ix] do
local cellNumber = self.game.grid[ix][iy]
love.graphics.setColor(255, 255, 255)
local roomType = self.game.rooms[ix][iy]
if roomType == self.hoveredRoom then
love.graphics.setColor(102, 43, 170)
end
local screenX, screenY = x + (ix-1) * self.tileWidth, y + (iy-1) * self.tileHeight
if cellNumber == 1 then
love.graphics.rectangle('fill', screenX, screenY, self.tileWidth, self.tileHeight)
end
if roomType == self.game.currentRoom then
if ix < activeMinX then activeMinX = ix end
if iy < activeMinY then activeMinY = iy end
if ix > activeMaxX then activeMaxX = ix end
if iy > activeMaxY then activeMaxY = iy end
end
end
end
if self.game.currentRoom ~= -1 then
local minScreenX, minScreenY = x + (activeMinX-1) * self.tileWidth, y + (activeMinY-1) * self.tileHeight
local maxScreenX, maxScreenY = x + (activeMaxX) * self.tileWidth, y + (activeMaxY) * self.tileHeight
local width, height = maxScreenX - minScreenX, maxScreenY - minScreenY
local m = 2
love.graphics.rectangle('line', minScreenX-m, minScreenY-m, width+m*2, height+m*2)
end
end
return Map
|
local Map = Class('Map')
function Map:initialize(parent, props)
self.parent = parent
self.bgColor = {127, 127, 127}
self.inactiveColor = {255, 255, 255}
self.activeColor = {127, 127, 127}
self.position = Vector(0, 0)
self.width = 240
self.height = 240
self.tileWidth = 8
self.tileHeight = 8
self.mapWidth = 0
self.mapHeight = 0
self.onClicked = function() end
--[[ note that the tileWidth and tileHeight should multiply evenly
into the width and height based on the grid size]]
for k, prop in pairs(props) do
self[k] = prop
end
if self.game.grid then
self.mapWidth = #self.game.grid * self.tileWidth
self.mapHeight = #self.game.grid[1] * self.tileHeight
--error(self.mapWidth..' '..self.mapHeight)
end
self.isPressed = false
self.hoveredRoom = -1
end
function Map:getPressed(x, y)
return (x >= self.position.x - self.width/2 ) and
(x <= self.position.x + self.width/2 ) and
(y >= self.position.y - self.height/2) and
(y <= self.position.y + self.height/2)
end
function Map:screenToTile(x, y)
if (x >= self.position.x - self.width/2 ) and
(x <= self.position.x + self.width/2 ) and
(y >= self.position.y - self.height/2) and
(y <= self.position.y + self.height/2) then
local tileX, tileY = math.ceil(x / self.tileWidth), math.ceil(y / self.tileHeight)
if tileX <= 0 or tileY <= 0 or tileX >= #self.game.grid or tileY >= #self.game.grid[1] then
return nil, nil
end
return tileX, tileY
else
return nil, nil
end
end
function Map:mousepressed(x, y, mbutton)
end
function Map:mousemoved(x, y, dx, dy, istouch)
self.hoveredRoom = -1
local hoverX, hoverY = self:screenToTile(x, y)
if hoverX and hoverY then
local roomType = self.game.rooms[hoverX][hoverY]
if roomType ~= 0 then
self.hoveredRoom = roomType
end
end
end
function Map:mousereleased(x, y, mbutton)
self.hoveredRoom = -1
local hoverX, hoverY = self:screenToTile(x, y)
if hoverX and hoverY then
local roomType = self.game.rooms[hoverX][hoverY]
if roomType ~= 0 then
self.hoveredRoom = roomType
self.game.currentRoom = roomType
end
end
end
function Map:draw()
local power = self.parent.power
love.graphics.setColor(self.inactiveColor)
local margin = self.margin
local x, y, w, h = self.position.x, self.position.y, self.width, self.height
x, y = x - w/2, y - h/2
love.graphics.setColor(self.bgColor)
love.graphics.rectangle('fill', x, y, w, h)
love.graphics.setColor(self.inactiveColor)
--x, y, w, h = x + margin, y + margin, w - margin*2, h - margin*2
love.graphics.rectangle('line', x, y, w, h)
-- draw map tiles
--love.graphics.push()
--love.graphics.translate(w/2, h/2)
--love.graphics.translate(-self.mapWidth/2, -self.mapHeight/2)
local activeMinX, activeMinY, activeMaxX, activeMaxY = math.huge, math.huge, -1, -1
for ix = 1, #self.game.grid do
for iy = 1, #self.game.grid[ix] do
local cellNumber = self.game.grid[ix][iy]
love.graphics.setColor(255, 255, 255)
local roomType = self.game.rooms[ix][iy]
if roomType == self.hoveredRoom then
love.graphics.setColor(102, 43, 170)
end
local screenX, screenY = x + (ix-1) * self.tileWidth, y + (iy-1) * self.tileHeight
if cellNumber == 1 then
love.graphics.rectangle('fill', screenX, screenY, self.tileWidth, self.tileHeight)
end
if roomType == self.game.currentRoom then
if ix < activeMinX then activeMinX = ix end
if iy < activeMinY then activeMinY = iy end
if ix > activeMaxX then activeMaxX = ix end
if iy > activeMaxY then activeMaxY = iy end
end
end
end
if self.game.currentRoom ~= -1 then
local minScreenX, minScreenY = x + (activeMinX-1) * self.tileWidth, y + (activeMinY-1) * self.tileHeight
local maxScreenX, maxScreenY = x + (activeMaxX) * self.tileWidth, y + (activeMaxY) * self.tileHeight
local width, height = maxScreenX - minScreenX, maxScreenY - minScreenY
local m = 2
love.graphics.rectangle('line', minScreenX-m, minScreenY-m, width+m*2, height+m*2)
end
end
return Map
|
fixed map hover crash
|
fixed map hover crash
|
Lua
|
mit
|
Nuthen/ludum-dare-39
|
87cc25c2723db70d98ed46d4aa764e475f5335f2
|
mod_mam/rsm.lib.lua
|
mod_mam/rsm.lib.lua
|
local stanza = require"util.stanza".stanza;
local tostring, tonumber = tostring, tonumber;
local type = type;
local pairs = pairs;
local xmlns_rsm = 'http://jabber.org/protocol/rsm';
local element_parsers;
do
local function xs_int(st)
return tonumber((st:get_text()));
end
local function xs_string(st)
return st:get_text();
end
element_parsers = {
after = xs_string;
before = function(st)
return st:get_text() or true;
end;
max = xs_int;
index = xs_int;
first = function(st)
return { index = tonumber(st.attr.index); st:get_text() };
end;
last = xs_string;
count = xs_int;
}
end
local element_generators = setmetatable({
first = function(st, data)
if type(data) == "table" then
st:tag("first", { index = data.index }):text(data[1]):up();
else
st:tag("first"):text(tostring(data)):up();
end
end;
}, {
__index = function(_, name)
return function(st, data)
st:tag(name):text(tostring(data)):up();
end
end;
});
local function parse(stanza)
local rs = {};
for tag in stanza:childtags() do
local name = tag.name;
local parser = name and element_parsers[name];
if parser then
rs[name] = parser(tag);
end
end
return rs;
end
local function generate(t)
local st = stanza("set", { xmlns = xmlns_rsm });
for k,v in pairs(t) do
if element_parsers[k] then
element_generators[k](st, v);
end
end
return st;
end
local function get(st)
local set = st:get_child("set", xmlns_rsm);
if set and #set.tags > 0 then
return parse(set);
else
module:log("debug", "RSM parse failed, %s", tostring(st));
end
end
return { parse = parse, generate = generate, get = get };
|
local stanza = require"util.stanza".stanza;
local tostring, tonumber = tostring, tonumber;
local type = type;
local pairs = pairs;
local xmlns_rsm = 'http://jabber.org/protocol/rsm';
local element_parsers;
do
local function xs_int(st)
return tonumber((st:get_text()));
end
local function xs_string(st)
return st:get_text();
end
element_parsers = {
after = xs_string;
before = function(st)
return st:get_text() or true;
end;
max = xs_int;
index = xs_int;
first = function(st)
return { index = tonumber(st.attr.index); st:get_text() };
end;
last = xs_string;
count = xs_int;
}
end
local element_generators = setmetatable({
first = function(st, data)
if type(data) == "table" then
st:tag("first", { index = data.index }):text(data[1]):up();
else
st:tag("first"):text(tostring(data)):up();
end
end;
}, {
__index = function(_, name)
return function(st, data)
st:tag(name):text(tostring(data)):up();
end
end;
});
local function parse(stanza)
local rs = {};
for tag in stanza:childtags() do
local name = tag.name;
local parser = name and element_parsers[name];
if parser then
rs[name] = parser(tag);
end
end
return rs;
end
local function generate(t)
local st = stanza("set", { xmlns = xmlns_rsm });
for k,v in pairs(t) do
if element_parsers[k] then
element_generators[k](st, v);
end
end
return st;
end
local function get(st)
local set = st:get_child("set", xmlns_rsm);
if set and #set.tags > 0 then
return parse(set);
end
end
return { parse = parse, generate = generate, get = get };
|
mod_mam/rsm.lib: Remove log statement (fixes usage in verse)
|
mod_mam/rsm.lib: Remove log statement (fixes usage in verse)
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
bf1e9affebb577205016b79d98076ee461de8db1
|
durden/browser.lua
|
durden/browser.lua
|
-- Copyright: 2015, Björn Ståhl
-- License: 3-Clause BSD
-- Reference: http://durden.arcan-fe.com
-- Description: Brower covers a lbar- based resource picker for
-- existing resources.
local function match_ext(v, tbl)
if (tbl == nil) then
return true;
end
local ext = string.match(v, "^.+(%..+)$");
ext = ext ~= nil and string.sub(ext, 2) or ext;
if (ext == nil or string.len(ext) == 0) then
return false;
end
return tbl[ext];
end
local function browse_cb(ctx, instr, done, lastv)
if (done) then
if (instr == "..") then
local path = ctx.path;
if (#path > ctx.minlen) then
table.remove(path, #path);
end
browse_file(path, ctx.fltext, ctx.namespace, ctx.trigger, 0);
return;
end
string.gsub(instr, "..", "");
local pn = string.format("%s/%s", table.concat(ctx.path, "/"), instr);
local r, v = resource(pn, ctx.namespace);
if (v == "directory") then
table.insert(ctx.path, instr);
browse_file(ctx.path, ctx.fltext, ctx.namespace, ctx.trigger, 0);
else
local fn = match_ext(pn, ctx.fltext);
if (type(fn) == "function") then
fn(pn);
elseif (ctx.trigger) then
ctx.trigger(pn);
end
end
return;
end
-- glob and tag the resulting table with the type
local path = table.concat(ctx.path, "/");
if (ctx.paths[path] == nil) then
ctx.paths[path] = glob_resource(path .. "/*", ctx.namespace);
ctx.paths[path] = ctx.paths[path] and ctx.paths[path] or {};
for i=1,#ctx.paths[path] do
local elem = ctx.paths[path][i];
local ign;
ign, ctx.paths[path][elem] = resource(path .. "/" .. elem, ctx.namespace);
end
end
-- sweep through and color code accordingly, filter matches
local mlbl = gconfig_get("lbar_menulblstr");
local msellbl = gconfig_get("lbar_menulblselstr");
local res = (string.len(instr) > 0 or instr == "." or instr == "..")
and {".."} or {};
for i,v in ipairs(ctx.paths[path]) do
if (string.sub(v,1,string.len(instr)) == instr) then
if (ctx.paths[path][v] == "directory") then
table.insert(res, {mlbl, msellbl, v});
elseif (match_ext(v, ctx.fltext)) then
table.insert(res, v);
end
end
end
return {set = res, valid = false};
end
function browse_file(pathtbl, extensions, mask, donecb, tblmin)
active_display():lbar(browse_cb, {
base = prefix,
path = pathtbl,
paths = {},
minlen = tblmin ~= nil and tblmin or #pathtbl,
fltext = extensions,
namespace = mask,
trigger = donecb
}, {force_completion = true});
end
|
-- Copyright: 2015, Björn Ståhl
-- License: 3-Clause BSD
-- Reference: http://durden.arcan-fe.com
-- Description: Brower covers a lbar- based resource picker for
-- existing resources.
local function match_ext(v, tbl)
if (tbl == nil) then
return true;
end
local ext = string.match(v, "^.+(%..+)$");
ext = ext ~= nil and string.sub(ext, 2) or ext;
if (ext == nil or string.len(ext) == 0) then
return false;
end
return tbl[ext];
end
local function browse_cb(ctx, instr, done, lastv)
if (done) then
if (instr == "..") then
local path = ctx.path;
if (#path > ctx.minlen) then
table.remove(path, #path);
end
browse_file(path, ctx.fltext, ctx.namespace, ctx.trigger, 0);
return;
end
string.gsub(instr, "..", "");
local pn = string.format("%s/%s", table.concat(ctx.path, "/"), instr);
local r, v = resource(pn, ctx.namespace);
if (v == "directory") then
table.insert(ctx.path, instr);
browse_file(ctx.path, ctx.fltext, ctx.namespace, ctx.trigger, 0);
else
local fn = match_ext(pn, ctx.fltext);
if (type(fn) == "function") then
fn(pn);
elseif (ctx.trigger) then
ctx.trigger(pn);
end
end
return;
end
-- glob and tag the resulting table with the type
local path = table.concat(ctx.path, "/");
if (ctx.paths[path] == nil) then
ctx.paths[path] = glob_resource(path .. "/*", ctx.namespace);
ctx.paths[path] = ctx.paths[path] and ctx.paths[path] or {};
for i=1,#ctx.paths[path] do
local elem = ctx.paths[path][i];
local ign;
ign, ctx.paths[path][elem] = resource(path .. "/" .. elem, ctx.namespace);
end
end
-- sweep through and color code accordingly, filter matches
local mlbl = gconfig_get("lbar_menulblstr");
local msellbl = gconfig_get("lbar_menulblselstr");
local res = {};
for i,v in ipairs(ctx.paths[path]) do
if (string.sub(v,1,string.len(instr)) == instr) then
if (ctx.paths[path][v] == "directory") then
table.insert(res, {mlbl, msellbl, v});
elseif (match_ext(v, ctx.fltext)) then
table.insert(res, v);
end
end
end
table.insert(res, "..");
return {set = res, valid = false};
end
function browse_file(pathtbl, extensions, mask, donecb, tblmin)
active_display():lbar(browse_cb, {
base = prefix,
path = pathtbl,
paths = {},
minlen = tblmin ~= nil and tblmin or #pathtbl,
fltext = extensions,
namespace = mask,
trigger = donecb
}, {force_completion = true});
end
|
browser .. search order fix
|
browser .. search order fix
|
Lua
|
bsd-3-clause
|
letoram/durden
|
164d7fd4fbfb25c349528fdbce9f3fbdac146186
|
globes/tetra.lua
|
globes/tetra.lua
|
-- degrees
local d120 = tau/3
local d60 = d120 / 2
local d30 = d60 / 2
-- tetrahedron dimensions
local r = 1 -- face to vertex
local s = 2*r*sin(d60) -- side length
local h = sqrt(s*s-r*r) -- face to vertex opposite face
local theta = acos(r/s) -- face to vertex to vertex opposite face
local c = s/2/sin(theta) -- center to vertex
local d = s/2/tan(theta) -- center to edge
local e = r*cos(d60) -- face to edge
local f = h-c -- center to face
-- having to add 0.1 to compensate error roundoff
local fovr = 2*atan(s/2/f)+0.1
local fovd = fovr * 180 / pi
local y = e - e*e/(r+e)
local z =-f + h*e/(r+e)
plates = {
{ -- top
{0,-y/f,z/f},
{0,-(e-y)/e,(-f-z)/e},
fovd
},
{ -- left
{y/f*sin(d120),-y/f*cos(d120),z/f},
{(e-y)/e*sin(d120),-(e-y)/e*cos(d120),(-f-z)/e},
fovd
},
{ -- right
{y/f*sin(-d120),-y/f*cos(-d120),z/f},
{(e-y)/e*sin(-d120),-(e-y)/e*cos(-d120),(-f-z)/e},
fovd
},
{{0,0,-1},{0,-1,0},fovd} -- back
}
|
-- degrees
local d120 = tau/3
local d60 = d120 / 2
local d30 = d60 / 2
-- tetrahedron dimensions
local r = 1 -- face to vertex
local s = 2*r*sin(d60) -- side length
local h = sqrt(s*s-r*r) -- face to vertex opposite face
local theta = acos(r/s) -- face to vertex to vertex opposite face
local c = s/2/sin(theta) -- center to vertex
local d = s/2/tan(theta) -- center to edge
local e = r*cos(d60) -- face to edge
local f = h-c -- center to face
-- compute fov
local fovr = 2*atan(r/f)
local fovd = fovr * 180 / pi + 1 -- +1 to get rid of the hole in the center
print(fovd)
local y = e - e*e/(r+e)
local z =-f + h*e/(r+e)
plates = {
{ -- bottom
{0,-y/f,z/f},
{0,-(e-y)/e,(-f-z)/e},
fovd
},
{ -- right
{y/f*sin(d120),-y/f*cos(d120),z/f},
{(e-y)/e*sin(d120),-(e-y)/e*cos(d120),(-f-z)/e},
fovd
},
{ -- left
{y/f*sin(-d120),-y/f*cos(-d120),z/f},
{(e-y)/e*sin(-d120),-(e-y)/e*cos(-d120),(-f-z)/e},
fovd
},
{{0,0,-1},{0,-1,0},fovd} -- back
}
|
fixed tetra globe FOV math (face to vertex is longer than half side length)
|
fixed tetra globe FOV math (face to vertex is longer than half side length)
|
Lua
|
mit
|
shaunlebron/blinky,khonkhortisan/blinky,khonkhortisan/blinky,shaunlebron/blinky,shaunlebron/blinky,khonkhortisan/blinky
|
5a9bfc01f4c676b75e1b57b0446e499df2431fa8
|
src_trunk/resources/global/s_animation_globals.lua
|
src_trunk/resources/global/s_animation_globals.lua
|
function applyAnimation(thePlayer, block, name, animtime, loop, updatePosition, forced)
if animtime==nil then animtime=-1 end
if loop==nil then loop=true end
if updatePosition==nil then updatePosition=true end
if forced==nil then forced=true end
if isElement(thePlayer) and getElementType(thePlayer)=="player" and not getPedOccupiedVehicle(thePlayer) and getElementData(thePlayer, "freeze") ~= 1 then
if getElementData(thePlayer, "injuriedanimation") or ( not forced and getElementData(thePlayer, "forcedanimation") ) then
return false
end
removeAnimation(thePlayer)
toggleAllControls(thePlayer, false, true, false)
setElementData(thePlayer, "forcedanimation", forced)
setElementData(thePlayer, "animation", true)
local setanim = setPedAnimation(thePlayer, block, name, animtime, loop, updatePosition, false)
if animtime > 100 then
setTimer(setPedAnimation, 50, 2, thePlayer, block, name, animtime, loop, updatePosition, false)
end
if animtime > 50 then
setElementData(thePlayer, "animationt", setTimer(removeAnimation, animtime, 1, thePlayer), false)
end
return setanim
else
return false
end
end
function onSpawn()
setPedAnimation(source)
toggleAllControls(source, true, true, false)
setElementData(source, "forcedanimation", false)
setElementData(source, "animation", false)
end
addEventHandler("onPlayerSpawn", getRootElement(), onSpawn)
addEvent( "onPlayerStopAnimation", true )
function removeAnimation(thePlayer)
if isElement(thePlayer) and getElementType(thePlayer)=="player" and getElementData(thePlayer, "freeze") ~= 1 and not getElementData(thePlayer, "injuriedanimation") then
if isTimer( getElementData( thePlayer, "animationt" ) ) then
killTimer( getElementData( thePlayer, "animationt" ) )
end
local setanim = setPedAnimation(thePlayer)
removeElementData(thePlayer, "forcedanimation")
removeElementData(thePlayer, "animation")
removeElementData(thePlayer, "animationt")
toggleAllControls(thePlayer, true, true, false)
setPedAnimation(thePlayer)
setTimer(setPedAnimation, 50, 2, thePlayer)
setTimer(triggerEvent, 100, 1, "onPlayerStopAnimation", thePlayer)
return setanim
else
return false
end
end
|
function applyAnimation(thePlayer, block, name, animtime, loop, updatePosition, forced)
if animtime==nil then animtime=-1 end
if loop==nil then loop=true end
if updatePosition==nil then updatePosition=true end
if forced==nil then forced=true end
if isElement(thePlayer) and getElementType(thePlayer)=="player" and not getPedOccupiedVehicle(thePlayer) and getElementData(thePlayer, "freeze") ~= 1 then
if getElementData(thePlayer, "injuriedanimation") or ( not forced and getElementData(thePlayer, "forcedanimation") ) then
return false
end
toggleAllControls(thePlayer, false, true, false)
setElementData(thePlayer, "forcedanimation", forced)
setElementData(thePlayer, "animation", true)
local setanim = setPedAnimation(thePlayer, block, name, animtime, loop, updatePosition, false)
if animtime > 100 then
setTimer(setPedAnimation, 50, 2, thePlayer, block, name, animtime, loop, updatePosition, false)
end
if animtime > 50 then
setElementData(thePlayer, "animationt", setTimer(removeAnimation, animtime, 1, thePlayer), false)
end
return setanim
else
return false
end
end
function onSpawn()
setPedAnimation(source)
toggleAllControls(source, true, true, false)
setElementData(source, "forcedanimation", false)
setElementData(source, "animation", false)
end
addEventHandler("onPlayerSpawn", getRootElement(), onSpawn)
addEvent( "onPlayerStopAnimation", true )
function removeAnimation(thePlayer)
if isElement(thePlayer) and getElementType(thePlayer)=="player" and getElementData(thePlayer, "freeze") ~= 1 and not getElementData(thePlayer, "injuriedanimation") then
if isTimer( getElementData( thePlayer, "animationt" ) ) then
killTimer( getElementData( thePlayer, "animationt" ) )
end
local setanim = setPedAnimation(thePlayer)
removeElementData(thePlayer, "forcedanimation")
removeElementData(thePlayer, "animation")
removeElementData(thePlayer, "animationt")
toggleAllControls(thePlayer, true, true, false)
setPedAnimation(thePlayer)
setTimer(setPedAnimation, 50, 2, thePlayer)
setTimer(triggerEvent, 100, 1, "onPlayerStopAnimation", thePlayer)
return setanim
else
return false
end
end
|
anim fix
|
anim fix
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1879 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
ab39109f164ba954e174fdd8e02dfad369dcd170
|
src/lua/lluv/redis.lua
|
src/lua/lluv/redis.lua
|
------------------------------------------------------------------
--
-- Author: Alexey Melnichuk <[email protected]>
--
-- Copyright (C) 2015 Alexey Melnichuk <[email protected]>
--
-- Licensed according to the included 'LICENSE' document
--
-- This file is part of lua-lluv-redis library.
--
------------------------------------------------------------------
local uv = require "lluv"
local ut = require "lluv.utils"
local RedisStream = require "lluv.redis.stream"
local RedisCommander = require "lluv.redis.commander"
local function ocall(fn, ...) if fn then return fn(...) end end
local EOF = uv.error("LIBUV", uv.EOF)
local function nil_if_empty(t)
if t and #t == 0 then return nil end
return t
end
-- Redis url shold be `[<redis>://][<password>@]host[:<port>][/<db>]`
function decode_url(url)
local scheme, pass, host, port, db
scheme, url = ut.split_first(url, '://', true)
if not url then url = scheme
elseif scheme ~= 'redis' then
error('unsupported scheme: ' .. scheme)
end
pass, url = ut.split_first(url, '@', true)
if not url then url, pass = pass end
host, url = ut.split_first(url, ':', true)
if not url then host, db = ut.split_first(host, '/', true)
else port, db = ut.split_first(url, '/', true) end
return nil_if_empty(host), nil_if_empty(port), nil_if_empty(pass), nil_if_empty(db)
end
local function call_q(q, ...)
while true do
local cb = q:pop()
if not cb then break end
cb(...)
end
end
-------------------------------------------------------------------
local Connection = ut.class() do
function Connection:__init(opt)
if type(opt) == 'string' then
opt = {server = opt}
else opt = opt or {} end
if opt.server then
self._host, self._port, self._pass, self._db = decode_url(opt.server)
self._host = self._host or '127.0.0.1'
self._port = self._port or '6379'
else
self._host = opt.host or '127.0.0.1'
self._port = opt.port or '6379'
self._db = opt.db
self._pass = opt.pass
end
self._stream = RedisStream.new(self)
self._commander = RedisCommander.new(self._stream)
self._open_q = ut.Queue.new()
self._close_q = ut.Queue.new()
self._delay_q = ut.Queue.new()
self._ready = false
self._on_message = nil
self._on_error = nil
local function on_write_error(cli, err)
if err then self._stream:halt(err) end
end
self._on_write_handler = on_write_error
self._stream
:on_command(function(s, data, cb)
if self._ready then
return self._cnn:write(data, on_write_error)
end
if self._cnn then
self._delay_q:push(data)
return true
end
error('Can not execute command on closed client', 3)
end)
:on_halt(function(s, err)
self:close(err)
if err ~= EOF then
ocall(self._on_error, self, err)
end
end)
:on_message(function(...)
ocall(self._on_message, ...)
end)
return self
end
function Connection:clone()
return Connection.new{
host = self._host;
port = self._port;
pass = self._pass;
db = self._db;
}
end
local function on_ready(self, ...)
self._ready = true
while true do
local data = self._delay_q:pop()
if not data then break end
self._cnn:write(data, self._on_write_handler)
end
while self._ready do
local cb = self._open_q:pop()
if not cb then break end
cb(self, ...)
end
end
function Connection:open(cb)
if self._ready then
uv.defer(cb, self)
return self
end
if cb then self._open_q:push(cb) end
-- Only first call
if self._cnn then return self end
local cmd -- Init command
local ok, err = uv.tcp():connect(self._host, self._port, function(cli, err)
if err then return self:close(err) end
cli:start_read(function(cli, err, data)
if err then return self._stream:halt(err) end
self._stream:append(data):execute()
end)
if not cmd then return on_ready(self) end
-- send out init command
for _, data in ipairs(cmd) do
cli:write(data, self._on_write_handler)
end
end)
if not ok then return nil, err end
self._cnn = ok
if self._db or self._pass then
local called = false
-- call until first error
local wrap = function(last)
return function(_, err, ...)
if called then return end
if err then
called = true
return self:close(err)
end
if last then on_ready(self, err, ...) end
end
end
local last = not not self._db
if self._pass then self:auth (tostring(self._pass), wrap(last)) end
if self._db then self:select(tostring(self._db ), wrap(true)) end
cmd = {}
while true do
local data = self._delay_q:pop()
if not data then break end
cmd[#cmd + 1] = data
end
end
return self
end
function Connection:close(err, cb)
if type(err) == 'function' then
cb, err = err
end
if not self._cnn then
if cb then uv.defer(cb, self) end
return
end
if cb then self._close_q:push(cb) end
if not (self._cnn:closed() or self._cnn:closing()) then
local err = err
self._cnn:close(function()
self._cnn = nil
call_q(self._open_q, self, err or EOF)
self._stream:reset(err or EOF)
call_q(self._close_q, self, err)
self._delay_q:reset()
end)
end
self._ready = false
end
function Connection:closed()
if self._cnn then
return self._cnn:closed() or self._cnn:closing()
end
return true
end
function Connection:pipeline()
return self._commander:pipeline()
end
function Connection:on_error(handler)
self._on_error = handler
return self
end
function Connection:on_message(handler)
self._on_message = handler
return self
end
function Connection:__tostring()
return string.format("Lua UV Redis (%s)", tostring(self._cnn))
end
RedisCommander.commands(function(name)
name = name:lower()
Connection[name] = function(self, ...)
return self._commander[name](self._commander, ...)
end
end)
end
-------------------------------------------------------------------
local cnn = Connection.new({
server = 'redis://127.0.0.1/11'
})
return {
Connection = Connection;
}
|
------------------------------------------------------------------
--
-- Author: Alexey Melnichuk <[email protected]>
--
-- Copyright (C) 2015 Alexey Melnichuk <[email protected]>
--
-- Licensed according to the included 'LICENSE' document
--
-- This file is part of lua-lluv-redis library.
--
------------------------------------------------------------------
local uv = require "lluv"
local ut = require "lluv.utils"
local RedisStream = require "lluv.redis.stream"
local RedisCommander = require "lluv.redis.commander"
local function ocall(fn, ...) if fn then return fn(...) end end
local EOF = uv.error("LIBUV", uv.EOF)
local function nil_if_empty(t)
if t and #t == 0 then return nil end
return t
end
-- Redis url shold be `[<redis>://][<password>@]host[:<port>][/<db>]`
function decode_url(url)
local scheme, pass, host, port, db
scheme, url = ut.split_first(url, '://', true)
if not url then url = scheme
elseif scheme ~= 'redis' then
error('unsupported scheme: ' .. scheme)
end
pass, url = ut.split_first(url, '@', true)
if not url then url, pass = pass end
host, url = ut.split_first(url, ':', true)
if not url then host, db = ut.split_first(host, '/', true)
else port, db = ut.split_first(url, '/', true) end
return nil_if_empty(host), nil_if_empty(port), nil_if_empty(pass), nil_if_empty(db)
end
local function call_q(q, ...)
while true do
local cb = q:pop()
if not cb then break end
cb(...)
end
end
-------------------------------------------------------------------
local Connection = ut.class() do
function Connection:__init(opt)
if type(opt) == 'string' then
opt = {server = opt}
else opt = opt or {} end
if opt.server then
self._host, self._port, self._pass, self._db = decode_url(opt.server)
self._host = self._host or '127.0.0.1'
self._port = self._port or '6379'
self._pass = self._pass or opt.pass
self._db = self._db or opt.db
else
self._host = opt.host or '127.0.0.1'
self._port = opt.port or '6379'
self._db = opt.db
self._pass = opt.pass
end
self._stream = RedisStream.new(self)
self._commander = RedisCommander.new(self._stream)
self._open_q = ut.Queue.new()
self._close_q = ut.Queue.new()
self._delay_q = ut.Queue.new()
self._ready = false
self._on_message = nil
self._on_error = nil
local function on_write_error(cli, err)
if err then self._stream:halt(err) end
end
self._on_write_handler = on_write_error
self._stream
:on_command(function(s, data, cb)
if self._ready then
return self._cnn:write(data, on_write_error)
end
if self._cnn then
self._delay_q:push(data)
return true
end
error('Can not execute command on closed client', 3)
end)
:on_halt(function(s, err)
self:close(err)
if err ~= EOF then
ocall(self._on_error, self, err)
end
end)
:on_message(function(...)
ocall(self._on_message, ...)
end)
return self
end
function Connection:clone()
return Connection.new{
host = self._host;
port = self._port;
pass = self._pass;
db = self._db;
}
end
local function on_ready(self, ...)
self._ready = true
while true do
local data = self._delay_q:pop()
if not data then break end
self._cnn:write(data, self._on_write_handler)
end
while self._ready do
local cb = self._open_q:pop()
if not cb then break end
cb(self, ...)
end
end
function Connection:open(cb)
if self._ready then
uv.defer(cb, self)
return self
end
if cb then self._open_q:push(cb) end
-- Only first call
if self._cnn then return self end
local cmd -- Init command
local ok, err = uv.tcp():connect(self._host, self._port, function(cli, err)
if err then return self:close(err) end
cli:start_read(function(cli, err, data)
if err then return self._stream:halt(err) end
self._stream:append(data):execute()
end)
if not cmd then return on_ready(self) end
-- send out init command
for _, data in ipairs(cmd) do
cli:write(data, self._on_write_handler)
end
end)
if not ok then return nil, err end
self._cnn = ok
if self._db or self._pass then
local called = false
-- call until first error
local wrap = function(last)
return function(_, err, ...)
if called then return end
if err then
called = true
return self:close(err)
end
if last then on_ready(self, err, ...) end
end
end
local last = not not self._db
if self._pass then self:auth (tostring(self._pass), wrap(last)) end
if self._db then self:select(tostring(self._db ), wrap(true)) end
cmd = {}
while true do
local data = self._delay_q:pop()
if not data then break end
cmd[#cmd + 1] = data
end
end
return self
end
function Connection:close(err, cb)
if type(err) == 'function' then
cb, err = err
end
if not self._cnn then
if cb then uv.defer(cb, self) end
return
end
if cb then self._close_q:push(cb) end
if not (self._cnn:closed() or self._cnn:closing()) then
local err = err
self._cnn:close(function()
self._cnn = nil
call_q(self._open_q, self, err or EOF)
self._stream:reset(err or EOF)
call_q(self._close_q, self, err)
self._delay_q:reset()
end)
end
self._ready = false
end
function Connection:closed()
if self._cnn then
return self._cnn:closed() or self._cnn:closing()
end
return true
end
function Connection:pipeline()
return self._commander:pipeline()
end
function Connection:on_error(handler)
self._on_error = handler
return self
end
function Connection:on_message(handler)
self._on_message = handler
return self
end
function Connection:__tostring()
return string.format("Lua UV Redis (%s)", tostring(self._cnn))
end
RedisCommander.commands(function(name)
name = name:lower()
Connection[name] = function(self, ...)
return self._commander[name](self._commander, ...)
end
end)
end
-------------------------------------------------------------------
local cnn = Connection.new({
server = 'redis://127.0.0.1/11'
})
return {
Connection = Connection;
}
|
Fix. Pass password and db as options when use server option
|
Fix. Pass password and db as options when use server option
|
Lua
|
mit
|
moteus/lua-lluv-redis
|
929f385871db676bc7a7e309f52ed8619ca10665
|
lib/url.lua
|
lib/url.lua
|
local Url = {}
function Url.parse(url)
local href = url
local chunk, protocol = url:match("^(([a-z0-9+]+)://)")
url = url:sub((chunk and #chunk or 0) + 1)
local host = url:match("^([^/]+)")
if host then
local hostname = host:match("^([^:/]+)")
local port = host:match(":(%d+)$")
end
url = url:sub((host and #host or 0) + 1)
local pathname = url:match("^[^?]*")
local search = url:sub((pathname and #pathname or 0) + 1)
local query = search:sub(2)
return {
href = href,
protocol = protocol,
host = host,
hostname = hostname,
port = port,
pathname = pathname,
search = search,
query = query
}
end
--p(Url.parse("http://creationix.com:8080/foo/bar?this=sdr"))
--p(Url.parse("http://creationix.com/foo/bar?this=sdr"))
--p(Url.parse("http://creationix.com/foo/bar"))
--p(Url.parse("http://creationix.com/"))
--p(Url.parse("creationix.com/"))
--p(Url.parse("/"))
--p(Url.parse("/foobar"))
--p(Url.parse("/README.markdown"))
return Url
|
local Url = {}
function Url.parse(url)
local href = url
local chunk, protocol = url:match("^(([a-z0-9+]+)://)")
url = url:sub((chunk and #chunk or 0) + 1)
local host = url:match("^([^/]+)")
local hostname, port
if host then
hostname = host:match("^([^:/]+)")
port = host:match(":(%d+)$")
end
url = url:sub((host and #host or 0) + 1)
local pathname = url:match("^[^?]*")
local search = url:sub((pathname and #pathname or 0) + 1)
local query = search:sub(2)
return {
href = href,
protocol = protocol,
host = host,
hostname = hostname,
port = port,
pathname = pathname,
search = search,
query = query
}
end
--p(Url.parse("http://creationix.com:8080/foo/bar?this=sdr"))
--p(Url.parse("http://creationix.com/foo/bar?this=sdr"))
--p(Url.parse("http://creationix.com/foo/bar"))
--p(Url.parse("http://creationix.com/"))
--p(Url.parse("creationix.com/"))
--p(Url.parse("/"))
--p(Url.parse("/foobar"))
--p(Url.parse("/README.markdown"))
return Url
|
lua variable scope fixed
|
lua variable scope fixed
|
Lua
|
apache-2.0
|
zhaozg/luvit,boundary/luvit,boundary/luvit,boundary/luvit,GabrielNicolasAvellaneda/luvit-upstream,AndrewTsao/luvit,DBarney/luvit,rjeli/luvit,rjeli/luvit,boundary/luvit,luvit/luvit,DBarney/luvit,bsn069/luvit,AndrewTsao/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,bsn069/luvit,sousoux/luvit,AndrewTsao/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,rjeli/luvit,luvit/luvit,GabrielNicolasAvellaneda/luvit-upstream,boundary/luvit,sousoux/luvit,sousoux/luvit,connectFree/lev,sousoux/luvit,connectFree/lev,kaustavha/luvit,boundary/luvit,kaustavha/luvit,zhaozg/luvit,DBarney/luvit,rjeli/luvit,kaustavha/luvit,DBarney/luvit,bsn069/luvit
|
4405fef30fa044b2acf33fbc47f3516c657fd157
|
core/utilities.lua
|
core/utilities.lua
|
local utilities = {}
require("bit32-compat")
function utilities.required(t, name, context)
if not t[name] then utilities.error(context.." needs a "..name.." parameter") end
return t[name]
end
function utilities.error(message,bug)
if(SILE.currentCommand and type(SILE.currentCommand) == "table") then
print("\n! "..message.. " at "..SILE.currentlyProcessingFile.." l."..(SILE.currentCommand.line)..", col."..(SILE.currentCommand.col))
else
print("\n! "..message.. " at "..SILE.currentlyProcessingFile)
end
if bug then print(debug.traceback()) end
SILE.outputter:finish()
os.exit(1)
end
function utilities.warn(message)
print("\n! "..message)
--print(debug.traceback())
--os.exit(1)
end
function utilities.debugging(category)
return SILE.debugFlags.all or SILE.debugFlags[category]
end
function utilities.gtoke(string, pattern)
string = string and tostring(string) or ''
pattern = pattern and tostring(pattern) or "%s+"
local length = #string
return coroutine.wrap(function()
local index = 1
repeat
local first, last = string:find(pattern, index)
if last then
if index < first then coroutine.yield({ string = string:sub(index, first - 1) }) end
coroutine.yield({ separator = string:sub(first, last) })
index = last + 1
else
if index <= length then
coroutine.yield({ string = string:sub(index) })
end
break
end
until index > length
end)
end
function utilities.debug(category, messages)
if utilities.debugging(category) then
print("["..category.."]", messages)
end
end
function utilities.concat(array, c)
return table.concat(utilities.map(tostring, array), c)
end
function utilities.inherit(orig, spec)
local new = std.tree.clone(orig)
if spec then
for k,v in pairs(spec) do new[k] = v end
end
if new.init then new:init() end
return new
end
function utilities.map(func, array)
local new_array = {}
local last = #array
for i = 1, last do
new_array[i] = func(array[i])
end
return new_array
end
function utilities.splice(array, start, stop, replacement)
local ptr = start
local room = stop - start + 1
local last = replacement and #replacement or 0
for i = 1, last do
if room > 0 then
room = room - 1
array[ptr] = replacement[i]
else
table.insert(array, ptr, replacement[i])
end
ptr = ptr + 1
end
for i = 1, room do
table.remove(array, ptr)
end
return array
end
function utilities.sum(array)
local t = 0
local last = #array
for i = 1, last do
t = t + array[i]
end
return t
end
function utilities.allCombinations(options)
local count = 1
for i=1,#options do count = count * options[i] end
return coroutine.wrap(function()
for i=0,count-1 do
local this = i
local rv = {}
for j = 1,#options do
local base = options[j]
rv[#rv+1] = this % base + 1
this = (this - this % base )/ base
end
coroutine.yield(rv)
end
end)
end
-- Unicode-related utilities
pcall(function() utf8 = require("utf8") end)
utilities.codepoint = utf8.codepoint or function (uchar)
local seq = 0
local val = -1
for i = 1, #uchar do
local c = string.byte(uchar, i)
if seq == 0 then
if val > -1 then return val end
seq = c < 0x80 and 1 or c < 0xE0 and 2 or c < 0xF0 and 3 or
c < 0xF8 and 4 or --c < 0xFC and 5 or c < 0xFE and 6 or
error("invalid UTF-8 character sequence")
val = bit32.band(c, 2^(8-seq) - 1)
else
val = bit32.bor(bit32.lshift(val, 6), bit32.band(c, 0x3F))
end
seq = seq - 1
end
return val
end
utilities.utf8codes = utf8.codes or function (ustr)
local pos = 1
return function()
if pos > #ustr then
return nil
else
local c, ucv = 0, 0
local nbytes = 0
c = string.byte(ustr, pos)
pos = pos + 1
if c < 0x80 then
ucv = c
nbytes = 0
elseif c >= 0xc0 and c < 0xe0 then -- 110x xxxx
ucv = c - 0xc0
nbytes = 1
elseif c >= 0xe0 and c < 0xf0 then -- 1110 xxxx
ucv = c - 0xe0
nbytes = 2
elseif c >= 0xf0 and c < 0xf8 then -- 1111 0xxx
ucv = c - 0xf0
nbytes = 3
elseif c >= 0xf8 and c < 0xfc then -- 1111 10xx
ucv = c - 0xf8
nbytes = 4
elseif c >= 0xfc and c < 0xfe then -- 1111 110x
ucv = c - 0xfc
nbytes = 5
else -- Invalid
return nil
end
if pos + nbytes > #ustr + 1 then -- Invalid
return nil
end
while nbytes > 0 do
nbytes = nbytes - 1
c = string.byte(ustr, pos)
pos = pos + 1
if c < 0x80 or c >= 0xc0 then -- Invalid
return nil
else
ucv = ucv * 64 + (c - 0x80);
end
end
return ucv
end
end
end
function utilities.splitUtf8(s) -- Return an array of UTF8 strings each representing a Unicode char
local seq = 0
local rv = {}
local val = -1
local this = ""
for i = 1, #s do
local c = string.byte(s, i)
if seq == 0 then
if val > -1 then
rv[1+#rv] = this
this = ""
end
seq = c < 0x80 and 1 or c < 0xE0 and 2 or c < 0xF0 and 3 or
c < 0xF8 and 4 or --c < 0xFC and 5 or c < 0xFE and 6 or
error("invalid UTF-8 character sequence")
val = bit32.band(c, 2^(8-seq) - 1)
this = this .. s[i]
else
val = bit32.bor(bit32.lshift(val, 6), bit32.band(c, 0x3F))
this = this .. s[i]
end
seq = seq - 1
end
rv[1+#rv] = this
return rv
end
function utilities.utf8_to_utf16be(str)
local ustr = string.format("%04x", 0xfeff) -- BOM
for uchr in utilities.utf8codes(str) do
if (uchr < 0x10000) then
ustr = ustr..string.format("%04x", uchr)
else -- Surrogate pair
local sur_hi = (uchr - 0x10000) / 0x400 + 0xd800
local sur_lo = (uchr - 0x10000) % 0x400 + 0xdc00
ustr = ustr..string.format("%04x%04x", sur_hi, sur_lo)
end
end
return ustr
end
return utilities
|
local utilities = {}
require("bit32-compat")
function utilities.required(t, name, context)
if not t[name] then utilities.error(context.." needs a "..name.." parameter") end
return t[name]
end
function utilities.error(message,bug)
if(SILE.currentCommand and type(SILE.currentCommand) == "table") then
print("\n! "..message.. " at "..SILE.currentlyProcessingFile.." l."..(SILE.currentCommand.line)..", col."..(SILE.currentCommand.col))
else
print("\n! "..message.. " at "..SILE.currentlyProcessingFile)
end
if bug then print(debug.traceback()) end
SILE.outputter:finish()
os.exit(1)
end
function utilities.warn(message)
print("\n! "..message)
--print(debug.traceback())
--os.exit(1)
end
function utilities.debugging(category)
return SILE.debugFlags.all or SILE.debugFlags[category]
end
function utilities.gtoke(string, pattern)
string = string and tostring(string) or ''
pattern = pattern and tostring(pattern) or "%s+"
local length = #string
return coroutine.wrap(function()
local index = 1
repeat
local first, last = string:find(pattern, index)
if last then
if index < first then coroutine.yield({ string = string:sub(index, first - 1) }) end
coroutine.yield({ separator = string:sub(first, last) })
index = last + 1
else
if index <= length then
coroutine.yield({ string = string:sub(index) })
end
break
end
until index > length
end)
end
function utilities.debug(category, messages)
if utilities.debugging(category) then
print("["..category.."]", messages)
end
end
function utilities.concat(array, c)
return table.concat(utilities.map(tostring, array), c)
end
function utilities.inherit(orig, spec)
local new = std.tree.clone(orig)
if spec then
for k,v in pairs(spec) do new[k] = v end
end
if new.init then new:init() end
return new
end
function utilities.map(func, array)
local new_array = {}
local last = #array
for i = 1, last do
new_array[i] = func(array[i])
end
return new_array
end
function utilities.splice(array, start, stop, replacement)
local ptr = start
local room = stop - start + 1
local last = replacement and #replacement or 0
for i = 1, last do
if room > 0 then
room = room - 1
array[ptr] = replacement[i]
else
table.insert(array, ptr, replacement[i])
end
ptr = ptr + 1
end
for i = 1, room do
table.remove(array, ptr)
end
return array
end
function utilities.sum(array)
local t = 0
local last = #array
for i = 1, last do
t = t + array[i]
end
return t
end
function utilities.allCombinations(options)
local count = 1
for i=1,#options do count = count * options[i] end
return coroutine.wrap(function()
for i=0,count-1 do
local this = i
local rv = {}
for j = 1,#options do
local base = options[j]
rv[#rv+1] = this % base + 1
this = (this - this % base )/ base
end
coroutine.yield(rv)
end
end)
end
-- Unicode-related utilities
pcall(function() utf8 = require("utf8") end)
if not utf8 then utf8 = {} end
utilities.codepoint = utf8.codepoint or function (uchar)
local seq = 0
local val = -1
for i = 1, #uchar do
local c = string.byte(uchar, i)
if seq == 0 then
if val > -1 then return val end
seq = c < 0x80 and 1 or c < 0xE0 and 2 or c < 0xF0 and 3 or
c < 0xF8 and 4 or --c < 0xFC and 5 or c < 0xFE and 6 or
error("invalid UTF-8 character sequence")
val = bit32.band(c, 2^(8-seq) - 1)
else
val = bit32.bor(bit32.lshift(val, 6), bit32.band(c, 0x3F))
end
seq = seq - 1
end
return val
end
utilities.utf8codes = utf8.codes or function (ustr)
local pos = 1
return function()
if pos > #ustr then
return nil
else
local c, ucv = 0, 0
local nbytes = 0
c = string.byte(ustr, pos)
pos = pos + 1
if c < 0x80 then
ucv = c
nbytes = 0
elseif c >= 0xc0 and c < 0xe0 then -- 110x xxxx
ucv = c - 0xc0
nbytes = 1
elseif c >= 0xe0 and c < 0xf0 then -- 1110 xxxx
ucv = c - 0xe0
nbytes = 2
elseif c >= 0xf0 and c < 0xf8 then -- 1111 0xxx
ucv = c - 0xf0
nbytes = 3
elseif c >= 0xf8 and c < 0xfc then -- 1111 10xx
ucv = c - 0xf8
nbytes = 4
elseif c >= 0xfc and c < 0xfe then -- 1111 110x
ucv = c - 0xfc
nbytes = 5
else -- Invalid
return nil
end
if pos + nbytes > #ustr + 1 then -- Invalid
return nil
end
while nbytes > 0 do
nbytes = nbytes - 1
c = string.byte(ustr, pos)
pos = pos + 1
if c < 0x80 or c >= 0xc0 then -- Invalid
return nil
else
ucv = ucv * 64 + (c - 0x80);
end
end
return ucv
end
end
end
function utilities.splitUtf8(s) -- Return an array of UTF8 strings each representing a Unicode char
local seq = 0
local rv = {}
local val = -1
local this = ""
for i = 1, #s do
local c = string.byte(s, i)
if seq == 0 then
if val > -1 then
rv[1+#rv] = this
this = ""
end
seq = c < 0x80 and 1 or c < 0xE0 and 2 or c < 0xF0 and 3 or
c < 0xF8 and 4 or --c < 0xFC and 5 or c < 0xFE and 6 or
error("invalid UTF-8 character sequence")
val = bit32.band(c, 2^(8-seq) - 1)
this = this .. s[i]
else
val = bit32.bor(bit32.lshift(val, 6), bit32.band(c, 0x3F))
this = this .. s[i]
end
seq = seq - 1
end
rv[1+#rv] = this
return rv
end
function utilities.utf8_to_utf16be(str)
local ustr = string.format("%04x", 0xfeff) -- BOM
for uchr in utilities.utf8codes(str) do
if (uchr < 0x10000) then
ustr = ustr..string.format("%04x", uchr)
else -- Surrogate pair
local sur_hi = (uchr - 0x10000) / 0x400 + 0xd800
local sur_lo = (uchr - 0x10000) % 0x400 + 0xdc00
ustr = ustr..string.format("%04x%04x", sur_hi, sur_lo)
end
end
return ustr
end
return utilities
|
Fix broken build?
|
Fix broken build?
|
Lua
|
mit
|
WAKAMAZU/sile_fe,simoncozens/sile,WAKAMAZU/sile_fe,shirat74/sile,WAKAMAZU/sile_fe,anthrotype/sile,alerque/sile,simoncozens/sile,shirat74/sile,alerque/sile,neofob/sile,anthrotype/sile,simoncozens/sile,alerque/sile,WAKAMAZU/sile_fe,alerque/sile,anthrotype/sile,shirat74/sile,anthrotype/sile,neofob/sile,shirat74/sile,neofob/sile,neofob/sile,simoncozens/sile
|
d53080dbea39c1134a658874ff3375e2a0b3f665
|
nsagent.lua
|
nsagent.lua
|
#!/usr/bin/env lua
-- flock -xn /tmp/ns-agent.lock -c "/usr/bin/lua <agent_path>"
local cjson = require "cjson"
local md5 = require "md5"
local http = require "socket.http"
local inspect = require "inspect"
local API_VERSION = "1.0"
local API_PACKAGE_CONFIG = 'http://localhost:8888/api/v1/package-config.json'
local SD_CARD_DIR = '/tmp/data'
local APK_CACHE_DIR = SD_CARD_DIR .. '/apk_cache'
local IPA_CACHE_DIR = SD_CARD_DIR .. '/ipa_cache'
local TPM_IPA_DIR = SD_CARD_DIR .. '/tpm_ipa'
local TPM_APK_DIR = SD_CARD_DIR .. '/tpm_apk'
local TPM_IPA_NAME = "tpm.ipa"
local TPM_APK_NAME = "tpm.apk"
local DELIMITER = "/"
local PLATFORM_IOS = "ios"
local PLATFORM_ANDROID = "android"
local function calc_md5sum(filename)
local file, err = io.open(filename, "rb")
if err then
error("Can't open file: " .. filename .. " Reason: " .. err)
end
local content = file:read("*a")
file:close()
return md5.sumhexa(content)
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
local function startswith(str, substr)
if str == nil or substr == nil then
return nil, "the string or the sub-stirng parameter is nil"
end
if string.find(str, substr) ~= 1 then
return false
else
return true
end
end
local function get_package_config()
local response, status_code = http.request(API_PACKAGE_CONFIG)
if status_code ~= 200 then
error("Get package config failed.")
end
return cjson.decode(response)
end
local function get_cache_dir(platform)
if platform == PLATFORM_ANDROID then
return APK_CACHE_DIR
elseif platform == PLATFORM_IOS then
return IPA_CACHE_DIR
else
error(string.format("Invalid platform: %s", platform))
end
end
-- 包都匹配返回true, 否则返回false
local function check_all_pkg(packages, platform)
-- NOTE: 因为是move过去的, 所以认为一定成功, 不再校验md5
local all_exist = true
for i=1, #packages do
local delimiter = ''
local path = packages[i]["path"]
if not startswith(path, "/") then
delimiter = DELIMITER
end
path = get_cache_dir(platform) .. delimiter .. path
-- print(path)
if not is_file_exists(path) then
all_exist = false
end
end
return all_exist
end
local function get_tmp_pkg_name(platform)
if platform == PLATFORM_ANDROID then
return TPM_APK_DIR .. DELIMITER .. TPM_APK_NAME
elseif platform == PLATFORM_IOS then
return TPM_IPA_DIR .. DELIMITER .. TPM_IPA_NAME
else
error(string.format("Invalid platform: %s", platform))
end
end
local function download_pkg(package, platform)
local tmp_pkg_name = get_tmp_pkg_name(platform)
local cmd = "rm -f " .. tmp_pkg_name
os.execute(cmd)
cmd = string.format("wget '%s' -O %s", package["url"], tmp_pkg_name)
os.execute(cmd)
local file_md5 = calc_md5sum(tmp_pkg_name)
if file_md5 ~= package["md5sum"] then
error(string.format("Invalid MD5: %s md5sum: %s", package["url"], file_md5))
end
end
local function move_pkg_to_cache_dir(package, platform)
local delimiter = ''
local path = package["path"]
if not startswith(path, "/") then
delimiter = DELIMITER
end
path = get_cache_dir(platform) .. delimiter .. path
local cmd = "mkdir -p " .. path
os.execute(cmd)
cmd = string.format("mv -f %s %s%s", get_tmp_pkg_name(platform), get_cache_dir(platform), package["path"])
-- print(cmd)
os.execute(cmd)
end
local function remove_cache_dir(platform)
local cmd = string.format("rm -rf %s/*", get_cache_dir(platform))
os.execute(cmd)
end
local function make_all_dir()
local cmd = "mkdir -p " .. IPA_CACHE_DIR
os.execute(cmd)
cmd = "mkdir -p " .. TPM_IPA_DIR
os.execute(cmd)
cmd = "mkdir -p " .. APK_CACHE_DIR
os.execute(cmd)
cmd = "mkdir -p " .. TPM_APK_DIR
os.execute(cmd)
end
local function update_pkg(package, platform)
if not check_all_pkg(package, platform) then
remove_cache_dir(platform)
make_all_dir()
for i=1, #package do
local pkg = package[i]
download_pkg(pkg, platform)
move_pkg_to_cache_dir(pkg, platform)
end
end
print(string.format("%s status: %s", platform, tostring(check_all_pkg(package, platform))))
end
local function run()
make_all_dir()
local config = get_package_config()
if config["version"] ~= API_VERSION then
error("API version does't match")
end
-- TODO: check schema
update_pkg(config["iosPackages"], PLATFORM_IOS)
update_pkg(config["androidPackages"], PLATFORM_ANDROID)
end
-----------------------------------
run()
|
#!/usr/bin/env lua
-- flock -xn /tmp/ns-agent.lock -c "/usr/bin/lua <agent_path>"
local NS_DEBUG = true
local cjson = require "cjson"
local md5 = require "md5"
local http = require "socket.http"
local inspect = require "inspect"
local API_VERSION = "1.0"
local API_PACKAGE_CONFIG = 'http://willard.com.cn/test.html'
local SD_CARD_DIR = '/tmp/data'
local APK_CACHE_DIR = SD_CARD_DIR .. '/apk_cache'
local IPA_CACHE_DIR = SD_CARD_DIR .. '/ipa_cache'
local TPM_IPA_DIR = SD_CARD_DIR .. '/tpm_ipa'
local TPM_APK_DIR = SD_CARD_DIR .. '/tpm_apk'
local TPM_IPA_NAME = "tpm.ipa"
local TPM_APK_NAME = "tpm.apk"
local DELIMITER = "/"
local PLATFORM_IOS = "ios"
local PLATFORM_ANDROID = "android"
local function debug_log(msg)
if NS_DEBUG then
print(msg)
end
end
local function calc_md5sum(filename)
local file, err = io.open(filename, "rb")
if err then
error("Can't open file: " .. filename .. " Reason: " .. err)
end
local content = file:read("*a")
file:close()
return md5.sumhexa(content)
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
local function startswith(str, substr)
if str == nil or substr == nil then
return nil, "the string or the sub-stirng parameter is nil"
end
if string.find(str, substr) ~= 1 then
return false
else
return true
end
end
local function get_package_config()
local response, status_code = http.request(API_PACKAGE_CONFIG)
if status_code ~= 200 then
error("Get package config failed.")
end
return cjson.decode(response)
end
local function get_cache_dir(platform)
if platform == PLATFORM_ANDROID then
return APK_CACHE_DIR
elseif platform == PLATFORM_IOS then
return IPA_CACHE_DIR
else
error(string.format("Invalid platform: %s", platform))
end
end
-- 包都匹配返回true, 否则返回false
local function check_all_pkg(packages, platform)
-- NOTE: 因为是move过去的, 所以认为一定成功, 不再校验md5
local all_exist = true
for i=1, #packages do
local delimiter = ''
local path = packages[i]["path"]
if not startswith(path, "/") then
delimiter = DELIMITER
end
path = get_cache_dir(platform) .. delimiter .. path
if not is_file_exists(path) then
all_exist = false
end
end
return all_exist
end
local function get_tmp_pkg_name(platform)
if platform == PLATFORM_ANDROID then
return TPM_APK_DIR .. DELIMITER .. TPM_APK_NAME
elseif platform == PLATFORM_IOS then
return TPM_IPA_DIR .. DELIMITER .. TPM_IPA_NAME
else
error(string.format("Invalid platform: %s", platform))
end
end
local function download_pkg(package, platform)
local tmp_pkg_name = get_tmp_pkg_name(platform)
local cmd = "rm -f " .. tmp_pkg_name
debug_log(cmd)
os.execute(cmd)
cmd = string.format("wget '%s' -O %s", package["url"], tmp_pkg_name)
debug_log(cmd)
os.execute(cmd)
local file_md5 = calc_md5sum(tmp_pkg_name)
if file_md5 ~= package["md5sum"] then
error(string.format("Invalid MD5: %s md5sum: %s", package["url"], file_md5))
end
end
local function move_pkg_to_cache_dir(package, platform)
local delimiter = ''
local path = string.match(package["path"], "(.+)/[^/]*%.%w+$")
if path == nil then
path = "/"
end
if not startswith(path, "/") then
delimiter = DELIMITER
end
path = get_cache_dir(platform) .. delimiter .. path
local cmd = "mkdir -p " .. path
debug_log(cmd)
os.execute(cmd)
cmd = string.format("mv -f %s %s%s", get_tmp_pkg_name(platform), get_cache_dir(platform), package["path"])
debug_log(cmd)
os.execute(cmd)
end
local function remove_cache_dir(platform)
local cmd = string.format("rm -rf %s/*", get_cache_dir(platform))
debug_log(cmd)
os.execute(cmd)
end
local function make_all_dir()
local cmd = "mkdir -p " .. IPA_CACHE_DIR
debug_log(cmd)
os.execute(cmd)
cmd = "mkdir -p " .. TPM_IPA_DIR
debug_log(cmd)
os.execute(cmd)
cmd = "mkdir -p " .. APK_CACHE_DIR
debug_log(cmd)
os.execute(cmd)
cmd = "mkdir -p " .. TPM_APK_DIR
debug_log(cmd)
os.execute(cmd)
end
local function update_pkg(package, platform)
if not check_all_pkg(package, platform) then
remove_cache_dir(platform)
make_all_dir()
for i=1, #package do
local pkg = package[i]
download_pkg(pkg, platform)
move_pkg_to_cache_dir(pkg, platform)
end
end
print(string.format("%s status: %s", platform, tostring(check_all_pkg(package, platform))))
end
local function run()
make_all_dir()
local config = get_package_config()
if config["version"] ~= API_VERSION then
error("API version does't match")
end
-- TODO: check schema
update_pkg(config["iosPackages"], PLATFORM_IOS)
update_pkg(config["androidPackages"], PLATFORM_ANDROID)
end
-----------------------------------
run()
|
Add debug log & fix path issue
|
Add debug log & fix path issue
|
Lua
|
mit
|
NsLib/hiwifi-appstore-proxy,NsLib/hiwifi-appstore-proxy
|
92f52581fe2f3d166d26dd5bbacf946c962ab34f
|
SVUI_!Core/system/_reports/reputation_new.lua
|
SVUI_!Core/system/_reports/reputation_new.lua
|
--[[
##############################################################################
S V U I By: Failcoder
##############################################################################
##########################################################
LOCALIZED LUA FUNCTIONS
##########################################################
]]--
--[[ GLOBALS ]]--
local _G = _G;
local select = _G.select;
local table = _G.table;
local twipe = table.wipe;
local tsort = table.sort;
--[[ STRING METHODS ]]--
local format, gsub = string.format, string.gsub;
--[[
##########################################################
GET ADDON DATA
##########################################################
]]--
local SV = select(2, ...)
local L = SV.L;
local Reports = SV.Reports;
local LRD = LibStub("LibReputationData-1.0");
--[[
##########################################################
REPUTATION STATS
##########################################################
]]--
local HEX_COLOR = "22FFFF";
local TEXT_PATTERN = "|cff22EF5F%s|r|cff888888 - [|r%d%%|cff888888]|r";
local FACTION_BAR_COLORS = _G.FACTION_BAR_COLORS;
local sort_menu_fn = function(a,b)
if (a ~= nil and b ~= nil) then
if (a.text ~= nil and b.text ~= nil) then
return a.text < b.text
end
end
return false
end;
local function CacheRepData(data)
local count = 1
local factions = LRD:GetAllActiveFactionsInfo();
if not factions then return end
twipe(data)
for i=1, #factions do
if(factions[i].isActive and (not factions[i].isHeader)) then
local factionIndex = tonumber(factions[i].factionIndex)
local fn = function()
local active = LRD:GetWatchedFactionIndex()
if factionIndex ~= active then
LRD:SetWatchedFaction(factionIndex)
end
end
tinsert(data,{text = factions[i].name, func = fn});
count=count+1;
end
end
if #data > 0 then
tsort(data, sort_menu_fn);
end
end
local function DoTooltip(self)
Reports:SetDataTip(self)
local factionIndex, faction = LRD:GetReputationInfo()
if not factionIndex then
Reports.ToolTip:AddLine("No Watched Factions")
else
Reports.ToolTip:AddLine(faction.name)
Reports.ToolTip:AddLine(' ')
Reports.ToolTip:AddDoubleLine(STANDING..':', faction.standing, 1, 1, 1)
Reports.ToolTip:AddDoubleLine(REPUTATION..':', format('%d / %d (%d%%)', faction.value - faction.min, faction.max - faction.min, (faction.value - faction.min) / (faction.max - faction.min) * 100), 1, 1, 1)
end
Reports.ToolTip:AddLine(" ", 1, 1, 1)
Reports.ToolTip:AddDoubleLine("[Click]", "Change Watched Faction", 0,1,0, 0.5,1,0.5)
Reports:ShowDataTip(true)
end
--[[
##########################################################
STANDARD TYPE
##########################################################
]]--
local REPORT_NAME = "Reputation";
local Report = Reports:NewReport(REPORT_NAME, {
type = "data source",
text = REPORT_NAME .. " Info",
icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]]
});
Report.Populate = function(self)
if self.barframe:IsShown()then
self.text:SetAllPoints(self)
self.text:SetJustifyH("CENTER")
self.barframe:Hide()
self.text:SetAlpha(1)
self.text:SetShadowOffset(2, -4)
end
local factionIndex, faction = LRD:GetReputationInfo()
if not factionIndex then
self.text:SetText("No watched factions")
else
self.text:SetFormattedText(TEXT_PATTERN , faction.standing, ((faction.value - faction.min) / (faction.max - faction.min) * 100))
end
end
Report.OnClick = function(self, button)
SV.Dropdown:Open(self, self.InnerData, "Select Faction")
end
Report.OnEnter = function(self)
DoTooltip(self)
end
Report.OnInit = function(self)
LRD.RegisterCallback(self,"FACTIONS_LOADED", function ()
if(not self.InnerData) then
self.InnerData = {}
end
CacheRepData(self.InnerData)
Report.Populate(self)
end)
LRD.RegisterCallback(self, "REPUTATION_CHANGED", function()
Report.Populate(self)
end)
LRD:ForceUpdate()
end
--[[
##########################################################
BAR TYPE
##########################################################
]]--
local BAR_NAME = "Reputation Bar";
local ReportBar = Reports:NewReport(BAR_NAME, {
type = "data source",
text = BAR_NAME,
icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]]
});
ReportBar.Populate = function(self)
if not self.barframe:IsShown()then
self.barframe:Show()
self.barframe.icon.texture:SetTexture(SV.media.dock.reputationLabel)
self.text:SetAlpha(1)
self.text:SetShadowOffset(1, -2)
end
local bar = self.barframe.bar;
local factionIndex, faction = LRD:GetReputationInfo()
if not factionIndex then
bar:SetStatusBarColor(0,0,0)
bar:SetMinMaxValues(0,1)
bar:SetValue(0)
self.text:SetText("No Faction")
else
local color = FACTION_BAR_COLORS[faction.standingID]
bar:SetStatusBarColor(color.r, color.g, color.b)
bar:SetMinMaxValues(faction.min, faction.max)
bar:SetValue(faction.value)
self.text:SetText(faction.standing)
end
end
ReportBar.OnClick = function(self, button)
SV.Dropdown:Open(self, self.InnerData, "Select Faction")
end
ReportBar.OnEnter = function(self)
DoTooltip(self)
end
ReportBar.OnInit = function(self)
LRD.RegisterCallback(self,"FACTIONS_LOADED", function ()
if(not self.InnerData) then
self.InnerData = {}
end
CacheRepData(self.InnerData)
ReportBar.Populate(self)
end)
LRD.RegisterCallback(self, "REPUTATION_CHANGED", function()
ReportBar.Populate(self)
end)
LRD:ForceUpdate()
end
|
--[[
##############################################################################
S V U I By: Failcoder
##############################################################################
##########################################################
LOCALIZED LUA FUNCTIONS
##########################################################
]]--
--[[ GLOBALS ]]--
local _G = _G;
local select = _G.select;
local table = _G.table;
local twipe = table.wipe;
local tsort = table.sort;
--[[ STRING METHODS ]]--
local format, gsub = string.format, string.gsub;
--[[
##########################################################
GET ADDON DATA
##########################################################
]]--
local SV = select(2, ...)
local L = SV.L;
local Reports = SV.Reports;
local LRD = LibStub("LibReputationData-1.0");
--[[
##########################################################
REPUTATION STATS
##########################################################
]]--
local HEX_COLOR = "22FFFF";
local TEXT_PATTERN = "|cff22EF5F%s|r|cff888888 - [|r%d%%|cff888888]|r";
local FACTION_BAR_COLORS = _G.FACTION_BAR_COLORS;
local sort_menu_fn = function(a,b)
if (a ~= nil and b ~= nil) then
if (a.text ~= nil and b.text ~= nil) then
return a.text < b.text
end
end
return false
end;
local function CacheRepData(data)
local count = 1
local factions = LRD:GetAllActiveFactionsInfo();
if not factions then return end
twipe(data)
for i=1, #factions do
if(factions[i].isActive and (not factions[i].isHeader)) then
local factionIndex = tonumber(factions[i].factionIndex)
local fn = function()
local active = LRD:GetWatchedFactionIndex()
if factionIndex ~= active then
LRD:SetWatchedFaction(factionIndex)
end
end
tinsert(data,{text = factions[i].name, func = fn});
count=count+1;
end
end
if #data > 0 then
tsort(data, sort_menu_fn);
end
end
local function DoTooltip(self)
Reports:SetDataTip(self)
local factionIndex, faction = LRD:GetReputationInfo()
if not factionIndex then
Reports.ToolTip:AddLine("No Watched Factions")
else
Reports.ToolTip:AddLine(faction.name)
Reports.ToolTip:AddLine(' ')
Reports.ToolTip:AddDoubleLine(STANDING..':', faction.standing, 1, 1, 1)
if (faction.standing == "Exalted") then
Reports.ToolTip:AddDoubleLine(REPUTATION..':', '24,000 / 24,000 (100%)', 1, 1, 1)
else
Reports.ToolTip:AddDoubleLine(REPUTATION..':', format('%d / %d (%d%%)', faction.value - faction.min, faction.max - faction.min, (faction.value - faction.min) / (faction.max - faction.min) * 100), 1, 1, 1)
end
end
Reports.ToolTip:AddLine(" ", 1, 1, 1)
Reports.ToolTip:AddDoubleLine("[Click]", "Change Watched Faction", 0,1,0, 0.5,1,0.5)
Reports:ShowDataTip(true)
end
--[[
##########################################################
STANDARD TYPE
##########################################################
]]--
local REPORT_NAME = "Reputation";
local Report = Reports:NewReport(REPORT_NAME, {
type = "data source",
text = REPORT_NAME .. " Info",
icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]]
});
Report.Populate = function(self)
if self.barframe:IsShown()then
self.text:SetAllPoints(self)
self.text:SetJustifyH("CENTER")
self.barframe:Hide()
self.text:SetAlpha(1)
self.text:SetShadowOffset(2, -4)
end
local factionIndex, faction = LRD:GetReputationInfo()
if not factionIndex then
self.text:SetText("No watched factions")
else
self.text:SetFormattedText(TEXT_PATTERN , faction.standing, ((faction.value - faction.min) / (faction.max - faction.min) * 100))
end
end
Report.OnClick = function(self, button)
SV.Dropdown:Open(self, self.InnerData, "Select Faction")
end
Report.OnEnter = function(self)
DoTooltip(self)
end
Report.OnInit = function(self)
LRD.RegisterCallback(self,"FACTIONS_LOADED", function ()
if(not self.InnerData) then
self.InnerData = {}
end
CacheRepData(self.InnerData)
Report.Populate(self)
end)
LRD.RegisterCallback(self, "REPUTATION_CHANGED", function()
Report.Populate(self)
end)
LRD:ForceUpdate()
end
--[[
##########################################################
BAR TYPE
##########################################################
]]--
local BAR_NAME = "Reputation Bar";
local ReportBar = Reports:NewReport(BAR_NAME, {
type = "data source",
text = BAR_NAME,
icon = [[Interface\Addons\SVUI_!Core\assets\icons\SVUI]]
});
ReportBar.Populate = function(self)
if not self.barframe:IsShown()then
self.barframe:Show()
self.barframe.icon.texture:SetTexture(SV.media.dock.reputationLabel)
self.text:SetAlpha(1)
self.text:SetShadowOffset(1, -2)
end
local bar = self.barframe.bar;
local factionIndex, faction = LRD:GetReputationInfo()
if not factionIndex then
bar:SetStatusBarColor(0,0,0)
bar:SetMinMaxValues(0,1)
bar:SetValue(0)
self.text:SetText("No Faction")
else
local color = FACTION_BAR_COLORS[faction.standingID]
bar:SetStatusBarColor(color.r, color.g, color.b)
bar:SetMinMaxValues(faction.min, faction.max)
bar:SetValue(faction.value)
self.text:SetText(faction.standing)
end
end
ReportBar.OnClick = function(self, button)
SV.Dropdown:Open(self, self.InnerData, "Select Faction")
end
ReportBar.OnEnter = function(self)
DoTooltip(self)
end
ReportBar.OnInit = function(self)
LRD.RegisterCallback(self,"FACTIONS_LOADED", function ()
if(not self.InnerData) then
self.InnerData = {}
end
CacheRepData(self.InnerData)
ReportBar.Populate(self)
end)
LRD.RegisterCallback(self, "REPUTATION_CHANGED", function()
ReportBar.Populate(self)
end)
LRD:ForceUpdate()
end
|
Reputation bar - Exalted tooltip fix.
|
Reputation bar - Exalted tooltip fix.
|
Lua
|
mit
|
finalsliver/supervillain-ui,FailcoderAddons/supervillain-ui
|
afa9a85ad2eb8efc957c92dd197e7b3743f2ca1c
|
premake.lua
|
premake.lua
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu > ../releases/release.log")
result = os.execute("make CONFIG=Release >../releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
print("TODO - set version number in premake")
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.execute("premake --clean --no-tests --target gnu >../release.log")
os.execute("make CONFIG=Release >../release.log")
if (windows) then
result = os.execute(string.format("7z a -tzip ..\\premake-win32-%s.zip bin\\release\\premake4.exe >../release.log", version))
elseif (macosx) then
error("OSX binary not implemented yet")
else
error("Linux binary not implemented yet")
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.chdir("..")
os.rmdir(folder)
os.remove("release.log")
end
|
project.name = "Premake4"
-- Project options
addoption("no-tests", "Build without automated tests")
-- Output directories
project.config["Debug"].bindir = "bin/debug"
project.config["Release"].bindir = "bin/release"
-- Packages
dopackage("src")
-- Cleanup code
function doclean(cmd, arg)
docommand(cmd, arg)
os.rmdir("bin")
os.rmdir("doc")
end
-- Release code
REPOS = "https://premake.svn.sourceforge.net/svnroot/premake"
TRUNK = "/trunk"
BRANCHES = "/branches/4.0-alpha/"
function dorelease(cmd, arg)
if (not arg) then
error "You must specify a version"
end
-------------------------------------------------------------------
-- Make sure everything is good before I start
-------------------------------------------------------------------
print("")
print("PRE-FLIGHT CHECKLIST")
print(" * is README up-to-date?")
print(" * is CHANGELOG up-to-date?")
print(" * did you test build with GCC?")
print(" * did you test build with Doxygen?")
print(" * are 'svn' (all) and '7z' (Windows) available?")
print("")
print("Press [Enter] to continue or [^C] to quit.")
io.stdin:read("*l")
-------------------------------------------------------------------
-- Set up environment
-------------------------------------------------------------------
local version = arg
os.mkdir("releases")
local folder = "premake-"..version
local trunk = REPOS..TRUNK
local branch = REPOS..BRANCHES..version
-------------------------------------------------------------------
-- Build and run all automated tests on working copy
-------------------------------------------------------------------
print("Building tests on working copy...")
os.execute("premake --target gnu >releases/release.log")
result = os.execute("make CONFIG=Release >releases/release.log")
if (result ~= 0) then
error("Test build failed; see release.log for details")
end
-------------------------------------------------------------------
-- Look for a release branch in SVN, and create one from trunk if necessary
-------------------------------------------------------------------
print("Checking for release branch...")
os.chdir("releases")
result = os.execute(string.format("svn ls %s >release.log 2>&1", branch))
if (result ~= 0) then
print("Creating release branch...")
result = os.execute(string.format('svn copy %s %s -m "Creating release branch for %s" >release.log', trunk, branch, version))
if (result ~= 0) then
error("Failed to create release branch at "..branch)
end
end
-------------------------------------------------------------------
-- Checkout a local copy of the release branch
-------------------------------------------------------------------
print("Getting source code from release branch...")
os.execute(string.format("svn co %s %s >release.log", branch, folder))
if (not os.fileexists(folder.."/README.txt")) then
error("Unable to checkout from repository at "..branch)
end
-------------------------------------------------------------------
-- Embed version numbers into the files
-------------------------------------------------------------------
print("TODO - set version number in premake")
-------------------------------------------------------------------
-- Build the release binary for this platform
-------------------------------------------------------------------
print("Building release version...")
os.chdir(folder)
os.execute("premake --clean --no-tests --target gnu >../release.log")
os.execute("make CONFIG=Release >../release.log")
if (windows) then
result = os.execute(string.format("7z a -tzip ..\\premake-win32-%s.zip bin\\release\\premake4.exe >../release.log", version))
elseif (macosx) then
error("OSX binary not implemented yet")
else
error("Linux binary not implemented yet")
end
if (result ~= 0) then
error("Failed to build binary package; see release.log for details")
end
-------------------------------------------------------------------
-- Clean up
-------------------------------------------------------------------
print("Cleaning up...")
os.chdir("..")
os.rmdir(folder)
os.remove("release.log")
end
|
Minor fixes to release script
|
Minor fixes to release script
--HG--
extra : convert_revision : svn%3A644ed5ae-bb15-0410-aa60-99f397bbb77a/trunk%40315
|
Lua
|
bsd-3-clause
|
annulen/premake-dev-rgeary,annulen/premake,annulen/premake,annulen/premake,annulen/premake-annulen,annulen/premake-annulen,warrenseine/premake,Lusito/premake,annulen/premake,annulen/premake-annulen,Lusito/premake,annulen/premake-dev-rgeary,annulen/premake-dev-rgeary,Lusito/premake,annulen/premake-annulen,warrenseine/premake,Lusito/premake,warrenseine/premake
|
f05918122ce93226f6b9e94f3048c7987146c88e
|
core/certmanager.lua
|
core/certmanager.lua
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local configmanager = require "core.configmanager";
local log = require "util.logger".init("certmanager");
local ssl = ssl;
local ssl_newcontext = ssl and ssl.newcontext;
local setmetatable, tostring = setmetatable, tostring;
local prosody = prosody;
local resolve_path = configmanager.resolve_relative_path;
local config_path = prosody.paths.config;
local luasec_major, luasec_minor = ssl and ssl._VERSION:match("^(%d+)%.(%d+)");
local luasec_has_noticket = ssl and (tonumber(luasec_major)>0 or tonumber(luasec_minor)>=4);
module "certmanager"
-- Global SSL options if not overridden per-host
local default_ssl_config = configmanager.get("*", "core", "ssl");
local default_capath = "/etc/ssl/certs";
local default_verify = (ssl and ssl.x509 and { "peer", "client_once", "continue", "ignore_purpose" }) or "none";
local default_options = { "no_sslv2", luasec_has_noticket and "no_ticket" or nil };
function create_context(host, mode, user_ssl_config)
user_ssl_config = user_ssl_config or default_ssl_config;
if not ssl then return nil, "LuaSec (required for encryption) was not found"; end
if not user_ssl_config then return nil, "No SSL/TLS configuration present for "..host; end
local ssl_config = {
mode = mode;
protocol = user_ssl_config.protocol or "sslv23";
key = resolve_path(config_path, user_ssl_config.key);
password = user_ssl_config.password or function() log("error", "Encrypted certificate for %s requires 'ssl' 'password' to be set in config", host); end;
certificate = resolve_path(config_path, user_ssl_config.certificate);
capath = resolve_path(config_path, user_ssl_config.capath or default_capath);
cafile = resolve_path(config_path, user_ssl_config.cafile);
verify = user_ssl_config.verify or default_verify;
options = user_ssl_config.options or default_options;
depth = user_ssl_config.depth;
};
local ctx, err = ssl_newcontext(ssl_config);
-- LuaSec ignores the cipher list from the config, so we have to take care
-- of it ourselves (W/A for #x)
if ctx and user_ssl_config.ciphers then
local success;
success, err = ssl.context.setcipher(ctx, user_ssl_config.ciphers);
if not success then ctx = nil; end
end
if not ctx then
err = err or "invalid ssl config"
local file = err:match("^error loading (.-) %(");
if file then
if file == "private key" then
file = ssl_config.key or "your private key";
elseif file == "certificate" then
file = ssl_config.certificate or "your certificate file";
end
local reason = err:match("%((.+)%)$") or "some reason";
if reason == "Permission denied" then
reason = "Check that the permissions allow Prosody to read this file.";
elseif reason == "No such file or directory" then
reason = "Check that the path is correct, and the file exists.";
elseif reason == "system lib" then
reason = "Previous error (see logs), or other system error.";
elseif reason == "(null)" or not reason then
reason = "Check that the file exists and the permissions are correct";
else
reason = "Reason: "..tostring(reason):lower();
end
log("error", "SSL/TLS: Failed to load '%s': %s (for %s)", file, reason, host);
else
log("error", "SSL/TLS: Error initialising for %s: %s", host, err);
end
end
return ctx, err;
end
function reload_ssl_config()
default_ssl_config = configmanager.get("*", "core", "ssl");
end
prosody.events.add_handler("config-reloaded", reload_ssl_config);
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local configmanager = require "core.configmanager";
local log = require "util.logger".init("certmanager");
local ssl = ssl;
local ssl_newcontext = ssl and ssl.newcontext;
local setmetatable, tostring = setmetatable, tostring;
local prosody = prosody;
local resolve_path = configmanager.resolve_relative_path;
local config_path = prosody.paths.config;
local luasec_has_noticket;
if ssl then
local luasec_major, luasec_minor = ssl._VERSION:match("^(%d+)%.(%d+)");
luasec_has_noticket = tonumber(luasec_major)>0 or tonumber(luasec_minor)>=4;
end
module "certmanager"
-- Global SSL options if not overridden per-host
local default_ssl_config = configmanager.get("*", "core", "ssl");
local default_capath = "/etc/ssl/certs";
local default_verify = (ssl and ssl.x509 and { "peer", "client_once", "continue", "ignore_purpose" }) or "none";
local default_options = { "no_sslv2", luasec_has_noticket and "no_ticket" or nil };
function create_context(host, mode, user_ssl_config)
user_ssl_config = user_ssl_config or default_ssl_config;
if not ssl then return nil, "LuaSec (required for encryption) was not found"; end
if not user_ssl_config then return nil, "No SSL/TLS configuration present for "..host; end
local ssl_config = {
mode = mode;
protocol = user_ssl_config.protocol or "sslv23";
key = resolve_path(config_path, user_ssl_config.key);
password = user_ssl_config.password or function() log("error", "Encrypted certificate for %s requires 'ssl' 'password' to be set in config", host); end;
certificate = resolve_path(config_path, user_ssl_config.certificate);
capath = resolve_path(config_path, user_ssl_config.capath or default_capath);
cafile = resolve_path(config_path, user_ssl_config.cafile);
verify = user_ssl_config.verify or default_verify;
options = user_ssl_config.options or default_options;
depth = user_ssl_config.depth;
};
local ctx, err = ssl_newcontext(ssl_config);
-- LuaSec ignores the cipher list from the config, so we have to take care
-- of it ourselves (W/A for #x)
if ctx and user_ssl_config.ciphers then
local success;
success, err = ssl.context.setcipher(ctx, user_ssl_config.ciphers);
if not success then ctx = nil; end
end
if not ctx then
err = err or "invalid ssl config"
local file = err:match("^error loading (.-) %(");
if file then
if file == "private key" then
file = ssl_config.key or "your private key";
elseif file == "certificate" then
file = ssl_config.certificate or "your certificate file";
end
local reason = err:match("%((.+)%)$") or "some reason";
if reason == "Permission denied" then
reason = "Check that the permissions allow Prosody to read this file.";
elseif reason == "No such file or directory" then
reason = "Check that the path is correct, and the file exists.";
elseif reason == "system lib" then
reason = "Previous error (see logs), or other system error.";
elseif reason == "(null)" or not reason then
reason = "Check that the file exists and the permissions are correct";
else
reason = "Reason: "..tostring(reason):lower();
end
log("error", "SSL/TLS: Failed to load '%s': %s (for %s)", file, reason, host);
else
log("error", "SSL/TLS: Error initialising for %s: %s", host, err);
end
end
return ctx, err;
end
function reload_ssl_config()
default_ssl_config = configmanager.get("*", "core", "ssl");
end
prosody.events.add_handler("config-reloaded", reload_ssl_config);
return _M;
|
certmanager: Fix for traceback WITH LuaSec... (!) (thanks IRON)
|
certmanager: Fix for traceback WITH LuaSec... (!) (thanks IRON)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
8b27e6eb0f67a33a5d2499b725f5d360bc6c1fed
|
lua/parse/yaml/prefix/directives.lua
|
lua/parse/yaml/prefix/directives.lua
|
local re = require 're'
return re.compile([[
directives <- {| directive* |} end_marker {}
end_marker <- '---' !%S %s*
directive <- {|
'%'
-- name
{ns_char+}
-- parameters
( %LINESPACE+ !'#' {ns_char+} )*
-- comment(s) & line break(s)
%REST_OF_LINE+
-- if there's no space between the name/final param and
-- the comments, the # will be part of the name/param
|}
ns_char <- !%BOM %S
]], {
LINESPACE = require 'parse.char.ascii7.in_line_space';
BOM = require 'parse.match.utf8.bom';
REST_OF_LINE = require 'parse.yaml.match.rest_of_line.not_final';
})
|
local re = require 're'
return re.compile([[
directives <- {| directive* |} end_marker {}
end_marker <- '---' !%S %s*
directive <- {|
'%'
-- name
{:name: {ns_char+} :}
-- parameters
{:arguments: {| ( %LINESPACE+ !'#' {ns_char+} )+ |} :}?
-- comment(s) & line break(s)
%REST_OF_LINE+
-- if there's no space between the name/final param and
-- the comments, the # will be part of the name/param
|}
ns_char <- !%BOM %S
]], {
LINESPACE = require 'parse.char.ascii7.in_line_space';
BOM = require 'parse.match.utf8.bom';
REST_OF_LINE = require 'parse.yaml.match.rest_of_line.not_final';
})
|
Fix argument capture
|
Fix argument capture
|
Lua
|
mit
|
taxler/radish,taxler/radish,taxler/radish,taxler/radish,taxler/radish,taxler/radish
|
48f3e9f9a284b6f979bc0ba770146208164e0c8e
|
zaqar/storage/redis/scripts/claim_messages.lua
|
zaqar/storage/redis/scripts/claim_messages.lua
|
--[[
Copyright (c) 2014 Rackspace Hosting, 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.
--]]
-- Read params
local msgset_key = KEYS[1]
local now = tonumber(ARGV[1])
local limit = tonumber(ARGV[2])
local claim_id = ARGV[3]
local claim_expires = tonumber(ARGV[4])
local msg_ttl = tonumber(ARGV[5])
local msg_expires = tonumber(ARGV[6])
-- Scan for up to 'limit' unclaimed messages
local BATCH_SIZE = 100
local start = 0
local claimed_msgs = {}
local found_unclaimed = false
while (#claimed_msgs < limit) do
local stop = (start + BATCH_SIZE - 1)
local msg_ids = redis.call('ZRANGE', msgset_key, start, stop)
if (#msg_ids == 0) then
break
end
start = start + BATCH_SIZE
-- TODO(kgriffs): Try moving claimed IDs to a different set
-- to avoid scanning through already-claimed messages.
for i, mid in ipairs(msg_ids) do
-- NOTE(kgriffs): Since execution of this script can not
-- happen in parallel, once we find the first unclaimed
-- message, the remaining messages will always be
-- unclaimed as well.
if not found_unclaimed then
local msg = redis.call('HMGET', mid, 'c', 'c.e')
if msg[1] == '' or tonumber(msg[2]) <= now then
found_unclaimed = true
end
end
if found_unclaimed then
local msg_expires_prev = redis.call('HGET', mid, 'e')
-- Found an unclaimed message, so claim it
redis.call('HMSET', mid,
'c', claim_id,
'c.e', claim_expires)
-- Will the message expire early?
if tonumber(msg_expires_prev) < claim_expires then
redis.call('HMSET', mid,
't', msg_ttl,
'e', msg_expires)
end
claimed_msgs[#claimed_msgs + 1] = mid
if (#claimed_msgs == limit) then
break
end
end
end
end
return claimed_msgs
|
--[[
Copyright (c) 2014 Rackspace Hosting, 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.
--]]
-- Read params
local msgset_key = KEYS[1]
local now = tonumber(ARGV[1])
local limit = tonumber(ARGV[2])
local claim_id = ARGV[3]
local claim_expires = tonumber(ARGV[4])
local msg_ttl = tonumber(ARGV[5])
local msg_expires = tonumber(ARGV[6])
-- Scan for up to 'limit' unclaimed messages
local BATCH_SIZE = 100
local start = 0
local claimed_msgs = {}
local msg_ids_to_cleanup = {}
local found_unclaimed = false
while (#claimed_msgs < limit) do
local stop = (start + BATCH_SIZE - 1)
local msg_ids = redis.call('ZRANGE', msgset_key, start, stop)
if (#msg_ids == 0) then
break
end
start = start + BATCH_SIZE
-- TODO(kgriffs): Try moving claimed IDs to a different set
-- to avoid scanning through already-claimed messages.
for i, mid in ipairs(msg_ids) do
-- NOTE(kgriffs): Since execution of this script can not
-- happen in parallel, once we find the first unclaimed
-- message, the remaining messages will always be
-- unclaimed as well.
if not found_unclaimed then
local msg = redis.call('HMGET', mid, 'c', 'c.e')
if msg[1] == false and msg[2] == false then
-- NOTE(Eva-i): It means the message expired and does not
-- actually exist anymore, we must later garbage collect it's
-- ID from the set and move on.
msg_ids_to_cleanup[#msg_ids_to_cleanup + 1] = mid
elseif msg[1] == '' or tonumber(msg[2]) <= now then
found_unclaimed = true
end
end
if found_unclaimed then
-- Found an unclaimed message, so claim it.
local msg_expires_prev = redis.call('HGET', mid, 'e')
if msg_expires_prev ~= false then
-- NOTE(Eva-i): Condition above means the message is not
-- expired and we really can claim it.
redis.call('HMSET', mid,
'c', claim_id,
'c.e', claim_expires)
-- Will the message expire early?
if tonumber(msg_expires_prev) < claim_expires then
redis.call('HMSET', mid,
't', msg_ttl,
'e', msg_expires)
end
claimed_msgs[#claimed_msgs + 1] = mid
if (#claimed_msgs == limit) then
break
end
end
end
end
end
if (#msg_ids_to_cleanup ~= 0) then
-- Garbage collect expired message IDs stored in msgset_key.
redis.call('ZREM', msgset_key, unpack(msg_ids_to_cleanup))
end
return claimed_msgs
|
Fix fail of claim after some message expire(Redis)
|
Fix fail of claim after some message expire(Redis)
If some messages in Redis are already expired, it's impossible to claim
any new messages.
Zaqar internally catches this error from running "claim_messages.lua":
"ResponseError: Error running script: @user_script:59: user_script:59:
attempt to compare nil with number". And returns 503 response code to
the user.
This happens because if some message is expired (it's <message_id>
record was automatically deleted from database), it's ID is still listed
in set "<project_id>.<queue_name>.messages" and Zaqar uses this ID. In
this case on attempt to get some values from <message_id>'s fields, it
gets 'nil' values.
This patch makes Zaqar check if returned field values from <message_id>
record are 'nil'. If values are not 'nil', process the record normally.
If values are 'nil', remember message ID. In the end of the script
"claim_messages.lua" garbage collect all such message IDs, because it's
a good opportunity to do so.
Closes-Bug: 1548135
Change-Id: Iedd2b82f6da30dd38bfdbb837bf9d0d4c282e222
|
Lua
|
apache-2.0
|
openstack/zaqar,openstack/zaqar,openstack/zaqar,openstack/zaqar
|
4d42cfaa6145b12d7b7bbfa6ce2bc7a0229440c9
|
libs/weblit-app.lua
|
libs/weblit-app.lua
|
--[[lit-meta
name = "creationix/weblit-app"
version = "2.1.0"
dependencies = {
'creationix/[email protected]',
'luvit/[email protected]',
'luvit/[email protected]',
}
description = "Weblit is a webapp framework designed around routes and middleware layers."
tags = {"weblit", "router", "framework"}
license = "MIT"
author = { name = "Tim Caswell" }
homepage = "https://github.com/creationix/weblit/blob/master/libs/weblit-app.lua"
]]
local createServer = require('coro-net').createServer
local httpCodec = require('http-codec')
local parseQuery = require('querystring').parse
-- Ignore SIGPIPE if it exists on platform
local uv = require('uv')
if uv.constants.SIGPIPE then
uv.new_signal():start("sigpipe")
end
local server = {}
local handlers = {}
local bindings = {}
-- Provide a nice case insensitive interface to headers.
local headerMeta = {
__index = function (list, name)
if type(name) ~= "string" then
return rawget(list, name)
end
name = name:lower()
for i = 1, #list do
local key, value = unpack(list[i])
if key:lower() == name then return value end
end
end,
__newindex = function (list, name, value)
-- non-string keys go through as-is.
if type(name) ~= "string" then
return rawset(list, name, value)
end
-- First remove any existing pairs with matching key
local lowerName = name:lower()
for i = #list, 1, -1 do
if list[i][1]:lower() == lowerName then
table.remove(list, i)
end
end
-- If value is nil, we're done
if value == nil then return end
-- Otherwise, set the key(s)
if (type(value) == "table") then
-- We accept a table of strings
for i = 1, #value do
rawset(list, #list + 1, {name, tostring(value[i])})
end
else
-- Or a single value interperted as string
rawset(list, #list + 1, {name, tostring(value)})
end
end,
}
local function handleRequest(head, input, socket)
local req = {
socket = socket,
method = head.method,
path = head.path,
headers = setmetatable({}, headerMeta),
version = head.version,
keepAlive = head.keepAlive,
body = input
}
for i = 1, #head do
req.headers[i] = head[i]
end
local res = {
code = 404,
headers = setmetatable({}, headerMeta),
body = "Not Found\n",
}
local function run(i)
local success, err = pcall(function ()
i = i or 1
local go = i < #handlers
and function ()
return run(i + 1)
end
or function () end
return handlers[i](req, res, go)
end)
if not success then
res.code = 500
res.headers = setmetatable({}, headerMeta)
res.body = err
print(err)
end
end
run(1)
local out = {
code = res.code,
keepAlive = res.keepAlive,
}
for i = 1, #res.headers do
out[i] = res.headers[i]
end
return out, res.body, res.upgrade
end
local function handleConnection(read, write, socket, updateDecoder, updateEncoder)
for head in read do
local parts = {}
for chunk in read do
if #chunk > 0 then
parts[#parts + 1] = chunk
else
break
end
end
local res, body, upgrade = handleRequest(head, #parts > 0 and table.concat(parts) or nil, socket)
write(res)
if upgrade then
return upgrade(read, write, updateDecoder, updateEncoder, socket)
end
write(body)
if not (res.keepAlive and head.keepAlive) then
break
end
end
write()
end
function server.bind(options)
if not options.host then
options.host = "127.0.0.1"
end
if not options.port then
options.port = require('uv').getuid() == 0 and
(options.tls and 443 or 80) or
(options.tls and 8443 or 8080)
end
bindings[#bindings + 1] = options
return server
end
function server.use(handler)
handlers[#handlers + 1] = handler
return server
end
function server.start()
if #bindings == 0 then
server.bind({})
end
for i = 1, #bindings do
local options = bindings[i]
options.decode = httpCodec.decoder()
options.encode = httpCodec.encoder()
createServer(options, handleConnection)
print("HTTP server listening at http" .. (options.tls and "s" or "") .. "://" .. options.host .. (options.port == (options.tls and 443 or 80) and "" or ":" .. options.port) .. "/")
end
return server
end
local quotepattern = '(['..("%^$().[]*+-?"):gsub("(.)", "%%%1")..'])'
local function escape(str)
return str:gsub(quotepattern, "%%%1")
end
local function compileGlob(glob)
local parts = {"^"}
for a, b in glob:gmatch("([^*]*)(%**)") do
if #a > 0 then
parts[#parts + 1] = escape(a)
end
if #b > 0 then
parts[#parts + 1] = "(.*)"
end
end
parts[#parts + 1] = "$"
local pattern = table.concat(parts)
return function (string)
return string and string:match(pattern)
end
end
local function compileRoute(route)
local parts = {"^"}
local names = {}
for a, b, c, d in route:gmatch("([^:]*):([_%a][_%w]*)(:?)([^:]*)") do
if #a > 0 then
parts[#parts + 1] = escape(a)
end
if #c > 0 then
parts[#parts + 1] = "(.*)"
else
parts[#parts + 1] = "([^/]*)"
end
names[#names + 1] = b
if #d > 0 then
parts[#parts + 1] = escape(d)
end
end
if #parts == 1 then
return function (string)
if string == route then return {} end
end
end
parts[#parts + 1] = "$"
local pattern = table.concat(parts)
return function (string)
local matches = {string:match(pattern)}
if #matches > 0 then
local results = {}
for i = 1, #matches do
results[i] = matches[i]
results[names[i]] = matches[i]
end
return results
end
end
end
function server.route(options, handler)
local method = options.method
local path = options.path and compileRoute(options.path)
local host = options.host and compileGlob(options.host)
local filter = options.filter
server.use(function (req, res, go)
if method and req.method ~= method then return go() end
if host and not host(req.headers.host) then return go() end
if filter and not filter(req) then return go() end
local params
if path then
local pathname, query = req.path:match("^([^?]*)%??(.*)")
params = path(pathname)
if not params then return go() end
if #query > 0 then
req.query = parseQuery(query)
end
end
req.params = params or {}
return handler(req, res, go)
end)
return server
end
return server
|
--[[lit-meta
name = "creationix/weblit-app"
version = "2.1.1"
dependencies = {
'creationix/[email protected]',
'luvit/[email protected]',
'luvit/[email protected]',
}
description = "Weblit is a webapp framework designed around routes and middleware layers."
tags = {"weblit", "router", "framework"}
license = "MIT"
author = { name = "Tim Caswell" }
homepage = "https://github.com/creationix/weblit/blob/master/libs/weblit-app.lua"
]]
local createServer = require('coro-net').createServer
local httpCodec = require('http-codec')
local parseQuery = require('querystring').parse
-- Ignore SIGPIPE if it exists on platform
local uv = require('uv')
if uv.constants.SIGPIPE then
uv.new_signal():start("sigpipe")
end
local server = {}
local handlers = {}
local bindings = {}
-- Provide a nice case insensitive interface to headers.
local headerMeta = {
__index = function (list, name)
if type(name) ~= "string" then
return rawget(list, name)
end
name = name:lower()
for i = 1, #list do
local key, value = unpack(list[i])
if key:lower() == name then return value end
end
end,
__newindex = function (list, name, value)
-- non-string keys go through as-is.
if type(name) ~= "string" then
return rawset(list, name, value)
end
-- First remove any existing pairs with matching key
local lowerName = name:lower()
for i = #list, 1, -1 do
if list[i][1]:lower() == lowerName then
table.remove(list, i)
end
end
-- If value is nil, we're done
if value == nil then return end
-- Otherwise, set the key(s)
if (type(value) == "table") then
-- We accept a table of strings
for i = 1, #value do
rawset(list, #list + 1, {name, tostring(value[i])})
end
else
-- Or a single value interperted as string
rawset(list, #list + 1, {name, tostring(value)})
end
end,
}
local function handleRequest(head, input, socket)
local req = {
socket = socket,
method = head.method,
path = head.path,
headers = setmetatable({}, headerMeta),
version = head.version,
keepAlive = head.keepAlive,
body = input
}
for i = 1, #head do
req.headers[i] = head[i]
end
local res = {
code = 404,
headers = setmetatable({}, headerMeta),
body = "Not Found\n",
}
local function run(i)
local success, err = pcall(function ()
i = i or 1
local go = i < #handlers
and function ()
return run(i + 1)
end
or function () end
return handlers[i](req, res, go)
end)
if not success then
res.code = 500
res.headers = setmetatable({}, headerMeta)
res.body = err
print(err)
end
end
run(1)
local out = {
code = res.code,
keepAlive = res.keepAlive,
}
for i = 1, #res.headers do
out[i] = res.headers[i]
end
return out, res.body, res.upgrade
end
local function handleConnection(read, write, socket, updateDecoder, updateEncoder)
for head in read do
local parts = {}
for chunk in read do
if #chunk > 0 then
parts[#parts + 1] = chunk
else
break
end
end
local res, body, upgrade = handleRequest(head, #parts > 0 and table.concat(parts) or nil, socket)
write(res)
if upgrade then
return upgrade(read, write, updateDecoder, updateEncoder, socket)
end
write(body)
if not (res.keepAlive and head.keepAlive) then
break
end
end
write()
end
function server.bind(options)
if not options.host then
options.host = "127.0.0.1"
end
if not options.port then
local getuid = require('uv').getuid
options.port = (getuid and getuid() == 0) and
(options.tls and 443 or 80) or
(options.tls and 8443 or 8080)
end
bindings[#bindings + 1] = options
return server
end
function server.use(handler)
handlers[#handlers + 1] = handler
return server
end
function server.start()
if #bindings == 0 then
server.bind({})
end
for i = 1, #bindings do
local options = bindings[i]
options.decode = httpCodec.decoder()
options.encode = httpCodec.encoder()
createServer(options, handleConnection)
print("HTTP server listening at http" .. (options.tls and "s" or "") .. "://" .. options.host .. (options.port == (options.tls and 443 or 80) and "" or ":" .. options.port) .. "/")
end
return server
end
local quotepattern = '(['..("%^$().[]*+-?"):gsub("(.)", "%%%1")..'])'
local function escape(str)
return str:gsub(quotepattern, "%%%1")
end
local function compileGlob(glob)
local parts = {"^"}
for a, b in glob:gmatch("([^*]*)(%**)") do
if #a > 0 then
parts[#parts + 1] = escape(a)
end
if #b > 0 then
parts[#parts + 1] = "(.*)"
end
end
parts[#parts + 1] = "$"
local pattern = table.concat(parts)
return function (string)
return string and string:match(pattern)
end
end
local function compileRoute(route)
local parts = {"^"}
local names = {}
for a, b, c, d in route:gmatch("([^:]*):([_%a][_%w]*)(:?)([^:]*)") do
if #a > 0 then
parts[#parts + 1] = escape(a)
end
if #c > 0 then
parts[#parts + 1] = "(.*)"
else
parts[#parts + 1] = "([^/]*)"
end
names[#names + 1] = b
if #d > 0 then
parts[#parts + 1] = escape(d)
end
end
if #parts == 1 then
return function (string)
if string == route then return {} end
end
end
parts[#parts + 1] = "$"
local pattern = table.concat(parts)
return function (string)
local matches = {string:match(pattern)}
if #matches > 0 then
local results = {}
for i = 1, #matches do
results[i] = matches[i]
results[names[i]] = matches[i]
end
return results
end
end
end
function server.route(options, handler)
local method = options.method
local path = options.path and compileRoute(options.path)
local host = options.host and compileGlob(options.host)
local filter = options.filter
server.use(function (req, res, go)
if method and req.method ~= method then return go() end
if host and not host(req.headers.host) then return go() end
if filter and not filter(req) then return go() end
local params
if path then
local pathname, query = req.path:match("^([^?]*)%??(.*)")
params = path(pathname)
if not params then return go() end
if #query > 0 then
req.query = parseQuery(query)
end
end
req.params = params or {}
return handler(req, res, go)
end)
return server
end
return server
|
Fix default port logic for windows
|
Fix default port logic for windows
|
Lua
|
mit
|
zhaozg/weblit
|
2851d0db33729bc50d03dd9472d8e467a2de2284
|
lib/cassandra.lua
|
lib/cassandra.lua
|
-- Implementation of CQL Binary protocol V2 available at https://git-wip-us.apache.org/repos/asf?p=cassandra.git;a=blob_plain;f=doc/native_protocol_v2.spec;hb=HEAD
local tcp = ngx.socket.tcp
local _M = {}
_M.version = "0.0.1"
local CQL_VERSION = "3.0.0"
local version_codes = {
REQUEST='\002',
RESPONSE='\130', --\x82
}
local op_codes = {
ERROR='\000',
STARTUP='\001',
READY='\002',
AUTHENTICATE='\003',
--\004
OPTIONS='\005',
SUPPORTED='\006',
QUERY='\007',
RESULT='\008',
PREPARE='\009',
EXECUTE='\010',
REGISTER='\011',
EVENT='\012',
BATCH='\013',
AUTH_CHALLENGE='\014',
AUTH_RESPONSE='\015',
AUTH_SUCCESS='\016',
}
local consistency = {
ANY='\000\000',
ONE='\000\001',
TWO='\000\002',
THREE='\000\003',
QUORUM='\000\004',
ALL='\000\005',
LOCAL_QUORUM='\000\006',
EACH_QUORUM='\000\007',
SERIAL='\000\008',
LOCAL_SERIAL='\000\009',
LOCAL_ONE='\000\010'
}
local mt = { __index = _M }
---
--- SOCKET METHODS
---
function _M.new(self)
local sock, err = tcp()
if not sock then
return nil, err
end
return setmetatable({ sock = sock }, mt)
end
function _M.set_timeout(self, timeout)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:settimeout(timeout)
end
function _M.connect(self, ...)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
local ok, err = sock:connect(...)
if not ok then
return false, err
end
return self:startup()
end
function _M.set_keepalive(self, ...)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:setkeepalive(...)
end
function _M.get_reused_times(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:getreusedtimes()
end
local function close(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:close()
end
_M.close = close
---
--- ENCODE FUNCTIONS
---
local function big_endian_representation(num, bytes)
local t = {}
while num > 0 do
local rest = math.fmod(num, 256)
table.insert(t, 1, string.char(rest))
num = (num-rest) / 256
end
local padding = string.rep(string.char(0), bytes - #t)
return padding .. table.concat(t)
end
local function int_representation(num)
return big_endian_representation(num, 4)
end
local function short_representation(num)
return big_endian_representation(num, 2)
end
local function string_representation(str)
return short_representation(#str) .. str
end
local function long_string_representation(str)
return int_representation(#str) .. str
end
local function string_map_representation(map)
local buffer = {}
local n = 0
for k, v in pairs(map) do
buffer[#buffer + 1] = string_representation(k)
buffer[#buffer + 1] = string_representation(v)
n = n + 1
end
return short_representation(n) .. table.concat(buffer)
end
---
--- DECODE FUNCTIONS
---
local function string_to_number(str)
local number = 0
local exponent = 1
for i = #str, 1, -1 do
number = number + string.byte(str, i) * exponent
exponent = exponent * 16
end
return number
end
local function create_buffer(str)
return {str=str, pos=1}
end
local function read_bytes(buffer, n_bytes)
local bytes = string.sub(buffer.str, buffer.pos, buffer.pos + n_bytes - 1)
buffer.pos = buffer.pos + n_bytes
return bytes
end
local function read_byte(buffer)
return read_bytes(buffer, 1)
end
local function read_int(buffer)
return string_to_number(read_bytes(buffer, 4))
end
local function read_short(buffer)
return string_to_number(read_bytes(buffer, 2))
end
local function read_string(buffer)
local str_size = read_short(buffer)
return read_bytes(buffer, str_size)
end
local function debug_hex_string(str)
buffer = {}
for i = 1, #str do
buffer[i] = string.byte(str, i)
end
return table.concat(buffer, " ")
end
local function read_frame(self)
local header, err, partial = self.sock:receive(8)
if not header then
error("Failed to read frame:" .. err)
end
local header_buffer = create_buffer(header)
local version = read_byte(header_buffer)
local flags = read_byte(header_buffer)
local stream = read_byte(header_buffer)
local op_code = read_byte(header_buffer)
local length = read_int(header_buffer)
local body, err, partial = self.sock:receive(length)
if not body then
error("Failed to read body:" .. err)
end
if version ~= version_codes.RESPONSE then
error("Invalid response version")
end
local body_buffer = create_buffer(body)
if op_code == op_codes.ERROR then
local error_code = read_int(body_buffer)
local hex_error_code = string.format("%x", error_code)
local error_message = read_string(body_buffer)
error("Cassandra returned error (" .. hex_error_code .. "): '" .. error_message .. "'")
end
return {
flags=flags,
stream=stream,
op_code=op_code,
buffer=body_buffer
}
end
---
--- CLIENT METHODS
---
local function send_reply_and_get_response(self, op_code, body)
local version = version_codes.REQUEST
local flags = '\000'
local stream_id = '\000'
local length = int_representation(#body)
local frame = version .. flags .. stream_id .. op_code .. length .. body
local bytes, err = self.sock:send(frame)
if not bytes then
error("Failed to send data to cassandra: " .. err)
end
return read_frame(self)
end
function _M.startup(self)
local body = string_map_representation({["CQL_VERSION"]=CQL_VERSION})
local response = send_reply_and_get_response(self, op_codes.STARTUP, body)
if response.op_code ~= op_codes.READY then
error("Server is not ready")
end
return true
end
function _M.execute(self, query)
local query_repr = long_string_representation(query)
local flags = '\000'
local query_params = consistency.ANY .. flags
local body = query_repr .. query_params
local response = send_reply_and_get_response(self, op_codes.STARTUP, body)
end
return _M
|
-- Implementation of CQL Binary protocol V2 available at https://git-wip-us.apache.org/repos/asf?p=cassandra.git;a=blob_plain;f=doc/native_protocol_v2.spec;hb=HEAD
local tcp = ngx.socket.tcp
local _M = {}
_M.version = "0.0.1"
local CQL_VERSION = "3.0.0"
local version_codes = {
REQUEST='\002',
RESPONSE='\130', --\x82
}
local op_codes = {
ERROR='\000',
STARTUP='\001',
READY='\002',
AUTHENTICATE='\003',
--\004
OPTIONS='\005',
SUPPORTED='\006',
QUERY='\007',
RESULT='\008',
PREPARE='\009',
EXECUTE='\010',
REGISTER='\011',
EVENT='\012',
BATCH='\013',
AUTH_CHALLENGE='\014',
AUTH_RESPONSE='\015',
AUTH_SUCCESS='\016',
}
local consistency = {
ANY='\000\000',
ONE='\000\001',
TWO='\000\002',
THREE='\000\003',
QUORUM='\000\004',
ALL='\000\005',
LOCAL_QUORUM='\000\006',
EACH_QUORUM='\000\007',
SERIAL='\000\008',
LOCAL_SERIAL='\000\009',
LOCAL_ONE='\000\010'
}
local result_kinds = {
VOID=1,
ROWS=2,
SET_KEYSPACE=3,
PREPARED=4,
SCHEMA_CHANGE=5
}
local mt = { __index = _M }
---
--- SOCKET METHODS
---
function _M.new(self)
local sock, err = tcp()
if not sock then
return nil, err
end
return setmetatable({ sock = sock }, mt)
end
function _M.set_timeout(self, timeout)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:settimeout(timeout)
end
function _M.connect(self, ...)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
local ok, err = sock:connect(...)
if not ok then
return false, err
end
return self:startup()
end
function _M.set_keepalive(self, ...)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:setkeepalive(...)
end
function _M.get_reused_times(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:getreusedtimes()
end
local function close(self)
local sock = self.sock
if not sock then
return nil, "not initialized"
end
return sock:close()
end
_M.close = close
---
--- ENCODE FUNCTIONS
---
local function big_endian_representation(num, bytes)
local t = {}
while num > 0 do
local rest = math.fmod(num, 256)
table.insert(t, 1, string.char(rest))
num = (num-rest) / 256
end
local padding = string.rep(string.char(0), bytes - #t)
return padding .. table.concat(t)
end
local function int_representation(num)
return big_endian_representation(num, 4)
end
local function short_representation(num)
return big_endian_representation(num, 2)
end
local function string_representation(str)
return short_representation(#str) .. str
end
local function long_string_representation(str)
return int_representation(#str) .. str
end
local function string_map_representation(map)
local buffer = {}
local n = 0
for k, v in pairs(map) do
buffer[#buffer + 1] = string_representation(k)
buffer[#buffer + 1] = string_representation(v)
n = n + 1
end
return short_representation(n) .. table.concat(buffer)
end
---
--- DECODE FUNCTIONS
---
local function string_to_number(str)
local number = 0
local exponent = 1
for i = #str, 1, -1 do
number = number + string.byte(str, i) * exponent
exponent = exponent * 16
end
return number
end
local function create_buffer(str)
return {str=str, pos=1}
end
local function read_bytes(buffer, n_bytes)
local bytes = string.sub(buffer.str, buffer.pos, buffer.pos + n_bytes - 1)
buffer.pos = buffer.pos + n_bytes
return bytes
end
local function read_byte(buffer)
return read_bytes(buffer, 1)
end
local function read_int(buffer)
return string_to_number(read_bytes(buffer, 4))
end
local function read_short(buffer)
return string_to_number(read_bytes(buffer, 2))
end
local function read_string(buffer)
local str_size = read_short(buffer)
return read_bytes(buffer, str_size)
end
local function debug_hex_string(str)
buffer = {}
for i = 1, #str do
buffer[i] = string.byte(str, i)
end
return table.concat(buffer, " ")
end
local function read_frame(self)
local header, err, partial = self.sock:receive(8)
if not header then
error("Failed to read frame:" .. err)
end
local header_buffer = create_buffer(header)
local version = read_byte(header_buffer)
local flags = read_byte(header_buffer)
local stream = read_byte(header_buffer)
local op_code = read_byte(header_buffer)
local length = read_int(header_buffer)
local body, err, partial = self.sock:receive(length)
if not body then
error("Failed to read body:" .. err)
end
if version ~= version_codes.RESPONSE then
error("Invalid response version")
end
local body_buffer = create_buffer(body)
if op_code == op_codes.ERROR then
local error_code = read_int(body_buffer)
local hex_error_code = string.format("%x", error_code)
local error_message = read_string(body_buffer)
error("Cassandra returned error (" .. hex_error_code .. "): '" .. error_message .. "'")
end
return {
flags=flags,
stream=stream,
op_code=op_code,
buffer=body_buffer
}
end
---
--- CLIENT METHODS
---
local function send_reply_and_get_response(self, op_code, body)
local version = version_codes.REQUEST
local flags = '\000'
local stream_id = '\000'
local length = int_representation(#body)
local frame = version .. flags .. stream_id .. op_code .. length .. body
local bytes, err = self.sock:send(frame)
if not bytes then
error("Failed to send data to cassandra: " .. err)
end
return read_frame(self)
end
function _M.startup(self)
local body = string_map_representation({["CQL_VERSION"]=CQL_VERSION})
local response = send_reply_and_get_response(self, op_codes.STARTUP, body)
if response.op_code ~= op_codes.READY then
error("Server is not ready")
end
return true
end
function _M.execute(self, query)
local query_repr = long_string_representation(query)
local flags = '\000'
local query_params = consistency.ONE .. flags
local body = query_repr .. query_params
local response = send_reply_and_get_response(self, op_codes.QUERY, body)
if response.op_code ~= op_codes.RESULT then
error("Result expected")
end
assert(read_int(response.buffer) == result_kinds.ROWS)
ngx.log(ngx.ERR, "body: '" .. debug_hex_string(response.buffer.str) .. "'")
end
return _M
|
Fix query
|
Fix query
|
Lua
|
mit
|
Mashape/lua-resty-cassandra,thibaultCha/lua-resty-cassandra,kidaa/lua-resty-cassandra,jbochi/lua-resty-cassandra
|
f733686b7f493411af2d487a86773ac7a87f9704
|
upcache.lua
|
upcache.lua
|
local module = {}
local cacheScope = require "scope"
local cacheTag = require "tag"
cacheScope.publicKeys = ngx.shared.upcachePublicKeys
cacheScope.restrictions = ngx.shared.upcacheRestrictions
cacheTag.tags = ngx.shared.upcacheTags
cacheTag.variants = ngx.shared.upcacheVariants
function module.request()
local keyReq = ngx.var.uri
local nkeyReq = keyReq
local method = ngx.req.get_method()
if method == "GET" or method == "HEAD" then
nkeyReq = cacheScope.get(nkeyReq, ngx.var)
else
cacheScope.requestHandshake(ngx.var.host)
end
nkeyReq = cacheTag.get(nkeyReq)
ngx.var.hashReq = ngx.md5(nkeyReq)
ngx.ctx.upcacheKey = nkeyReq
ngx.log(ngx.INFO, "request key '", nkeyReq, "'")
end
function module.response()
local method = ngx.req.get_method()
local keyRes = ngx.ctx.upcacheKey
local nkeyRes = keyRes
if method == "GET" or method == "HEAD" then
nkeyRes = cacheScope.set(nkeyRes, ngx.var, ngx.header)
else
cacheScope.responseHandshake(ngx.var.host, ngx.header)
end
nkeyRes = cacheTag.set(nkeyRes, ngx.header)
if nkeyRes ~= keyRes then
ngx.var.hashRes = ngx.md5(nkeyRes)
else
ngx.var.hashRes = ngx.var.hashReq
end
ngx.log(ngx.INFO, "response key '", nkeyRes, "'")
end
return module
|
local module = {}
local cacheScope = require "scope"
local cacheTag = require "tag"
cacheScope.publicKeys = ngx.shared.upcachePublicKeys
cacheScope.restrictions = ngx.shared.upcacheRestrictions
cacheTag.tags = ngx.shared.upcacheTags
cacheTag.variants = ngx.shared.upcacheVariants
function module.request()
local keyReq = ngx.var.host .. ngx.var.uri
ngx.ctx.upcacheKey = keyReq
local nkeyReq = keyReq
local method = ngx.req.get_method()
if method == "GET" or method == "HEAD" then
nkeyReq = cacheScope.get(nkeyReq, ngx.var)
else
cacheScope.requestHandshake(ngx.var.host)
end
nkeyReq = cacheTag.get(nkeyReq)
ngx.var.hashReq = ngx.md5(nkeyReq)
ngx.log(ngx.INFO, "request key '", nkeyReq, "'")
end
function module.response()
local method = ngx.req.get_method()
local keyRes = ngx.ctx.upcacheKey
local nkeyRes = keyRes
if method == "GET" or method == "HEAD" then
nkeyRes = cacheScope.set(nkeyRes, ngx.var, ngx.header)
else
cacheScope.responseHandshake(ngx.var.host, ngx.header)
end
nkeyRes = cacheTag.set(nkeyRes, ngx.header)
if nkeyRes ~= keyRes then
ngx.var.hashRes = ngx.md5(nkeyRes)
else
ngx.var.hashRes = ngx.var.hashReq
end
ngx.log(ngx.INFO, "response key '", nkeyRes, "'")
end
return module
|
Fix response passing
|
Fix response passing
|
Lua
|
mit
|
kapouer/cache-protocols,kapouer/upcache
|
3fce713ae69d094cff9edec340b4537237976424
|
lua/autorun/resources_api.lua
|
lua/autorun/resources_api.lua
|
--
-- Created by IntelliJ IDEA.
-- User: Sam Elmer
-- Date: 8/11/12
-- Time: 9:03 AM
-- To change this template use File | Settings | File Templates.
--
RS = {}
--TODO: Complete Documentation
--TODO: For Developers: You need to fill this file out with your custom RD replacement/whatever.
if (SERVER) then
AddCSLuaFile("autorun/resources_api.lua")
end
if (CLIENT) then
local meta = FindMetaTable("Entity")
--- Used to draw any connections, "beams", info huds, etc for the devices.
-- This should go into ENT:Draw() or any other draw functions.
-- @param ent The entity. Does this really need explanation?
-- @return nil
function meta:ResourcesDraw(ent)
end
end
--Credit really should goto Maddog. I just rewrote these slighty
---Note: limit may be a function, value, or nil. So within tool make sure to check against function if type(limit)=="function"
--Optional: categories
function RESOURCES:ToolRegister(name, description, limit)
self.Tools[toolname] = self.Tools[toolname] or {}
self.Tools[toolname].limit = limit or 30
self.Tools[toolname].description = description or ""
end
---adds a category row to the tool
function RESOURCES:ToolRegisterCategory( toolname, categoryname, categorydescription, limit )
self.Tools[toolname] = self.Tools[toolname] or {}
self.Tools[toolname].categories = self.Tools[toolname].categories or {}
self.Tools[toolname].categories[categoryname] = {
description = categorydescription,
limit = limit
}
end
---This function will make it so custom devices could be added to your tool system.
--This call would be placed in the entities shared.lua file
--example: RESOURCES:ToolRegisterDevice("Life Support", "Storage Devices", "Air Tank", "air_tank", "models/props_c17/canister01a.mdl")
--makefunc is for backwards compatibility. This really should just but in the ENT:Initalize function
--@params toolname The name of the Tools EG: 'Cdsweapons'
--@params categoryname The Name of the category
--@params name The print name of the entity to be added
--@params class No idea
--@params model The model
--@params makefunc Backwards Compatibilty really
function RESOURCES:ToolRegisterDevice(toolname, categoryname, name, class, model, makefunc)
if type(name) == "table" then
for _, v in pairs(name) do CAF_AddStoolItem(toolname, categoryname, v.name, v.class, v.model, v.makefunc) end
return
end
self.Tools[toolname] = self.Tools[toolname] or {}
self.Tools[toolname].categories = self.Tools[toolname].categories or {}
self.Tools[toolname].categories[categoryname] = self.Tools[toolname].categories[categoryname] or {}
self.Tools[toolname].categories[categoryname].devices = self.Tools[toolname].categories[categoryname].devices or {}
self.Tools[toolname].categories[categoryname].devices[name] = {
class = class,
model = model,
makefunc = makefunc
}
CAF_AddStoolItem( category, name, model, class, makefunc )
end
if (SERVER) then
function RS:Link(ent,ent1)
RD.Link(ent,ent1)
end
--Start of Entity: Functions
local meta = FindMetaTable("Entity")
function meta:Register(typeEnt)
if (type(typeEnt) == "string") then
if (typeEnt == "NonStorage") then
RD.RegisterNonStorageDevice(self)
eslif (typeEnt == "
end
end
--- Used to Consume Resources.
-- Call it with ENT:ResConsume()
--@param res The String or table of the resource(s) you want to consume
--@param amt The amount you want to consume. Can be negative or positive.
--@returns Amount Consumed.. If it is coded by Developers to.
function meta:ResConsume( res, amt )
if (type(res) == "table") then
for k,v in pairs(res) do
local amtTotal = amtTotal + RD.Consume(self,v,amt)
end
elseif (type(res) == "string") then
return RD.Consume(self,res,amt)
end
end
--- Supplies the Resource to the connected network.
-- Call it with ENT:ResourcesSupply()
--@param res The string or table of the resource(s) you want to supply to the connected network.
--@param amt The amount you want to supply
--@returns Amount that could not be supplied.
function meta:ResourcesSupply( res, amt )
if (type(res) == "table") then
for k,v in pairs(res) do
local amtTotal = amtTotal + RD.SupplyResource(self,v,amt)
end
return amtTotal
elseif (type(res) == "string") then
return RD.SupplyResource(self,res,amt)
end
end
--- Get's the network capacity of the entity.
--@returns The Capcity of the network attached to the entity. This is the maximum amount of res it can have.
--@param res The resource you want it to return the capacity of.
function meta:ResourcesGetCapacity( res )
RD.GetNetworkCapacity(self,res)
end
--- Set's the Capacity of the entity.
--@param amt The capacity you want to set
--@param res The resource (string or table) you want to set the capacity (amt) of
--@param def The default amount you want the entity to contain.
function meta:ResourcesSetDeviceCapacity( res, amt, def )
if (type(res) == "table") then
for k,v in pairs(res) do
RD.AddResource(self, v, amt, def)
end
elseif (type(res) == "string") then
RD.AddResource(self,res,amt,def)
end
end
--- Get's the amount of the entity.
--@returns The amount contained
--@params res The resource you want the amount of. (String or Table)
function meta:ResourcesGetAmount( res )
if (type(res) == "table") then
resources = {}
for _,v in pairs(res) do
resources[v] = RD.GetResourceAmount(self, v)
end
return resources
else
return RD.GetResourceAmount(self, res )
end
end
--- Get's how much of the resource is contained in the netowrk attached to this entity.
--@returns The amount stored in the device's network
--@params res The resource you want to return the amount of. (String or Table)
function meta:ResourceGetDeviceCapaciy( res )
if (type(res) == "table") then
resources = {}
for _,v in pairs(res) do
resources[v] = RD.GetUnitCapacity(self, v)
end
return resources
else
return RD.GetUnitCapacity(self, res )
end
end
--- Custom Link. Not needed for RD3 or RD2
function ResourcesLink( ent, ent1)
end
-- No idea how this works.
function meta:ResourcesGetConnected()
local ent = self
end
function meta:ResourcesApplyDupeInfo( ply, entity, CreatedEntities )
RD.ApplyDupeInfo(self, CreatedEntities)
end
function meta:ResourceBuildDupeInfo()
RD.BuildDupeInfo(self)
end
end
|
--
-- Created by IntelliJ IDEA.
-- User: Sam Elmer
-- Date: 8/11/12
-- Time: 9:03 AM
-- To change this template use File | Settings | File Templates.
--
RS = {}
--TODO: Complete Documentation
--TODO: For Developers: You need to fill this file out with your custom RD replacement/whatever.
if (SERVER) then
AddCSLuaFile("autorun/resources_api.lua")
end
if (CLIENT) then
local meta = FindMetaTable("Entity")
--- Used to draw any connections, "beams", info huds, etc for the devices.
-- This should go into ENT:Draw() or any other draw functions.
-- @param ent The entity. Does this really need explanation?
-- @return nil
function meta:ResourcesDraw(ent)
end
end
--Credit really should goto Maddog. I just rewrote these slighty
---Note: limit may be a function, value, or nil. So within tool make sure to check against function if type(limit)=="function"
--Optional: categories
function RESOURCES:ToolRegister(name, description, limit)
self.Tools[toolname] = self.Tools[toolname] or {}
self.Tools[toolname].limit = limit or 30
self.Tools[toolname].description = description or ""
end
---adds a category row to the tool
function RESOURCES:ToolRegisterCategory( toolname, categoryname, categorydescription, limit )
self.Tools[toolname] = self.Tools[toolname] or {}
self.Tools[toolname].categories = self.Tools[toolname].categories or {}
self.Tools[toolname].categories[categoryname] = {
description = categorydescription,
limit = limit
}
end
---This function will make it so custom devices could be added to your tool system.
--This call would be placed in the entities shared.lua file
--example: RESOURCES:ToolRegisterDevice("Life Support", "Storage Devices", "Air Tank", "air_tank", "models/props_c17/canister01a.mdl")
--makefunc is for backwards compatibility. This really should just but in the ENT:Initalize function
--@params toolname The name of the Tools EG: 'Cdsweapons'
--@params categoryname The Name of the category
--@params name The print name of the entity to be added
--@params class No idea
--@params model The model
--@params makefunc Backwards Compatibilty really
function RESOURCES:ToolRegisterDevice(toolname, categoryname, name, class, model, makefunc)
if type(name) == "table" then
for _, v in pairs(name) do CAF_AddStoolItem(toolname, categoryname, v.name, v.class, v.model, v.makefunc) end
return
end
self.Tools[toolname] = self.Tools[toolname] or {}
self.Tools[toolname].categories = self.Tools[toolname].categories or {}
self.Tools[toolname].categories[categoryname] = self.Tools[toolname].categories[categoryname] or {}
self.Tools[toolname].categories[categoryname].devices = self.Tools[toolname].categories[categoryname].devices or {}
self.Tools[toolname].categories[categoryname].devices[name] = {
class = class,
model = model,
makefunc = makefunc
}
CAF_AddStoolItem( category, name, model, class, makefunc )
end
if (SERVER) then
function RS:Link(ent,ent1)
RD.Link(ent,ent1)
end
--Start of Entity: Functions
local meta = FindMetaTable("Entity")
function meta:Register(typeEnt)
if (type(typeEnt) == "string") then
if (typeEnt == "NonStorage") then
RD.RegisterNonStorageDevice(self)
else
RD.RegisterDevice(self)
end
end
end
--- Used to Consume Resources.
-- Call it with ENT:ResConsume()
--@param res The String or table of the resource(s) you want to consume
--@param amt The amount you want to consume. Can be negative or positive.
--@returns Amount Consumed.. If it is coded by Developers to.
function meta:ResConsume( res, amt )
if (type(res) == "table") then
for k,v in pairs(res) do
local amtTotal = amtTotal + RD.Consume(self,v,amt)
end
elseif (type(res) == "string") then
return RD.Consume(self,res,amt)
end
end
--- Supplies the Resource to the connected network.
-- Call it with ENT:ResourcesSupply()
--@param res The string or table of the resource(s) you want to supply to the connected network.
--@param amt The amount you want to supply
--@returns Amount that could not be supplied.
function meta:ResourcesSupply( res, amt )
if (type(res) == "table") then
for k,v in pairs(res) do
local amtTotal = amtTotal + RD.SupplyResource(self,v,amt)
end
return amtTotal
elseif (type(res) == "string") then
return RD.SupplyResource(self,res,amt)
end
end
--- Get's the network capacity of the entity.
--@returns The Capcity of the network attached to the entity. This is the maximum amount of res it can have.
--@param res The resource you want it to return the capacity of.
function meta:ResourcesGetCapacity( res )
RD.GetNetworkCapacity(self,res)
end
--- Set's the Capacity of the entity.
--@param amt The capacity you want to set
--@param res The resource (string or table) you want to set the capacity (amt) of
--@param def The default amount you want the entity to contain.
function meta:ResourcesSetDeviceCapacity( res, amt, def )
if (type(res) == "table") then
for k,v in pairs(res) do
RD.AddResource(self, v, amt, def)
end
elseif (type(res) == "string") then
RD.AddResource(self,res,amt,def)
end
end
--- Get's the amount of the entity.
--@returns The amount contained
--@params res The resource you want the amount of. (String or Table)
function meta:ResourcesGetAmount( res )
if (type(res) == "table") then
resources = {}
for _,v in pairs(res) do
resources[v] = RD.GetResourceAmount(self, v)
end
return resources
else
return RD.GetResourceAmount(self, res )
end
end
--- Get's how much of the resource is contained in the netowrk attached to this entity.
--@returns The amount stored in the device's network
--@params res The resource you want to return the amount of. (String or Table)
function meta:ResourceGetDeviceCapaciy( res )
if (type(res) == "table") then
resources = {}
for _,v in pairs(res) do
resources[v] = RD.GetUnitCapacity(self, v)
end
return resources
else
return RD.GetUnitCapacity(self, res )
end
end
--- Custom Link. Not needed for RD3 or RD2
function ResourcesLink( ent, ent1)
end
-- No idea how this works.
function meta:ResourcesGetConnected()
local ent = self
end
function meta:ResourcesApplyDupeInfo( ply, entity, CreatedEntities )
RD.ApplyDupeInfo(self, CreatedEntities)
end
function meta:ResourceBuildDupeInfo()
RD.BuildDupeInfo(self)
end
end
|
api typos fix
|
api typos fix
|
Lua
|
apache-2.0
|
N3X15/spacebuild
|
bc1da210b678361d554fd2e85761b34e7d5fdf58
|
projects/premake/thirdparty/string_id.lua
|
projects/premake/thirdparty/string_id.lua
|
#!lua
--
-- @file string_id.lua
-- @author PJ O Halloran
-- @date 25/09/2017
--
-- For building the string_id library.
--
local lib_name = "string_id"
local output_lib_name = "foonathan_" .. lib_name
local lib_src_dir = path.join(ember_thirdparty_src, lib_name)
local function build()
os.mkdir(lib_name)
os.chdir(lib_name)
os.execute("cmake -DCMAKE_INSTALL_PREFIX:PATH=\"" .. ember_home .. "\" \"" .. lib_src_dir .. "\"")
os.execute("cmake --build . --target \"" .. output_lib_name .. "\"")
if(copy_files("*." .. lib_ext, ember_root_lib) == false) then
os.exit()
end
lib_include_path = path.join(ember_root_include, lib_name)
os.mkdir(lib_include_path)
if(copy_files(path.join(lib_src_dir, "*.hpp*"), lib_include_path) == false) then
os.exit()
end
append_lib(output_lib_name)
append_shared_link_flag("-std=c++14")
append_exe_link_flag("-std=c++14")
append_cpp_flag("-std=c++14")
append_cpp_flag("-stdlib=libc++")
os.chdir("..")
os.rmdir(lib_name)
end
build()
|
#!lua
--
-- @file string_id.lua
-- @author PJ O Halloran
-- @date 25/09/2017
--
-- For building the string_id library.
--
local lib_name = "string_id"
local output_lib_name = "foonathan_" .. lib_name
local lib_src_dir = path.join(ember_thirdparty_src, lib_name)
local function build()
os.mkdir(lib_name)
os.chdir(lib_name)
os.execute("cmake -DCMAKE_INSTALL_PREFIX:PATH=\"" .. ember_home .. "\" \"" .. lib_src_dir .. "\"")
os.execute("cmake --build . --target \"" .. output_lib_name .. "\"")
if(copy_files("*." .. lib_ext, ember_root_lib) == false) then
os.exit()
end
if(copy_files("config_impl.hpp", path.join(ember_root_include, lib_name)) == false) then
os.exit()
end
lib_include_path = path.join(ember_root_include, lib_name)
os.mkdir(lib_include_path)
if(copy_files(path.join(lib_src_dir, "*.hpp*"), lib_include_path) == false) then
os.exit()
end
append_lib(output_lib_name)
append_shared_link_flag("-std=c++14")
append_exe_link_flag("-std=c++14")
append_cpp_flag("-std=c++14")
append_cpp_flag("-stdlib=libc++")
os.chdir("..")
os.rmdir(lib_name)
end
build()
|
Fix bug where required auto generated header was not copied to string_id install location.
|
Fix bug where required auto generated header was not copied to string_id install location.
|
Lua
|
mit
|
pjohalloran/ember,pjohalloran/ember,pjohalloran/ember
|
06e254cd1e180e3b97549f1635eb053403def72b
|
logout-menu-widget/logout-menu.lua
|
logout-menu-widget/logout-menu.lua
|
-------------------------------------------------
-- Logout Menu Widget for Awesome Window Manager
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/logout-menu-widget
-- @author Pavel Makhov
-- @copyright 2020 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local wibox = require("wibox")
local gears = require("gears")
local beautiful = require("beautiful")
local HOME = os.getenv('HOME')
local ICON_DIR = HOME .. '/.config/awesome/awesome-wm-widgets/logout-menu-widget/icons/'
local logout_menu_widget = wibox.widget {
{
image = ICON_DIR .. 'power_w.svg',
resize = true,
widget = wibox.widget.imagebox,
},
margins = 4,
layout = wibox.container.margin
}
local popup = awful.popup {
ontop = true,
visible = false,
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, 4)
end,
border_width = 1,
border_color = beautiful.bg_focus,
maximum_width = 400,
offset = { y = 5 },
widget = {}
}
local rows = { layout = wibox.layout.fixed.vertical }
local function worker(user_args)
local args = user_args or {}
local font = args.font or beautiful.font
local onlogout = args.onlogout or function () awesome.quit() end
local onlock = args.onlock or function() awful.spawn.with_shell("i3lock") end
local onreboot = args.onreboot or function() awful.spawn.with_shell("reboot") end
local onsuspend = args.onsuspend or function() awful.spawn.with_shell("systemctl suspend") end
local onpoweroff = args.onpoweroff or function() awful.spawn.with_shell("shutdown now") end
local menu_items = {
{ name = 'Log out', icon_name = 'log-out.svg', command = onlogout },
{ name = 'Lock', icon_name = 'lock.svg', command = onlock },
{ name = 'Reboot', icon_name = 'refresh-cw.svg', command = onreboot },
{ name = 'Suspend', icon_name = 'moon.svg', command = onsuspend },
{ name = 'Power off', icon_name = 'power.svg', command = onpoweroff },
}
for _, item in ipairs(menu_items) do
local row = wibox.widget {
{
{
{
image = ICON_DIR .. item.icon_name,
resize = false,
widget = wibox.widget.imagebox
},
{
text = item.name,
font = font,
widget = wibox.widget.textbox
},
spacing = 12,
layout = wibox.layout.fixed.horizontal
},
margins = 8,
layout = wibox.container.margin
},
bg = beautiful.bg_normal,
widget = wibox.container.background
}
row:connect_signal("mouse::enter", function(c) c:set_bg(beautiful.bg_focus) end)
row:connect_signal("mouse::leave", function(c) c:set_bg(beautiful.bg_normal) end)
local old_cursor, old_wibox
row:connect_signal("mouse::enter", function()
local wb = mouse.current_wibox
old_cursor, old_wibox = wb.cursor, wb
wb.cursor = "hand1"
end)
row:connect_signal("mouse::leave", function()
if old_wibox then
old_wibox.cursor = old_cursor
old_wibox = nil
end
end)
row:buttons(awful.util.table.join(awful.button({}, 1, function()
popup.visible = not popup.visible
item.command()
end)))
table.insert(rows, row)
end
popup:setup(rows)
logout_menu_widget:buttons(
awful.util.table.join(
awful.button({}, 1, function()
if popup.visible then
popup.visible = not popup.visible
else
popup:move_next_to(mouse.current_widget_geometry)
end
end)
)
)
return logout_menu_widget
end
return setmetatable(logout_menu_widget, { __call = function(_, ...) return worker(...) end })
|
-------------------------------------------------
-- Logout Menu Widget for Awesome Window Manager
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/logout-menu-widget
-- @author Pavel Makhov
-- @copyright 2020 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local wibox = require("wibox")
local gears = require("gears")
local beautiful = require("beautiful")
local HOME = os.getenv('HOME')
local ICON_DIR = HOME .. '/.config/awesome/awesome-wm-widgets/logout-menu-widget/icons/'
local logout_menu_widget = wibox.widget {
{
image = ICON_DIR .. 'power_w.svg',
resize = true,
widget = wibox.widget.imagebox,
},
margins = 4,
layout = wibox.container.margin
}
local popup = awful.popup {
ontop = true,
visible = false,
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, 4)
end,
border_width = 1,
border_color = beautiful.bg_focus,
maximum_width = 400,
offset = { y = 5 },
widget = {}
}
local function worker(user_args)
local rows = { layout = wibox.layout.fixed.vertical }
local args = user_args or {}
local font = args.font or beautiful.font
local onlogout = args.onlogout or function () awesome.quit() end
local onlock = args.onlock or function() awful.spawn.with_shell("i3lock") end
local onreboot = args.onreboot or function() awful.spawn.with_shell("reboot") end
local onsuspend = args.onsuspend or function() awful.spawn.with_shell("systemctl suspend") end
local onpoweroff = args.onpoweroff or function() awful.spawn.with_shell("shutdown now") end
local menu_items = {
{ name = 'Log out', icon_name = 'log-out.svg', command = onlogout },
{ name = 'Lock', icon_name = 'lock.svg', command = onlock },
{ name = 'Reboot', icon_name = 'refresh-cw.svg', command = onreboot },
{ name = 'Suspend', icon_name = 'moon.svg', command = onsuspend },
{ name = 'Power off', icon_name = 'power.svg', command = onpoweroff },
}
for _, item in ipairs(menu_items) do
local row = wibox.widget {
{
{
{
image = ICON_DIR .. item.icon_name,
resize = false,
widget = wibox.widget.imagebox
},
{
text = item.name,
font = font,
widget = wibox.widget.textbox
},
spacing = 12,
layout = wibox.layout.fixed.horizontal
},
margins = 8,
layout = wibox.container.margin
},
bg = beautiful.bg_normal,
widget = wibox.container.background
}
row:connect_signal("mouse::enter", function(c) c:set_bg(beautiful.bg_focus) end)
row:connect_signal("mouse::leave", function(c) c:set_bg(beautiful.bg_normal) end)
local old_cursor, old_wibox
row:connect_signal("mouse::enter", function()
local wb = mouse.current_wibox
old_cursor, old_wibox = wb.cursor, wb
wb.cursor = "hand1"
end)
row:connect_signal("mouse::leave", function()
if old_wibox then
old_wibox.cursor = old_cursor
old_wibox = nil
end
end)
row:buttons(awful.util.table.join(awful.button({}, 1, function()
popup.visible = not popup.visible
item.command()
end)))
table.insert(rows, row)
end
popup:setup(rows)
logout_menu_widget:buttons(
awful.util.table.join(
awful.button({}, 1, function()
if popup.visible then
popup.visible = not popup.visible
else
popup:move_next_to(mouse.current_widget_geometry)
end
end)
)
)
return logout_menu_widget
end
return setmetatable(logout_menu_widget, { __call = function(_, ...) return worker(...) end })
|
[logout] fix #241 - duplicated logout menu
|
[logout] fix #241 - duplicated logout menu
|
Lua
|
mit
|
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
|
3c0134c167f54ac98f39e61ec99f2a93ceb8bd82
|
scripts/bgfx.lua
|
scripts/bgfx.lua
|
--
-- Copyright 2010-2015 Branimir Karadzic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
function bgfxProject(_name, _kind, _defines)
project ("bgfx" .. _name)
uuid (os.uuid("bgfx" .. _name))
kind (_kind)
if _kind == "SharedLib" then
defines {
"BGFX_SHARED_LIB_BUILD=1",
}
configuration { "vs20* or mingw*" }
links {
"gdi32",
"psapi",
}
configuration { "mingw*" }
linkoptions {
"-shared",
}
configuration { "linux-*" }
buildoptions {
"-fPIC",
}
configuration {}
end
includedirs {
path.join(BGFX_DIR, "3rdparty"),
path.join(BGFX_DIR, "../bx/include"),
}
defines {
_defines,
}
if _OPTIONS["with-glfw"] then
defines {
"BGFX_CONFIG_MULTITHREADED=0",
}
end
if _OPTIONS["with-ovr"] then
defines {
"BGFX_CONFIG_USE_OVR=1",
}
includedirs {
"$(OVR_DIR)/LibOVR/Include",
}
end
if (_OPTIONS["vs"] == "vs2012-xp")
or (_OPTIONS["vs"] == "vs2013-xp") then
configuration { "vs201*" }
includedirs {
"$(DXSDK_DIR)/include",
}
end
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "android*" }
links {
"EGL",
"GLESv2",
}
configuration { "vs2008" }
includedirs {
"$(DXSDK_DIR)/include",
}
configuration { "winphone8* or winstore8*"}
linkoptions {
"/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata
}
configuration { "osx" }
links {
"Cocoa.framework",
}
configuration { "not nacl" }
includedirs {
--nacl has GLES2 headers modified...
path.join(BGFX_DIR, "3rdparty/khronos"),
}
configuration { "x64", "vs* or mingw*" }
defines {
"_WIN32_WINNT=0x601",
}
configuration {}
includedirs {
path.join(BGFX_DIR, "include"),
}
files {
path.join(BGFX_DIR, "include/**.h"),
path.join(BGFX_DIR, "src/**.cpp"),
path.join(BGFX_DIR, "src/**.h"),
}
removefiles {
path.join(BGFX_DIR, "src/**.bin.h"),
}
if _OPTIONS["with-amalgamated"] then
excludes {
path.join(BGFX_DIR, "src/bgfx.cpp"),
path.join(BGFX_DIR, "src/glcontext_egl.cpp"),
path.join(BGFX_DIR, "src/glcontext_glx.cpp"),
path.join(BGFX_DIR, "src/glcontext_ppapi.cpp"),
path.join(BGFX_DIR, "src/glcontext_wgl.cpp"),
path.join(BGFX_DIR, "src/image.cpp"),
path.join(BGFX_DIR, "src/ovr.cpp"),
path.join(BGFX_DIR, "src/renderdoc.cpp"),
path.join(BGFX_DIR, "src/renderer_d3d9.cpp"),
path.join(BGFX_DIR, "src/renderer_d3d11.cpp"),
path.join(BGFX_DIR, "src/renderer_d3d12.cpp"),
path.join(BGFX_DIR, "src/renderer_null.cpp"),
path.join(BGFX_DIR, "src/renderer_gl.cpp"),
path.join(BGFX_DIR, "src/renderer_vk.cpp"),
path.join(BGFX_DIR, "src/vertexdecl.cpp"),
}
configuration { "xcode4 or osx or ios*" }
excludes {
path.join(BGFX_DIR, "src/glcontext_eagl.mm"),
path.join(BGFX_DIR, "src/glcontext_nsgl.mm"),
path.join(BGFX_DIR, "src/renderer_mtl.mm"),
path.join(BGFX_DIR, "src/amalgamated.cpp"),
}
configuration {}
else
configuration { "xcode4 or osx or ios*" }
files {
path.join(BGFX_DIR, "src/glcontext_eagl.mm"),
path.join(BGFX_DIR, "src/glcontext_nsgl.mm"),
path.join(BGFX_DIR, "src/renderer_mtl.mm"),
}
configuration {}
excludes {
path.join(BGFX_DIR, "src/amalgamated.**"),
}
end
configuration {}
copyLib()
end
|
--
-- Copyright 2010-2015 Branimir Karadzic. All rights reserved.
-- License: http://www.opensource.org/licenses/BSD-2-Clause
--
function bgfxProject(_name, _kind, _defines)
project ("bgfx" .. _name)
uuid (os.uuid("bgfx" .. _name))
kind (_kind)
if _kind == "SharedLib" then
defines {
"BGFX_SHARED_LIB_BUILD=1",
}
configuration { "vs20* or mingw*" }
links {
"gdi32",
"psapi",
}
configuration { "mingw*" }
linkoptions {
"-shared",
}
configuration { "linux-*" }
buildoptions {
"-fPIC",
}
configuration {}
end
includedirs {
path.join(BGFX_DIR, "3rdparty"),
path.join(BGFX_DIR, "../bx/include"),
}
defines {
_defines,
}
if _OPTIONS["with-glfw"] then
defines {
"BGFX_CONFIG_MULTITHREADED=0",
}
end
if _OPTIONS["with-ovr"] then
defines {
"BGFX_CONFIG_USE_OVR=1",
}
includedirs {
"$(OVR_DIR)/LibOVR/Include",
}
end
if (_OPTIONS["vs"] == "vs2012-xp")
or (_OPTIONS["vs"] == "vs2013-xp") then
configuration { "vs201*" }
includedirs {
"$(DXSDK_DIR)/include",
}
end
configuration { "Debug" }
defines {
"BGFX_CONFIG_DEBUG=1",
}
configuration { "android*" }
links {
"EGL",
"GLESv2",
}
configuration { "vs2008" }
includedirs {
"$(DXSDK_DIR)/include",
}
configuration { "winphone8* or winstore8*"}
linkoptions {
"/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata
}
configuration { "osx" }
links {
"Cocoa.framework",
}
configuration { "not nacl" }
includedirs {
--nacl has GLES2 headers modified...
path.join(BGFX_DIR, "3rdparty/khronos"),
}
configuration { "x64", "vs* or mingw*" }
defines {
"_WIN32_WINNT=0x601",
}
configuration {}
includedirs {
path.join(BGFX_DIR, "include"),
}
files {
path.join(BGFX_DIR, "include/**.h"),
path.join(BGFX_DIR, "src/**.cpp"),
path.join(BGFX_DIR, "src/**.h"),
}
removefiles {
path.join(BGFX_DIR, "src/**.bin.h"),
}
if _OPTIONS["with-amalgamated"] then
excludes {
path.join(BGFX_DIR, "src/bgfx.cpp"),
path.join(BGFX_DIR, "src/glcontext_egl.cpp"),
path.join(BGFX_DIR, "src/glcontext_glx.cpp"),
path.join(BGFX_DIR, "src/glcontext_ppapi.cpp"),
path.join(BGFX_DIR, "src/glcontext_wgl.cpp"),
path.join(BGFX_DIR, "src/image.cpp"),
path.join(BGFX_DIR, "src/ovr.cpp"),
path.join(BGFX_DIR, "src/renderdoc.cpp"),
path.join(BGFX_DIR, "src/renderer_d3d9.cpp"),
path.join(BGFX_DIR, "src/renderer_d3d11.cpp"),
path.join(BGFX_DIR, "src/renderer_d3d12.cpp"),
path.join(BGFX_DIR, "src/renderer_null.cpp"),
path.join(BGFX_DIR, "src/renderer_gl.cpp"),
path.join(BGFX_DIR, "src/renderer_vk.cpp"),
path.join(BGFX_DIR, "src/vertexdecl.cpp"),
}
configuration { "xcode4 or osx or ios*" }
files {
path.join(BGFX_DIR, "src/amalgamated.mm"),
}
excludes {
path.join(BGFX_DIR, "src/glcontext_eagl.mm"),
path.join(BGFX_DIR, "src/glcontext_nsgl.mm"),
path.join(BGFX_DIR, "src/renderer_mtl.mm"),
path.join(BGFX_DIR, "src/amalgamated.cpp"),
}
configuration {}
else
configuration { "xcode4 or osx or ios*" }
files {
path.join(BGFX_DIR, "src/glcontext_eagl.mm"),
path.join(BGFX_DIR, "src/glcontext_nsgl.mm"),
path.join(BGFX_DIR, "src/renderer_mtl.mm"),
}
configuration {}
excludes {
path.join(BGFX_DIR, "src/amalgamated.**"),
}
end
configuration {}
copyLib()
end
|
OSX: Fixed amalgamated build.
|
OSX: Fixed amalgamated build.
|
Lua
|
bsd-2-clause
|
0-wiz-0/bgfx,LWJGL-CI/bgfx,mendsley/bgfx,septag/bgfx,LWJGL-CI/bgfx,MikePopoloski/bgfx,LWJGL-CI/bgfx,marco-we/bgfx,jdryg/bgfx,emoon/bgfx,Synxis/bgfx,jpcy/bgfx,bkaradzic/bgfx,kondrak/bgfx,mmicko/bgfx,jdryg/bgfx,jdryg/bgfx,emoon/bgfx,mcanthony/bgfx,mcanthony/bgfx,MikePopoloski/bgfx,v3n/bgfx,ktotheoz/bgfx,mendsley/bgfx,aonorin/bgfx,elmindreda/bgfx,LWJGL-CI/bgfx,marco-we/bgfx,attilaz/bgfx,jpcy/bgfx,LSBOSS/bgfx,darkimage/bgfx,cyndis/bgfx,Vertexwahn/bgfx,kondrak/bgfx,cyndis/bgfx,darkimage/bgfx,LSBOSS/bgfx,jdryg/bgfx,Synxis/bgfx,0-wiz-0/bgfx,Vertexwahn/bgfx,cuavas/bgfx,mcanthony/bgfx,cuavas/bgfx,0-wiz-0/bgfx,marco-we/bgfx,attilaz/bgfx,Extrawurst/bgfx,mendsley/bgfx,fluffyfreak/bgfx,v3n/bgfx,septag/bgfx,sergeScherbakov/bgfx,jpcy/bgfx,ktotheoz/bgfx,darkimage/bgfx,Synxis/bgfx,cyndis/bgfx,MikePopoloski/bgfx,andr3wmac/bgfx,Vertexwahn/bgfx,fluffyfreak/bgfx,BlueCrystalLabs/bgfx,sergeScherbakov/bgfx,sergeScherbakov/bgfx,aonorin/bgfx,fluffyfreak/bgfx,elmindreda/bgfx,elmindreda/bgfx,attilaz/bgfx,andr3wmac/bgfx,Extrawurst/bgfx,janstk/bgfx,septag/bgfx,ktotheoz/bgfx,aonorin/bgfx,emoon/bgfx,jpcy/bgfx,janstk/bgfx,bkaradzic/bgfx,bkaradzic/bgfx,fluffyfreak/bgfx,Extrawurst/bgfx,mmicko/bgfx,v3n/bgfx,cuavas/bgfx,BlueCrystalLabs/bgfx,janstk/bgfx,bkaradzic/bgfx,BlueCrystalLabs/bgfx,kondrak/bgfx,mmicko/bgfx,andr3wmac/bgfx,LSBOSS/bgfx
|
8a2970632ac14fa9a61b020597ccdde72790caff
|
xmake/modules/package/tools/xmake.lua
|
xmake/modules/package/tools/xmake.lua
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- imports
import("core.base.option")
-- get configs
function _get_configs(package, configs)
local configs = configs or {}
local cflags = package:config("cflags")
local cxflags = package:config("cxflags")
local cxxflags = package:config("cxxflags")
local asflags = package:config("asflags")
if package:is_plat("windows") then
local vs_runtime = package:config("vs_runtime")
if vs_runtime then
cxflags = (cxflags or "") .. " /" .. vs_runtime .. (package:debug() and "d" or "")
end
end
table.insert(configs, "--mode=" .. (package:debug() and "debug" or "release"))
if cflags then
table.insert(configs, "--cflags=" .. cflags)
end
if cxflags then
table.insert(configs, "--cxflags=" .. cxflags)
end
if cxxflags then
table.insert(configs, "--cxxflags=" .. cxxflags)
end
if asflags then
table.insert(configs, "--asflags=" .. asflags)
end
return configs
end
-- install package
function install(package, configs)
-- inherit builtin configs
local argv = {"f", "-y", "-c"}
local names = {"plat", "arch", "ndk", "ndk_sdkver", "vs", "mingw", "sdk", "bin", "cross", "ld", "sh", "ar", "cc", "cxx", "mm", "mxx"}
for _, name in ipairs(names) do
local value = get_config(name)
if value ~= nil then
table.insert(argv, "--" .. name .. "=" .. tostring(value))
end
end
-- pass configurations
for name, value in pairs(_get_configs(package, configs)) do
value = tostring(value):trim()
if type(name) == "number" then
if value ~= "" then
table.insert(argv, value)
end
else
table.insert(argv, "--" .. name .. "=" .. value)
end
end
if option.get("verbose") then
table.insert(argv, "-v")
end
if option.get("diagnosis") then
table.insert(argv, "--diagnosis")
end
os.vrunv("xmake", argv)
-- do build
argv = {}
if option.get("verbose") then
table.insert(argv, "-v")
end
if option.get("diagnosis") then
table.insert(argv, "--diagnosis")
end
os.vrunv("xmake", argv)
-- do install
argv = {"install", "-y", "-o", package:installdir()}
if option.get("verbose") then
table.insert(argv, "-v")
end
if option.get("diagnosis") then
table.insert(argv, "--diagnosis")
end
os.vrunv("xmake", argv)
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2019, TBOOX Open Source Group.
--
-- @author ruki
-- @file xmake.lua
--
-- imports
import("core.base.option")
-- get configs
function _get_configs(package, configs)
local configs = configs or {}
local cflags = package:config("cflags")
local cxflags = package:config("cxflags")
local cxxflags = package:config("cxxflags")
local asflags = package:config("asflags")
if package:is_plat("windows") then
local vs_runtime = package:config("vs_runtime")
if vs_runtime then
cxflags = (cxflags or "") .. " /" .. vs_runtime .. (package:debug() and "d" or "")
end
end
table.insert(configs, "--mode=" .. (package:debug() and "debug" or "release"))
if cflags then
table.insert(configs, "--cflags=" .. cflags)
end
if cxflags then
table.insert(configs, "--cxflags=" .. cxflags)
end
if cxxflags then
table.insert(configs, "--cxxflags=" .. cxxflags)
end
if asflags then
table.insert(configs, "--asflags=" .. asflags)
end
return configs
end
-- init arguments and inherit some global options from the parent xmake
function _init_argv(...)
local argv = {...}
for _, name in ipairs({"diagnosis", "verbose", "quiet", "yes", "confirm", "root"}) do
local value = option.get(name)
if type(value) == "boolean" then
table.insert(argv, "--" .. name)
elseif value ~= nil then
table.insert(argv, "--" .. name .. "=" .. value)
end
end
return argv
end
-- install package
function install(package, configs)
-- inherit builtin configs
local argv = _init_argv("f", "-y", "-c")
local names = {"plat", "arch", "ndk", "ndk_sdkver", "vs", "mingw", "sdk", "bin", "cross", "ld", "sh", "ar", "cc", "cxx", "mm", "mxx"}
for _, name in ipairs(names) do
local value = get_config(name)
if value ~= nil then
table.insert(argv, "--" .. name .. "=" .. tostring(value))
end
end
-- pass configurations
for name, value in pairs(_get_configs(package, configs)) do
value = tostring(value):trim()
if type(name) == "number" then
if value ~= "" then
table.insert(argv, value)
end
else
table.insert(argv, "--" .. name .. "=" .. value)
end
end
os.vrunv("xmake", argv)
-- do build
argv = _init_argv()
os.vrunv("xmake", argv)
-- do install
argv = _init_argv("install", "-y", "-o", package:installdir())
os.vrunv("xmake", argv)
end
|
fix tools/xmake for root
|
fix tools/xmake for root
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
e0a19b96e8a920a37ba59f4418bf955df18b0561
|
share/lua/sd/metachannels.lua
|
share/lua/sd/metachannels.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="Channels.com" }
end
function search( string )
-- Do the query
query = string.gsub( string, ' ', '+' )
local feed = simplexml.parse_url( "http://www.metachannels.com/api/search?apikey=54868d5d73af69d6afa12d55db6f3d18735baa7d&searchTerms=" .. query )
local channel = feed.children[1]
-- List all answers
local node = vlc.sd.add_node( { path = "", title = string } )
for _,item in ipairs( channel.children ) do
if( item.name == 'item' ) then
simplexml.add_name_maps( item )
local url = string.gsub( item.children_map['link'][1].children[1], '&', '&' )
local arturl = item.children_map['media:thumbnail'][1].attributes['url']
if( arturl == '/images/thumb_channel_default.jpg' ) then
arturl = 'http://www.metachannels.com/images/thumb_channel_default.jpg'
end
node:add_subitem( { path = url,
title = item.children_map['title'][1].children[1],
arturl = arturl } )
end
end
end
function main()
-- get the primary feed and parse the <channel> tag
local feed = simplexml.parse_url( "http://metachannels.com/meta_channels?device=vlc&lang=en,es,fr,de,it,other&format=rss&adult_ok=y" )
local channel = feed.children[1]
-- list all children that are items
for _,item in ipairs( channel.children ) do
if( item.name == 'item' ) then
simplexml.add_name_maps( item )
local url = string.gsub( item.children_map['link'][1].children[1], '&', '&' )
local node = vlc.sd.add_item( { path = url,
title = item.children_map['title'][1].children[1],
arturl = item.children_map['image'][1].children_map['url'][1].children[1] } )
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="Channels.com" }
end
function search( string )
-- Do the query
query = string.gsub( string, ' ', '+' )
local feed = simplexml.parse_url( "http://www.metachannels.com/api/search?apikey=54868d5d73af69d6afa12d55db6f3d18735baa7d&searchTerms=" .. query )
local channel = feed.children[1]
-- List all answers
local node = vlc.sd.add_node( { path = "", title = string } )
for _,item in ipairs( channel.children ) do
if( item.name == 'item' ) then
simplexml.add_name_maps( item )
local url = string.gsub( item.children_map['link'][1].children[1], '&', '&' )
local arturl = item.children_map['media:thumbnail'][1].attributes['url']
if( arturl == '/images/thumb_channel_default.jpg' ) then
arturl = 'http://www.metachannels.com/images/thumb_channel_default.jpg'
end
node:add_subitem( { path = url,
title = item.children_map['title'][1].children[1],
arturl = arturl } )
end
end
end
function main()
-- get the primary feed and parse the <channel> tag
local feed = simplexml.parse_url( "http://metachannels.com/meta_channels?device=vlc&lang=en,es,fr,de,it,other&format=rss&adult_ok=y" )
local channel = feed.children[1]
-- list all children that are items
for _,item in ipairs( channel.children ) do
if( item.name == 'item' ) then
simplexml.add_name_maps( item )
local url = string.gsub( item.children_map['link'][1].children[1], '&', '&' )
local title = item.children_map['title'][1].children[1]
local arturl = nil
if item.children_map['image'] ~= nil then
arturl = item.children_map['image'][1].children_map['url'][1].children[1]
end
local node = vlc.sd.add_item( { path = url,
title = title,
arturl = arturl } )
end
end
end
|
metachannels: don't crash if image tag is missing
|
metachannels: don't crash if image tag is missing
Fixes #6008
|
Lua
|
lgpl-2.1
|
xkfz007/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.2,krichter722/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,shyamalschandra/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,xkfz007/vlc,xkfz007/vlc,krichter722/vlc,krichter722/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,shyamalschandra/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc
|
c61420cefdd8dc16aa75f68cfaa5f58e1e950712
|
mattata/plugins/cats.lua
|
mattata/plugins/cats.lua
|
local cats = {}
local HTTP = require('socket.http')
local functions = require('mattata.functions')
function cats:init(configuration)
cats.triggers = functions.triggers(self.info.username, configuration.command_prefix):t('cat').table
cats.command = 'cat'
cats.doc = 'A random picture of a cat!'
end
function cats:action(msg, configuration)
local api = configuration.cat_api .. '&api_key=' .. configuration.cat_api_key
end
local str, res = HTTP.request(api)
if res ~= 200 then
functions.send_reply(self, msg, configuration.errors.connection)
return
end
str = str:match('<img src="(.-)">')
local output = '[Meow!]('..str..')'
functions.send_message(self, msg.chat.id, output, false, nil, true)
end
return cats
|
local cats = {}
local HTTP = require('socket.http')
local functions = require('mattata.functions')
function cats:init(configuration)
cats.command = 'cat'
cats.triggers = functions.triggers(self.info.username, configuration.command_prefix):t('cat').table
cats.doc = 'A random picture of a cat!'
end
function cats:action(msg, configuration)
local api = configuration.cat_api .. '&api_key=' .. configuration.cat_api_key
local str, res = HTTP.request(api)
if res ~= 200 then
functions.send_reply(self, msg, configuration.errors.connection)
return
end
str = str:match('<img src="(.-)">')
local output = '[Meow!]('..str..')'
functions.send_message(self, msg.chat.id, output, false, nil, true)
end
return cats
|
Minor fixes
|
Minor fixes
|
Lua
|
mit
|
barreeeiroo/BarrePolice
|
dec53bf4f1610a2baee34cb0ee2cb460d8e5676c
|
CosineDistance.lua
|
CosineDistance.lua
|
local CosineDistance, parent = torch.class('nn.CosineDistance', 'nn.Module')
function CosineDistance:__init()
parent.__init(self)
self.gradInput = {torch.Tensor(), torch.Tensor()}
end
function CosineDistance:updateOutput(input)
local input1, input2 = input[1], input[2]
if input1:dim() == 1 then
input1 = input1:view(1,-1)
input2 = input2:view(1,-1)
end
if not self.buffer then
self.buffer = input1.new()
self.w1 = input1.new()
self.w22 = input1.new()
self.w = input1.new()
self.w32 = input1.new()
self.ones = input1.new()
end
self.buffer:cmul(input1,input2)
self.w1:sum(self.buffer,2)
local epsilon = 1e-12
self.buffer:cmul(input1,input1)
self.w22:sum(self.buffer,2):add(epsilon)
self.ones:resizeAs(self.w22):fill(1)
self.w22:cdiv(self.ones, self.w22)
self.w:resizeAs(self.w22):copy(self.w22)
self.buffer:cmul(input2,input2)
self.w32:sum(self.buffer,2):add(epsilon)
self.w32:cdiv(self.ones, self.w32)
self.w:cmul(self.w32)
self.w:sqrt()
self.output:cmul(self.w1,self.w)
self.output = self.output:select(2,1)
return self.output
end
function CosineDistance:updateGradInput(input, gradOutput)
local v1 = input[1]
local v2 = input[2]
local not_batch = false
if v1:dim() == 1 then
v1 = v1:view(1,-1)
v2 = v2:view(1,-1)
not_batch = true
end
local gw1 = self.gradInput[1]
local gw2 = self.gradInput[2]
gw1:resizeAs(v1):copy(v2)
gw2:resizeAs(v1):copy(v1)
self.w = self.w:expandAs(v1)
self.buffer:cmul(self.w1,self.w22)
self.buffer = self.buffer:expandAs(v1)
gw1:addcmul(-1,self.buffer,v1)
gw1:cmul(self.w)
self.buffer:cmul(self.w1,self.w32)
self.buffer = self.buffer:expandAs(v1)
gw2:addcmul(-1,self.buffer,v2)
gw2:cmul(self.w)
local go = gradOutput:view(-1,1):expandAs(v1)
gw1:cmul(go)
gw2:cmul(go)
if not_batch then
self.gradInput[1] = gw1:select(1,1)
self.gradInput[2] = gw2:select(1,1)
end
-- fix for torch bug
-- https://github.com/torch/torch7/issues/289
self.buffer:resize()
return self.gradInput
end
|
local CosineDistance, parent = torch.class('nn.CosineDistance', 'nn.Module')
function CosineDistance:__init()
parent.__init(self)
self.gradInput = {torch.Tensor(), torch.Tensor()}
end
function CosineDistance:updateOutput(input)
local input1, input2 = input[1], input[2]
if not input1:isContiguous() then input1 = input1:clone() end
if not input2:isContiguous() then input2 = input2:clone() end
if input1:dim() == 1 then
input1 = input1:view(1,-1)
input2 = input2:view(1,-1)
end
if not self.buffer then
self.buffer = input1.new()
self.w1 = input1.new()
self.w22 = input1.new()
self.w = input1.new()
self.w32 = input1.new()
self.ones = input1.new()
end
self.buffer:cmul(input1,input2)
self.w1:sum(self.buffer,2)
local epsilon = 1e-12
self.buffer:cmul(input1,input1)
self.w22:sum(self.buffer,2):add(epsilon)
self.ones:resizeAs(self.w22):fill(1)
self.w22:cdiv(self.ones, self.w22)
self.w:resizeAs(self.w22):copy(self.w22)
self.buffer:cmul(input2,input2)
self.w32:sum(self.buffer,2):add(epsilon)
self.w32:cdiv(self.ones, self.w32)
self.w:cmul(self.w32)
self.w:sqrt()
self.output:cmul(self.w1,self.w)
self.output = self.output:select(2,1)
return self.output
end
function CosineDistance:updateGradInput(input, gradOutput)
local v1 = input[1]
local v2 = input[2]
local not_batch = false
if not v1:isContiguous() then v1 = v1:clone() end
if not v2:isContiguous() then v2 = v2:clone() end
if v1:dim() == 1 then
v1 = v1:view(1,-1)
v2 = v2:view(1,-1)
not_batch = true
end
local gw1 = self.gradInput[1]
local gw2 = self.gradInput[2]
gw1:resizeAs(v1):copy(v2)
gw2:resizeAs(v1):copy(v1)
self.w = self.w:expandAs(v1)
self.buffer:cmul(self.w1,self.w22)
self.buffer = self.buffer:expandAs(v1)
gw1:addcmul(-1,self.buffer,v1)
gw1:cmul(self.w)
self.buffer:cmul(self.w1,self.w32)
self.buffer = self.buffer:expandAs(v1)
gw2:addcmul(-1,self.buffer,v2)
gw2:cmul(self.w)
local go = gradOutput:view(-1,1):expandAs(v1)
gw1:cmul(go)
gw2:cmul(go)
if not_batch then
self.gradInput[1] = gw1:select(1,1)
self.gradInput[2] = gw2:select(1,1)
end
-- fix for torch bug
-- https://github.com/torch/torch7/issues/289
self.buffer:resize()
return self.gradInput
end
|
Fix CosineDistance to handle non-contiguous input
|
Fix CosineDistance to handle non-contiguous input
Thanks for the batch version of CosineDistance. Just one quick fix here so it can handle the non-contiguous input. This is for backward-compatibility purpose since the original/old CosineDistance.lua can handle non-contiguous input without problems, and also it is a little bit troublesome for end-users to make all input tensors contiguous by themselves. Non-contiguous input cases could happen... (for example in this model: github.com/hohoCode/textSimilarityConvNet ), so I tested this fix on my end, it now works.
Thanks.
|
Lua
|
bsd-3-clause
|
elbamos/nn,clementfarabet/nn,xianjiec/nn,joeyhng/nn,jonathantompson/nn,eriche2016/nn,nicholas-leonard/nn,colesbury/nn,witgo/nn,vgire/nn,kmul00/nn,jhjin/nn,diz-vara/nn,lukasc-ch/nn,sagarwaghmare69/nn,Moodstocks/nn,apaszke/nn,andreaskoepf/nn,PraveerSINGH/nn,caldweln/nn,mlosch/nn
|
6d601d11b55e8ce18190b9ff02d27e046cbd52f7
|
SpatialSoftMax.lua
|
SpatialSoftMax.lua
|
local SpatialSoftMax, parent = torch.class('cudnn.SpatialSoftMax', 'nn.Module')
local errcheck = cudnn.errcheck
function SpatialSoftMax:__init(fast)
parent.__init(self)
if fast then
self.algorithm = 'CUDNN_SOFTMAX_FAST'
else
self.algorithm = 'CUDNN_SOFTMAX_ACCURATE'
end
self.mode = 'CUDNN_SOFTMAX_MODE_CHANNEL'
self.iSize = torch.LongStorage(4):fill(0)
end
function SpatialSoftMax:createIODescriptors(input)
local batch = true
local singleDim = false
if input:dim() == 1 then
singleDim = true
batch = false
input = input:view(1, input:size(1), 1, 1)
elseif input:dim() == 2 then
singleDim = true
input = input:view(input:size(1), input:size(2), 1, 1)
elseif input:dim() == 3 then
input = input:view(1, input:size(1), input:size(2), input:size(3))
batch = false
end
assert(input:dim() == 4 and input:isContiguous());
if not self.iDesc or not self.oDesc or
input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2]
or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then
self.iSize = input:size()
self.gradInput:resizeAs(input)
self.output:resizeAs(input)
self.iDesc = cudnn.toDescriptor(input)
self.oDesc = cudnn.toDescriptor(self.output)
if not singleDim and not batch then
self.gradInput = self.gradInput:view(self.gradInput:size(2),
self.gradInput:size(3),
self.gradInput:size(4))
self.output = self.output:view(self.output:size(2),
self.output:size(3),
self.output:size(4))
elseif singleDim and not batch then
self.gradInput = self.gradInput:view(self.gradInput:size(2))
self.output = self.output:view(self.output:size(2))
elseif singleDim and batch then
self.gradInput = self.gradInput:view(self.gradInput:size(1), self.gradInput:size(2))
self.output = self.output:view(self.output:size(1), self.output:size(2))
end
end
end
local one = torch.FloatTensor({1});
local zero = torch.FloatTensor({0});
function SpatialSoftMax:updateOutput(input)
self:createIODescriptors(input)
errcheck('cudnnSoftmaxForward',
cudnn.getHandle(),
self.algorithm, self.mode,
one:data(),
self.iDesc[0], input:data(),
zero:data(),
self.oDesc[0], self.output:data());
return self.output
end
function SpatialSoftMax:updateGradInput(input, gradOutput)
assert(gradOutput:isContiguous());
self:createIODescriptors(input)
errcheck('cudnnSoftmaxBackward',
cudnn.getHandle(),
self.algorithm, self.mode,
one:data(),
self.oDesc[0], self.output:data(),
self.oDesc[0], gradOutput:data(),
zero:data(),
self.iDesc[0], self.gradInput:data());
return self.gradInput
end
function SpatialSoftMax:write(f)
self.iDesc = nil
self.oDesc = nil
local var = {}
for k,v in pairs(self) do
var[k] = v
end
f:writeObject(var)
end
|
local SpatialSoftMax, parent = torch.class('cudnn.SpatialSoftMax', 'nn.Module')
local errcheck = cudnn.errcheck
function SpatialSoftMax:__init(fast)
parent.__init(self)
if fast then
self.algorithm = 'CUDNN_SOFTMAX_FAST'
else
self.algorithm = 'CUDNN_SOFTMAX_ACCURATE'
end
self.mode = 'CUDNN_SOFTMAX_MODE_CHANNEL'
self.iSize = torch.LongStorage(4):fill(0)
end
function SpatialSoftMax:createIODescriptors(input)
local batch = true
local singleDim = false
if input:dim() == 1 then
singleDim = true
batch = false
input = input:view(1, input:size(1), 1, 1)
elseif input:dim() == 2 then
singleDim = true
input = input:view(input:size(1), input:size(2), 1, 1)
elseif input:dim() == 3 then
input = input:view(1, input:size(1), input:size(2), input:size(3))
batch = false
end
assert(input:dim() == 4 and input:isContiguous());
if not self.iDesc or not self.oDesc or
input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2]
or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then
self.iSize = input:size()
self.gradInput:resizeAs(input)
self.output:resizeAs(input)
self.iDesc = cudnn.toDescriptor(input)
self.oDesc = cudnn.toDescriptor(self.output)
if not singleDim and not batch then
self.gradInput = self.gradInput:view(self.gradInput:size(2),
self.gradInput:size(3),
self.gradInput:size(4))
self.output = self.output:view(self.output:size(2),
self.output:size(3),
self.output:size(4))
elseif singleDim and not batch then
self.gradInput = self.gradInput:view(self.gradInput:size(2))
self.output = self.output:view(self.output:size(2))
elseif singleDim and batch then
self.gradInput = self.gradInput:view(self.gradInput:size(1), self.gradInput:size(2))
self.output = self.output:view(self.output:size(1), self.output:size(2))
end
end
end
local one = torch.FloatTensor({1});
local zero = torch.FloatTensor({0});
function SpatialSoftMax:updateOutput(input)
self:createIODescriptors(input)
errcheck('cudnnSoftmaxForward',
cudnn.getHandle(),
self.algorithm, self.mode,
one:data(),
self.iDesc[0], input:data(),
zero:data(),
self.oDesc[0], self.output:data());
return self.output
end
function SpatialSoftMax:updateGradInput(input, gradOutput)
if not gradOutput:isContiguous() then
self._gradOutput = self._gradOutput or gradOutput.new()
self._gradOutput:resizeAs(gradOutput):copy(gradOutput)
gradOutput = self._gradOutput
end
self:createIODescriptors(input)
errcheck('cudnnSoftmaxBackward',
cudnn.getHandle(),
self.algorithm, self.mode,
one:data(),
self.oDesc[0], self.output:data(),
self.oDesc[0], gradOutput:data(),
zero:data(),
self.iDesc[0], self.gradInput:data());
return self.gradInput
end
function SpatialSoftMax:write(f)
self.iDesc = nil
self.oDesc = nil
local var = {}
for k,v in pairs(self) do
var[k] = v
end
f:writeObject(var)
end
|
Natalias contiguity fix
|
Natalias contiguity fix
|
Lua
|
bsd-3-clause
|
phunghx/phnn.torch,phunghx/phnn.torch,phunghx/phnn.torch
|
28bee27748ab207a67f2cbe13ed3952aef7cf64f
|
src/api-umbrella/cli/health.lua
|
src/api-umbrella/cli/health.lua
|
local cjson = require "cjson"
local http = require("socket.http")
local read_config = require "api-umbrella.cli.read_config"
local unistd = require "posix.unistd"
local function health(options, config)
local status = "red"
local exit_code = 1
local url = "http://127.0.0.1:" .. config["http_port"] .. "/api-umbrella/v1/health"
if options["wait_for_status"] then
url = url .. "?wait_for_status=" .. options["wait_for_status"] .. "&wait_timeout=" .. options["wait_timeout"]
end
local body, response_code, headers = http.request(url)
if not body then
local err = response_code
return status, exit_code, err
elseif headers["content-type"] ~= "application/json" then
local err = "nginx error"
return status, exit_code, err
else
local data = cjson.decode(body)
if data["status"] then
status = data["status"]
if response_code == 200 and status ~= "red" then
exit_code = 0
end
end
end
return status, exit_code
end
return function(options)
local config = read_config()
-- Perform a health check using the API health endpoint.
--
-- By default, perform the health check and return the status immediately.
--
-- If the --wait-for-status option is given, then the CLI app will wait until
-- that status (or better) is met (or until timeout).
local status, exit_code, health_err, _
if not options["wait_for_status"] then
status, exit_code, _ = health(options, config)
else
-- Validate the wait_for_status param.
local wait_for_status = options["wait_for_status"]
if wait_for_status ~= "green" and wait_for_status ~= "yellow" and wait_for_status ~= "red" then
print("Error: invalid --wait-for-status argument (" .. (tostring(wait_for_status) or "") .. ")")
os.exit(1)
end
-- Validate the wait_timeout param (defaults to 50 seconds).
local wait_timeout = tonumber(options["wait_timeout"] or 50)
if not wait_timeout then
print("Error: invalid --wait-timeout argument (" .. (tostring(wait_timeout) or "") .. ")")
os.exit(1)
end
-- Most of the wait-for-status functionality is implemented within the API
-- endpoint (will will wait until the expected status is achieved).
-- However, we will also loop in the CLI app until this status is achieved
-- to handle connection errors if nginx hasn't yet bound to the expected
-- port.
local timeout_at = os.time() + wait_timeout
while true do
status, exit_code, health_err = health(options, config)
-- If a low-level connection error wasn't returned, then we assume the
-- API endpoint was hit and it already waited the proper amount of time,
-- so we should immediately return whatever status the API returned.
if not health_err then
break
end
-- Bail if we've exceeded the timeout waiting.
if os.time() > timeout_at then
break
end
unistd.sleep(1)
end
end
print(status or "red")
os.exit(exit_code or 1)
end
|
local cjson = require "cjson"
local http = require("socket.http")
local read_config = require "api-umbrella.cli.read_config"
local unistd = require "posix.unistd"
local function health(options, config)
local status = "red"
local exit_code = 1
local url = "http://127.0.0.1:" .. config["http_port"] .. "/api-umbrella/v1/health"
if options["wait_for_status"] then
url = url .. "?wait_for_status=" .. options["wait_for_status"] .. "&wait_timeout=" .. options["wait_timeout"]
end
local body, response_code, headers = http.request(url)
if not body then
local err = response_code
return status, exit_code, err
elseif headers["content-type"] ~= "application/json" then
local err = "nginx error"
return status, exit_code, err
else
local data = cjson.decode(body)
if data["status"] then
status = data["status"]
if response_code == 200 and status ~= "red" then
exit_code = 0
end
else
local err = "nginx error"
return status, exit_code, err
end
end
return status, exit_code
end
return function(options)
local config = read_config()
-- Perform a health check using the API health endpoint.
--
-- By default, perform the health check and return the status immediately.
--
-- If the --wait-for-status option is given, then the CLI app will wait until
-- that status (or better) is met (or until timeout).
local status, exit_code, health_err, _
if not options["wait_for_status"] then
status, exit_code, _ = health(options, config)
else
-- Validate the wait_for_status param.
local wait_for_status = options["wait_for_status"]
if wait_for_status ~= "green" and wait_for_status ~= "yellow" and wait_for_status ~= "red" then
print("Error: invalid --wait-for-status argument (" .. (tostring(wait_for_status) or "") .. ")")
os.exit(1)
end
-- Validate the wait_timeout param (defaults to 50 seconds).
local wait_timeout = tonumber(options["wait_timeout"] or 50)
if not wait_timeout then
print("Error: invalid --wait-timeout argument (" .. (tostring(wait_timeout) or "") .. ")")
os.exit(1)
end
-- Most of the wait-for-status functionality is implemented within the API
-- endpoint (will will wait until the expected status is achieved).
-- However, we will also loop in the CLI app until this status is achieved
-- to handle connection errors if nginx hasn't yet bound to the expected
-- port.
local timeout_at = os.time() + wait_timeout
while true do
status, exit_code, health_err = health(options, config)
-- If a low-level connection error wasn't returned, then we assume the
-- API endpoint was hit and it already waited the proper amount of time,
-- so we should immediately return whatever status the API returned.
if not health_err then
break
end
-- Bail if we've exceeded the timeout waiting.
if os.time() > timeout_at then
break
end
unistd.sleep(1)
end
end
print(status or "red")
os.exit(exit_code or 1)
end
|
Fix waiting on health check for unexpected JSON responses.
|
Fix waiting on health check for unexpected JSON responses.
This fixes the case that while waiting for things to startup, the app
returns a 404 JSON response. This can happen if mongodb takes longer
than expected to startup. With this fix, the heath check cli will
continue to loop and wait for a valid health status response.
|
Lua
|
mit
|
NREL/api-umbrella,apinf/api-umbrella,apinf/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,NREL/api-umbrella
|
28d73a9e4fe5297453d0058c381474659860624c
|
lua/wire/stools/value.lua
|
lua/wire/stools/value.lua
|
WireToolSetup.setCategory( "I/O" )
WireToolSetup.open( "value", "Constant Value", "gmod_wire_value", nil, "Constant Values" )
if CLIENT then
language.Add("Tool.wire_value.name", "Value Tool (Wire)")
language.Add("Tool.wire_value.desc", "Spawns a constant value for use with the wire system.")
language.Add("Tool.wire_value.0", "Primary: Create/Update Value, Secondary: Copy Settings")
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax( 20 )
if SERVER then
local playerValues = {}
util.AddNetworkString( "wire_value_values" )
net.Receive( "wire_value_values", function( length, ply )
playerValues[ply] = net.ReadTable()
end)
function TOOL:GetConVars()
return playerValues[self:GetOwner()] or {}
end
function TOOL:MakeEnt( ply, model, Ang, trace )
return MakeWireValue( ply, trace.HitPos, Ang, model, self:GetConVars() )
end
function TOOL:RightClick(trace)
if not IsValid(trace.Entity) or trace.Entity:GetClass() != "gmod_wire_value" then return false end
playerValues[self:GetOwner()] = trace.Entity.value
net.Start("wire_value_values")
net.WriteTable(trace.Entity.value)
net.Send(self:GetOwner())
end
end
TOOL.ClientConVar = {
model = "models/kobilica/value.mdl",
modelsize = "",
}
if CLIENT then
function TOOL:RightClick(trace)
return IsValid(trace.Entity) and trace.Entity:GetClass() == "gmod_wire_value"
end
local ValuePanels = {}
local selectedValues = {}
local function SendUpdate()
net.Start("wire_value_values")
net.WriteTable(selectedValues)
net.SendToServer()
end
// Supported Data Types.
local DataTypes = {
["NORMAL"] = "Number",
["STRING"] = "String",
["VECTOR"] = "Vector",
["ANGLE"] = "Angle"
}
local function AddValue( panel, id )
local w,_ = panel:GetSize()
selectedValues[id] = {
DataType = "Number",
Value = 0
}
local control = vgui.Create( "DCollapsibleCategory", panel )
control:SetSize( w, 100 )
control:SetText( "Value: " .. id )
control:SetLabel( "Value " .. id )
control:Dock(TOP)
local typeSelection = vgui.Create( "DComboBox", control )
control.typeSelection = typeSelection
local _, controlW = control:GetSize()
typeSelection:SetText( DataTypes["NORMAL"] )
typeSelection:SetSize( controlW , 25 )
typeSelection:DockMargin( 5,2,5,2 )
typeSelection:Dock( TOP )
typeSelection.OnSelect = function( panel, index, value )
selectedValues[id].DataType = value
SendUpdate()
end
for k,v in pairs( DataTypes ) do
typeSelection:AddChoice(v)
end
local valueEntry = vgui.Create( "DTextEntry",control )
control.valueEntry = valueEntry
valueEntry:Dock( TOP )
valueEntry:DockMargin( 5,2,5,2 )
valueEntry:DockPadding(5,5,5,5)
valueEntry:SetValue(0)
local oldLoseFocus = valueEntry.OnLoseFocus
valueEntry.OnLoseFocus = function( panel )
selectedValues[id].Value = panel:GetValue() or 0
SendUpdate()
oldLoseFocus(panel) -- Otherwise we can't close the spawnmenu!
end
return control
end
local ValuePanels = {}
local valueSlider
net.Receive( "wire_value_values", function( length )
if not IsValid(valueSlider) then return end -- How'd they right click without opening the cpanel?
local oldSendUpdate = SendUpdate
SendUpdate = function() end -- Lets not bother the server with 20 updates it already knows about
local tab = net.ReadTable()
//valueSlider:OnValueChanged(#tab)
valueSlider:SetValue(#tab)
for id,v in pairs(tab) do
ValuePanels[id].typeSelection:SetText( v.DataType )
ValuePanels[id].typeSelection:OnSelect( _, v.DataType )
ValuePanels[id].valueEntry:SetValue(v.Value)
end
SendUpdate = oldSendUpdate
end)
function TOOL.BuildCPanel( panel )
WireToolHelpers.MakeModelSizer(panel, "wire_value_modelsize")
ModelPlug_AddToCPanel(panel, "Value", "wire_value", true)
local reset = panel:Button("Reset Values")
local w,_ = panel:GetSize()
valueSlider = vgui.Create( "DNumSlider", panel )
valueSlider:SetSize(w, 25 )
valueSlider:SetText( "Amount:" )
valueSlider:SetDark( true )
valueSlider:SetMin(1)
valueSlider:SetMax(20)
valueSlider:SetDecimals( 0 )
valueSlider:DockMargin( 5, 5, 5, 5 )
valueSlider:Dock( TOP )
local LastValueAmount = 0
reset.DoClick = function( panel )
valueSlider:SetValue(1)
for k,v in pairs(ValuePanels) do
v:Remove()
v = nil
end
for k,v in pairs( selectedValues ) do
v = nil
end
LastValueAmount = 0
valueSlider.OnValueChanged( panel, 1 )
end
valueSlider.OnValueChanged = function( valueSlider, value )
local value = math.ceil(tonumber(value)) -- Silly Garry, giving me strings.
if value != LastValueAmount then
if value > LastValueAmount then
for i = LastValueAmount + 1, value, 1 do
ValuePanels[i] = AddValue( panel, i )
local _,h = panel:GetSize()
panel:SetSize(w, h+120 )
end
elseif value < LastValueAmount then
for i = value + 1, LastValueAmount, 1 do
selectedValues[i] = nil
if IsValid(ValuePanels[i]) then ValuePanels[i]:Remove() end
ValuePanels[i] = nil
local _,h = panel:GetSize()
panel:SetSize(w, h-120 )
end
else
Msg("Error Incorrect value exists?!?!.\n")
end
LastValueAmount = value
SendUpdate()
end
end
valueSlider:SetValue( 1 )
end
end
|
WireToolSetup.setCategory( "I/O" )
WireToolSetup.open( "value", "Constant Value", "gmod_wire_value", nil, "Constant Values" )
if CLIENT then
language.Add("Tool.wire_value.name", "Value Tool (Wire)")
language.Add("Tool.wire_value.desc", "Spawns a constant value for use with the wire system.")
language.Add("Tool.wire_value.0", "Primary: Create/Update Value, Secondary: Copy Settings")
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax( 20 )
if SERVER then
local playerValues = {}
util.AddNetworkString( "wire_value_values" )
net.Receive( "wire_value_values", function( length, ply )
playerValues[ply] = net.ReadTable()
end)
function TOOL:GetConVars()
return playerValues[self:GetOwner()] or {}
end
function TOOL:MakeEnt( ply, model, Ang, trace )
return MakeWireValue( ply, trace.HitPos, Ang, model, self:GetConVars() )
end
function TOOL:RightClick(trace)
if not IsValid(trace.Entity) or trace.Entity:GetClass() != "gmod_wire_value" then return false end
playerValues[self:GetOwner()] = trace.Entity.value
net.Start("wire_value_values")
net.WriteTable(trace.Entity.value)
net.Send(self:GetOwner())
end
end
TOOL.ClientConVar = {
model = "models/kobilica/value.mdl",
modelsize = "",
}
if CLIENT then
function TOOL:RightClick(trace)
return IsValid(trace.Entity) and trace.Entity:GetClass() == "gmod_wire_value"
end
local ValuePanels = {}
local selectedValues = {}
local function SendUpdate()
net.Start("wire_value_values")
net.WriteTable(selectedValues)
net.SendToServer()
end
// Supported Data Types.
local DataTypes = {
["NORMAL"] = "Number",
["STRING"] = "String",
["VECTOR"] = "Vector",
["ANGLE"] = "Angle"
}
local function AddValue( panel, id )
local w,_ = panel:GetSize()
selectedValues[id] = {
DataType = "Number",
Value = 0
}
local control = vgui.Create( "DCollapsibleCategory", panel )
control:SetSize( w, 100 )
control:SetText( "Value: " .. id )
control:SetLabel( "Value " .. id )
control:Dock(TOP)
local typeSelection = vgui.Create( "DComboBox", control )
control.typeSelection = typeSelection
local _, controlW = control:GetSize()
typeSelection:SetText( DataTypes["NORMAL"] )
typeSelection:SetSize( controlW , 25 )
typeSelection:DockMargin( 5,2,5,2 )
typeSelection:Dock( TOP )
typeSelection.OnSelect = function( panel, index, value )
selectedValues[id].DataType = value
SendUpdate()
end
for k,v in pairs( DataTypes ) do
typeSelection:AddChoice(v)
end
local valueEntry = vgui.Create( "DTextEntry",control )
control.valueEntry = valueEntry
valueEntry:Dock( TOP )
valueEntry:DockMargin( 5,2,5,2 )
valueEntry:DockPadding(5,5,5,5)
valueEntry:SetValue(0)
local oldLoseFocus = valueEntry.OnLoseFocus
valueEntry.OnLoseFocus = function( panel )
selectedValues[id].Value = panel:GetValue() or 0
SendUpdate()
oldLoseFocus(panel) -- Otherwise we can't close the spawnmenu!
end
return control
end
local ValuePanels = {}
local valueSlider
net.Receive( "wire_value_values", function( length )
if not IsValid(valueSlider) then return end -- How'd they right click without opening the cpanel?
local oldSendUpdate = SendUpdate
SendUpdate = function() end -- Lets not bother the server with 20 updates it already knows about
local tab = net.ReadTable()
//valueSlider:OnValueChanged(#tab)
valueSlider:SetValue(#tab)
for id,v in pairs(tab) do
ValuePanels[id].typeSelection:SetText( v.DataType )
ValuePanels[id].typeSelection:OnSelect( _, v.DataType )
ValuePanels[id].valueEntry:SetValue(v.Value)
selectedValues[id].Value = v.Value
end
SendUpdate = oldSendUpdate
end)
function TOOL.BuildCPanel( panel )
WireToolHelpers.MakeModelSizer(panel, "wire_value_modelsize")
ModelPlug_AddToCPanel(panel, "Value", "wire_value", true)
local reset = panel:Button("Reset Values")
local w,_ = panel:GetSize()
valueSlider = vgui.Create( "DNumSlider", panel )
valueSlider:SetSize(w, 25 )
valueSlider:SetText( "Amount:" )
valueSlider:SetDark( true )
valueSlider:SetMin(1)
valueSlider:SetMax(20)
valueSlider:SetDecimals( 0 )
valueSlider:DockMargin( 5, 5, 5, 5 )
valueSlider:Dock( TOP )
local LastValueAmount = 0
reset.DoClick = function( panel )
valueSlider:SetValue(1)
for k,v in pairs(ValuePanels) do
v:Remove()
v = nil
end
for k,v in pairs( selectedValues ) do
v = nil
end
LastValueAmount = 0
valueSlider.OnValueChanged( panel, 1 )
end
valueSlider.OnValueChanged = function( valueSlider, value )
local value = math.ceil(tonumber(value)) -- Silly Garry, giving me strings.
if value != LastValueAmount then
if value > LastValueAmount then
for i = LastValueAmount + 1, value, 1 do
ValuePanels[i] = AddValue( panel, i )
local _,h = panel:GetSize()
panel:SetSize(w, h+120 )
end
elseif value < LastValueAmount then
for i = value + 1, LastValueAmount, 1 do
selectedValues[i] = nil
if IsValid(ValuePanels[i]) then ValuePanels[i]:Remove() end
ValuePanels[i] = nil
local _,h = panel:GetSize()
panel:SetSize(w, h-120 )
end
else
Msg("Error Incorrect value exists?!?!.\n")
end
LastValueAmount = value
SendUpdate()
end
end
valueSlider:SetValue( 1 )
end
end
|
Constant Value: Fixed rightclick not sending values to server
|
Constant Value: Fixed rightclick not sending values to server
|
Lua
|
apache-2.0
|
plinkopenguin/wiremod,thegrb93/wire,wiremod/wire,CaptainPRICE/wire,notcake/wire,mms92/wire,dvdvideo1234/wire,immibis/wiremod,garrysmodlua/wire,NezzKryptic/Wire,rafradek/wire,mitterdoo/wire,Python1320/wire,sammyt291/wire,Grocel/wire,bigdogmat/wire
|
0e08c5fc1513bb036dde2bd1362ff6de521b8c78
|
share/media/gaskrank.lua
|
share/media/gaskrank.lua
|
-- libquvi-scripts
-- Copyright (C) 2010-2012 Toni Gundogdu <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local Gaskrank = {} -- Utility functions unique to this script
-- Identify the media script.
function ident(qargs)
local A = require 'quvi/accepts'
local C = require 'quvi/const'
local r = {
accepts = A.accepts(qargs.input_url, {"gaskrank%.tv"}, {"/tv/"}),
categories = C.qmspc_http
}
return r
end
-- Parse media properties.
function parse(qargs)
local p = quvi.fetch(qargs.input_url)
qargs.thumb_url = p:match('"og:image" content="(.-)"') or ''
qargs.title = p:match('"og:title" content="(.-)"') or ''
qargs.id = qargs.input_url:match("%-(%d+)%.h")
or error("no match: media ID")
qargs.streams = Gaskrank.iter_streams(p)
return qargs
end
--
-- Utility functions.
--
function Gaskrank.iter_streams(p)
local u = p:match("(http://movies.-%.flv)")
or error("no match: media stream URL")
local S = require 'quvi/stream'
return {S.stream_new(u)}
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
-- libquvi-scripts
-- Copyright (C) 2010-2012 Toni Gundogdu <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301 USA
--
local Gaskrank = {} -- Utility functions unique to this script
-- Identify the media script.
function ident(qargs)
local A = require 'quvi/accepts'
local C = require 'quvi/const'
local r = {
accepts = A.accepts(qargs.input_url, {"gaskrank%.tv"}, {"/tv/"}),
categories = C.qmspc_http
}
return r
end
-- Parse media properties.
function parse(qargs)
local p = quvi.fetch(qargs.input_url)
qargs.thumb_url = p:match('"og:image" content="(.-)"') or ''
qargs.title = p:match('"og:title" content="(.-)"') or ''
qargs.streams = Gaskrank.iter_streams(p)
qargs.id = qargs.streams[1].url:match("/%d+/(%d+)%.%w+") or ''
return qargs
end
--
-- Utility functions.
--
function Gaskrank.iter_streams(p)
local u = p:match("(http://movies.-%.flv)")
or error("no match: media stream URL")
local S = require 'quvi/stream'
return {S.stream_new(u)}
end
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
FIX: media/gaskrank.lua: Parse media ID from stream URL
|
FIX: media/gaskrank.lua: Parse media ID from stream URL
|
Lua
|
agpl-3.0
|
legatvs/libquvi-scripts,alech/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts
|
e06f3cd6e2fb965a30b8dc0db3814f3e60686f35
|
usr/product/sigma-firmware/pkg.lua
|
usr/product/sigma-firmware/pkg.lua
|
-- Sigma rules
local R = require 'rules'
require 'chicken'
-- base
R:add { 'ast-files' }
R:add { 'cmake-modules' }
R:add { 'linux' }
R:add { 'xsdk' }
R:add { 'ucode',
{ 'install' }
}
-- host
R:add { 'utils', 'host' }
R:add { 'karaoke-player', 'host',
{ 'configure',
requires = {
'chicken-eggs',
'ffmpeg',
'libuv',
},
{ 'astindex', 'unpack' },
}
}
R:add { 'astindex',
{ 'unpack', { 'karaoke-player', 'unpack' } }
}
-- kernel
local kernel_rule_template = {
config = 'target',
{ 'configure', { 'kernel', 'compile', 'target' } }
}
local function kernel_rule(r)
r.template = kernel_rule_template
R:add(r)
end
R:add { 'kernel', 'target',
{ 'configure',
{ 'linux', 'unpack' },
{ 'rootfs', 'compile' },
{ 'ezboot', 'compile', 'target' },
},
{ 'install' },
{ 'image', { 'rootfs', 'install' } }
}
kernel_rule { 'loop-aes' }
kernel_rule { 'ralink' }
-- rootfs
local rootfs_rule_template = {
config = 'target',
{ 'configure', { 'rootfs', 'compile', 'target' } }
}
local function rootfs_rule(r)
r.template = rootfs_rule_template
R:add(r)
end
R:add { 'rootfs', 'target',
template = rootfs_rule_template,
skip_template = true,
{ 'configure',
{ 'ast-files', 'unpack' },
{ 'xsdk', 'unpack' },
{ 'toolchain', 'install', 'target' },
},
{ 'compile' },
{ 'install',
requires = {
'busybox',
'gnupg',
'ntpclient',
'util-linux',
'utils',
},
{ 'kernel', 'install', 'target' },
{ 'mrua', 'modules', 'target' },
{ 'loop-aes', 'install', 'target' },
{ 'ralink', 'install', 'target' },
},
{ 'strip' }
}
R:add { 'mrua', 'target',
{ 'compile', { 'kernel', 'compile', 'target' } },
{ 'modules' },
{ 'install' },
}
rootfs_rule { 'ezboot' }
rootfs_rule { 'busybox',
install = {
root = '$jagen_sdk_initfs_dir',
prefix = ''
},
{ 'patch', { 'ast-files', 'unpack' } }
}
rootfs_rule { 'utils',
{ 'configure',
requires = { 'gpgme' },
{ 'dbus', 'install', 'target' }
}
}
-- firmware
local firmware_rule_template = {
config = 'target',
install = {
prefix = '/firmware'
},
{ 'install', { 'firmware', 'unpack' } }
}
local function firmware_rule(r)
r.template = firmware_rule_template
R:add(r)
end
R:add { 'firmware',
template = firmware_rule_template,
skip_template = true,
{ 'compile',
{ 'mrua', 'compile', 'target' }
},
{ 'install',
requires = {
'karaoke-player',
'rsync',
'wpa_supplicant',
},
{ 'kernel', 'image', 'target' },
{ 'mrua', 'install', 'target' },
{ 'ucode', 'install' },
{ 'ezboot', 'install', 'target' },
},
{ 'strip' }
}
firmware_rule { 'karaoke-player',
{ 'configure',
requires = {
'chicken-eggs',
'connman',
'dbus',
'ffmpeg',
'freetype',
'libass',
'libpng',
'libuv',
'soundtouch',
},
{ 'astindex', 'unpack' },
{ 'mrua', 'compile', 'target' },
{ 'chicken-eggs', 'install', 'host' },
}
}
|
-- Sigma rules
local R = require 'rules'
require 'chicken'
-- base
R:add { 'ast-files' }
R:add { 'cmake-modules' }
R:add { 'linux' }
R:add { 'xsdk' }
R:add { 'ucode',
{ 'install' }
}
-- host
R:add { 'utils', 'host' }
R:add { 'karaoke-player', 'host',
{ 'configure',
requires = {
'chicken-eggs',
'ffmpeg',
'libuv',
},
{ 'astindex', 'unpack' },
}
}
R:add { 'astindex',
{ 'unpack', { 'karaoke-player', 'unpack' } }
}
-- kernel
local kernel_rule_template = {
config = 'target',
{ 'configure', { 'kernel', 'compile', 'target' } }
}
local function kernel_rule(r)
r.template = kernel_rule_template
R:add(r)
end
R:add { 'kernel', 'target',
{ 'configure',
{ 'linux', 'unpack' },
{ 'rootfs', 'compile', 'target' },
{ 'ezboot', 'compile', 'target' },
},
{ 'install' },
{ 'image',
{ 'rootfs', 'install', 'target' }
}
}
kernel_rule { 'loop-aes' }
kernel_rule { 'ralink' }
-- rootfs
local rootfs_rule_template = {
config = 'target',
{ 'configure', { 'rootfs', 'compile', 'target' } }
}
local function rootfs_rule(r)
r.template = rootfs_rule_template
R:add(r)
end
R:add { 'rootfs', 'target',
template = rootfs_rule_template,
skip_template = true,
{ 'configure',
{ 'ast-files', 'unpack' },
{ 'xsdk', 'unpack' },
{ 'toolchain', 'install', 'target' },
},
{ 'compile' },
{ 'install',
requires = {
'busybox',
'gnupg',
'ntpclient',
'util-linux',
'utils',
},
{ 'kernel', 'install', 'target' },
{ 'mrua', 'modules', 'target' },
{ 'loop-aes', 'install', 'target' },
{ 'ralink', 'install', 'target' },
},
{ 'strip' }
}
R:add { 'mrua', 'target',
{ 'compile', { 'kernel', 'compile', 'target' } },
{ 'modules' },
{ 'install' },
}
rootfs_rule { 'ezboot' }
rootfs_rule { 'busybox',
install = {
root = '$jagen_sdk_initfs_dir',
prefix = ''
},
{ 'patch', { 'ast-files', 'unpack' } }
}
rootfs_rule { 'utils',
{ 'configure',
requires = { 'gpgme' },
{ 'dbus', 'install', 'target' }
}
}
-- firmware
local firmware_rule_template = {
config = 'target',
install = {
prefix = '/firmware'
},
{ 'install', { 'firmware', 'unpack' } }
}
local function firmware_rule(r)
r.template = firmware_rule_template
R:add(r)
end
R:add { 'firmware',
template = firmware_rule_template,
skip_template = true,
{ 'compile',
{ 'mrua', 'compile', 'target' }
},
{ 'install',
requires = {
'karaoke-player',
'rsync',
'wpa_supplicant',
},
{ 'kernel', 'image', 'target' },
{ 'mrua', 'install', 'target' },
{ 'ucode', 'install' },
{ 'ezboot', 'install', 'target' },
},
{ 'strip' }
}
firmware_rule { 'karaoke-player',
{ 'configure',
requires = {
'chicken-eggs',
'connman',
'dbus',
'ffmpeg',
'freetype',
'libass',
'libpng',
'libuv',
'soundtouch',
},
{ 'astindex', 'unpack' },
{ 'mrua', 'compile', 'target' },
{ 'chicken-eggs', 'install', 'host' },
}
}
|
Fix sigma rules
|
Fix sigma rules
|
Lua
|
mit
|
bazurbat/jagen
|
821000f4051465fdd529232f479782073fa83297
|
src/logfactory/LogCreator.lua
|
src/logfactory/LogCreator.lua
|
local LogCreator = {};
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local GIT_COMMAND = 'git log --reverse --numstat --pretty=format:"info: %an|%ae|%ct" --name-status --no-merges';
local LOG_FOLDER = 'logs/';
local LOG_FILE = '/log.txt';
local INFO_FILE = '/info.lua';
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
---
-- Creates a git log if git is available and no log has been
-- created in the target folder yet.
-- @param projectname
-- @param path
--
function LogCreator.createGitLog(projectname, path, force)
if not force and love.filesystem.isFile(LOG_FOLDER .. projectname .. LOG_FILE) then
print('Git log for ' .. projectname .. ' already exists!');
else
print('Writing log for ' .. projectname .. '.');
love.filesystem.createDirectory(LOG_FOLDER .. projectname);
local cmd = 'cd ' .. path .. '&&' .. GIT_COMMAND;
local handle = io.popen(cmd);
local fileContent = '';
for line in handle:lines() do
fileContent = fileContent .. line .. '\r\n';
end
handle:close();
love.filesystem.write(LOG_FOLDER .. projectname .. LOG_FILE, fileContent);
print('Done!');
end
end
function LogCreator.createInfoFile(projectname, path, force)
if not force and love.filesystem.isFile(LOG_FOLDER .. projectname .. INFO_FILE) then
print('Info file for ' .. projectname .. ' already exists!');
else
local fileContent = '';
fileContent = fileContent .. 'return {\r\n';
-- Project name.
fileContent = fileContent .. ' name = "' .. projectname .. '",\r\n';
-- First commit.
local handle = io.popen('cd ' .. path .. '&&git log --pretty=format:%ct|tail -1');
fileContent = fileContent .. ' firstCommit = ' .. handle:read('*a'):gsub('[%s]+', '') .. ',\r\n';
handle:close();
-- Latest commit.
local handle = io.popen('cd ' .. path .. '&&git log --pretty=format:%ct|head -1');
fileContent = fileContent .. ' latestCommit = ' .. handle:read('*a'):gsub('[%s]+', '') .. ',\r\n';
handle:close();
-- Number of commits.
local handle = io.popen('cd ' .. path .. '&&git rev-list HEAD --count');
fileContent = fileContent .. ' totalCommits = ' .. handle:read('*a'):gsub('[%s]+', '') .. '\r\n';
handle:close();
fileContent = fileContent .. '};\r\n';
love.filesystem.write(LOG_FOLDER .. projectname .. INFO_FILE, fileContent);
end
end
-- ------------------------------------------------
-- Getters
-- ------------------------------------------------
---
-- Checks if git is available on the system.
--
function LogCreator.isGitAvailable()
return os.execute('git version') == 0;
end
return LogCreator;
|
local LogCreator = {};
-- ------------------------------------------------
-- Constants
-- ------------------------------------------------
local GIT_COMMAND = 'git log --reverse --numstat --pretty=format:"info: %an|%ae|%ct" --name-status --no-merges';
local LOG_FOLDER = 'logs/';
local LOG_FILE = '/log.txt';
local INFO_FILE = '/info.lua';
-- ------------------------------------------------
-- Public Functions
-- ------------------------------------------------
---
-- Creates a git log if git is available and no log has been
-- created in the target folder yet.
-- @param projectname
-- @param path
--
function LogCreator.createGitLog(projectname, path, force)
if not force and love.filesystem.isFile(LOG_FOLDER .. projectname .. LOG_FILE) then
io.write('Git log for ' .. projectname .. ' already exists!\r\n');
else
io.write('Writing log for ' .. projectname .. '.\r\n');
love.filesystem.createDirectory(LOG_FOLDER .. projectname);
local cmd = 'cd ' .. path .. '&&' .. GIT_COMMAND;
local handle = io.popen(cmd);
local fileContent = '';
for line in handle:lines() do
fileContent = fileContent .. line .. '\r\n';
end
handle:close();
love.filesystem.write(LOG_FOLDER .. projectname .. LOG_FILE, fileContent);
io.write('Done!\r\n');
end
end
function LogCreator.createInfoFile(projectname, path, force)
if not force and love.filesystem.isFile(LOG_FOLDER .. projectname .. INFO_FILE) then
io.write('Info file for ' .. projectname .. ' already exists!\r\n');
else
local fileContent = '';
fileContent = fileContent .. 'return {\r\n';
-- Project name.
fileContent = fileContent .. ' name = "' .. projectname .. '",\r\n';
-- First commit.
local handle = io.popen('cd ' .. path .. '&&git log --pretty=format:%ct|tail -1');
fileContent = fileContent .. ' firstCommit = ' .. handle:read('*a'):gsub('[%s]+', '') .. ',\r\n';
handle:close();
-- Latest commit.
local handle = io.popen('cd ' .. path .. '&&git log --pretty=format:%ct|head -1');
fileContent = fileContent .. ' latestCommit = ' .. handle:read('*a'):gsub('[%s]+', '') .. ',\r\n';
handle:close();
-- Number of commits.
local handle = io.popen('cd ' .. path .. '&&git rev-list HEAD --count');
fileContent = fileContent .. ' totalCommits = ' .. handle:read('*a'):gsub('[%s]+', '') .. '\r\n';
handle:close();
fileContent = fileContent .. '};\r\n';
love.filesystem.write(LOG_FOLDER .. projectname .. INFO_FILE, fileContent);
end
end
-- ------------------------------------------------
-- Getters
-- ------------------------------------------------
---
-- Checks if git is available on the system.
--
function LogCreator.isGitAvailable()
return os.execute('git version') == 0;
end
return LogCreator;
|
Fix #24 - Use io.write instead of print to get proper console output
|
Fix #24 - Use io.write instead of print to get proper console output
|
Lua
|
mit
|
rm-code/logivi
|
bda365dd8ee7dc5f7e350516f7ed228387efcfe0
|
scripts/src/h.lua
|
scripts/src/h.lua
|
require "lmkbuild"
local assert = assert
local append = lmkbuild.append_local
local cp = lmkbuild.cp
local file_newer = lmkbuild.file_newer
local ipairs = ipairs
local is_valid = lmkbuild.is_valid
local mkdir = lmkbuild.mkdir
local print = print
local resolve = lmkbuild.resolve
local rm = lmkbuild.rm
local split = lmkbuild.split
local sys = lmkbuild.system ()
module (...)
function main (files)
if sys == "iphone" then
mkdir ("$(lmk.includeDir)dmz/")
append ("localIncludes", "$(lmk.includePathFlag)$(lmk.includeDir)dmz/")
else
mkdir ("$(lmk.includeDir)$(name)")
append ("localIncludes", "$(lmk.includePathFlag)$(lmk.includeDir)$(name)/")
end
for index, item in ipairs (files) do
local file = nil
local item = resolve (item)
local p, f, e = split (item)
if sys == "iphone" then file = "$(lmk.includeDir)dmz/" .. f .. "." .. e
else
file = "$(lmk.includeDir)$(name)/" .. f
if e then file = file .. "." .. e end
end
if file_newer (item, file) then
print ("Exporting: " .. item)
assert (
cp (item, file),
"Failed copying file: " .. item .. " to " .. resolve (file))
end
end
end
function test (files)
main (files)
end
function clean (files)
for index, item in ipairs (files) do
local file = nil
local p, f, e = split (item)
if sys == "iphone" then file = resolve ("$(lmk.includeDir)dmz/" .. f .. "." .. e)
else
if e then file = resolve ("$(lmk.includeDir)$(name)/" .. f .. "." .. e)
else file = resolve ("$(lmk.includeDir)$(name)/" .. f)
end
end
if is_valid (file) then rm (file) end
end
end
function clobber (files)
clean (files)
end
|
require "lmkbuild"
local assert = assert
local append = lmkbuild.append_local
local cp = lmkbuild.cp
local file_newer = lmkbuild.file_newer
local ipairs = ipairs
local is_valid = lmkbuild.is_valid
local mkdir = lmkbuild.mkdir
local print = print
local resolve = lmkbuild.resolve
local rm = lmkbuild.rm
local split = lmkbuild.split
local sys = lmkbuild.system ()
module (...)
function main (files)
if sys == "iphone" then
mkdir ("$(lmk.includeDir)dmz/")
append ("localIncludes", "$(lmk.includePathFlag)$(lmk.includeDir)dmz/")
else
mkdir ("$(lmk.includeDir)$(name)")
append ("localIncludes", "$(lmk.includePathFlag)$(lmk.includeDir)$(name)/")
end
for index, item in ipairs (files) do
local file = nil
local item = resolve (item)
local p, f, e = split (item)
if sys == "iphone" then file = "$(lmk.includeDir)dmz/" .. f .. "." .. e
else
file = "$(lmk.includeDir)$(name)/" .. f
if e then file = file .. "." .. e end
end
if file_newer (item, file) then
print ("Exporting: " .. item)
assert (
cp (item, file),
"Failed copying file: " .. item .. " to " .. resolve (file))
end
end
end
function test (files)
main (files)
end
function clean (files)
for index, item in ipairs (files) do
local file = nil
local p, f, e = split (item)
if sys == "iphone" then file = resolve ("$(lmk.includeDir)dmz/" .. f .. "." .. e)
else
file = "$(lmk.includeDir)$(name)/" .. f
if e then file = file .. "." .. e end
end
if is_valid (file) then rm (file) end
end
end
function clobber (files)
clean (files)
end
|
small fix to lmk
|
small fix to lmk
|
Lua
|
mit
|
shillcock/lmk,dmzgroup/lmk
|
aa49cf041c3765beb14a05009b9f48cdec43b5fd
|
turbovisor.lua
|
turbovisor.lua
|
--- Turbo.lua Turbovisor, auto-reload of application on file changes.
--
-- Copyright 2013 John Abrahamsen, Deyuan Deng
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local ffi = require "ffi"
local bit = require "bit"
local turbo = require "turbo"
local fs = require "turbo.fs"
--- Parsing arguments for turbovisor
-- @param arg All command line input. Note arg[0] is 'turbovisor', arg[1] is
-- application name; so user-defined argument starts from arg[2]
-- @return a table containing option/value pair, options including:
-- 'watch': set of files or directories to watch
-- 'ignore': set of files or directories that turbovisor shouldn't watch
local function get_param(arg)
local arg_opt
local arg_tbl = {}
for i = 2, #arg, 1 do
if arg[i] == '--watch' or arg[i] == '-w' then
arg_tbl.watch = {}
arg_opt = 'watch'
elseif arg[i] == '--ignore' or arg[i] == '-i' then
arg_tbl.ignore = {}
arg_opt = 'ignore'
else
if string.sub(arg[i], 1, 2) == "./" then
arg[i] = string.sub(arg[i], 3) -- pass './'
end
local files = fs.glob(arg[i])
-- insert glob expanded result into table
if files then
for _,v in ipairs(files) do
table.insert(arg_tbl[arg_opt], v)
end
end
end
end
-- Deal with default parameters
if arg_tbl.watch == nil then arg_tbl.watch = {'.'} end
return arg_tbl;
end
--- Kill all descendants for a given pid
local function kill_tree(pid)
local status = ffi.new("int[1]")
local cpids = io.popen('pgrep -P ' .. pid)
for cpid in cpids:lines() do
kill_tree(cpid)
ffi.C.kill(tonumber(cpid), 9)
ffi.C.waitpid(tonumber(cpid), status, 0)
assert(status[0] == 9 or bit.band(status[0], 0x7f) == 0,
"Child process " .. cpid .. " not killed.")
end
cpids:close()
end
--- The turbovisor class is a supervisor for detecting file changes
-- and restart supervised application.
local turbovisor = class("turbovisor", turbo.ioloop.IOLoop)
--- Start supervising.
function turbovisor:supervise()
-- Get command line parameters
self.arg_tbl = get_param(arg)
-- Create a new inotify
self.i_fd = turbo.inotify:new()
-- Create a buffer for reading event in callback handler
self.buf = ffi.gc(ffi.C.malloc(turbo.fs.PATH_MAX), ffi.C.free)
-- Initialize ioloop, add inotify handler
self:initialize()
self:add_handler(self.i_fd, turbo.ioloop.READ, self.restart, self)
-- Set watch on target file or directory
for i, target in pairs(self.arg_tbl.watch) do
if turbo.fs.is_dir(target) then
turbo.inotify:watch_all(target, self.arg_tbl.ignore)
else
turbo.inotify:watch_file(target)
end
end
-- Parameters for starting application
local para = ffi.new("const char *[?]", 3)
para[0] = "luajit"
para[1] = arg[1]
para[2] = nil
self.para = ffi.cast("char *const*", para)
-- Run application and supervisor
local cpid = ffi.C.fork()
if cpid == 0 then
turbo.inotify:close()
ffi.C.execvp("luajit", self.para)
error(ffi.string(ffi.C.strerror(ffi.errno())))
else
self:start()
end
end
--- Callback handler when files changed
-- For now, just restart the only one application
function turbovisor.restart(self, fd, events)
-- Read out event
ffi.C.read(fd, self.buf, turbo.fs.PATH_MAX);
self.buf = ffi.cast("struct inotify_event*", self.buf)
local full_path
if self.buf.len == 0 then -- 'len = 0' if we watch on file directly
full_path = turbo.inotify:get_watched_file(self.buf.wd)
else
local path = turbo.inotify:get_watched_file(self.buf.wd)
full_path = path .. '/' .. ffi.string(self.buf.name)
if path == '.' then full_path = ffi.string(self.buf.name) end
end
turbo.inotify:rewatch_if_ignored(self.buf, full_path)
-- Simply return if we need to ignore the file
if turbo.util.is_in(full_path, self.arg_tbl.ignore) then
return
end
turbo.log.notice("[turbovisor.lua] File '" .. full_path ..
"' changed, application restarted!")
-- Restart application
kill_tree(ffi.C.getpid())
local cpid = ffi.C.fork()
if cpid == 0 then
turbo.inotify:close()
ffi.C.execvp("luajit", self.para)
error(ffi.string(ffi.C.strerror(ffi.errno())))
end
end
return turbovisor
|
--- Turbo.lua Turbovisor, auto-reload of application on file changes.
--
-- Copyright 2013 John Abrahamsen, Deyuan Deng
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local ffi = require "ffi"
local bit = require "bit"
local turbo = require "turbo"
local fs = require "turbo.fs"
--- Parsing arguments for turbovisor
-- @param arg All command line input. Note arg[0] is 'turbovisor', arg[1] is
-- application name; so user-defined argument starts from arg[2]
-- @return a table containing option/value pair, options including:
-- 'watch': set of files or directories to watch
-- 'ignore': set of files or directories that turbovisor shouldn't watch
local function get_param(arg)
local arg_opt
local arg_tbl = {}
for i = 2, #arg, 1 do
if arg[i] == '--watch' or arg[i] == '-w' then
arg_tbl.watch = arg_tbl.watch or {}
arg_opt = 'watch'
elseif arg[i] == '--ignore' or arg[i] == '-i' then
arg_tbl.ignore = arg_tbl.ignore or {}
arg_opt = 'ignore'
else
if string.sub(arg[i], 1, 2) == "./" then
arg[i] = string.sub(arg[i], 3) -- pass './'
end
local files = fs.glob(arg[i])
-- insert glob expanded result into table
if files then
for _,v in ipairs(files) do
table.insert(arg_tbl[arg_opt], v)
end
end
end
end
-- Deal with default parameters
if arg_tbl.watch == nil then arg_tbl.watch = {'.'} end
return arg_tbl;
end
--- Kill all descendants for a given pid
local function kill_tree(pid)
local status = ffi.new("int[1]")
local cpids = io.popen('pgrep -P ' .. pid)
for cpid in cpids:lines() do
kill_tree(cpid)
ffi.C.kill(tonumber(cpid), 9)
ffi.C.waitpid(tonumber(cpid), status, 0)
assert(status[0] == 9 or bit.band(status[0], 0x7f) == 0,
"Child process " .. cpid .. " not killed.")
end
cpids:close()
end
--- The turbovisor class is a supervisor for detecting file changes
-- and restart supervised application.
local turbovisor = class("turbovisor", turbo.ioloop.IOLoop)
--- Start supervising.
function turbovisor:supervise()
-- Get command line parameters
self.arg_tbl = get_param(arg)
-- Create a new inotify
self.i_fd = turbo.inotify:new()
-- Create a buffer for reading event in callback handler
self.buf = ffi.gc(ffi.C.malloc(turbo.fs.PATH_MAX), ffi.C.free)
-- Initialize ioloop, add inotify handler
self:initialize()
self:add_handler(self.i_fd, turbo.ioloop.READ, self.restart, self)
-- Set watch on target file or directory
for i, target in pairs(self.arg_tbl.watch) do
if turbo.fs.is_dir(target) then
turbo.inotify:watch_all(target, self.arg_tbl.ignore)
else
turbo.inotify:watch_file(target)
end
end
-- Parameters for starting application
local para = ffi.new("const char *[?]", 3)
para[0] = "luajit"
para[1] = arg[1]
para[2] = nil
self.para = ffi.cast("char *const*", para)
-- Run application and supervisor
local cpid = ffi.C.fork()
if cpid == 0 then
turbo.inotify:close()
ffi.C.execvp("luajit", self.para)
error(ffi.string(ffi.C.strerror(ffi.errno())))
else
self:start()
end
end
--- Callback handler when files changed
-- For now, just restart the only one application
function turbovisor.restart(self, fd, events)
-- Read out event
ffi.C.read(fd, self.buf, turbo.fs.PATH_MAX);
self.buf = ffi.cast("struct inotify_event*", self.buf)
local full_path
if self.buf.len == 0 then -- 'len = 0' if we watch on file directly
full_path = turbo.inotify:get_watched_file(self.buf.wd)
else
local path = turbo.inotify:get_watched_file(self.buf.wd)
full_path = path .. '/' .. ffi.string(self.buf.name)
if path == '.' then full_path = ffi.string(self.buf.name) end
end
turbo.inotify:rewatch_if_ignored(self.buf, full_path)
-- Simply return if we need to ignore the file
if turbo.util.is_in(full_path, self.arg_tbl.ignore) then
return
end
turbo.log.notice("[turbovisor.lua] File '" .. full_path ..
"' changed, application restarted!")
-- Restart application
kill_tree(ffi.C.getpid())
local cpid = ffi.C.fork()
if cpid == 0 then
turbo.inotify:close()
ffi.C.execvp("luajit", self.para)
error(ffi.string(ffi.C.strerror(ffi.errno())))
end
end
return turbovisor
|
turbovisor: Fix multiple repeating arguments
|
turbovisor: Fix multiple repeating arguments
Running 'turbovisor -w somefile.lua -w otherdir' works now as expected.
Signed-off-by: Petr Štetiar <[email protected]>
|
Lua
|
apache-2.0
|
ddysher/turbo,kernelsauce/turbo,zcsteele/turbo,mniestroj/turbo,ddysher/turbo,luastoned/turbo,zcsteele/turbo,YuanPeir-Chen/turbo-support-mipsel,YuanPeir-Chen/turbo-support-mipsel,luastoned/turbo
|
faf255bb0be4b6fb09f6c35ddc3d0c61ef60bcef
|
premake5.lua
|
premake5.lua
|
local sep = "/"
local ext = ""
if os.ishost("windows") then
sep = "\\"
ext = ".exe"
end
cwd = os.getcwd()
-- Workspace definition.
workspace("Rendu")
-- Configurations
configurations({ "Release", "Dev"})
location("build")
targetdir ("build/%{prj.name}/%{cfg.longname}")
debugdir ("build/%{prj.name}/%{cfg.longname}")
architecture("x64")
-- Configuration specific settings.
filter("configurations:Release")
defines({ "NDEBUG" })
optimize("On")
filter("configurations:Dev")
defines({ "DEBUG" })
symbols("On")
filter({})
startproject("ALL")
-- Helper functions for the projects.
function CommonSetup()
-- C++ settings
language("C++")
cppdialect("C++11")
systemversion("latest")
-- Compiler flags
filter("toolset:not msc*")
buildoptions({ "-Wall", "-Wextra" })
filter("toolset:msc*")
buildoptions({ "-W3"})
filter({})
-- Common include dirs
-- System headers are used to support angled brackets in Xcode.
sysincludedirs({ "src/libs/", "src/libs/glfw/include/" })
end
function ExecutableSetup()
kind("ConsoleApp")
-- Link with compiled librarires
includedirs({ "src/engine" })
links({"Engine"})
links({"nfd", "glfw3"})
-- Libraries for each platform.
filter("system:macosx")
links({"OpenGL.framework", "Cocoa.framework", "IOKit.framework", "CoreVideo.framework", "AppKit.framework"})
filter("system:windows")
links({"opengl32", "comctl32"})
filter("system:linux")
links({"GL", "X11", "Xi", "Xrandr", "Xxf86vm", "Xinerama", "Xcursor", "Xext", "Xrender", "Xfixes", "xcb", "Xau", "Xdmcp", "rt", "m", "pthread", "dl", "gtk-3", "gdk-3", "pangocairo-1.0", "pango-1.0", "atk-1.0", "cairo-gobject", "cairo", "gdk_pixbuf-2.0", "gio-2.0", "gobject-2.0", "glib-2.0"})
filter({})
end
function ShaderValidation()
-- Run the shader validator on all existing shaders.
-- Output IDE compatible error messages.
dependson({"ShaderValidator"})
filter("configurations:Release")
prebuildcommands({
path.translate("{CHDIR} "..cwd.."/build/ShaderValidator/Release/", sep),
path.translate("./ShaderValidator"..ext.." "..cwd.."/resources/", sep)
})
filter("configurations:Dev")
prebuildcommands({
path.translate("{CHDIR} "..cwd.."/build/ShaderValidator/Dev/", sep),
path.translate("./ShaderValidator"..ext.." "..cwd.."/resources/", sep)
})
filter({})
end
function RegisterSourcesAndShaders(srcPath, shdPath)
files({ srcPath, shdPath })
removefiles({"**.DS_STORE", "**.thumbs"})
-- Reorganize file hierarchy in the IDE project.
vpaths({
["*"] = {srcPath},
["Shaders/*"] = {shdPath}
})
end
function AppSetup(appName)
CommonSetup()
ExecutableSetup()
ShaderValidation()
-- Declare src and resources files.
srcPath = "src/apps/"..appName.."/**"
rscPath = "resources/"..appName.."/shaders/**"
RegisterSourcesAndShaders(srcPath, rscPath)
end
function ToolSetup()
CommonSetup()
ExecutableSetup()
ShaderValidation()
end
-- Projects
project("Engine")
CommonSetup()
kind("StaticLib")
includedirs({ "src/engine" })
-- Some additional files (README, scenes) are hidden, but you can display them in the project by uncommenting them below.
files({ "src/engine/**.hpp", "src/engine/**.cpp",
"resources/common/shaders/**",
"src/libs/**.hpp", "src/libs/*/*.cpp", "src/libs/**.h",
"premake5.lua",
"README.md",
-- "resources/**.scene"
})
removefiles { "src/libs/nfd/*" }
removefiles { "src/libs/glfw/*" }
removefiles({"**.DS_STORE", "**.thumbs"})
-- Virtual path allow us to get rid of the on-disk hierarchy.
vpaths({
["Engine/*"] = {"src/engine/**"},
["Shaders/*"] = {"resources/common/shaders/**"},
["Libraries/*"] = {"src/libs/**"},
[""] = { "*.*" },
-- ["Scenes/*"] = {"resources/**.scene"},
})
group("Apps")
project("PBRDemo")
AppSetup("pbrdemo")
project("Playground")
AppSetup("playground")
project("Atmosphere")
AppSetup("atmosphere")
project("SnakeGame")
AppSetup("snakegame")
project("PathTracer")
AppSetup("pathtracer")
project("ImageFiltering")
AppSetup("imagefiltering")
group("Tools")
project("AtmosphericScatteringEstimator")
ToolSetup()
files({ "src/tools/AtmosphericScatteringEstimator.cpp" })
project("BRDFEstimator")
ToolSetup()
includedirs({ "src/apps/pbrdemo" })
files({ "src/tools/BRDFEstimator.cpp" })
project("ControllerTest")
ToolSetup()
files({ "src/tools/ControllerTest.cpp" })
project("ImageViewer")
ToolSetup()
RegisterSourcesAndShaders("src/tools/ImageViewer.cpp", "resources/imageviewer/shaders/**")
project("ObjToScene")
ToolSetup()
files({ "src/tools/objtoscene/*.cpp", "src/tools/objtoscene/*.hpp" })
project("ShaderValidator")
CommonSetup()
ExecutableSetup()
files({ "src/tools/ShaderValidator.cpp" })
group("Meta")
project("ALL")
CommonSetup()
kind("ConsoleApp")
dependson( {"Engine", "PBRDemo", "Playground", "Atmosphere", "ImageViewer", "ImageFiltering", "AtmosphericScatteringEstimator", "BRDFEstimator", "ControllerTest", "SnakeGame", "PathTracer", "ObjToScene"})
-- Include NFD premake file.
include("src/libs/nfd/premake5.lua")
include("src/libs/glfw/premake5.lua")
-- Actions
newaction {
trigger = "clean",
description = "Clean the build directory",
execute = function ()
print("Cleaning...")
os.rmdir("./build")
print("Done.")
end
}
newaction {
trigger = "docs",
description = "Build the documentation using Doxygen",
execute = function ()
print("Generating documentation...")
os.execute("doxygen"..ext.." docs/Doxyfile")
print("Done.")
end
}
-- Internal private projects can be added here.
if os.isfile("src/internal/premake5.lua") then
include("src/internal/premake5.lua")
end
|
local sep = "/"
local ext = ""
if os.ishost("windows") then
sep = "\\"
ext = ".exe"
end
cwd = os.getcwd()
-- Workspace definition.
workspace("Rendu")
-- Configurations
configurations({ "Release", "Dev"})
location("build")
targetdir ("build/%{prj.name}/%{cfg.longname}")
debugdir ("build/%{prj.name}/%{cfg.longname}")
architecture("x64")
-- Configuration specific settings.
filter("configurations:Release")
defines({ "NDEBUG" })
optimize("On")
filter("configurations:Dev")
defines({ "DEBUG" })
symbols("On")
filter({})
startproject("ALL")
-- Helper functions for the projects.
function CommonSetup()
-- C++ settings
language("C++")
cppdialect("C++11")
systemversion("latest")
-- Compiler flags
filter("toolset:not msc*")
buildoptions({ "-Wall", "-Wextra" })
filter("toolset:msc*")
buildoptions({ "-W3"})
filter({})
-- Common include dirs
-- System headers are used to support angled brackets in Xcode.
sysincludedirs({ "src/libs/", "src/libs/glfw/include/" })
end
function ExecutableSetup()
kind("ConsoleApp")
-- Link with compiled librarires
includedirs({ "src/engine" })
links({"Engine"})
links({"nfd", "glfw3"})
-- Libraries for each platform.
filter("system:macosx")
links({"OpenGL.framework", "Cocoa.framework", "IOKit.framework", "CoreVideo.framework", "AppKit.framework"})
filter("system:windows")
links({"opengl32", "comctl32"})
filter("system:linux")
links({"GL", "X11", "Xi", "Xrandr", "Xxf86vm", "Xinerama", "Xcursor", "Xext", "Xrender", "Xfixes", "xcb", "Xau", "Xdmcp", "rt", "m", "pthread", "dl", "gtk-3", "gdk-3", "pangocairo-1.0", "pango-1.0", "atk-1.0", "cairo-gobject", "cairo", "gdk_pixbuf-2.0", "gio-2.0", "gobject-2.0", "glib-2.0"})
filter({})
end
function ShaderValidation()
-- Run the shader validator on all existing shaders.
-- Output IDE compatible error messages.
dependson({"ShaderValidator"})
filter("configurations:Release")
prebuildcommands({
path.translate(cwd.."/build/ShaderValidator/Release/ShaderValidator"..ext.." "..cwd.."/resources/", sep)
})
filter("configurations:Dev")
prebuildcommands({
path.translate(cwd.."/build/ShaderValidator/Dev/ShaderValidator"..ext.." "..cwd.."/resources/", sep)
})
filter({})
end
function RegisterSourcesAndShaders(srcPath, shdPath)
files({ srcPath, shdPath })
removefiles({"**.DS_STORE", "**.thumbs"})
-- Reorganize file hierarchy in the IDE project.
vpaths({
["*"] = {srcPath},
["Shaders/*"] = {shdPath}
})
end
function AppSetup(appName)
CommonSetup()
ExecutableSetup()
ShaderValidation()
-- Declare src and resources files.
srcPath = "src/apps/"..appName.."/**"
rscPath = "resources/"..appName.."/shaders/**"
RegisterSourcesAndShaders(srcPath, rscPath)
end
function ToolSetup()
CommonSetup()
ExecutableSetup()
ShaderValidation()
end
-- Projects
project("Engine")
CommonSetup()
kind("StaticLib")
includedirs({ "src/engine" })
-- Some additional files (README, scenes) are hidden, but you can display them in the project by uncommenting them below.
files({ "src/engine/**.hpp", "src/engine/**.cpp",
"resources/common/shaders/**",
"src/libs/**.hpp", "src/libs/*/*.cpp", "src/libs/**.h",
"premake5.lua",
"README.md",
-- "resources/**.scene"
})
removefiles { "src/libs/nfd/*" }
removefiles { "src/libs/glfw/*" }
removefiles({"**.DS_STORE", "**.thumbs"})
-- Virtual path allow us to get rid of the on-disk hierarchy.
vpaths({
["Engine/*"] = {"src/engine/**"},
["Shaders/*"] = {"resources/common/shaders/**"},
["Libraries/*"] = {"src/libs/**"},
[""] = { "*.*" },
-- ["Scenes/*"] = {"resources/**.scene"},
})
group("Apps")
project("PBRDemo")
AppSetup("pbrdemo")
project("Playground")
AppSetup("playground")
project("Atmosphere")
AppSetup("atmosphere")
project("SnakeGame")
AppSetup("snakegame")
project("PathTracer")
AppSetup("pathtracer")
project("ImageFiltering")
AppSetup("imagefiltering")
group("Tools")
project("AtmosphericScatteringEstimator")
ToolSetup()
files({ "src/tools/AtmosphericScatteringEstimator.cpp" })
project("BRDFEstimator")
ToolSetup()
includedirs({ "src/apps/pbrdemo" })
files({ "src/tools/BRDFEstimator.cpp" })
project("ControllerTest")
ToolSetup()
files({ "src/tools/ControllerTest.cpp" })
project("ImageViewer")
ToolSetup()
RegisterSourcesAndShaders("src/tools/ImageViewer.cpp", "resources/imageviewer/shaders/**")
project("ObjToScene")
ToolSetup()
files({ "src/tools/objtoscene/*.cpp", "src/tools/objtoscene/*.hpp" })
project("ShaderValidator")
CommonSetup()
ExecutableSetup()
files({ "src/tools/ShaderValidator.cpp" })
group("Meta")
project("ALL")
CommonSetup()
kind("ConsoleApp")
dependson( {"Engine", "PBRDemo", "Playground", "Atmosphere", "ImageViewer", "ImageFiltering", "AtmosphericScatteringEstimator", "BRDFEstimator", "ControllerTest", "SnakeGame", "PathTracer", "ObjToScene"})
-- Include NFD premake file.
include("src/libs/nfd/premake5.lua")
include("src/libs/glfw/premake5.lua")
-- Actions
newaction {
trigger = "clean",
description = "Clean the build directory",
execute = function ()
print("Cleaning...")
os.rmdir("./build")
print("Done.")
end
}
newaction {
trigger = "docs",
description = "Build the documentation using Doxygen",
execute = function ()
print("Generating documentation...")
os.execute("doxygen"..ext.." docs/Doxyfile")
print("Done.")
end
}
-- Internal private projects can be added here.
if os.isfile("src/internal/premake5.lua") then
include("src/internal/premake5.lua")
end
|
Premake: fix access right for shader validation on Linux.
|
Premake: fix access right for shader validation on Linux.
|
Lua
|
mit
|
kosua20/GL_Template,kosua20/GL_Template
|
2b9068e5f79b444977c007eff37c9749d1e3b3bb
|
src/plugins/lua/once_received.lua
|
src/plugins/lua/once_received.lua
|
--[[
Copyright (c) 2011-2015, Vsevolod Stakhov <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- 0 or 1 received: = spam
local symbol = 'ONCE_RECEIVED'
local symbol_rdns = 'RDNS_NONE'
-- Symbol for strict checks
local symbol_strict = nil
local bad_hosts = {}
local good_hosts = {}
local whitelist = nil
local rspamd_logger = require "rspamd_logger"
local function check_quantity_received (task)
local function recv_dns_cb(resolver, to_resolve, results, err)
task:inc_dns_req()
if not results then
task:insert_result(symbol, 1)
task:insert_result(symbol_strict, 1)
task:insert_result(symbol_rdns, 1)
else
rspamd_logger.infox(task, 'SMTP resolver failed to resolve: %1 is %2',
to_resolve, results[1])
if good_hosts then
for _,gh in ipairs(good_hosts) do
if string.find(results[1], gh) then
return
end
end
end
task:insert_result(symbol, 1)
for _,h in ipairs(bad_hosts) do
if string.find(results[1], h) then
task:insert_result(symbol_strict, 1, h)
return
end
end
end
end
if task:get_user() ~= nil then
return
end
if whitelist then
local addr = task:get_from_ip()
if addr and whitelist:get_key(addr) then
rspamd_logger.infox(task, 'whitelisted mail from %s',
addr:to_string())
return
end
end
local recvh = task:get_received_headers()
if recvh and #recvh <= 1 then
local ret = true
local r = recvh[1]
local task_ip = task:get_ip()
-- Here we don't care about received
if not task:get_hostname() and task_ip then
rspamd_logger.infox(task, 'hui')
task:get_resolver():resolve_ptr({task = task,
name = task_ip:to_string(),
callback = recv_dns_cb
})
return
end
if not r then
return
end
local hn = nil
if r['real_hostname'] then
hn = string.lower(r['real_hostname'])
-- Check for good hostname
if hn and good_hosts then
for _,gh in ipairs(good_hosts) do
if string.find(hn, gh) then
ret = false
break
end
end
end
end
if ret then
-- Strict checks
if symbol_strict then
-- Unresolved host
task:insert_result(symbol, 1)
for _,h in ipairs(bad_hosts) do
if string.find(hn, h) then
task:insert_result(symbol_strict, 1, h)
return
end
end
else
task:insert_result(symbol, 1)
end
end
end
end
-- Registration
if type(rspamd_config.get_api_version) ~= 'nil' then
if rspamd_config:get_api_version() >= 1 then
rspamd_config:register_module_option('once_received', 'symbol', 'string')
rspamd_config:register_module_option('once_received', 'symbol_strict', 'string')
rspamd_config:register_module_option('once_received', 'bad_host', 'string')
rspamd_config:register_module_option('once_received', 'good_host', 'string')
end
end
-- Configuration
local opts = rspamd_config:get_all_opt('once_received')
if opts then
if opts['symbol'] then
local symbol = opts['symbol']
local id = rspamd_config:register_symbol(symbol, 1.0, check_quantity_received)
for n,v in pairs(opts) do
if n == 'symbol_strict' then
symbol_strict = v
elseif n == 'symbol_rdns' then
symbol_rdns = v
elseif n == 'bad_host' then
if type(v) == 'string' then
bad_hosts[1] = v
else
bad_hosts = v
end
elseif n == 'good_host' then
if type(v) == 'string' then
good_hosts[1] = v
else
good_hosts = v
end
elseif n == 'whitelist' then
whitelist = rspamd_config:add_radix_map (v, 'once received whitelist')
end
end
rspamd_config:register_virtual_symbol(symbol_rdns, 1.0, id)
rspamd_config:register_virtual_symbol(symbol_strict, 1.0, id)
end
end
|
--[[
Copyright (c) 2011-2015, Vsevolod Stakhov <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
-- 0 or 1 received: = spam
local symbol = 'ONCE_RECEIVED'
local symbol_rdns = 'RDNS_NONE'
-- Symbol for strict checks
local symbol_strict = nil
local bad_hosts = {}
local good_hosts = {}
local whitelist = nil
local rspamd_logger = require "rspamd_logger"
local function check_quantity_received (task)
local function recv_dns_cb(resolver, to_resolve, results, err)
task:inc_dns_req()
if not results then
task:insert_result(symbol, 1)
task:insert_result(symbol_strict, 1)
task:insert_result(symbol_rdns, 1)
else
rspamd_logger.infox(task, 'SMTP resolver failed to resolve: %1 is %2',
to_resolve, results[1])
if good_hosts then
for _,gh in ipairs(good_hosts) do
if string.find(results[1], gh) then
return
end
end
end
task:insert_result(symbol, 1)
for _,h in ipairs(bad_hosts) do
if string.find(results[1], h) then
task:insert_result(symbol_strict, 1, h)
return
end
end
end
end
if task:get_user() ~= nil then
return
end
if whitelist then
local addr = task:get_from_ip()
if addr and whitelist:get_key(addr) then
rspamd_logger.infox(task, 'whitelisted mail from %s',
addr:to_string())
return
end
end
local task_ip = task:get_ip()
-- Here we don't care about received
if not task:get_hostname() and task_ip then
task:get_resolver():resolve_ptr({task = task,
name = task_ip:to_string(),
callback = recv_dns_cb
})
return
end
local recvh = task:get_received_headers()
if recvh and #recvh <= 1 then
local ret = true
local r = recvh[1]
if not r then
return
end
local hn = nil
if r['real_hostname'] then
hn = string.lower(r['real_hostname'])
-- Check for good hostname
if hn and good_hosts then
for _,gh in ipairs(good_hosts) do
if string.find(hn, gh) then
ret = false
break
end
end
end
end
if ret then
-- Strict checks
if symbol_strict then
-- Unresolved host
task:insert_result(symbol, 1)
for _,h in ipairs(bad_hosts) do
if string.find(hn, h) then
task:insert_result(symbol_strict, 1, h)
return
end
end
else
task:insert_result(symbol, 1)
end
end
end
end
-- Registration
if type(rspamd_config.get_api_version) ~= 'nil' then
if rspamd_config:get_api_version() >= 1 then
rspamd_config:register_module_option('once_received', 'symbol', 'string')
rspamd_config:register_module_option('once_received', 'symbol_strict', 'string')
rspamd_config:register_module_option('once_received', 'bad_host', 'string')
rspamd_config:register_module_option('once_received', 'good_host', 'string')
end
end
-- Configuration
local opts = rspamd_config:get_all_opt('once_received')
if opts then
if opts['symbol'] then
local symbol = opts['symbol']
local id = rspamd_config:register_symbol(symbol, 1.0, check_quantity_received)
for n,v in pairs(opts) do
if n == 'symbol_strict' then
symbol_strict = v
elseif n == 'symbol_rdns' then
symbol_rdns = v
elseif n == 'bad_host' then
if type(v) == 'string' then
bad_hosts[1] = v
else
bad_hosts = v
end
elseif n == 'good_host' then
if type(v) == 'string' then
good_hosts[1] = v
else
good_hosts = v
end
elseif n == 'whitelist' then
whitelist = rspamd_config:add_radix_map (v, 'once received whitelist')
end
end
rspamd_config:register_virtual_symbol(symbol_rdns, 1.0, id)
rspamd_config:register_virtual_symbol(symbol_strict, 1.0, id)
end
end
|
[Fix] Fix placement of RDNS checks
|
[Fix] Fix placement of RDNS checks
|
Lua
|
bsd-2-clause
|
andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,minaevmike/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd
|
df8994982e34bb6c1ce719fd8e0a8f39812cda48
|
search-script.lua
|
search-script.lua
|
#!/usr/bin/env lua
local config = require "config"
local filePath = config.filePath
function printArgs()
for k,v in pairs(arg) do
print(k,v)
end
end
function countArgs()
count = 0
for _ in pairs(arg) do count = count + 1 end
return count - 2
end
function helpMenu()
print "#========================================================================#"
print "# -h Display this help menu #"
print "# -n The string to search #"
print "# -b Search by file name, category or both #"
print "# filename, category, all default all #"
print "# Usage: ./search-script.lua -n foofile -b all -e png #"
print "#========================================================================#"
end
-- see if the file exists
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then print "El archivo no existe" os.exit() end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- tests the functions above
local file = filePath
local lines = lines_from(file)
-- print all line numbers and their contents
function printAll(lines)
for k,v in pairs(lines) do
local i = string.find(v, script)
if i ~= nil then print('[' .. k .. ']', v) end
end
end
function printResults(lines,script)
for k,v in pairs(lines) do
local i = string.find(v, script)
if i ~= nil then print('[' .. k .. ']', v) end
end
end
function defineArgs()
local string
for i=1,countArgs() do
if arg[i] == "-h" then helpMenu() os.exit() end
if arg[i] == "-n" then
string = arg[i+1]
print(script)
end
end
--printResults(lines,script)
end
if countArgs() < 1 then
printAll(lines)
else
defineArgs()
end
|
#!/usr/bin/env lua
local config = require "config"
local filePath = config.filePath
function printArgs()
for k,v in pairs(arg) do
print(k,v)
end
end
function countArgs()
count = 0
for _ in pairs(arg) do count = count + 1 end
return count - 2
end
function helpMenu()
print "#========================================================================#"
print "# -h Display this help menu #"
print "# -n The string to search #"
print "# -b Search by file name, category or both #"
print "# filename, category, all default all #"
print "# Usage: ./search-script.lua -n foofile -b all -e png #"
print "#========================================================================#"
end
-- see if the file exists
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then print "El archivo no existe" os.exit() end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- tests the functions above
local file = filePath
local lines = lines_from(file)
-- print all line numbers and their contents
function printAll(lines)
for k,v in pairs(lines) do
print('line[' .. k .. ']', v)
end
end
function printResults(lines,script)
for k,v in pairs(lines) do
local i = string.find(v, script)
if i ~= nil then print('[' .. k .. ']', v) end
end
end
function defineArgs()
local string
for i=1,countArgs() do
if arg[i] == "-h" then helpMenu() os.exit() end
if arg[i] == "-n" then
string = arg[i+1]
print(script)
end
end
--printResults(lines,script)
end
if countArgs() < 1 then
printAll(lines)
else
defineArgs()
end
|
Fixing print all files results
|
Fixing print all files results
Signed-off-by: Jacobo Tibaquira <[email protected]>
|
Lua
|
apache-2.0
|
JKO/nsearch,JKO/nsearch
|
9d9cb6228c9a41194c693c76ed0936e6779cd9ce
|
trovebox.lua
|
trovebox.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 = {}
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local html = urlpos["link_expect_html"]
local parenturl = parent["url"]
if downloaded[url] == true or addedtolist[url] == true then
return false
end
if item_type == "site" and (downloaded[url] ~= true and addedtolist[url] ~= true) then
if string.match(url, item_value) then
return verdict
elseif html == 0 then
return verdict
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
local function check(url)
if (downloaded[url] ~= true and addedtolist[url] ~= true) then
table.insert(urls, { url=url })
addedtolist[url] = true
end
end
if item_type == "site" then
if string.match(url, "%?") then
local newurl = string.match(url, "(https://[^%?]+)%?")
check(newurl)
end
if string.match(url, "https?://[^%.]+%.trovebox%.com") and not string.match(url, "%.jpg") then
html = read_file(file)
for newurl in string.gmatch(html, '"(https?://[^"]+)"') do
if string.match(newurl, "\/") then
local newnewurl = string.gsub(newurl, "\/", "/")
check(newnewurl)
elseif string.match(newurl, item_value) or string.match(newurl, "%.jpg") or string.match(newurl, "%.png") or string.match(url, "%.cloudfront%.com") then
check(newurl)
end
end
for newurl2 in string.gmatch(html, '"(%?[^"]+)"') then
local newurl1 = string.match(url, "(https?://[^%?]+)%?")
local newurl = newurl1..newurl2
check(newurl)
end
for newurl2 in string.gmatch(html, '"(/[^"]+)"') do
if not string.match(newurl2, "%%") then
local newurl1 = string.match(url, "(https?://[^/]+)/")
local newurl = newurl1..newurl2
check(newurl)
end
end
if string.match(url, "%.trovebox%.com/p/[0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z]") then
local photoid = string.match(url, "%.trovebox%.com/p/([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])")
for newphotoid in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])"') do
local newurl = string.gsub(url, "/p/"..photoid, "/p/"..newphotoid)
check(newurl)
end
end
if string.match(url, "%.trovebox%.com/albums/") then
for newalbum in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z])"') do
local newurl = string.gsub(url, "/albums/", "/photos/album%-"..newalbum.."/list")
check(newurl)
end
end
if string.match(url, "%.trovebox%.com/photos/album%-[0-9a-zA-Z][0-9a-zA-Z]/list") then
local albumid = string.match(url, "%.trovebox%.com/photos/album%-([0-9a-zA-Z][0-9a-zA-Z])")
for photoid in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])"')
local newurl = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid
local newurl0 = "https://"..item_value..".trovebox.com/p/"..photoid
local newurl1 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateTaken,asc"
local newurl2 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateTaken,desc"
local newurl3 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateUploaded,asc"
local newurl4 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateUploaded,desc"
check(newurl)
check(newurl0)
check(newurl1)
check(newurl2)
check(newurl3)
check(newurl4)
end
end
end
end
return urls
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
last_http_statcode = status_code
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) then
if string.match(url["url"], "https://") then
local newurl = string.gsub(url["url"], "https://", "http://")
downloaded[newurl] = true
else
downloaded[url["url"]] = true
end
end
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 5")
tries = tries + 1
if tries >= 20 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 10 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
dofile("urlcode.lua")
dofile("table_show.lua")
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
local addedtolist = {}
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local html = urlpos["link_expect_html"]
local parenturl = parent["url"]
if downloaded[url] == true or addedtolist[url] == true then
return false
end
if item_type == "site" and (downloaded[url] ~= true and addedtolist[url] ~= true) then
if string.match(url, item_value) then
return verdict
elseif html == 0 then
return verdict
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
local function check(url)
if (downloaded[url] ~= true and addedtolist[url] ~= true) then
table.insert(urls, { url=url })
addedtolist[url] = true
end
end
if item_type == "site" then
if string.match(url, "%?") then
local newurl = string.match(url, "(https://[^%?]+)%?")
check(newurl)
end
if string.match(url, "https?://[^%.]+%.trovebox%.com") and not string.match(url, "%.jpg") then
html = read_file(file)
for newurl in string.gmatch(html, '"(https?://[^"]+)"') do
if string.match(newurl, "\/") then
local newnewurl = string.gsub(newurl, "\/", "/")
check(newnewurl)
elseif string.match(newurl, item_value) or string.match(newurl, "%.jpg") or string.match(newurl, "%.png") or string.match(url, "%.cloudfront%.com") then
check(newurl)
end
end
for newurl2 in string.gmatch(html, '"(%?[^"]+)"') do
local newurl1 = string.match(url, "(https?://[^%?]+)%?")
local newurl = newurl1..newurl2
check(newurl)
end
for newurl2 in string.gmatch(html, '"(/[^"]+)"') do
if not string.match(newurl2, "%%") then
local newurl1 = string.match(url, "(https?://[^/]+)/")
local newurl = newurl1..newurl2
check(newurl)
end
end
if string.match(url, "%.trovebox%.com/p/[0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z]") then
local photoid = string.match(url, "%.trovebox%.com/p/([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])")
for newphotoid in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])"') do
local newurl = "https://"..item_value..".trovebox.com/p/"..newphotoid
check(newurl)
end
end
if string.match(url, "%.trovebox%.com/albums/") then
for newalbum in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z])"') do
local newurl = "https://"..item_value..".trovebox.com/photos/album-"..newalbum.."/list"
check(newurl)
end
end
if string.match(url, "%.trovebox%.com/photos/album%-[0-9a-zA-Z][0-9a-zA-Z]/list") then
local albumid = string.match(url, "%.trovebox%.com/photos/album%-([0-9a-zA-Z][0-9a-zA-Z])")
for photoid in string.gmatch(html, '"id":"([0-9a-zA-Z][0-9a-zA-Z][0-9a-zA-Z])"') do
local newurl = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid
local newurl0 = "https://"..item_value..".trovebox.com/p/"..photoid
local newurl1 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateTaken,asc"
local newurl2 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateTaken,desc"
local newurl3 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateUploaded,asc"
local newurl4 = "https://"..item_value..".trovebox.com/p/"..photoid.."/album-"..albumid.."?sortBy=dateUploaded,desc"
check(newurl)
check(newurl0)
check(newurl1)
check(newurl2)
check(newurl3)
check(newurl4)
end
end
end
end
return urls
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
last_http_statcode = status_code
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) then
if string.match(url["url"], "https://") then
local newurl = string.gsub(url["url"], "https://", "http://")
downloaded[newurl] = true
else
downloaded[url["url"]] = true
end
end
if status_code >= 500 or
(status_code >= 400 and status_code ~= 404) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 5")
tries = tries + 1
if tries >= 20 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 10 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
trovebox.lua: fixes
|
trovebox.lua: fixes
|
Lua
|
unlicense
|
ArchiveTeam/trovebox-grab,ArchiveTeam/trovebox-grab
|
39e5df2b3a110cfb29b68f22c17ad8514716e2a0
|
lua/parse/char/utf8/tools.lua
|
lua/parse/char/utf8/tools.lua
|
local strbyte, strchar = string.byte, string.char
local strsub = string.sub
local contiguous_byte_ranges = require 'parse.char.utf8.data.contiguous_byte_ranges'
local blob_tools = require 'parse.blob.tools'
local next_blob = blob_tools.next
local previous_blob = blob_tools.previous
local special_next = {}
local special_previous = {}
for i = 2, #contiguous_byte_ranges do
local current = contiguous_byte_ranges[i]
local previous = contiguous_byte_ranges[i - 1]
special_next[previous.max] = current.min
special_previous[current.min] = previous.max
end
local tools = {}
local function next_char(v)
if v < '\x80' then
return next_blob(v)
end
local last_byte = strbyte(v, -1)
if last_byte ~= 0xBF then
return next_blob(v)
end
local special = special_next[v]
if special then
return special
end
return next_blob(strsub(v,1,-2)) .. '\x80'
end
tools.next = next_char
local function previous_80_BF(v)
local last_byte = strbyte(v, -1)
local rest = strsub(v, 1, -2)
if last_byte == 0x80 then
return previous_80_BF(rest) .. '\xBF'
end
return rest .. strchar(last_byte - 1)
end
local function previous_char(v)
if v < '\x80' then
return previous_blob(v)
end
local last_byte = strbyte(v, -1)
if last_byte ~= 0x80 then
return previous_blob(v)
end
local special = special_previous[v]
if special then
return special
end
return previous_80_BF(strsub(v,1,-2)) .. '\xBF'
end
tools.previous = previous_char
local function range_aux(final_char, ref_char)
local char = next_char(ref_char)
if char > final_char then
return nil
end
return char
end
function tools.range(from_char, to_char)
return range_aux, to_char, previous_char(from_char)
end
return tools
|
local strbyte, strchar = string.byte, string.char
local strsub = string.sub
local contiguous_byte_ranges = require 'parse.char.utf8.data.contiguous_byte_ranges'
local blob_tools = require 'parse.blob.tools'
local next_blob = blob_tools.next
local previous_blob = blob_tools.previous
local special_next = {}
local special_previous = {}
for i = 2, #contiguous_byte_ranges do
local current = contiguous_byte_ranges[i]
local previous = contiguous_byte_ranges[i - 1]
special_next[previous.max] = current.min
special_previous[current.min] = previous.max
end
local tools = {}
local function next_80_BF(v)
local last_byte = strbyte(v, -1)
local rest = strsub(v, 1, -2)
if last_byte == 0xBF then
return next_80_BF(rest) .. '\x80'
end
return rest .. strchar(last_byte + 1)
end
local function next_char(v)
if v < '\x80' then
return next_blob(v)
end
local last_byte = strbyte(v, -1)
if last_byte ~= 0xBF then
return next_blob(v)
end
local special = special_next[v]
if special then
return special
end
return next_80_BF(strsub(v,1,-2)) .. '\x80'
end
tools.next = next_char
local function previous_80_BF(v)
local last_byte = strbyte(v, -1)
local rest = strsub(v, 1, -2)
if last_byte == 0x80 then
return previous_80_BF(rest) .. '\xBF'
end
return rest .. strchar(last_byte - 1)
end
local function previous_char(v)
if v < '\x80' then
return previous_blob(v)
end
local last_byte = strbyte(v, -1)
if last_byte ~= 0x80 then
return previous_blob(v)
end
local special = special_previous[v]
if special then
return special
end
return previous_80_BF(strsub(v,1,-2)) .. '\xBF'
end
tools.previous = previous_char
local function range_aux(final_char, ref_char)
local char = next_char(ref_char)
if char > final_char then
return nil
end
return char
end
function tools.range(from_char, to_char)
return range_aux, to_char, previous_char(from_char)
end
return tools
|
Fix next char in the same way as previous was
|
Fix next char in the same way as previous was
|
Lua
|
mit
|
taxler/radish,taxler/radish,taxler/radish,taxler/radish,taxler/radish,taxler/radish
|
ba6bbd00495725097eb564fd915d2b91f0b5b971
|
src/conman.lua
|
src/conman.lua
|
--- @module conman
local conman = {}
local config = require("config")
local db = require("db")
local cjdns = require("rpc-interface.cjdns")
local threadman = require("threadman")
local rpc = require("rpc")
local conManTs = 0
local subscriberManager = function()
local sinceTimestamp = conManTs
conManTs = os.time()
local subscribers, err = db.getTimingOutSubscribers(sinceTimestamp)
if err == nil and subscribers == nil then
err = "Unexpected subscriber list query result"
end
if err then
threadman.notify({type = "error", module = "conman", error = err})
return
end
for k,subscriber in pairs(subscribers) do
local at = ""
if subscriber.meshIP ~= nil then
at = at..subscriber.method.."::"..subscriber.meshIP.." "
end
local addr = ""
if subscriber.internetIPv4 ~= nil then
addr = addr..subscriber.internetIPv4.." "
end
if subscriber.internetIPv6 ~= nil then
addr = addr..subscriber.internetIPv6.." "
end
if subscriber.method == "cjdns" then
cjdns.releaseConnection(subscriber.sid)
else
threadman.notify({type = "error", module = "conman", error = "Unknown method", method = subscriber.method})
end
threadman.notify({type = "subscriberSessionTimedOut", ["sid"] = subscriber.sid})
end
end
local gatewayManager = function()
local currentTimestamp = os.time()
local gracePeriod = 10;
local sessions, err = db.getLastActiveSessions()
if err == nil and sessions == nil then
err = "Unexpected session list query result"
end
if err then
threadman.notify({type = "error", module = "conman", error = err})
return
end
for k, session in pairs(sessions) do
if session.subscriber == 0 and session.active == 1 then
if currentTimestamp > session.timeout_timestamp then
db.deactivateSession(session.sid)
threadman.notify({type = "gatewaySessionTimedOut", ["sid"] = session.sid})
elseif currentTimestamp > session.timeout_timestamp-gracePeriod then
local gateway = rpc.getProxy(session.meshIP, session.port)
local result, err = gateway.renewConnection(session.sid)
if err then
threadman.notify({type = "error", module = "conman", ["error"] = err})
elseif not result then
threadman.notify({type = "error", module = "conman", ["error"] = "Unknown error"})
elseif result.success == false and result.errorMsg then
threadman.notify({type = "error", module = "conman", ["error"] = result.errorMsg})
elseif result.success == false then
threadman.notify({type = "error", module = "conman", ["error"] = "Unknown error"})
else
db.updateSessionTimeout(session.sid, result.timeout)
threadman.notify({type = "renewedGatewaySession", ["sid"] = session.sid, ["timeout"] = result.timeout})
end
end
end
end
end
function conman.connectToGateway(ip, port, method, sid)
local gateway = rpc.getProxy(ip, port)
local record = db.lookupGateway(ip)
print("[conman] Checking " .. ip .. "...")
local info, err = gateway.nodeInfo()
if err then
return nil, "Failed to connect to " .. ip .. ": " .. err
else
db.registerNode(info.name, ip, port)
end
if info.methods then
-- check to make sure method is supported
local supported = false
for k, m in pairs(info.methods) do
if m == method then
supported = true
end
-- register methods
if m and m.name then
db.registerGateway(info.name, ip, port, m.name)
end
end
else
method = nil
end
if method == nil then
return nil, "No supported connection methods at " .. ip
end
print("[conman] Connecting to gateway '" .. info.name .. "' at " .. ip)
local result
if method == "cjdns" then
print("[conman] Connecting to " .. ip .. " port " .. port)
db.registerGatewaySession(sid, info.name, method, ip, port)
result = cjdns.connectTo(ip, port, method, sid)
if result.success then
print("Registered with gateway at " .. ip .. " port "..port.."!")
if result.timeout then
if result.ipv4 then print("IPv4:" .. result.ipv4) end
if result.ipv4gateway then print("IPv4 gateway:" .. result.ipv4gateway) end
if result.ipv6 then print("IPv6:" .. result.ipv6) end
if result.ipv6gateway then print("IPv6 gateway:" .. result.ipv6gateway) end
if result.dns then print("IPv6 DNS:" .. result.dns) end
if result.timeout then print("Timeout is " .. result.timeout .. " seconds") end
end
db.updateGatewaySession(sid, true, result.ipv4, result.ipv6, result.timeout)
end
return result, nil
else
return nil, "Unsupported method"
end
if result.success then
return true
else
return nil, result.errorMsg
end
end
local connectionManager = function()
subscriberManager()
gatewayManager()
end
function conman.startConnectionManager()
local socket = require("socket")
local listener = threadman.registerListener("conman")
while true do
socket.sleep(2)
connectionManager()
local msg = {};
while msg ~= nil do
msg = listener:listen(true)
if msg ~= nil then
if msg["type"] == "exit" then
threadman.unregisterListener(listener)
return
end
end
end
end
end
return conman
|
--- @module conman
local conman = {}
local config = require("config")
local db = require("db")
local cjdns = require("rpc-interface.cjdns")
local threadman = require("threadman")
local rpc = require("rpc")
local conManTs = 0
local subscriberManager = function()
local sinceTimestamp = conManTs
conManTs = os.time()
local subscribers, err = db.getTimingOutSubscribers(sinceTimestamp)
if err == nil and subscribers == nil then
err = "Unexpected subscriber list query result"
end
if err then
threadman.notify({type = "error", module = "conman", error = err})
return
end
for k,subscriber in pairs(subscribers) do
local at = ""
if subscriber.meshIP ~= nil then
at = at..subscriber.method.."::"..subscriber.meshIP.." "
end
local addr = ""
if subscriber.internetIPv4 ~= nil then
addr = addr..subscriber.internetIPv4.." "
end
if subscriber.internetIPv6 ~= nil then
addr = addr..subscriber.internetIPv6.." "
end
if subscriber.method == "cjdns" then
cjdns.releaseConnection(subscriber.sid)
else
threadman.notify({type = "error", module = "conman", error = "Unknown method", method = subscriber.method})
end
threadman.notify({type = "subscriberSessionTimedOut", ["sid"] = subscriber.sid})
end
end
local gatewayManager = function()
local currentTimestamp = os.time()
local gracePeriod = 10;
local sessions, err = db.getLastActiveSessions()
if err == nil and sessions == nil then
err = "Unexpected session list query result"
end
if err then
threadman.notify({type = "error", module = "conman", error = err})
return
end
for k, session in pairs(sessions) do
if session.subscriber == 0 and session.active == 1 then
if currentTimestamp > session.timeout_timestamp then
db.deactivateSession(session.sid)
threadman.notify({type = "gatewaySessionTimedOut", ["sid"] = session.sid})
elseif currentTimestamp > session.timeout_timestamp-gracePeriod then
local gateway = rpc.getProxy(session.meshIP, session.port)
local result, err = gateway.renewConnection(session.sid)
if err then
threadman.notify({type = "error", module = "conman", ["error"] = err})
elseif not result then
threadman.notify({type = "error", module = "conman", ["error"] = "Unknown error"})
elseif result.success == false and result.errorMsg then
threadman.notify({type = "error", module = "conman", ["error"] = result.errorMsg})
elseif result.success == false then
threadman.notify({type = "error", module = "conman", ["error"] = "Unknown error"})
else
db.updateSessionTimeout(session.sid, result.timeout)
threadman.notify({type = "renewedGatewaySession", ["sid"] = session.sid, ["timeout"] = result.timeout})
end
end
end
end
end
function conman.connectToGateway(ip, port, method, sid)
local gateway = rpc.getProxy(ip, port)
print("[conman] Checking " .. ip .. "...")
local info, err = gateway.nodeInfo()
if err then
return nil, "Failed to connect to " .. ip .. ": " .. err
else
db.registerNode(info.name, ip, port)
end
if info.methods then
-- check to make sure method is supported
local supported = false
for k, m in pairs(info.methods) do
if m == method then
supported = true
end
-- register methods
if m and m.name then
db.registerGateway(info.name, ip, port, m.name)
end
end
else
method = nil
end
if method == nil then
return nil, "No supported connection methods at " .. ip
end
print("[conman] Connecting to gateway '" .. info.name .. "' at " .. ip)
local result
if method == "cjdns" then
print("[conman] Connecting to " .. ip .. " port " .. port)
db.registerGatewaySession(sid, info.name, method, ip, port)
result = cjdns.connectTo(ip, port, method, sid)
if result.success then
print("Registered with gateway at " .. ip .. " port "..port.."!")
if result.timeout then
if result.ipv4 then print("IPv4:" .. result.ipv4) end
if result.ipv4gateway then print("IPv4 gateway:" .. result.ipv4gateway) end
if result.ipv6 then print("IPv6:" .. result.ipv6) end
if result.ipv6gateway then print("IPv6 gateway:" .. result.ipv6gateway) end
if result.dns then print("IPv6 DNS:" .. result.dns) end
if result.timeout then print("Timeout is " .. result.timeout .. " seconds") end
end
db.updateGatewaySession(sid, true, result.ipv4, result.ipv6, result.timeout)
end
return result, nil
else
return nil, "Unsupported method"
end
if result.success then
return true
else
return nil, result.errorMsg
end
end
local connectionManager = function()
subscriberManager()
gatewayManager()
end
function conman.startConnectionManager()
local socket = require("socket")
local listener = threadman.registerListener("conman")
while true do
socket.sleep(2)
connectionManager()
local msg = {};
while msg ~= nil do
msg = listener:listen(true)
if msg ~= nil then
if msg["type"] == "exit" then
threadman.unregisterListener(listener)
return
end
end
end
end
end
return conman
|
Crash fix
|
Crash fix
|
Lua
|
mit
|
transitd/transitd,transitd/transitd,transitd/transitd,pdxmeshnet/mnigs,intermesh-networks/transitd,intermesh-networks/transitd,pdxmeshnet/mnigs
|
e588f8d5f98757256ef6b248fd92d594426f90d7
|
ioncore/ioncore_wd.lua
|
ioncore/ioncore_wd.lua
|
--
-- ion/share/ioncore_wd.lua
--
-- Copyright (c) Tuomo Valkonen 2004-2007.
--
-- See the included file LICENSE for details.
--
local savefile="saved_wd"
local dirs={}
local px
if pcall(function() return require('posix') end) then
px=posix
end
local function checkdir(d)
if not px then
return true
else
local t, err=px.stat(d, "type")
if not t then
return nil, err
elseif t=="link" then
local d2, err=px.readlink(d)
if not d2 then
return nil, err
else
print('follow')
return checkdir(d2)
end
elseif t=="directory" then
return true
else
return TR("Not a directory.")
end
end
end
local function regtreepath_i(reg)
local function f(s, v)
if v then
return v:manager()
else
return s
end
end
return f, reg, nil
end
--DOC
-- Change default working directory for new programs started in \var{reg}.
function ioncore.chdir_for(reg, dir)
assert(dir==nil or type(dir)=="string")
if dir=="" or dir==nil then
dirs[reg]=nil
return true
else
local ok, err=checkdir(dir)
if ok then
dirs[reg]=dir
end
return ok, err
end
end
--DOC
-- Get default working directory for new programs started in \var{reg}.
function ioncore.get_dir_for(reg)
for r in regtreepath_i(reg) do
if dirs[r] then
return dirs[r]
end
end
end
local function lookup_script_warn(script)
local script=ioncore.lookup_script(script)
if not script then
warn(TR("Could not find %s", script))
end
return script
end
local function lookup_runinxterm_warn(prog, title, wait)
local rx=lookup_script_warn("ion-runinxterm")
if rx then
if wait then
rx=rx.." -w"
end
if title then
rx=rx.." -T "..string.shell_safe(title)
end
if prog then
rx=rx.." -- "..prog
end
end
return rx
end
--DOC
-- Run \var{cmd} with the environment variable DISPLAY set to point to the
-- root window of the X screen \var{reg} is on. If \var{cmd} is prefixed
-- by a colon (\code{:}), the following command is executed in an xterm
-- (or other terminal emulator) with the help of the \command{ion-runinxterm}
-- script. If the command is prefixed by two colons, \command{ion-runinxterm}
-- will ask you to press enter after the command is finished, even if it
-- returns succesfully.
function ioncore.exec_on(reg, cmd, merr_internal)
local _, _, col, c=string.find(cmd, "^[%s]*(:+)(.*)")
if col then
cmd=lookup_runinxterm_warn(c, nil, string.len(col)>1)
if not cmd then
return
end
if XTERM then
cmd='XTERMCMD='..string.shell_safe(XTERM)..' '..cmd
end
end
return ioncore.do_exec_on(reg, cmd, ioncore.get_dir_for(reg),
merr_internal)
end
local function load_config()
local d=ioncore.read_savefile(savefile)
if d then
dirs={}
for nm, d in pairs(d) do
local r=ioncore.lookup_region(nm)
if r then
local ok, err=checkdir(d)
if ok then
dirs[r]=d
else
warn(err)
end
end
end
end
end
local function save_config()
local t={}
for r, d in pairs(dirs) do
t[r:name()]=d
end
ioncore.write_savefile(savefile, t)
end
local function init()
load_config()
ioncore.get_hook("ioncore_snapshot_hook"):add(save_config)
ioncore.get_hook("ioncore_post_layout_setup_hook"):add(load_config)
end
init()
|
--
-- ion/share/ioncore_wd.lua
--
-- Copyright (c) Tuomo Valkonen 2004-2007.
--
-- See the included file LICENSE for details.
--
local savefile="saved_wd"
local dirs={}
local px
if pcall(function() return require('posix') end) then
px=posix
end
local function checkdir(d)
if not px then
return true
else
local t, err=px.stat(d, "type")
if not t then
return nil, err
elseif t=="link" then
local d2, err=px.readlink(d)
if not d2 then
return nil, err
else
return checkdir(d2)
end
elseif t=="directory" then
return true
else
return nil, TR("Not a directory.")
end
end
end
local function regtreepath_i(reg)
local function f(s, v)
if v then
return v:manager()
else
return s
end
end
return f, reg, nil
end
--DOC
-- Change default working directory for new programs started in \var{reg}.
function ioncore.chdir_for(reg, dir)
assert(dir==nil or type(dir)=="string")
if dir=="" or dir==nil then
dirs[reg]=nil
return true
else
local ok, err=checkdir(dir)
if ok then
dirs[reg]=dir
end
return ok, err
end
end
--DOC
-- Get default working directory for new programs started in \var{reg}.
function ioncore.get_dir_for(reg)
for r in regtreepath_i(reg) do
if dirs[r] then
return dirs[r]
end
end
end
local function lookup_script_warn(script)
local script=ioncore.lookup_script(script)
if not script then
warn(TR("Could not find %s", script))
end
return script
end
local function lookup_runinxterm_warn(prog, title, wait)
local rx=lookup_script_warn("ion-runinxterm")
if rx then
if wait then
rx=rx.." -w"
end
if title then
rx=rx.." -T "..string.shell_safe(title)
end
if prog then
rx=rx.." -- "..prog
end
end
return rx
end
--DOC
-- Run \var{cmd} with the environment variable DISPLAY set to point to the
-- root window of the X screen \var{reg} is on. If \var{cmd} is prefixed
-- by a colon (\code{:}), the following command is executed in an xterm
-- (or other terminal emulator) with the help of the \command{ion-runinxterm}
-- script. If the command is prefixed by two colons, \command{ion-runinxterm}
-- will ask you to press enter after the command is finished, even if it
-- returns succesfully.
function ioncore.exec_on(reg, cmd, merr_internal)
local _, _, col, c=string.find(cmd, "^[%s]*(:+)(.*)")
if col then
cmd=lookup_runinxterm_warn(c, nil, string.len(col)>1)
if not cmd then
return
end
if XTERM then
cmd='XTERMCMD='..string.shell_safe(XTERM)..' '..cmd
end
end
return ioncore.do_exec_on(reg, cmd, ioncore.get_dir_for(reg),
merr_internal)
end
local function load_config()
local d=ioncore.read_savefile(savefile)
if d then
dirs={}
for nm, d in pairs(d) do
local r=ioncore.lookup_region(nm)
if r then
local ok, err=checkdir(d)
if ok then
dirs[r]=d
else
warn(err)
end
end
end
end
end
local function save_config()
local t={}
for r, d in pairs(dirs) do
t[r:name()]=d
end
ioncore.write_savefile(savefile, t)
end
local function init()
load_config()
ioncore.get_hook("ioncore_snapshot_hook"):add(save_config)
ioncore.get_hook("ioncore_post_layout_setup_hook"):add(load_config)
end
init()
|
Lua-posix dir. checking support fixes.
|
Lua-posix dir. checking support fixes.
darcs-hash:20071109180341-4eba8-6db36f9fcf3d7a3740190cb2d247fd6a3dc863e5.gz
|
Lua
|
lgpl-2.1
|
raboof/notion,anoduck/notion,anoduck/notion,neg-serg/notion,dkogan/notion,knixeur/notion,raboof/notion,dkogan/notion.xfttest,p5n/notion,neg-serg/notion,p5n/notion,p5n/notion,neg-serg/notion,knixeur/notion,anoduck/notion,raboof/notion,neg-serg/notion,p5n/notion,dkogan/notion,dkogan/notion,p5n/notion,dkogan/notion,knixeur/notion,dkogan/notion.xfttest,raboof/notion,anoduck/notion,anoduck/notion,dkogan/notion,dkogan/notion.xfttest,knixeur/notion,dkogan/notion.xfttest,knixeur/notion
|
5b9a80b0c437c439a4feb18c734fe2b1483208e2
|
plugins/mod_legacyauth.lua
|
plugins/mod_legacyauth.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 t_concat = table.concat;
local secure_auth_only = module:get_option("require_encryption");
local sessionmanager = require "core.sessionmanager";
local usermanager = require "core.usermanager";
module:add_feature("jabber:iq:auth");
module:add_event_hook("stream-features", function (session, features)
if secure_auth_only and not session.secure then
-- Sorry, not offering to insecure streams!
return;
elseif not session.username then
features:tag("auth", {xmlns='http://jabber.org/features/iq-auth'}):up();
end
end);
module:add_iq_handler("c2s_unauthed", "jabber:iq:auth",
function (session, stanza)
if secure_auth_only and not session.secure then
session.send(st.error_reply(stanza, "modify", "not-acceptable", "Encryption (SSL or TLS) is required to connect to this server"));
return true;
end
local username = stanza.tags[1]:child_with_name("username");
local password = stanza.tags[1]:child_with_name("password");
local resource = stanza.tags[1]:child_with_name("resource");
if not (username and password and resource) then
local reply = st.reply(stanza);
session.send(reply:query("jabber:iq:auth")
:tag("username"):up()
:tag("password"):up()
:tag("resource"):up());
else
username, password, resource = t_concat(username), t_concat(password), t_concat(resource);
local reply = st.reply(stanza);
if usermanager.validate_credentials(session.host, username, password) then
-- Authentication successful!
local success, err = sessionmanager.make_authenticated(session, username);
if success then
local err_type, err_msg;
success, err_type, err, err_msg = sessionmanager.bind_resource(session, resource);
if not success then
session.send(st.error_reply(stanza, err_type, err, err_msg));
return true;
end
end
session.send(st.reply(stanza));
else
session.send(st.error_reply(stanza, "auth", "not-authorized"));
end
end
return true;
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 t_concat = table.concat;
local secure_auth_only = module:get_option("require_encryption");
local sessionmanager = require "core.sessionmanager";
local usermanager = require "core.usermanager";
module:add_feature("jabber:iq:auth");
module:add_event_hook("stream-features", function (session, features)
if secure_auth_only and not session.secure then
-- Sorry, not offering to insecure streams!
return;
elseif not session.username then
features:tag("auth", {xmlns='http://jabber.org/features/iq-auth'}):up();
end
end);
module:add_iq_handler("c2s_unauthed", "jabber:iq:auth",
function (session, stanza)
if secure_auth_only and not session.secure then
session.send(st.error_reply(stanza, "modify", "not-acceptable", "Encryption (SSL or TLS) is required to connect to this server"));
return true;
end
local username = stanza.tags[1]:child_with_name("username");
local password = stanza.tags[1]:child_with_name("password");
local resource = stanza.tags[1]:child_with_name("resource");
if not (username and password and resource) then
local reply = st.reply(stanza);
session.send(reply:query("jabber:iq:auth")
:tag("username"):up()
:tag("password"):up()
:tag("resource"):up());
else
username, password, resource = t_concat(username), t_concat(password), t_concat(resource);
local reply = st.reply(stanza);
if usermanager.validate_credentials(session.host, username, password) then
-- Authentication successful!
local success, err = sessionmanager.make_authenticated(session, username);
if success then
local err_type, err_msg;
success, err_type, err, err_msg = sessionmanager.bind_resource(session, resource);
if not success then
session.send(st.error_reply(stanza, err_type, err, err_msg));
return true; -- FIXME need to unauthenticate here
end
end
session.send(st.reply(stanza));
else
session.send(st.error_reply(stanza, "auth", "not-authorized"));
end
end
return true;
end);
|
mod_legacyauth: Added a FIXME
|
mod_legacyauth: Added a FIXME
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
3a00f6c112270493d9738b9e1a8c3fbae1464970
|
item/id_9_saw.lua
|
item/id_9_saw.lua
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- UPDATE items SET itm_script='item.id_9_saw' WHERE itm_id IN (9);
local sawing = require("craft.intermediate.sawing")
local metal = require("item.general.metal")
local M = {}
M.LookAtItem = metal.LookAtItem
function M.UseItem(User, SourceItem, ltstate)
local _, _, change, willpower, essence, intelligence = string.find(User.lastSpokenText,"(%a+) (%d+) (%d+) (%d+)")
if change == "attributes" then
User:setAttrib("willpower", willpower)
User:setAttrib("essence", essence)
User:setAttrib("intelligence", intelligence)
User:inform("Set willpower, essence, intelligence to")
User:inform(User:increaseAttrib("willpower", 0))
User:inform(User:increaseAttrib("essence", 0))
User:inform(User:increaseAttrib("intelligence", 0))
elseif change == "class" then
User:setMagicType(willpower)
User:inform("class is")
User:inform(User:getMagicType())
end
sawing.sawing:showDialog(User, SourceItem)
end
return M
|
--[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- UPDATE items SET itm_script='item.id_9_saw' WHERE itm_id IN (9);
local sawing = require("craft.intermediate.sawing")
local metal = require("item.general.metal")
local M = {}
M.LookAtItem = metal.LookAtItem
function M.UseItem(User, SourceItem, ltstate)
local _, _, change, willpower, essence, intelligence = string.find(User.lastSpokenText,"(%a+) (%d+) (%d+) (%d+)")
if change == "attributes" then
User:setAttrib("willpower", tonumber(willpower))
User:setAttrib("essence", tonumber(essence))
User:setAttrib("intelligence", tonumber(intelligence))
User:inform("Set willpower, essence, intelligence to")
User:inform(User:increaseAttrib("willpower", 0))
User:inform(User:increaseAttrib("essence", 0))
User:inform(User:increaseAttrib("intelligence", 0))
elseif change == "class" then
User:setMagicType(tonumber(willpower))
User:inform("class is")
User:inform(User:getMagicType())
end
sawing.sawing:showDialog(User, SourceItem)
end
return M
|
Fix test script
|
Fix test script
|
Lua
|
agpl-3.0
|
KayMD/Illarion-Content,Illarion-eV/Illarion-Content,Baylamon/Illarion-Content,vilarion/Illarion-Content
|
c7b1e0f4546c6ad55f0d147abe64c281fa226c55
|
modules/admin-full/luasrc/controller/admin/network.lua
|
modules/admin-full/luasrc/controller/admin/network.lua
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.admin.network", package.seeall)
function index()
require("luci.i18n")
local uci = require("luci.model.uci").cursor()
local i18n = luci.i18n.translate
local page = node("admin", "network")
page.target = alias("admin", "network", "network")
page.title = i18n("network")
page.order = 50
page.index = true
local page = node("admin", "network", "vlan")
page.target = cbi("admin_network/vlan")
page.title = i18n("a_n_switch")
page.order = 20
local page = entry({"admin", "network", "wireless"}, arcombine(template("admin_network/wifi_overview"), cbi("admin_network/wifi")), i18n("wifi"), 15)
page.i18n = "wifi"
page.leaf = true
page.subindex = true
uci:foreach("wireless", "wifi-device",
function (section)
local ifc = section[".name"]
entry({"admin", "network", "wireless", ifc},
true,
ifc:upper()).i18n = "wifi"
end
)
local page = entry({"admin", "network", "wireless_join"}, call("wifi_join"), nil, 16)
page.i18n = "wifi"
page.leaf = true
local page = entry({"admin", "network", "network"}, arcombine(cbi("admin_network/network"), cbi("admin_network/ifaces")), i18n("interfaces", "Schnittstellen"), 10)
page.leaf = true
page.subindex = true
local page = entry({"admin", "network", "add"}, cbi("admin_network/iface_add"), nil)
page.leaf = true
uci:foreach("network", "interface",
function (section)
local ifc = section[".name"]
if ifc ~= "loopback" then
entry({"admin", "network", "network", ifc},
true,
ifc:upper())
end
end
)
local page = node("admin", "network", "dhcp")
page.target = cbi("admin_network/dhcp")
page.title = "DHCP"
page.order = 30
page.subindex = true
entry(
{"admin", "network", "dhcp", "leases"},
cbi("admin_network/dhcpleases"),
i18n("dhcp_leases")
)
local page = node("admin", "network", "hosts")
page.target = cbi("admin_network/hosts")
page.title = i18n("hostnames", "Hostnames")
page.order = 40
local page = node("admin", "network", "routes")
page.target = cbi("admin_network/routes")
page.title = i18n("a_n_routes_static")
page.order = 50
end
function wifi_join()
local function param(x)
return luci.http.formvalue(x)
end
local function ptable(x)
x = param(x)
return x and (type(x) ~= "table" and { x } or x) or {}
end
local dev = param("device")
local ssid = param("join")
if dev and ssid then
local wep = (tonumber(param("wep")) == 1)
local wpa = tonumber(param("wpa_version")) or 0
local channel = tonumber(param("channel"))
local mode = param("mode")
local bssid = param("bssid")
local confirm = (param("confirm") == "1")
local cancel = param("cancel") and true or false
if confirm and not cancel then
local fixed_bssid = (param("fixed_bssid") == "1")
local replace_net = (param("replace_net") == "1")
local autoconnect = (param("autoconnect") == "1")
local attach_intf = param("attach_intf")
local uci = require "luci.model.uci".cursor()
if replace_net then
uci:delete_all("wireless", "wifi-iface")
end
local wificonf = {
device = dev,
mode = (mode == "Ad-Hoc" and "adhoc" or "sta"),
ssid = ssid
}
if attach_intf and uci:get("network", attach_intf, "ifname") then
-- target network already has a interface, make it a bridge
uci:set("network", attach_intf, "type", "bridge")
uci:save("network")
uci:commit("network")
if autoconnect then
require "luci.sys".call("/sbin/ifup " .. attach_intf)
end
end
if fixed_bssid then
wificonf.bssid = bssid
end
if wep then
wificonf.encryption = "wep"
wificonf.key = param("key")
elseif wpa > 0 then
wificonf.encryption = param("wpa_suite")
wificonf.key = param("key")
end
uci:section("wireless", "wifi-iface", nil, wificonf)
uci:delete("wireless", dev, "disabled")
uci:set("wireless", dev, "channel", channel)
uci:save("wireless")
uci:commit("wireless")
if autoconnect then
require "luci.sys".call("/sbin/wifi")
end
luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless", dev))
elseif cancel then
luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless_join?device=" .. dev))
else
luci.template.render("admin_network/wifi_join_settings")
end
else
luci.template.render("admin_network/wifi_join")
end
end
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.admin.network", package.seeall)
function index()
require("luci.i18n")
local uci = require("luci.model.uci").cursor()
local i18n = luci.i18n.translate
local page = node("admin", "network")
page.target = alias("admin", "network", "network")
page.title = i18n("network")
page.order = 50
page.index = true
local page = node("admin", "network", "vlan")
page.target = cbi("admin_network/vlan")
page.title = i18n("a_n_switch")
page.order = 20
local page = entry({"admin", "network", "wireless"}, arcombine(template("admin_network/wifi_overview"), cbi("admin_network/wifi")), i18n("wifi"), 15)
page.i18n = "wifi"
page.leaf = true
page.subindex = true
uci:foreach("wireless", "wifi-device",
function (section)
local ifc = section[".name"]
entry({"admin", "network", "wireless", ifc},
true,
ifc:upper()).i18n = "wifi"
end
)
local page = entry({"admin", "network", "wireless_join"}, call("wifi_join"), nil, 16)
page.i18n = "wifi"
page.leaf = true
local page = entry({"admin", "network", "wireless_delete"}, call("wifi_delete"), nil, 16)
page.i18n = "wifi"
page.leaf = true
local page = entry({"admin", "network", "network"}, arcombine(cbi("admin_network/network"), cbi("admin_network/ifaces")), i18n("interfaces", "Schnittstellen"), 10)
page.leaf = true
page.subindex = true
local page = entry({"admin", "network", "add"}, cbi("admin_network/iface_add"), nil)
page.leaf = true
uci:foreach("network", "interface",
function (section)
local ifc = section[".name"]
if ifc ~= "loopback" then
entry({"admin", "network", "network", ifc},
true,
ifc:upper())
end
end
)
local page = node("admin", "network", "dhcp")
page.target = cbi("admin_network/dhcp")
page.title = "DHCP"
page.order = 30
page.subindex = true
entry(
{"admin", "network", "dhcp", "leases"},
cbi("admin_network/dhcpleases"),
i18n("dhcp_leases")
)
local page = node("admin", "network", "hosts")
page.target = cbi("admin_network/hosts")
page.title = i18n("hostnames", "Hostnames")
page.order = 40
local page = node("admin", "network", "routes")
page.target = cbi("admin_network/routes")
page.title = i18n("a_n_routes_static")
page.order = 50
end
function wifi_join()
local function param(x)
return luci.http.formvalue(x)
end
local function ptable(x)
x = param(x)
return x and (type(x) ~= "table" and { x } or x) or {}
end
local dev = param("device")
local ssid = param("join")
if dev and ssid then
local wep = (tonumber(param("wep")) == 1)
local wpa = tonumber(param("wpa_version")) or 0
local channel = tonumber(param("channel"))
local mode = param("mode")
local bssid = param("bssid")
local confirm = (param("confirm") == "1")
local cancel = param("cancel") and true or false
if confirm and not cancel then
local fixed_bssid = (param("fixed_bssid") == "1")
local replace_net = (param("replace_net") == "1")
local autoconnect = (param("autoconnect") == "1")
local attach_intf = param("attach_intf")
local uci = require "luci.model.uci".cursor()
if replace_net then
uci:delete_all("wireless", "wifi-iface")
end
local wificonf = {
device = dev,
mode = (mode == "Ad-Hoc" and "adhoc" or "sta"),
ssid = ssid
}
if attach_intf and uci:get("network", attach_intf) == "interface" then
-- target network already has a interface, make it a bridge
uci:set("network", attach_intf, "type", "bridge")
uci:save("network")
uci:commit("network")
wificonf.network = attach_intf
if autoconnect then
require "luci.sys".call("/sbin/ifup " .. attach_intf)
end
end
if fixed_bssid then
wificonf.bssid = bssid
end
if wep then
wificonf.encryption = "wep"
wificonf.key = param("key")
elseif wpa > 0 then
wificonf.encryption = param("wpa_suite")
wificonf.key = param("key")
end
local s = uci:section("wireless", "wifi-iface", nil, wificonf)
uci:delete("wireless", dev, "disabled")
uci:set("wireless", dev, "channel", channel)
uci:save("wireless")
uci:commit("wireless")
if autoconnect then
require "luci.sys".call("/sbin/wifi")
end
luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless"))
elseif cancel then
luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless_join?device=" .. dev))
else
luci.template.render("admin_network/wifi_join_settings")
end
else
luci.template.render("admin_network/wifi_join")
end
end
function wifi_delete(network)
local uci = require "luci.model.uci".cursor()
local wlm = require "luci.model.wireless"
wlm.init(uci)
wlm:del_network(network)
uci:save("wireless")
luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless"))
end
|
modules/admin-full: support deleting wireless networks and fix wireless join
|
modules/admin-full: support deleting wireless networks and fix wireless join
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5442 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
|
9dd613a698ab5c79b132fff1486415ad82c7451e
|
lua/entities/gmod_wire_cpu/init.lua
|
lua/entities/gmod_wire_cpu/init.lua
|
if (EmuFox) then
include('gmod_wire_cpu/compiler_asm.lua')
include('gmod_wire_cpu/cpu_bitwise.lua')
include('gmod_wire_cpu/cpu_vm.lua')
include('gmod_wire_cpu/cpu_opcodes.lua')
include('gmod_wire_cpu/cpu_bus.lua')
include('gmod_wire_cpu/cpu_interrupt.lua')
else
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')
include('compiler_asm.lua')
include('cpu_bitwise.lua')
include('cpu_vm.lua')
include('cpu_opcodes.lua')
include('cpu_bus.lua')
include('cpu_interrupt.lua')
end
ENT.WireDebugName = "CPU"
function ENT:Initialize()
self.Entity:PhysicsInit(SOLID_VPHYSICS)
self.Entity:SetMoveType(MOVETYPE_VPHYSICS)
self.Entity:SetSolid(SOLID_VPHYSICS)
self.Inputs = Wire_CreateInputs(self.Entity, { "MemBus", "IOBus", "Frequency", "Clk", "Reset", "NMI"})
self.Outputs = Wire_CreateOutputs(self.Entity, { "Error" })
self.Debug = false //!!!GLOBAL DEBUG MODE SWITCH!!!
//Debug mode is cool. All cool guys use it to debug their programs
//It spams your console with step-by-step description of what your CPU does
self.DebugLines = {}
self.DebugData = {}
self.Memory = {}
self.ROMMemory = {}
self.PrecompileData = {}
self.PrecompileMemory = {}
self.SerialNo = math.floor(math.random()*1000000)
self.UseROM = false
self.Clk = 0
self.InputClk = 0
self.AuxIO = 0
self:Reset()
self.DeltaTime = 0
self.Freq = 2000
self.PrevThinkTime = CurTime()
self.PrevTime = CurTime()
self.SkipIterations = false
self:SetOverlayText("CPU")
self:InitializeOpcodeTable()
self:InitializeLookupTables()
self:InitializeOpcodeRunlevels()
self:InitializeOpcodeNames()
self:InitializeRegisterNames()
self:InitializeOptimizer()
self:InitializeCPUVariableSet()
self:InitializeASMOpcodes()
end
function ENT:CPUID_Version()
//SVN shit doesnt want to work!!
local SVNString = "$Revision: 643 $"
return 900//tonumber(string.sub(SVNString,12,14))
end
function ENT:DebugMessage(msg)
if (self.CPUName) then
Msg(self.CPUName.." ")
end
Msg("===========================================\n")
Msg(msg.."\n")
end
//CPUID
//Value | EAX
//--------------------------------------------
//0 | CPU Version
//1 | RAM Size
//--------------------------------------------
function ENT:RunExecute(Iterations)
while (Iterations > 0) && (self.Clk >= 1.0) && (self.Idle == 0) do
self:Execute()
if (self.SkipIterations == true) then
self.SkipIterations = false
Iterations = Iterations - 30
else
Iterations = Iterations - 1
end
end
//Restore current page for external bus reading
self.CurrentPage = {}
self.CurrentPage.Read = 1
self.CurrentPage.Write = 1
self.CurrentPage.Execute = 1
self.CurrentPage.RunLevel = self.XTRL //External reads have runlevel 1
if (self.Idle == 1) then
self.Idle = 0
end
end//self.Freq
function ENT:Think()
local DeltaTime = CurTime() - self.PrevThinkTime
local Iterations = math.floor(self.Freq*DeltaTime*0.5)
self:RunExecute(Iterations)
self.PrevThinkTime = CurTime()
//Run every tick (or at least attempt to)
if (self.Clk >= 1.0) then self.Entity:NextThink(CurTime()) end
return true
end
//FIXME: remove this:
function ENT:SingleThink()
if (self.Clk >= 1.0) then
self:Execute()
end
//Restore current page for external bus reading
self.CurrentPage = {}
self.CurrentPage.Read = 1
self.CurrentPage.Write = 1
self.CurrentPage.Execute = 1
self.CurrentPage.RunLevel = self.XTRL //External reads have runlevel 1
if (self.Idle == 1) then
self.Idle = 0
end
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
info.UseROM = self.UseROM
info.SerialNo = self.SerialNo
if (self.UseROM) then
info.Memory = {}
for i=0,65535 do
if ((self.ROMMemory[i]) && (self.ROMMemory[i] ~= 0)) then
info.Memory[i] = self.ROMMemory[i]
end
end
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.SerialNo = info.SerialNo
if ((info.UseROM) && (info.UseROM == true)) then
self.UseROM = info.UseROM
self.ROMMemory = {}
for i=0,65535 do
if (info.Memory[i]) then
self.ROMMemory[i] = info.Memory[i]
end
end
self:Reset()
end
end
function ENT:TriggerInput(iname, value)
if (iname == "Clk") then
self.Clk = value
self.InputClk = value
self.PrevTime = CurTime()
self.PrevThinkTime = CurTime()
self.Entity:NextThink(CurTime())
elseif (iname == "Frequency") then
if (not SinglePlayer() && (value > 120000)) then
self.Freq = 120000
return
end
if (value > 0) then
self.Freq = math.floor(value)
end
elseif (iname == "Reset") then
if (value >= 1.0) then
self:Reset()
end
elseif (iname == "NMI") then
if (value >= 32) && (value < 256) then
if (self.Clk >= 1.0) then
self.AuxIO = 0
self:NMIInterrupt(math.floor(value))
self.AuxIO = 1
end
end
end
end
|
if (EmuFox) then
include('gmod_wire_cpu/compiler_asm.lua')
include('gmod_wire_cpu/cpu_bitwise.lua')
include('gmod_wire_cpu/cpu_vm.lua')
include('gmod_wire_cpu/cpu_opcodes.lua')
include('gmod_wire_cpu/cpu_bus.lua')
include('gmod_wire_cpu/cpu_interrupt.lua')
else
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')
include('compiler_asm.lua')
include('cpu_bitwise.lua')
include('cpu_vm.lua')
include('cpu_opcodes.lua')
include('cpu_bus.lua')
include('cpu_interrupt.lua')
end
ENT.WireDebugName = "CPU"
function ENT:Initialize()
self.Entity:PhysicsInit(SOLID_VPHYSICS)
self.Entity:SetMoveType(MOVETYPE_VPHYSICS)
self.Entity:SetSolid(SOLID_VPHYSICS)
self.Inputs = Wire_CreateInputs(self.Entity, { "MemBus", "IOBus", "Frequency", "Clk", "Reset", "NMI"})
self.Outputs = Wire_CreateOutputs(self.Entity, { "Error" })
self.Debug = false //!!!GLOBAL DEBUG MODE SWITCH!!!
//Debug mode is cool. All cool guys use it to debug their programs
//It spams your console with step-by-step description of what your CPU does
self.DebugLines = {}
self.DebugData = {}
self.Memory = {}
self.ROMMemory = {}
self.PrecompileData = {}
self.PrecompileMemory = {}
self.SerialNo = math.floor(math.random()*1000000)
self.UseROM = false
self.Clk = 0
self.InputClk = 0
self.AuxIO = 0
self:Reset()
self.DeltaTime = 0
self.Freq = 2000
self.PrevThinkTime = CurTime()
self.PrevTime = CurTime()
self.SkipIterations = false
self:SetOverlayText("CPU")
self:InitializeOpcodeTable()
self:InitializeLookupTables()
self:InitializeOpcodeRunlevels()
self:InitializeOpcodeNames()
self:InitializeRegisterNames()
self:InitializeOptimizer()
self:InitializeCPUVariableSet()
self:InitializeASMOpcodes()
end
function ENT:CPUID_Version()
//SVN shit doesnt want to work!!
local SVNString = "$Revision: 643 $"
return 990//tonumber(string.sub(SVNString,12,14))
end
function ENT:DebugMessage(msg)
if (self.CPUName) then
Msg(self.CPUName.." ")
end
Msg("===========================================\n")
Msg(msg.."\n")
end
//CPUID
//Value | EAX
//--------------------------------------------
//0 | CPU Version
//1 | RAM Size
//--------------------------------------------
function ENT:RunExecute(Iterations)
while (Iterations > 0) && (self.Clk >= 1.0) && (self.Idle == 0) do
self:Execute()
if (self.SkipIterations == true) then
self.SkipIterations = false
Iterations = Iterations - 30
else
Iterations = Iterations - 1
end
end
//Restore current page for external bus reading
self.CurrentPage = {}
self.CurrentPage.Read = 1
self.CurrentPage.Write = 1
self.CurrentPage.Execute = 1
self.CurrentPage.RunLevel = self.XTRL //External reads have runlevel 1
if (self.Idle == 1) then
self.Idle = 0
end
end//self.Freq
function ENT:Think()
local DeltaTime = CurTime() - self.PrevThinkTime
local Iterations = math.max(1,math.floor(self.Freq*DeltaTime*0.5))
self:RunExecute(Iterations)
self.PrevThinkTime = CurTime()
//Run every tick (or at least attempt to)
if (self.Clk >= 1.0) then self.Entity:NextThink(CurTime()) end
return true
end
//FIXME: remove this:
function ENT:SingleThink()
if (self.Clk >= 1.0) then
self:Execute()
end
//Restore current page for external bus reading
self.CurrentPage = {}
self.CurrentPage.Read = 1
self.CurrentPage.Write = 1
self.CurrentPage.Execute = 1
self.CurrentPage.RunLevel = self.XTRL //External reads have runlevel 1
if (self.Idle == 1) then
self.Idle = 0
end
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
info.UseROM = self.UseROM
info.SerialNo = self.SerialNo
if (self.UseROM) then
info.Memory = {}
for i=0,65535 do
if ((self.ROMMemory[i]) && (self.ROMMemory[i] ~= 0)) then
info.Memory[i] = self.ROMMemory[i]
end
end
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.SerialNo = info.SerialNo
if ((info.UseROM) && (info.UseROM == true)) then
self.UseROM = info.UseROM
self.ROMMemory = {}
for i=0,65535 do
if (info.Memory[i]) then
self.ROMMemory[i] = info.Memory[i]
end
end
self:Reset()
end
end
function ENT:TriggerInput(iname, value)
if (iname == "Clk") then
self.Clk = value
self.InputClk = value
self.PrevTime = CurTime()
self.PrevThinkTime = CurTime()
self.Entity:NextThink(CurTime())
elseif (iname == "Frequency") then
if (not SinglePlayer() && (value > 120000)) then
self.Freq = 120000
return
end
if (value > 0) then
self.Freq = math.floor(value)
end
elseif (iname == "Reset") then
if (self.HWDEBUG ~= 0) then
self.DBGSTATE = math.floor(value)
if (value > 0) and (value <= 1.0) then self:Reset() end
else
if (value >= 1.0) then self:Reset() end
end
elseif (iname == "NMI") then
if (value >= 32) && (value < 256) then
if (self.Clk >= 1.0) then
self.AuxIO = 0
self:NMIInterrupt(math.floor(value))
self.AuxIO = 1
end
end
end
end
|
[FIXED] Added some missing code for the debug mode. [CHANGED] CPU returns CPUID version of 990 now. [FIXED] CPU will now execute AT LEAST 1 opcode every cycle (even if frequency is 1)
|
[FIXED] Added some missing code for the debug mode.
[CHANGED] CPU returns CPUID version of 990 now.
[FIXED] CPU will now execute AT LEAST 1 opcode every cycle (even if frequency is 1)
|
Lua
|
apache-2.0
|
dvdvideo1234/wire,mms92/wire,immibis/wiremod,mitterdoo/wire,bigdogmat/wire,garrysmodlua/wire,Grocel/wire,NezzKryptic/Wire,sammyt291/wire,CaptainPRICE/wire,notcake/wire,rafradek/wire,plinkopenguin/wiremod,Python1320/wire,wiremod/wire,thegrb93/wire
|
43b2514f71686b05217803d592f42f865ba40a0a
|
spec/unit/statics_spec.lua
|
spec/unit/statics_spec.lua
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
local fs = require "luarocks.fs"
describe("Static files", function()
describe("Constants", function()
it("version set in constants should match the one in the rockspec", function()
local rockspec_path
for _, filename in ipairs(fs.list_dir(".")) do
if stringy.endswith(filename, "rockspec") then
rockspec_path = filename
break
end
end
if not rockspec_path then
error("Can't find the rockspec file")
end
local file_content = IO.read_file(rockspec_path)
local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+")
local extracted_version = res:sub(2, res:len() - 1)
assert.are.same(constants.VERSION, extracted_version)
end)
end)
describe("Configuration", function()
it("should parse a correct configuration", function()
local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE)
assert.are.same([[
# Available plugins on this server
plugins_available:
- keyauth
- basicauth
- ratelimiting
- tcplog
- udplog
- filelog
- request_transformer
nginx_working_dir: /usr/local/kong/
proxy_port: 8000
admin_api_port: 8001
# Specify the DAO to use
database: cassandra
# Databases configuration
databases_available:
cassandra:
properties:
hosts: "localhost"
port: 9042
timeout: 1000
keyspace: kong
keepalive: 60000
# Sends anonymous error reports
send_anonymous_reports: true
nginx_plus_status: false
# Cassandra cache configuration
cache:
expiration: 5 # in seconds
nginx: |
worker_processes auto;
error_log logs/error.log info;
daemon on;
# Set "worker_rlimit_nofile" to a high value
# worker_rlimit_nofile 65536;
env KONG_CONF;
events {
# Set "worker_connections" to a high value
worker_connections 1024;
}
http {
resolver 8.8.8.8;
charset UTF-8;
access_log logs/access.log;
access_log on;
# Timeouts
keepalive_timeout 60s;
client_header_timeout 60s;
client_body_timeout 60s;
send_timeout 60s;
# Proxy Settings
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_ssl_server_name on;
# IP Address
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
# Other Settings
client_max_body_size 128m;
underscores_in_headers on;
reset_timedout_connection on;
tcp_nopush on;
################################################
# The following code is required to run Kong #
# Please be careful if you'd like to change it #
################################################
# Lua Settings
lua_package_path ';;';
lua_code_cache on;
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict cache 512m;
init_by_lua '
kong = require "kong"
local status, err = pcall(kong.init)
if not status then
ngx.log(ngx.ERR, "Startup error: "..err)
os.exit(1)
end
';
server {
listen {{proxy_port}};
location / {
default_type 'text/plain';
# This property will be used later by proxy_pass
set $backend_url nil;
# Authenticate the user and load the API info
access_by_lua 'kong.exec_plugins_access()';
# Proxy the request
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass $backend_url;
# Add additional response headers
header_filter_by_lua 'kong.exec_plugins_header_filter()';
# Change the response body
body_filter_by_lua 'kong.exec_plugins_body_filter()';
# Log the request
log_by_lua 'kong.exec_plugins_log()';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
error_page 500 /500.html;
location = /500.html {
internal;
content_by_lua '
local utils = require "kong.tools.utils"
utils.show_error(ngx.status, "Oops, an unexpected error occurred!")
';
}
}
server {
listen {{admin_api_port}};
location / {
default_type application/json;
content_by_lua 'require("lapis").serve("kong.api.app")';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
# Do not remove, additional configuration placeholder for some plugins
# {{additional_configuration}}
}
}
]], configuration)
end)
end)
end)
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
local fs = require "luarocks.fs"
describe("Static files", function()
describe("Constants", function()
it("version set in constants should match the one in the rockspec", function()
local rockspec_path
for _, filename in ipairs(fs.list_dir(".")) do
if stringy.endswith(filename, "rockspec") then
rockspec_path = filename
break
end
end
if not rockspec_path then
error("Can't find the rockspec file")
end
local file_content = IO.read_file(rockspec_path)
local res = file_content:match("\"+[0-9.-]+[a-z]*[0-9-]*\"+")
local extracted_version = res:sub(2, res:len() - 1)
assert.are.same(constants.VERSION, extracted_version)
end)
end)
describe("Configuration", function()
it("should parse a correct configuration", function()
local configuration = IO.read_file(spec_helper.DEFAULT_CONF_FILE)
assert.are.same([[
# Available plugins on this server
plugins_available:
- keyauth
- basicauth
- ratelimiting
- tcplog
- udplog
- filelog
- request_transformer
nginx_working_dir: /usr/local/kong/
proxy_port: 8000
admin_api_port: 8001
# Specify the DAO to use
database: cassandra
# Databases configuration
databases_available:
cassandra:
properties:
hosts: "localhost"
port: 9042
timeout: 1000
keyspace: kong
keepalive: 60000
# Sends anonymous error reports
send_anonymous_reports: true
nginx_plus_status: false
# Cassandra cache configuration
cache:
expiration: 5 # in seconds
nginx: |
worker_processes auto;
error_log logs/error.log info;
daemon on;
# Set "worker_rlimit_nofile" to a high value
# worker_rlimit_nofile 65536;
env KONG_CONF;
events {
# Set "worker_connections" to a high value
worker_connections 1024;
}
http {
resolver 8.8.8.8;
charset UTF-8;
access_log logs/access.log;
access_log on;
# Timeouts
keepalive_timeout 60s;
client_header_timeout 60s;
client_body_timeout 60s;
send_timeout 60s;
# Proxy Settings
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_ssl_server_name on;
# IP Address
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
real_ip_recursive on;
# Other Settings
client_max_body_size 128m;
underscores_in_headers on;
reset_timedout_connection on;
tcp_nopush on;
################################################
# The following code is required to run Kong #
# Please be careful if you'd like to change it #
################################################
# Lua Settings
lua_package_path ';;';
lua_code_cache on;
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict cache 512m;
lua_socket_log_errors off;
init_by_lua '
kong = require "kong"
local status, err = pcall(kong.init)
if not status then
ngx.log(ngx.ERR, "Startup error: "..err)
os.exit(1)
end
';
server {
listen {{proxy_port}};
location / {
default_type 'text/plain';
# This property will be used later by proxy_pass
set $backend_url nil;
# Authenticate the user and load the API info
access_by_lua 'kong.exec_plugins_access()';
# Proxy the request
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass $backend_url;
# Add additional response headers
header_filter_by_lua 'kong.exec_plugins_header_filter()';
# Change the response body
body_filter_by_lua 'kong.exec_plugins_body_filter()';
# Log the request
log_by_lua 'kong.exec_plugins_log()';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
error_page 500 /500.html;
location = /500.html {
internal;
content_by_lua '
local utils = require "kong.tools.utils"
utils.show_error(ngx.status, "Oops, an unexpected error occurred!")
';
}
}
server {
listen {{admin_api_port}};
location / {
default_type application/json;
content_by_lua 'require("lapis").serve("kong.api.app")';
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
# Do not remove, additional configuration placeholder for some plugins
# {{additional_configuration}}
}
}
]], configuration)
end)
end)
end)
|
fix: config test broken by 5c5da4e1e70ceb
|
fix: config test broken by 5c5da4e1e70ceb
|
Lua
|
apache-2.0
|
chourobin/kong,AnsonSmith/kong,wakermahmud/kong,sbuettner/kong,ropik/kong,vmercierfr/kong,ChristopherBiscardi/kong,peterayeni/kong,puug/kong,paritoshmmmec/kong,skynet/kong,bbalu/kong,Skyscanner/kong
|
9dd9ba6340fe8591b673f0f786b8d767da81b891
|
share/lua/sd/metachannels.lua
|
share/lua/sd/metachannels.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="Channels.com" }
end
function search( string )
-- Do the query
query = string.gsub( string, ' ', '+' )
local feed = simplexml.parse_url( "http://www.metachannels.com/api/search?apikey=54868d5d73af69d6afa12d55db6f3d18735baa7d&searchTerms=" .. query )
local channel = feed.children[1]
-- List all answers
local node = vlc.sd.add_node( { path = "", title = string } )
for _,item in ipairs( channel.children ) do
if( item.name == 'item' ) then
simplexml.add_name_maps( item )
local url = string.gsub( item.children_map['link'][1].children[1], '&', '&' )
local arturl = item.children_map['media:thumbnail'][1].attributes['url']
if( arturl == '/images/thumb_channel_default.jpg' ) then
arturl = 'http://www.metachannels.com/images/thumb_channel_default.jpg'
end
node:add_subitem( { path = url,
title = item.children_map['title'][1].children[1],
arturl = arturl } )
end
end
end
function main()
-- get the primary feed and parse the <channel> tag
local feed = simplexml.parse_url( "http://metachannels.com/meta_channels?device=vlc&lang=en,es,fr,de,it,other&format=rss&adult_ok=y" )
local channel = feed.children[1]
-- list all children that are items
for _,item in ipairs( channel.children ) do
if( item.name == 'item' ) then
simplexml.add_name_maps( item )
local url = string.gsub( item.children_map['link'][1].children[1], '&', '&' )
local title = item.children_map['title'][1].children[1]
local arturl = nil
if item.children_map['image'] ~= nil then
arturl = item.children_map['image'][1].children_map['url'][1].children[1]
end
local node = vlc.sd.add_item( { path = url,
title = title,
arturl = arturl } )
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="Channels.com" }
end
function search( string )
-- Do the query
query = string.gsub( string, ' ', '+' )
local feed = simplexml.parse_url( "http://www.metachannels.com/api/search?apikey=54868d5d73af69d6afa12d55db6f3d18735baa7d&searchTerms=" .. query )
local channel = feed.children[1]
-- List all answers
local node = vlc.sd.add_node( { path = "", title = string } )
for _,item in ipairs( channel.children ) do
if( item.name == 'item' ) then
simplexml.add_name_maps( item )
local url = string.gsub( item.children_map['link'][1].children[1], '&', '&' )
local title = item.children_map['title'][1].children[1]
local arturl = nil
if item.children_map['media:thumbnail'] ~= nil then
arturl = item.children_map['media:thumbnail'][1].attributes['url']
if( arturl == '/images/thumb_channel_default.jpg' ) then
arturl = 'http://www.metachannels.com/images/thumb_channel_default.jpg'
end
end
node:add_subitem( { path = url, title = title, arturl = arturl } )
end
end
end
function main()
-- get the primary feed and parse the <channel> tag
local feed = simplexml.parse_url( "http://metachannels.com/meta_channels?device=vlc&lang=en,es,fr,de,it,other&format=rss&adult_ok=y" )
local channel = feed.children[1]
-- list all children that are items
for _,item in ipairs( channel.children ) do
if( item.name == 'item' ) then
simplexml.add_name_maps( item )
local url = string.gsub( item.children_map['link'][1].children[1], '&', '&' )
local title = item.children_map['title'][1].children[1]
local arturl = nil
if item.children_map['image'] ~= nil then
arturl = item.children_map['image'][1].children_map['url'][1].children[1]
end
local node = vlc.sd.add_item( { path = url,
title = title,
arturl = arturl } )
end
end
end
|
metachannels: fix search function too
|
metachannels: fix search function too
|
Lua
|
lgpl-2.1
|
shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,shyamalschandra/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,krichter722/vlc,jomanmuk/vlc-2.2,shyamalschandra/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,vlc-mirror/vlc,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc,krichter722/vlc,xkfz007/vlc
|
4956ef91728c9a8f763dab565f56e439981b122f
|
src/inputobjectutils/src/Client/InputObjectRayUtils.lua
|
src/inputobjectutils/src/Client/InputObjectRayUtils.lua
|
--- Utility functions for constructing rays from input objects
-- @module InputObjectRayUtils
local Workspace = game:GetService("Workspace")
local DEFAULT_RAY_DISTANCE = 1000
local InputObjectRayUtils = {}
function InputObjectRayUtils.cameraRayFromInputObject(inputObject, distance)
assert(inputObject, "Bad inputObject")
return InputObjectRayUtils.cameraRayFromScreenPosition(inputObject.Position, distance)
end
function InputObjectRayUtils.cameraRayFromInputObjectWithOffset(inputObject, distance, offset)
assert(inputObject, "Bad inputObject")
return InputObjectRayUtils.cameraRayFromScreenPosition(inputObject.Position + offset, distance)
end
function InputObjectRayUtils.cameraRayFromScreenPosition(position, distance)
distance = distance or DEFAULT_RAY_DISTANCE
local baseRay = Workspace.CurrentCamera:ScreenPointToRay(position.X, position.Y)
return Ray.new(baseRay.Origin, baseRay.Direction.unit * distance)
end
function InputObjectRayUtils.cameraRayFromViewportPosition(position, distance)
distance = distance or DEFAULT_RAY_DISTANCE
local baseRay = Workspace.CurrentCamera:ViewportPointToRay(position.X, position.Y)
return Ray.new(baseRay.Origin, baseRay.Direction.unit * distance)
end
-- Generates a circle of rays including the center ray
function InputObjectRayUtils.generateCircleRays(ray, count, radius)
local rays = { }
local origin = ray.Origin
local direction = ray.Direction
local cframePointing = CFrame.new(origin, origin + direction)
for i=1, count do
local angle = math.pi*2*(i-1)/count
local offset = cframePointing:vectorToWorldSpace(Vector3.new(
math.cos(angle)*radius,
math.sin(angle)*radius,
0))
table.insert(rays, Ray.new(origin + offset, direction))
end
return rays
end
return InputObjectRayUtils
|
--- Utility functions for constructing rays from input objects
-- @module InputObjectRayUtils
local Workspace = game:GetService("Workspace")
local DEFAULT_RAY_DISTANCE = 1000
local InputObjectRayUtils = {}
function InputObjectRayUtils.cameraRayFromInputObject(inputObject, distance, offset, camera)
assert(inputObject, "Bad inputObject")
offset = offset or Vector3.new()
return InputObjectRayUtils.cameraRayFromScreenPosition(inputObject.Position + offset, distance, camera)
end
function InputObjectRayUtils.cameraRayFromMouse(mouse, distance, offset, camera)
assert(mouse, "Bad mouse")
offset = offset or Vector3.new(0, 0, 0)
return InputObjectRayUtils.cameraRayFromScreenPosition(
Vector2.new(mouse.x + offset.x, mouse.y + offset.y),
distance,
camera)
end
function InputObjectRayUtils.cameraRayFromInputObjectWithOffset(inputObject, distance, offset, camera)
assert(inputObject, "Bad inputObject")
return InputObjectRayUtils.cameraRayFromScreenPosition(
inputObject.Position + offset,
distance,
camera)
end
function InputObjectRayUtils.cameraRayFromScreenPosition(position, distance, camera)
distance = distance or DEFAULT_RAY_DISTANCE
camera = camera or Workspace.CurrentCamera
local baseRay = camera:ScreenPointToRay(position.X, position.Y)
return Ray.new(baseRay.Origin, baseRay.Direction.unit * distance)
end
function InputObjectRayUtils.cameraRayFromViewportPosition(position, distance, camera)
distance = distance or DEFAULT_RAY_DISTANCE
camera = camera or Workspace.CurrentCamera
local baseRay = camera:ViewportPointToRay(position.X, position.Y)
return Ray.new(baseRay.Origin, baseRay.Direction.unit * distance)
end
-- Generates a circle of rays including the center ray
function InputObjectRayUtils.generateCircleRays(ray, count, radius)
local rays = { }
local origin = ray.Origin
local direction = ray.Direction
local cframePointing = CFrame.new(origin, origin + direction)
for i=1, count do
local angle = math.pi*2*(i-1)/count
local offset = cframePointing:vectorToWorldSpace(Vector3.new(
math.cos(angle)*radius,
math.sin(angle)*radius,
0))
table.insert(rays, Ray.new(origin + offset, direction))
end
return rays
end
return InputObjectRayUtils
|
fix: InputObjectRayUtils allows the specification of the camera
|
fix: InputObjectRayUtils allows the specification of the camera
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
da2290031b22b619edbf44a4fd2f897439648b2d
|
scen_edit/command/set_sun_parameters_command.lua
|
scen_edit/command/set_sun_parameters_command.lua
|
SetSunParametersCommand = Command:extends{}
SetSunParametersCommand.className = "SetSunParametersCommand"
function SetSunParametersCommand:init(opts)
self.className = "SetSunParametersCommand"
self.opts = opts
self._execute_unsynced = true
end
function SetSunParametersCommand:execute()
local cmd = WidgetSetSunParametersCommand(self.opts)
SB.commandManager:execute(cmd, true)
end
function SetSunParametersCommand:unexecute()
self.old = {
-- params = {Spring.GetSunParameters()},
params = {gl.GetSun()},
}
if self.opts.startAngle then
Spring.SetSunParameters(self.opts.dirX, self.opts.dirY, self.opts.dirZ,
self.opts.distance, self.opts.startAngle, self.opts.orbitTime)
else
Spring.SetSunDirection(self.opts.dirX, self.opts.dirY, self.opts.dirZ)
end
end
function SetSunParametersCommand:unexecute()
if #self.old.params >= 4 then
Spring.SetSunParameters(self.old.params[1], self.old.params[2], self.old.params[3], self.old.params[4], self.old.params[5], self.old.params[6])
else
Spring.SetSunDirection(self.old.params[1], self.old.params[2], self.old.params[3])
end
end
|
SetSunParametersCommand = Command:extends{}
SetSunParametersCommand.className = "SetSunParametersCommand"
function SetSunParametersCommand:init(opts)
self.className = "SetSunParametersCommand"
self.opts = opts
self._execute_unsynced = true
end
function SetSunParametersCommand:execute()
self.old = {
-- params = {Spring.GetSunParameters()},
params = {gl.GetSun()},
}
Spring.SetSunDirection(self.opts.dirX, self.opts.dirY, self.opts.dirZ)
end
function SetSunParametersCommand:unexecute()
Spring.SetSunDirection(self.old.params[1], self.old.params[2], self.old.params[3])
end
|
fix sun editing
|
fix sun editing
|
Lua
|
mit
|
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
|
8e159a974b6c3fa96dac4d8666f70a807e849a83
|
Learnlist-entry7.lua
|
Learnlist-entry7.lua
|
-- Gli entry dei learnlist di settima generazione
local z = {}
local mw = require('mw')
local txt = require('Wikilib-strings')
local lib = require('Wikilib-learnlists')
local moves = require("Move-data")
local links = require('Links')
-- stab, mossa, notes, tipo, cat, pw, acc, pp, gara, exib, inib
local entry = function(stab, mossa, notes)
local data = moves[string.lower(mossa)]
return lib.categoryentry(stab, mossa, notes, string.fu(data.type), string.fu(data.category), data.power, data.accuracy, data.pp)
end
--Entry per le mosse apprese aumentando di livello
z.level = function(frame)
local p = lib.sanitize(mw.clone(frame.args))
if p[1] == 'Evo' or p[1] == 'Evoluzione' then
p[1] = 'Evo<span class="hidden-xs">luzione</span>'
end
if p[2] == 'Evo' or p[2] == 'Evoluzione' then
p[2] = 'Evo<span class="hidden-xs">luzione</span>'
end
return table.concat{'|-\n', lib.gameslevel(
p[1] or links.tt('—', 'Disponibile solo in Ultrasole e Ultraluna'),
p[2] or links.tt('—', 'Disponibile solo in Sole e Luna')
),
entry(p[5] or '', p[3] or 'Geloraggio', lib.makeNotes(p[4] or ''))}
end
z.Level = z.level
-- It's perfect but for a colspan, so I'll use this because right now I'm in a
-- hurry
z.levelLGPE = z.level
-- Entry per le mosse appprese tramite MT/MN
z.tm = function(frame)
local p = lib.sanitize(mw.clone(frame.args))
return string.interp(table.concat{[=[|-
| style="padding: 0.1em 0.3em;" | <span class="hidden-xs">[[File:${img} ${tipo} VI Sprite Zaino.png]]</span>[[${p1}|<span style="color:#000;">${p1}</span>]]]=],
entry(p[4] or '', p[2] or 'Purogelo', lib.makeNotes(p[3] or ''))},
{
img = string.match(p[1] or 'MT55', '^(M[TN])%d'),
p1 = p[1] or 'MT55',
tipo = string.fu(moves[string.lower(p[2] or 'Purogelo')].type) or 'Sconosciuto'
})
end
z.Tm = z.tm
-- It's perfect, here just to make easier a future update
z.tmLGPE = z.tm
-- Entry per le mosse apprese tramite accoppiamento
z.breed = function(frame)
local p = lib.sanitize(mw.clone(frame.args))
return string.interp(table.concat{[[|-
| style="padding: 0.1em 0.3em;" | ${p1}]],
entry(p[4] or '', p[2] or 'Lanciafiamme', lib.makeNotes(p[3] or '', lib.makeNotes(p[5] or '', lib.makeNotes(p[6] or ''))))},
{
p1 = lib.mslistToModal(p[1] or '', '7', nil, 6)
})
end
z.Breed = z.breed
-- Entry per le mosse apprese tramite esperto mosse
z.tutor = function(frame)
local p = lib.sanitize(mw.clone(frame.args))
return table.concat{lib.tutorgames{{'SL', p[4]}, {'USUL', p[5]}},
' ', entry(p[3] or '',
p[1] or 'Tuono', lib.makeNotes(p[2] or ''))}
end
z.Tutor = z.tutor
-- Entry per le mosse apprese tramite evoluzioni precedenti
z.preevo = function(frame)
local p = lib.sanitize(mw.clone(frame.args))
return table.concat{lib.preevodata(p, '7'), ' ', entry(p[8] or '',
p[7] or 'Scontro', '')}
end
z.Preevo, z.prevo, z.Prevo = z.preevo, z.preevo, z.preevo
-- Entry per le mosse apprese tramite eventi
z.event = function(frame)
local p = lib.sanitize(mw.clone(frame.args))
return string.interp(table.concat{[[|-
| style="padding: 0.1em 0.3em;" | ${p1}${p10}]],
entry(p[4] or '', p[2] or 'Bora', lib.makeNotes(p[3] or ''))},
{
p1 = p[1] or 'Evento',
p10 = lib.makeLevel(p[5])
})
end
z.Event = z.event
-- Entry per i Pokémon che non imparano mosse aumentando di livello
z.levelnull = function(frame)
return lib.entrynull('level', '11')
end
z.Levelnull = z.levenull
-- Entry per i Pokémon che non imparano mosse tramite MT/MN
z.tmnull = function(frame)
return lib.entrynull('tm', '11')
end
z.Tmnull = z.tmnull
-- Entry per i Pokémon che non imparano mosse tramite accoppiamento
z.breednull = function(frame)
return lib.entrynull('breed', '10')
end
z.Breednull = z.breednull
-- Entry per i Pokémon che non imparano mosse dall'esperto mosse
z.tutornull = function(frame)
return lib.entrynull('tutor', '13')
end
z.Tutornull = z.tutornull
-- Entry per i Pokémon che non imparano mosse tramite evoluzioni precedenti
z.preevonull = function(frame)
return lib.entrynull('preevo', '10')
end
z.Preevonull, z.prevonull, z.Prevonull = z.preevonull, z.preevonull, z.preevonull
return z
|
-- Gli entry dei learnlist di settima generazione
local z = {}
local mw = require('mw')
local txt = require('Wikilib-strings')
local lib = require('Wikilib-learnlists')
local moves = require("Move-data")
local links = require('Links')
-- stab, mossa, notes, tipo, cat, pw, acc, pp, gara, exib, inib
local entry = function(stab, mossa, notes)
local data = moves[string.lower(mossa)]
return lib.categoryentry(stab, mossa, notes, string.fu(data.type), string.fu(data.category), data.power, data.accuracy, data.pp)
end
--Entry per le mosse apprese aumentando di livello
z.level = function(frame)
local p = lib.sanitize(mw.clone(frame.args))
if p[1] == 'Evo' or p[1] == 'Evoluzione' then
p[1] = 'Evo<span class="hidden-xs">luzione</span>'
end
if p[2] == 'Evo' or p[2] == 'Evoluzione' then
p[2] = 'Evo<span class="hidden-xs">luzione</span>'
end
return table.concat{'|-\n', lib.gameslevel(
p[1] or links.tt('—', 'Disponibile solo in Ultrasole e Ultraluna'),
p[2] or links.tt('—', 'Disponibile solo in Sole e Luna')
),
entry(p[5] or '', p[3] or 'Geloraggio', lib.makeNotes(p[4] or ''))}
end
z.Level = z.level
-- It's perfect un corno, doesn't work becuase it takes one more parameter
-- Wrapper for level function, adding a "second level"
z.levelLGPE = function(frame)
table.insert(frame.args, 1, frame.args[1])
return z.level(frame)
end
-- Entry per le mosse appprese tramite MT/MN
z.tm = function(frame)
local p = lib.sanitize(mw.clone(frame.args))
return string.interp(table.concat{[=[|-
| style="padding: 0.1em 0.3em;" | <span class="hidden-xs">[[File:${img} ${tipo} VI Sprite Zaino.png]]</span>[[${p1}|<span style="color:#000;">${p1}</span>]]]=],
entry(p[4] or '', p[2] or 'Purogelo', lib.makeNotes(p[3] or ''))},
{
img = string.match(p[1] or 'MT55', '^(M[TN])%d'),
p1 = p[1] or 'MT55',
tipo = string.fu(moves[string.lower(p[2] or 'Purogelo')].type) or 'Sconosciuto'
})
end
z.Tm = z.tm
-- It's perfect, here just to make easier a future update
z.tmLGPE = z.tm
-- Entry per le mosse apprese tramite accoppiamento
z.breed = function(frame)
local p = lib.sanitize(mw.clone(frame.args))
return string.interp(table.concat{[[|-
| style="padding: 0.1em 0.3em;" | ${p1}]],
entry(p[4] or '', p[2] or 'Lanciafiamme', lib.makeNotes(p[3] or '', lib.makeNotes(p[5] or '', lib.makeNotes(p[6] or ''))))},
{
p1 = lib.mslistToModal(p[1] or '', '7', nil, 6)
})
end
z.Breed = z.breed
-- Entry per le mosse apprese tramite esperto mosse
z.tutor = function(frame)
local p = lib.sanitize(mw.clone(frame.args))
return table.concat{lib.tutorgames{{'SL', p[4]}, {'USUL', p[5]}},
' ', entry(p[3] or '',
p[1] or 'Tuono', lib.makeNotes(p[2] or ''))}
end
z.Tutor = z.tutor
-- Entry per le mosse apprese tramite evoluzioni precedenti
z.preevo = function(frame)
local p = lib.sanitize(mw.clone(frame.args))
return table.concat{lib.preevodata(p, '7'), ' ', entry(p[8] or '',
p[7] or 'Scontro', '')}
end
z.Preevo, z.prevo, z.Prevo = z.preevo, z.preevo, z.preevo
-- Entry per le mosse apprese tramite eventi
z.event = function(frame)
local p = lib.sanitize(mw.clone(frame.args))
return string.interp(table.concat{[[|-
| style="padding: 0.1em 0.3em;" | ${p1}${p10}]],
entry(p[4] or '', p[2] or 'Bora', lib.makeNotes(p[3] or ''))},
{
p1 = p[1] or 'Evento',
p10 = lib.makeLevel(p[5])
})
end
z.Event = z.event
-- Entry per i Pokémon che non imparano mosse aumentando di livello
z.levelnull = function(frame)
return lib.entrynull('level', '11')
end
z.Levelnull = z.levenull
-- Entry per i Pokémon che non imparano mosse tramite MT/MN
z.tmnull = function(frame)
return lib.entrynull('tm', '11')
end
z.Tmnull = z.tmnull
-- Entry per i Pokémon che non imparano mosse tramite accoppiamento
z.breednull = function(frame)
return lib.entrynull('breed', '10')
end
z.Breednull = z.breednull
-- Entry per i Pokémon che non imparano mosse dall'esperto mosse
z.tutornull = function(frame)
return lib.entrynull('tutor', '13')
end
z.Tutornull = z.tutornull
-- Entry per i Pokémon che non imparano mosse tramite evoluzioni precedenti
z.preevonull = function(frame)
return lib.entrynull('preevo', '10')
end
z.Preevonull, z.prevonull, z.Prevonull = z.preevonull, z.preevonull, z.preevonull
return z
|
Quick and dirty fix in learnlist/entry7
|
Quick and dirty fix in learnlist/entry7
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
59aee3404fb1d340dda323e8aa194b4203fa8d92
|
spec/02-integration/06_error_handling_spec.lua
|
spec/02-integration/06_error_handling_spec.lua
|
local utils = require "spec.spec_utils"
local cassandra = require "cassandra"
describe("error handling", function()
local _hosts, _shm
setup(function()
_hosts, _shm = utils.ccm_start()
end)
describe("spawn_cluster()", function()
it("should return option errors", function()
local options = require "cassandra.options"
spy.on(options, "parse_cluster")
finally(function()
options.parse_cluster:revert()
end)
local ok, err = cassandra.spawn_cluster()
assert.False(ok)
assert.spy(options.parse_cluster).was.called()
assert.equal("shm is required for spawning a cluster/session", err)
ok, err = cassandra.spawn_cluster {}
assert.False(ok)
assert.equal("shm is required for spawning a cluster/session", err)
ok, err = cassandra.spawn_cluster {shm = ""}
assert.False(ok)
assert.equal("shm must be a valid string", err)
end)
it("should return an error when no contact_point is valid", function()
local contact_points = {"0.0.0.1", "0.0.0.2", "0.0.0.3"}
local ok, err = cassandra.spawn_cluster {
shm = "test",
contact_points = contact_points
}
assert.False(ok)
assert.truthy(string.match(err, "all hosts tried for query failed"))
end)
end)
describe("spawn_session()", function()
it("should return options errors", function()
local options = require "cassandra.options"
spy.on(options, "parse_session")
finally(function()
options.parse_session:revert()
end)
local session, err = cassandra.spawn_session()
assert.falsy(session)
assert.spy(options.parse_session).was.called()
assert.equal("shm is required for spawning a cluster/session", err)
end)
it("should error when spawning a session without contact_points not cluster", function()
local shm = "session_without_cluster_nor_contact_points"
local session, err = cassandra.spawn_session {
shm = shm
}
assert.falsy(session)
assert.equal("option error: options must contain contact_points to spawn session or cluster", err)
end)
end)
describe("execute()", function()
local session
setup(function()
local err
session, err = cassandra.spawn_session {
shm = _shm,
contact_points = _hosts
}
assert.falsy(err)
end)
teardown(function()
session:shutdown()
end)
it("should handle CQL errors", function()
local res, err = session:execute "CAN I HAZ CQL"
assert.falsy(res)
assert.equal("[Syntax error] line 1:0 no viable alternative at input 'CAN' ([CAN]...)", err)
res, err = session:execute "SELECT * FROM system.local WHERE key = ?"
assert.falsy(res)
assert.equal("[Invalid] Invalid amount of bind variables", err)
end)
it("returns the CQL error code", function()
local res, err, cql_code = session:execute "CAN I HAZ CQL"
assert.falsy(res)
assert.equal(cassandra.cql_errors.SYNTAX_ERROR, cql_code)
res, err, cql_code = session:execute "SELECT * FROM system.local WHERE key = ?"
assert.falsy(res)
assert.equal(cassandra.cql_errors.INVALID, cql_code)
end)
end)
describe("shm errors", function()
it("should trigger a cluster refresh if the hosts are not available anymore", function()
local shm = "test_shm_errors"
local cache = require "cassandra.cache"
local dict = cache.get_dict(shm)
assert.is_table(dict)
local ok, err = cassandra.spawn_cluster {
shm = shm,
contact_points = _hosts
}
assert.falsy(err)
assert.True(ok)
assert.is_table(cache.get_hosts(shm))
-- erase hosts from the cache
dict:delete("hosts")
assert.falsy(cache.get_hosts(shm))
-- attempt session create
local session, err = cassandra.spawn_session {
shm = shm,
contact_points = _hosts
}
assert.falsy(err)
-- attempt query
local rows, err = session:execute "SELECT * FROM system.local"
assert.falsy(err)
assert.is_table(rows)
assert.equal(1, #rows)
end)
end)
end)
|
local utils = require "spec.spec_utils"
local cassandra = require "cassandra"
describe("error handling", function()
local _hosts, _shm
setup(function()
_hosts, _shm = utils.ccm_start()
end)
describe("spawn_cluster()", function()
it("should return option errors", function()
local options = require "cassandra.options"
spy.on(options, "parse_cluster")
finally(function()
options.parse_cluster:revert()
end)
local ok, err = cassandra.spawn_cluster()
assert.False(ok)
assert.spy(options.parse_cluster).was.called()
assert.equal("shm is required for spawning a cluster/session", err)
ok, err = cassandra.spawn_cluster {}
assert.False(ok)
assert.equal("shm is required for spawning a cluster/session", err)
ok, err = cassandra.spawn_cluster {shm = ""}
assert.False(ok)
assert.equal("shm must be a valid string", err)
end)
it("should return an error when no contact_point is valid", function()
local contact_points = {"0.0.0.1", "0.0.0.2", "0.0.0.3"}
local ok, err = cassandra.spawn_cluster {
shm = "test",
contact_points = contact_points
}
assert.False(ok)
assert.truthy(string.match(err, "all hosts tried for query failed"))
end)
end)
describe("spawn_session()", function()
it("should return options errors", function()
local options = require "cassandra.options"
spy.on(options, "parse_session")
finally(function()
options.parse_session:revert()
end)
local session, err = cassandra.spawn_session()
assert.falsy(session)
assert.spy(options.parse_session).was.called()
assert.equal("shm is required for spawning a cluster/session", err)
end)
it("should error when spawning a session without contact_points not cluster", function()
local shm = "session_without_cluster_nor_contact_points"
local session, err = cassandra.spawn_session {
shm = shm
}
assert.falsy(session)
assert.equal("option error: options must contain contact_points to spawn session or cluster", err)
end)
end)
describe("execute()", function()
local session
setup(function()
local err
session, err = cassandra.spawn_session {
shm = _shm,
contact_points = _hosts
}
assert.falsy(err)
end)
teardown(function()
session:shutdown()
end)
it("should handle CQL errors", function()
local res, err = session:execute "CAN I HAZ CQL"
assert.falsy(res)
assert.equal("[Syntax error] line 1:0 no viable alternative at input 'CAN' ([CAN]...)", err)
res, err = session:execute "SELECT * FROM system.local WHERE key = ?"
assert.falsy(res)
assert.equal("[Invalid] Invalid amount of bind variables", err)
end)
it("returns the CQL error code", function()
local res, err, cql_code = session:execute "CAN I HAZ CQL"
assert.falsy(res)
assert.truthy(err)
assert.equal(cassandra.cql_errors.SYNTAX_ERROR, cql_code)
res, err, cql_code = session:execute "SELECT * FROM system.local WHERE key = ?"
assert.falsy(res)
assert.truthy(err)
assert.equal(cassandra.cql_errors.INVALID, cql_code)
end)
end)
describe("shm errors", function()
it("should trigger a cluster refresh if the hosts are not available anymore", function()
local shm = "test_shm_errors"
local cache = require "cassandra.cache"
local dict = cache.get_dict(shm)
assert.is_table(dict)
local ok, err = cassandra.spawn_cluster {
shm = shm,
contact_points = _hosts
}
assert.falsy(err)
assert.True(ok)
assert.is_table(cache.get_hosts(shm))
-- erase hosts from the cache
dict:delete("hosts")
assert.falsy(cache.get_hosts(shm))
-- attempt session create
local session, err = cassandra.spawn_session {
shm = shm,
contact_points = _hosts
}
assert.falsy(err)
-- attempt query
local rows, err = session:execute "SELECT * FROM system.local"
assert.falsy(err)
assert.is_table(rows)
assert.equal(1, #rows)
end)
end)
end)
|
fix(lint) unused var in specs
|
fix(lint) unused var in specs
|
Lua
|
mit
|
thibaultCha/lua-cassandra,thibaultCha/lua-cassandra
|
dec09bf5f31ada7b8bef852d55988a99ec34d8b6
|
busted/modules/files/terra.lua
|
busted/modules/files/terra.lua
|
local ret = {}
local ok, terralib = pcall(function() return require 'terralib' end)
local getTrace = function(filename, info)
local index = info.traceback:find('\n%s*%[C]')
info.traceback = info.traceback:sub(1, index)
return info
end
ret.match = function(busted, filename)
if ok then
local path, name, ext = filename:match('(.-)([^\\/\\\\]-%.?([^%.\\/]*))$')
if ext == 't' then
return true
end
end
return false
end
ret.load = function(busted, filename)
local file
local success, err = pcall(function()
file, err = terralib.loadfile(filename)
if not file then
busted.publish({ 'error', 'file' }, filename, nil, nil, err)
end
end)
if not success then
busted.publish({ 'error', 'file' }, filename, nil, nil, err)
end
return file, getTrace
end
return ret
|
local ret = {}
local ok, terralib = pcall(function() return require 'terralib' end)
local getTrace = function(filename, info)
local index = info.traceback:find('\n%s*%[C]')
info.traceback = info.traceback:sub(1, index)
return info
end
ret.match = function(busted, filename)
if ok then
local path, name, ext = filename:match('(.-)([^\\/\\\\]-%.?([^%.\\/]*))$')
if ext == 't' then
return true
end
end
return false
end
ret.load = function(busted, filename)
local file
local success, err = pcall(function()
file, err = terralib.loadfile(filename)
if not file then
busted.publish({ 'error', 'file' }, { descriptor = 'file', name = filename }, nil, err, {})
end
end)
if not success then
busted.publish({ 'error', 'file' }, { descriptor = 'file', name = filename }, nil, err, {})
end
return file, getTrace
end
return ret
|
Fix error message for terra test files
|
Fix error message for terra test files
|
Lua
|
mit
|
o-lim/busted,leafo/busted,DorianGray/busted,nehz/busted,Olivine-Labs/busted,ryanplusplus/busted,sobrinho/busted,mpeterv/busted,xyliuke/busted,istr/busted
|
c68fa1513031450554acfbfff7ac47f55a097bd3
|
src/modules/wms_time_service/wms_time_service.lua
|
src/modules/wms_time_service/wms_time_service.lua
|
local onearth_wms_time_service = {}
local lfs = require "lfs"
local lyaml = require "lyaml"
local request = require "http.request"
local JSON = require "JSON"
local xml = require "pl.xml"
-- Utility functions
local function split(sep, str)
local results = {}
for value in string.gmatch(str, "([^" .. sep .. "]+)") do
results[#results + 1] = value
end
return results
end
local function get_query_param(param, query_string)
if not query_string then
return nil
end
local query_parts = split("&", query_string)
local date_string = nil;
for _, part in pairs(query_parts) do
local query_pair = split("=", part)
if string.lower(query_pair[1]) == param then
return query_pair[2]
end
end
return date_string
end
local function sendErrorResponse(code, locator, msg_string)
local return_msg = '<?xml version="1.0" encoding="UTF-8"?>\n'
return_msg = return_msg .. '<ExceptionReport xmlns="http://www.opengis.net/ows/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemas.opengis.net/ows/1.1.0/owsExceptionReport.xsd" version="1.1.0" xml:lang="en">\n'
return_msg = return_msg .. '<Exception exceptionCode="' .. code .. '" locator="' .. locator .. '">\n'
return_msg = return_msg .. '<ExceptionText>' .. msg_string .. '</ExceptionText></Exception>\n'
return_msg = return_msg .. '</ExceptionReport>\n'
return return_msg,
{
["Content-Type"] = "text/xml"
},
200
end
local function sendResponse(code, msg_string)
return "<html><body>" .. msg_string .. "</body></html>",
{
["Content-Type"] = "text/html"
},
code
end
local function sendResponseRedirect(url)
return url, {
["Location"] = url
},
308
end
local function getTimeServiceOutput(endpointConfig, layer, time)
local dateServiceUri = endpointConfig["time_service_uri"]
local dateServiceKeys = endpointConfig["time_service_keys"]
if dateServiceKeys then
local formattedKeys = {}
for idx, value in ipairs(dateServiceKeys) do
formattedKeys[#formattedKeys + 1] = "key" .. tostring(idx) .. "=" .. value
end
local keyString = table.concat(formattedKeys, "&")
if string.sub(dateServiceUri, -1) ~= "?" then
dateServiceUri = dateServiceUri .. "?"
end
dateServiceUri = dateServiceUri .. keyString
end
dateServiceUri = dateServiceUri .. "&layer=" .. layer .. "&datetime=" .. time
local headers, stream = assert(request.new_from_uri(dateServiceUri):go(5))
local body = assert(stream:get_body_as_string())
if headers:get ":status" ~= "200" then
print("Error contacting date service: " .. body)
return {}
end
local dateList = JSON:decode(body)
return dateList or {}
end
function validate_time(time)
local n = string.len(time)
if n == 10 or n == 20 then
-- Example 1: 2021-09-23
-- Example 2: 2021-09-23T20:05:08Z
local y = tonumber(string.sub(time, 0, 4))
if string.sub(time, 5, 5) ~= '-' then
return false
end
local m = tonumber(string.sub(time, 6, 7))
if string.sub(time, 8, 8) ~= '-' then
return false
end
local d = tonumber(string.sub(time, 9, 10))
if y == nil or y < 0 or m == nil or m < 0 or d == nil or d < 0 then
return false
end
if n == 10 then
return true
end
end
if n == 20 then
if string.sub(time, 11, 11) ~= 'T' then
return false
end
local h = tonumber(string.sub(time, 12, 13))
if string.sub(time, 14, 14) ~= ':' then
return false
end
local m = tonumber(string.sub(time, 15, 16))
if string.sub(time, 17, 17) ~= ':' then
return false
end
local s = tonumber(string.sub(time, 18, 19))
if string.sub(time, 20, 20) ~= 'Z' then
return false
end
if h == nil or h < 0 or m == nil or m < 0 or s == nil or s < 0 then
return false
end
return true
end
return false
end
-- Pass-through all requests to mapserver, except "getmap" requests should append
-- each layer's <layer_name>_PREFIX and <layer_name>_SHAPEFILE variables to URL
function onearth_wms_time_service.handler(endpointConfig)
return function(query_string, headers_in, notes)
local req = get_query_param("request", query_string)
local time_string = get_query_param("time", query_string)
if not req then
return sendResponse(200, 'No REQUEST parameter specified')
end
if time_string then
if validate_time(time_string) == false then
return sendErrorResponse('InvalidParameterValue', 'TIME', 'Invalid time format, must be YYYY-MM-DD or YYYY-MM-DDThh:mm:ssZ')
end
else
time_string = "default"
end
local redirect_url = notes["URI"]:gsub("wms", "mapserver", 1) .. "?" .. query_string
req = req:lower()
if req == "getmap" then
local layers_string = get_query_param("layers", query_string)
local layers_url = ""
if layers_string then
local layers = split(",", layers_string)
for _, layer in pairs(layers) do
local time_service_output = getTimeServiceOutput(endpointConfig, layer, time_string)
if time_service_output["date"] and time_service_output["prefix"] then
local year = string.sub(time_service_output["date"], 0, 4)
layers_url = layers_url .. "&" .. layer .. "_PREFIX=" .. time_service_output["prefix"] .. "%2F" .. year .. "%2F"
end
if time_service_output["filename"] then
layers_url = layers_url .. "&" .. layer .. "_SHAPEFILE=" .. time_service_output["filename"]
end
end
end
redirect_url = redirect_url .. layers_url
end
return sendResponseRedirect(redirect_url)
end
end
if pcall(debug.getlocal, 4, 1) then
return onearth_wms_time_service
else
print("pcall - Call main method here")
end
|
local onearth_wms_time_service = {}
local lfs = require "lfs"
local lyaml = require "lyaml"
local request = require "http.request"
local JSON = require "JSON"
local xml = require "pl.xml"
-- Utility functions
local function split(sep, str)
local results = {}
for value in string.gmatch(str, "([^" .. sep .. "]+)") do
results[#results + 1] = value
end
return results
end
local function get_query_param(param, query_string)
if not query_string then
return nil
end
local query_parts = split("&", query_string)
local date_string = nil;
for _, part in pairs(query_parts) do
local query_pair = split("=", part)
if string.lower(query_pair[1]) == param then
return query_pair[2]
end
end
return date_string
end
local function sendErrorResponse(code, locator, msg_string)
local return_msg = '<?xml version="1.0" encoding="UTF-8"?>\n'
return_msg = return_msg .. '<ExceptionReport xmlns="http://www.opengis.net/ows/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemas.opengis.net/ows/1.1.0/owsExceptionReport.xsd" version="1.1.0" xml:lang="en">\n'
return_msg = return_msg .. '<Exception exceptionCode="' .. code .. '" locator="' .. locator .. '">\n'
return_msg = return_msg .. '<ExceptionText>' .. msg_string .. '</ExceptionText></Exception>\n'
return_msg = return_msg .. '</ExceptionReport>\n'
return return_msg,
{
["Content-Type"] = "text/xml"
},
200
end
local function sendResponse(code, msg_string)
return "<html><body>" .. msg_string .. "</body></html>",
{
["Content-Type"] = "text/html"
},
code
end
local function sendResponseRedirect(url)
return url, {
["Location"] = url
},
308
end
local function getTimeServiceOutput(endpointConfig, layer, time)
local dateServiceUri = endpointConfig["time_service_uri"]
local dateServiceKeys = endpointConfig["time_service_keys"]
if dateServiceKeys then
local formattedKeys = {}
for idx, value in ipairs(dateServiceKeys) do
formattedKeys[#formattedKeys + 1] = "key" .. tostring(idx) .. "=" .. value
end
local keyString = table.concat(formattedKeys, "&")
if string.sub(dateServiceUri, -1) ~= "?" then
dateServiceUri = dateServiceUri .. "?"
end
dateServiceUri = dateServiceUri .. keyString
end
dateServiceUri = dateServiceUri .. "&layer=" .. layer .. "&datetime=" .. time
local headers, stream = assert(request.new_from_uri(dateServiceUri):go(5))
local body = assert(stream:get_body_as_string())
if headers:get ":status" ~= "200" then
print("Error contacting date service: " .. body)
return {}
end
local dateList = JSON:decode(body)
return dateList or {}
end
function validate_time(time)
local n = string.len(time)
if n == 10 or n == 20 then
-- Example 1: 2021-09-23
-- Example 2: 2021-09-23T20:05:08Z
local y = tonumber(string.sub(time, 0, 4))
if string.sub(time, 5, 5) ~= '-' then
return false
end
local m = tonumber(string.sub(time, 6, 7))
if string.sub(time, 8, 8) ~= '-' then
return false
end
local d = tonumber(string.sub(time, 9, 10))
if y == nil or y < 0 or m == nil or m < 0 or d == nil or d < 0 then
return false
end
if n == 10 then
return true
end
end
if n == 20 then
if string.sub(time, 11, 11) ~= 'T' then
return false
end
local h = tonumber(string.sub(time, 12, 13))
if string.sub(time, 14, 14) ~= ':' then
return false
end
local m = tonumber(string.sub(time, 15, 16))
if string.sub(time, 17, 17) ~= ':' then
return false
end
local s = tonumber(string.sub(time, 18, 19))
if string.sub(time, 20, 20) ~= 'Z' then
return false
end
if h == nil or h < 0 or m == nil or m < 0 or s == nil or s < 0 then
return false
end
return true
end
return false
end
-- Pass-through all requests to mapserver, except "getmap" requests should append
-- each layer's <layer_name>_PREFIX and <layer_name>_SHAPEFILE variables to URL
function onearth_wms_time_service.handler(endpointConfig)
return function(query_string, headers_in, notes)
local req = get_query_param("request", query_string)
local time_string = get_query_param("time", query_string)
if not req then
return sendResponse(200, 'No REQUEST parameter specified')
end
if time_string then
if time_string ~= "default" and validate_time(time_string) == false then
return sendErrorResponse("InvalidParameterValue", "TIME", "Invalid time format, must be YYYY-MM-DD or YYYY-MM-DDThh:mm:ssZ")
end
else
time_string = "default"
end
local redirect_url = notes["URI"]:gsub("wms", "mapserver", 1) .. "?" .. query_string
req = req:lower()
if req == "getmap" then
local layers_string = get_query_param("layers", query_string)
local layers_url = ""
if layers_string then
local layers = split(",", layers_string)
for _, layer in pairs(layers) do
local time_service_output = getTimeServiceOutput(endpointConfig, layer, time_string)
if time_service_output["date"] and time_service_output["prefix"] then
local year = string.sub(time_service_output["date"], 0, 4)
layers_url = layers_url .. "&" .. layer .. "_PREFIX=" .. time_service_output["prefix"] .. "%2F" .. year .. "%2F"
end
if time_service_output["filename"] then
layers_url = layers_url .. "&" .. layer .. "_SHAPEFILE=" .. time_service_output["filename"]
end
end
end
redirect_url = redirect_url .. layers_url
end
return sendResponseRedirect(redirect_url)
end
end
if pcall(debug.getlocal, 4, 1) then
return onearth_wms_time_service
else
print("pcall - Call main method here")
end
|
Fixed bug to allow time=default
|
Fixed bug to allow time=default
|
Lua
|
apache-2.0
|
nasa-gibs/onearth,nasa-gibs/onearth,nasa-gibs/onearth,nasa-gibs/onearth,nasa-gibs/onearth,nasa-gibs/onearth
|
ab44d1f7e3336d0a12e0e4cd04178cd9084bd034
|
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{
height = Screen:getHeight(),
width = Screen:getWidth(),
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,
}
function FileChooser:init()
-- 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 _("1 item") or items > 1 and _("%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:refreshPath()
self:swithItemTable(nil, self:genItemTableFromPath(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{
height = Screen:getHeight(),
width = Screen:getWidth(),
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,
}
function FileChooser:init()
-- 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:refreshPath()
self:swithItemTable(nil, self:genItemTableFromPath(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 item number distinction (plural forms)
|
fix item number distinction (plural forms)
|
Lua
|
agpl-3.0
|
houqp/koreader,mihailim/koreader,koreader/koreader,frankyifei/koreader,lgeek/koreader,pazos/koreader,chihyang/koreader,ashang/koreader,mwoz123/koreader,apletnev/koreader,Frenzie/koreader,koreader/koreader,noname007/koreader,Frenzie/koreader,ashhher3/koreader,Markismus/koreader,chrox/koreader,NiLuJe/koreader,Hzj-jie/koreader,poire-z/koreader,robert00s/koreader,NickSavage/koreader,poire-z/koreader,NiLuJe/koreader
|
1049d01dc99c97822bbc833dcf9220b78c633d7b
|
net/http.lua
|
net/http.lua
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local socket = require "socket"
local mime = require "mime"
local url = require "socket.url"
local httpstream_new = require "util.httpstream".new;
local server = require "net.server"
local connlisteners_get = require "net.connlisteners".get;
local listener = connlisteners_get("httpclient") or error("No httpclient listener!");
local t_insert, t_concat = table.insert, table.concat;
local pairs, ipairs = pairs, ipairs;
local tonumber, tostring, xpcall, select, debug_traceback, char, format =
tonumber, tostring, xpcall, select, debug.traceback, string.char, string.format;
local log = require "util.logger".init("http");
module "http"
function urlencode(s) return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end)); end
function urldecode(s) return s and (s:gsub("%%(%x%x)", function (c) return char(tonumber(c,16)); end)); end
local function _formencodepart(s)
return s and (s:gsub("%W", function (c)
if c ~= " " then
return format("%%%02x", c:byte());
else
return "+";
end
end));
end
function formencode(form)
local result = {};
for _, field in ipairs(form) do
t_insert(result, _formencodepart(field.name).."=".._formencodepart(field.value));
end
return t_concat(result, "&");
end
function formdecode(s)
if not s:match("=") then return urldecode(s); end
local r = {};
for k, v in s:gmatch("([^=&]*)=([^&]*)") do
k, v = k:gsub("%+", "%%20"), v:gsub("%+", "%%20");
k, v = urldecode(k), urldecode(v);
t_insert(r, { name = k, value = v });
r[k] = v;
end
return r;
end
local function request_reader(request, data, startpos)
if not request.parser then
if not data then return; end
local function success_cb(r)
if request.callback then
for k,v in pairs(r) do request[k] = v; end
request.callback(r.body, r.code, request);
request.callback = nil;
end
destroy_request(request);
end
local function error_cb(r)
if request.callback then
request.callback(r or "connection-closed", 0, request);
request.callback = nil;
end
destroy_request(request);
end
local function options_cb()
return request;
end
request.parser = httpstream_new(success_cb, error_cb, "client", options_cb);
end
request.parser:feed(data);
end
local function handleerr(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug_traceback()); end
function request(u, ex, callback)
local req = url.parse(u);
if not (req and req.host) then
callback(nil, 0, req);
return nil, "invalid-url";
end
if not req.path then
req.path = "/";
end
local custom_headers, body;
local default_headers = { ["Host"] = req.host, ["User-Agent"] = "Prosody XMPP Server" }
if req.userinfo then
default_headers["Authorization"] = "Basic "..mime.b64(req.userinfo);
end
if ex then
custom_headers = ex.headers;
req.onlystatus = ex.onlystatus;
body = ex.body;
if body then
req.method = "POST ";
default_headers["Content-Length"] = tostring(#body);
default_headers["Content-Type"] = "application/x-www-form-urlencoded";
end
if ex.method then req.method = ex.method; end
end
req.handler, req.conn = server.wrapclient(socket.tcp(), req.host, req.port or 80, listener, "*a");
req.write = function (...) return req.handler:write(...); end
req.conn:settimeout(0);
local ok, err = req.conn:connect(req.host, req.port or 80);
if not ok and err ~= "timeout" then
callback(nil, 0, req);
return nil, err;
end
local request_line = { req.method or "GET", " ", req.path, " HTTP/1.1\r\n" };
if req.query then
t_insert(request_line, 4, "?");
t_insert(request_line, 5, req.query);
end
req.write(t_concat(request_line));
local t = { [2] = ": ", [4] = "\r\n" };
if custom_headers then
for k, v in pairs(custom_headers) do
t[1], t[3] = k, v;
req.write(t_concat(t));
default_headers[k] = nil;
end
end
for k, v in pairs(default_headers) do
t[1], t[3] = k, v;
req.write(t_concat(t));
default_headers[k] = nil;
end
req.write("\r\n");
if body then
req.write(body);
end
req.callback = function (content, code, request) log("debug", "Calling callback, status %s", code or "---"); return select(2, xpcall(function () return callback(content, code, request) end, handleerr)); end
req.reader = request_reader;
req.state = "status";
listener.register_request(req.handler, req);
return req;
end
function destroy_request(request)
if request.conn then
request.conn = nil;
request.handler:close()
listener.ondisconnect(request.handler, "closed");
end
end
_M.urlencode = urlencode;
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local socket = require "socket"
local mime = require "mime"
local url = require "socket.url"
local httpstream_new = require "util.httpstream".new;
local server = require "net.server"
local connlisteners_get = require "net.connlisteners".get;
local listener = connlisteners_get("httpclient") or error("No httpclient listener!");
local t_insert, t_concat = table.insert, table.concat;
local pairs, ipairs = pairs, ipairs;
local tonumber, tostring, xpcall, select, debug_traceback, char, format =
tonumber, tostring, xpcall, select, debug.traceback, string.char, string.format;
local log = require "util.logger".init("http");
module "http"
function urlencode(s) return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end)); end
function urldecode(s) return s and (s:gsub("%%(%x%x)", function (c) return char(tonumber(c,16)); end)); end
local function _formencodepart(s)
return s and (s:gsub("%W", function (c)
if c ~= " " then
return format("%%%02x", c:byte());
else
return "+";
end
end));
end
function formencode(form)
local result = {};
for _, field in ipairs(form) do
t_insert(result, _formencodepart(field.name).."=".._formencodepart(field.value));
end
return t_concat(result, "&");
end
function formdecode(s)
if not s:match("=") then return urldecode(s); end
local r = {};
for k, v in s:gmatch("([^=&]*)=([^&]*)") do
k, v = k:gsub("%+", "%%20"), v:gsub("%+", "%%20");
k, v = urldecode(k), urldecode(v);
t_insert(r, { name = k, value = v });
r[k] = v;
end
return r;
end
local function request_reader(request, data, startpos)
if not request.parser then
if not data then return; end
local function success_cb(r)
if request.callback then
for k,v in pairs(r) do request[k] = v; end
request.callback(r.body, r.code, request);
request.callback = nil;
end
destroy_request(request);
end
local function error_cb(r)
if request.callback then
request.callback(r or "connection-closed", 0, request);
request.callback = nil;
end
destroy_request(request);
end
local function options_cb()
return request;
end
request.parser = httpstream_new(success_cb, error_cb, "client", options_cb);
end
request.parser:feed(data);
end
local function handleerr(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug_traceback()); end
function request(u, ex, callback)
local req = url.parse(u);
if not (req and req.host) then
callback(nil, 0, req);
return nil, "invalid-url";
end
if not req.path then
req.path = "/";
end
local custom_headers, body;
local default_headers = { ["Host"] = req.host, ["User-Agent"] = "Prosody XMPP Server" }
if req.userinfo then
default_headers["Authorization"] = "Basic "..mime.b64(req.userinfo);
end
if ex then
custom_headers = ex.headers;
req.onlystatus = ex.onlystatus;
body = ex.body;
if body then
req.method = "POST ";
default_headers["Content-Length"] = tostring(#body);
default_headers["Content-Type"] = "application/x-www-form-urlencoded";
end
if ex.method then method = ex.method; end
if ex.headers then
for k, v in pairs(ex.headers) do
headers[k] = v;
end
end
end
req.handler, req.conn = server.wrapclient(socket.tcp(), req.host, req.port or 80, listener, "*a");
req.write = function (...) return req.handler:write(...); end
req.conn:settimeout(0);
local ok, err = req.conn:connect(req.host, req.port or 80);
if not ok and err ~= "timeout" then
callback(nil, 0, req);
return nil, err;
end
local request_line = { req.method or "GET", " ", req.path, " HTTP/1.1\r\n" };
if req.query then
t_insert(request_line, 4, "?");
t_insert(request_line, 5, req.query);
end
req.write(t_concat(request_line));
local t = { [2] = ": ", [4] = "\r\n" };
if custom_headers then
for k, v in pairs(custom_headers) do
t[1], t[3] = k, v;
req.write(t_concat(t));
default_headers[k] = nil;
end
end
for k, v in pairs(default_headers) do
t[1], t[3] = k, v;
req.write(t_concat(t));
default_headers[k] = nil;
end
req.write("\r\n");
if body then
req.write(body);
end
req.callback = function (content, code, request) log("debug", "Calling callback, status %s", code or "---"); return select(2, xpcall(function () return callback(content, code, request) end, handleerr)); end
req.reader = request_reader;
req.state = "status";
listener.register_request(req.handler, req);
return req;
end
function destroy_request(request)
if request.conn then
request.conn = nil;
request.handler:close()
listener.ondisconnect(request.handler, "closed");
end
end
_M.urlencode = urlencode;
return _M;
|
net.http: Whitespace fixes
|
net.http: Whitespace fixes
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
438386ef290393dffc34f553c642cac4e8525e07
|
core/portmanager.lua
|
core/portmanager.lua
|
local multitable = require "util.multitable";
local fire_event = prosody.events.fire_event;
--- Config
local default_interfaces = { "*" };
local default_local_interfaces = { "127.0.0.1" };
if config.get("*", "use_ipv6") then
table.insert(default_interfaces, "::");
table.insert(default_local_interfaces, "::1");
end
--- Private state
-- service_name -> { service_info, ... }
local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end });
-- service_name, interface (string), port (number)
local active_services = multitable.new();
--- Private helpers
local function error_to_friendly_message(service_name, port, err)
local friendly_message = err;
if err:match(" in use") then
-- FIXME: Use service_name here
if port == 5222 or port == 5223 or port == 5269 then
friendly_message = "check that Prosody or another XMPP server is "
.."not already running and using this port";
elseif port == 80 or port == 81 then
friendly_message = "check that a HTTP server is not already using "
.."this port";
elseif port == 5280 then
friendly_message = "check that Prosody or a BOSH connection manager "
.."is not already running";
else
friendly_message = "this port is in use by another application";
end
elseif err:match("permission") then
friendly_message = "Prosody does not have sufficient privileges to use this port";
elseif err == "no ssl context" then
if not config.get("*", "core", "ssl") then
friendly_message = "there is no 'ssl' config under Host \"*\" which is "
.."require for legacy SSL ports";
else
friendly_message = "initializing SSL support failed, see previous log entries";
end
end
return friendly_message;
end
module("portmanager", package.seeall);
prosody.events.add_handler("item-added/net-provider", function (event)
local item = event.item;
register_service(item.name, item);
end);
prosody.events.add_handler("item-removed/net-provider", function (event)
local item = event.item;
unregister_service(item.name, item);
end);
--- Public API
function activate_service(service_name)
local service_info = services[service_name][1];
if not service_info then
return nil, "Unknown service: "..service_name;
end
local bind_interfaces = set.new(config.get("*", service_name.."_interfaces")
or config.get("*", service_name.."_interface") -- COMPAT w/pre-0.9
or (service_info.private and default_local_interfaces)
or config.get("*", "interfaces")
or config.get("*", "interface") -- COMPAT w/pre-0.9
or service_info.default_interface -- COMPAT w/pre0.9
or default_interfaces);
local bind_ports = set.new(config.get("*", service_name.."_ports")
or (service_info.multiplex and config.get("*", "ports"))
or service_info.default_ports
or {service_info.default_port});
local listener = service_info.listener;
local mode = listener.default_mode or "*a";
local ssl;
if service_info.encryption == "ssl" then
ssl = prosody.global_ssl_ctx;
if not ssl then
return nil, "global-ssl-context-required";
end
end
for interface in bind_interfaces do
for port in bind_ports do
if not service_info.multiplex and #active_services:search(nil, interface, port) > 0 then
log("error", "Multiple services configured to listen on the same port: %s, %s", table.concat(active_services:search(nil, interface, port), ", "), service_name);
else
local handler, err = server.addserver(interface, port, listener, mode, ssl);
if not handler then
log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err));
else
log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port);
active_services:add(service_name, interface, port, {
server = handler;
service = service_info;
});
end
end
end
end
log("info", "Activated service '%s'", service_name);
return true;
end
function deactivate(service_name)
local active = active_services:search(service_name)[1];
if not active then return; end
for interface, ports in pairs(active) do
for port, active_service in pairs(ports) do
active_service:close();
active_services:remove(service_name, interface, port, active_service);
log("debug", "Removed listening service %s from [%s]:%d", service_name, interface, port);
end
end
log("info", "Deactivated service '%s'", service_name);
end
function register_service(service_name, service_info)
table.insert(services[service_name], service_info);
if not active_services:get(service_name) then
log("debug", "No active service for %s, activating...", service_name);
local ok, err = activate_service(service_name);
if not ok then
log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error");
end
end
fire_event("service-added", { name = service_name, service = service_info });
return true;
end
function unregister_service(service_name, service_info)
local service_info_list = services[service_name];
for i, service in ipairs(service_info_list) do
if service == service_info then
table.remove(service_info_list, i);
end
end
if active_services[service_name] == service_info then
deactivate(service_name);
if #service_info_list > 0 then -- Other services registered with this name
activate(service_name); -- Re-activate with the next available one
end
end
end
function get_service(service_name)
return services[service_name];
end
function get_active_services(...)
return active_services;
end
return _M;
|
local multitable = require "util.multitable";
local fire_event = prosody.events.fire_event;
--- Config
local default_interfaces = { "*" };
local default_local_interfaces = { "127.0.0.1" };
if config.get("*", "use_ipv6") then
table.insert(default_interfaces, "::");
table.insert(default_local_interfaces, "::1");
end
--- Private state
-- service_name -> { service_info, ... }
local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end });
-- service_name, interface (string), port (number)
local active_services = multitable.new();
--- Private helpers
local function error_to_friendly_message(service_name, port, err)
local friendly_message = err;
if err:match(" in use") then
-- FIXME: Use service_name here
if port == 5222 or port == 5223 or port == 5269 then
friendly_message = "check that Prosody or another XMPP server is "
.."not already running and using this port";
elseif port == 80 or port == 81 then
friendly_message = "check that a HTTP server is not already using "
.."this port";
elseif port == 5280 then
friendly_message = "check that Prosody or a BOSH connection manager "
.."is not already running";
else
friendly_message = "this port is in use by another application";
end
elseif err:match("permission") then
friendly_message = "Prosody does not have sufficient privileges to use this port";
elseif err == "no ssl context" then
if not config.get("*", "core", "ssl") then
friendly_message = "there is no 'ssl' config under Host \"*\" which is "
.."require for legacy SSL ports";
else
friendly_message = "initializing SSL support failed, see previous log entries";
end
end
return friendly_message;
end
module("portmanager", package.seeall);
prosody.events.add_handler("item-added/net-provider", function (event)
local item = event.item;
register_service(item.name, item);
end);
prosody.events.add_handler("item-removed/net-provider", function (event)
local item = event.item;
unregister_service(item.name, item);
end);
--- Public API
function activate_service(service_name)
local service_info = services[service_name][1];
if not service_info then
return nil, "Unknown service: "..service_name;
end
local bind_interfaces = set.new(config.get("*", service_name.."_interfaces")
or config.get("*", service_name.."_interface") -- COMPAT w/pre-0.9
or (service_info.private and default_local_interfaces)
or config.get("*", "interfaces")
or config.get("*", "interface") -- COMPAT w/pre-0.9
or service_info.default_interface -- COMPAT w/pre0.9
or default_interfaces);
local bind_ports = set.new(config.get("*", service_name.."_ports")
or (service_info.multiplex and config.get("*", "ports"))
or service_info.default_ports
or {service_info.default_port});
local listener = service_info.listener;
local mode = listener.default_mode or "*a";
local ssl;
if service_info.encryption == "ssl" then
ssl = prosody.global_ssl_ctx;
if not ssl then
return nil, "global-ssl-context-required";
end
end
for interface in bind_interfaces do
for port in bind_ports do
if not service_info.multiplex and #active_services:search(nil, interface, port) > 0 then
log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>");
else
local handler, err = server.addserver(interface, port, listener, mode, ssl);
if not handler then
log("error", "Failed to open server port %d on %s, %s", port, interface, error_to_friendly_message(service_name, port, err));
else
log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port);
active_services:add(service_name, interface, port, {
server = handler;
service = service_info;
});
end
end
end
end
log("info", "Activated service '%s'", service_name);
return true;
end
function deactivate(service_name)
local active = active_services:search(service_name)[1];
if not active then return; end
for interface, ports in pairs(active) do
for port, active_service in pairs(ports) do
active_service:close();
active_services:remove(service_name, interface, port, active_service);
log("debug", "Removed listening service %s from [%s]:%d", service_name, interface, port);
end
end
log("info", "Deactivated service '%s'", service_name);
end
function register_service(service_name, service_info)
table.insert(services[service_name], service_info);
if not active_services:get(service_name) then
log("debug", "No active service for %s, activating...", service_name);
local ok, err = activate_service(service_name);
if not ok then
log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error");
end
end
fire_event("service-added", { name = service_name, service = service_info });
return true;
end
function unregister_service(service_name, service_info)
local service_info_list = services[service_name];
for i, service in ipairs(service_info_list) do
if service == service_info then
table.remove(service_info_list, i);
end
end
if active_services[service_name] == service_info then
deactivate(service_name);
if #service_info_list > 0 then -- Other services registered with this name
activate(service_name); -- Re-activate with the next available one
end
end
end
function get_service(service_name)
return services[service_name];
end
function get_active_services(...)
return active_services;
end
return _M;
|
portmanager: Fix log message when multiple services are configured to use the same port
|
portmanager: Fix log message when multiple services are configured to use the same port
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
1a9b5381c0099469a1c21190fee39b9cb47c4bba
|
libs/core/luasrc/model/wireless.lua
|
libs/core/luasrc/model/wireless.lua
|
--[[
LuCI - Wireless model
Copyright 2009 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local pairs, i18n, uci, math = pairs, luci.i18n, luci.model.uci, math
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.network.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(self, cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local id = "%s.network%d" %{ self.device, count }
ifs[id] = {
id = id,
sid = s['.name'],
count = count
}
local dev = st:get("wireless", s['.name'], "ifname")
or st:get("wireless", s['.name'], "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
ifs[id].winfo = iwi[wtype]
ifs[id].wdev = dev
end
end)
end
function get_device(self, dev)
return device(dev)
end
function get_network(self, id)
if ifs[id] then
return network(ifs[id].sid)
else
local n
for n, _ in pairs(ifs) do
if ifs[n].sid == id then
return network(id)
end
end
end
end
function shortname(self, iface)
if iface.dev and iface.dev.wifi then
return "%s %q" %{
i18n.translate("a_s_if_iwmode_" .. (iface.dev.wifi.mode or "ap")),
iface.dev.wifi.ssid or iface.dev.wifi.bssid or "(hidden)"
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.dev and iface.dev.wifi then
return "%s: %s %q" %{
i18n.translate("a_s_if_wifinet", "Wireless Network"),
i18n.translate("a_s_if_iwmode_" .. (iface.dev.wifi.mode or "ap"), iface.dev.wifi.mode or "AP"),
iface.dev.wifi.ssid or iface.dev.wifi.bssid or "(hidden)"
}
else
return "%s: %q" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
device = ub:section("wifi-device")
device:property("type")
device:property("channel")
device:property("disabled")
function device.name(self)
return self.sid
end
function device.get_networks(self)
local nets = { }
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.device == self:name() then
nets[#nets+1] = network(s['.name'])
end
end)
return nets
end
network = ub:section("wifi-iface")
network:property("mode")
network:property("ssid")
network:property("bssid")
network:property("network")
function network._init(self, sid)
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
return s['.name'] ~= sid
end)
self.id = "%s.network%d" %{ self.device, count }
local dev = st:get("wireless", sid, "ifname")
or st:get("wireless", sid, "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
self.winfo = iwi[wtype]
self.wdev = dev
end
end
function network.name(self)
return self.id
end
function network.ifname(self)
return self.wdev
end
function network.get_device(self)
if self.device then
return device(self.device)
end
end
function network.active_mode(self)
local m = self.winfo and self.winfo.mode(self.wdev)
if m == "Master" or m == "Auto" then
m = "ap"
elseif m == "Ad-Hoc" then
m = "adhoc"
elseif m == "Client" then
m = "sta"
elseif m then
m = m:lower()
else
m = self:mode()
end
return m or "ap"
end
function network.active_mode_i18n(self)
return i18n.translate("a_s_if_iwmode_" .. self:active_mode())
end
function network.active_ssid(self)
return self.winfo and self.winfo.ssid(self.wdev) or
self:ssid()
end
function network.active_bssid(self)
return self.winfo and self.winfo.bssid(self.wdev) or
self:bssid() or "00:00:00:00:00:00"
end
function network.signal(self)
return self.winfo and self.winfo.signal(self.wdev) or 0
end
function network.noise(self)
return self.winfo and self.winfo.noise(self.wdev) or 0
end
function network.signal_level(self)
if self:active_bssid() ~= "00:00:00:00:00:00" then
local signal = self:signal()
local noise = self:noise()
if signal > 0 and noise > 0 then
local snr = -1 * (noise - signal)
return math.floor(snr / 5)
else
return 0
end
else
return -1
end
end
function network.signal_percent(self)
local qc = self.winfo and
self.winfo.quality(self.wdev) or 0
local qm = self.winfo and
self.winfo.quality_max(self.wdev) or 0
if qc > 0 and qm > 0 then
return math.floor((100 / qm) * qc)
else
return 0
end
end
|
--[[
LuCI - Wireless model
Copyright 2009 Jo-Philipp Wich <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local pairs, i18n, uci, math = pairs, luci.i18n, luci.model.uci, math
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local id = "%s.network%d" %{ s.device, count }
ifs[id] = {
id = id,
sid = s['.name'],
count = count
}
local dev = st:get("wireless", s['.name'], "ifname")
or st:get("wireless", s['.name'], "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
ifs[id].winfo = iwi[wtype]
ifs[id].wdev = dev
end
end)
end
function get_device(self, dev)
return device(dev)
end
function get_network(self, id)
if ifs[id] then
return network(ifs[id].sid)
else
local n
for n, _ in pairs(ifs) do
if ifs[n].sid == id then
return network(id)
end
end
end
end
function shortname(self, iface)
if iface.wdev and iface.winfo then
return "%s %q" %{
i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)),
iface:active_ssid() or "(hidden)"
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.wdev and iface.winfo then
return "%s: %s %q (%s)" %{
i18n.translate("a_s_if_wifinet", "Wireless Network"),
i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)),
iface:active_ssid() or "(hidden)", iface.wdev
}
else
return "%s: %q" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
device = ub:section("wifi-device")
device:property("type")
device:property("channel")
device:property("disabled")
function device.name(self)
return self.sid
end
function device.get_networks(self)
local nets = { }
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.device == self:name() then
nets[#nets+1] = network(s['.name'])
end
end)
return nets
end
network = ub:section("wifi-iface")
network:property("mode")
network:property("ssid")
network:property("bssid")
network:property("network")
function network._init(self, sid)
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
return s['.name'] ~= sid
end)
local dev = st:get("wireless", sid, "ifname")
or st:get("wireless", sid, "device")
if dev then
self.id = "%s.network%d" %{ dev, count }
local wtype = iwi.type(dev)
if dev and wtype then
self.winfo = iwi[wtype]
self.wdev = dev
end
end
end
function network.name(self)
return self.id
end
function network.ifname(self)
return self.wdev
end
function network.get_device(self)
if self.device then
return device(self.device)
end
end
function network.active_mode(self)
local m = self.winfo and self.winfo.mode(self.wdev)
if m == "Master" or m == "Auto" then
m = "ap"
elseif m == "Ad-Hoc" then
m = "adhoc"
elseif m == "Client" then
m = "sta"
elseif m then
m = m:lower()
else
m = self:mode()
end
return m or "ap"
end
function network.active_mode_i18n(self)
return i18n.translate("a_s_if_iwmode_" .. self:active_mode())
end
function network.active_ssid(self)
return self.winfo and self.winfo.ssid(self.wdev) or
self:ssid()
end
function network.active_bssid(self)
return self.winfo and self.winfo.bssid(self.wdev) or
self:bssid() or "00:00:00:00:00:00"
end
function network.signal(self)
return self.winfo and self.winfo.signal(self.wdev) or 0
end
function network.noise(self)
return self.winfo and self.winfo.noise(self.wdev) or 0
end
function network.signal_level(self)
if self:active_bssid() ~= "00:00:00:00:00:00" then
local signal = self:signal()
local noise = self:noise()
if signal > 0 and noise > 0 then
local snr = -1 * (noise - signal)
return math.floor(snr / 5)
else
return 0
end
else
return -1
end
end
function network.signal_percent(self)
local qc = self.winfo and
self.winfo.quality(self.wdev) or 0
local qm = self.winfo and
self.winfo.quality_max(self.wdev) or 0
if qc > 0 and qm > 0 then
return math.floor((100 / qm) * qc)
else
return 0
end
end
|
libs/core: fixes luci.model.wireless
|
libs/core: fixes luci.model.wireless
|
Lua
|
apache-2.0
|
cshore/luci,david-xiao/luci,teslamint/luci,dwmw2/luci,oyido/luci,dwmw2/luci,hnyman/luci,palmettos/test,Noltari/luci,bright-things/ionic-luci,tcatm/luci,Wedmer/luci,cappiewu/luci,lcf258/openwrtcn,keyidadi/luci,LuttyYang/luci,aa65535/luci,ReclaimYourPrivacy/cloak-luci,jlopenwrtluci/luci,thess/OpenWrt-luci,981213/luci-1,jlopenwrtluci/luci,fkooman/luci,RedSnake64/openwrt-luci-packages,urueedi/luci,Kyklas/luci-proto-hso,ReclaimYourPrivacy/cloak-luci,keyidadi/luci,sujeet14108/luci,mumuqz/luci,Hostle/openwrt-luci-multi-user,Wedmer/luci,forward619/luci,cshore-firmware/openwrt-luci,thesabbir/luci,tobiaswaldvogel/luci,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,jchuang1977/luci-1,Wedmer/luci,RedSnake64/openwrt-luci-packages,taiha/luci,Sakura-Winkey/LuCI,remakeelectric/luci,forward619/luci,harveyhu2012/luci,deepak78/new-luci,ReclaimYourPrivacy/cloak-luci,maxrio/luci981213,db260179/openwrt-bpi-r1-luci,chris5560/openwrt-luci,mumuqz/luci,ollie27/openwrt_luci,urueedi/luci,cshore-firmware/openwrt-luci,981213/luci-1,cshore-firmware/openwrt-luci,dismantl/luci-0.12,male-puppies/luci,Kyklas/luci-proto-hso,obsy/luci,hnyman/luci,opentechinstitute/luci,hnyman/luci,MinFu/luci,rogerpueyo/luci,keyidadi/luci,cappiewu/luci,keyidadi/luci,thesabbir/luci,daofeng2015/luci,jchuang1977/luci-1,ff94315/luci-1,hnyman/luci,taiha/luci,fkooman/luci,dwmw2/luci,obsy/luci,kuoruan/lede-luci,nmav/luci,palmettos/cnLuCI,palmettos/cnLuCI,artynet/luci,LazyZhu/openwrt-luci-trunk-mod,Sakura-Winkey/LuCI,shangjiyu/luci-with-extra,palmettos/cnLuCI,Wedmer/luci,slayerrensky/luci,joaofvieira/luci,RuiChen1113/luci,zhaoxx063/luci,Hostle/luci,jchuang1977/luci-1,david-xiao/luci,RuiChen1113/luci,remakeelectric/luci,ollie27/openwrt_luci,schidler/ionic-luci,remakeelectric/luci,tobiaswaldvogel/luci,schidler/ionic-luci,harveyhu2012/luci,jorgifumi/luci,dismantl/luci-0.12,ReclaimYourPrivacy/cloak-luci,male-puppies/luci,shangjiyu/luci-with-extra,artynet/luci,RedSnake64/openwrt-luci-packages,marcel-sch/luci,artynet/luci,kuoruan/luci,tcatm/luci,oyido/luci,981213/luci-1,teslamint/luci,florian-shellfire/luci,wongsyrone/luci-1,zhaoxx063/luci,oneru/luci,kuoruan/luci,LazyZhu/openwrt-luci-trunk-mod,david-xiao/luci,palmettos/cnLuCI,Noltari/luci,forward619/luci,dismantl/luci-0.12,wongsyrone/luci-1,wongsyrone/luci-1,thesabbir/luci,jorgifumi/luci,981213/luci-1,nmav/luci,RuiChen1113/luci,rogerpueyo/luci,bittorf/luci,cshore/luci,sujeet14108/luci,zhaoxx063/luci,thess/OpenWrt-luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,ff94315/luci-1,nmav/luci,forward619/luci,LazyZhu/openwrt-luci-trunk-mod,oyido/luci,remakeelectric/luci,shangjiyu/luci-with-extra,oneru/luci,sujeet14108/luci,NeoRaider/luci,jorgifumi/luci,Hostle/openwrt-luci-multi-user,teslamint/luci,keyidadi/luci,shangjiyu/luci-with-extra,male-puppies/luci,wongsyrone/luci-1,wongsyrone/luci-1,jorgifumi/luci,forward619/luci,LazyZhu/openwrt-luci-trunk-mod,joaofvieira/luci,urueedi/luci,cshore/luci,urueedi/luci,urueedi/luci,Hostle/openwrt-luci-multi-user,Noltari/luci,openwrt/luci,slayerrensky/luci,cshore-firmware/openwrt-luci,Hostle/luci,ff94315/luci-1,palmettos/test,nmav/luci,obsy/luci,ReclaimYourPrivacy/cloak-luci,obsy/luci,RedSnake64/openwrt-luci-packages,lbthomsen/openwrt-luci,palmettos/test,ff94315/luci-1,daofeng2015/luci,cappiewu/luci,bright-things/ionic-luci,daofeng2015/luci,chris5560/openwrt-luci,fkooman/luci,oneru/luci,LuttyYang/luci,cappiewu/luci,jchuang1977/luci-1,dwmw2/luci,chris5560/openwrt-luci,Wedmer/luci,florian-shellfire/luci,daofeng2015/luci,lcf258/openwrtcn,Noltari/luci,harveyhu2012/luci,oneru/luci,male-puppies/luci,Noltari/luci,NeoRaider/luci,NeoRaider/luci,aircross/OpenWrt-Firefly-LuCI,male-puppies/luci,fkooman/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,NeoRaider/luci,artynet/luci,cappiewu/luci,rogerpueyo/luci,urueedi/luci,oyido/luci,cappiewu/luci,ollie27/openwrt_luci,hnyman/luci,kuoruan/luci,sujeet14108/luci,cappiewu/luci,deepak78/new-luci,Hostle/luci,thess/OpenWrt-luci,obsy/luci,ollie27/openwrt_luci,aa65535/luci,tobiaswaldvogel/luci,981213/luci-1,nmav/luci,slayerrensky/luci,palmettos/test,cshore/luci,shangjiyu/luci-with-extra,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,aa65535/luci,nwf/openwrt-luci,LuttyYang/luci,joaofvieira/luci,deepak78/new-luci,tcatm/luci,rogerpueyo/luci,openwrt/luci,lbthomsen/openwrt-luci,opentechinstitute/luci,tcatm/luci,rogerpueyo/luci,david-xiao/luci,jorgifumi/luci,male-puppies/luci,oneru/luci,florian-shellfire/luci,harveyhu2012/luci,bright-things/ionic-luci,remakeelectric/luci,aa65535/luci,RuiChen1113/luci,bright-things/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,kuoruan/lede-luci,aa65535/luci,981213/luci-1,Sakura-Winkey/LuCI,marcel-sch/luci,marcel-sch/luci,taiha/luci,thess/OpenWrt-luci,RuiChen1113/luci,opentechinstitute/luci,kuoruan/luci,aa65535/luci,sujeet14108/luci,jchuang1977/luci-1,Wedmer/luci,cshore-firmware/openwrt-luci,slayerrensky/luci,chris5560/openwrt-luci,palmettos/test,LuttyYang/luci,oneru/luci,zhaoxx063/luci,NeoRaider/luci,dwmw2/luci,schidler/ionic-luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,cshore/luci,thess/OpenWrt-luci,cshore/luci,david-xiao/luci,oyido/luci,bittorf/luci,lbthomsen/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,mumuqz/luci,cshore/luci,opentechinstitute/luci,opentechinstitute/luci,Kyklas/luci-proto-hso,thesabbir/luci,ollie27/openwrt_luci,db260179/openwrt-bpi-r1-luci,ollie27/openwrt_luci,hnyman/luci,openwrt/luci,Wedmer/luci,maxrio/luci981213,deepak78/new-luci,bittorf/luci,Wedmer/luci,ReclaimYourPrivacy/cloak-luci,rogerpueyo/luci,david-xiao/luci,kuoruan/lede-luci,Kyklas/luci-proto-hso,dismantl/luci-0.12,wongsyrone/luci-1,mumuqz/luci,marcel-sch/luci,NeoRaider/luci,RedSnake64/openwrt-luci-packages,chris5560/openwrt-luci,daofeng2015/luci,thess/OpenWrt-luci,thess/OpenWrt-luci,aircross/OpenWrt-Firefly-LuCI,kuoruan/luci,Noltari/luci,ff94315/luci-1,opentechinstitute/luci,oneru/luci,dwmw2/luci,bittorf/luci,fkooman/luci,dismantl/luci-0.12,taiha/luci,teslamint/luci,nwf/openwrt-luci,rogerpueyo/luci,kuoruan/lede-luci,fkooman/luci,aa65535/luci,bittorf/luci,fkooman/luci,lbthomsen/openwrt-luci,Hostle/luci,keyidadi/luci,aircross/OpenWrt-Firefly-LuCI,jorgifumi/luci,MinFu/luci,palmettos/cnLuCI,maxrio/luci981213,Kyklas/luci-proto-hso,palmettos/test,forward619/luci,remakeelectric/luci,opentechinstitute/luci,palmettos/test,joaofvieira/luci,RedSnake64/openwrt-luci-packages,deepak78/new-luci,mumuqz/luci,zhaoxx063/luci,nwf/openwrt-luci,tcatm/luci,forward619/luci,Hostle/luci,oyido/luci,teslamint/luci,joaofvieira/luci,artynet/luci,nmav/luci,florian-shellfire/luci,hnyman/luci,openwrt-es/openwrt-luci,palmettos/cnLuCI,opentechinstitute/luci,obsy/luci,marcel-sch/luci,florian-shellfire/luci,dismantl/luci-0.12,lbthomsen/openwrt-luci,NeoRaider/luci,lcf258/openwrtcn,taiha/luci,chris5560/openwrt-luci,harveyhu2012/luci,schidler/ionic-luci,bittorf/luci,aircross/OpenWrt-Firefly-LuCI,Hostle/openwrt-luci-multi-user,wongsyrone/luci-1,shangjiyu/luci-with-extra,db260179/openwrt-bpi-r1-luci,RuiChen1113/luci,openwrt/luci,Noltari/luci,LuttyYang/luci,david-xiao/luci,lcf258/openwrtcn,openwrt/luci,forward619/luci,nmav/luci,lcf258/openwrtcn,cshore-firmware/openwrt-luci,kuoruan/luci,tcatm/luci,joaofvieira/luci,schidler/ionic-luci,marcel-sch/luci,teslamint/luci,jorgifumi/luci,ollie27/openwrt_luci,tcatm/luci,jlopenwrtluci/luci,tcatm/luci,tobiaswaldvogel/luci,palmettos/cnLuCI,hnyman/luci,kuoruan/lede-luci,thesabbir/luci,ff94315/luci-1,nwf/openwrt-luci,lbthomsen/openwrt-luci,schidler/ionic-luci,MinFu/luci,aa65535/luci,sujeet14108/luci,jorgifumi/luci,jlopenwrtluci/luci,nwf/openwrt-luci,lcf258/openwrtcn,male-puppies/luci,jlopenwrtluci/luci,Noltari/luci,slayerrensky/luci,mumuqz/luci,Hostle/luci,harveyhu2012/luci,nwf/openwrt-luci,oyido/luci,openwrt/luci,sujeet14108/luci,joaofvieira/luci,ff94315/luci-1,nmav/luci,david-xiao/luci,Kyklas/luci-proto-hso,schidler/ionic-luci,aircross/OpenWrt-Firefly-LuCI,nwf/openwrt-luci,florian-shellfire/luci,marcel-sch/luci,keyidadi/luci,deepak78/new-luci,lcf258/openwrtcn,thesabbir/luci,remakeelectric/luci,sujeet14108/luci,schidler/ionic-luci,Hostle/luci,openwrt/luci,shangjiyu/luci-with-extra,cshore-firmware/openwrt-luci,taiha/luci,zhaoxx063/luci,taiha/luci,openwrt-es/openwrt-luci,tobiaswaldvogel/luci,deepak78/new-luci,bright-things/ionic-luci,mumuqz/luci,cappiewu/luci,Hostle/openwrt-luci-multi-user,zhaoxx063/luci,urueedi/luci,deepak78/new-luci,rogerpueyo/luci,florian-shellfire/luci,maxrio/luci981213,Sakura-Winkey/LuCI,harveyhu2012/luci,LazyZhu/openwrt-luci-trunk-mod,slayerrensky/luci,openwrt/luci,thesabbir/luci,RuiChen1113/luci,urueedi/luci,LuttyYang/luci,LuttyYang/luci,thess/OpenWrt-luci,dwmw2/luci,artynet/luci,kuoruan/lede-luci,keyidadi/luci,thesabbir/luci,teslamint/luci,nmav/luci,Hostle/luci,palmettos/cnLuCI,RuiChen1113/luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,dismantl/luci-0.12,MinFu/luci,maxrio/luci981213,daofeng2015/luci,chris5560/openwrt-luci,db260179/openwrt-bpi-r1-luci,Kyklas/luci-proto-hso,daofeng2015/luci,fkooman/luci,openwrt-es/openwrt-luci,db260179/openwrt-bpi-r1-luci,palmettos/test,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,openwrt-es/openwrt-luci,marcel-sch/luci,male-puppies/luci,chris5560/openwrt-luci,jchuang1977/luci-1,artynet/luci,MinFu/luci,tobiaswaldvogel/luci,maxrio/luci981213,florian-shellfire/luci,cshore/luci,maxrio/luci981213,Sakura-Winkey/LuCI,jchuang1977/luci-1,slayerrensky/luci,bright-things/ionic-luci,Hostle/openwrt-luci-multi-user,bittorf/luci,mumuqz/luci,NeoRaider/luci,db260179/openwrt-bpi-r1-luci,openwrt-es/openwrt-luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,teslamint/luci,maxrio/luci981213,LuttyYang/luci,oneru/luci,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,db260179/openwrt-bpi-r1-luci,MinFu/luci,lcf258/openwrtcn,daofeng2015/luci,bright-things/ionic-luci,remakeelectric/luci,ff94315/luci-1,zhaoxx063/luci,wongsyrone/luci-1,981213/luci-1,obsy/luci,nwf/openwrt-luci,artynet/luci,artynet/luci,Hostle/openwrt-luci-multi-user,joaofvieira/luci,Sakura-Winkey/LuCI,Noltari/luci,Hostle/openwrt-luci-multi-user,MinFu/luci,Sakura-Winkey/LuCI,dwmw2/luci,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,oyido/luci,slayerrensky/luci,jlopenwrtluci/luci,openwrt-es/openwrt-luci,RedSnake64/openwrt-luci-packages,taiha/luci,MinFu/luci,obsy/luci,jlopenwrtluci/luci,jchuang1977/luci-1,kuoruan/luci,tobiaswaldvogel/luci,lcf258/openwrtcn
|
eebffc3d0afc1d45e5d8e02e18a7887e299be63a
|
game/scripts/vscripts/modules/options/options.lua
|
game/scripts/vscripts/modules/options/options.lua
|
Options = Options or class({})
Options.Values = Options.Values or {}
Options.PreGameVotings = Options.PreGameVotings or {}
function Options:SetValue(name, value)
--if type(value) == "boolean" then value = value and 1 or 0 end
Options.Values[name] = value
PlayerTables:SetTableValue("options", name, value)
end
function Options:SetInitialValue(name, value)
--if type(value) == "boolean" then value = value and 1 or 0 end
if not Options.Values[name] then
Options.Values[name] = value
PlayerTables:SetTableValue("options", name, value)
end
end
function Options:GetValue(name)
return Options.Values[name]
end
function Options:IsEquals(name, value)
--if type(value) == "boolean" then value = value and 1 or 0 end
if value == nil then value = true end
return Options:GetValue(name) == value
end
function Options:SetPreGameVoting(name, variants, default, calculation)
if not Options.PreGameVotings[name] then
Options.PreGameVotings[name] = {votes = {}}
end
if variants then
Options.PreGameVotings[name].variants = variants
end
if default then
Options.PreGameVotings[name].default = default
end
if calculation then
Options.PreGameVotings[name].calculation = calculation
end
PlayerTables:SetTableValue("option_votings", name, Options.PreGameVotings[name])
return Options.PreGameVotings[name]
end
function Options:OnVote(data)
local voteTable = Options.PreGameVotings[data.name]
if table.includes(voteTable.variants, data.vote) then
voteTable.votes[data.PlayerID] = data.vote
CustomGameEventManager:Send_ServerToAllClients("option_votings_refresh", {name = data.name, data = voteTable})
--PlayerTables:SetTableValue("option_votings", data.name, table.deepcopy(voteTable))
end
end
function Options:CalculateVotes()
for voteName, voteData in pairs(Options.PreGameVotings) do
local counts = {}
for player, voted in pairs(voteData.votes) do
counts[voted] = (counts[voted] or 0) + 1
end
if table.count(counts) == 0 then
counts[voteData.default] = 1
end
local calculation = voteData.calculation
if type(calculation) == "function" then
calculation(counts)
elseif type(calculation) == "table" then
local value = counts
local calculationFunction = calculation.calculationFunction
if calculationFunction then
if type(calculationFunction) == "function" then
value = calculationFunction(counts)
elseif calculationFunction == "/" then
local sum = 0
local count = 0
for v, num in pairs(counts) do
sum = sum + v * num
count = count + num
end
value = sum / count
elseif calculationFunction == ">" then
local key, max = next(counts)
for k, v in pairs(counts) do
if v > max then
key, max = k, v
elseif v == max and key ~= k and RollPercentage(50) then --TODO: better chance based roll
key, max = k, v
end
end
value = key
else
error("Unknown calculation function type")
end
end
if calculation.callback then
calculation.callback(value, counts)
end
else
error("Unknown vote type")
end
end
Options.PreGameVotings = {}
end
function Options:LoadDefaultValues()
Options:SetInitialValue("EnableAbilityShop", false)
Options:SetInitialValue("EnableRandomAbilities", false)
Options:SetInitialValue("EnableStatisticsCollection", true)
Options:SetInitialValue("EnableRatingAffection", false)
Options:SetInitialValue("DynamicKillWeight", true)
Options:SetInitialValue("TeamSetupMode", "open")
Options:SetInitialValue("EnableBans", true)
Options:SetInitialValue("CustomTeamColors", false)
Options:SetInitialValue("KillLimit", 0)
--Options:SetInitialValue("MapLayout", "5v5")
Options:SetInitialValue("BanningPhaseBannedPercentage", 0)
Options:SetInitialValue("MainHeroList", "Selection")
--Can be not networkable
Options:SetInitialValue("PreGameTime", 60)
Options:SetPreGameVoting("kill_limit", {100, 125, 150, 175}, 150, {
calculationFunction = "/",
callback = function(value)
Options:SetValue("KillLimit", math.round(value))
end
})
Options:SetPreGameVoting("disable_pauses", {"yes", "no"}, "no", {
calculationFunction = ">",
callback = function(value)
Options:SetValue("EnablePauses", value == "no")
end
})
end
function Options:LoadMapValues()
local mapName = GetMapName()
local underscoreIndex = mapName:find("_")
local landscape = underscoreIndex and mapName:sub(1, underscoreIndex - 1) or mapName
local gamemode = underscoreIndex and mapName:sub(underscoreIndex - #mapName) or ""
if gamemode == "custom_abilities" then
Options:SetValue("MainHeroList", "NoAbilities")
Options:SetValue("EnableAbilityShop", true)
CustomAbilities:PostAbilityShopData()
elseif gamemode == "ranked" then
Options:SetValue("EnableRatingAffection", true)
Options:SetValue("BanningPhaseBannedPercentage", 80)
GameRules:SetCustomGameSetupAutoLaunchDelay(-1)
GameRules:LockCustomGameSetupTeamAssignment(true)
GameRules:EnableCustomGameSetupAutoLaunch(false)
Options:SetValue("TeamSetupMode", "balanced")
Events:Once("AllPlayersLoaded", function()
local playerCount = GetInGamePlayerCount()
local desiredPlayerCount = Teams:GetTotalDesiredPlayerCount()
local failed = not StatsClient.Debug and (matchID == 0 or playerCount < desiredPlayerCount)
if failed then
GameMode:BreakSetup("Not enough players. Ranked games are meant to be full.")
return
end
StatsClient:AssignTeams(function(response)
for i = 0, DOTA_MAX_TEAM_PLAYERS - 1 do
local player = PlayerResource:GetPlayer(i)
if player then player:SetTeam(DOTA_TEAM_NOTEAM) end
end
for team, players in ipairs(response) do
for _, player in ipairs(players) do
local player = PlayerResource:GetPlayer(player)
if player then player:SetTeam(team + 1) end
end
end
GameRules:FinishCustomGameSetup()
end)
end, true)
elseif gamemode == "" then
Options:SetValue("BanningPhaseBannedPercentage", 40)
end
if landscape == "war3" then
MAP_LENGTH = 16384
MAP_BORDER = 128
elseif landscape == "4v4v4v4" then
MAP_LENGTH = 9216
Options:SetValue("CustomTeamColors", true)
elseif landscape == "1v1" then
MAP_LENGTH = 3840
Options:SetValue("DynamicKillWeight", false)
Options:SetPreGameVoting("kill_limit", {10, 15, 20, 25, 30, 35}, 25)
-- Would be pretty annoying for enemy
Options:SetValue("EnableBans", false)
end
end
function Options:LoadCheatValues()
Options:SetValue("EnableBans", false)
end
function Options:LoadToolsValues()
Options:SetInitialValue("PreGameTime", 0)
end
function Options:Preload()
if not PlayerTables:TableExists("options") then PlayerTables:CreateTable("options", {}, AllPlayersInterval) end
if not PlayerTables:TableExists("option_votings") then PlayerTables:CreateTable("option_votings", {}, AllPlayersInterval) end
Options:LoadDefaultValues()
Options:LoadMapValues()
if GameRules:IsCheatMode() then Options:LoadCheatValues() end
if IsInToolsMode() then Options:LoadToolsValues() end
end
|
Options = Options or class({})
Options.Values = Options.Values or {}
Options.PreGameVotings = Options.PreGameVotings or {}
function Options:SetValue(name, value)
--if type(value) == "boolean" then value = value and 1 or 0 end
Options.Values[name] = value
PlayerTables:SetTableValue("options", name, value)
end
function Options:SetInitialValue(name, value)
--if type(value) == "boolean" then value = value and 1 or 0 end
if not Options.Values[name] then
Options.Values[name] = value
PlayerTables:SetTableValue("options", name, value)
end
end
function Options:GetValue(name)
return Options.Values[name]
end
function Options:IsEquals(name, value)
--if type(value) == "boolean" then value = value and 1 or 0 end
if value == nil then value = true end
return Options:GetValue(name) == value
end
function Options:SetPreGameVoting(name, variants, default, calculation)
if not Options.PreGameVotings[name] then
Options.PreGameVotings[name] = {votes = {}}
end
if variants then
Options.PreGameVotings[name].variants = variants
end
if default then
Options.PreGameVotings[name].default = default
end
if calculation then
Options.PreGameVotings[name].calculation = calculation
end
PlayerTables:SetTableValue("option_votings", name, Options.PreGameVotings[name])
return Options.PreGameVotings[name]
end
function Options:OnVote(data)
local voteTable = Options.PreGameVotings[data.name]
if table.includes(voteTable.variants, data.vote) then
voteTable.votes[data.PlayerID] = data.vote
CustomGameEventManager:Send_ServerToAllClients("option_votings_refresh", {name = data.name, data = voteTable})
--PlayerTables:SetTableValue("option_votings", data.name, table.deepcopy(voteTable))
end
end
function Options:CalculateVotes()
for voteName, voteData in pairs(Options.PreGameVotings) do
local counts = {}
for player, voted in pairs(voteData.votes) do
counts[voted] = (counts[voted] or 0) + 1
end
if table.count(counts) == 0 then
counts[voteData.default] = 1
end
local calculation = voteData.calculation
if type(calculation) == "function" then
calculation(counts)
elseif type(calculation) == "table" then
local value = counts
local calculationFunction = calculation.calculationFunction
if calculationFunction then
if type(calculationFunction) == "function" then
value = calculationFunction(counts)
elseif calculationFunction == "/" then
local sum = 0
local count = 0
for v, num in pairs(counts) do
sum = sum + v * num
count = count + num
end
value = sum / count
elseif calculationFunction == ">" then
local key, max = next(counts)
for k, v in pairs(counts) do
if v > max then
key, max = k, v
elseif v == max and key ~= k and RollPercentage(50) then --TODO: better chance based roll
key, max = k, v
end
end
value = key
else
error("Unknown calculation function type")
end
end
if calculation.callback then
calculation.callback(value, counts)
end
else
error("Unknown vote type")
end
end
Options.PreGameVotings = {}
end
function Options:LoadDefaultValues()
Options:SetInitialValue("EnableAbilityShop", false)
Options:SetInitialValue("EnableRandomAbilities", false)
Options:SetInitialValue("EnableStatisticsCollection", true)
Options:SetInitialValue("EnableRatingAffection", false)
Options:SetInitialValue("DynamicKillWeight", true)
Options:SetInitialValue("TeamSetupMode", "open")
Options:SetInitialValue("EnableBans", true)
Options:SetInitialValue("CustomTeamColors", false)
Options:SetInitialValue("KillLimit", 0)
--Options:SetInitialValue("MapLayout", "5v5")
Options:SetInitialValue("BanningPhaseBannedPercentage", 0)
Options:SetInitialValue("MainHeroList", "Selection")
--Can be not networkable
Options:SetInitialValue("PreGameTime", 60)
Options:SetPreGameVoting("kill_limit", {100, 125, 150, 175}, 150, {
calculationFunction = "/",
callback = function(value)
Options:SetValue("KillLimit", math.round(value))
end
})
Options:SetPreGameVoting("disable_pauses", {"yes", "no"}, "no", {
calculationFunction = ">",
callback = function(value)
Options:SetValue("EnablePauses", value == "no")
end
})
end
function Options:LoadMapValues()
local mapName = GetMapName()
local underscoreIndex = mapName:find("_")
local landscape = underscoreIndex and mapName:sub(1, underscoreIndex - 1) or mapName
local gamemode = underscoreIndex and mapName:sub(underscoreIndex - #mapName) or ""
if gamemode == "custom_abilities" then
Options:SetValue("MainHeroList", "NoAbilities")
Options:SetValue("EnableAbilityShop", true)
CustomAbilities:PostAbilityShopData()
elseif gamemode == "ranked" then
Options:SetValue("EnableRatingAffection", true)
Options:SetValue("BanningPhaseBannedPercentage", 80)
GameRules:SetCustomGameSetupAutoLaunchDelay(-1)
GameRules:LockCustomGameSetupTeamAssignment(true)
GameRules:EnableCustomGameSetupAutoLaunch(false)
Options:SetValue("TeamSetupMode", "balanced")
Events:Once("AllPlayersLoaded", function()
local playerCount = GetInGamePlayerCount()
local desiredPlayerCount = Teams:GetTotalDesiredPlayerCount()
local failed = not StatsClient.Debug and (matchID == 0 or playerCount < desiredPlayerCount)
if failed then
GameMode:BreakSetup("Not enough players. Ranked games are meant to be full.")
return
end
StatsClient:AssignTeams(function(response)
for i = 0, DOTA_MAX_TEAM_PLAYERS - 1 do
PlayerResource:SetCustomTeamAssignment(i, DOTA_TEAM_NOTEAM)
end
for team, players in ipairs(response) do
for _, player in ipairs(players) do
PlayerResource:SetCustomTeamAssignment(player, team + 1)
end
end
GameRules:FinishCustomGameSetup()
end)
end, true)
elseif gamemode == "" then
Options:SetValue("BanningPhaseBannedPercentage", 40)
end
if landscape == "war3" then
MAP_LENGTH = 16384
MAP_BORDER = 128
elseif landscape == "4v4v4v4" then
MAP_LENGTH = 9216
Options:SetValue("CustomTeamColors", true)
elseif landscape == "1v1" then
MAP_LENGTH = 3840
Options:SetValue("DynamicKillWeight", false)
Options:SetPreGameVoting("kill_limit", {10, 15, 20, 25, 30, 35}, 25)
-- Would be pretty annoying for enemy
Options:SetValue("EnableBans", false)
end
end
function Options:LoadCheatValues()
Options:SetValue("EnableBans", false)
end
function Options:LoadToolsValues()
Options:SetInitialValue("PreGameTime", 0)
end
function Options:Preload()
if not PlayerTables:TableExists("options") then PlayerTables:CreateTable("options", {}, AllPlayersInterval) end
if not PlayerTables:TableExists("option_votings") then PlayerTables:CreateTable("option_votings", {}, AllPlayersInterval) end
Options:LoadDefaultValues()
Options:LoadMapValues()
if GameRules:IsCheatMode() then Options:LoadCheatValues() end
if IsInToolsMode() then Options:LoadToolsValues() end
end
|
fix: ranked player team reassigning not updates team slots
|
fix: ranked player team reassigning not updates team slots
Fixes #456.
|
Lua
|
mit
|
ark120202/aabs
|
566c49bf314d6b77af07da8e53c91b015aeb5995
|
model/dictionary.lua
|
model/dictionary.lua
|
------------------------------------------------------------------------
--[[ Dictionary ]]--
-- Adapts a nn.LookupTable
-- Works on a WordTensor:context() view.
------------------------------------------------------------------------
local Dictionary, parent = torch.class("dp.Dictionary", "dp.Layer")
Dictionary.isDictionary = true
function Dictionary:__init(config)
assert(type(config) == 'table', "Constructor requires key-value arguments")
local args, dict_size, output_size, typename
= xlua.unpack(
{config},
'Dictionary',
'adapts a nn.LookupTable',
{arg='dict_size', type='number', req=true,
help='Number of entries in the dictionary (e.g. num of words)'},
{arg='output_size', type='number', req=true,
help='Number of neurons per entry.'},
{arg='typename', type='string', default='dictionary',
help='identifies Model type in reports.'}
)
assert(not config.dropout,
"Dictionary doesn't work with dropout")
assert(not config.sparse_init,
"Dictionary doesn't work with sparse_init")
config.sparse_init = false
self._dict_size = dict_size
self._output_size = output_size
self._module = nn.LookupTable(dict_size, output_size)
config.typename = typename
config.input_type = 'torch.IntTensor'
config.tags = config.tags or {}
config.tags['no-maxnorm'] = true
parent.__init(self, config)
end
function Dictionary:_forward(carry)
local activation = self:inputAct()
activation = self._module:forward(activation)
self:outputAct(activation)
return carry
end
function Dictionary:backward(output, carry)
assert(output.isSequenceTensor, "Expecting dp.SequenceTensor output")
self.output.grad = output:shallowClone()
carry = self:_backward(carry) or carry
self.backwarded = true
return self.input.grad, carry
end
function Dictionary:_backward(carry)
local scale = carry.scale
self._report.scale = scale
local output_grad = self:outputGrad()
local input_act = self:inputAct()
self._module:backward(input_act, output_grad, scale)
return carry
end
function Dictionary:inputAct()
return self.input.act:context(self._input_type)
end
function Dictionary:inputGrad()
-- has no input gradient
self.input.grad = nil
end
function Dictionary:outputAct(output_act)
if output_act then
assert(torch.isTensor(output_act))
self.output.act = dp.SequenceTensor{data=output_act}
return
end
return self.output.act:conv1D(self._output_type)
end
function Dictionary:outputGrad()
return self.output.grad:conv1D(self._output_type)
end
function Dictionary:zeroGradParameters()
self._module:zeroGradParameters()
end
function Dictionary:_type(type)
if type == 'torch.FloatTensor' or type == 'torch.DoubleTensor' then
self._output_type = type
self._module:type(type)
elseif type == 'torch.IntTensor' or type == 'torch.LongTensor' then
self._input_type = type
end
return self
end
function Dictionary:reset()
self._module:reset()
end
function Dictionary:parameters()
local params = {}
local module = self._module
if self.forwarded then
-- only return the parameters affected by the forward/backward
for k,nBackward in pairs(module.inputs) do
local kscale = module:scaleUpdateByKey(k)
params[k] = {
param = module.weight:select(1, k),
grad = module.gradWeight:select(1, k),
learn_scale = module:scaleUpdateByKey(k)
}
end
else
params.weight = { param=module.weight, grad=module.gradWeight }
end
return params
end
function Dictionary:share(dict, ...)
assert(dict.isDictionary)
return parent.share(self, dict, ...)
end
function Dictionary:sharedClone()
local clone = torch.protoClone(self, {
dict_size = 1, output_size = 1, typename=self._typename,
gather_stats=self._gather_stats,
input_type=self._input_type, output_type=self._output_type,
module_type=self._module_type, mvstate=self.mvstate
})
clone._dict_size = self._dict_size
clone._output_size = self._output_size
clone._module.gradWeight:resizeAs(self._module.gradWeight)
clone._module.batchSize = self._module.batchSize
return self:share(clone, 'weight')
end
function Dictionary:paramModule()
return self._module
end
|
------------------------------------------------------------------------
--[[ Dictionary ]]--
-- Adapts a nn.LookupTable
-- Works on a WordTensor:context() view.
------------------------------------------------------------------------
local Dictionary, parent = torch.class("dp.Dictionary", "dp.Layer")
Dictionary.isDictionary = true
function Dictionary:__init(config)
assert(type(config) == 'table', "Constructor requires key-value arguments")
local args, dict_size, output_size, typename
= xlua.unpack(
{config},
'Dictionary',
'adapts a nn.LookupTable',
{arg='dict_size', type='number', req=true,
help='Number of entries in the dictionary (e.g. num of words)'},
{arg='output_size', type='number', req=true,
help='Number of neurons per entry.'},
{arg='typename', type='string', default='dictionary',
help='identifies Model type in reports.'}
)
assert(not config.dropout,
"Dictionary doesn't work with dropout")
assert(not config.sparse_init,
"Dictionary doesn't work with sparse_init")
config.sparse_init = false
self._dict_size = dict_size
self._output_size = output_size
self._module = nn.LookupTable(dict_size, output_size)
config.typename = typename
config.input_type = 'torch.IntTensor'
config.tags = config.tags or {}
config.tags['no-maxnorm'] = true
parent.__init(self, config)
end
function Dictionary:_forward(carry)
local activation = self:inputAct()
activation = self._module:forward(activation)
self:outputAct(activation)
return carry
end
function Dictionary:backward(output, carry)
assert(output.isSequenceTensor, "Expecting dp.SequenceTensor output")
self.output.grad = output:shallowClone()
carry = self:_backward(carry) or carry
self.backwarded = true
return self.input.grad, carry
end
function Dictionary:_backward(carry)
local scale = carry.scale
self._report.scale = scale
local output_grad = self:outputGrad()
local input_act = self:inputAct()
self._module:backward(input_act, output_grad, scale)
return carry
end
function Dictionary:inputAct()
return self.input.act:context(self._input_type)
end
function Dictionary:inputGrad()
-- has no input gradient
self.input.grad = nil
end
function Dictionary:outputAct(output_act)
if output_act then
assert(torch.isTensor(output_act))
self.output.act = dp.SequenceTensor{data=output_act}
return
end
return self.output.act:conv1D(self._output_type)
end
function Dictionary:outputGrad()
return self.output.grad:conv1D(self._output_type)
end
function Dictionary:zeroGradParameters()
self._module:zeroGradParameters()
end
function Dictionary:_type(type)
self._module:type(type)
if type == 'torch.FloatTensor' or type == 'torch.DoubleTensor' or type == 'torch.CudaTensor' then
self._output_type = type
elseif type == 'torch.IntTensor' or type == 'torch.LongTensor' then
self._input_type = type
end
return self
end
function Dictionary:reset()
self._module:reset()
end
function Dictionary:parameters()
local params = {}
local module = self._module
if self.forwarded then
-- only return the parameters affected by the forward/backward
for k,nBackward in pairs(module.inputs) do
local kscale = module:scaleUpdateByKey(k)
params[k] = {
param = module.weight:select(1, k),
grad = module.gradWeight:select(1, k),
learn_scale = module:scaleUpdateByKey(k)
}
end
else
params.weight = { param=module.weight, grad=module.gradWeight }
end
return params
end
function Dictionary:share(dict, ...)
assert(dict.isDictionary)
return parent.share(self, dict, ...)
end
function Dictionary:sharedClone()
local clone = torch.protoClone(self, {
dict_size = 1, output_size = 1, typename=self._typename,
gather_stats=self._gather_stats,
input_type=self._input_type, output_type=self._output_type,
module_type=self._module_type, mvstate=self.mvstate
})
clone._dict_size = self._dict_size
clone._output_size = self._output_size
clone._module.gradWeight:resizeAs(self._module.gradWeight)
clone._module.batchSize = self._module.batchSize
return self:share(clone, 'weight')
end
function Dictionary:paramModule()
return self._module
end
|
fixed dp.Dictionary
|
fixed dp.Dictionary
|
Lua
|
bsd-3-clause
|
eulerreich/dp,fiskio/dp,kracwarlock/dp,jnhwkim/dp,nicholas-leonard/dp,sagarwaghmare69/dp,rickyHong/dptorchLib
|
748451fe8076376b6faafbae762583e37ca3e52a
|
nvim/lua/plugins.lua
|
nvim/lua/plugins.lua
|
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd')
local g = vim.g -- a table to access global variables
cmd([[packadd packer.nvim]])
return require('packer').startup(function()
-- plugin management
use('wbthomason/packer.nvim')
-- treesitter (LSP)
use({ 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' })
use('nvim-treesitter/playground')
-- LSP config
use({
'neovim/nvim-lspconfig',
'williamboman/nvim-lsp-installer',
})
-- show signature while typing
use('ray-x/lsp_signature.nvim')
-- faster than built-in filetype.vim (might go to core at some point)
use('nathom/filetype.nvim')
-- buffer/tab line
use({
'akinsho/bufferline.nvim',
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require('bufferline').setup({
options = {
offsets = {
{
filetype = 'NvimTree',
text = '',
padding = 1,
text_align = 'right',
},
},
},
})
end,
})
-- completion and snippets
use({
'rafamadriz/friendly-snippets',
event = 'InsertEnter',
})
use({
'hrsh7th/nvim-cmp',
})
use({
'L3MON4D3/LuaSnip',
wants = 'friendly-snippets',
})
use({
'saadparwaiz1/cmp_luasnip',
})
use({
'hrsh7th/cmp-nvim-lua',
})
use({
'hrsh7th/cmp-nvim-lsp',
})
use({
'hrsh7th/cmp-buffer',
})
use({
'folke/trouble.nvim',
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require('trouble').setup({
-- your configuration comes here
-- or leave it empty to use the default settings
-- refer to the configuration section below
})
end,
})
-- footer support
-- NOTE: using fork for now - original is hoob3rt/lualine.nvim
use({
'nvim-lualine/lualine.nvim',
requires = { 'kyazdani42/nvim-web-devicons', opt = true },
})
-- highlight TODOs
use({
'folke/todo-comments.nvim',
requires = 'nvim-lua/plenary.nvim',
config = function()
require('todo-comments').setup()
end,
})
-- pane showing symbols
use('simrat39/symbols-outline.nvim')
-- scrollbar in terminal
use('dstein64/nvim-scrollview')
-- toggle terminal
use({
'akinsho/toggleterm.nvim',
config = function()
require('toggleterm').setup({
-- size can be a number or function which is passed the current terminal
size = 20,
-- open_mapping = [[<c-\>]],
open_mapping = [[<c-t>]],
hide_numbers = true, -- hide the number column in toggleterm buffers
shade_terminals = true,
start_in_insert = true,
insert_mappings = true, -- whether or not the open mapping applies in insert mode
persist_size = false,
direction = 'float',
close_on_exit = true, -- close the terminal window when the process exits
shell = 'fish', -- change the default shell
-- This field is only relevant if direction is set to 'float'
float_opts = {
-- The border key is *almost* the same as 'nvim_open_win'
-- see :h nvim_open_win for details on borders however
-- the 'curved' border is a custom border type
-- not natively supported but implemented in this plugin.
border = 'curved',
winblend = 3,
highlights = {
border = 'Normal',
background = 'Normal',
},
},
})
end,
})
-- which key plugin
use('folke/which-key.nvim')
-- like nerd tree
use({
'kyazdani42/nvim-tree.lua',
cmd = { 'NvimTreeToggle', 'NvimTreeFocus' },
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require('nvim-tree').setup({
view = {
side = 'right',
},
})
end,
})
-- close buffers without messing up window layout
use('moll/vim-bbye')
use('editorconfig/editorconfig-vim')
-- ident lines
use('lukas-reineke/indent-blankline.nvim')
-- autopairs
use({
'windwp/nvim-autopairs',
config = function()
require('nvim-autopairs').setup()
end,
})
-- s plus motion to jump around (like vim-sneak)
use('ggandor/lightspeed.nvim')
-- colorizer
use({
'norcalli/nvim-colorizer.lua',
config = function()
require('colorizer').setup()
end,
})
-- find files, buffers, etc.
use({
'nvim-telescope/telescope.nvim',
requires = { { 'nvim-lua/popup.nvim' }, { 'nvim-lua/plenary.nvim' } },
module_patterns = 'telescope*',
})
-- use fzf-native matcher instead
use({ 'nvim-telescope/telescope-fzf-native.nvim', run = 'make' })
-- commenting code
use({
'numToStr/Comment.nvim',
config = function()
require('Comment').setup()
end,
})
-- notifications
use({
'rcarriga/nvim-notify',
config = function()
vim.notify = require('notify')
end,
})
-- git support
use({
'TimUntersberger/neogit',
requires = 'nvim-lua/plenary.nvim',
config = function()
require('neogit').setup({})
end,
})
-- git signs
use({
'lewis6991/gitsigns.nvim',
requires = {
'nvim-lua/plenary.nvim',
},
config = function()
require('gitsigns').setup()
end,
})
-- logging
use('tjdevries/vlog.nvim')
-- surround motion
use('tpope/vim-surround')
-- most recently used
use('yegappan/mru')
use({
'jose-elias-alvarez/null-ls.nvim',
config = function()
local null_ls = require('null-ls')
local sources = {
null_ls.builtins.formatting.prettier,
null_ls.builtins.formatting.rustfmt,
null_ls.builtins.formatting.stylelint,
null_ls.builtins.formatting.stylua,
null_ls.builtins.diagnostics.cspell,
null_ls.builtins.diagnostics.eslint,
null_ls.builtins.diagnostics.luacheck,
null_ls.builtins.diagnostics.proselint,
}
null_ls.config({
sources = sources,
})
require('lspconfig')['null-ls'].setup({
on_attach = function(client)
if client.resolved_capabilities.document_formatting then
vim.cmd('autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()')
end
end,
})
end,
requires = { 'nvim-lua/plenary.nvim', 'neovim/nvim-lspconfig' },
})
-- search for visually selected text
use('bronson/vim-visual-star-search')
-- rainbow parens
use('p00f/nvim-ts-rainbow')
-- colors
use('fatih/molokai')
use('altercation/vim-colors-solarized')
use('NLKNguyen/papercolor-theme')
use('navarasu/onedark.nvim')
end)
|
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd')
local g = vim.g -- a table to access global variables
cmd([[packadd packer.nvim]])
return require('packer').startup(function()
-- plugin management
use('wbthomason/packer.nvim')
-- treesitter (LSP)
use({ 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' })
use('nvim-treesitter/playground')
-- LSP config
use({
'neovim/nvim-lspconfig',
'williamboman/nvim-lsp-installer',
})
-- show signature while typing
use('ray-x/lsp_signature.nvim')
-- faster than built-in filetype.vim (might go to core at some point)
use('nathom/filetype.nvim')
-- buffer/tab line
use({
'akinsho/bufferline.nvim',
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require('bufferline').setup({
options = {
offsets = {
{
filetype = 'NvimTree',
text = '',
padding = 1,
text_align = 'right',
},
},
},
})
end,
})
-- completion and snippets
use({
'rafamadriz/friendly-snippets',
event = 'InsertEnter',
})
use({
'hrsh7th/nvim-cmp',
})
use({
'L3MON4D3/LuaSnip',
wants = 'friendly-snippets',
})
use({
'saadparwaiz1/cmp_luasnip',
})
use({
'hrsh7th/cmp-nvim-lua',
})
use({
'hrsh7th/cmp-nvim-lsp',
})
use({
'hrsh7th/cmp-buffer',
})
use({
'folke/trouble.nvim',
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require('trouble').setup({
-- your configuration comes here
-- or leave it empty to use the default settings
-- refer to the configuration section below
})
end,
})
-- footer support
-- NOTE: using fork for now - original is hoob3rt/lualine.nvim
use({
'nvim-lualine/lualine.nvim',
requires = { 'kyazdani42/nvim-web-devicons', opt = true },
})
-- highlight TODOs
use({
'folke/todo-comments.nvim',
requires = 'nvim-lua/plenary.nvim',
config = function()
require('todo-comments').setup()
end,
})
-- pane showing symbols
use('simrat39/symbols-outline.nvim')
-- scrollbar in terminal
use('dstein64/nvim-scrollview')
-- toggle terminal
use({
'akinsho/toggleterm.nvim',
config = function()
require('toggleterm').setup({
-- size can be a number or function which is passed the current terminal
size = 20,
-- open_mapping = [[<c-\>]],
open_mapping = [[<c-t>]],
hide_numbers = true, -- hide the number column in toggleterm buffers
start_in_insert = true,
insert_mappings = true, -- whether or not the open mapping applies in insert mode
persist_size = false,
direction = 'horizontal',
close_on_exit = true, -- close the terminal window when the process exits
shell = 'fish', -- change the default shell
-- This field is only relevant if direction is set to 'float'
float_opts = {
-- The border key is *almost* the same as 'nvim_open_win'
-- see :h nvim_open_win for details on borders however
-- the 'curved' border is a custom border type
-- not natively supported but implemented in this plugin.
border = 'curved',
winblend = 3,
highlights = {
border = 'Normal',
background = 'Normal',
},
},
})
end,
})
-- which key plugin
use('folke/which-key.nvim')
-- like nerd tree
use({
'kyazdani42/nvim-tree.lua',
cmd = { 'NvimTreeToggle', 'NvimTreeFocus' },
requires = 'kyazdani42/nvim-web-devicons',
config = function()
require('nvim-tree').setup({
view = {
side = 'right',
},
})
end,
})
-- close buffers without messing up window layout
use('moll/vim-bbye')
use('editorconfig/editorconfig-vim')
-- ident lines
use('lukas-reineke/indent-blankline.nvim')
-- autopairs
use({
'windwp/nvim-autopairs',
config = function()
require('nvim-autopairs').setup()
end,
})
-- s plus motion to jump around (like vim-sneak)
use('ggandor/lightspeed.nvim')
-- colorizer
use({
'norcalli/nvim-colorizer.lua',
config = function()
require('colorizer').setup()
end,
})
-- find files, buffers, etc.
use({
'nvim-telescope/telescope.nvim',
requires = { { 'nvim-lua/popup.nvim' }, { 'nvim-lua/plenary.nvim' } },
module_patterns = 'telescope*',
})
-- use fzf-native matcher instead
use({ 'nvim-telescope/telescope-fzf-native.nvim', run = 'make' })
-- commenting code
use({
'numToStr/Comment.nvim',
config = function()
require('Comment').setup()
end,
})
-- notifications
use({
'rcarriga/nvim-notify',
config = function()
vim.notify = require('notify')
end,
})
-- git support
use({
'TimUntersberger/neogit',
requires = 'nvim-lua/plenary.nvim',
config = function()
require('neogit').setup({})
end,
})
-- git signs
use({
'lewis6991/gitsigns.nvim',
requires = {
'nvim-lua/plenary.nvim',
},
config = function()
require('gitsigns').setup()
end,
})
-- logging
use('tjdevries/vlog.nvim')
-- surround motion
use('tpope/vim-surround')
-- most recently used
use('yegappan/mru')
use({
'jose-elias-alvarez/null-ls.nvim',
config = function()
local null_ls = require('null-ls')
local sources = {
null_ls.builtins.formatting.prettier,
null_ls.builtins.formatting.rustfmt,
null_ls.builtins.formatting.stylelint,
null_ls.builtins.formatting.stylua,
null_ls.builtins.diagnostics.cspell,
null_ls.builtins.diagnostics.eslint,
null_ls.builtins.diagnostics.luacheck,
null_ls.builtins.diagnostics.proselint,
}
null_ls.config({
sources = sources,
})
require('lspconfig')['null-ls'].setup({
on_attach = function(client)
if client.resolved_capabilities.document_formatting then
vim.cmd('autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()')
end
end,
})
end,
requires = { 'nvim-lua/plenary.nvim', 'neovim/nvim-lspconfig' },
})
-- search for visually selected text
use('bronson/vim-visual-star-search')
-- rainbow parens
use('p00f/nvim-ts-rainbow')
-- colors
use('fatih/molokai')
use('altercation/vim-colors-solarized')
use('NLKNguyen/papercolor-theme')
use('navarasu/onedark.nvim')
end)
|
fix: minor toggleterm tweak
|
fix: minor toggleterm tweak
|
Lua
|
mit
|
drmohundro/dotfiles
|
b1bfa0671597167d77b483c69fe7063c6044d067
|
spec/integration/proxy/realip_spec.lua
|
spec/integration/proxy/realip_spec.lua
|
local spec_helper = require "spec.spec_helpers"
local http_client = require "kong.tools.http_client"
local stringy = require "stringy"
local cjson = require "cjson"
local yaml = require "yaml"
local uuid = require "uuid"
local IO = require "kong.tools.io"
-- This is important to seed the UUID generator
uuid.seed()
local FILE_LOG_PATH = "/tmp/file_log_spec_output.log"
describe("Real IP", function()
setup(function()
spec_helper.prepare_db()
spec_helper.insert_fixtures {
api = {
{ name = "tests realip", public_dns = "realip.com", target_url = "http://mockbin.com" }
},
plugin_configuration = {
{ name = "filelog", value = { path = FILE_LOG_PATH }, __api = 1 }
}
}
spec_helper.start_kong()
end)
teardown(function()
spec_helper.stop_kong()
end)
it("should parse the correct IP", function()
os.remove(FILE_LOG_PATH)
local uuid = string.gsub(uuid(), "-", "")
-- Making the request
local _, status = http_client.get(spec_helper.STUB_GET_URL, nil,
{
host = "realip.com",
["X-Forwarded-For"] = "4.4.4.4, 1.1.1.1, 5.5.5.5",
file_log_uuid = uuid
}
)
assert.are.equal(200, status)
while not (IO.file_exists(FILE_LOG_PATH) and IO.file_size(FILE_LOG_PATH) > 0) do
-- Wait for the file to be created, and for the log to be appended
end
local file_log = IO.read_file(FILE_LOG_PATH)
local log_message = cjson.decode(stringy.strip(file_log))
assert.are.same("4.4.4.4", log_message.client_ip)
assert.are.same(uuid, log_message.request.headers.file_log_uuid)
end)
end)
|
local spec_helper = require "spec.spec_helpers"
local http_client = require "kong.tools.http_client"
local stringy = require "stringy"
local cjson = require "cjson"
local yaml = require "yaml"
local uuid = require "uuid"
local IO = require "kong.tools.io"
-- This is important to seed the UUID generator
uuid.seed()
local FILE_LOG_PATH = spec_helper.get_env().configuration.nginx_working_dir.."/file_log_spec_output.log"
describe("Real IP", function()
setup(function()
spec_helper.prepare_db()
spec_helper.insert_fixtures {
api = {
{ name = "tests realip", public_dns = "realip.com", target_url = "http://mockbin.com" }
},
plugin_configuration = {
{ name = "filelog", value = { path = FILE_LOG_PATH }, __api = 1 }
}
}
spec_helper.start_kong()
end)
teardown(function()
spec_helper.stop_kong()
end)
it("should parse the correct IP", function()
os.remove(FILE_LOG_PATH)
local uuid = string.gsub(uuid(), "-", "")
-- Making the request
local _, status = http_client.get(spec_helper.STUB_GET_URL, nil,
{
host = "realip.com",
["X-Forwarded-For"] = "4.4.4.4, 1.1.1.1, 5.5.5.5",
file_log_uuid = uuid
}
)
assert.are.equal(200, status)
while not (IO.file_exists(FILE_LOG_PATH) and IO.file_size(FILE_LOG_PATH) > 0) do
-- Wait for the file to be created, and for the log to be appended
end
local file_log = IO.read_file(FILE_LOG_PATH)
local log_message = cjson.decode(stringy.strip(file_log))
assert.are.same("4.4.4.4", log_message.client_ip)
assert.are.same(uuid, log_message.request.headers.file_log_uuid)
end)
end)
|
fix(tests) using the local nginx_tmp directory
|
fix(tests) using the local nginx_tmp directory
Former-commit-id: 415a90b0d86d0c69d6c8de44bf6206c53af3b029
|
Lua
|
apache-2.0
|
isdom/kong,Mashape/kong,rafael/kong,Kong/kong,akh00/kong,streamdataio/kong,ind9/kong,kyroskoh/kong,smanolache/kong,rafael/kong,streamdataio/kong,ejoncas/kong,beauli/kong,Kong/kong,ajayk/kong,vzaramel/kong,kyroskoh/kong,shiprabehera/kong,ejoncas/kong,vzaramel/kong,jerizm/kong,li-wl/kong,Kong/kong,ind9/kong,isdom/kong,xvaara/kong,Vermeille/kong,jebenexer/kong,ccyphers/kong,salazar/kong,icyxp/kong
|
99095f5c163970693e92b6b98d63e20b83295b20
|
base.lua
|
base.lua
|
base = {buyship = {}, mission = {}, trade = {}, talk = {}, visit = {}, info = {scrolly = 0, maxscrolly = 520}}
registerstate'base_mission'
registerstate'base_trade'
registerstate'base_buyship'
registerstate'base_talk'
registerstate'base_visit'
function base.load()
end
local rtime = 0
function base.update(dt)
if not base.displist then rtime = rtime + dt return end --quick fix
local x, y = love.mouse.getPosition()
local mouseDown = love.mouse.isDown'l'
if mouseDown then
if x >= 780 and x <= 790 then
base.info.scrolling = true
end
else
base.info.scrolling = false
end
if base.info.scrolling then
if y >= 20 and y <= 580 then
base.info.scrolly = math.max(math.min(y - 40, base.info.maxscrolly), 0)
end
end
base.info.selected = nil
if x > 20 and x < 720 then
local sy = y + math.max(0,#base.displist-4)*150 * base.info.scrolly / base.info.maxscrolly
if (sy-20) % 150 < 120 then
base.info.selected = math.ceil(sy / 150)
if mouseDown then
base.info.activate(base.info.selected)
end
end
end
end
function base.draw()
if state.current == 'base_trade' then
-- draw two list: "player has..." and "base has..."
local maxcargo = player.ship.cargospace
local holds = 0
for i = 1, #player.ship.cargo do
holds = holds + map.objectreserve[player.ship.cargo[i]].weight
end
local ydiff = -120*(holds/maxcargo)
love.graphics.rectangle('line', 142, 40, 70, 120) --will be replaced with cool cargo image
love.graphics.rectangle('fill', 142, 160, 70, ydiff)
graphics.drawshape(graphics.vector.trade, 458+165, 100, 20+math.sin(rtime)*5, rtime)
love.graphics.rectangle('line', 12, 170, 330, 418)
love.graphics.rectangle('line', 458, 170, 330, 418)
elseif state.current == 'base_talk' then
love.graphics.print('There is no talking to do at the moment. Come back later.', 20, 20)
love.graphics.print('(maybe next version ;)', 20, 40)
elseif state.current == 'base_visit' then
love.graphics.print('There is nothing to visit at the moment. Come back later.', 20, 20)
love.graphics.print('(maybe next version ;)', 20, 40)
else
ui.drawlist(base.displist, base.info)
end
end
function base.mission.activate(i)
if not mission.mission or mission.mission.canrefuse and #base.mission.list > 0 then
mission.newmission = base.mission.list[i]
mission.text = mission.newmission.description
mission.tagline = mission.newmission.canrefuse and 'Press Enter to accept or Escape to refuse.' or 'Press Enter or Escape to accept.'
mission.closescreen = mission.close_mission
love.graphics.setFont(mediumfont)
state.current = 'mission'
end
end
function base.mission.init()
base.mission.list = {}
local l = base.mission.list
for k,v in pairs(mission.list) do
if not v.completed and v.available() and v ~= mission.mission then
v.randomid = math.random() --used for sorting
table.insert(l, v)
end
end
if #l > 10 then
table.sort(l, function(a,b) return a.randomid < b.randomid end)
for i=#l,11,-1 do
l[i] = nil
end
end
base.displist = {}
local dl = base.displist
for i=1,#l do
table.insert(dl, {name = officialnames[l[i].commissionedby], description = l[i].name})
end
base.info.scrolly = 0
base.info.activate = base.mission.activate
end
function base.buyship.activate()
-- buy a ship, yes pretty useless at this point
end
function base.buyship.init()
local dl = {}
base.displist = dl
for i, v in ipairs(player.landed.shipsselling) do
table.insert(dl, {name = '', description = ships[v].description})
end
base.info.scrolly = 0
base.info.activate = base.buyship.activate
end
function states.base_mission.keypressed.escape()
state.current = 'base'
end
function states.base_mission.keypressed.enter()
if not mission.mission or mission.mission.canrefuse and #base.mission.list > 0 then
mission.newmission = base.mission.list[1]
love.graphics.setFont(mediumfont)
state.current = 'mission'
end
end
states.base_mission.keypressed['1'] = states.base_mission.keypressed.enter
states.base_mission.keypressed['2'] = function ()
if not mission.mission or mission.mission.canrefuse and #base.mission.list > 2 then
mission.newmission = base.mission.list[2]
love.graphics.setFont(mediumfont)
state.current = 'mission'
end
end
states.base_mission.keypressed['3'] = function ()
if not mission.mission or mission.mission.canrefuse and #base.mission.list > 3 then
mission.newmission = base.mission.list[3]
love.graphics.setFont(mediumfont)
state.current = 'mission'
end
end
states.base_trade.keypressed.escape = states.base_mission.keypressed.escape
states.base_buyship.keypressed.escape = states.base_mission.keypressed.escape
states.base_talk.keypressed.escape = states.base_mission.keypressed.escape
states.base_visit.keypressed.escape = states.base_mission.keypressed.escape
function base.talk.init()
love.graphics.setFont(mediumfont)
conv.speakers = {player.landed.owner}
table.insert(conv.speakers, math.random(1,2), 'player')
conv[1] = {1, 'Hello.'}
conv[2] = {2, 'Hey, how are you doing?'}
conv[3] = {1, 'Great, how about you?'}
conv[4] = {2, 'Fine, absolutely fine.'}
conv.index = 1
state.current = 'conv'
end
function base.visit.init()
hook.call('visitbase', player.landed)
end
local bfuncs = {load=true, update=true, draw=true, mission=true, buyship=true,
allowsave=true}
function base.allowsave(key)
return not bfuncs[key]
end
|
base = {buyship = {}, mission = {}, trade = {}, talk = {}, visit = {}, info = {scrolly = 0, maxscrolly = 520}}
registerstate'base_mission'
registerstate'base_trade'
registerstate'base_buyship'
registerstate'base_talk'
registerstate'base_visit'
function base.load()
end
local rtime = 0
function base.update(dt)
if not base.displist then rtime = rtime + dt return end --quick fix
local x, y = love.mouse.getPosition()
local mouseDown = love.mouse.isDown'l'
if mouseDown then
if x >= 780 and x <= 790 then
base.info.scrolling = true
end
else
base.info.click_enabled = true
base.info.scrolling = false
end
if base.info.scrolling then
if y >= 20 and y <= 580 then
base.info.scrolly = math.max(math.min(y - 40, base.info.maxscrolly), 0)
end
end
base.info.selected = nil
if x > 20 and x < 720 then
local sy = y + math.max(0,#base.displist-4)*150 * base.info.scrolly / base.info.maxscrolly
if (sy-20) % 150 < 120 then
base.info.selected = math.ceil(sy / 150)
if mouseDown and base.info.click_enabled then
base.info.activate(base.info.selected)
end
end
end
end
function base.draw()
if state.current == 'base_trade' then
-- draw two list: "player has..." and "base has..."
local maxcargo = player.ship.cargospace
local holds = 0
for i = 1, #player.ship.cargo do
holds = holds + map.objectreserve[player.ship.cargo[i]].weight
end
local ydiff = -120*(holds/maxcargo)
love.graphics.rectangle('line', 142, 40, 70, 120) --will be replaced with cool cargo image
love.graphics.rectangle('fill', 142, 160, 70, ydiff)
graphics.drawshape(graphics.vector.trade, 458+165, 100, 20+math.sin(rtime)*5, rtime)
love.graphics.rectangle('line', 12, 170, 330, 418)
love.graphics.rectangle('line', 458, 170, 330, 418)
elseif state.current == 'base_talk' then
love.graphics.print('There is no talking to do at the moment. Come back later.', 20, 20)
love.graphics.print('(maybe next version ;)', 20, 40)
elseif state.current == 'base_visit' then
love.graphics.print('There is nothing to visit at the moment. Come back later.', 20, 20)
love.graphics.print('(maybe next version ;)', 20, 40)
else
ui.drawlist(base.displist, base.info)
end
end
function base.mission.activate(i)
if not mission.mission or mission.mission.canrefuse and #base.mission.list >= i then
mission.newmission = base.mission.list[i]
mission.text = mission.newmission.description
mission.tagline = mission.newmission.canrefuse and 'Press Enter to accept or Escape to refuse.' or 'Press Enter or Escape to accept.'
mission.closescreen = mission.close_mission
love.graphics.setFont(mediumfont)
state.current = 'mission'
end
end
function base.mission.init()
base.mission.list = {}
local l = base.mission.list
for k,v in pairs(mission.list) do
if not v.completed and v.available() and v ~= mission.mission then
v.randomid = math.random() --used for sorting
table.insert(l, v)
end
end
if #l > 10 then
table.sort(l, function(a,b) return a.randomid < b.randomid end)
for i=#l,11,-1 do
l[i] = nil
end
end
base.displist = {}
local dl = base.displist
for i=1,#l do
table.insert(dl, {name = officialnames[l[i].commissionedby], description = l[i].name})
end
base.info.scrolly = 0
base.info.activate = base.mission.activate
base.info.click_enabled = false
end
function base.buyship.activate()
-- buy a ship, yes pretty useless at this point
end
function base.buyship.init()
local dl = {}
base.displist = dl
for i, v in ipairs(player.landed.shipsselling) do
table.insert(dl, {name = '', description = ships[v].description})
end
base.info.scrolly = 0
base.info.activate = base.buyship.activate
end
function states.base_mission.keypressed.escape()
state.current = 'base'
end
for i=1,4 do
states.base_mission.keypressed[tostring(i)] = function () base.mission.activate(i) end
end
states.base_mission.keypressed.enter = states.base_mission.keypressed['1']
states.base_trade.keypressed.escape = states.base_mission.keypressed.escape
states.base_buyship.keypressed.escape = states.base_mission.keypressed.escape
states.base_talk.keypressed.escape = states.base_mission.keypressed.escape
states.base_visit.keypressed.escape = states.base_mission.keypressed.escape
function base.talk.init()
love.graphics.setFont(mediumfont)
conv.speakers = {player.landed.owner}
table.insert(conv.speakers, math.random(1,2), 'player')
conv[1] = {1, 'Hello.'}
conv[2] = {2, 'Hey, how are you doing?'}
conv[3] = {1, 'Great, how about you?'}
conv[4] = {2, 'Fine, absolutely fine.'}
conv.index = 1
state.current = 'conv'
end
function base.visit.init()
hook.call('visitbase', player.landed)
end
local bfuncs = {load=true, update=true, draw=true, mission=true, buyship=true,
allowsave=true}
function base.allowsave(key)
return not bfuncs[key]
end
|
Fixes mission menu
|
Fixes mission menu
|
Lua
|
mit
|
gvx/space,gvx/space
|
97d55d606bdf13130d010374a86346ba9ea2815c
|
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 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$"
}
}
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
|
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",
["luacheck.*.*"] = "src"
},
exclude = {
"bin/luacheck$"
}
}
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 luacheck.stages.* modules being ignored by luacov
|
Fix luacheck.stages.* modules being ignored by luacov
|
Lua
|
mit
|
xpol/luacheck,mpeterv/luacheck,mpeterv/luacheck,mpeterv/luacheck,xpol/luacheck,xpol/luacheck
|
2b8a3a7a000baae3e084e9df07470c5280df87e8
|
spec/parser.lua
|
spec/parser.lua
|
describe('Test the ini parser', function()
local ini = require 'ini'
setup(function()
end)
it('basic test', function()
assert.same(ini.parse('a_key = this is the value for this set'), {'a_key', 'this is the value for this set'})
assert.same(ini.parse('[this_is_a_section_test]'), {'this_is_a_section_test'})
assert.same(ini.parse('; this is a comment test'), {';',' this is a comment test'})
end)
it('section', function()
assert.same(ini.parse('[section_test]'),{'section_test'})
assert.same(ini.parse('[section_test1]'),{'section_test1'}) -- test digit
assert.same(ini.parse('[section1_test]'),{'section1_test'}) -- test digit
assert.same(ini.parse('[ section_test ] '), {'section_test'}) -- test space
assert.is_nil(ini.parse('[test_section'))
-- assert.is_nil(ini.parse('test_section]'))
assert.is_nil(ini.parse('[1my_section_test]')) -- fail because starts with a digit
end)
it('Multi-lines string',function()
local t = ini.parse[[
; this is a comment
[opengl]
fullscreen = true
window = 200,200
]]
assert.same(t,{
';',
' this is a comment',
'opengl',
'fullscreen',
'true',
'window',
'200,200'
})
end)
end)
|
describe('Test the parser', function()
local ini = require 'ini'
it('basic test', function()
assert.same({'a_key', 'this is the value for this set'}, ini.parse('a_key = this is the value for this set'))
assert.same({'this_is_a_section_test'}, ini.parse('[this_is_a_section_test]'))
assert.same({';',' this is a comment test'},ini.parse('; this is a comment test'))
end)
it('section', function()
assert.same({'section_test'}, ini.parse('[section_test]'))
assert.same({'section_test1'}, ini.parse('[section_test1]')) -- test digit
assert.same({'s1ection_test'}, ini.parse('[s1ection_test]')) -- test digit
-- assert.same(ini.parse('[ section_test ] '), {'section_test'}) -- test space
-- assert.is_nil(ini.parse('[test_section'))
-- -- assert.is_nil(ini.parse('test_section]'))
-- assert.is_nil(ini.parse('[1my_section_test]')) -- fail because starts with a digit
end)
it('Multi-lines string',function()
local t = ini.parse[[
; this is a comment
[opengl]
fullscreen = true
window = 200,200
]]
assert.same(t,{
';',
' this is a comment',
'opengl',
'fullscreen',
'true',
'window',
'200,200'
})
end)
end)
|
Fix inverted expected and passed parameter
|
Fix inverted expected and passed parameter
|
Lua
|
mit
|
lzubiaur/ini.lua
|
dcb569ec01206f1048cceeee3ef3b7f9f71a1db0
|
lds/allocator.lua
|
lds/allocator.lua
|
--[[
lds - LuaJIT Data Structures
@copyright Copyright (c) 2012-2014 Evan Wies. All rights reserved.
@license MIT License, see the COPYRIGHT file.
@module allocator
allocator_interface = {
allocate = function(self, n) -- allocates storage of n elements
deallocate = function(self, p) -- deallocates storage using the allocator
reallocate = function(self, p, n) -- reallocates storage at p to n elements
}
MallocAllocator uses the standard C malloc/free
VLAAllocator uses FFI VLAs and hence the LuaJIT allocator
JemallocAllocator uses jemalloc (if available)
--]]
local lds = require 'lds/init'
local ffi = require 'ffi'
local C = ffi.C
-------------------------------------------------------------------------------
-- MallocAllocator
--
-- An lds allocator that uses the standard C malloc/free
--
ffi.cdef([[
void * malloc(size_t size);
void * calloc(size_t count, size_t size);
void * valloc(size_t size);
void * realloc(void *ptr, size_t size);
void free(void *ptr);
]])
local MallocAllocatorT__mt = {
__index = {
-- may be re-assigned in MallocAllocatorT
allocate = function(self, n)
return C.calloc( n, self._ct_size )
end,
deallocate = function(self, p)
if p ~= 0 then C.free(p) end
end,
reallocate = function(self, p, n)
return C.realloc(p, n)
end,
}
}
-- which is 'malloc', 'calloc' (zeroed), or 'valloc' (page-aligned)
-- calloc is the default to be consistent with LuaJIT's zero-ing behavior
function lds.MallocAllocatorT( ct, which )
if type(ct) ~= 'cdata' then error('argument 1 is not a valid "cdata"') end
-- clone the metatable and insert type-specific data
local t_mt = lds.simple_deep_copy(MallocAllocatorT__mt)
t_mt.__index._ct = ct
t_mt.__index._ct_size = ffi.sizeof(ct)
if which == nil or which == 'calloc' then
-- keep default
elseif which == 'malloc' then
t_mt.__index.allocate = function(self, n)
return C.malloc( n * self._ct_size )
end
elseif which == 'valloc' then
t_mt.__index.allocate = function(self, n)
return C.malloc( n * self._ct_size )
end
else
error('argument 2 must be nil, "calloc", "malloc", or "valloc"')
end
local t_anonymous = ffi.typeof( 'struct {}' )
return ffi.metatype( t_anonymous, t_mt )
end
-- which is 'malloc', 'calloc' (zeroed), or 'valloc' (page-aligned)
-- calloc is the default to be consistent with LuaJIT's zero-ing behavior
function lds.MallocAllocator( ct, which )
return lds.MallocAllocatorT( ct, which )()
end
-------------------------------------------------------------------------------
-- VLAAllocator
--
-- An lds allocator that uses FFI VLAs and hence the LuaJIT allocator
--
-- Note that there is some extra bookkeeping required by the allocator.
-- of one 32-character string per allocated object.
--
-- This allocator also does not support a true realloc, but rather does
-- a new and copy.
--
-- Anchor for VLA objects used by all VLAAllocators
--
-- Since e are returning raw pointers, we need to keep the VLA cdata from
-- being garbage collected. So we convert the address to a size_t and then
-- to a string, and use that as a key for the VLA cdata.
local VLAAllocator__anchors = {}
VLAAllocatorT__mt = {
__index = {
allocate = function(self, n)
local vla = ffi.new( self._vla, n )
VLAAllocator__anchors[tostring(ffi.cast(lds.size_t, vla._data))] = vla
return vla._data
end,
deallocate = function(self, p)
-- remove the stored reference and then let GC do the rest
if p ~= nil then
VLAAllocator__anchors[tostring(ffi.cast(lds.size_t, p))] = nil
end
end,
reallocate = function(self, p, n)
if p == nil then
local vla = ffi.new( self._vla, n )
VLAAllocator__anchors[tostring(ffi.cast(lds.size_t, vla._data))] = vla
return vla._data
else
local key_old = tostring(ffi.cast(lds.size_t, p))
local vla_old = VLAAllocator__anchors[key_old]
local vla_new = ffi.new( self._vla, n )
local key_new = tostring(ffi.cast(lds.size_t, vla_new._data))
VLAAllocator__anchors[key_new] = vla_new
ffi.copy(vla_new._data, p, ffi.sizeof(vla_old))
VLAAllocator__anchors[key_old] = nil
return vla_new._data
end
end,
}
}
function lds.VLAAllocatorT( ct )
if type(ct) ~= 'cdata' then error('argument 1 is not a valid "cdata"') end
-- clone the metatable and insert type-specific data
local t_mt = lds.simple_deep_copy(VLAAllocatorT__mt)
t_mt.__index._ct = ct
t_mt.__index._ct_size = ffi.sizeof(ct)
t_mt.__index._vla = ffi.typeof( 'struct { $ _data[?]; }', ct )
local t_anonymous = ffi.typeof( 'struct {}' )
return ffi.metatype( t_anonymous, t_mt )
end
function lds.VLAAllocator( ct )
return lds.VLAAllocatorT( ct )()
end
-------------------------------------------------------------------------------
-- JemallocAllocator
--
-- An lds allocator that uses jemalloc, if available.
--
-- check for jemalloc
local success, J = pcall(function() return require 'lds/jemalloc' end)
if success and J then
lds.J = J -- make jemalloc lib immediately available to clients
local JeallocAllocatorT__mt = {
__index = {
allocate = function(self, n)
return J.mallocx( n * self._ct_size, self._flags )
end,
deallocate = function(self, p)
if p ~= 0 then J.dallocx(p) end
end,
reallocate = function(self, p, n)
return C.rallocx(p, n)
end,
}
}
-- if flags is not specified, J.MALLOCX_ZERO is the default to be
-- consistent with LuaJIT's allocation behavior
function lds.JemallocAllocatorT( ct, flags )
if type(ct) ~= 'cdata' then error("argument 1 is not a valid 'cdata'") end
-- clone the metatable and insert type-specific data
local t_mt = lds.simple_deep_copy(MallocAllocatorT__mt)
t_mt.__index._ct = ct
t_mt.__index._ct_size = ffi.sizeof(ct)
t_mt.__index._flags = flags or J.MALLOCX_ZERO
local t_anonymous = ffi.typeof( "struct {}" )
return ffi.metatype( t_anonymous, t_mt )
end
-- if flags is not specified, J.MALLOCX_ZERO is the default to be
-- consistent with LuaJIT's allocation behavior
function lds.JemallocAllocator( ct, flags )
return lds.JemallocAllocatorT( ct, flags )()
end
end -- was jemalloc required?
-- Return the lds API
return lds
|
--[[
lds - LuaJIT Data Structures
@copyright Copyright (c) 2012-2014 Evan Wies. All rights reserved.
@license MIT License, see the COPYRIGHT file.
@module allocator
allocator_interface = {
allocate = function(self, n) -- allocates storage of n elements
deallocate = function(self, p) -- deallocates storage using the allocator
reallocate = function(self, p, n) -- reallocates storage at p to n elements
}
MallocAllocator uses the standard C malloc/free
VLAAllocator uses FFI VLAs and hence the LuaJIT allocator
JemallocAllocator uses jemalloc (if available)
--]]
local lds = require 'lds/init'
local ffi = require 'ffi'
local C = ffi.C
-------------------------------------------------------------------------------
-- MallocAllocator
--
-- An lds allocator that uses the standard C malloc/free
--
ffi.cdef([[
void * malloc(size_t size);
void * calloc(size_t count, size_t size);
void * valloc(size_t size);
void * realloc(void *ptr, size_t size);
void free(void *ptr);
]])
local MallocAllocatorT__mt = {
__index = {
-- may be re-assigned in MallocAllocatorT
allocate = function(self, n)
return C.calloc( n, self._ct_size )
end,
deallocate = function(self, p)
if p ~= 0 then C.free(p) end
end,
reallocate = function(self, p, n)
return C.realloc(p, n)
end,
}
}
-- which is 'malloc', 'calloc' (zeroed), or 'valloc' (page-aligned)
-- calloc is the default to be consistent with LuaJIT's zero-ing behavior
function lds.MallocAllocatorT( ct, which )
if type(ct) ~= 'cdata' then error('argument 1 is not a valid "cdata"') end
-- clone the metatable and insert type-specific data
local t_mt = lds.simple_deep_copy(MallocAllocatorT__mt)
t_mt.__index._ct = ct
t_mt.__index._ct_size = ffi.sizeof(ct)
if which == nil or which == 'calloc' then
-- keep default
elseif which == 'malloc' then
t_mt.__index.allocate = function(self, n)
return C.malloc( n * self._ct_size )
end
elseif which == 'valloc' then
t_mt.__index.allocate = function(self, n)
return C.malloc( n * self._ct_size )
end
else
error('argument 2 must be nil, "calloc", "malloc", or "valloc"')
end
local t_anonymous = ffi.typeof( 'struct {}' )
return ffi.metatype( t_anonymous, t_mt )
end
-- which is 'malloc', 'calloc' (zeroed), or 'valloc' (page-aligned)
-- calloc is the default to be consistent with LuaJIT's zero-ing behavior
function lds.MallocAllocator( ct, which )
return lds.MallocAllocatorT( ct, which )()
end
-------------------------------------------------------------------------------
-- VLAAllocator
--
-- An lds allocator that uses FFI VLAs and hence the LuaJIT allocator
--
-- Note that there is some extra bookkeeping required by the allocator.
-- of one 32-character string per allocated object.
--
-- This allocator also does not support a true realloc, but rather does
-- a new and copy.
--
-- Anchor for VLA objects used by all VLAAllocators
--
-- Since e are returning raw pointers, we need to keep the VLA cdata from
-- being garbage collected. So we convert the address to a size_t and then
-- to a string, and use that as a key for the VLA cdata.
local VLAAllocator__anchors = {}
VLAAllocatorT__mt = {
__index = {
allocate = function(self, n)
local vla = ffi.new( self._vla, n )
VLAAllocator__anchors[tostring(ffi.cast(lds.size_t, vla._data))] = vla
return vla._data
end,
deallocate = function(self, p)
-- remove the stored reference and then let GC do the rest
if p ~= nil then
VLAAllocator__anchors[tostring(ffi.cast(lds.size_t, p))] = nil
end
end,
reallocate = function(self, p, n)
if p == nil then
local vla = ffi.new( self._vla, n )
VLAAllocator__anchors[tostring(ffi.cast(lds.size_t, vla._data))] = vla
return vla._data
else
local key_old = tostring(ffi.cast(lds.size_t, p))
local vla_old = VLAAllocator__anchors[key_old]
local vla_new = ffi.new( self._vla, n )
local key_new = tostring(ffi.cast(lds.size_t, vla_new._data))
VLAAllocator__anchors[key_new] = vla_new
ffi.copy(vla_new._data, p, ffi.sizeof(vla_old))
VLAAllocator__anchors[key_old] = nil
return vla_new._data
end
end,
}
}
function lds.VLAAllocatorT( ct )
if type(ct) ~= 'cdata' then error('argument 1 is not a valid "cdata"') end
-- clone the metatable and insert type-specific data
local t_mt = lds.simple_deep_copy(VLAAllocatorT__mt)
t_mt.__index._ct = ct
t_mt.__index._ct_size = ffi.sizeof(ct)
t_mt.__index._vla = ffi.typeof( 'struct { $ _data[?]; }', ct )
local t_anonymous = ffi.typeof( 'struct {}' )
return ffi.metatype( t_anonymous, t_mt )
end
function lds.VLAAllocator( ct )
return lds.VLAAllocatorT( ct )()
end
-------------------------------------------------------------------------------
-- JemallocAllocator
--
-- An lds allocator that uses jemalloc, if available.
--
-- check for jemalloc
local success, J = pcall(function() return require 'lds/jemalloc' end)
if success and J then
lds.J = J -- make jemalloc lib immediately available to clients
local JemallocAllocatorT__mt = {
__index = {
allocate = function(self, n)
return J.mallocx( n * self._ct_size, self._flags )
end,
deallocate = function(self, p)
if p ~= nil then J.dallocx(p, self._flags) end
end,
reallocate = function(self, p, n)
if p == nil then
return J.mallocx( n * self._ct_size, self._flags )
else
return J.rallocx(p, n, self._flags)
end
end,
}
}
-- if flags is not specified, J.MALLOCX_ZERO is the default to be
-- consistent with LuaJIT's allocation behavior
function lds.JemallocAllocatorT( ct, flags )
if type(ct) ~= 'cdata' then error("argument 1 is not a valid 'cdata'") end
-- clone the metatable and insert type-specific data
local t_mt = lds.simple_deep_copy(JemallocAllocatorT__mt)
t_mt.__index._ct = ct
t_mt.__index._ct_size = ffi.sizeof(ct)
t_mt.__index._flags = flags or J.MALLOCX_ZERO()
local t_anonymous = ffi.typeof( "struct {}" )
return ffi.metatype( t_anonymous, t_mt )
end
-- if flags is not specified, J.MALLOCX_ZERO is the default to be
-- consistent with LuaJIT's allocation behavior
function lds.JemallocAllocator( ct, flags )
return lds.JemallocAllocatorT( ct, flags )()
end
end -- was jemalloc required?
-- Return the lds API
return lds
|
JemallocAllocator bug fixes
|
JemallocAllocator bug fixes
|
Lua
|
mit
|
yurenyong123/lds,umegaya/lds,umegaya/lds,yurenyong123/lds
|
6eddb6ef3250490f101de883a373c39afbecde0d
|
tools/utils/BPE.lua
|
tools/utils/BPE.lua
|
local unicode = require 'tools.utils.unicode'
local separators = require('tools.utils.separators')
local BPE = torch.class('BPE')
function BPE:__init(opt)
self.split = string.split
-- to be able to run the code without torch
if not self.split then
self.split = function(t, sep)
local fields = {}
local pattern = string.format("([^%s]+)", sep)
t:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
end
self.codes = {}
local f = assert(io.open(opt.bpe_model, "r"))
self.EOT_marker = opt.EOT_marker or opt.bpe_EOT_marker
self.BOT_marker = opt.BOT_marker or opt.bpe_EOT_marker
self.joiner_new = opt.joiner_new
self.joiner_annotate = opt.joiner_annotate
local t = f:read("*line")
local options = self.split(t, ";")
if (#options == 3 or #options == 4 ) then
self.prefix = options[1] == "true"
self.suffix = options[2] == "true"
self.case_insensitive = options[3] == "true"
t = f:read("*line")
if #options == 4 then
print ("Warning: The 'mode' parameter for tokenization compatibility between train and test has been depreciated, please make sure that the same tokenization parameters are applied while training BPE models and applying them on raw text inputs")
end
else
self.prefix = opt.bpe_mode == "prefix" or opt.bpe_mode == "both"
self.suffix = opt.bpe_mode == "suffix" or opt.bpe_mode == "both"
self.case_insensitive = opt.bpe_case_insensitive
end
local i = 1
while not(t == nil) do
local l = self.split(t, " ")
if #l == 2 then
self.codes[t] = i
i = i + 1
end
t=f:read("*line")
end
end
local function getPairs(word)
local pairs = {}
for i = 1, #word-1, 1 do
table.insert(pairs, word[i] .. ' ' .. word[i+1])
end
return pairs
end
local function str2word(l, case_insensitive)
local word = {}
for v, c in unicode.utf8_iter(l) do
if (case_insensitive) then
local lu, lc = unicode.getLower(v)
if lu then
c = lc
end
end
table.insert(word, c)
end
return word
end
function BPE:minPair(pairsTable)
local mintmp = 100000
local minpair = ''
for i = 1, #pairsTable, 1 do
local pair_cur = pairsTable[i]
if self.codes[pair_cur] then
local scoretmp = self.codes[pair_cur]
if (scoretmp < mintmp) then
mintmp = scoretmp
minpair = pair_cur
end
end
end
return minpair
end
function BPE:encode(l)
local word = str2word(l, self.case_insensitive)
if #word == 1 then
word[1] = l
return word
end
if self.prefix then table.insert(word, 1, self.BOT_marker) end
if self.suffix then table.insert(word, self.EOT_marker) end
local pairs = getPairs(word)
while true do
local bigram = self:minPair(pairs)
if bigram == '' then break end
bigram = self.split(bigram, ' ')
local new_word = {}
local merge = false
for _, xx in ipairs(word) do
if (merge) then
if xx == bigram[2] then
table.insert(new_word, bigram[1] .. bigram[2])
merge = false
elseif xx == bigram[1] then
table.insert(new_word, bigram[1])
else
table.insert(new_word, bigram[1])
table.insert(new_word, xx)
merge = false
end
else
if bigram[1] == xx then
merge = true
else
table.insert(new_word, xx)
end
end
end
if merge then table.insert(new_word, bigram[1]) end
word = new_word
if #word == 1 then
break
else
pairs = getPairs(word)
end
end
if self.suffix then
if word[#word] == self.EOT_marker then
table.remove(word, #word)
elseif string.sub(word[#word],-string.len(self.EOT_marker)) == self.EOT_marker then
word[#word] = string.sub(word[#word], 1, -string.len(self.EOT_marker)-1)
end
end
if self.prefix then
if word[1] == self.BOT_marker then
table.remove(word, 1)
elseif string.sub(word[1], 1, string.len(self.BOT_marker)) == self.BOT_marker then
word[1] = string.sub(word[1], string.len(self.BOT_marker)+1)
end
end
if (self.case_insensitive) then
local tcword = {}
local prev_idx = 1
for i = 1, #word do
local curr_idx = prev_idx+unicode.utf8len(word[i])
table.insert(tcword, unicode.utf8substr(l, prev_idx, curr_idx - 1))
prev_idx = curr_idx
end
word = tcword
end
return word
end
function BPE:segment(tokens, separator)
local bpeSegment = {}
for i=1, #tokens do
local token = tokens[i]
if token:sub(1, separators.ph_marker_open:len()) == separators.ph_marker_open then
table.insert(bpeSegment, token)
else
local left_sep = false
local right_sep = false
if self.joiner_annotate and not self.joiner_new then
if token:sub(1, #separator) == separator then
token = token:sub(#separator + 1)
left_sep = true
end
if token:sub(-#separator, -1) == separator then
token = token:sub(1, -#separator-1)
right_sep = true
end
end
local bpeTokens = self:encode(token)
if self.joiner_annotate and not self.joiner_new then
if left_sep then
bpeTokens[1] = separator .. bpeTokens[1]
end
if right_sep then
bpeTokens[#bpeTokens] = bpeTokens[#bpeTokens] .. separator
end
end
for j=1, #bpeTokens-1 do
if self.joiner_annotate then
if not self.joiner_new then
table.insert(bpeSegment, bpeTokens[j] .. separator)
else
table.insert(bpeSegment, bpeTokens[j])
table.insert(bpeSegment, separator)
end
else
table.insert(bpeSegment, bpeTokens[j])
end
end
table.insert(bpeSegment, bpeTokens[#bpeTokens])
end
end
return bpeSegment
end
return BPE
|
local unicode = require 'tools.utils.unicode'
local separators = require('tools.utils.separators')
local BPE = torch.class('BPE')
function BPE:__init(opt)
self.split = string.split
-- to be able to run the code without torch
if not self.split then
self.split = function(t, sep)
local fields = {}
local pattern = string.format("([^%s]+)", sep)
t:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
end
self.codes = {}
local f = assert(io.open(opt.bpe_model, "r"))
self.EOT_marker = opt.bpe_EOT_marker
self.BOT_marker = opt.bpe_BOT_marker
self.joiner_new = opt.joiner_new
self.joiner_annotate = opt.joiner_annotate
local t = f:read("*line")
local options = self.split(t, ";")
if (#options == 3 or #options == 4 ) then
self.prefix = options[1] == "true"
self.suffix = options[2] == "true"
self.case_insensitive = options[3] == "true"
t = f:read("*line")
if #options == 4 then
print ("Warning: The 'mode' parameter for tokenization compatibility between train and test has been depreciated, please make sure that the same tokenization parameters are applied while training BPE models and applying them on raw text inputs")
end
else
self.prefix = opt.bpe_mode == "prefix" or opt.bpe_mode == "both"
self.suffix = opt.bpe_mode == "suffix" or opt.bpe_mode == "both"
self.case_insensitive = opt.bpe_case_insensitive
end
local i = 1
while not(t == nil) do
local l = self.split(t, " ")
if #l == 2 then
self.codes[t] = i
i = i + 1
end
t=f:read("*line")
end
end
local function getPairs(word)
local pairs = {}
for i = 1, #word-1, 1 do
table.insert(pairs, word[i] .. ' ' .. word[i+1])
end
return pairs
end
local function str2word(l, case_insensitive)
local word = {}
for v, c in unicode.utf8_iter(l) do
if (case_insensitive) then
local lu, lc = unicode.getLower(v)
if lu then
c = lc
end
end
table.insert(word, c)
end
return word
end
function BPE:minPair(pairsTable)
local mintmp = 100000
local minpair = ''
for i = 1, #pairsTable, 1 do
local pair_cur = pairsTable[i]
if self.codes[pair_cur] then
local scoretmp = self.codes[pair_cur]
if (scoretmp < mintmp) then
mintmp = scoretmp
minpair = pair_cur
end
end
end
return minpair
end
function BPE:encode(l)
local word = str2word(l, self.case_insensitive)
if #word == 1 then
word[1] = l
return word
end
if self.prefix then table.insert(word, 1, self.BOT_marker) end
if self.suffix then table.insert(word, self.EOT_marker) end
local pairs = getPairs(word)
while true do
local bigram = self:minPair(pairs)
if bigram == '' then break end
bigram = self.split(bigram, ' ')
local new_word = {}
local merge = false
for _, xx in ipairs(word) do
if (merge) then
if xx == bigram[2] then
table.insert(new_word, bigram[1] .. bigram[2])
merge = false
elseif xx == bigram[1] then
table.insert(new_word, bigram[1])
else
table.insert(new_word, bigram[1])
table.insert(new_word, xx)
merge = false
end
else
if bigram[1] == xx then
merge = true
else
table.insert(new_word, xx)
end
end
end
if merge then table.insert(new_word, bigram[1]) end
word = new_word
if #word == 1 then
break
else
pairs = getPairs(word)
end
end
if self.suffix then
if word[#word] == self.EOT_marker then
table.remove(word, #word)
elseif string.sub(word[#word],-string.len(self.EOT_marker)) == self.EOT_marker then
word[#word] = string.sub(word[#word], 1, -string.len(self.EOT_marker)-1)
end
end
if self.prefix then
if word[1] == self.BOT_marker then
table.remove(word, 1)
elseif string.sub(word[1], 1, string.len(self.BOT_marker)) == self.BOT_marker then
word[1] = string.sub(word[1], string.len(self.BOT_marker)+1)
end
end
if (self.case_insensitive) then
local tcword = {}
local prev_idx = 1
for i = 1, #word do
local curr_idx = prev_idx+unicode.utf8len(word[i])
table.insert(tcword, unicode.utf8substr(l, prev_idx, curr_idx - 1))
prev_idx = curr_idx
end
word = tcword
end
return word
end
function BPE:segment(tokens, separator)
local bpeSegment = {}
for i=1, #tokens do
local token = tokens[i]
if token:sub(1, separators.ph_marker_open:len()) == separators.ph_marker_open then
table.insert(bpeSegment, token)
else
local left_sep = false
local right_sep = false
if self.joiner_annotate and not self.joiner_new then
if token:sub(1, #separator) == separator then
token = token:sub(#separator + 1)
left_sep = true
end
if token:sub(-#separator, -1) == separator then
token = token:sub(1, -#separator-1)
right_sep = true
end
end
local bpeTokens = self:encode(token)
if self.joiner_annotate and not self.joiner_new then
if left_sep then
bpeTokens[1] = separator .. bpeTokens[1]
end
if right_sep then
bpeTokens[#bpeTokens] = bpeTokens[#bpeTokens] .. separator
end
end
for j=1, #bpeTokens-1 do
if self.joiner_annotate then
if not self.joiner_new then
table.insert(bpeSegment, bpeTokens[j] .. separator)
else
table.insert(bpeSegment, bpeTokens[j])
table.insert(bpeSegment, separator)
end
else
table.insert(bpeSegment, bpeTokens[j])
end
end
table.insert(bpeSegment, bpeTokens[#bpeTokens])
end
end
return bpeSegment
end
return BPE
|
Fix typo in BPE.lua
|
Fix typo in BPE.lua
|
Lua
|
mit
|
OpenNMT/OpenNMT,jungikim/OpenNMT,jungikim/OpenNMT,jsenellart-systran/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,jungikim/OpenNMT,jsenellart/OpenNMT,jsenellart/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT
|
e0b7b01048a2f8ba6e030211638f418b90b13970
|
libs/handlers.lua
|
libs/handlers.lua
|
--[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local log = require('log').log
local git = require('git')
local digest = require('openssl').digest.digest
local githubQuery = require('github-request')
local jsonParse = require('json').parse
local verifySignature = require('verify-signature')
local function split(line)
local args = {}
for match in string.gmatch(line, "[^ ]+") do
args[#args + 1] = match
end
return unpack(args)
end
return function (core)
local db = core.db
local handlers = {}
function handlers.read(remote, data)
local name, version = split(data)
local author
author, name = name:match("([^/]+)/(.*)")
-- TODO: check for mismatch
local hash = db.read(author, name, version)
remote.writeAs("reply", hash)
end
function handlers.match(remote, data)
local name, version = split(data)
local author
author, name = name:match("([^/]+)/(.*)")
if not name then
return remote.writeAs("error", "Missing name parameter")
end
local match, hash = db.match(author, name, version)
if not match and hash then
error(hash)
end
remote.writeAs("reply", match and (match .. ' ' .. hash))
end
function handlers.wants(remote, hashes)
for i = 1, #hashes do
local hash = hashes[i]
local data, err = db.load(hash)
if not data then
return remote.writeAs("error", err or "No such hash: " .. hash)
end
local kind, raw = git.deframe(data)
if kind == 'tag' then
local tag = git.decoders.tag(raw)
log("client want", tag.tag)
else
log("client want", hash, "string")
end
remote.writeAs("send", data)
end
end
function handlers.want(remote, hash)
return handlers.wants(remote, {hash})
end
function handlers.send(remote, data)
local authorized = remote.authorized or {}
local kind, raw = git.deframe(data)
local hashes = {}
local hash = digest("sha1", data)
if kind == "tag" then
if remote.tag then
return remote.writeAs("error", "package upload already in progress: " .. remote.tag.tag)
end
local tag = git.decoders.tag(raw)
local username = string.match(tag.tag, "^[^/]+")
if not verifySignature(db, username, raw) then
return remote.writeAs("error", "Signature verification failure")
end
tag.hash = hash
remote.tag = tag
remote.authorized = authorized
hashes[#hashes + 1] = tag.object
else
if not authorized[hash] then
return remote.writeAs('error', "Attempt to send unauthorized object: " .. hash)
end
authorized[hash] = nil
if kind == "tree" then
local tree = git.decoders.tree(raw)
for i = 1, #tree do
hashes[#hashes + 1] = tree[i].hash
end
end
end
assert(db.save(data) == hash)
local wants = {}
for i = 1, #hashes do
local hash = hashes[i]
if not db.has(hash) then
wants[#wants + 1] = hash
authorized[hash] = true
end
end
if #wants > 0 then
remote.writeAs("wants", wants)
elseif not next(authorized) then
local tag = remote.tag
local author, name, version = string.match(tag.tag, "([^/]+)/(.*)/v(.*)")
db.write(author, name, version, tag.hash)
log("new package", tag.tag)
remote.writeAs("done", tag.hash)
remote.tag = nil
remote.authorized = nil
end
end
local function verifyRequest(raw)
local data = assert(jsonParse(string.match(raw, "([^\n]+)")))
assert(verifySignature(db, data.username, raw), "Signature verification failure")
return data
end
function handlers.claim(remote, raw)
-- The request is RSA signed by the .username field.
-- This will verify the signature and return the data table
local data = verifyRequest(raw)
local username, org = data.username, data.org
if db.isOwner(org, username) then
error("Already an owner in org: " .. org)
end
local head, members = githubQuery("/orgs/" .. org .. "/public_members")
if head.code == 404 then
error("Not an org name: " .. org)
end
local member = false
for i = 1, #members do
if members[i].login == username then
member = true
break
end
end
if not member then
error("Not a public member of org: " .. org)
end
db.addOwner(org, username)
remote.writeAs("reply", "claimed")
end
function handlers.share(remote, raw)
local data = verifyRequest(raw)
local username, org, friend = data.username, data.org, data.friend
if not db.isOwner(org, username) then
error("Can't share a org you're not in: " .. org)
end
if (db.isOwner(org, friend)) then
error("Friend already in org: " .. friend)
end
db.addOwner(org, friend)
remote.writeAs("reply", "shared")
end
function handlers.unclaim(remote, raw)
local data = verifyRequest(raw)
local username, org = data.username, data.org
if not db.isOwner(org, username) then
error("Non a member of org: " .. org)
end
db.removeOwner(org, username)
remote.writeAs("reply", "unshared")
end
return handlers
end
|
--[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local log = require('log').log
local git = require('git')
local digest = require('openssl').digest.digest
local githubQuery = require('github-request')
local jsonParse = require('json').parse
local verifySignature = require('verify-signature')
local function split(line)
local args = {}
for match in string.gmatch(line, "[^ ]+") do
args[#args + 1] = match
end
return unpack(args)
end
return function (core)
local db = core.db
local handlers = {}
function handlers.read(remote, data)
local name, version = split(data)
local author
author, name = name:match("([^/]+)/(.*)")
-- TODO: check for mismatch
local hash = db.read(author, name, version)
remote.writeAs("reply", hash)
end
function handlers.match(remote, data)
local name, version = split(data)
local author
author, name = name:match("([^/]+)/(.*)")
if not name then
return remote.writeAs("error", "Missing name parameter")
end
local match, hash = db.match(author, name, version)
if not match and hash then
error(hash)
end
remote.writeAs("reply", match and (match .. ' ' .. hash))
end
function handlers.wants(remote, hashes)
for i = 1, #hashes do
local hash = hashes[i]
local data, err = db.load(hash)
if not data then
return remote.writeAs("error", err or "No such hash: " .. hash)
end
local kind, raw = git.deframe(data)
if kind == 'tag' then
local tag = git.decoders.tag(raw)
log("client want", tag.tag)
else
log("client want", hash, "string")
end
remote.writeAs("send", data)
end
end
function handlers.want(remote, hash)
return handlers.wants(remote, {hash})
end
function handlers.send(remote, data)
local authorized = remote.authorized or {}
local kind, raw = git.deframe(data)
local hashes = {}
local hash = digest("sha1", data)
if kind == "tag" then
if remote.tag then
return remote.writeAs("error", "package upload already in progress: " .. remote.tag.tag)
end
local tag = git.decoders.tag(raw)
local username = string.match(tag.tag, "^[^/]+")
if not verifySignature(db, username, raw) then
return remote.writeAs("error", "Signature verification failure")
end
tag.hash = hash
remote.tag = tag
remote.authorized = authorized
hashes[#hashes + 1] = tag.object
local meta = jsonParse(tag.message)
if meta and meta.snapshot then
hashes[#hashes + 1] = meta.snapshot
end
else
if not authorized[hash] then
return remote.writeAs('error', "Attempt to send unauthorized object: " .. hash)
end
authorized[hash] = nil
if kind == "tree" then
local tree = git.decoders.tree(raw)
for i = 1, #tree do
hashes[#hashes + 1] = tree[i].hash
end
end
end
assert(db.save(data) == hash)
local wants = {}
for i = 1, #hashes do
local hash = hashes[i]
if not (authorized[hash] or db.has(hash)) then
wants[#wants + 1] = hash
authorized[hash] = true
end
end
if #wants > 0 then
remote.writeAs("wants", wants)
elseif not next(authorized) then
local tag = remote.tag
local author, name, version = string.match(tag.tag, "([^/]+)/(.*)/v(.*)")
db.write(author, name, version, tag.hash)
log("new package", tag.tag)
remote.writeAs("done", tag.hash)
remote.tag = nil
remote.authorized = nil
end
end
local function verifyRequest(raw)
local data = assert(jsonParse(string.match(raw, "([^\n]+)")))
assert(verifySignature(db, data.username, raw), "Signature verification failure")
return data
end
function handlers.claim(remote, raw)
-- The request is RSA signed by the .username field.
-- This will verify the signature and return the data table
local data = verifyRequest(raw)
local username, org = data.username, data.org
if db.isOwner(org, username) then
error("Already an owner in org: " .. org)
end
local head, members = githubQuery("/orgs/" .. org .. "/public_members")
if head.code == 404 then
error("Not an org name: " .. org)
end
local member = false
for i = 1, #members do
if members[i].login == username then
member = true
break
end
end
if not member then
error("Not a public member of org: " .. org)
end
db.addOwner(org, username)
remote.writeAs("reply", "claimed")
end
function handlers.share(remote, raw)
local data = verifyRequest(raw)
local username, org, friend = data.username, data.org, data.friend
if not db.isOwner(org, username) then
error("Can't share a org you're not in: " .. org)
end
if (db.isOwner(org, friend)) then
error("Friend already in org: " .. friend)
end
db.addOwner(org, friend)
remote.writeAs("reply", "shared")
end
function handlers.unclaim(remote, raw)
local data = verifyRequest(raw)
local username, org = data.username, data.org
if not db.isOwner(org, username) then
error("Non a member of org: " .. org)
end
db.removeOwner(org, username)
remote.writeAs("reply", "unshared")
end
return handlers
end
|
Fix race condition in publisher and make sure to sync up snapshot trees
|
Fix race condition in publisher and make sure to sync up snapshot trees
|
Lua
|
apache-2.0
|
squeek502/lit,luvit/lit,zhaozg/lit,james2doyle/lit,kidaa/lit,1yvT0s/lit
|
33195882171850bfa3d7db8b233cdf3dd43864b2
|
src_trunk/resources/gate-system/Chinatown_Gate.lua
|
src_trunk/resources/gate-system/Chinatown_Gate.lua
|
local objChinaGate = createObject(986, 2562.5, 1822, 10, 0, 0, 0)
exports.pool:allocateElement(objChinaGate)
local objChinaGate2 = createObject(986, 2562.5, 1826, 10, 0, 0, 0)
exports.pool:allocateElement(objChinaGate2)
local objChinaFence = createObject( 987, 2544.3037109375, 1840.0390625, 10, 0, 0, 0)
exports.pool:allocateElement(objChinaFence)
open = false
-- Gate code
function useChinaGate(thePlayer)
local team = getPlayerTeam(thePlayer)
if (team==getTeamFromName("Yamaguchi-Gumi")) then
local x, y, z = getElementPosition(thePlayer)
local distance = getDistanceBetweenPoints3D( 2565.1757, 1820.6582, 10.8203, x, y, z )
if (distance<=10) and (open==false) then
open = true
outputChatBox("Yakuza gate is now Open!", thePlayer, 0, 255, 0)
moveObject(objChinaGate, 3000, 2568, 1822, 10, 0, 0, 0)
moveObject(objChinaGate2, 4000, 2568, 1826, 10, 0, 0, 0)
setTimer(closeChinaGate, 6000, 1, thePlayer)
end
end
end
addCommandHandler("gate", useChinaGate)
function closeChinaGate(thePlayer)
if (getElementType(thePlayer)) then
outputChatBox("Yakuza gate is now Closed!", thePlayer, 255, 0, 0)
end
moveObject(objChinaGate, 3000, 2562.5, 1822, 10, 0, 0, 0)
moveObject(objChinaGate2, 4000, 2562.5, 1826, 10, 0, 0, 0)
setTimer(resetChinaGateState, 1000, 1)
end
function resetChinaGateState()
open = false
end
|
local objChinaGate = createObject(986, 2566.45, 1822, 11, 0, 0, 180)
exports.pool:allocateElement(objChinaGate)
local objChinaGate2 = createObject(986, 2566.45, 1826, 11, 0, 0, 180)
exports.pool:allocateElement(objChinaGate2)
local objChinaFence = createObject( 987, 2544.3037109375, 1840.0390625, 10, 0, 0, 0)
exports.pool:allocateElement(objChinaFence)
open = false
-- Gate code
function useChinaGate(thePlayer)
local team = getPlayerTeam(thePlayer)
if (team==getTeamFromName("Yamaguchi-Gumi")) then
local x, y, z = getElementPosition(thePlayer)
local distance = getDistanceBetweenPoints3D( 2565.1757, 1820.6582, 10.8203, x, y, z )
if (distance<=10) and (open==false) then
open = true
outputChatBox("Yakuza gate is now Open!", thePlayer, 0, 255, 0)
moveObject(objChinaGate, 3000, 2571.8, 1822, 11)
moveObject(objChinaGate2, 4000, 2571.8, 1826, 11)
setTimer(closeChinaGate, 6000, 1, thePlayer)
end
end
end
addCommandHandler("gate", useChinaGate)
function closeChinaGate(thePlayer)
if (getElementType(thePlayer)) then
outputChatBox("Yakuza gate is now Closed!", thePlayer, 255, 0, 0)
end
moveObject(objChinaGate, 3000, 2566.45, 1822, 11)
moveObject(objChinaGate2, 4000, 2566.45, 1826, 11)
setTimer(resetChinaGateState, 1000, 1)
end
function resetChinaGateState()
open = false
end
|
"Fixed Yakuza HQ gate" #2
|
"Fixed Yakuza HQ gate" #2
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@703 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
43eb6f2dee3c1e4550834858a31437f93245be4c
|
libs/luvit-websocket/libs/server.lua
|
libs/luvit-websocket/libs/server.lua
|
local net = require('net')
local b64 = require('./base64.lua')
local sha1 = require('./sha1.lua')
local table = require('table')
local math = require('math')
local bit = require('bit')
local table = require('table')
local string = require('string')
require('./table.lua')(table)
require('./string.lua')(string)
function toBits(num)
-- returns a table of bits, least significant first.
local t={} -- will contain the bits
while num>0 do
rest=math.fmod(num,2)
t[#t+1]=rest
num=(num-rest)/2
end
return t
end
function decodeMessage(buf)
local bytes = {}
local byteString = ""
for i = 1, #buf do
bytes[i] = string.byte(buf:sub(i,i))
byteString = byteString .. string.byte(buf:sub(i,i)) .. " "
end
local flags = toBits(bytes[1])
if flags[4] == 1 then
return 2
end
if flags[5] == 1 and flags[6] == 0 and flags[7] == 1 and flags[8] == 0 then
flags[6] = 1
flags[7] = 0
bytes[1] = tonumber(table.concat(flags, ""), 2)
local buff = {}
for k,v in pairs(bytes) do
buff = buff .. string.char(v)
end
return 1, buff
end
if flags[1] == 0 then
print("WebSocket Error: Message Fragmentation not supported.")
return nil
end
bytes[1] = nil
local length = 0
local offset = 0
if bytes[2]-128 >= 0 and bytes[2]-128 <= 125 then
length = bytes[2] - 128
bytes[2] = nil
offset = 2
elseif bytes[2] == 126 then
length = tonumber(string.format("%x%x", bytes[3], bytes[4]), 16)
bytes[2] = nil bytes[3] = nil bytes[4] = nil
offset = 2 + 2
elseif bytes[2] == 127 then
length = tonumber(string.format("%x%x%x%x%x%x%x%x", bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10]), 16)
bytes[2] = nil bytes[3] = nil bytes[4] = nil bytes[5] = nil bytes[6] = nil bytes[7] = nil bytes[8] = nil bytes[9] = nil bytes[10] = nil
offset = 2 + 8
end
for k,v in pairs(bytes) do
bytes[k-offset] = v
bytes[k] = nil
end
local mask = {bytes[1], bytes[2], bytes[3], bytes[4]}
bytes[1] = nil bytes[2] = nil bytes[3] = nil bytes[4] = nil
for k,v in pairs(bytes) do
bytes[k-5] = v
bytes[k] = nil
end
local ret = ""
for i,v in pairs(bytes) do
local b = bit.bxor(mask[(i % 4)+1], v)
ret = ret .. string.char(b)
end
return ret
end
return function(port)
local this = {}
this.listener = {connect = {}, data = {}, disconnect = {}, _buffer = "", _startup = true}
this.on = function(this, s, c)
if this.listener[s] and type(this.listener[s]) == "table" and type(c) == "function" then
table.insert(this.listener[s], c)
end
end
this.call = function(this, s, args)
if this.listener[s] and type(this.listener[s]) == "table" then
for k,v in pairs(this.listener[s]) do
if type(v) == "function" then
if type(args) == "table" then
v(table.unpack(args))
else
v(args)
end
end
end
end
end
this.clients = {}
net.createServer(function (client)
client._startup = true
client._buffer = ""
client:on("data", function(c)
client.send = function(client, msg)
local flags = "10000001"
local bytes = {tonumber(flags, 2), #msg}
if bytes[2] > 65535 then
local bits = table.reverse(toBits(bytes[2]))
local zeros = 64 - #bits
local size = ""
for i = 1, zeros do
size = size .. "0"
end
for k,v in pairs(bits) do
size = size .. v
end
bytes[3] = "" bytes[4] = "" bytes[5] = "" bytes[6] = ""
bytes[7] = "" bytes[8] = "" bytes[9] = "" bytes[10] = ""
local b = 0
for bit = 1, 64 do
bytes[3 + b] = bytes[3 + b] .. size:sub(bit,bit)
if bit - 8 * b >= 8 then
bytes[3+b] = tonumber(bytes[3+b], 2)
b = b + 1
end
end
bytes[2] = 255 - 128
elseif bytes[2] > 125 then
local bits = table.reverse(toBits(bytes[2]))
local zeros = 16 - #bits
local size = ""
for i = 1, zeros do
size = size .. "0"
end
for k,v in pairs(bits) do
size = size .. v
end
bytes[3] = "" bytes[4] = ""
local b = 0
for bit = 1, 16 do
bytes[3 + b] = bytes[3 + b] .. size:sub(bit,bit)
if bit - 8 * b >= 8 then
bytes[3+b] = tonumber(bytes[3+b], 2)
b = b + 1
end
end
bytes[2] = 254 - 128
end
for i = 1, #msg do
table.insert(bytes, string.byte(msg:sub(i,i)))
end
local str = ""
for k,v in pairs(bytes) do
str = str .. string.char(v)
end
client:write(str)
end
if client._startup then
client._buffer = client._buffer .. c
c = client._buffer
end
if c:sub(1, 3) == "GET" and string.find(c, "\r\n\r\n", 0, true) then -- Handshake
local lines = c:split('\r\n')
local title = lines[1]
lines[1] = nil
local data = {}
for k,v in pairs(lines) do
if #v > 2 then
local line = v:split(": ")
data[line[1]] = line[2]
end
end
local responseKey = data["Sec-WebSocket-Key"] .. '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
responseKey = b64.encode(sha1.binary(responseKey))
local response = "HTTP/1.1 101 Switching Protocols\r\n"
.."Connection: Upgrade\r\n"
.."Upgrade: websocket\r\n"
.."Sec-WebSocket-Accept: " .. responseKey .. "\r\n"
.."\r\n"
client:write(response)
client._startup = false
client._buffer = ""
this:call("connect", {client})
table.insert(this.clients, client)
for k,v in pairs(this.clients) do
if v == client then
client.id = k
end
end
elseif client._startup == false then
local message, v = decodeMessage(c)
if message == 2 then
this:call("disconnect", {client})
this.clients[client.id or 0] = nil
elseif message == 1 then
client:write(v)
elseif message then
this:call("data", {client, message})
else
print("Could not parse message: " .. c)
end
end
end)
end):listen(port)
print("WebSocket Server listening on port " .. port)
return this
end
|
local net = require('net')
local b64 = require('./base64.lua')
local sha1 = require('./sha1.lua')
local table = require('table')
local math = require('math')
local bit = require('bit')
local table = require('table')
local string = require('string')
require('./table.lua')(table)
require('./string.lua')(string)
function toBits(num)
-- returns a table of bits, least significant first.
local t={} -- will contain the bits
while num>0 do
rest=math.fmod(num,2)
t[#t+1]=rest
num=(num-rest)/2
end
return t
end
function decodeMessage(buf)
local bytes = {}
local byteString = ""
for i = 1, #buf do
bytes[i] = string.byte(buf:sub(i,i))
byteString = byteString .. string.byte(buf:sub(i,i)) .. " "
end
local flags = toBits(bytes[1])
if flags[4] == 1 then
return 2
end
if flags[5] == 1 and flags[6] == 0 and flags[7] == 1 and flags[8] == 0 then
flags[6] = 1
flags[7] = 0
bytes[1] = tonumber(table.concat(flags, ""), 2)
local buff = {}
for k,v in pairs(bytes) do
buff = buff .. string.char(v)
end
return 1, buff
end
if flags[1] == 0 then
print("WebSocket Error: Message Fragmentation not supported.")
return nil
end
bytes[1] = nil
local length = 0
local offset = 0
if bytes[2]-128 >= 0 and bytes[2]-128 <= 125 then
length = bytes[2] - 128
bytes[2] = nil
offset = 2
elseif bytes[2]-128 == 126 then
length = tonumber(string.format("%x%x", bytes[3], bytes[4]), 16)
bytes[2] = nil bytes[3] = nil bytes[4] = nil
offset = 2 + 2
elseif bytes[2]-128 == 127 then
length = tonumber(string.format("%x%x%x%x%x%x%x%x", bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10]), 16)
bytes[2] = nil bytes[3] = nil bytes[4] = nil bytes[5] = nil bytes[6] = nil bytes[7] = nil bytes[8] = nil bytes[9] = nil bytes[10] = nil
offset = 2 + 8
end
for k,v in pairs(bytes) do
bytes[k-offset] = v
bytes[k] = nil
end
local mask = {bytes[1], bytes[2], bytes[3], bytes[4]}
bytes[1] = nil bytes[2] = nil bytes[3] = nil bytes[4] = nil
for k,v in pairs(bytes) do
bytes[k-5] = v
bytes[k] = nil
end
local ret = ""
for i,v in pairs(bytes) do
local b = bit.bxor(mask[(i % 4)+1], v)
ret = ret .. string.char(b)
end
return ret
end
return function(port)
local this = {}
this.listener = {connect = {}, data = {}, disconnect = {}, _buffer = "", _startup = true}
this.on = function(this, s, c)
if this.listener[s] and type(this.listener[s]) == "table" and type(c) == "function" then
table.insert(this.listener[s], c)
end
end
this.call = function(this, s, args)
if this.listener[s] and type(this.listener[s]) == "table" then
for k,v in pairs(this.listener[s]) do
if type(v) == "function" then
if type(args) == "table" then
v(table.unpack(args))
else
v(args)
end
end
end
end
end
this.clients = {}
this.server = net.createServer(function (client)
client._startup = true
client._buffer = ""
client:on("data", function(c)
client.send = function(client, msg)
local flags = "10000001"
local bytes = {tonumber(flags, 2), #msg}
if bytes[2] > 65535 then
local bits = table.reverse(toBits(bytes[2]))
local zeros = 64 - #bits
local size = ""
for i = 1, zeros do
size = size .. "0"
end
for k,v in pairs(bits) do
size = size .. v
end
bytes[3] = "" bytes[4] = "" bytes[5] = "" bytes[6] = ""
bytes[7] = "" bytes[8] = "" bytes[9] = "" bytes[10] = ""
local b = 0
for bit = 1, 64 do
bytes[3 + b] = bytes[3 + b] .. size:sub(bit,bit)
if bit - 8 * b >= 8 then
bytes[3+b] = tonumber(bytes[3+b], 2)
b = b + 1
end
end
bytes[2] = 255 - 128
elseif bytes[2] > 125 then
local bits = table.reverse(toBits(bytes[2]))
local zeros = 16 - #bits
local size = ""
for i = 1, zeros do
size = size .. "0"
end
for k,v in pairs(bits) do
size = size .. v
end
bytes[3] = "" bytes[4] = ""
local b = 0
for bit = 1, 16 do
bytes[3 + b] = bytes[3 + b] .. size:sub(bit,bit)
if bit - 8 * b >= 8 then
bytes[3+b] = tonumber(bytes[3+b], 2)
b = b + 1
end
end
bytes[2] = 254 - 128
end
for i = 1, #msg do
table.insert(bytes, string.byte(msg:sub(i,i)))
end
local str = ""
for k,v in pairs(bytes) do
str = str .. string.char(v)
end
client:write(str)
end
if client._startup then
client._buffer = client._buffer .. c
c = client._buffer
end
if this.verbose then
print("Websocket Server received " .. #c .. " bytes")
end
if c:sub(1, 3) == "GET" and string.find(c, "\r\n\r\n", 0, true) then -- Handshake
local lines = c:split('\r\n')
local title = lines[1]
lines[1] = nil
local data = {}
for k,v in pairs(lines) do
if #v > 2 then
local line = v:split(": ")
data[line[1]] = line[2]
end
end
local responseKey = data["Sec-WebSocket-Key"] .. '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
responseKey = b64.encode(sha1.binary(responseKey))
local response = "HTTP/1.1 101 Switching Protocols\r\n"
.."Connection: Upgrade\r\n"
.."Upgrade: websocket\r\n"
.."Sec-WebSocket-Accept: " .. responseKey .. "\r\n"
.."\r\n"
client:write(response)
client._startup = false
client._buffer = ""
this:call("connect", {client})
table.insert(this.clients, client)
for k,v in pairs(this.clients) do
if v == client then
client.id = k
end
end
elseif client._startup == false then
local message, v = decodeMessage(c, this.debug)
if message == 2 then
this:call("disconnect", {client})
this.clients[client.id or 0] = nil
elseif message == 1 then
client:write(v)
elseif message then
this:call("data", {client, message})
else
print("Could not parse message: " .. c)
end
end
end)
end)
this.server:listen(port)
print("WebSocket Server listening on port " .. port)
return this
end
|
Fix a bug in luvit-websocket related to parsing long messages
|
Fix a bug in luvit-websocket related to parsing long messages
|
Lua
|
bsd-2-clause
|
elflang/elf,elflang/elf,elflang/elf
|
39bb6a8a58f1a67410f54ccbbc22b52569e8a4c9
|
jwt.lua
|
jwt.lua
|
local encode = function(payload, key)
header = { typ='JWT', alg="HS256" }
segments = {
urlsafeB64Encode(jsonEncode(header)),
urlsafeB64Encode(jsonEncode(payload))
}
signing_input = table.concat(segments, ".")
signature = sign(signing_input, key)
segments[#segments+1] = urlsafeB64Encode(signature)
return table.concat(segments, ".")
end
local sign = function(msg, key)
return crypto.hmac(key, msg, crypto.sha256).digest()
end
local jsonEncode = function(input)
result = json.stringify(input)
return result
end
local urlsafeB64Encode = function(input)
result = base64.encode(input)
result = string.gsub(result, "+", "-")
result = string.gsub(result, "/", "_")
result = string.gsub(result, "=", "")
return result
end
return { encode = encode, sign = sign, jsonEncode = jsonEncode, urlsafeB64Encode = urlsafeB64Encode }
|
local jwt = {}
-- public
function jwt.encode(payload, key)
header = { typ='JWT', alg="HS256" }
segments = {
urlsafeB64Encode(jsonEncode(header)),
urlsafeB64Encode(jsonEncode(payload))
}
signing_input = table.concat(segments, ".")
signature = sign(signing_input, key)
segments[#segments+1] = urlsafeB64Encode(signature)
return table.concat(segments, ".")
end
-- private
local function sign(msg, key)
return crypto.hmac(key, msg, crypto.sha256).digest()
end
local function jsonEncode(input)
result = json.stringify(input)
return result
end
local function urlsafeB64Encode(input)
result = base64.encode(input)
result = string.gsub(result, "+", "-")
result = string.gsub(result, "/", "_")
result = string.gsub(result, "=", "")
return result
end
return jwt
|
Fixing reference again
|
Fixing reference again
|
Lua
|
bsd-3-clause
|
robertbrook/lib,thejeshgn/lib
|
4953c210b5ac915fc34499173a315bd0e166d511
|
models/upload.lua
|
models/upload.lua
|
--- A basic lower upload API
--
module(..., package.seeall)
require 'posix'
local Model = require 'bamboo.model'
local Form = require 'bamboo.form'
local function calcNewFilename(dir, oldname)
-- separate the base name and extense name of a filename
local main, ext = oldname:match('^(.+)(%.%w+)$')
if not ext then
main = oldname
ext = ''
end
-- check if exists the same name file
local tstr = ''
local i = 0
while posix.stat( dir + main + tstr + ext ) do
i = i + 1
tstr = '_' + tostring(i)
end
-- concat to new filename
local newbasename = main + tstr
return newbasename, ext
end
--- here, we temprorily only consider the file data is passed wholly by zeromq
-- and save by bamboo
-- @field t.req
-- @field t.file_obj
-- @field t.dest_dir
-- @field t.prefix
-- @field t.postfix
--
local function savefile(t)
local req, file_obj = t.req, t.file_obj
local dest_dir = t.dest_dir and ('media/uploads/' + t.dest_dir + '/') or 'media/uploads/'
dest_dir = string.trailingPath(dest_dir)
local prefix = t.prefix or ''
local postfix = t.postfix or ''
local filename = ''
local body = ''
local rename_func = t.rename_func or nil
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- when html5 upload, we think of the name of that file was stored in header x-file-name
-- if this info missing, we may consider the filename was put in the query string
filename = req.headers['x-file-name'] or Form:parseQuery(req)['filename']
-- TODO:
-- req.body contains all file binary data
body = req.body
else
checkType(file_obj, 'table')
-- Notice: the filename in the form string are quoted by ""
-- this pattern rule can deal with the windows style directory delimiter
-- file_obj['content-disposition'] contains many file associated info
filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$')
body = file_obj.body
end
if isFalse(filename) or isFalse(body) then return nil, nil end
if not posix.stat(dest_dir) then
-- why posix have no command like " mkdir -p "
os.execute('mkdir -p ' + dest_dir)
end
-- if passed in a rename function, use it to replace the orignial filename
if rename_func and type(rename_func) == 'function' then
filename = rename_func(filename)
end
local newbasename, ext = calcNewFilename(dest_dir, filename)
local newname = prefix + newbasename + postfix + ext
local path = dest_dir + newname
-- write file to disk
local fd = io.open(path, "wb")
fd:write(body)
fd:close()
return newname, path
end
local Upload = Model:extend {
__tag = 'Bamboo.Model.Upload';
__name = 'Upload';
__desc = "User's upload files.";
__indexfd = "path";
__fields = {
['name'] = {},
['path'] = {unique=true},
['size'] = {},
['timestamp'] = {},
['desc'] = {},
};
init = function (self, t)
if not t then return self end
self.name = t.name
self.path = t.path
self.size = posix.stat(self.path).size
self.timestamp = os.time()
-- according the current design, desc field is nil
self.desc = t.desc or ''
return self
end;
--- For traditional Html4 form upload
--
batch = function (self, req, params, dest_dir, prefix, postfix, rename_func)
I_AM_CLASS(self)
local file_objs = List()
-- file data are stored as arraies in params
for i, v in ipairs(params) do
local name, path = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix, rename_func }
if not path or not name then return nil end
-- create file instance
local file_instance = self { name = name, path = path }
if file_instance then
-- store to db
file_instance:save()
file_objs:append(file_instance)
end
end
-- a file object list
return file_objs
end;
process = function (self, web, req, dest_dir, prefix, postfix, rename_func)
I_AM_CLASS(self)
assert(web, '[Error] Upload input parameter: "web" must be not nil.')
assert(req, '[Error] Upload input parameter: "req" must be not nil.')
-- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately
if req.headers['x-mongrel2-upload-start'] then
print('return blank to abort upload.')
web.conn:reply(req, '')
return nil, 'Uploading file is too large.'
end
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- stored to disk
local name, path = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix, rename_func = rename_func }
if not path or not name then return nil, '[Error] empty file.' end
local file_instance = self { name = name, path = path }
if file_instance then
file_instance:save()
return file_instance, 'single'
end
else
-- for uploading in html4 way
local params = Form:parse(req)
local files = self:batch ( req, params, dest_dir, prefix, postfix, rename_func )
if isEmpty(files) then return nil, '[Error] empty file.' end
if #files == 1 then
-- even only one file upload, batch function will return a list
return files[1], 'single'
else
return files, 'multiple'
end
end
end;
calcNewFilename = function (self, dest_dir, oldname)
return calcNewFilename(dest_dir, oldname)
end;
-- this function, encorage override by child model, to execute their own delete action
specDelete = function (self)
I_AM_INSTANCE()
-- remove file from disk
os.execute('rm ' + self.path)
return self
end;
}
return Upload
|
--- A basic lower upload API
--
module(..., package.seeall)
require 'posix'
local http = require 'lglib.http'
local Model = require 'bamboo.model'
local Form = require 'bamboo.form'
local function calcNewFilename(dir, oldname)
-- separate the base name and extense name of a filename
local main, ext = oldname:match('^(.+)(%.%w+)$')
if not ext then
main = oldname
ext = ''
end
-- check if exists the same name file
local tstr = ''
local i = 0
while posix.stat( dir + main + tstr + ext ) do
i = i + 1
tstr = '_' + tostring(i)
end
-- concat to new filename
local newbasename = main + tstr
return newbasename, ext
end
--- here, we temprorily only consider the file data is passed wholly by zeromq
-- and save by bamboo
-- @field t.req
-- @field t.file_obj
-- @field t.dest_dir
-- @field t.prefix
-- @field t.postfix
--
local function savefile(t)
local req, file_obj = t.req, t.file_obj
local dest_dir = t.dest_dir and ('media/uploads/' + t.dest_dir + '/') or 'media/uploads/'
dest_dir = string.trailingPath(dest_dir)
local prefix = t.prefix or ''
local postfix = t.postfix or ''
local filename = ''
local body = ''
local rename_func = t.rename_func or nil
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- when html5 upload, we think of the name of that file was stored in header x-file-name
-- if this info missing, we may consider the filename was put in the query string
filename = req.headers['x-file-name'] or Form:parseQuery(req)['filename']
-- TODO:
-- req.body contains all file binary data
body = req.body
else
checkType(file_obj, 'table')
-- Notice: the filename in the form string are quoted by ""
-- this pattern rule can deal with the windows style directory delimiter
-- file_obj['content-disposition'] contains many file associated info
filename = file_obj['content-disposition'].filename:sub(2, -2):match('\\?([^\\]-%.%w+)$')
body = file_obj.body
end
if isFalse(filename) or isFalse(body) then return nil, nil end
if not req.ajax then
filename = http.encodeURL(filename)
end
if not posix.stat(dest_dir) then
-- why posix have no command like " mkdir -p "
os.execute('mkdir -p ' + dest_dir)
end
-- if passed in a rename function, use it to replace the orignial filename
if rename_func and type(rename_func) == 'function' then
filename = rename_func(filename)
end
local newbasename, ext = calcNewFilename(dest_dir, filename)
local newname = prefix + newbasename + postfix + ext
local path = dest_dir + newname
-- write file to disk
local fd = io.open(path, "wb")
fd:write(body)
fd:close()
return newname, path
end
local Upload = Model:extend {
__tag = 'Bamboo.Model.Upload';
__name = 'Upload';
__desc = "User's upload files.";
__indexfd = "path";
__fields = {
['name'] = {},
['path'] = {unique=true},
['size'] = {},
['timestamp'] = {},
['desc'] = {},
};
init = function (self, t)
if not t then return self end
self.name = t.name
self.path = t.path
self.size = posix.stat(self.path).size
self.timestamp = os.time()
-- according the current design, desc field is nil
self.desc = t.desc or ''
return self
end;
--- For traditional Html4 form upload
--
batch = function (self, req, params, dest_dir, prefix, postfix, rename_func)
I_AM_CLASS(self)
local file_objs = List()
-- file data are stored as arraies in params
for i, v in ipairs(params) do
local name, path = savefile { req = req, file_obj = v, dest_dir = dest_dir, prefix = prefix, postfix = postfix, rename_func }
if not path or not name then return nil end
-- create file instance
local file_instance = self { name = name, path = path }
if file_instance then
-- store to db
file_instance:save()
file_objs:append(file_instance)
end
end
-- a file object list
return file_objs
end;
process = function (self, web, req, dest_dir, prefix, postfix, rename_func)
I_AM_CLASS(self)
assert(web, '[Error] Upload input parameter: "web" must be not nil.')
assert(req, '[Error] Upload input parameter: "req" must be not nil.')
-- current scheme: for those larger than PRESIZE, send a ABORT signal, and abort immediately
if req.headers['x-mongrel2-upload-start'] then
print('return blank to abort upload.')
web.conn:reply(req, '')
return nil, 'Uploading file is too large.'
end
-- if upload in html5 way
if req.headers['x-requested-with'] then
-- stored to disk
local name, path = savefile { req = req, dest_dir = dest_dir, prefix = prefix, postfix = postfix, rename_func = rename_func }
if not path or not name then return nil, '[Error] empty file.' end
local file_instance = self { name = name, path = path }
if file_instance then
file_instance:save()
return file_instance, 'single'
end
else
-- for uploading in html4 way
local params = Form:parse(req)
local files = self:batch ( req, params, dest_dir, prefix, postfix, rename_func )
if isEmpty(files) then return nil, '[Error] empty file.' end
if #files == 1 then
-- even only one file upload, batch function will return a list
return files[1], 'single'
else
return files, 'multiple'
end
end
end;
calcNewFilename = function (self, dest_dir, oldname)
return calcNewFilename(dest_dir, oldname)
end;
-- this function, encorage override by child model, to execute their own delete action
specDelete = function (self)
I_AM_INSTANCE()
-- remove file from disk
os.execute('rm ' + self.path)
return self
end;
}
return Upload
|
fix a upload bug for IE6.
|
fix a upload bug for IE6.
in hmtl5 upload, the js should and already use encodeComponent to encode the filename;
but in html4 upload, the form doesn't encode it, so on server, bamboo should encode it once.
for html5 uploading, it is unneccessary.
Signed-off-by: Daogang Tang <[email protected]>
|
Lua
|
bsd-3-clause
|
daogangtang/bamboo,daogangtang/bamboo
|
4abf23fe8ccd6c29e0f940cfbf39c231084828c3
|
scen_edit/state/terrain_smooth_state.lua
|
scen_edit/state/terrain_smooth_state.lua
|
TerrainSmoothState = AbstractHeightmapEditingState:extends{}
function TerrainSmoothState:GetCommand(x, z, strength)
self.sigma = math.max(math.min(math.sqrt(math.sqrt(strength)) / 2, 1.5), 0.20)
return TerrainSmoothCommand({
x = x + self.size/2,
z = z + self.size/2,
size = self.size,
shapeName = self.patternTexture,
rotation = self.rotation,
sigma = self.sigma,
strength = strength,
})
end
--gl.Color(0, 1, 0, 0.4)
|
TerrainSmoothState = AbstractHeightmapEditingState:extends{}
function TerrainSmoothState:GetCommand(x, z, strength)
strength = math.abs(strength)
self.sigma = math.max(math.min(math.sqrt(math.sqrt(strength)) / 2, 1.5), 0.20)
return TerrainSmoothCommand({
x = x + self.size/2,
z = z + self.size/2,
size = self.size,
shapeName = self.patternTexture,
rotation = self.rotation,
sigma = self.sigma,
strength = strength,
})
end
--gl.Color(0, 1, 0, 0.4)
|
fix RMB terrain smoothing error
|
fix RMB terrain smoothing error
|
Lua
|
mit
|
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
|
5e47af8773c16eccdee58b598f977bd1cedf8c72
|
worldedit_commands/mark.lua
|
worldedit_commands/mark.lua
|
worldedit.marker1 = {}
worldedit.marker2 = {}
worldedit.marker_region = {}
--marks worldedit region position 1
worldedit.mark_pos1 = function(name)
local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name]
if pos1 ~= nil then
--make area stay loaded
local manip = minetest.get_voxel_manip()
manip:read_from_map(pos1, pos1)
end
if worldedit.marker1[name] ~= nil then --marker already exists
worldedit.marker1[name]:remove() --remove marker
worldedit.marker1[name] = nil
end
if pos1 ~= nil then
--add marker
worldedit.marker1[name] = minetest.add_entity(pos1, "worldedit:pos1")
if worldedit.marker1[name] ~= nil then
worldedit.marker1[name]:get_luaentity().player_name = name
end
end
worldedit.mark_region(name)
end
--marks worldedit region position 2
worldedit.mark_pos2 = function(name)
local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name]
if pos2 ~= nil then
--make area stay loaded
local manip = minetest.get_voxel_manip()
manip:read_from_map(pos2, pos2)
end
if worldedit.marker2[name] ~= nil then --marker already exists
worldedit.marker2[name]:remove() --remove marker
worldedit.marker2[name] = nil
end
if pos2 ~= nil then
--add marker
worldedit.marker2[name] = minetest.add_entity(pos2, "worldedit:pos2")
if worldedit.marker2[name] ~= nil then
worldedit.marker2[name]:get_luaentity().player_name = name
end
end
worldedit.mark_region(name)
end
worldedit.mark_region = function(name)
local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name]
if worldedit.marker_region[name] ~= nil then --marker already exists
--wip: make the area stay loaded somehow
for _, entity in ipairs(worldedit.marker_region[name]) do
entity:remove()
end
worldedit.marker_region[name] = nil
end
if pos1 ~= nil and pos2 ~= nil then
local pos1, pos2 = worldedit.sort_pos(pos1, pos2)
local vec = vector.subtract(pos2, pos1)
local maxside = math.max(vec.x, math.max(vec.y, vec.z))
local limit = tonumber(minetest.settings:get("active_object_send_range_blocks")) * 16
if maxside > limit * 1.5 then
-- The client likely won't be able to see the plane markers as intended anyway,
-- thus don't place them and also don't load the area into memory
return
end
local thickness = 0.2
local sizex, sizey, sizez = (1 + pos2.x - pos1.x) / 2, (1 + pos2.y - pos1.y) / 2, (1 + pos2.z - pos1.z) / 2
--make area stay loaded
local manip = minetest.get_voxel_manip()
manip:read_from_map(pos1, pos2)
local markers = {}
--XY plane markers
for _, z in ipairs({pos1.z - 0.5, pos2.z + 0.5}) do
local marker = minetest.add_entity({x=pos1.x + sizex - 0.5, y=pos1.y + sizey - 0.5, z=z}, "worldedit:region_cube")
if marker ~= nil then
marker:set_properties({
visual_size={x=sizex * 2, y=sizey * 2},
collisionbox = {-sizex, -sizey, -thickness, sizex, sizey, thickness},
})
marker:get_luaentity().player_name = name
table.insert(markers, marker)
end
end
--YZ plane markers
for _, x in ipairs({pos1.x - 0.5, pos2.x + 0.5}) do
local marker = minetest.add_entity({x=x, y=pos1.y + sizey - 0.5, z=pos1.z + sizez - 0.5}, "worldedit:region_cube")
if marker ~= nil then
marker:set_properties({
visual_size={x=sizez * 2, y=sizey * 2},
collisionbox = {-thickness, -sizey, -sizez, thickness, sizey, sizez},
})
marker:set_yaw(math.pi / 2)
marker:get_luaentity().player_name = name
table.insert(markers, marker)
end
end
worldedit.marker_region[name] = markers
end
end
minetest.register_entity(":worldedit:pos1", {
initial_properties = {
visual = "cube",
visual_size = {x=1.1, y=1.1},
textures = {"worldedit_pos1.png", "worldedit_pos1.png",
"worldedit_pos1.png", "worldedit_pos1.png",
"worldedit_pos1.png", "worldedit_pos1.png"},
collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55},
physical = false,
},
on_step = function(self, dtime)
if worldedit.marker1[self.player_name] == nil then
self.object:remove()
end
end,
on_punch = function(self, hitter)
self.object:remove()
worldedit.marker1[self.player_name] = nil
end,
})
minetest.register_entity(":worldedit:pos2", {
initial_properties = {
visual = "cube",
visual_size = {x=1.1, y=1.1},
textures = {"worldedit_pos2.png", "worldedit_pos2.png",
"worldedit_pos2.png", "worldedit_pos2.png",
"worldedit_pos2.png", "worldedit_pos2.png"},
collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55},
physical = false,
},
on_step = function(self, dtime)
if worldedit.marker2[self.player_name] == nil then
self.object:remove()
end
end,
on_punch = function(self, hitter)
self.object:remove()
worldedit.marker2[self.player_name] = nil
end,
})
minetest.register_entity(":worldedit:region_cube", {
initial_properties = {
visual = "upright_sprite",
textures = {"worldedit_cube.png"},
visual_size = {x=10, y=10},
physical = false,
},
on_step = function(self, dtime)
if worldedit.marker_region[self.player_name] == nil then
self.object:remove()
return
end
end,
on_punch = function(self, hitter)
local markers = worldedit.marker_region[self.player_name]
if not markers then
return
end
for _, entity in ipairs(markers) do
entity:remove()
end
worldedit.marker_region[self.player_name] = nil
end,
})
|
worldedit.marker1 = {}
worldedit.marker2 = {}
worldedit.marker_region = {}
--marks worldedit region position 1
worldedit.mark_pos1 = function(name)
local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name]
if pos1 ~= nil then
--make area stay loaded
local manip = minetest.get_voxel_manip()
manip:read_from_map(pos1, pos1)
end
if worldedit.marker1[name] ~= nil then --marker already exists
worldedit.marker1[name]:remove() --remove marker
worldedit.marker1[name] = nil
end
if pos1 ~= nil then
--add marker
worldedit.marker1[name] = minetest.add_entity(pos1, "worldedit:pos1")
if worldedit.marker1[name] ~= nil then
worldedit.marker1[name]:get_luaentity().player_name = name
end
end
worldedit.mark_region(name)
end
--marks worldedit region position 2
worldedit.mark_pos2 = function(name)
local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name]
if pos2 ~= nil then
--make area stay loaded
local manip = minetest.get_voxel_manip()
manip:read_from_map(pos2, pos2)
end
if worldedit.marker2[name] ~= nil then --marker already exists
worldedit.marker2[name]:remove() --remove marker
worldedit.marker2[name] = nil
end
if pos2 ~= nil then
--add marker
worldedit.marker2[name] = minetest.add_entity(pos2, "worldedit:pos2")
if worldedit.marker2[name] ~= nil then
worldedit.marker2[name]:get_luaentity().player_name = name
end
end
worldedit.mark_region(name)
end
worldedit.mark_region = function(name)
local pos1, pos2 = worldedit.pos1[name], worldedit.pos2[name]
if worldedit.marker_region[name] ~= nil then --marker already exists
--wip: make the area stay loaded somehow
for _, entity in ipairs(worldedit.marker_region[name]) do
entity:remove()
end
worldedit.marker_region[name] = nil
end
if pos1 ~= nil and pos2 ~= nil then
local pos1, pos2 = worldedit.sort_pos(pos1, pos2)
local vec = vector.subtract(pos2, pos1)
local maxside = math.max(vec.x, math.max(vec.y, vec.z))
local limit = tonumber(minetest.settings:get("active_object_send_range_blocks")) * 16
if maxside > limit * 1.5 then
-- The client likely won't be able to see the plane markers as intended anyway,
-- thus don't place them and also don't load the area into memory
return
end
local thickness = 0.2
local sizex, sizey, sizez = (1 + pos2.x - pos1.x) / 2, (1 + pos2.y - pos1.y) / 2, (1 + pos2.z - pos1.z) / 2
--make area stay loaded
local manip = minetest.get_voxel_manip()
manip:read_from_map(pos1, pos2)
local markers = {}
--XY plane markers
for _, z in ipairs({pos1.z - 0.5, pos2.z + 0.5}) do
local marker = minetest.add_entity({x=pos1.x + sizex - 0.5, y=pos1.y + sizey - 0.5, z=z}, "worldedit:region_cube")
if marker ~= nil then
marker:set_properties({
visual_size={x=sizex * 2, y=sizey * 2},
collisionbox = {-sizex, -sizey, -thickness, sizex, sizey, thickness},
})
marker:get_luaentity().player_name = name
table.insert(markers, marker)
end
end
--YZ plane markers
for _, x in ipairs({pos1.x - 0.5, pos2.x + 0.5}) do
local marker = minetest.add_entity({x=x, y=pos1.y + sizey - 0.5, z=pos1.z + sizez - 0.5}, "worldedit:region_cube")
if marker ~= nil then
marker:set_properties({
visual_size={x=sizez * 2, y=sizey * 2},
collisionbox = {-thickness, -sizey, -sizez, thickness, sizey, sizez},
})
marker:set_yaw(math.pi / 2)
marker:get_luaentity().player_name = name
table.insert(markers, marker)
end
end
worldedit.marker_region[name] = markers
end
end
minetest.register_entity(":worldedit:pos1", {
initial_properties = {
visual = "cube",
visual_size = {x=1.1, y=1.1},
textures = {"worldedit_pos1.png", "worldedit_pos1.png",
"worldedit_pos1.png", "worldedit_pos1.png",
"worldedit_pos1.png", "worldedit_pos1.png"},
collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55},
physical = false,
},
on_step = function(self, dtime)
if worldedit.marker1[self.player_name] == nil then
self.object:remove()
end
end,
on_punch = function(self, hitter)
self.object:remove()
worldedit.marker1[self.player_name] = nil
end,
on_blast = function(self, damage)
return false, false, {} -- don't damage or knockback
end,
})
minetest.register_entity(":worldedit:pos2", {
initial_properties = {
visual = "cube",
visual_size = {x=1.1, y=1.1},
textures = {"worldedit_pos2.png", "worldedit_pos2.png",
"worldedit_pos2.png", "worldedit_pos2.png",
"worldedit_pos2.png", "worldedit_pos2.png"},
collisionbox = {-0.55, -0.55, -0.55, 0.55, 0.55, 0.55},
physical = false,
},
on_step = function(self, dtime)
if worldedit.marker2[self.player_name] == nil then
self.object:remove()
end
end,
on_punch = function(self, hitter)
self.object:remove()
worldedit.marker2[self.player_name] = nil
end,
on_blast = function(self, damage)
return false, false, {} -- don't damage or knockback
end,
})
minetest.register_entity(":worldedit:region_cube", {
initial_properties = {
visual = "upright_sprite",
textures = {"worldedit_cube.png"},
visual_size = {x=10, y=10},
physical = false,
},
on_step = function(self, dtime)
if worldedit.marker_region[self.player_name] == nil then
self.object:remove()
return
end
end,
on_punch = function(self, hitter)
local markers = worldedit.marker_region[self.player_name]
if not markers then
return
end
for _, entity in ipairs(markers) do
entity:remove()
end
worldedit.marker_region[self.player_name] = nil
end,
on_blast = function(self, damage)
return false, false, {} -- don't damage or knockback
end,
})
|
Make region marker entities withstand TNT explosions
|
Make region marker entities withstand TNT explosions
Also fixes a crash when detonating TNT near them though this is
not our fault and the proper fix is pending in minetest_game.
|
Lua
|
agpl-3.0
|
Uberi/Minetest-WorldEdit
|
7c0f77383245802a21015ed3980aed81e253e869
|
includes/common.lua
|
includes/common.lua
|
local pairs, tcon, rawset, date = pairs, table.concat, rawset, os.date
local base_path, lfs = base_path, lfs
local str_replace = seawolf.text.str_replace
function page_set_title(header_title, title)
if header_title then
if title == nil then title = header_title end
ophal.title = title
ophal.header_title = (header_title and header_title .. ' | ' or '') .. settings.site.name
else
ophal.header_title = settings.site.name
end
end
do
local javascript = {}
local order = {}
function add_js(data, options)
if options == nil then options = {} end
if data ~= nil then
javascript[data] = options
rawset(order, #order + 1, data)
end
end
function get_js()
local output, options = {}
for _, v in pairs(order) do
options = javascript[v]
if options ~= nil and options.type == 'inline'then
rawset(output, #output + 1, ([[<script type="text/javascript">%s</script>
]]):format(options.content))
else
rawset(output, #output + 1, ([[<script type="text/javascript" src="%s%s?%s"></script>
]]):format(base_path, v, lfs.attributes(v, 'modification')))
end
end
return tcon(output)
end
end
do
local css = {
[('themes/%s/style.css'):format(settings.theme)] = {},
}
function add_css(data, options)
if options == nil then options = {} end
if data ~= nil then
css[data] = options
end
end
function get_css()
local output = {}
for k, v in pairs(css) do
rawset(output, #output + 1, ([[<link type="text/css" rel="stylesheet" media="all" href="%s%s?%s" />
]]):format(base_path, k, lfs.attributes(k, 'modification')))
end
return tcon(output)
end
end
function exit_ophal()
-- call hook exit
if module_invoke_all then
module_invoke_all 'exit'
end
-- destroy session (phase end)
if settings.sessionapi and session_write_close then
session_write_close()
end
-- flush output buffer
if settings.output_buffering then
output_flush()
end
end
--[[
Send the user to a different Ophal page.
This issues an on-site HTTP redirect. The function makes sure the redirected
URL is formatted correctly.
This function ends the request; use it rather than a print theme('page')
statement in your menu callback.
@param path
A Drupal path or a full URL.
@param query
The query string component, if any.
@param fragment
The destination fragment identifier (named anchor).
@param http_response_code
Valid values for an actual "goto" as per RFC 2616 section 10.3 are:
- 301 Moved Permanently (the recommended value for most redirects)
- 302 Found (default in Drupal and PHP, sometimes used for spamming search
engines)
- 303 See Other
- 304 Not Modified
- 305 Use Proxy
- 307 Temporary Redirect (an alternative to "503 Site Down for Maintenance")
Note: Other values are defined by RFC 2616, but are rarely used and poorly
supported.
@see get_destination()
]]
function goto(path, http_response_code)
path = path or ''
http_response_code = http_response_code or 302
local dest_url
dest_url = url(path, {absolute = true})
-- Remove newlines from the URL to avoid header injection attacks.
dest_url = str_replace({'\n', '\r'}, '', dest_url)
redirect(dest_url, http_response_code)
exit_ophal()
end
--[[
Format given unix timestamp by system date format.
]]
function format_date(uts, date_format)
return date(date_format and date_format or settings.date_format, uts)
end
|
local pairs, tcon, rawset, date = pairs, table.concat, rawset, os.date
local base_path, lfs = base_path, lfs
local str_replace, is_file = seawolf.text.str_replace, seawolf.fs.is_file
function page_set_title(header_title, title)
if header_title then
if title == nil then title = header_title end
ophal.title = title
ophal.header_title = (header_title and header_title .. ' | ' or '') .. settings.site.name
else
ophal.header_title = settings.site.name
end
end
do
local javascript = {}
local order = {}
function add_js(data, options)
if options == nil then options = {} end
if data ~= nil then
javascript[data] = options
rawset(order, #order + 1, data)
end
end
function get_js()
local output, options = {}
for _, v in pairs(order) do
options = javascript[v]
if options ~= nil and options.type == 'inline'then
rawset(output, #output + 1, ([[<script type="text/javascript">%s</script>
]]):format(options.content))
elseif is_file(v) then
rawset(output, #output + 1, ([[<script type="text/javascript" src="%s%s?%s"></script>
]]):format(base_path, v, lfs.attributes(v, 'modification')))
end
end
return tcon(output)
end
end
do
local css = {
[('themes/%s/style.css'):format(settings.theme)] = {},
}
function add_css(data, options)
if options == nil then options = {} end
if data ~= nil then
css[data] = options
end
end
function get_css()
local output = {}
for k, v in pairs(css) do
if is_file(k) then
rawset(output, #output + 1, ([[<link type="text/css" rel="stylesheet" media="all" href="%s%s?%s" />
]]):format(base_path, k, lfs.attributes(k, 'modification')))
end
end
return tcon(output)
end
end
function exit_ophal()
-- call hook exit
if module_invoke_all then
module_invoke_all 'exit'
end
-- destroy session (phase end)
if settings.sessionapi and session_write_close then
session_write_close()
end
-- flush output buffer
if settings.output_buffering then
output_flush()
end
end
--[[
Send the user to a different Ophal page.
This issues an on-site HTTP redirect. The function makes sure the redirected
URL is formatted correctly.
This function ends the request; use it rather than a print theme('page')
statement in your menu callback.
@param path
A Drupal path or a full URL.
@param query
The query string component, if any.
@param fragment
The destination fragment identifier (named anchor).
@param http_response_code
Valid values for an actual "goto" as per RFC 2616 section 10.3 are:
- 301 Moved Permanently (the recommended value for most redirects)
- 302 Found (default in Drupal and PHP, sometimes used for spamming search
engines)
- 303 See Other
- 304 Not Modified
- 305 Use Proxy
- 307 Temporary Redirect (an alternative to "503 Site Down for Maintenance")
Note: Other values are defined by RFC 2616, but are rarely used and poorly
supported.
@see get_destination()
]]
function goto(path, http_response_code)
path = path or ''
http_response_code = http_response_code or 302
local dest_url
dest_url = url(path, {absolute = true})
-- Remove newlines from the URL to avoid header injection attacks.
dest_url = str_replace({'\n', '\r'}, '', dest_url)
redirect(dest_url, http_response_code)
exit_ophal()
end
--[[
Format given unix timestamp by system date format.
]]
function format_date(uts, date_format)
return date(date_format and date_format or settings.date_format, uts)
end
|
Bug fix: get_css() and get_js() rendering missing files.
|
Bug fix: get_css() and get_js() rendering missing files.
|
Lua
|
agpl-3.0
|
ophal/core,coinzen/coinage,coinzen/coinage,coinzen/coinage,ophal/core,ophal/core
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.