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
|
|---|---|---|---|---|---|---|---|---|---|
aff20746428310aaf07c82f4c45073f891079e1e
|
applications/luci-splash/luasrc/controller/splash/splash.lua
|
applications/luci-splash/luasrc/controller/splash/splash.lua
|
module("luci.controller.splash.splash", package.seeall)
function index()
entry({"admin", "services", "splash"}, cbi("splash/splash"), "Client-Splash")
node("splash").target = call("action_dispatch")
node("splash", "activate").target = call("action_activate")
node("splash", "splash").target = template("splash_splash/splash")
end
function action_dispatch()
local mac = luci.sys.net.ip4mac(luci.http.getenv("REMOTE_ADDR")) or ""
local status = luci.util.execl("luci-splash status "..mac)[1]
if #mac > 0 and ( status == "whitelisted" or status == "lease" ) then
luci.http.redirect(luci.dispatcher.build_url())
else
luci.http.redirect(luci.dispatcher.build_url("splash", "splash"))
end
end
function action_activate()
local mac = luci.sys.net.ip4mac(luci.http.getenv("REMOTE_ADDR"))
if mac and luci.http.formvalue("accept") then
os.execute("luci-splash add "..mac.." >/dev/null 2>&1")
luci.http.redirect(luci.model.uci.cursor():get("freifunk", "community", "homepage"))
else
luci.http.redirect(luci.dispatcher.build_url())
end
end
|
module("luci.controller.splash.splash", package.seeall)
function index()
entry({"admin", "services", "splash"}, cbi("splash/splash"), "Client-Splash")
node("splash").target = call("action_dispatch")
node("splash", "activate").target = call("action_activate")
node("splash", "splash").target = template("splash_splash/splash")
end
function action_dispatch()
local mac = luci.sys.net.ip4mac(luci.http.getenv("REMOTE_ADDR")) or ""
local status = luci.util.execl("luci-splash status "..mac)[1]
if #mac > 0 and ( status == "whitelisted" or status == "lease" ) then
luci.http.redirect(luci.dispatcher.build_url())
else
luci.http.redirect(luci.dispatcher.build_url("splash", "splash"))
end
end
function action_activate()
local ip = luci.http.getenv("REMOTE_ADDR") or "127.0.0.1"
local mac = luci.sys.net.ip4mac(ip:match("^[\[::ffff:]*(%d+.%d+%.%d+%.%d+)\]*$"))
if mac and luci.http.formvalue("accept") then
os.execute("luci-splash add "..mac.." >/dev/null 2>&1")
luci.http.redirect(luci.model.uci.cursor():get("freifunk", "community", "homepage"))
else
luci.http.redirect(luci.dispatcher.build_url())
end
end
|
applications/luci-splash: properly fix mac address detection in mixed IPv4/IPv6 environments (thanks stargieg)
|
applications/luci-splash: properly fix mac address detection in mixed IPv4/IPv6 environments (thanks stargieg)
|
Lua
|
apache-2.0
|
deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci
|
348db49b920f83f5885b9809313a38b2c8eb18ef
|
src/romdisk/system/lib/org/xboot/core/Application.lua
|
src/romdisk/system/lib/org/xboot/core/Application.lua
|
---
-- The 'Application' class contains the execution environment of
-- current application.
--
-- @module Application
local M = Class()
---
-- Creates a new 'Application'.
--
-- @function [parent=#Application] new
-- @return New 'Application' object.
function M:init()
self.display = Display.new()
self.stage = DisplayObject.new()
self.asset = Asset.new()
self.stopwatch = Stopwatch.new()
self.timermanager = TimerManager.new()
self.timermanager:addTimer(Timer.new(1 / 60, 0, function(t, e)
self.stage:render(self.display, Event.new(Event.ENTER_FRAME))
self.display:present()
end))
self.running = true
application = self
stage = self.stage
asset = self.asset
timermanager = self.timermanager
require("main")
end
function M:quit()
self.running = false
end
function M:exec()
while true do
local info = pump()
if info ~= nil then
local e = Event.new(info.type, info)
self.stage:dispatch(e)
end
local elapsed = self.stopwatch:elapsed()
if elapsed ~= 0 then
self.stopwatch:reset()
self.timermanager:schedule(elapsed)
end
if not self.running then
return;
end
end
end
return M
|
---
-- The 'Application' class contains the execution environment of
-- current application.
--
-- @module Application
local M = Class()
---
-- Creates a new 'Application'.
--
-- @function [parent=#Application] new
-- @return New 'Application' object.
function M:init()
self.display = Display.new()
self.stage = DisplayObject.new()
self.asset = Asset.new()
self.stopwatch = Stopwatch.new()
self.timermanager = TimerManager.new()
self.timermanager:addTimer(Timer.new(1 / 60, 0, function(t, e)
self.stage:render(self.display, Event.new(Event.ENTER_FRAME))
self.display:present()
end))
self.running = true
application = self
stage = self.stage
asset = self.asset
timermanager = self.timermanager
require("main")
end
---
-- Quit application
--
-- @function [parent=#Application] quit
function M:quit()
self.running = false
end
---
-- Exec application
--
-- @function [parent=#Application] exec
function M:exec()
while self.running do
local info = pump()
if info ~= nil then
local e = Event.new(info.type, info)
self.stage:dispatch(e)
end
local elapsed = self.stopwatch:elapsed()
if elapsed ~= 0 then
self.stopwatch:reset()
self.timermanager:schedule(elapsed)
end
end
end
return M
|
fix Application.lua
|
fix Application.lua
|
Lua
|
mit
|
xboot/xboot,xboot/xboot
|
34abe3d7a12056c2ea3cda47b5be197652176120
|
src/plugins/finalcutpro/timeline/renameclip.lua
|
src/plugins/finalcutpro/timeline/renameclip.lua
|
--- === plugins.finalcutpro.timeline.renameclip ===
---
--- Rename Clip
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local require = require
--------------------------------------------------------------------------------
-- Logger:
--------------------------------------------------------------------------------
local log = require("hs.logger").new("renameClip")
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local axutils = require("cp.ui.axutils")
local Do = require("cp.rx.go.Do")
local fcp = require("cp.apple.finalcutpro")
local If = require("cp.rx.go.If")
local just = require("cp.just")
local tools = require("cp.tools")
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.timeline.renameclip",
group = "finalcutpro",
dependencies = {
["finalcutpro.commands"] = "fcpxCmds",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Rename Clip Rx:
--------------------------------------------------------------------------------
local doRenameClip = function()
return If(function()
local selectedClip
local content = fcp:timeline():contents()
local selectedClips = content:selectedClipsUI()
if selectedClips and #selectedClips == 1 then
selectedClip = selectedClips[1]
end
return selectedClip
end)
:Then(function(selectedClip)
selectedClip:performAction("AXShowMenu")
return selectedClip
end)
:Then(function(selectedClip)
local parent = selectedClip:attributeValue("AXParent")
local menu = axutils.childWithRole(parent, "AXMenu")
local item = axutils.childWith(menu, "AXTitle", fcp:string("FFRename Bin Object"))
if item then
item:performAction("AXPress")
return
end
end)
:Catch(function(message)
tools.playErrorSound()
log.ef("doRenameClip: %s", message)
end)
end
--------------------------------------------------------------------------------
-- Add Commands:
--------------------------------------------------------------------------------
deps.fcpxCmds:add("renameClip")
:whenActivated(function() doRenameClip():Now() end)
:titled(fcp:string("FFRename Bin Object"))
return mod
end
return plugin
|
--- === plugins.finalcutpro.timeline.renameclip ===
---
--- Rename Clip
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local require = require
--------------------------------------------------------------------------------
-- Logger:
--------------------------------------------------------------------------------
local log = require("hs.logger").new("renameClip")
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local axutils = require("cp.ui.axutils")
local fcp = require("cp.apple.finalcutpro")
local If = require("cp.rx.go.If")
local tools = require("cp.tools")
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.timeline.renameclip",
group = "finalcutpro",
dependencies = {
["finalcutpro.commands"] = "fcpxCmds",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Rename Clip Rx:
--------------------------------------------------------------------------------
local doRenameClip = function()
return If(function()
local selectedClip
local content = fcp:timeline():contents()
local selectedClips = content:selectedClipsUI()
if selectedClips and #selectedClips == 1 then
selectedClip = selectedClips[1]
end
return selectedClip
end)
:Then(function(selectedClip)
selectedClip:performAction("AXShowMenu")
return selectedClip
end)
:Then(function(selectedClip)
local parent = selectedClip:attributeValue("AXParent")
local menu = axutils.childWithRole(parent, "AXMenu")
local item = axutils.childWith(menu, "AXTitle", fcp:string("FFRename Bin Object"))
if item then
item:performAction("AXPress")
return
end
end)
:Catch(function(message)
tools.playErrorSound()
log.ef("doRenameClip: %s", message)
end)
end
--------------------------------------------------------------------------------
-- Add Commands:
--------------------------------------------------------------------------------
deps.fcpxCmds:add("renameClip")
:whenActivated(function() doRenameClip():Now() end)
:titled(fcp:string("FFRename Bin Object"))
return mod
end
return plugin
|
#1583
|
#1583
- Fixed @stickler-ci errors
|
Lua
|
mit
|
CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks,CommandPost/CommandPost
|
74a705f9e25f4e6bca295ea8ae8e9339a465b0d0
|
test/utils.lua
|
test/utils.lua
|
local pop3 = require "pop3"
local lunit = require "lunit"
local assert_equal, assert_not_equal = lunit.assert_equal, lunit.assert_not_equal
DIRSEP = package.config:sub(1,1)
function new_message(...)
local msg = pop3.message(...)
msg:set_eol('\r\n')
msg:set_cp('windows-1251')
return msg
end
function load_msg_table(t)
return new_message(t)
end
function load_msg_file(f)
local m = {}
for str in io.lines(f) do
table.insert(m,str)
end
return load_msg_table(m)
end
local cmp_t
local function cmp_v(v1,v2)
local flag = true
if type(v1) == 'table' then
flag = (type(v2) == 'table') and cmp_t(v1, v2)
else
flag = (v1 == v2)
end
return flag
end
function cmp_t(t1,t2)
for k in pairs(t2)do
if t1[k] == nil then
return false
end
end
for k,v in pairs(t1)do
if not cmp_v(t2[k],v) then
return false
end
end
return true
end
is_equal = cmp_v
function path_join(...)
local t = {...}
local result = t[1]
for i = 2, #t do result = result .. DIRSEP .. t[i] end
return result
end
function read_file(path)
local f = assert(io.open(path, 'rb'))
local str = f:read('*all')
f:close()
return str
end
function assert_str_file(str, fname, msg)
assert_equal(str, read_file(fname), msg)
end
function assert_not_str_file(str, fname, msg)
assert_not_equal(str, read_file(fname), msg)
end
function str_line_iter(str, nl)
return coroutine.wrap(function()
for line in str:gmatch("(.-)"..nl)do
coroutine.yield(line)
end
end)
end
function file_line_iter(path, nl)
return str_line_iter(read_file(path),nl)
end
function cmp_lines(it1, it2)
while true do
local line = it1()
if line ~= it2() then return false end
if line == nil then return true end
end
end
local test_server = {
-- out_buf = {}; --
-- in_buf = {}; --
};
function test_server:receive()
return table.remove(self.out_buf,1)
end
function test_server:send(stuff)
local v = table.remove(self.in_buf,1)
if type(v) == 'table' then
local i = v[2]
if type(i) == 'string' then i = {i} end
for k = #i, 1, -1 do
table.insert(self.out_buf,1,i[k])
end
v = v[1]
end
assert_equal(v, stuff)
return true
end
function test_server:close() end
function test_server:settimeout() end
function new_test_server(t)
return function(host, port)
return setmetatable({
out_buf = t.o;
in_buf = t.i;
}, {__index=test_server})
end
end
|
local pop3 = require "pop3"
local lunit = require "lunit"
local assert_equal, assert_not_equal = lunit.assert_equal, lunit.assert_not_equal
DIRSEP = package.config:sub(1,1)
function new_message(...)
local msg = pop3.message(...)
msg:set_eol('\r\n')
msg:set_cp('windows-1251')
return msg
end
function load_msg_table(t)
return new_message(t)
end
function load_msg_file(f)
local m = {}
local data = assert(read_file(f))
for str in data:gmatch("(.-)\r?\n") do
table.insert(m,str)
end
return load_msg_table(m)
end
local cmp_t
local function cmp_v(v1,v2)
local flag = true
if type(v1) == 'table' then
flag = (type(v2) == 'table') and cmp_t(v1, v2)
else
flag = (v1 == v2)
end
return flag
end
function cmp_t(t1,t2)
for k in pairs(t2)do
if t1[k] == nil then
return false
end
end
for k,v in pairs(t1)do
if not cmp_v(t2[k],v) then
return false
end
end
return true
end
is_equal = cmp_v
function path_join(...)
local t = {...}
local result = t[1]
for i = 2, #t do result = result .. DIRSEP .. t[i] end
return result
end
function read_file(path)
local f = assert(io.open(path, 'rb'))
local str = f:read('*all')
f:close()
return str
end
function assert_str_file(str, fname, msg)
assert_equal(str, read_file(fname), msg)
end
function assert_not_str_file(str, fname, msg)
assert_not_equal(str, read_file(fname), msg)
end
function str_line_iter(str, nl)
return coroutine.wrap(function()
for line in str:gmatch("(.-)"..nl)do
coroutine.yield(line)
end
end)
end
function file_line_iter(path, nl)
return str_line_iter(read_file(path),nl)
end
function cmp_lines(it1, it2)
while true do
local line = it1()
if line ~= it2() then return false end
if line == nil then return true end
end
end
local test_server = {
-- out_buf = {}; --
-- in_buf = {}; --
};
function test_server:receive()
return table.remove(self.out_buf,1)
end
function test_server:send(stuff)
local v = table.remove(self.in_buf,1)
if type(v) == 'table' then
local i = v[2]
if type(i) == 'string' then i = {i} end
for k = #i, 1, -1 do
table.insert(self.out_buf,1,i[k])
end
v = v[1]
end
assert_equal(v, stuff)
return true
end
function test_server:close() end
function test_server:settimeout() end
function new_test_server(t)
return function(host, port)
return setmetatable({
out_buf = t.o;
in_buf = t.i;
}, {__index=test_server})
end
end
|
Fix. Test on linux system.
|
Fix. Test on linux system.
|
Lua
|
mit
|
moteus/lua-pop3
|
9b0dd01b01feb133d30f7cd42313cbe299882165
|
gin/db/sql.lua
|
gin/db/sql.lua
|
-- perf
local error = error
local pairs = pairs
local require = require
local setmetatable = setmetatable
local required_options = {
adapter = true,
host = true,
port = true,
database = true,
user = true,
password = true,
pool = true
}
local SqlDatabase = {}
SqlDatabase.__index = SqlDatabase
function SqlDatabase.new(options)
-- check for required params
local remaining_options = required_options
for k, _ in pairs(options) do remaining_options[k] = nil end
local missing_options = {}
for k, _ in pairs(remaining_options) do tinsert(missing_options, k) end
if #missing_options > 0 then error("missing required database options: " .. tconcat(missing_options, ', ')) end
-- init adapter
local adapter = require 'gin.db.sql.mysql.adapter'
-- init instance
local instance = {
options = options,
adapter = adapter
}
setmetatable(instance, SqlDatabase)
return instance
end
function SqlDatabase:execute(sql)
return self.adapter.execute(self.options, sql)
end
function SqlDatabase:execute_and_return_last_id(sql)
return self.adapter.execute_and_return_last_id(self.options, sql)
end
function SqlDatabase:quote(str)
return self.adapter.quote(self.options, str)
end
function SqlDatabase:tables()
return self.adapter.tables(self.options)
end
function SqlDatabase:schema()
return self.adapter.schema(self.options)
end
return SqlDatabase
|
-- perf
local error = error
local pairs = pairs
local require = require
local setmetatable = setmetatable
local SqlDatabase = {}
SqlDatabase.__index = SqlDatabase
function SqlDatabase.new(options)
-- check for required params
local required_options = {
adapter = true,
host = true,
port = true,
database = true,
user = true,
password = true,
pool = true
}
for k, _ in pairs(options) do required_options[k] = nil end
local missing_options = {}
for k, _ in pairs(required_options) do tinsert(missing_options, k) end
if #missing_options > 0 then error("missing required database options: " .. tconcat(missing_options, ', ')) end
-- init adapter
local adapter = require('gin.db.sql.' .. options.adapter .. '.adapter')
-- init instance
local instance = {
options = options,
adapter = adapter
}
setmetatable(instance, SqlDatabase)
return instance
end
function SqlDatabase:execute(sql)
return self.adapter.execute(self.options, sql)
end
function SqlDatabase:execute_and_return_last_id(sql)
return self.adapter.execute_and_return_last_id(self.options, sql)
end
function SqlDatabase:quote(str)
return self.adapter.quote(self.options, str)
end
function SqlDatabase:tables()
return self.adapter.tables(self.options)
end
function SqlDatabase:schema()
return self.adapter.schema(self.options)
end
return SqlDatabase
|
Fix adapter being hardcoded to MySQL and ensure params get redefined entirely.
|
Fix adapter being hardcoded to MySQL and ensure params get redefined entirely.
[#60908070]
|
Lua
|
mit
|
ostinelli/gin,istr/gin
|
fa82be6ea8559eb722ac96fff0181392bda02a4e
|
rima.lua
|
rima.lua
|
--
-- rima.lua
--
--
-- Task manager for imap collector.
-- Task's key is a user email address.
-- Rima can manage some tasks with the same key.
-- Tasks with identical keys will be groupped and managed as one bunch of tasks.
--
-- Producers can adds tasks by rima_put() calls.
-- Consumer request a bunch of tasks (with common key) by calling rima_get().
-- When Rima gives a task to worker it locks the key until worker calls rima_done(key).
-- Rima does not return task with already locked keys.
--
--
-- Space 0: Remote IMAP Collector Task Queue
-- Tuple: { task_id (NUM64), key (STR), task_description (NUM), add_time (NUM) }
-- Index 0: TREE { task_id }
-- Index 1: TREE { key, task_id }
--
-- Space 2: Task Priority
-- Tuple: { key (STR), priority (NUM), is_locked (NUM), lock_time (NUM) }
-- Index 0: TREE { key }
-- Index 1: TREE { priority, is_locked }
--
local no_priority = 4294967295
--
-- Put task to the queue.
--
local function rima_put_impl(key, data, prio)
-- insert task data into the queue
box.auto_increment(0, key, data, box.time())
-- increase priority of the key
local pr = box.select(2, 0, key)
if pr == nil then
box.insert(2, key, prio, 0, box.time())
elseif box.unpack('i', pr[1]) < prio or box.unpack('i', pr[1]) == no_priority then
box.update(2, key, "=p", 1, prio)
end
end
function rima_put(key, data) -- deprecated
rima_put_impl(key, data, 512)
end
function rima_put_prio(key, data) -- deprecated
rima_put_impl(key, data, 1024)
end
function rima_put_with_prio(key, data, prio)
prio = box.unpack('i', prio)
rima_put_impl(key, data, prio)
end
local function get_prio_key(prio)
for v in box.space[2].index[1]:iterator(box.index.EQ, prio, 0) do
local key = v[0]
-- lock the key and set prio to no_priority
box.update(2, key, "=p=p=p", 1, no_priority, 2, 1, 3, box.time())
return key
end
return nil
end
local function get_key_data_old(key) -- deprecated
if key == nil then return nil end
local result = {}
local tuples = { box.select_limit(0, 1, 0, 8000, key) }
for _, tuple in pairs(tuples) do
tuple = box.delete(0, tuple[0])
if tuple ~= nil then table.insert(result, tuple[2]) end
end
return result
end
local function get_key_data(key)
if key == nil then return nil end
local result = {}
local tuples = { box.select_limit(0, 1, 0, 8000, key) }
for _, tuple in pairs(tuples) do
tuple = box.delete(0, tuple[0])
if tuple ~= nil then
local add_time
if #tuple > 3 then
add_time = box.unpack('i', tuple[3])
else
add_time = box.time() -- deprecated
end
table.insert(result, { add_time, tuple[2] })
end
end
return result
end
local function rima_get_prio_impl_old(prio) -- deprecated
local key = get_prio_key(prio)
local result = get_key_data_old(key)
return key, result
end
local function rima_get_prio_impl(prio)
local key = get_prio_key(prio)
local result = get_key_data(key)
return key, result
end
--
-- Request tasks from the queue.
--
function rima_get_with_prio(prio) -- deprecated
prio = box.unpack('i', prio)
for i = 1,10 do
local key, result = rima_get_prio_impl_old(prio)
if key ~= nil then return key, unpack(result) end
box.fiber.sleep(0.001)
end
end
function rima_get_ex(prio)
prio = box.unpack('i', prio)
for i = 1,10 do
local key, result = rima_get_prio_impl(prio)
if key ~= nil then return key, unpack(result) end
box.fiber.sleep(0.001)
end
end
--
-- Notify manager that tasks for that key was completed.
-- Rima unlocks key and next rima_get() may returns tasks with such key.
--
function rima_done(key)
local pr = box.select(2, 0, key)
if pr == nil then return end
if box.unpack('i', pr[1]) == no_priority then
-- no tasks added while key was locked
box.delete(2, key)
else
box.update(2, key, "=p=p", 2, 0, 3, box.time())
end
end
--
-- Run expiration of tuples
--
local function is_expired(args, tuple)
if tuple == nil or #tuple <= args.fieldno then
return nil
end
-- expire only locked keys
if box.unpack('i', tuple[2]) == 0 then return false end
local field = tuple[args.fieldno]
local current_time = box.time()
local tuple_expire_time = box.unpack('i', field) + args.expiration_time
return current_time >= tuple_expire_time
end
local function delete_expired(spaceno, args, tuple)
rima_done(tuple[0])
end
dofile('expirationd.lua')
expirationd.run_task('expire_locks', 2, is_expired, delete_expired, {fieldno = 3, expiration_time = 30*60})
|
--
-- rima.lua
--
--
-- Task manager for imap collector.
-- Task's key is a user email address.
-- Rima can manage some tasks with the same key.
-- Tasks with identical keys will be groupped and managed as one bunch of tasks.
--
-- Producers can adds tasks by rima_put() calls.
-- Consumer request a bunch of tasks (with common key) by calling rima_get().
-- When Rima gives a task to worker it locks the key until worker calls rima_done(key).
-- Rima does not return task with already locked keys.
--
--
-- Space 0: Remote IMAP Collector Task Queue
-- Tuple: { task_id (NUM64), key (STR), task_description (NUM), add_time (NUM) }
-- Index 0: TREE { task_id }
-- Index 1: TREE { key, task_id }
--
-- Space 2: Task Priority
-- Tuple: { key (STR), priority (NUM), is_locked (NUM), lock_time (NUM) }
-- Index 0: TREE { key }
-- Index 1: TREE { priority, is_locked }
--
--
-- Put task to the queue.
--
local function rima_put_impl(key, data, prio)
-- insert task data into the queue
box.auto_increment(0, key, data, box.time())
-- increase priority of the key
local pr = box.select(2, 0, key)
if pr == nil then
box.insert(2, key, prio, 0, box.time())
elseif box.unpack('i', pr[1]) < prio then
box.update(2, key, "=p", 1, prio)
end
end
function rima_put(key, data) -- deprecated
rima_put_impl(key, data, 512)
end
function rima_put_prio(key, data) -- deprecated
rima_put_impl(key, data, 1024)
end
function rima_put_with_prio(key, data, prio)
prio = box.unpack('i', prio)
rima_put_impl(key, data, prio)
end
local function get_prio_key(prio)
for v in box.space[2].index[1]:iterator(box.index.EQ, prio, 0) do
local key = v[0]
-- lock the key
box.update(2, key, "=p=p", 2, 1, 3, box.time())
return key
end
return nil
end
local function get_key_data_old(key) -- deprecated
if key == nil then return nil end
local result = {}
local tuples = { box.select_limit(0, 1, 0, 8000, key) }
for _, tuple in pairs(tuples) do
tuple = box.delete(0, tuple[0])
if tuple ~= nil then table.insert(result, tuple[2]) end
end
return result
end
local function get_key_data(key)
if key == nil then return nil end
local result = {}
local tuples = { box.select_limit(0, 1, 0, 2000, key) }
for _, tuple in pairs(tuples) do
tuple = box.delete(0, tuple[0])
if tuple ~= nil then
local add_time
if #tuple > 3 then
add_time = box.unpack('i', tuple[3])
else
add_time = box.time() -- deprecated
end
table.insert(result, { add_time, tuple[2] } )
end
end
return result
end
local function rima_get_prio_impl_old(prio) -- deprecated
local key = get_prio_key(prio)
local result = get_key_data_old(key)
return key, result
end
local function rima_get_prio_impl(prio)
local key = get_prio_key(prio)
local result = get_key_data(key)
return key, result
end
--
-- Request tasks from the queue.
--
function rima_get_with_prio(prio) -- deprecated
prio = box.unpack('i', prio)
for i = 1,10 do
local key, result = rima_get_prio_impl_old(prio)
if key ~= nil then return key, unpack(result) end
box.fiber.sleep(0.001)
end
end
function rima_get_ex(prio)
prio = box.unpack('i', prio)
for i = 1,10 do
local key, result = rima_get_prio_impl(prio)
if key ~= nil then return key, unpack(result) end
box.fiber.sleep(0.001)
end
end
--
-- Notify manager that tasks for that key was completed.
-- Rima unlocks key and next rima_get() may returns tasks with such key.
--
function rima_done(key)
local pr = box.select(2, 0, key)
if pr == nil then return end
if box.select(0, 1, key) == nil then
-- no tasks for this key in the queue
box.delete(2, key)
else
box.update(2, key, "=p=p", 2, 0, 3, box.time())
end
end
--
-- Run expiration of tuples
--
local function is_expired(args, tuple)
if tuple == nil or #tuple <= args.fieldno then
return nil
end
-- expire only locked keys
if tuple[2] == '' then return false end
print("tuple[2] = " .. box.unpack('i', tuple[2]))
local field = tuple[args.fieldno]
local current_time = box.time()
local tuple_expire_time = box.unpack('i', field) + args.expiration_time
return current_time >= tuple_expire_time
end
local function delete_expired(spaceno, args, tuple)
rima_done(tuple[0])
end
dofile('expirationd.lua')
expirationd.run_task('expire_locks', 2, is_expired, delete_expired, {fieldno = 3, expiration_time = 30*60})
|
rima.lua: bug fixes
|
rima.lua: bug fixes
|
Lua
|
bsd-2-clause
|
mailru/tntlua,BHYCHIK/tntlua,spectrec/tntlua,grechkin-pogrebnyakov/tntlua,derElektrobesen/tntlua
|
d8e45b4e7c234e72d5dd87e88b4efdb45ddef2dd
|
frontend/ui/reader/readertypeset.lua
|
frontend/ui/reader/readertypeset.lua
|
ReaderTypeset = InputContainer:new{
css_menu_title = _("Set render style"),
css = nil,
internal_css = true,
}
function ReaderTypeset:init()
self.ui.menu:registerToMainMenu(self)
end
function ReaderTypeset:onReadSettings(config)
self.css = config:readSetting("css")
if self.css and self.css ~= "" then
self.ui.document:setStyleSheet(self.css)
else
self.ui.document:setStyleSheet("")
self.css = nil
end
self.embedded_css = config:readSetting("embedded_css")
-- default to enable embedded css
if self.embedded_css == nil then
self.embedded_css = true
end
if not self.embedded_css then
self.ui.document:setEmbeddedStyleSheet(0)
end
end
function ReaderTypeset:onCloseDocument()
self.ui.doc_settings:saveSetting("css", self.css)
self.ui.doc_settings:saveSetting("embedded_css", self.embedded_css)
end
function ReaderTypeset:onToggleEmbeddedStyleSheet()
self:toggleEmbeddedStyleSheet()
return true
end
function ReaderTypeset:genStyleSheetMenu()
local file_list = {
{
text = _("clear all external styles"),
callback = function()
self:setStyleSheet(nil)
end
},
{
text = _("Auto"),
callback = function()
self:setStyleSheet(self.ui.document.default_css)
end
},
}
for f in lfs.dir("./data") do
if lfs.attributes("./data/"..f, "mode") == "file" and string.match(f, "%.css$") then
table.insert(file_list, {
text = f,
callback = function()
self:setStyleSheet("./data/"..f)
end
})
end
end
return file_list
end
function ReaderTypeset:setStyleSheet(new_css)
if new_css ~= self.css then
--DEBUG("setting css to ", new_css)
self.css = new_css
if new_css == nil then
new_css = ""
end
self.ui.document:setStyleSheet(new_css)
self.ui:handleEvent(Event:new("UpdatePos"))
end
end
function ReaderTypeset:setEmbededStyleSheetOnly()
if self.css ~= nil then
-- clear applied css
self.ui.document:setStyleSheet("")
self.ui.document:setEmbeddedStyleSheet(1)
self.css = nil
self.ui:handleEvent(Event:new("UpdatePos"))
end
end
function ReaderTypeset:toggleEmbeddedStyleSheet()
if self.embedded_css then
self.ui.document:setEmbeddedStyleSheet(0)
self.embedded_css = false
else
self.ui.document:setEmbeddedStyleSheet(1)
self.embedded_css = true
end
self.ui:handleEvent(Event:new("UpdatePos"))
end
function ReaderTypeset:addToMainMenu(tab_item_table)
-- insert table to main reader menu
table.insert(tab_item_table.typeset, {
text = self.css_menu_title,
sub_item_table = self:genStyleSheetMenu(),
})
end
|
ReaderTypeset = InputContainer:new{
css_menu_title = _("Set render style"),
css = nil,
internal_css = true,
}
function ReaderTypeset:init()
self.ui.menu:registerToMainMenu(self)
end
function ReaderTypeset:onReadSettings(config)
self.css = config:readSetting("css")
if self.css and self.css ~= "" then
self.ui.document:setStyleSheet(self.css)
else
self.ui.document:setStyleSheet("")
self.css = nil
end
self.embedded_css = config:readSetting("embedded_css")
-- default to enable embedded css
if self.embedded_css == nil then
self.embedded_css = true
end
if not self.embedded_css then
self.ui.document:setEmbeddedStyleSheet(0)
end
end
function ReaderTypeset:onCloseDocument()
self.ui.doc_settings:saveSetting("css", self.css)
self.ui.doc_settings:saveSetting("embedded_css", self.embedded_css)
end
function ReaderTypeset:onToggleEmbeddedStyleSheet(toggle)
self:toggleEmbeddedStyleSheet(toggle)
return true
end
function ReaderTypeset:genStyleSheetMenu()
local file_list = {
{
text = _("clear all external styles"),
callback = function()
self:setStyleSheet(nil)
end
},
{
text = _("Auto"),
callback = function()
self:setStyleSheet(self.ui.document.default_css)
end
},
}
for f in lfs.dir("./data") do
if lfs.attributes("./data/"..f, "mode") == "file" and string.match(f, "%.css$") then
table.insert(file_list, {
text = f,
callback = function()
self:setStyleSheet("./data/"..f)
end
})
end
end
return file_list
end
function ReaderTypeset:setStyleSheet(new_css)
if new_css ~= self.css then
--DEBUG("setting css to ", new_css)
self.css = new_css
if new_css == nil then
new_css = ""
end
self.ui.document:setStyleSheet(new_css)
self.ui:handleEvent(Event:new("UpdatePos"))
end
end
function ReaderTypeset:setEmbededStyleSheetOnly()
if self.css ~= nil then
-- clear applied css
self.ui.document:setStyleSheet("")
self.ui.document:setEmbeddedStyleSheet(1)
self.css = nil
self.ui:handleEvent(Event:new("UpdatePos"))
end
end
function ReaderTypeset:toggleEmbeddedStyleSheet(toggle)
if not toggle then
self.ui.document:setEmbeddedStyleSheet(0)
self.embedded_css = false
else
self.ui.document:setEmbeddedStyleSheet(1)
self.embedded_css = true
end
self.ui:handleEvent(Event:new("UpdatePos"))
end
function ReaderTypeset:addToMainMenu(tab_item_table)
-- insert table to main reader menu
table.insert(tab_item_table.typeset, {
text = self.css_menu_title,
sub_item_table = self:genStyleSheetMenu(),
})
end
|
bugfix: embedded css toggle now shows correct status
|
bugfix: embedded css toggle now shows correct status
|
Lua
|
agpl-3.0
|
mihailim/koreader,chihyang/koreader,Frenzie/koreader,houqp/koreader,robert00s/koreader,NiLuJe/koreader,poire-z/koreader,ashang/koreader,ashhher3/koreader,noname007/koreader,koreader/koreader,chrox/koreader,Hzj-jie/koreader,apletnev/koreader,poire-z/koreader,Frenzie/koreader,NiLuJe/koreader,pazos/koreader,Markismus/koreader,frankyifei/koreader,NickSavage/koreader,mwoz123/koreader,koreader/koreader,lgeek/koreader
|
678cea9890ea6880c3e464d24a361ce0926b7152
|
slt2.lua
|
slt2.lua
|
--[[
-- slt2 - Simple Lua Template 2
--
-- Project page: https://github.com/henix/slt2
--
-- @License
-- MIT License
--
-- @Copyright
-- Copyright (C) 2012-2013 henix.
--]]
local slt2 = {}
-- process included file
-- @return string
local function precompile(template, start_tag, end_tag)
local result = {}
local start_tag_inc = start_tag..'include:'
local start1, end1 = string.find(template, start_tag_inc, 1, true)
local start2 = nil
local end2 = 0
while start1 ~= nil do
if start1 > end2 + 1 then -- for beginning part of file
table.insert(result, string.sub(template, end2 + 1, start1 - 1))
end
start2, end2 = string.find(template, end_tag, end1 + 1, true)
assert(start2, 'end tag "'..end_tag..'" missing')
do -- recursively include the file
local filename = assert(loadstring('return '..string.sub(template, end1 + 1, start2 - 1)))()
assert(filename)
local fin = assert(io.open(filename))
-- TODO: detect cyclic inclusion?
table.insert(result, precompile(fin:read('*a'), start_tag, end_tag))
fin:close()
end
start1, end1 = string.find(template, start_tag_inc, end2 + 1, true)
end
table.insert(result, string.sub(template, end2 + 1))
return table.concat(result)
end
-- @return { name = string, code = string / function}
function slt2.loadstring(template, start_tag, end_tag, tmpl_name)
-- compile it to lua code
local lua_code = {}
start_tag = start_tag or '#{'
end_tag = end_tag or '}#'
local output_func = "coroutine.yield"
template = precompile(template, start_tag, end_tag)
local start1, end1 = string.find(template, start_tag, 1, true)
local start2 = nil
local end2 = 0
local cEqual = string.byte('=', 1)
while start1 ~= nil do
if start1 > end2 + 1 then
table.insert(lua_code, output_func..'('..string.format("%q", string.sub(template, end2 + 1, start1 - 1))..')')
end
start2, end2 = string.find(template, end_tag, end1 + 1, true)
assert(start2, 'end_tag "'..end_tag..'" missing')
if string.byte(template, end1 + 1) == cEqual then
table.insert(lua_code, output_func..'('..string.sub(template, end1 + 2, start2 - 1)..')')
else
table.insert(lua_code, string.sub(template, end1 + 1, start2 - 1))
end
start1, end1 = string.find(template, start_tag, end2 + 1, true)
end
table.insert(lua_code, output_func..'('..string.format("%q", string.sub(template, end2 + 1))..')')
local ret = { name = tmpl_name or '=(slt2.loadstring)' }
if setfenv == nil then -- lua 5.2
ret.code = table.concat(lua_code, '\n')
else -- lua 5.1
ret.code = assert(loadstring(table.concat(lua_code, '\n'), ret.name))
end
return ret
end
-- @return { name = string, code = string / function }
function slt2.loadfile(filename, start_tag, end_tag)
local fin = assert(io.open(filename))
local all = fin:read('*a')
fin:close()
local ret = slt2.loadstring(all, start_tag, end_tag, filename)
ret.name = filename
return ret
end
local mt52 = { __index = _ENV }
local mt51 = { __index = _G }
-- @return a coroutine function
function slt2.render_co(t, env)
local f
if setfenv == nil then -- lua 5.2
if env ~= nil then
setmetatable(env, mt52)
end
f = assert(load(t.code, t.name, 't', env or _ENV))
else -- lua 5.1
if env ~= nil then
setmetatable(env, mt51)
end
f = setfenv(t.code, env or _G)
end
return f
end
-- @return string
function slt2.render(t, env)
local result = {}
local f = coroutine.wrap(slt2.render_co(t, env))
local chunk = f()
while chunk ~= nil do
table.insert(result, chunk)
chunk = f()
end
return table.concat(result)
end
return slt2
|
--[[
-- slt2 - Simple Lua Template 2
--
-- Project page: https://github.com/henix/slt2
--
-- @License
-- MIT License
--
-- @Copyright
-- Copyright (C) 2012-2013 henix.
--]]
local slt2 = {}
-- process included file
-- @return string
local function precompile(template, start_tag, end_tag)
local result = {}
local start_tag_inc = start_tag..'include:'
local start1, end1 = string.find(template, start_tag_inc, 1, true)
local start2 = nil
local end2 = 0
while start1 ~= nil do
if start1 > end2 + 1 then -- for beginning part of file
table.insert(result, string.sub(template, end2 + 1, start1 - 1))
end
start2, end2 = string.find(template, end_tag, end1 + 1, true)
assert(start2, 'end tag "'..end_tag..'" missing')
do -- recursively include the file
local filename = assert(loadstring('return '..string.sub(template, end1 + 1, start2 - 1)))()
assert(filename)
local fin = assert(io.open(filename))
-- TODO: detect cyclic inclusion?
table.insert(result, precompile(fin:read('*a'), start_tag, end_tag))
fin:close()
end
start1, end1 = string.find(template, start_tag_inc, end2 + 1, true)
end
table.insert(result, string.sub(template, end2 + 1))
return table.concat(result)
end
-- @return { name = string, code = string / function}
function slt2.loadstring(template, start_tag, end_tag, tmpl_name)
-- compile it to lua code
local lua_code = {}
start_tag = start_tag or '#{'
end_tag = end_tag or '}#'
local output_func = "coroutine.yield"
template = precompile(template, start_tag, end_tag)
local start1, end1 = string.find(template, start_tag, 1, true)
local start2 = nil
local end2 = 0
local cEqual = string.byte('=', 1)
while start1 ~= nil do
if start1 > end2 + 1 then
table.insert(lua_code, output_func..'('..string.format("%q", string.sub(template, end2 + 1, start1 - 1))..')')
end
start2, end2 = string.find(template, end_tag, end1 + 1, true)
assert(start2, 'end_tag "'..end_tag..'" missing')
if string.byte(template, end1 + 1) == cEqual then
table.insert(lua_code, output_func..'('..string.sub(template, end1 + 2, start2 - 1)..')')
else
table.insert(lua_code, string.sub(template, end1 + 1, start2 - 1))
end
start1, end1 = string.find(template, start_tag, end2 + 1, true)
end
table.insert(lua_code, output_func..'('..string.format("%q", string.sub(template, end2 + 1))..')')
local ret = { name = tmpl_name or '=(slt2.loadstring)' }
if setfenv == nil then -- lua 5.2
ret.code = table.concat(lua_code, '\n')
else -- lua 5.1
ret.code = assert(loadstring(table.concat(lua_code, '\n'), ret.name))
end
return ret
end
-- @return { name = string, code = string / function }
function slt2.loadfile(filename, start_tag, end_tag)
local fin = assert(io.open(filename))
local all = fin:read('*a')
fin:close()
local ret = slt2.loadstring(all, start_tag, end_tag, filename)
ret.name = filename
return ret
end
local mt52 = { __index = _ENV }
local mt51 = { __index = _G }
-- @return a coroutine function
function slt2.render_co(t, env)
local f
if setfenv == nil then -- lua 5.2
if env ~= nil then
setmetatable(env, mt52)
end
f = assert(load(t.code, t.name, 't', env or _ENV))
else -- lua 5.1
if env ~= nil then
setmetatable(env, mt51)
end
f = setfenv(t.code, env or _G)
end
return f
end
-- @return string
function slt2.render(t, env)
local result = {}
local co = coroutine.create(slt2.render_co(t, env))
while coroutine.status(co) ~= 'dead' do
local ok, chunk = coroutine.resume(co)
if not ok then
error(chunk)
end
table.insert(result, chunk)
end
return table.concat(result)
end
return slt2
|
Allow yield nil values. Fix #5
|
Allow yield nil values. Fix #5
|
Lua
|
mit
|
FSMaxB/liluat
|
b23d15d719d52bf961e23f9c3a060f7d0f97f646
|
test.lua
|
test.lua
|
#!/usr/bin/env th
local torch = require 'torch'
torch.setdefaulttensortype('torch.DoubleTensor')
local gurobi = require 'gurobi'
local tester = torch.Tester()
local gurobiTest = torch.TestSuite()
local eps = 1e-5
function gurobiTest.SmallLP()
local env = gurobi.loadenv("")
local c = torch.Tensor{2.0, 1.0}
local G = torch.Tensor{{-1, 1}, {-1, -1}, {0, -1}, {1, -2}}
local h = torch.Tensor{1.0, -2.0, 0.0, 4.0}
local model = gurobi.newmodel(env, "", c)
gurobi.addconstrs(model, G, 'LE', h)
local status, x = gurobi.solve(model)
local optX = torch.Tensor{0.5, 1.5}
tester:asserteq(status, 2, 'Non-optimal status: ' .. status)
tester:assertTensorEq(x, optX, eps, 'Invalid optimal value.')
end
function gurobiTest.SmallLP_Incremental()
local env = gurobi.loadenv("")
-- minimize y
-- subject to y >= x
-- y >= -x
-- y >= x + 1
local c = torch.Tensor{0.0, 1.0}
local G = torch.Tensor{{1, -1}, {-1, -1}, {1, -1}}
local h = torch.Tensor{0.0, 0.0, -1.0}
local env = gurobi.loadenv("")
local model = gurobi.newmodel(env, "", c)
local I = {{1,2}}
gurobi.addconstrs(model, G[I], 'LE', h[I])
local status, x = gurobi.solve(model)
local optX = torch.Tensor{0.0, 0.0}
tester:asserteq(status, 2, 'Non-optimal status: ' .. status)
tester:assertTensorEq(x, optX, eps, 'Invalid optimal value.')
gurobi.addconstr(model, G[3], 'LE', h[3])
status, x = gurobi.solve(model)
optX = torch.Tensor{-0.5, 0.5}
tester:asserteq(status, 2, 'Non-optimal status: ' .. status)
tester:assertTensorEq(x, optX, eps, 'Invalid optimal value.')
end
tester:add(gurobiTest)
tester:run()
|
#!/usr/bin/env th
local torch = require 'torch'
torch.setdefaulttensortype('torch.DoubleTensor')
local gurobi = require 'gurobi'
local tester = torch.Tester()
local gurobiTest = torch.TestSuite()
local eps = 1e-5
function gurobiTest.SmallLP()
local env = gurobi.loadenv("")
local c = torch.Tensor{2.0, 1.0}
local G = torch.Tensor{{-1, 1}, {-1, -1}, {0, -1}, {1, -2}}
local h = torch.Tensor{1.0, -2.0, 0.0, 4.0}
local model = gurobi.newmodel(env, "", c)
gurobi.addconstrs(model, G, 'LE', h)
local status, x = gurobi.solve(model)
local optX = torch.Tensor{0.5, 1.5}
tester:asserteq(status, 2, 'Non-optimal status: ' .. status)
tester:assertTensorEq(x, optX, eps, 'Invalid optimal value.')
end
function gurobiTest.SmallLP_Incremental()
-- minimize y
-- subject to y >= x
-- y >= -x
-- y >= x + 1
local c = torch.Tensor{0.0, 1.0}
local G = torch.Tensor{{1, -1}, {-1, -1}, {1, -1}}
local h = torch.Tensor{0.0, 0.0, -1.0}
local env = gurobi.loadenv("")
local model = gurobi.newmodel(env, "", c)
local I = {{1,2}}
gurobi.addconstrs(model, G[I], 'LE', h[I])
local status, x = gurobi.solve(model)
local optX = torch.Tensor{0.0, 0.0}
tester:asserteq(status, 2, 'Non-optimal status: ' .. status)
tester:assertTensorEq(x, optX, eps, 'Invalid optimal value.')
gurobi.addconstr(model, G[3], 'LE', h[3])
status, x = gurobi.solve(model)
optX = torch.Tensor{-0.5, 0.5}
tester:asserteq(status, 2, 'Non-optimal status: ' .. status)
tester:assertTensorEq(x, optX, eps, 'Invalid optimal value.')
end
tester:add(gurobiTest)
tester:run()
|
Fix multiple definitions of env.
|
Fix multiple definitions of env.
|
Lua
|
apache-2.0
|
bamos/gurobi.torch
|
b646a1b8a34b238340ce4e17756c1b7fc9894490
|
examples/login/gated.lua
|
examples/login/gated.lua
|
local msgserver = require "snax.msgserver"
local crypt = require "crypt"
local skynet = require "skynet"
local loginservice = tonumber(...)
local server = {}
local users = {}
local username_map = {}
local internal_id = 0
-- login server disallow multi login, so login_handler never be reentry
-- call by login server
function server.login_handler(uid, secret)
if users[uid] then
error(string.format("%s is already login", uid))
end
internal_id = internal_id + 1
local username = msgserver.username(uid, internal_id, servername)
-- you can use a pool to alloc new agent
local agent = skynet.newservice "msgagent"
local u = {
username = username,
agent = agent,
uid = uid,
subid = internal_id,
}
-- trash subid (no used)
skynet.call(agent, "lua", "login", uid, internal_id, secret)
users[uid] = u
username_map[username] = u
msgserver.login(username, secret)
-- you should return unique subid
return internal_id
end
-- call by agent
function server.logout_handler(uid, subid)
local u = users[uid]
if u then
local username = msgserver.username(uid, subid, servername)
assert(u.username == username)
msgserver.logout(u.username)
users[uid] = nil
username_map[u.username] = nil
skynet.call(loginservice, "lua", "logout",uid, subid)
end
end
-- call by login server
function server.kick_handler(uid, subid)
local u = users[uid]
if u then
local username = msgserver.username(uid, subid, servername)
assert(u.username == username)
-- NOTICE: logout may call skynet.exit, so you should use pcall.
pcall(skynet.call, u.agent, "lua", "logout")
end
end
-- call by self (when socket disconnect)
function server.disconnect_handler(username)
local u = username_map[username]
if u then
skynet.call(u.agent, "lua", "afk")
end
end
-- call by self (when recv a request from client)
function server.request_handler(username, msg, sz)
local u = username_map[username]
return skynet.tostring(skynet.rawcall(u.agent, "client", msg, sz))
end
-- call by self (when gate open)
function server.register_handler(name)
servername = name
skynet.call(loginservice, "lua", "register_gate", servername, skynet.self())
end
msgserver.start(server)
|
local msgserver = require "snax.msgserver"
local crypt = require "crypt"
local skynet = require "skynet"
local loginservice = tonumber(...)
local server = {}
local users = {}
local username_map = {}
local internal_id = 0
-- login server disallow multi login, so login_handler never be reentry
-- call by login server
function server.login_handler(uid, secret)
if users[uid] then
error(string.format("%s is already login", uid))
end
internal_id = internal_id + 1
local id = internal_id -- don't use internal_id directly
local username = msgserver.username(uid, id, servername)
-- you can use a pool to alloc new agent
local agent = skynet.newservice "msgagent"
local u = {
username = username,
agent = agent,
uid = uid,
subid = id,
}
-- trash subid (no used)
skynet.call(agent, "lua", "login", uid, id, secret)
users[uid] = u
username_map[username] = u
msgserver.login(username, secret)
-- you should return unique subid
return id
end
-- call by agent
function server.logout_handler(uid, subid)
local u = users[uid]
if u then
local username = msgserver.username(uid, subid, servername)
assert(u.username == username)
msgserver.logout(u.username)
users[uid] = nil
username_map[u.username] = nil
skynet.call(loginservice, "lua", "logout",uid, subid)
end
end
-- call by login server
function server.kick_handler(uid, subid)
local u = users[uid]
if u then
local username = msgserver.username(uid, subid, servername)
assert(u.username == username)
-- NOTICE: logout may call skynet.exit, so you should use pcall.
pcall(skynet.call, u.agent, "lua", "logout")
end
end
-- call by self (when socket disconnect)
function server.disconnect_handler(username)
local u = username_map[username]
if u then
skynet.call(u.agent, "lua", "afk")
end
end
-- call by self (when recv a request from client)
function server.request_handler(username, msg, sz)
local u = username_map[username]
return skynet.tostring(skynet.rawcall(u.agent, "client", msg, sz))
end
-- call by self (when gate open)
function server.register_handler(name)
servername = name
skynet.call(loginservice, "lua", "register_gate", servername, skynet.self())
end
msgserver.start(server)
|
fix login example
|
fix login example
|
Lua
|
mit
|
chuenlungwang/skynet,catinred2/skynet,puXiaoyi/skynet,lawnight/skynet,nightcj/mmo,hongling0/skynet,ag6ag/skynet,chenjiansnail/skynet,catinred2/skynet,icetoggle/skynet,zhangshiqian1214/skynet,ag6ag/skynet,QuiQiJingFeng/skynet,bttscut/skynet,great90/skynet,zhangshiqian1214/skynet,helling34/skynet,asanosoyokaze/skynet,zhangshiqian1214/skynet,sanikoyes/skynet,cloudwu/skynet,letmefly/skynet,yunGit/skynet,fhaoquan/skynet,vizewang/skynet,enulex/skynet,cdd990/skynet,zzh442856860/skynet,Ding8222/skynet,icetoggle/skynet,puXiaoyi/skynet,plsytj/skynet,plsytj/skynet,cmingjian/skynet,gitfancode/skynet,xjdrew/skynet,ilylia/skynet,vizewang/skynet,cdd990/skynet,nightcj/mmo,javachengwc/skynet,matinJ/skynet,cuit-zhaxin/skynet,xinjuncoding/skynet,yinjun322/skynet,fhaoquan/skynet,lawnight/skynet,MetSystem/skynet,MetSystem/skynet,sdgdsffdsfff/skynet,liuxuezhan/skynet,bingo235/skynet,zhoukk/skynet,fztcjjl/skynet,Markal128/skynet,korialuo/skynet,firedtoad/skynet,cpascal/skynet,letmefly/skynet,xcjmine/skynet,MetSystem/skynet,rainfiel/skynet,chenjiansnail/skynet,chuenlungwang/skynet,leezhongshan/skynet,ludi1991/skynet,yunGit/skynet,jiuaiwo1314/skynet,sundream/skynet,LiangMa/skynet,ilylia/skynet,plsytj/skynet,ludi1991/skynet,bigrpg/skynet,jxlczjp77/skynet,cuit-zhaxin/skynet,codingabc/skynet,kyle-wang/skynet,wangyi0226/skynet,kyle-wang/skynet,yinjun322/skynet,matinJ/skynet,xjdrew/skynet,lynx-seu/skynet,kyle-wang/skynet,nightcj/mmo,sanikoyes/skynet,Zirpon/skynet,samael65535/skynet,great90/skynet,lynx-seu/skynet,leezhongshan/skynet,icetoggle/skynet,samael65535/skynet,harryzeng/skynet,bigrpg/skynet,cloudwu/skynet,longmian/skynet,bigrpg/skynet,lc412/skynet,fztcjjl/skynet,enulex/skynet,zhoukk/skynet,ag6ag/skynet,zzh442856860/skynet,bingo235/skynet,Markal128/skynet,puXiaoyi/skynet,KAndQ/skynet,cpascal/skynet,KAndQ/skynet,harryzeng/skynet,ypengju/skynet_comment,catinred2/skynet,felixdae/skynet,great90/skynet,iskygame/skynet,wangjunwei01/skynet,xcjmine/skynet,pichina/skynet,wangyi0226/skynet,chenjiansnail/skynet,korialuo/skynet,hongling0/skynet,boyuegame/skynet,MoZhonghua/skynet,cmingjian/skynet,ludi1991/skynet,rainfiel/skynet,MRunFoss/skynet,korialuo/skynet,xinjuncoding/skynet,KittyCookie/skynet,JiessieDawn/skynet,zhangshiqian1214/skynet,zhangshiqian1214/skynet,boyuegame/skynet,LiangMa/skynet,MoZhonghua/skynet,ypengju/skynet_comment,lawnight/skynet,MoZhonghua/skynet,czlc/skynet,Zirpon/skynet,dymx101/skynet,Ding8222/skynet,KittyCookie/skynet,your-gatsby/skynet,javachengwc/skynet,letmefly/skynet,sdgdsffdsfff/skynet,LiangMa/skynet,felixdae/skynet,sanikoyes/skynet,helling34/skynet,firedtoad/skynet,iskygame/skynet,jxlczjp77/skynet,sundream/skynet,KittyCookie/skynet,bingo235/skynet,sundream/skynet,Ding8222/skynet,zhouxiaoxiaoxujian/skynet,jiuaiwo1314/skynet,JiessieDawn/skynet,pigparadise/skynet,liuxuezhan/skynet,wangjunwei01/skynet,MRunFoss/skynet,xinjuncoding/skynet,wangyi0226/skynet,gitfancode/skynet,cpascal/skynet,QuiQiJingFeng/skynet,cloudwu/skynet,asanosoyokaze/skynet,fhaoquan/skynet,yinjun322/skynet,firedtoad/skynet,kebo/skynet,Zirpon/skynet,jiuaiwo1314/skynet,microcai/skynet,liuxuezhan/skynet,bttscut/skynet,your-gatsby/skynet,codingabc/skynet,liuxuezhan/skynet,pigparadise/skynet,codingabc/skynet,harryzeng/skynet,helling34/skynet,Markal128/skynet,kebo/skynet,leezhongshan/skynet,pichina/skynet,KAndQ/skynet,xjdrew/skynet,felixdae/skynet,dymx101/skynet,dymx101/skynet,cdd990/skynet,pigparadise/skynet,hongling0/skynet,chuenlungwang/skynet,matinJ/skynet,QuiQiJingFeng/skynet,u20024804/skynet,JiessieDawn/skynet,pichina/skynet,cmingjian/skynet,u20024804/skynet,ilylia/skynet,wangjunwei01/skynet,chfg007/skynet,your-gatsby/skynet,jxlczjp77/skynet,samael65535/skynet,zhouxiaoxiaoxujian/skynet,longmian/skynet,czlc/skynet,javachengwc/skynet,kebo/skynet,iskygame/skynet,zhouxiaoxiaoxujian/skynet,lc412/skynet,czlc/skynet,MRunFoss/skynet,sdgdsffdsfff/skynet,lc412/skynet,chfg007/skynet,xcjmine/skynet,lynx-seu/skynet,rainfiel/skynet,gitfancode/skynet,chfg007/skynet,microcai/skynet,fztcjjl/skynet,letmefly/skynet,zhoukk/skynet,cuit-zhaxin/skynet,ypengju/skynet_comment,zhangshiqian1214/skynet,asanosoyokaze/skynet,microcai/skynet,vizewang/skynet,yunGit/skynet,bttscut/skynet,longmian/skynet,u20024804/skynet,ludi1991/skynet,enulex/skynet,boyuegame/skynet,lawnight/skynet,zzh442856860/skynet
|
574eab280a869a55682d4408b516529b0a73864b
|
Hydra/API/hydra.lua
|
Hydra/API/hydra.lua
|
--- === ext ===
---
--- Standard high-level namespace for third-party extensions.
ext = {}
local function clear_old_state()
hydra.menu.hide()
hotkey.disableall()
pathwatcher.stopall()
timer.stopall()
textgrid.destroyall()
notify.unregisterall()
notify.applistener.stopall()
battery.watcher.stopall()
end
local function load_default_config()
clear_old_state()
local fallbackinit = dofile(hydra.resourcesdir .. "/fallback_init.lua")
fallbackinit.run()
end
--- hydra.reload()
--- Reloads your init-file. Makes sure to clear any state that makes sense to clear (hotkeys, pathwatchers, etc).
function hydra.reload()
local userfile = os.getenv("HOME") .. "/.hydra/init.lua"
local exists, isdir = hydra.fileexists(userfile)
if exists and not isdir then
local fn, err = loadfile(userfile)
if fn then
clear_old_state()
local ok, err = pcall(fn)
if not ok then
notify.show("Hydra config runtime error", "", tostring(err) .. " -- Falling back to sample config.", "")
load_default_config()
end
else
notify.show("Hydra config syntax error", "", tostring(err) .. " -- Doing nothing.", "")
end
else
-- don't say (via alert) anything more than what the default config already says
load_default_config()
end
end
--- hydra.errorhandler = function(err)
--- Error handler for hydra.call; intended for you to set, not for third party libs
function hydra.errorhandler(err)
print("Error: " .. err)
notify.show("Hydra Error", "", tostring(err), "error")
end
function hydra.tryhandlingerror(firsterr)
local ok, seconderr = pcall(function()
hydra.errorhandler(firsterr)
end)
if not ok then
notify.show("Hydra error", "", "Error while handling error: " .. tostring(seconderr) .. " -- Original error: " .. tostring(firsterr), "")
end
end
--- hydra.call(fn, ...) -> ...
--- Just like pcall, except that failures are handled using hydra.errorhandler
function hydra.call(fn, ...)
local results = table.pack(pcall(fn, ...))
if not results[1] then
-- print(debug.traceback())
hydra.tryhandlingerror(results[2])
end
return table.unpack(results)
end
local function trimstring(s)
return s:gsub("^%s+", ""):gsub("%s+$", "")
end
--- hydra.exec(command) -> string
--- Runs a shell function and returns stdout as a string (without trailing newline).
function hydra.exec(command)
local f = io.popen(command)
local str = f:read("*a")
f:close()
return str and trimstring(str)
end
--- hydra.version -> string
--- The current version of Hydra, as a human-readable string.
hydra.version = hydra.updates.currentversion()
--- hydra.licenses -> string
--- Returns a string containing the licenses of all the third party software Hydra uses (i.e. Lua)
hydra.licenses = [[
### Lua 5.2
Copyright (c) 1994-2014 Lua.org, PUC-Rio.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
### inspect
Copyright (c) 2013 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.]]
-- swizzle! this is necessary so hydra.settings can save keys on exit
os.exit = hydra.exit
|
--- === ext ===
---
--- Standard high-level namespace for third-party extensions.
ext = {}
local function clear_old_state()
hydra.menu.hide()
hotkey.disableall()
pathwatcher.stopall()
timer.stopall()
textgrid.destroyall()
notify.unregisterall()
notify.applistener.stopall()
battery.watcher.stopall()
end
local function load_default_config()
clear_old_state()
local fallbackinit = dofile(hydra.resourcesdir .. "/fallback_init.lua")
fallbackinit.run()
end
--- hydra.reload()
--- Reloads your init-file. Makes sure to clear any state that makes sense to clear (hotkeys, pathwatchers, etc).
function hydra.reload()
local userfile = os.getenv("HOME") .. "/.hydra/init.lua"
local exists, isdir = hydra.fileexists(userfile)
if exists and not isdir then
local fn, err = loadfile(userfile)
if fn then
clear_old_state()
local ok, err = pcall(fn)
if not ok then
notify.show("Hydra config runtime error", "", tostring(err) .. " -- Falling back to sample config.", "")
load_default_config()
end
else
notify.show("Hydra config syntax error", "", tostring(err) .. " -- Doing nothing.", "")
end
else
-- don't say (via alert) anything more than what the default config already says
load_default_config()
end
end
--- hydra.errorhandler = function(err)
--- Error handler for hydra.call; intended for you to set, not for third party libs
function hydra.errorhandler(err)
print("Error: " .. err)
notify.show("Hydra Error", "", tostring(err), "error")
end
function hydra.tryhandlingerror(firsterr)
local ok, seconderr = pcall(function()
hydra.errorhandler(firsterr)
end)
if not ok then
notify.show("Hydra error", "", "Error while handling error: " .. tostring(seconderr) .. " -- Original error: " .. tostring(firsterr), "")
end
end
--- hydra.call(fn, ...) -> ...
--- Just like pcall, except that failures are handled using hydra.errorhandler
function hydra.call(fn, ...)
local results = table.pack(pcall(fn, ...))
if not results[1] then
-- print(debug.traceback())
hydra.tryhandlingerror(results[2])
end
return table.unpack(results)
end
--- hydra.exec(command) -> string
--- Runs a shell function and returns stdout as a string (may include trailing newline).
function hydra.exec(command)
local f = io.popen(command)
local str = f:read('*a')
f:close()
return str
end
--- hydra.version -> string
--- The current version of Hydra, as a human-readable string.
hydra.version = hydra.updates.currentversion()
--- hydra.licenses -> string
--- Returns a string containing the licenses of all the third party software Hydra uses (i.e. Lua)
hydra.licenses = [[
### Lua 5.2
Copyright (c) 1994-2014 Lua.org, PUC-Rio.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
### inspect
Copyright (c) 2013 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.]]
-- swizzle! this is necessary so hydra.settings can save keys on exit
os.exit = hydra.exit
|
Fixed potential bugs in hydra.exec() by making it less convenient to use.
|
Fixed potential bugs in hydra.exec() by making it less convenient to use.
|
Lua
|
mit
|
lowne/hammerspoon,peterhajas/hammerspoon,peterhajas/hammerspoon,joehanchoi/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,Stimim/hammerspoon,emoses/hammerspoon,kkamdooong/hammerspoon,tmandry/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,dopcn/hammerspoon,wvierber/hammerspoon,asmagill/hammerspoon,Habbie/hammerspoon,bradparks/hammerspoon,wvierber/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,trishume/hammerspoon,knu/hammerspoon,chrisjbray/hammerspoon,cmsj/hammerspoon,lowne/hammerspoon,peterhajas/hammerspoon,latenitefilms/hammerspoon,joehanchoi/hammerspoon,asmagill/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,asmagill/hammerspoon,Stimim/hammerspoon,knu/hammerspoon,bradparks/hammerspoon,emoses/hammerspoon,wvierber/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,wsmith323/hammerspoon,peterhajas/hammerspoon,heptal/hammerspoon,knu/hammerspoon,asmagill/hammerspoon,ocurr/hammerspoon,kkamdooong/hammerspoon,emoses/hammerspoon,dopcn/hammerspoon,chrisjbray/hammerspoon,heptal/hammerspoon,tmandry/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,ocurr/hammerspoon,knl/hammerspoon,Stimim/hammerspoon,joehanchoi/hammerspoon,knu/hammerspoon,lowne/hammerspoon,ocurr/hammerspoon,junkblocker/hammerspoon,zzamboni/hammerspoon,heptal/hammerspoon,emoses/hammerspoon,nkgm/hammerspoon,lowne/hammerspoon,Stimim/hammerspoon,chrisjbray/hammerspoon,CommandPost/CommandPost-App,lowne/hammerspoon,bradparks/hammerspoon,wsmith323/hammerspoon,junkblocker/hammerspoon,wvierber/hammerspoon,ocurr/hammerspoon,heptal/hammerspoon,chrisjbray/hammerspoon,chrisjbray/hammerspoon,zzamboni/hammerspoon,Hammerspoon/hammerspoon,peterhajas/hammerspoon,nkgm/hammerspoon,zzamboni/hammerspoon,wvierber/hammerspoon,chrisjbray/hammerspoon,TimVonsee/hammerspoon,knl/hammerspoon,joehanchoi/hammerspoon,knu/hammerspoon,zzamboni/hammerspoon,dopcn/hammerspoon,hypebeast/hammerspoon,kkamdooong/hammerspoon,nkgm/hammerspoon,latenitefilms/hammerspoon,Stimim/hammerspoon,trishume/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,junkblocker/hammerspoon,kkamdooong/hammerspoon,ocurr/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,knl/hammerspoon,TimVonsee/hammerspoon,hypebeast/hammerspoon,knl/hammerspoon,cmsj/hammerspoon,hypebeast/hammerspoon,Habbie/hammerspoon,bradparks/hammerspoon,CommandPost/CommandPost-App,knl/hammerspoon,wsmith323/hammerspoon,latenitefilms/hammerspoon,junkblocker/hammerspoon,CommandPost/CommandPost-App,TimVonsee/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,knu/hammerspoon,zzamboni/hammerspoon,bradparks/hammerspoon,joehanchoi/hammerspoon,tmandry/hammerspoon,hypebeast/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon,hypebeast/hammerspoon,wsmith323/hammerspoon,dopcn/hammerspoon,nkgm/hammerspoon,emoses/hammerspoon,trishume/hammerspoon,dopcn/hammerspoon,TimVonsee/hammerspoon,TimVonsee/hammerspoon,nkgm/hammerspoon,kkamdooong/hammerspoon,wsmith323/hammerspoon,CommandPost/CommandPost-App,junkblocker/hammerspoon
|
aa19f6f3a2e376e8ff661edba7f7fe2554cd44e0
|
lua/String.lua
|
lua/String.lua
|
local squote = string.byte("'")
local dquote = string.byte('"')
-- escape "sequences"
local escapeSequences = {
a = '\a',
b = '\b',
f = '\f',
r = '\r',
n = '\n',
t = '\t',
v = '\v',
['"'] = '"',
["'"] = "'",
['\\'] = '\\'
}
-- Parse a string like it's a Lua 5.2 string.
local function parseString52(s)
-- "validate" string
local startChar = string.byte(s,1,1)
assert(startChar==squote or startChar==dquote)
assert(string.byte(s, -1, -1) == startChar)
-- remove quotes
local str = string.sub(s, 2, -2)
-- TODO check for unescaped quotes
-- replace "normal" escapes with a padded escape
str = string.gsub(str, "\\([^zx0-9])", "\\v*%1")
-- pad 1-digit numerical escapes
str = string.gsub(str, "\\([0-9])[^0-9]", "\\00%1")
-- pad 2-digit numerical escapes
str = string.gsub(str, "\\([0-9][0-9])[^0-9]", "\\0%1")
-- strip \z (and spaces)
str = string.gsub(str, "\\z%s+", "")
-- parse results
str = string.gsub(str, "\\(([vx0-9])(.(.)))",
function(a,b,c,d)
if b == "v" then
return escapeSequences[d] or error("invalid escape sequence near '\\" .. d .. "'")
elseif b == "x" then
local n = tonumber(c, 16)
assert(n, "hexadecimal digit expected near '\\x" .. c .. "'")
return string.char(n)
else
local n = tonumber(a)
assert(n < 256, "decimal escape too large near '\\" .. a .. "'")
return string.char(n)
end
end)
return str
end
return {
parse52 = parseString52,
}
|
local squote = "'"
local dquote = '"'
-- escape "sequences"
local escapeSequences = {
a = '\a',
b = '\b',
f = '\f',
r = '\r',
n = '\n',
t = '\t',
v = '\v',
['"'] = '"',
["'"] = "'",
['\\'] = '\\'
}
local pads = {
z = "\\z",
x = "\\x",
['0'] = '\\0',
['1'] = '\\1',
['2'] = '\\2',
['3'] = '\\3',
['4'] = '\\4',
['5'] = '\\5',
['6'] = '\\6',
['7'] = '\\7',
['8'] = '\\8',
['9'] = '\\9'
}
setmetatable(pads, {
__index = function(t,k)
return "\\v" .. k .. "/"
end
})
-- Parse a string like it's a Lua 5.2 string.
local function parseString52(s)
-- "validate" string
local startChar = string.sub(s,1,1)
assert(startChar==squote or startChar==dquote)
assert(string.sub(s, -1, -1) == startChar)
-- remove quotes
local str = string.sub(s, 2, -2)
-- TODO check for unescaped quotes
-- replace "normal" escapes with a padded escape
str = string.gsub(str, "\\(.)", function(c)
-- swap startChar with some invalid escape
if c == startChar then
c = "m"
-- swap the invalid escape with startChar
elseif c == "m" then
c = startChar
end
return pads[c]
end)
-- check for a padded escape for startChar - remember this is actually our invalid escape
assert(not string.find(str, "\\v" .. startChar .. "/"), "invalid escape sequence near '\\m'")
-- then check for non-escaped startChar
assert(not string.find(str, startChar), "unfinished string")
-- pad 1-digit numerical escapes
str = string.gsub(str, "\\([0-9])[^0-9]", "\\00%1")
-- pad 2-digit numerical escapes
str = string.gsub(str, "\\([0-9][0-9])[^0-9]", "\\0%1")
-- strip \z (and spaces)
str = string.gsub(str, "\\z[%s\n\r]+", "")
-- parse results
str = string.gsub(str, "\\(([vx0-9])((.).))",
function(a,b,c,d)
if b == "v" then
return escapeSequences[d] or (d == "m" and startChar or assert(false, "invalid escape sequence near '\\" .. d .. "'"))
elseif b == "x" then
local n = tonumber(c, 16)
assert(n, "hexadecimal digit expected near '\\x" .. c .. "'")
return string.char(n)
else
local n = tonumber(a)
assert(n < 256, "decimal escape too large near '\\" .. a .. "'")
return string.char(n)
end
end)
return str
end
-- "tests"
-- TODO add more
-- also add automatic checks
if _VERSION == "Lua 5.2" and not ... then
local t = {
[["\""]],
[["""]],
[["v""]],
[[""/"]],
[["\v"/"]],
[["\m"]]
}
for _, str in ipairs(t) do
local s, m = pcall(parseString52, str)
io.write(tostring(s and m or "nil"))
io.write(tostring(s and "" or ("\t" .. m)) .. "\n")
s, m = load("return " .. str, "@/home/soniex2/git/github/Stuff/lua/String.lua:")
io.write(tostring(s and s()))
io.write(tostring(m and "\t"..m or "") .. "\n")
end
elseif not ... then
print("Tests require Lua 5.2")
end
return {
parse52 = parseString52,
}
|
Fix bugs
|
Fix bugs
|
Lua
|
mit
|
SoniEx2/Stuff,SoniEx2/Stuff
|
40c9aa96effa54875e2fb4921c5a199c86cecd1e
|
core/sile.lua
|
core/sile.lua
|
SILE = {}
SILE.version = "0.9.4-unreleased"
SILE.utilities = require("core/utilities")
SU = SILE.utilities
SILE.inputs = {}
SILE.Commands = {};
SILE.debugFlags = {}
SILE.nodeMakers = {}
SILE.tokenizers = {}
loadstring = loadstring or load -- 5.3 compatibility
if not unpack then unpack = table.unpack end -- 5.3 compatibility
std = require("std")
if (os.getenv("SILE_COVERAGE")) then require("luacov") end
SILE.documentState = std.object {};
SILE.scratch = {};
SILE.length = require("core/length")
require("core/parserbits")
require("core/measurements")
require("core/baseclass")
SILE.nodefactory = require("core/nodefactory")
require("core/settings")
require("core/inputs-texlike")
require("core/inputs-xml")
require("core/inputs-common")
require("core/papersizes")
require("core/colorparser")
require("core/pagebuilder")
require("core/typesetter")
require("core/hyphenator-liang")
require("core/languages")
require("core/font")
SILE.frameParser = require("core/frameparser")
SILE.linebreak = require("core/break")
require("core/frame")
SILE.init = function()
if not SILE.backend then
if pcall(function () require("justenoughharfbuzz") end) then
SILE.backend = "libtexpdf"
else
SU.error("libtexpdf backend not available!")
end
end
if SILE.backend == "libtexpdf" then
require("core/harfbuzz-shaper")
require("core/libtexpdf-output")
end
if SILE.dolua then
_, err = pcall(SILE.dolua)
if err then error(err) end
end
end
SILE.require = function(d)
local f = SILE.resolveFile(d..".lua")
if f then return require(f:gsub(".lua$","")) end
return require(d)
end
SILE.parseArguments = function()
local parser = std.optparse ("SILE "..SILE.version..[[
Usage: sile [options] file.sil|file.xml
The SILE typesetter reads a single input file in either SIL or XML format to
generate an output in PDF format. The output will be writted to the same name
as the input file with the extention changed to .pdf.
Options:
-b, --backend=VALUE choose an alternative output backend
-d, --debug=VALUE debug SILE's operation
-e, --evaluate=VALUE evaluate some Lua code before processing file
-o, --output=[FILE] explicitly set output file name
-I, --include=[FILE] include a class or SILE file before processing input
--help display this help, then exit
--version display version information, then exit
]])
parser:on ('--', parser.finished)
_G.unparsed, _G.opts = parser:parse(_G.arg)
-- Turn slashes around in the event we get passed a path from a Windows shell
if _G.unparsed[1] then
SILE.masterFilename = _G.unparsed[1]:gsub("\\", "/")
end
SILE.debugFlags = {}
if opts.backend then
SILE.backend = opts.backend
end
if opts.debug then
for k,v in ipairs(std.string.split(opts.debug, ",")) do SILE.debugFlags[v] = 1 end
end
if opts.evaluate then
SILE.dolua,err = loadstring(opts.evaluate)
if err then SU.error(err) end
end
if opts.output then
SILE.outputFilename = opts.output
end
if opts.include then
SILE.preamble = opts.include
end
end
function SILE.initRepl ()
SILE._repl = require 'repl.console'
local has_linenoise = pcall(require, 'linenoise')
if has_linenoise then
SILE._repl:loadplugin 'linenoise'
else
-- XXX check that we're not receiving input from a non-tty
local has_rlwrap = os.execute('which rlwrap >/dev/null 2>/dev/null') == 0
if has_rlwrap and not os.getenv 'LUA_REPL_RLWRAP' then
local command = 'LUA_REPL_RLWRAP=1 rlwrap'
local index = 0
while arg[index - 1] do
index = index - 1
end
while arg[index] do
command = string.format('%s %q', command, arg[index])
index = index + 1
end
os.execute(command)
return
end
end
SILE._repl:loadplugin 'history'
SILE._repl:loadplugin 'completion'
SILE._repl:loadplugin 'autoreturn'
SILE._repl:loadplugin 'rcfile'
end
function SILE.repl()
if not SILE._repl then SILE.initRepl() end
SILE._repl:run()
end
function SILE.readFile(fn)
SILE.currentlyProcessingFile = fn
fn = SILE.resolveFile(fn)
if not fn then
SU.error("Could not find file")
end
local file, err = io.open(fn)
if not file then
print("Could not open "..fn..": "..err)
return
end
io.write("<"..fn..">\n")
-- Sniff first few bytes
local sniff = file:read("*l") or ""
file:seek("set", 0)
local inputsOrder = {}
for n in pairs(SILE.inputs) do
if SILE.inputs[n].order then table.insert(inputsOrder, n) end
end
table.sort(inputsOrder,function(a,b) return SILE.inputs[a].order < SILE.inputs[b].order end)
for i = 1,#inputsOrder do local input = SILE.inputs[inputsOrder[i]]
if input.appropriate(fn, sniff) then
input.process(fn)
return
end
end
SU.error("No input processor available for "..fn.." (should never happen)",1)
end
local function file_exists(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
function SILE.resolveFile(fn)
if file_exists(fn) then return fn end
if file_exists(fn..".sil") then return fn..".sil" end
if not SILE.masterFilename then return nil end
local dirname = SILE.masterFilename:match("(.-)[^%/]+$")
for k in SU.gtoke(dirname..";"..tostring(os.getenv("SILE_PATH")), ";") do
if k.string then
local f = std.io.catfile(k.string, fn)
if file_exists(f) then return f end
if file_exists(f..".sil") then return f..".sil" end
end
end
end
function SILE.call(cmd,options, content)
SILE.currentCommand = content
if not SILE.Commands[cmd] then SU.error("Unknown command "..cmd) end
SILE.Commands[cmd](options or {}, content or {})
end
return SILE
|
SILE = {}
SILE.version = "0.9.4-unreleased"
SILE.utilities = require("core/utilities")
SU = SILE.utilities
SILE.inputs = {}
SILE.Commands = {};
SILE.debugFlags = {}
SILE.nodeMakers = {}
SILE.tokenizers = {}
loadstring = loadstring or load -- 5.3 compatibility
if not unpack then unpack = table.unpack end -- 5.3 compatibility
std = require("std")
lfs = require("lfs")
if (os.getenv("SILE_COVERAGE")) then require("luacov") end
SILE.documentState = std.object {};
SILE.scratch = {};
SILE.length = require("core/length")
require("core/parserbits")
require("core/measurements")
require("core/baseclass")
SILE.nodefactory = require("core/nodefactory")
require("core/settings")
require("core/inputs-texlike")
require("core/inputs-xml")
require("core/inputs-common")
require("core/papersizes")
require("core/colorparser")
require("core/pagebuilder")
require("core/typesetter")
require("core/hyphenator-liang")
require("core/languages")
require("core/font")
SILE.frameParser = require("core/frameparser")
SILE.linebreak = require("core/break")
require("core/frame")
SILE.init = function()
if not SILE.backend then
if pcall(function () require("justenoughharfbuzz") end) then
SILE.backend = "libtexpdf"
else
SU.error("libtexpdf backend not available!")
end
end
if SILE.backend == "libtexpdf" then
require("core/harfbuzz-shaper")
require("core/libtexpdf-output")
end
if SILE.dolua then
_, err = pcall(SILE.dolua)
if err then error(err) end
end
end
SILE.require = function(d)
local f = SILE.resolveFile(d..".lua")
if f then return require(f:gsub(".lua$","")) end
return require(d)
end
SILE.parseArguments = function()
local parser = std.optparse ("SILE "..SILE.version..[[
Usage: sile [options] file.sil|file.xml
The SILE typesetter reads a single input file in either SIL or XML format to
generate an output in PDF format. The output will be writted to the same name
as the input file with the extention changed to .pdf.
Options:
-b, --backend=VALUE choose an alternative output backend
-d, --debug=VALUE debug SILE's operation
-e, --evaluate=VALUE evaluate some Lua code before processing file
-o, --output=[FILE] explicitly set output file name
-I, --include=[FILE] include a class or SILE file before processing input
--help display this help, then exit
--version display version information, then exit
]])
parser:on ('--', parser.finished)
_G.unparsed, _G.opts = parser:parse(_G.arg)
-- Turn slashes around in the event we get passed a path from a Windows shell
if _G.unparsed[1] then
SILE.masterFilename = _G.unparsed[1]:gsub("\\", "/")
end
SILE.debugFlags = {}
if opts.backend then
SILE.backend = opts.backend
end
if opts.debug then
for k,v in ipairs(std.string.split(opts.debug, ",")) do SILE.debugFlags[v] = 1 end
end
if opts.evaluate then
SILE.dolua,err = loadstring(opts.evaluate)
if err then SU.error(err) end
end
if opts.output then
SILE.outputFilename = opts.output
end
if opts.include then
SILE.preamble = opts.include
end
end
function SILE.initRepl ()
SILE._repl = require 'repl.console'
local has_linenoise = pcall(require, 'linenoise')
if has_linenoise then
SILE._repl:loadplugin 'linenoise'
else
-- XXX check that we're not receiving input from a non-tty
local has_rlwrap = os.execute('which rlwrap >/dev/null 2>/dev/null') == 0
if has_rlwrap and not os.getenv 'LUA_REPL_RLWRAP' then
local command = 'LUA_REPL_RLWRAP=1 rlwrap'
local index = 0
while arg[index - 1] do
index = index - 1
end
while arg[index] do
command = string.format('%s %q', command, arg[index])
index = index + 1
end
os.execute(command)
return
end
end
SILE._repl:loadplugin 'history'
SILE._repl:loadplugin 'completion'
SILE._repl:loadplugin 'autoreturn'
SILE._repl:loadplugin 'rcfile'
end
function SILE.repl()
if not SILE._repl then SILE.initRepl() end
SILE._repl:run()
end
function SILE.readFile(fn)
SILE.currentlyProcessingFile = fn
fn = SILE.resolveFile(fn)
if not fn then
SU.error("Could not find file")
end
if lfs.attributes(fn).mode ~= "file" then
SU.error(fn.." isn't a file, it's a "..lfs.attributes(fn).mode.."!")
end
local file, err = io.open(fn)
if not file then
print("Could not open "..fn..": "..err)
return
end
io.write("<"..fn..">\n")
-- Sniff first few bytes
local sniff = file:read("*l") or ""
file:seek("set", 0)
local inputsOrder = {}
for n in pairs(SILE.inputs) do
if SILE.inputs[n].order then table.insert(inputsOrder, n) end
end
table.sort(inputsOrder,function(a,b) return SILE.inputs[a].order < SILE.inputs[b].order end)
for i = 1,#inputsOrder do local input = SILE.inputs[inputsOrder[i]]
if input.appropriate(fn, sniff) then
input.process(fn)
return
end
end
SU.error("No input processor available for "..fn.." (should never happen)",1)
end
local function file_exists(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
function SILE.resolveFile(fn)
if file_exists(fn) then return fn end
if file_exists(fn..".sil") then return fn..".sil" end
if not SILE.masterFilename then return nil end
local dirname = SILE.masterFilename:match("(.-)[^%/]+$")
for k in SU.gtoke(dirname..";"..tostring(os.getenv("SILE_PATH")), ";") do
if k.string then
local f = std.io.catfile(k.string, fn)
if file_exists(f) then return f end
if file_exists(f..".sil") then return f..".sil" end
end
end
end
function SILE.call(cmd,options, content)
SILE.currentCommand = content
if not SILE.Commands[cmd] then SU.error("Unknown command "..cmd) end
SILE.Commands[cmd](options or {}, content or {})
end
return SILE
|
Test for stupidity. Fixes #263
|
Test for stupidity. Fixes #263
|
Lua
|
mit
|
neofob/sile,simoncozens/sile,simoncozens/sile,alerque/sile,alerque/sile,neofob/sile,neofob/sile,alerque/sile,simoncozens/sile,neofob/sile,simoncozens/sile,alerque/sile
|
1a20ec501b5ad433c85c770f557185e3d398833f
|
tools/benchmark.lua
|
tools/benchmark.lua
|
local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)()
package.path = path.join(path.dirname(__FILE__), "..", "lib", "?.lua;") .. package.path
require 'xlua'
require 'pl'
require 'w2nn'
local iproc = require 'iproc'
local reconstruct = require 'reconstruct'
local image_loader = require 'image_loader'
local gm = require 'graphicsmagick'
local cmd = torch.CmdLine()
cmd:text()
cmd:text("waifu2x-benchmark")
cmd:text("Options:")
cmd:option("-seed", 11, 'fixed input seed')
cmd:option("-dir", "./data/test", 'test image directory')
cmd:option("-model1_dir", "./models/anime_style_art", 'model1 directory')
cmd:option("-model2_dir", "./models/anime_style_art_rgb", 'model2 directory')
cmd:option("-method", "scale", '(scale|noise)')
cmd:option("-noise_level", 1, '(1|2)')
cmd:option("-color_weight", "y", '(y|rgb)')
cmd:option("-jpeg_quality", 75, 'jpeg quality')
cmd:option("-jpeg_times", 1, 'jpeg compression times')
cmd:option("-jpeg_quality_down", 5, 'value of jpeg quality to decrease each times')
local opt = cmd:parse(arg)
torch.setdefaulttensortype('torch.FloatTensor')
if cudnn then
cudnn.fastest = true
cudnn.benchmark = false
end
local function MSE(x1, x2)
return (x1 - x2):pow(2):mean()
end
local function YMSE(x1, x2)
local x1_2 = x1:clone()
local x2_2 = x2:clone()
x1_2[1]:mul(0.299 * 3)
x1_2[2]:mul(0.587 * 3)
x1_2[3]:mul(0.114 * 3)
x2_2[1]:mul(0.299 * 3)
x2_2[2]:mul(0.587 * 3)
x2_2[3]:mul(0.114 * 3)
return (x1_2 - x2_2):pow(2):mean()
end
local function PSNR(x1, x2)
local mse = MSE(x1, x2)
return 20 * (math.log(1.0 / math.sqrt(mse)) / math.log(10))
end
local function YPSNR(x1, x2)
local mse = YMSE(x1, x2)
return 20 * (math.log((0.587 * 3) / math.sqrt(mse)) / math.log(10))
end
local function transform_jpeg(x)
for i = 1, opt.jpeg_times do
jpeg = gm.Image(x, "RGB", "DHW")
jpeg:format("jpeg")
jpeg:samplingFactors({1.0, 1.0, 1.0})
blob, len = jpeg:toBlob(opt.jpeg_quality - (i - 1) * opt.jpeg_quality_down)
jpeg:fromBlob(blob, len)
x = jpeg:toTensor("byte", "RGB", "DHW")
end
return x
end
local function transform_scale(x)
return iproc.scale(x,
x:size(3) * 0.5,
x:size(2) * 0.5,
"Box")
end
local function benchmark(color_weight, x, input_func, v1_noise, v2_noise)
local v1_mse = 0
local v2_mse = 0
local v1_psnr = 0
local v2_psnr = 0
for i = 1, #x do
local ground_truth = x[i]
local input, v1_output, v2_output
input = input_func(ground_truth)
input = input:float():div(255)
ground_truth = ground_truth:float():div(255)
t = sys.clock()
if input:size(3) == ground_truth:size(3) then
v1_output = reconstruct.image(v1_noise, input)
v2_output = reconstruct.image(v2_noise, input)
else
v1_output = reconstruct.scale(v1_noise, 2.0, input)
v2_output = reconstruct.scale(v2_noise, 2.0, input)
end
if color_weight == "y" then
v1_mse = v1_mse + YMSE(ground_truth, v1_output)
v1_psnr = v1_psnr + YPSNR(ground_truth, v1_output)
v2_mse = v2_mse + YMSE(ground_truth, v2_output)
v2_psnr = v2_psnr + YPSNR(ground_truth, v2_output)
elseif color_weight == "rgb" then
v1_mse = v1_mse + MSE(ground_truth, v1_output)
v1_psnr = v1_psnr + PSNR(ground_truth, v1_output)
v2_mse = v2_mse + MSE(ground_truth, v2_output)
v2_psnr = v2_psnr + PSNR(ground_truth, v2_output)
end
io.stdout:write(
string.format("%d/%d; v1_mse=%f, v2_mse=%f, v1_psnr=%f, v2_psnr=%f \r",
i, #x,
v1_mse / i, v2_mse / i,
v1_psnr / i, v2_psnr / i
)
)
io.stdout:flush()
end
io.stdout:write("\n")
end
local function load_data(test_dir)
local test_x = {}
local files = dir.getfiles(test_dir, "*.*")
for i = 1, #files do
table.insert(test_x, iproc.crop_mod4(image_loader.load_byte(files[i])))
xlua.progress(i, #files)
end
return test_x
end
print(opt)
torch.manualSeed(opt.seed)
cutorch.manualSeed(opt.seed)
if opt.method == "scale" then
local v1 = torch.load(path.join(opt.model1_dir, "scale2.0x_model.t7"), "ascii")
local v2 = torch.load(path.join(opt.model2_dir, "scale2.0x_model.t7"), "ascii")
local test_x = load_data(opt.dir)
benchmark(opt.color_weight, test_x, transform_scale, v1, v2)
elseif opt.method == "noise" then
local v1 = torch.load(path.join(opt.model1_dir, string.format("noise%d_model.t7", opt.noise_level)), "ascii")
local v2 = torch.load(path.join(opt.model2_dir, string.format("noise%d_model.t7", opt.noise_level)), "ascii")
local test_x = load_data(opt.dir)
benchmark(opt.color_weight, test_x, transform_jpeg, v1, v2)
end
|
local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)()
package.path = path.join(path.dirname(__FILE__), "..", "lib", "?.lua;") .. package.path
require 'xlua'
require 'pl'
require 'w2nn'
local iproc = require 'iproc'
local reconstruct = require 'reconstruct'
local image_loader = require 'image_loader'
local gm = require 'graphicsmagick'
local cmd = torch.CmdLine()
cmd:text()
cmd:text("waifu2x-benchmark")
cmd:text("Options:")
cmd:option("-seed", 11, 'fixed input seed')
cmd:option("-dir", "./data/test", 'test image directory')
cmd:option("-model1_dir", "./models/anime_style_art", 'model1 directory')
cmd:option("-model2_dir", "./models/anime_style_art_rgb", 'model2 directory')
cmd:option("-method", "scale", '(scale|noise)')
cmd:option("-noise_level", 1, '(1|2)')
cmd:option("-color_weight", "y", '(y|rgb)')
cmd:option("-jpeg_quality", 75, 'jpeg quality')
cmd:option("-jpeg_times", 1, 'jpeg compression times')
cmd:option("-jpeg_quality_down", 5, 'value of jpeg quality to decrease each times')
local opt = cmd:parse(arg)
torch.setdefaulttensortype('torch.FloatTensor')
if cudnn then
cudnn.fastest = true
cudnn.benchmark = false
end
local function MSE(x1, x2)
return (x1 - x2):pow(2):mean()
end
local function YMSE(x1, x2)
local x1_2 = image.rgb2y(x1)
local x2_2 = image.rgb2y(x2)
return (x1_2 - x2_2):pow(2):mean()
end
local function PSNR(x1, x2)
local mse = MSE(x1, x2)
return 20 * (math.log(1.0 / math.sqrt(mse)) / math.log(10))
end
local function YPSNR(x1, x2)
local mse = YMSE(x1, x2)
return 20 * (math.log(1.0 / math.sqrt(mse)) / math.log(10))
end
local function transform_jpeg(x)
for i = 1, opt.jpeg_times do
jpeg = gm.Image(x, "RGB", "DHW")
jpeg:format("jpeg")
jpeg:samplingFactors({1.0, 1.0, 1.0})
blob, len = jpeg:toBlob(opt.jpeg_quality - (i - 1) * opt.jpeg_quality_down)
jpeg:fromBlob(blob, len)
x = jpeg:toTensor("byte", "RGB", "DHW")
end
return x
end
local function transform_scale(x)
return iproc.scale(x,
x:size(3) * 0.5,
x:size(2) * 0.5,
"Box")
end
local function benchmark(color_weight, x, input_func, v1_noise, v2_noise)
local v1_mse = 0
local v2_mse = 0
local v1_psnr = 0
local v2_psnr = 0
for i = 1, #x do
local ground_truth = x[i]
local input, v1_output, v2_output
input = input_func(ground_truth)
input = input:float():div(255)
ground_truth = ground_truth:float():div(255)
t = sys.clock()
if input:size(3) == ground_truth:size(3) then
v1_output = reconstruct.image(v1_noise, input)
v2_output = reconstruct.image(v2_noise, input)
else
v1_output = reconstruct.scale(v1_noise, 2.0, input)
v2_output = reconstruct.scale(v2_noise, 2.0, input)
end
if color_weight == "y" then
v1_mse = v1_mse + YMSE(ground_truth, v1_output)
v1_psnr = v1_psnr + YPSNR(ground_truth, v1_output)
v2_mse = v2_mse + YMSE(ground_truth, v2_output)
v2_psnr = v2_psnr + YPSNR(ground_truth, v2_output)
elseif color_weight == "rgb" then
v1_mse = v1_mse + MSE(ground_truth, v1_output)
v1_psnr = v1_psnr + PSNR(ground_truth, v1_output)
v2_mse = v2_mse + MSE(ground_truth, v2_output)
v2_psnr = v2_psnr + PSNR(ground_truth, v2_output)
end
io.stdout:write(
string.format("%d/%d; v1_mse=%f, v2_mse=%f, v1_psnr=%f, v2_psnr=%f \r",
i, #x,
v1_mse / i, v2_mse / i,
v1_psnr / i, v2_psnr / i
)
)
io.stdout:flush()
end
io.stdout:write("\n")
end
local function load_data(test_dir)
local test_x = {}
local files = dir.getfiles(test_dir, "*.*")
for i = 1, #files do
table.insert(test_x, iproc.crop_mod4(image_loader.load_byte(files[i])))
xlua.progress(i, #files)
end
return test_x
end
print(opt)
torch.manualSeed(opt.seed)
cutorch.manualSeed(opt.seed)
if opt.method == "scale" then
local v1 = torch.load(path.join(opt.model1_dir, "scale2.0x_model.t7"), "ascii")
local v2 = torch.load(path.join(opt.model2_dir, "scale2.0x_model.t7"), "ascii")
local test_x = load_data(opt.dir)
benchmark(opt.color_weight, test_x, transform_scale, v1, v2)
elseif opt.method == "noise" then
local v1 = torch.load(path.join(opt.model1_dir, string.format("noise%d_model.t7", opt.noise_level)), "ascii")
local v2 = torch.load(path.join(opt.model2_dir, string.format("noise%d_model.t7", opt.noise_level)), "ascii")
local test_x = load_data(opt.dir)
benchmark(opt.color_weight, test_x, transform_jpeg, v1, v2)
end
|
Fix the evaluation metric in benchmark
|
Fix the evaluation metric in benchmark
|
Lua
|
mit
|
nagadomi/waifu2x,higankanshi/waifu2x,nagadomi/waifu2x,vitaliylag/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,Spitfire1900/upscaler,nagadomi/waifu2x,zyhkz/waifu2x,vitaliylag/waifu2x,zyhkz/waifu2x,zyhkz/waifu2x,zyhkz/waifu2x,Spitfire1900/upscaler,vitaliylag/waifu2x,higankanshi/waifu2x,higankanshi/waifu2x
|
3089831ad2e7ccfb17c1d0d4a562242c3cd2def7
|
framework/libs/flexihash.lua
|
framework/libs/flexihash.lua
|
-- TODO more hash alg
-- TODO refactor with ffi
local CRC = require "framework.libs.hasher.crc32"
local Flexihash = {
obj = nil
}
Flexihash.__index = Flexihash
local DEFAULT_REPLICAS = 64
local function empty_table(tbl)
for k, v in pairs(tbl) do
return false
end
return true
end
function Flexihash:instance(replicas)
if not replicas then replicas = DEFAULT_REPLICAS end
if self.obj then
return self.obj
end
self.obj = setmetatable({
_replicas = replicas,
_target_count = 0,
_position_target_pairs = {},
_target2indexes = {},
_position_sorted = false,
}, self)
return self.obj
end
function Flexihash:add_target(target, weight)
if not weight then weight = 1 end
if self._target2indexes[target] then
return
end
self._target2indexes[target] = {}
-- hash the target into multiple positions
for i = 1, math.floor(self._replicas * weight) do
position = CRC.crc32(target .. i)
table.insert(self._position_target_pairs, {position, target}) -- lookup
table.insert(self._target2indexes[target], #self._position_target_pairs) -- target removal
end
self._position_sorted = false
self._target_count = self._target_count + 1
return self
end
function Flexihash:add_targets(targets, weight)
for k, target in pairs(targets) do
self:addTarget(target, weight)
end
return self
end
function Flexihash:remove_target(target)
if not self._target2indexes[target] then
return
end
for _, index in pairs(self._target2indexes[target]) do
table.remove(self._position_target_pairs, index)
end
self._target2indexes[target] = nil
self._target_count = self._target_count - 1
return self;
end
function Flexihash:get_all_targets()
local targets = {}
for target, _ in pairs(self._target2indexes) do
table.insert(targets, target)
end
return targets
end
function Flexihash:lookup(resource)
-- handle no targets
if empty_table(self._position_target_pairs) then
return
end
-- optimize single target
if self._target_count == 1 then
for target, _ in pairs(self._target2indexes) do
return target
end
end
local resource_position = CRC.crc32(resource)
self:_sort_position_targets()
local lower = 1
local higher = #self._position_target_pairs
if self._position_target_pairs[higher][1] < resource_position then
return self._position_target_pairs[1][2]
end
local middle
while higher - lower > 1 do
middle = math.ceil((lower + higher) / 2)
if resource_position == self._position_target_pairs[middle][1] then
return self._position_target_pairs[middle][2]
elseif resource_position < self._position_target_pairs[middle][1] then
higher = middle
else
lower = middle
end
end
return self._position_target_pairs[higher][2]
end
-- TODO need optimize
function Flexihash:lookup_list(resource, requested_count)
if not requested_count or requested_count < 1 then
return
end
-- handle no targets
if empty_table(self._position_target_pairs) then
return
end
-- optimize single target
if self._target_count == 1 then
for target, _ in pairs(self._target2indexes) do
return {target}
end
end
-- hash resource to a position
local resource_position = CRC.crc32(resource)
local results = {}
local results_map = {}
local collect = false
self:_sort_position_targets()
-- search values above the resourcePosition
for _, position_target in pairs(self._position_target_pairs) do
-- start collecting targets after passing resource position
if not collect and position_target[1] > resource_position then
collect = true
end
-- only collect the first instance of any target
if collect and not results_map[position_target[2]] then
table.insert(results, position_target[2])
results_map[position_target[2]] = 1
end
-- return when enough results, or list exhausted
if #results == requested_count or #results == self._target_count then
return results
end
end
-- loop to start - search values below the resourcePosition
for _, position_target in pairs(self._position_target_pairs) do
if not results_map[position_target[2]] then
table.insert(results, position_target[2])
results_map[position_target[2]] = 1
end
-- return when enough results, or list exhausted
if #results == requested_count or #results == self._target_count then
return results
end
end
-- return results after iterating through both "parts"
return results
end
Flexihash.__tostring = function(self)
return "Flexihash{targets:[" .. table.concat(self:get_all_targets(), ",") .. "]}"
end
-- Sorts the internal mapping (positions to targets) by position
function Flexihash:_sort_position_targets()
-- sort by key (position) if not already
if not self._position_sorted then
table.sort(self._position_target_pairs, function(a, b) return a[1] < b[1] end)
self._position_sorted = true
for target, _ in pairs(self._target2indexes) do
self._target2indexes[target] = {}
end
for index, position_target in pairs(self._position_target_pairs) do
table.insert(self._target2indexes[position_target[2]], index)
end
end
end
return Flexihash
|
-- TODO more hash alg
-- TODO refactor with ffi
local CRC = require "framework.libs.hasher.crc32"
local Flexihash = {}
Flexihash.__index = Flexihash
local DEFAULT_REPLICAS = 64
local function empty_table(tbl)
for k, v in pairs(tbl) do
return false
end
return true
end
function Flexihash:instance(replicas)
if not replicas then replicas = DEFAULT_REPLICAS end
local obj = setmetatable({
_replicas = replicas,
_target_count = 0,
_position_target_pairs = {},
_target2indexes = {},
_position_sorted = false,
}, self)
return obj
end
function Flexihash:add_target(target, weight)
if not weight then weight = 1 end
if self._target2indexes[target] then
return
end
self._target2indexes[target] = {}
-- hash the target into multiple positions
for i = 1, math.floor(self._replicas * weight) do
position = CRC.crc32(target .. i)
table.insert(self._position_target_pairs, {position, target}) -- lookup
table.insert(self._target2indexes[target], #self._position_target_pairs) -- target removal
end
self._position_sorted = false
self._target_count = self._target_count + 1
return self
end
function Flexihash:add_targets(targets, weight)
for k, target in pairs(targets) do
self:addTarget(target, weight)
end
return self
end
function Flexihash:remove_target(target)
if not self._target2indexes[target] then
return
end
for _, index in pairs(self._target2indexes[target]) do
table.remove(self._position_target_pairs, index)
end
self._target2indexes[target] = nil
self._target_count = self._target_count - 1
return self;
end
function Flexihash:get_all_targets()
local targets = {}
for target, _ in pairs(self._target2indexes) do
table.insert(targets, target)
end
return targets
end
function Flexihash:lookup(resource)
-- handle no targets
if empty_table(self._position_target_pairs) then
return
end
-- optimize single target
if self._target_count == 1 then
for target, _ in pairs(self._target2indexes) do
return target
end
end
local resource_position = CRC.crc32(resource)
self:_sort_position_targets()
local lower = 1
local higher = #self._position_target_pairs
if self._position_target_pairs[higher][1] < resource_position then
return self._position_target_pairs[1][2]
end
local middle
while higher - lower > 1 do
middle = math.ceil((lower + higher) / 2)
if resource_position == self._position_target_pairs[middle][1] then
return self._position_target_pairs[middle][2]
elseif resource_position < self._position_target_pairs[middle][1] then
higher = middle
else
lower = middle
end
end
return self._position_target_pairs[higher][2]
end
-- TODO need optimize
function Flexihash:lookup_list(resource, requested_count)
if not requested_count or requested_count < 1 then
return
end
-- handle no targets
if empty_table(self._position_target_pairs) then
return
end
-- optimize single target
if self._target_count == 1 then
for target, _ in pairs(self._target2indexes) do
return {target}
end
end
-- hash resource to a position
local resource_position = CRC.crc32(resource)
local results = {}
local results_map = {}
local collect = false
self:_sort_position_targets()
-- search values above the resourcePosition
for _, position_target in pairs(self._position_target_pairs) do
-- start collecting targets after passing resource position
if not collect and position_target[1] > resource_position then
collect = true
end
-- only collect the first instance of any target
if collect and not results_map[position_target[2]] then
table.insert(results, position_target[2])
results_map[position_target[2]] = 1
end
-- return when enough results, or list exhausted
if #results == requested_count or #results == self._target_count then
return results
end
end
-- loop to start - search values below the resourcePosition
for _, position_target in pairs(self._position_target_pairs) do
if not results_map[position_target[2]] then
table.insert(results, position_target[2])
results_map[position_target[2]] = 1
end
-- return when enough results, or list exhausted
if #results == requested_count or #results == self._target_count then
return results
end
end
-- return results after iterating through both "parts"
return results
end
Flexihash.__tostring = function(self)
return "Flexihash{targets:[" .. table.concat(self:get_all_targets(), ",") .. "]}"
end
-- Sorts the internal mapping (positions to targets) by position
function Flexihash:_sort_position_targets()
-- sort by key (position) if not already
if not self._position_sorted then
table.sort(self._position_target_pairs, function(a, b) return a[1] < b[1] end)
self._position_sorted = true
for target, _ in pairs(self._target2indexes) do
self._target2indexes[target] = {}
end
for index, position_target in pairs(self._position_target_pairs) do
table.insert(self._target2indexes[position_target[2]], index)
end
end
end
return Flexihash
|
fix bug: flexihash should not be singleton
|
fix bug: flexihash should not be singleton
|
Lua
|
bsd-2-clause
|
nicholaskh/strawberry,nicholaskh/strawberry
|
9b9b06759579581a01a103a239395976bbe4195d
|
src_trunk/resources/lvpd-system/c_headlights.lua
|
src_trunk/resources/lvpd-system/c_headlights.lua
|
-- Bind Keys required
function bindKeys(res)
bindKey("p", "down", toggleFlashers)
end
addEventHandler("onClientResourceStart", getResourceRootElement(), bindKeys)
function toggleFlashers()
local veh = getPedOccupiedVehicle(getLocalPlayer())
if (veh) then
local modelid = getElementModel(veh)
if (governmentVehicle[modelid]) or exports.global:cdoesVehicleHaveItem(veh, 61) then -- Emergency Light Becon
local lights = getVehicleOverrideLights(veh)
local state = getElementData(veh, "flashers")
if (lights==2) then
if not (state) then
setElementData(veh, "flashers", true, true)
setVehicleHeadLightColor(veh, 0, 0, 255)
setVehicleLightState(veh, 0, 1)
setVehicleLightState(veh, 1, 0)
else
setElementData(veh, "flashers", nil, true)
setVehicleLightState(veh, 0, 0)
setVehicleLightState(veh, 1, 0)
setVehicleHeadLightColor(veh, 255, 255, 255)
end
end
end
end
end
governmentVehicle = { [416]=true, [427]=true, [490]=true, [528]=true, [407]=true, [544]=true, [523]=true, [596]=true, [597]=true, [598]=true, [599]=true, [601]=true, [428]=true }
policevehicles = { }
policevehicleids = { }
function streamIn()
if (getElementType(source)=="vehicle") then
local modelid = getElementModel(source)
if (governmentVehicle[modelid]) or exports.global:cdoesVehicleHaveItem(source, 61) then
for i = 1, #policevehicles+1 do
if (policevehicles[i]==nil) then
policevehicles[i] = source
policevehicleids[source] = i
break
end
end
end
end
end
addEvent("forceElementStreamIn", true)
addEventHandler("forceElementStreamIn", getRootElement(), streamIn)
addEventHandler("onClientElementStreamIn", getRootElement(), streamIn)
function streamOut()
if (getElementType(source)=="vehicle") then
local modelid = getElementModel(source)
if (policevehicleids[source]~=nil) then
local id = policevehicleids[source]
setVehicleHeadLightColor(source, 255, 255, 255)
policevehicleids[source] = nil
policevehicles[id] = nil
end
end
end
addEventHandler("onClientElementStreamOut", getRootElement(), streamOut)
function doFlashes()
if (#policevehicles==0) then return end
for key, veh in ipairs(policevehicles) do
if not (isElement(veh)) then
local id = policevehicleids[veh]
policevehicleids[veh] = nil
policevehicles[id] = nil
elseif (getElementData(veh, "flashers")) then
local state1 = getVehicleLightState(veh, 0)
local state2 = getVehicleLightState(veh, 1)
if (state1==0) then
setVehicleHeadLightColor(veh, 0, 0, 255)
else
setVehicleHeadLightColor(veh, 255, 0, 0)
end
setVehicleLightState(veh, 0, state2)
setVehicleLightState(veh, 1, state1)
end
end
end
setTimer(doFlashes, 250, 0)
function vehicleBlown()
setElementData(source, "flashers", nil, true)
end
addEventHandler("onVehicleRespawn", getRootElement(), vehicleBlown)
|
-- Bind Keys required
function bindKeys(res)
bindKey("p", "down", toggleFlashers)
for key, value in ipairs(getElementsByType("vehicle")) do
local modelid = getVehicleModel(value)
if (isElementStreamedIn(value)) then
if (governmentVehicle[modelid]) or exports.global:cdoesVehicleHaveItem(value, 61) then
for i = 1, #policevehicles+1 do
if (policevehicles[i]==nil) then
policevehicles[i] = value
policevehicleids[value] = i
break
end
end
end
end
end
end
addEventHandler("onClientResourceStart", getResourceRootElement(), bindKeys)
function toggleFlashers()
local veh = getPedOccupiedVehicle(getLocalPlayer())
if (veh) then
local modelid = getElementModel(veh)
if (governmentVehicle[modelid]) or exports.global:cdoesVehicleHaveItem(veh, 61) then -- Emergency Light Becon
local lights = getVehicleOverrideLights(veh)
local state = getElementData(veh, "flashers")
if (lights==2) then
if not (state) then
setElementData(veh, "flashers", true, true)
setVehicleHeadLightColor(veh, 0, 0, 255)
setVehicleLightState(veh, 0, 1)
setVehicleLightState(veh, 1, 0)
else
setElementData(veh, "flashers", nil, true)
setVehicleLightState(veh, 0, 0)
setVehicleLightState(veh, 1, 0)
setVehicleHeadLightColor(veh, 255, 255, 255)
end
end
end
end
end
governmentVehicle = { [416]=true, [427]=true, [490]=true, [528]=true, [407]=true, [544]=true, [523]=true, [596]=true, [597]=true, [598]=true, [599]=true, [601]=true, [428]=true }
policevehicles = { }
policevehicleids = { }
function streamIn()
if (getElementType(source)=="vehicle") then
local modelid = getElementModel(source)
if (governmentVehicle[modelid]) or exports.global:cdoesVehicleHaveItem(source, 61) then
for i = 1, #policevehicles+1 do
if (policevehicles[i]==nil) then
policevehicles[i] = source
policevehicleids[source] = i
break
end
end
end
end
end
addEvent("forceElementStreamIn", true)
addEventHandler("forceElementStreamIn", getRootElement(), streamIn)
addEventHandler("onClientElementStreamIn", getRootElement(), streamIn)
function streamOut()
if (getElementType(source)=="vehicle") then
local modelid = getElementModel(source)
if (policevehicleids[source]~=nil) then
local id = policevehicleids[source]
setVehicleHeadLightColor(source, 255, 255, 255)
policevehicleids[source] = nil
policevehicles[id] = nil
end
end
end
addEventHandler("onClientElementStreamOut", getRootElement(), streamOut)
count = 0
function doFlashes()
if (#policevehicles==0) then return end
for key, veh in ipairs(policevehicles) do
if not (isElement(veh)) then
local id = policevehicleids[veh]
policevehicleids[veh] = nil
policevehicles[id] = nil
elseif (getElementData(veh, "flashers")) then
local state1 = getVehicleLightState(veh, 0)
local state2 = getVehicleLightState(veh, 1)
if (state1==0) then
setVehicleHeadLightColor(veh, 0, 0, 255)
else
setVehicleHeadLightColor(veh, 255, 0, 0)
end
setVehicleLightState(veh, 0, state2)
setVehicleLightState(veh, 1, state1)
end
end
end
setTimer(doFlashes, 250, 0)
function vehicleBlown()
setElementData(source, "flashers", nil, true)
end
addEventHandler("onVehicleRespawn", getRootElement(), vehicleBlown)
|
0001012: LSPD/ES Emergency Light Mods bugging out
|
0001012: LSPD/ES Emergency Light Mods bugging out
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1331 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
863c1b673d0986819b0228f324fb8e18e616c8c9
|
Modules/Shared/Utility/QFrame.lua
|
Modules/Shared/Utility/QFrame.lua
|
--- CFrame representation as a quaternion
-- @module QFrame
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Quaternion = require("Quaternion")
local QFrame = {}
QFrame.__index = QFrame
function QFrame.new(px, py, pz, w, x, y, z)
local self = setmetatable({}, QFrame)
self.px = px or 0
self.py = py or 0
self.pz = pz or 0
self.w = w or 1
self.x = x or 0
self.y = y or 0
self.z = z or 0
return self
end
function QFrame.fromCFrameClosestTo(cframe, closestTo)
local w, x, y, z = Quaternion.QuaternionFromCFrame(cframe)
local dot = w*closestTo.w + x*closestTo.x + y*closestTo.y + z*closestTo.z
if dot < 0 then
return QFrame.new(cframe.x, cframe.y, cframe.z, -w, -x, -y, -z)
end
return QFrame.new(cframe.x, cframe.y, cframe.z, w, x, y, z)
end
function QFrame.toCFrame(self)
local cframe = CFrame.new(self.px, self.py, self.pz, self.x, self.y, self.z, self.w)
if cframe == cframe then
return cframe
else
return nil
end
end
function QFrame.toPosition(self)
return Vector3.new(self.px, self.py, self.pz)
end
function QFrame.__add(a, b)
assert(getmetatable(a) == QFrame and getmetatable(b) == QFrame,
"QFrame + non-QFrame attempted")
return QFrame.new(a.px + b.px, a.py + b.py, a.pz + b.pz, a.w + b.w, a.x + b.x, a.y + b.y, a.z + b.z)
end
function QFrame.__mul(a, b)
if type(a) == "number" then
return QFrame.new(a*b.px, a*b.py, a*b.pz, a*b.w, a*b.x, a*b.y, a*b.z)
elseif type(b) == "number" then
return QFrame.new(a.px*b, a.py*b, a.pz*b, a.w*b, a.x*b, a.y*b, a.z*b)
else
error("QFrame * non-QFrame attempted")
end
end
return QFrame
|
--- CFrame representation as a quaternion
-- @module QFrame
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local Quaternion = require("Quaternion")
local QFrame = {}
QFrame.__index = QFrame
function QFrame.new(px, py, pz, w, x, y, z)
local self = setmetatable({}, QFrame)
self.px = px or 0
self.py = py or 0
self.pz = pz or 0
self.w = w or 1
self.x = x or 0
self.y = y or 0
self.z = z or 0
return self
end
function QFrame.fromCFrameClosestTo(cframe, closestTo)
local w, x, y, z = Quaternion.QuaternionFromCFrame(cframe)
if not w then
return nil
end
local dot = w*closestTo.w + x*closestTo.x + y*closestTo.y + z*closestTo.z
if dot < 0 then
return QFrame.new(cframe.x, cframe.y, cframe.z, -w, -x, -y, -z)
end
return QFrame.new(cframe.x, cframe.y, cframe.z, w, x, y, z)
end
function QFrame.toCFrame(self)
local cframe = CFrame.new(self.px, self.py, self.pz, self.x, self.y, self.z, self.w)
if cframe == cframe then
return cframe
else
return nil
end
end
function QFrame.toPosition(self)
return Vector3.new(self.px, self.py, self.pz)
end
function QFrame.__add(a, b)
assert(getmetatable(a) == QFrame and getmetatable(b) == QFrame,
"QFrame + non-QFrame attempted")
return QFrame.new(a.px + b.px, a.py + b.py, a.pz + b.pz, a.w + b.w, a.x + b.x, a.y + b.y, a.z + b.z)
end
function QFrame.__mul(a, b)
if type(a) == "number" then
return QFrame.new(a*b.px, a*b.py, a*b.pz, a*b.w, a*b.x, a*b.y, a*b.z)
elseif type(b) == "number" then
return QFrame.new(a.px*b, a.py*b, a.pz*b, a.w*b, a.x*b, a.y*b, a.z*b)
else
error("QFrame * non-QFrame attempted")
end
end
return QFrame
|
Fix QFrame
|
Fix QFrame
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
220aa69a516476a952aafd4d15190771d132e669
|
kong/cli/utils/utils.lua
|
kong/cli/utils/utils.lua
|
--[[
Kong CLI utilities
- Logging
- Luarocks helpers
]]
local ansicolors = require "ansicolors"
local constants = require "kong.constants"
local Object = require "classic"
local lpath = require "luarocks.path"
local IO = require "kong.tools.io"
--
-- Colors
--
local colors = {}
for _, v in ipairs({"red", "green", "yellow", "blue"}) do
colors[v] = function(str) return ansicolors("%{"..v.."}"..str.."%{reset}") end
end
local function trim(s)
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
--
-- Logging
--
local Logger = Object:extend()
function Logger:new(silent)
self.silent = silent
end
function Logger:print(str)
if not self.silent then
print(trim(str))
end
end
function Logger:info(str)
self:print(colors.blue("[INFO] ")..str)
end
function Logger:success(str)
self:print(colors.green("[OK] ")..str)
end
function Logger:warn(str)
self:print(colors.yellow("[WARN] ")..str)
end
function Logger:error(str)
self:print(colors.red("[ERR] ")..str)
end
function Logger:error_exit(str)
self:error(str)
-- Optional stacktrace
--print("")
--error("", 2)
os.exit(1)
end
local logger = Logger()
--
-- Luarocks
--
local function get_kong_infos()
return { name = constants.NAME, version = constants.ROCK_VERSION }
end
local function get_luarocks_dir()
local cfg = require "luarocks.cfg"
local search = require "luarocks.search"
local infos = get_kong_infos()
local tree_map = {}
local results = {}
for _, tree in ipairs(cfg.rocks_trees) do
local rocks_dir = lpath.rocks_dir(tree)
tree_map[rocks_dir] = tree
search.manifest_search(results, rocks_dir, search.make_query(infos.name:lower(), infos.version))
end
local version
for k, _ in pairs(results.kong) do
version = k
end
return tree_map[results.kong[version][1].repo]
end
local function get_luarocks_config_dir()
local repo = get_luarocks_dir()
local infos = get_kong_infos()
return lpath.conf_dir(infos.name:lower(), infos.version, repo)
end
local function get_luarocks_install_dir()
local repo = get_luarocks_dir()
local infos = get_kong_infos()
return lpath.install_dir(infos.name:lower(), infos.version, repo)
end
local function get_kong_config_path(args_config)
local config_path = args_config
-- Use the rock's config if no config at default location
if not IO.file_exists(config_path) then
logger:warn("No configuration at: "..config_path.." using default config instead.")
config_path = IO.path:join(get_luarocks_config_dir(), "kong.yml")
end
-- Make sure the configuration file really exists
if not IO.file_exists(config_path) then
logger:warn("No configuration at: "..config_path)
logger:error_exit("Could not find a configuration file.")
end
return config_path
end
local function get_ssl_cert_and_key(kong_config)
local ssl_cert_path, ssl_key_path
if (kong_config.ssl_cert and not kong_config.ssl_key) or
(kong_config.ssl_key and not kong_config.ssl_cert) then
logger:error_exit("Both \"ssl_cert_path\" and \"ssl_key_path\" need to be specified in the configuration, or none of them")
elseif kong_config.ssl_cert and kong_config.ssl_key then
ssl_cert_path = kong_config.ssl_cert_path
ssl_key_path = kong_config.ssl_key_path
else
ssl_cert_path = IO.path:join(get_luarocks_install_dir(), "ssl", "kong-default.crt")
ssl_key_path = IO.path:join(get_luarocks_install_dir(), "ssl", "kong-default.key")
end
-- Check that the file exists
if ssl_cert_path and not IO.file_exists(ssl_cert_path) then
logger:error_exit("Can't find default Kong SSL certificate at: "..ssl_cert_path)
end
if ssl_key_path and not IO.file_exists(ssl_key_path) then
logger:error_exit("Can't find default Kong SSL key at: "..ssl_key_path)
end
return ssl_cert_path, ssl_key_path
end
-- Checks if a port is open on localhost
-- @param `port` The port to check
-- @return `open` True if open, false otherwise
local function is_port_open(port)
local _, code = IO.os_execute("nc -w 5 -z 127.0.0.1 "..tostring(port))
return code == 0
end
return {
colors = colors,
logger = logger,
get_kong_infos = get_kong_infos,
get_kong_config_path = get_kong_config_path,
get_ssl_cert_and_key = get_ssl_cert_and_key,
get_luarocks_install_dir = get_luarocks_install_dir,
is_port_open = is_port_open
}
|
--[[
Kong CLI utilities
- Logging
- Luarocks helpers
]]
local ansicolors = require "ansicolors"
local constants = require "kong.constants"
local Object = require "classic"
local lpath = require "luarocks.path"
local IO = require "kong.tools.io"
--
-- Colors
--
local colors = {}
for _, v in ipairs({"red", "green", "yellow", "blue"}) do
colors[v] = function(str) return ansicolors("%{"..v.."}"..str.."%{reset}") end
end
local function trim(s)
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
--
-- Logging
--
local Logger = Object:extend()
function Logger:new(silent)
self.silent = silent
end
function Logger:print(str)
if not self.silent then
print(trim(str))
end
end
function Logger:info(str)
self:print(colors.blue("[INFO] ")..str)
end
function Logger:success(str)
self:print(colors.green("[OK] ")..str)
end
function Logger:warn(str)
self:print(colors.yellow("[WARN] ")..str)
end
function Logger:error(str)
self:print(colors.red("[ERR] ")..str)
end
function Logger:error_exit(str)
self:error(str)
-- Optional stacktrace
--print("")
--error("", 2)
os.exit(1)
end
local logger = Logger()
--
-- Luarocks
--
local function get_kong_infos()
return { name = constants.NAME, version = constants.ROCK_VERSION }
end
local function get_luarocks_dir()
local cfg = require "luarocks.cfg"
local search = require "luarocks.search"
local infos = get_kong_infos()
local tree_map = {}
local results = {}
for _, tree in ipairs(cfg.rocks_trees) do
local rocks_dir = lpath.rocks_dir(tree)
tree_map[rocks_dir] = tree
search.manifest_search(results, rocks_dir, search.make_query(infos.name:lower(), infos.version))
end
local version
for k, _ in pairs(results.kong) do
version = k
end
return tree_map[results.kong[version][1].repo]
end
local function get_luarocks_config_dir()
local repo = get_luarocks_dir()
local infos = get_kong_infos()
return lpath.conf_dir(infos.name:lower(), infos.version, repo)
end
local function get_luarocks_install_dir()
local repo = get_luarocks_dir()
local infos = get_kong_infos()
return lpath.install_dir(infos.name:lower(), infos.version, repo)
end
local function get_kong_config_path(args_config)
local config_path = args_config
-- Use the rock's config if no config at default location
if not IO.file_exists(config_path) then
logger:warn("No configuration at: "..config_path.." using default config instead.")
config_path = IO.path:join(get_luarocks_config_dir(), "kong.yml")
end
-- Make sure the configuration file really exists
if not IO.file_exists(config_path) then
logger:warn("No configuration at: "..config_path)
logger:error_exit("Could not find a configuration file.")
end
return config_path
end
local function get_ssl_cert_and_key(kong_config)
local ssl_cert_path, ssl_key_path
if (kong_config.ssl_cert_path and not kong_config.ssl_key_path) or
(kong_config.ssl_key_path and not kong_config.ssl_cert_path) then
logger:error_exit("Both \"ssl_cert_path\" and \"ssl_key_path\" need to be specified in the configuration, or none of them")
elseif kong_config.ssl_cert_path and kong_config.ssl_key_path then
ssl_cert_path = kong_config.ssl_cert_path
ssl_key_path = kong_config.ssl_key_path
else
ssl_cert_path = IO.path:join(get_luarocks_install_dir(), "ssl", "kong-default.crt")
ssl_key_path = IO.path:join(get_luarocks_install_dir(), "ssl", "kong-default.key")
end
-- Check that the file exists
if ssl_cert_path and not IO.file_exists(ssl_cert_path) then
logger:error_exit("Can't find default Kong SSL certificate at: "..ssl_cert_path)
end
if ssl_key_path and not IO.file_exists(ssl_key_path) then
logger:error_exit("Can't find default Kong SSL key at: "..ssl_key_path)
end
return ssl_cert_path, ssl_key_path
end
-- Checks if a port is open on localhost
-- @param `port` The port to check
-- @return `open` True if open, false otherwise
local function is_port_open(port)
local _, code = IO.os_execute("nc -w 5 -z 127.0.0.1 "..tostring(port))
return code == 0
end
return {
colors = colors,
logger = logger,
get_kong_infos = get_kong_infos,
get_kong_config_path = get_kong_config_path,
get_ssl_cert_and_key = get_ssl_cert_and_key,
get_luarocks_install_dir = get_luarocks_install_dir,
is_port_open = is_port_open
}
|
Fix ssl config
|
Fix ssl config
Former-commit-id: b22190171da0c2d978105d6cca19227ad9e74d7d
|
Lua
|
apache-2.0
|
shiprabehera/kong,ccyphers/kong,akh00/kong,Kong/kong,isdom/kong,ind9/kong,jerizm/kong,streamdataio/kong,salazar/kong,Kong/kong,ejoncas/kong,isdom/kong,kyroskoh/kong,rafael/kong,icyxp/kong,smanolache/kong,vzaramel/kong,Vermeille/kong,li-wl/kong,xvaara/kong,jebenexer/kong,kyroskoh/kong,Kong/kong,ajayk/kong,vzaramel/kong,streamdataio/kong,ejoncas/kong,ind9/kong,Mashape/kong,rafael/kong,beauli/kong
|
b66a302082eb97fec9f3d55ef28b05a4bf785988
|
languages/unicode.lua
|
languages/unicode.lua
|
require("char-def")
local chardata = characters.data
SILE.nodeMakers.base = std.object {
makeToken = function(self)
if #self.contents>0 then
coroutine.yield(SILE.shaper:formNnode(self.contents, self.token, self.options))
SU.debug("tokenizer", "Token: "..self.token)
self.contents = {} ; self.token = "" ; self.lastnode = "nnode"
end
end,
makeLetterSpaceGlue = function(self)
if self.lastnode ~= "glue" then
if SILE.settings.get("document.letterspaceglue") then
local w = SILE.settings.get("document.letterspaceglue").width
coroutine.yield(SILE.nodefactory.newKern({ width = w }))
end
end
self.lastnode = "glue"
end,
addToken = function (self, char, item)
self.token = self.token .. char
self.contents[#self.contents+1] = item
end,
makeGlue = function(self)
if SILE.settings.get("typesetter.obeyspaces") or self.lastnode ~= "glue" then
coroutine.yield(SILE.shaper:makeSpaceNode(self.options))
end
self.lastnode = "glue"
end,
makePenalty = function (self,p)
if self.lastnode ~= "penalty" and self.lastnode ~= "glue" then
coroutine.yield( SILE.nodefactory.newPenalty({ penalty = p or 0 }) )
end
self.lastnode = "penalty"
end,
init = function (self)
self.contents = {}
self.token = ""
self.lastnode = ""
end,
iterator = function (self,items)
SU.error("Abstract function nodemaker:iterator called",1)
end
}
SILE.nodeMakers.unicode = SILE.nodeMakers.base {
isWordType = { cm = true },
isSpaceType = { sp = true },
isBreakingType = { ba = true, zw = true },
dealWith = function (self, item)
local char = item.text
local cp = SU.codepoint(char)
local thistype = chardata[cp] and chardata[cp].linebreak
if chardata[cp] and self.isSpaceType[thistype] then
self:makeToken()
self:makeGlue()
elseif chardata[cp] and self.isBreakingType[thistype] then
self:addToken(char,item)
self:makeToken()
self:makePenalty(0)
elseif lasttype and (thistype and thistype ~= lasttype and not self.isWordType[thistype]) then
self:makeToken()
self:addToken(char,item)
else
if SILE.settings.get("document.letterspaceglue") then
self:makeToken()
self:makeLetterSpaceGlue()
end
self:addToken(char,item)
end
if not self.isWordType[thistype] then lasttype = chardata[cp] and chardata[cp].linebreak end
end,
iterator = function (self, items)
self:init()
return coroutine.wrap(function()
for i = 1,#items do self:dealWith(items[i]) end
if SILE.settings.get("document.letterspaceglue") then self:makeLetterSpaceGlue() end
self:makeToken()
end)
end
}
pcall( function () icu = require("justenoughicu") end)
if icu then
SILE.nodeMakers.unicode.iterator = function (self, items)
local fulltext = ""
local ics = SILE.settings.get("document.letterspaceglue")
for i = 1,#items do item = items[i]
fulltext = fulltext .. items[i].text
end
local chunks = {icu.breakpoints(fulltext, self.options.language)}
self:init()
table.remove(chunks,1)
return coroutine.wrap(function()
-- Special-case initial glue
local i = 1
while i <= #items do item = items[i]
local char = item.text
local cp = SU.codepoint(char)
local thistype = chardata[cp] and chardata[cp].linebreak
if thistype == "sp" then self:makeGlue() else break end
i = i + 1
end
-- And now onto the real thing
for i = i,#items do item = items[i]
local char = items[i].text
local cp = SU.codepoint(char)
if chunks[1] and (items[i].index >= chunks[1].index) then
-- There's a break here
local thistype = chardata[cp] and chardata[cp].linebreak
local bp = chunks[1]
while chunks[1] and items[i].index >= chunks[1].index do
table.remove(chunks,1)
end
if bp.type == "word" then
if chardata[cp] and thistype == "sp" then
-- Spacing word break
self:makeToken()
self:makeGlue()
else -- a word break which isn't a space
self:makeToken()
self:addToken(char,item)
end
elseif bp.type == "line" then
-- Line break
self:makeToken()
self:makePenalty(bp.subtype == "soft" and 0 or -1000)
self:addToken(char,item)
end
else
if ics then
self:makeToken()
self:makeLetterSpaceGlue()
end
self:addToken(char,item)
end
end
if ics then self:makeLetterSpaceGlue() end
self:makeToken()
end)
end
end
|
require("char-def")
local chardata = characters.data
SILE.nodeMakers.base = std.object {
makeToken = function(self)
if #self.contents>0 then
coroutine.yield(SILE.shaper:formNnode(self.contents, self.token, self.options))
SU.debug("tokenizer", "Token: "..self.token)
self.contents = {} ; self.token = "" ; self.lastnode = "nnode"
end
end,
makeLetterSpaceGlue = function(self)
if self.lastnode ~= "glue" then
if SILE.settings.get("document.letterspaceglue") then
local w = SILE.settings.get("document.letterspaceglue").width
coroutine.yield(SILE.nodefactory.newKern({ width = w }))
end
end
self.lastnode = "glue"
end,
addToken = function (self, char, item)
self.token = self.token .. char
self.contents[#self.contents+1] = item
end,
makeGlue = function(self)
if SILE.settings.get("typesetter.obeyspaces") or self.lastnode ~= "glue" then
coroutine.yield(SILE.shaper:makeSpaceNode(self.options))
end
self.lastnode = "glue"
end,
makePenalty = function (self,p)
if self.lastnode ~= "penalty" and self.lastnode ~= "glue" then
coroutine.yield( SILE.nodefactory.newPenalty({ penalty = p or 0 }) )
end
self.lastnode = "penalty"
end,
init = function (self)
self.contents = {}
self.token = ""
self.lastnode = ""
end,
iterator = function (self,items)
SU.error("Abstract function nodemaker:iterator called",1)
end
}
SILE.nodeMakers.unicode = SILE.nodeMakers.base {
isWordType = { cm = true },
isSpaceType = { sp = true },
isBreakingType = { ba = true, zw = true },
dealWith = function (self, item)
local char = item.text
local cp = SU.codepoint(char)
local thistype = chardata[cp] and chardata[cp].linebreak
if chardata[cp] and self.isSpaceType[thistype] then
self:makeToken()
self:makeGlue()
elseif chardata[cp] and self.isBreakingType[thistype] then
self:addToken(char,item)
self:makeToken()
self:makePenalty(0)
elseif lasttype and (thistype and thistype ~= lasttype and not self.isWordType[thistype]) then
self:makeToken()
self:addToken(char,item)
else
if SILE.settings.get("document.letterspaceglue") then
self:makeToken()
self:makeLetterSpaceGlue()
end
self:addToken(char,item)
end
if not self.isWordType[thistype] then lasttype = chardata[cp] and chardata[cp].linebreak end
end,
iterator = function (self, items)
self:init()
return coroutine.wrap(function()
for i = 1,#items do self:dealWith(items[i]) end
if SILE.settings.get("document.letterspaceglue") then self:makeLetterSpaceGlue() end
self:makeToken()
end)
end
}
pcall( function () icu = require("justenoughicu") end)
if icu then
SILE.nodeMakers.unicode.iterator = function (self, items)
local fulltext = ""
local ics = SILE.settings.get("document.letterspaceglue")
for i = 1,#items do item = items[i]
fulltext = fulltext .. items[i].text
end
local chunks = {icu.breakpoints(fulltext, self.options.language)}
self:init()
table.remove(chunks,1)
return coroutine.wrap(function()
-- Special-case initial glue
local i = 1
while i <= #items do item = items[i]
local char = item.text
local cp = SU.codepoint(char)
local thistype = chardata[cp] and chardata[cp].linebreak
if thistype == "sp" then self:makeGlue() else break end
i = i + 1
end
-- And now onto the real thing
for i = i,#items do item = items[i]
local char = items[i].text
local cp = SU.codepoint(char)
if chunks[1] and (items[i].index >= chunks[1].index) then
-- There's a break here
local thistype = chardata[cp] and chardata[cp].linebreak
local bp = chunks[1]
while chunks[1] and items[i].index >= chunks[1].index do
table.remove(chunks,1)
end
if bp.type == "word" then
if chardata[cp] and thistype == "sp" then
-- Spacing word break
self:makeToken()
self:makeGlue()
else -- a word break which isn't a space
self:makeToken()
self:addToken(char,item)
end
elseif bp.type == "line" then
if chardata[cp] and thistype == "sp" then
self:makeToken()
self:makeGlue()
else
-- Line break
self:makeToken()
self:makePenalty(bp.subtype == "soft" and 0 or -1000)
self:addToken(char,item)
end
end
else
local thistype = chardata[cp] and chardata[cp].linebreak
if ics then
self:makeToken()
self:makeLetterSpaceGlue()
end
if chardata[cp] and thistype == "sp" then
self:makeToken()
self:makeGlue()
else
self:addToken(char,item)
end
end
end
if ics then self:makeLetterSpaceGlue() end
self:makeToken()
end)
end
end
|
Check for end-of-stream space. Fixes color-fonts, may break everything else...
|
Check for end-of-stream space. Fixes color-fonts, may break everything else...
|
Lua
|
mit
|
alerque/sile,neofob/sile,alerque/sile,alerque/sile,neofob/sile,neofob/sile,simoncozens/sile,simoncozens/sile,alerque/sile,neofob/sile,simoncozens/sile,simoncozens/sile
|
0b4f9030c66682840904ed73ba1aaff2f2cadce9
|
src/plugins/finalcutpro/tangent/video.lua
|
src/plugins/finalcutpro/tangent/video.lua
|
--- === plugins.finalcutpro.tangent.video ===
---
--- Final Cut Pro Video Inspector for Tangent
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local require = require
--------------------------------------------------------------------------------
-- Logger:
--------------------------------------------------------------------------------
--local log = require("hs.logger").new("tng_video")
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local fcp = require("cp.apple.finalcutpro")
local deferred = require("cp.deferred")
local i18n = require("cp.i18n")
--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------
-- DEFER -> number
-- Constant
-- The amount of time to defer UI updates
local DEFER = 0.01
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
-- xyParameter() -> none
-- Function
-- Sets up a new XY Parameter
--
-- Parameters:
-- * group - The Tangent Group
-- * param - The Parameter
-- * id - The Tangent ID
--
-- Returns:
-- * An updated ID
-- * The `x` parameter value
-- * The `y` parameter value
-- * The xy binding
local function xyParameter(group, param, id)
--------------------------------------------------------------------------------
-- Set up the accumulator:
--------------------------------------------------------------------------------
local x, y = 0, 0
local updateUI = deferred.new(DEFER)
updateUI:action(function()
if x ~= 0 then
local current = param:x()
if current then
param:x(current + x)
end
x = 0
end
if y ~= 0 then
local current = param:y()
if current then
param:y(current + y)
end
y = 0
end
end)
local label = param:label()
local xParam = group:parameter(id + 1)
:name(label .. " X")
--------------------------------------------------------------------------------
-- TODO: Hack to work around Tangent Hub bug that doesn't send changes if
-- no min/max are set.
--------------------------------------------------------------------------------
:minValue(0)
:maxValue(100)
:stepSize(0.5)
:onGet(function() return param:x() end)
:onChange(function(amount)
x = x + amount
updateUI()
end)
:onReset(function() param:x(0) end)
local yParam = group:parameter(id + 2)
:name(label .. " Y")
--------------------------------------------------------------------------------
-- TODO: Hack to work around Tangent Hub bug that doesn't send changes if
-- no min/max are set.
--------------------------------------------------------------------------------
:minValue(0)
:maxValue(100)
:stepSize(0.5)
:onGet(function() return param:y() end)
:onChange(function(amount)
fcp:inspector():video():show()
y = y + amount
updateUI()
end)
:onReset(function() param:y(0) end)
local xyBinding = group:binding(label):members(xParam, yParam)
return id + 2, xParam, yParam, xyBinding
end
-- sliderParameter() -> none
-- Function
-- Sets up a new Slider Parameter
--
-- Parameters:
-- * group - The Tangent Group
-- * param - The Parameter
-- * id - The Tangent ID
-- * minValue - The minimum value
-- * maxValue - The maximum value
-- * stepSize - The step size
-- * default - The default value
--
-- Returns:
-- * An updated ID
-- * The parameters value
local function sliderParameter(group, param, id, minValue, maxValue, stepSize, default)
local label = param:label()
--------------------------------------------------------------------------------
-- Set up deferred update:
--------------------------------------------------------------------------------
local value = 0
local updateUI = deferred.new(DEFER)
updateUI:action(function()
if value ~= 0 then
local currentValue = param.value()
if currentValue then
param.value(currentValue + value)
value = 0
end
end
end)
default = default or 0
local valueParam = group:parameter(id + 1)
:name(label)
:minValue(minValue)
:maxValue(maxValue)
:stepSize(stepSize)
:onGet(function() return param:value() end)
:onChange(function(amount)
fcp:inspector():video():show()
value = value + amount
updateUI()
end)
:onReset(function() param:value(default) end)
return id + 1, valueParam
end
--- plugins.finalcutpro.tangent.video.init(deps) -> self
--- Function
--- Initialise the module.
---
--- Parameters:
--- * deps - Dependancies
---
--- Returns:
--- * Self
function mod.init(deps)
local video = fcp:inspector():video()
deps.tangentManager.addMode(0x00010010, "FCP: Video")
mod._videoGroup = deps.fcpGroup:group(i18n("video") .. " " .. i18n("inspector"))
local transform = video:transform()
local transformGroup = mod._videoGroup:group(transform:label())
local id = 0x0F730000
local px, py, rotation
id, px, py = xyParameter(transformGroup, transform:show():position(), id)
id, rotation = sliderParameter(transformGroup, transform:show():rotation(), id, 0, 360, 0.1)
transformGroup:binding(tostring(transform:show():position()) .. " " .. tostring(transform:rotation()))
:members(px, py, rotation)
id = sliderParameter(transformGroup, transform:scaleAll(), id, 0, 100, 0.1, 100.0)
id = sliderParameter(transformGroup, transform:scaleX(), id, 0, 100, 0.1, 100.0)
id = sliderParameter(transformGroup, transform:scaleY(), id, 0, 100, 0.1, 100.0)
xyParameter(transformGroup, transform:anchor(), id)
return mod
end
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.tangent.video",
group = "finalcutpro",
dependencies = {
["finalcutpro.tangent.group"] = "fcpGroup",
["core.tangent.manager"] = "tangentManager",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
return mod.init(deps)
end
return plugin
|
--- === plugins.finalcutpro.tangent.video ===
---
--- Final Cut Pro Video Inspector for Tangent
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local require = require
--------------------------------------------------------------------------------
-- Logger:
--------------------------------------------------------------------------------
--local log = require("hs.logger").new("tng_video")
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local fcp = require("cp.apple.finalcutpro")
local deferred = require("cp.deferred")
local i18n = require("cp.i18n")
--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------
-- DEFER -> number
-- Constant
-- The amount of time to defer UI updates
local DEFER = 0.01
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
-- xyParameter() -> none
-- Function
-- Sets up a new XY Parameter
--
-- Parameters:
-- * group - The Tangent Group
-- * param - The Parameter
-- * id - The Tangent ID
--
-- Returns:
-- * An updated ID
-- * The `x` parameter value
-- * The `y` parameter value
-- * The xy binding
local function xyParameter(group, param, id)
--------------------------------------------------------------------------------
-- Set up the accumulator:
--------------------------------------------------------------------------------
local x, y = 0, 0
local updateUI = deferred.new(DEFER)
updateUI:action(function()
if x ~= 0 then
local current = param:x()
if current then
param:x(current + x)
end
x = 0
end
if y ~= 0 then
local current = param:y()
if current then
param:y(current + y)
end
y = 0
end
end)
local label = param:label()
local xParam = group:parameter(id + 1)
:name(label .. " X")
--------------------------------------------------------------------------------
-- TODO: Hack to work around Tangent Hub bug that doesn't send changes if
-- no min/max are set.
--------------------------------------------------------------------------------
:minValue(0)
:maxValue(100)
:stepSize(0.5)
:onGet(function() return param:x() end)
:onChange(function(amount)
fcp:inspector():video():show()
x = x + amount
updateUI()
end)
:onReset(function() param:x(0) end)
local yParam = group:parameter(id + 2)
:name(label .. " Y")
--------------------------------------------------------------------------------
-- TODO: Hack to work around Tangent Hub bug that doesn't send changes if
-- no min/max are set.
--------------------------------------------------------------------------------
:minValue(0)
:maxValue(100)
:stepSize(0.5)
:onGet(function() return param:y() end)
:onChange(function(amount)
y = y + amount
updateUI()
end)
:onReset(function() param:y(0) end)
local xyBinding = group:binding(label):members(xParam, yParam)
return id + 2, xParam, yParam, xyBinding
end
-- sliderParameter() -> none
-- Function
-- Sets up a new Slider Parameter
--
-- Parameters:
-- * group - The Tangent Group
-- * param - The Parameter
-- * id - The Tangent ID
-- * minValue - The minimum value
-- * maxValue - The maximum value
-- * stepSize - The step size
-- * default - The default value
--
-- Returns:
-- * An updated ID
-- * The parameters value
local function sliderParameter(group, param, id, minValue, maxValue, stepSize, default)
local label = param:label()
--------------------------------------------------------------------------------
-- Set up deferred update:
--------------------------------------------------------------------------------
local value = 0
local updateUI = deferred.new(DEFER)
updateUI:action(function()
if value ~= 0 then
fcp:inspector():video():show()
local currentValue = param.value()
if currentValue then
param.value(currentValue + value)
value = 0
end
end
end)
default = default or 0
local valueParam = group:parameter(id + 1)
:name(label)
:minValue(minValue)
:maxValue(maxValue)
:stepSize(stepSize)
:onGet(function() return param:value() end)
:onChange(function(amount)
value = value + amount
updateUI()
end)
:onReset(function() param:value(default) end)
return id + 1, valueParam
end
--- plugins.finalcutpro.tangent.video.init(deps) -> self
--- Function
--- Initialise the module.
---
--- Parameters:
--- * deps - Dependancies
---
--- Returns:
--- * Self
function mod.init(deps)
local video = fcp:inspector():video()
deps.tangentManager.addMode(0x00010010, "FCP: Video")
mod._videoGroup = deps.fcpGroup:group(i18n("video") .. " " .. i18n("inspector"))
local transform = video:transform()
local transformGroup = mod._videoGroup:group(transform:label())
local id = 0x0F730000
local px, py, rotation
id, px, py = xyParameter(transformGroup, transform:position(), id)
id, rotation = sliderParameter(transformGroup, transform:rotation(), id, 0, 360, 0.1)
transformGroup:binding(tostring(transform:position()) .. " " .. tostring(transform:rotation()))
:members(px, py, rotation)
id = sliderParameter(transformGroup, transform:scaleAll(), id, 0, 100, 0.1, 100.0)
id = sliderParameter(transformGroup, transform:scaleX(), id, 0, 100, 0.1, 100.0)
id = sliderParameter(transformGroup, transform:scaleY(), id, 0, 100, 0.1, 100.0)
xyParameter(transformGroup, transform:anchor(), id)
return mod
end
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.tangent.video",
group = "finalcutpro",
dependencies = {
["finalcutpro.tangent.group"] = "fcpGroup",
["core.tangent.manager"] = "tangentManager",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
return mod.init(deps)
end
return plugin
|
#1471 * Fixed issue where Video would display every time CP reloaded.
|
#1471
* Fixed issue where Video would display every time CP reloaded.
|
Lua
|
mit
|
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost
|
13295779a6dbc6924c28343e4ff47e5ef6345a40
|
share/lua/playlist/jamendo.lua
|
share/lua/playlist/jamendo.lua
|
--[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Fabio Ritrovato <sephiroth87 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"
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "jamendo.com/get2/" )
and string.match( vlc.path, "/track/xml/" )
end
-- Parse function.
function parse()
local page = ""
while true do
local line = vlc.readline()
if line == nil then break end
page = page .. line
end
local tracks = {}
local tree = simplexml.parse_string( page )
for _, track in ipairs( tree.children ) do
simplexml.add_name_maps( track )
if track.children_map["id"] == nil and
track.children_map["stream"] == nil then
vlc.msg.err( "No track id or stream URL, not enough info to add tracks..." )
return {}
end
local stream_url
if track.children_map["id"][1].children[1] then
stream_url = "http://api.jamendo.com/get2/stream/track/redirect/?id=" .. track.children_map["id"][1].children[1]
else
stream_url = track.children_map["stream"][1].children[1]
end
table.insert( tracks, {path=stream_url,
arturl=track.children_map["album_image"] and track.children_map["album_image"][1].children[1] or ( track.children_map["album_id"] and "http://imgjam.com/albums/".. track.children_map["album_id"][1].children[1] .. "/covers/1.500.jpg" or nil ),
title=track.children_map["name"] and track.children_map["name"][1].children[1] or nil,
artist=track.children_map["artist_name"] and track.children_map["artist_name"][1].children[1] or nil,
album=track.children_map["album_name"] and track.children_map["album_name"][1].children[1] or nil,
genre=track.children_map["album_genre"] and track.children_map["album_genre"][1].children[1] or nil,
duration=track.children_map["duration"] and track.children_map["duration"][1].children[1] or nil,
date=track.children_map["album_dates"] and track.children_map["album_dates"][1].children_map["year"][1].children[1] or nil} )
end
return tracks
end
|
--[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Fabio Ritrovato <sephiroth87 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"
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "api.jamendo.com/" )
and string.match( vlc.path, "get2" )
and string.match( vlc.path, "track" )
and string.match( vlc.path, "xml" )
end
-- Parse function.
function parse()
local page = ""
while true do
local line = vlc.readline()
if line == nil then break end
page = page .. line
end
local tracks = {}
local tree = simplexml.parse_string( page )
for _, track in ipairs( tree.children ) do
simplexml.add_name_maps( track )
if track.children_map["id"] == nil and
track.children_map["stream"] == nil then
vlc.msg.err( "No track id or stream URL, not enough info to add tracks..." )
return {}
end
local stream_url
if track.children_map["id"][1].children[1] then
stream_url = "http://api.jamendo.com/get2/stream/track/redirect/?id=" .. track.children_map["id"][1].children[1]
else
stream_url = track.children_map["stream"][1].children[1]
end
table.insert( tracks, {path=stream_url,
arturl=track.children_map["album_image"] and track.children_map["album_image"][1].children[1] or ( track.children_map["album_id"] and "http://imgjam.com/albums/".. track.children_map["album_id"][1].children[1] .. "/covers/1.500.jpg" or nil ),
title=track.children_map["name"] and track.children_map["name"][1].children[1] or nil,
artist=track.children_map["artist_name"] and track.children_map["artist_name"][1].children[1] or nil,
album=track.children_map["album_name"] and track.children_map["album_name"][1].children[1] or nil,
genre=track.children_map["album_genre"] and track.children_map["album_genre"][1].children[1] or nil,
duration=track.children_map["duration"] and track.children_map["duration"][1].children[1] or nil,
date=track.children_map["album_dates"] and track.children_map["album_dates"][1].children_map["year"][1].children[1] or nil} )
end
return tracks
end
|
Fixed jamendo playlist demuxer.
|
Fixed jamendo playlist demuxer.
The check is a bit less strict to adapt to the various URL we can get.
It closes #5661.
|
Lua
|
lgpl-2.1
|
xkfz007/vlc,jomanmuk/vlc-2.2,krichter722/vlc,krichter722/vlc,krichter722/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,shyamalschandra/vlc,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,xkfz007/vlc,jomanmuk/vlc-2.2,krichter722/vlc,shyamalschandra/vlc,shyamalschandra/vlc,vlc-mirror/vlc,xkfz007/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,vlc-mirror/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc
|
adec4bf7f83e5d9214c708e816f8041f0da94541
|
src/luarocks/command_line.lua
|
src/luarocks/command_line.lua
|
--- Functions for command-line scripts.
--module("luarocks.command_line", package.seeall)
local command_line = {}
local unpack = unpack or table.unpack
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
local path = require("luarocks.path")
local dir = require("luarocks.dir")
local deps = require("luarocks.deps")
local fs = require("luarocks.fs")
local program = util.this_program("luarocks")
--- Display an error message and exit.
-- @param message string: The error message.
-- @param exitcode number: the exitcode to use
local function die(message, exitcode)
assert(type(message) == "string")
local ok, err = pcall(util.run_scheduled_functions)
if not ok then
util.printerr("\nLuaRocks "..cfg.program_version.." internal bug (please report at https://github.com/keplerproject/luarocks/issues):\n"..err)
end
util.printerr("\nError: "..message)
os.exit(exitcode or cfg.errorcodes.UNSPECIFIED)
end
local function replace_tree(flags, args, tree)
tree = dir.normalize(tree)
flags["tree"] = tree
for i = 1, #args do
if args[i]:match("%-%-tree=") then
args[i] = "--tree="..tree
break
end
end
path.use_tree(tree)
end
--- Main command-line processor.
-- Parses input arguments and calls the appropriate driver function
-- to execute the action requested on the command-line, forwarding
-- to it any additional arguments passed by the user.
-- Uses the global table "commands", which contains
-- the loaded modules representing commands.
-- @param ... string: Arguments given on the command-line.
function command_line.run_command(...)
local args = {...}
local cmdline_vars = {}
for i = #args, 1, -1 do
local arg = args[i]
if arg:match("^[^-][^=]*=") then
local var, val = arg:match("^([A-Z_][A-Z0-9_]*)=(.*)")
if val then
cmdline_vars[var] = val
table.remove(args, i)
else
die("Invalid assignment: "..arg)
end
end
end
local nonflags = { util.parse_flags(unpack(args)) }
local flags = table.remove(nonflags, 1)
if flags.ERROR then
die(flags.ERROR.." See --help.")
end
if flags["from"] then flags["server"] = flags["from"] end
if flags["only-from"] then flags["only-server"] = flags["only-from"] end
if flags["only-sources-from"] then flags["only-sources"] = flags["only-sources-from"] end
if flags["to"] then flags["tree"] = flags["to"] end
if flags["nodeps"] then
flags["deps-mode"] = "none"
table.insert(args, "--deps-mode=none")
end
cfg.flags = flags
local command
if flags["verbose"] then -- setting it in the config file will kick-in earlier in the process
cfg.verbose = true
fs.verbose()
end
if flags["timeout"] then -- setting it in the config file will kick-in earlier in the process
local timeout = tonumber(flags["timeout"])
if timeout then
cfg.connection_timeout = timeout
else
die "Argument error: --timeout expects a numeric argument."
end
end
if flags["version"] then
util.printout(program.." "..cfg.program_version)
util.printout(program_description)
util.printout()
os.exit(cfg.errorcodes.OK)
elseif flags["help"] or #nonflags == 0 then
command = "help"
args = nonflags
else
command = nonflags[1]
for i, arg in ipairs(args) do
if arg == command then
table.remove(args, i)
break
end
end
end
command = command:gsub("-", "_")
if cfg.local_by_default then
flags["local"] = true
end
if flags["deps-mode"] and not deps.check_deps_mode_flag(flags["deps-mode"]) then
die("Invalid entry for --deps-mode.")
end
if flags["branch"] then
cfg.branch = flags["branch"]
end
if flags["tree"] then
local named = false
for _, tree in ipairs(cfg.rocks_trees) do
if type(tree) == "table" and flags["tree"] == tree.name then
if not tree.root then
die("Configuration error: tree '"..tree.name.."' has no 'root' field.")
end
replace_tree(flags, args, tree.root)
named = true
break
end
end
if not named then
local fs = require("luarocks.fs")
local root_dir = fs.absolute_name(flags["tree"])
replace_tree(flags, args, root_dir)
end
elseif flags["local"] then
if not cfg.home_tree then
die("The --local flag is meant for operating in a user's home directory.\n"..
"You are running as a superuser, which is intended for system-wide operation.\n"..
"To force using the superuser's home, use --tree explicitly.")
end
replace_tree(flags, args, cfg.home_tree)
else
local trees = cfg.rocks_trees
path.use_tree(trees[#trees])
end
if type(cfg.root_dir) == "string" then
cfg.root_dir = cfg.root_dir:gsub("/+$", "")
else
cfg.root_dir.root = cfg.root_dir.root:gsub("/+$", "")
end
cfg.rocks_dir = cfg.rocks_dir:gsub("/+$", "")
cfg.deploy_bin_dir = cfg.deploy_bin_dir:gsub("/+$", "")
cfg.deploy_lua_dir = cfg.deploy_lua_dir:gsub("/+$", "")
cfg.deploy_lib_dir = cfg.deploy_lib_dir:gsub("/+$", "")
cfg.variables.ROCKS_TREE = cfg.rocks_dir
cfg.variables.SCRIPTS_DIR = cfg.deploy_bin_dir
if flags["server"] then
local protocol, path = dir.split_url(flags["server"])
table.insert(cfg.rocks_servers, 1, protocol.."://"..path)
end
if flags["only-server"] then
cfg.rocks_servers = { flags["only-server"] }
end
if flags["only-sources"] then
cfg.only_sources_from = flags["only-sources"]
end
if command ~= "help" then
for k, v in pairs(cmdline_vars) do
cfg.variables[k] = v
end
end
if not fs.current_dir() or fs.current_dir() == "" then
die("Current directory does not exist. Please run LuaRocks from an existing directory.")
end
if commands[command] then
-- TODO the interface of run should be modified, to receive the
-- flags table and the (possibly unpacked) nonflags arguments.
-- This would remove redundant parsing of arguments.
-- I'm not changing this now to avoid messing with the run()
-- interface, which I know some people use (even though
-- I never published it as a public API...)
local cmd = require(commands[command])
local xp, ok, err, exitcode = xpcall(function() return cmd.run(unpack(args)) end, function(err)
die(debug.traceback("LuaRocks "..cfg.program_version
.." bug (please report at https://github.com/keplerproject/luarocks/issues).\n"
..err, 2), cfg.errorcodes.CRASH)
end)
if xp and (not ok) then
die(err, exitcode)
end
else
die("Unknown command: "..command)
end
util.run_scheduled_functions()
end
return command_line
|
--- Functions for command-line scripts.
--module("luarocks.command_line", package.seeall)
local command_line = {}
local unpack = unpack or table.unpack
local util = require("luarocks.util")
local cfg = require("luarocks.cfg")
local path = require("luarocks.path")
local dir = require("luarocks.dir")
local deps = require("luarocks.deps")
local fs = require("luarocks.fs")
local program = util.this_program("luarocks")
--- Display an error message and exit.
-- @param message string: The error message.
-- @param exitcode number: the exitcode to use
local function die(message, exitcode)
assert(type(message) == "string")
local ok, err = pcall(util.run_scheduled_functions)
if not ok then
util.printerr("\nLuaRocks "..cfg.program_version.." internal bug (please report at https://github.com/keplerproject/luarocks/issues):\n"..err)
end
util.printerr("\nError: "..message)
os.exit(exitcode or cfg.errorcodes.UNSPECIFIED)
end
local function replace_tree(flags, args, tree)
tree = dir.normalize(tree)
flags["tree"] = tree
local added = false
for i = 1, #args do
if args[i]:match("%-%-tree=") then
args[i] = "--tree="..tree
added = true
break
end
end
if not added then
args[#args + 1] = "--tree="..tree
end
path.use_tree(tree)
end
--- Main command-line processor.
-- Parses input arguments and calls the appropriate driver function
-- to execute the action requested on the command-line, forwarding
-- to it any additional arguments passed by the user.
-- Uses the global table "commands", which contains
-- the loaded modules representing commands.
-- @param ... string: Arguments given on the command-line.
function command_line.run_command(...)
local args = {...}
local cmdline_vars = {}
for i = #args, 1, -1 do
local arg = args[i]
if arg:match("^[^-][^=]*=") then
local var, val = arg:match("^([A-Z_][A-Z0-9_]*)=(.*)")
if val then
cmdline_vars[var] = val
table.remove(args, i)
else
die("Invalid assignment: "..arg)
end
end
end
local nonflags = { util.parse_flags(unpack(args)) }
local flags = table.remove(nonflags, 1)
if flags.ERROR then
die(flags.ERROR.." See --help.")
end
if flags["from"] then flags["server"] = flags["from"] end
if flags["only-from"] then flags["only-server"] = flags["only-from"] end
if flags["only-sources-from"] then flags["only-sources"] = flags["only-sources-from"] end
if flags["to"] then flags["tree"] = flags["to"] end
if flags["nodeps"] then
flags["deps-mode"] = "none"
table.insert(args, "--deps-mode=none")
end
cfg.flags = flags
local command
if flags["verbose"] then -- setting it in the config file will kick-in earlier in the process
cfg.verbose = true
fs.verbose()
end
if flags["timeout"] then -- setting it in the config file will kick-in earlier in the process
local timeout = tonumber(flags["timeout"])
if timeout then
cfg.connection_timeout = timeout
else
die "Argument error: --timeout expects a numeric argument."
end
end
if flags["version"] then
util.printout(program.." "..cfg.program_version)
util.printout(program_description)
util.printout()
os.exit(cfg.errorcodes.OK)
elseif flags["help"] or #nonflags == 0 then
command = "help"
args = nonflags
else
command = nonflags[1]
for i, arg in ipairs(args) do
if arg == command then
table.remove(args, i)
break
end
end
end
command = command:gsub("-", "_")
if cfg.local_by_default then
flags["local"] = true
end
if flags["deps-mode"] and not deps.check_deps_mode_flag(flags["deps-mode"]) then
die("Invalid entry for --deps-mode.")
end
if flags["branch"] then
cfg.branch = flags["branch"]
end
if flags["tree"] then
local named = false
for _, tree in ipairs(cfg.rocks_trees) do
if type(tree) == "table" and flags["tree"] == tree.name then
if not tree.root then
die("Configuration error: tree '"..tree.name.."' has no 'root' field.")
end
replace_tree(flags, args, tree.root)
named = true
break
end
end
if not named then
local fs = require("luarocks.fs")
local root_dir = fs.absolute_name(flags["tree"])
replace_tree(flags, args, root_dir)
end
elseif flags["local"] then
if not cfg.home_tree then
die("The --local flag is meant for operating in a user's home directory.\n"..
"You are running as a superuser, which is intended for system-wide operation.\n"..
"To force using the superuser's home, use --tree explicitly.")
end
replace_tree(flags, args, cfg.home_tree)
else
local trees = cfg.rocks_trees
path.use_tree(trees[#trees])
end
if type(cfg.root_dir) == "string" then
cfg.root_dir = cfg.root_dir:gsub("/+$", "")
else
cfg.root_dir.root = cfg.root_dir.root:gsub("/+$", "")
end
cfg.rocks_dir = cfg.rocks_dir:gsub("/+$", "")
cfg.deploy_bin_dir = cfg.deploy_bin_dir:gsub("/+$", "")
cfg.deploy_lua_dir = cfg.deploy_lua_dir:gsub("/+$", "")
cfg.deploy_lib_dir = cfg.deploy_lib_dir:gsub("/+$", "")
cfg.variables.ROCKS_TREE = cfg.rocks_dir
cfg.variables.SCRIPTS_DIR = cfg.deploy_bin_dir
if flags["server"] then
local protocol, path = dir.split_url(flags["server"])
table.insert(cfg.rocks_servers, 1, protocol.."://"..path)
end
if flags["only-server"] then
cfg.rocks_servers = { flags["only-server"] }
end
if flags["only-sources"] then
cfg.only_sources_from = flags["only-sources"]
end
if command ~= "help" then
for k, v in pairs(cmdline_vars) do
cfg.variables[k] = v
end
end
if not fs.current_dir() or fs.current_dir() == "" then
die("Current directory does not exist. Please run LuaRocks from an existing directory.")
end
if commands[command] then
-- TODO the interface of run should be modified, to receive the
-- flags table and the (possibly unpacked) nonflags arguments.
-- This would remove redundant parsing of arguments.
-- I'm not changing this now to avoid messing with the run()
-- interface, which I know some people use (even though
-- I never published it as a public API...)
local cmd = require(commands[command])
local xp, ok, err, exitcode = xpcall(function() return cmd.run(unpack(args)) end, function(err)
die(debug.traceback("LuaRocks "..cfg.program_version
.." bug (please report at https://github.com/keplerproject/luarocks/issues).\n"
..err, 2), cfg.errorcodes.CRASH)
end)
if xp and (not ok) then
die(err, exitcode)
end
else
die("Unknown command: "..command)
end
util.run_scheduled_functions()
end
return command_line
|
Make sure --local always implies --tree=home.
|
Make sure --local always implies --tree=home.
Alternative fix for problem mentioned in #352.
|
Lua
|
mit
|
starius/luarocks,xpol/luainstaller,keplerproject/luarocks,luarocks/luarocks,xpol/luainstaller,xpol/luarocks,starius/luarocks,xpol/luavm,ignacio/luarocks,xpol/luainstaller,tarantool/luarocks,xpol/luavm,starius/luarocks,tarantool/luarocks,xpol/luainstaller,robooo/luarocks,tarantool/luarocks,keplerproject/luarocks,xpol/luavm,xpol/luavm,xpol/luarocks,keplerproject/luarocks,xpol/luarocks,robooo/luarocks,luarocks/luarocks,robooo/luarocks,starius/luarocks,keplerproject/luarocks,luarocks/luarocks,ignacio/luarocks,ignacio/luarocks,xpol/luarocks,ignacio/luarocks,xpol/luavm,robooo/luarocks
|
ccc4b3008eef0708123d56c6c9d118b74ddfac89
|
src/tests/cp/apple/finalcutpro/plugins_spec.lua
|
src/tests/cp/apple/finalcutpro/plugins_spec.lua
|
local require = require
-- local log = require "hs.logger" .new "t_plugins"
-- local inspect = require "hs.inspect"
local spec = require "cp.spec"
local expect = require "cp.spec.expect"
local describe, it = spec.describe, spec.it
local config = require "cp.config"
local plugins = require "cp.apple.finalcutpro.plugins"
local localeID = require "cp.i18n.localeID"
local v = require "semver"
local PLUGINS_PATH = config.testsPath .. "/cp/apple/finalcutpro/_plugins"
local EFFECTS_PATH = PLUGINS_PATH .. "/Effects.localized"
-- mock cp.apple.finalcutpro app.
local app = {
version = function() return v("10.4") end,
getPath = function() return "/Applications/Final Cut Pro.app" end
}
return describe "cp.apple.finalcutpro.plugins" {
it "gets a Motion theme"
:doing(function()
local testEffect = EFFECTS_PATH .. "/Test/Test Effect/Test Effect.moef"
expect(plugins._getMotionTheme(testEffect)):is(nil)
local themedTestEffect = EFFECTS_PATH .. "/Test/Test Theme/Themed Test Effect/Themed Test Effect.moef"
expect(plugins._getMotionTheme(themedTestEffect)):is("Test Theme")
end),
it "scans a theme"
:doing(function()
local testTheme = EFFECTS_PATH .. "/Test/Test Theme"
local scanner = plugins.new(app)
local plugin = {
type = "Effect",
extension = "moef",
check = function() return true end,
}
scanner:scanPluginThemeDirectory(localeID("en"), testTheme, plugin)
local p = {en = {Effect = {
{
path = testTheme .. "/Themed Test Effect",
type = "Effect",
theme = "Test Theme",
name = "Themed Test Effect",
locale = "en",
}
}}}
expect(scanner._plugins):is(p)
end),
it "scans a Category"
:doing(function()
local testCategory = EFFECTS_PATH .. "/Test"
local scanner = plugins.new(app)
local en = localeID("en")
local plugin = {
type = "Effect",
extension = "moef",
check = function() return true end,
}
scanner:scanPluginCategoryDirectory(en, testCategory, plugin)
local p = {en = {Effect = {
{
path = testCategory .. "/Test Effect",
type = "Effect",
theme = nil,
name = "Test Effect",
locale = "en",
},
{
path = testCategory .. "/Test Theme/Themed Test Effect",
type = "Effect",
theme = "Test Theme",
name = "Themed Test Effect",
locale = "en",
},
}}}
expect(scanner._plugins):is(p)
end),
it "Scan Effects"
:doing(function()
local path = EFFECTS_PATH
local scanner = plugins.new(app)
local en = localeID("en")
local plugin = {
type = "Effect",
extension = "moef",
check = function() return true end,
}
scanner:scanPluginTypeDirectory("en", path, plugin)
local p = {en = {Effect = {
{
path = path .. "/Test/Test Effect",
type = "Effect",
category = "Test",
theme = nil,
name = "Test Effect",
locale = "en",
},
{
path = path .. "/Test/Test Theme/Themed Test Effect",
type = "Effect",
category = "Test",
theme = "Test Theme",
name = "Themed Test Effect",
locale = "en",
},
{
path = path .. "/Local.localized/Local Effect.localized",
type = "Effect",
category = "Local EN",
theme = nil,
name = "Local Effect EN",
locale = "en",
},
{
category = "Local EN",
locale = "en",
name = "Versioned Effect EN",
path = path .. "/Local.localized/Versioned Effect.v2.localized",
type = "Effect"
},
}}}
expect(scanner._plugins):is(p)
end),
}
|
local require = require
-- local log = require "hs.logger" .new "t_plugins"
-- local inspect = require "hs.inspect"
local spec = require "cp.spec"
local expect = require "cp.spec.expect"
local describe, it = spec.describe, spec.it
local config = require "cp.config"
local plugins = require "cp.apple.finalcutpro.plugins"
local localeID = require "cp.i18n.localeID"
local v = require "semver"
local PLUGINS_PATH = config.testsPath .. "/cp/apple/finalcutpro/_plugins"
local EFFECTS_PATH = PLUGINS_PATH .. "/Effects.localized"
-- mock cp.apple.finalcutpro app.
local app = {
version = function() return v("10.4") end,
getPath = function() return "/Applications/Final Cut Pro.app" end
}
return describe "cp.apple.finalcutpro.plugins" {
it "gets a Motion theme"
:doing(function()
local testEffect = EFFECTS_PATH .. "/Test/Test Effect/Test Effect.moef"
expect(plugins._getMotionTheme(testEffect)):is(nil)
local themedTestEffect = EFFECTS_PATH .. "/Test/Test Theme/Themed Test Effect/Themed Test Effect.moef"
expect(plugins._getMotionTheme(themedTestEffect)):is("Test Theme")
end),
it "scans a theme"
:doing(function()
local testTheme = EFFECTS_PATH .. "/Test/Test Theme"
local scanner = plugins.new(app)
local plugin = {
type = "Effect",
extension = "moef",
check = function() return true end,
}
scanner:scanPluginThemeDirectory(localeID("en"), testTheme, plugin)
local p = {en = {Effect = {
{
path = testTheme .. "/Themed Test Effect",
type = "Effect",
theme = "Test Theme",
name = "Themed Test Effect",
locale = "en",
}
}}}
expect(scanner._plugins):is(p)
end),
it "scans a Category"
:doing(function()
local testCategory = EFFECTS_PATH .. "/Test"
local scanner = plugins.new(app)
local en = localeID("en")
local plugin = {
type = "Effect",
extension = "moef",
check = function() return true end,
}
scanner:scanPluginCategoryDirectory(en, testCategory, plugin)
local p = {en = {Effect = {
{
path = testCategory .. "/Test Effect",
type = "Effect",
theme = nil,
name = "Test Effect",
locale = "en",
},
{
path = testCategory .. "/Test Theme/Themed Test Effect",
type = "Effect",
theme = "Test Theme",
name = "Themed Test Effect",
locale = "en",
},
}}}
expect(scanner._plugins):is(p)
end),
it "Scan Effects"
:doing(function()
local path = EFFECTS_PATH
local scanner = plugins.new(app)
local plugin = {
type = "Effect",
extension = "moef",
check = function() return true end,
}
scanner:scanPluginTypeDirectory("en", path, plugin)
local p = {en = {Effect = {
{
path = path .. "/Test/Test Effect",
type = "Effect",
category = "Test",
theme = nil,
name = "Test Effect",
locale = "en",
},
{
path = path .. "/Test/Test Theme/Themed Test Effect",
type = "Effect",
category = "Test",
theme = "Test Theme",
name = "Themed Test Effect",
locale = "en",
},
{
path = path .. "/Local.localized/Local Effect.localized",
type = "Effect",
category = "Local EN",
theme = nil,
name = "Local Effect EN",
locale = "en",
},
{
category = "Local EN",
locale = "en",
name = "Versioned Effect EN",
path = path .. "/Local.localized/Versioned Effect.v2.localized",
type = "Effect"
},
}}}
expect(scanner._plugins):is(p)
end),
}
|
* Fixed stickler issue.
|
* Fixed stickler issue.
|
Lua
|
mit
|
CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks
|
1be06f657e7caaa40ae199e0af671a275b695330
|
src/symbolic.lua
|
src/symbolic.lua
|
local symbolic = {} -- package
--[[
Symbol metatable.
Symbol objects must not have any properties
in order to protect properties from user code.
Instead `properties` tables should be used.
--]]
local Symbol = {}
-- package global private variables
local symbols = {} -- list of symbols
local properties = {} -- symbol -> type
local constraints = {} -- list of constraints of an execution path
local solution = nil -- solution for constraints
-- libraries
local table, string, tostring = table, string, tostring
print = function (...)
io.stdout:write(table.concat({...}, "\t"))
io.stdout:write("\n")
end
-- random int generator
local randomizer = { x = 0, mod = 2^32 }
function randomizer:setseed (x)
self.x = x
for i = 1,10 do self:int() end
end
function randomizer:int (n)
self.x = (self.x * 16654525 + 1013904223) % self.mod
return n and self.x % n or self.x
end
local function issymbol (v)
return getmetatable(v) == Symbol
end
local function gettype (v)
return issymbol(v) and properties[v].t or type(v)
end
local function settype (v, t)
if properties[v].t then
assert(properties[v].t == t)
else
properties[v].t = t
end
end
local function z3code (symbols, constraints)
local lines = {}
table.insert(lines, "from z3 import *")
table.insert(lines, "solver = Solver()")
for i, v in ipairs(symbols) do
if properties[v].t == "number" then
table.insert(lines, string.format("%s = Real('%s')", v, v))
end
-- ignore table here
end
for i, v in ipairs(constraints) do
table.insert(lines, string.format("solver.add(%s)", v))
end
table.insert(lines, "r = solver.check()")
table.insert(lines, "print(r)")
table.insert(lines, "if repr(r) == 'sat':")
table.insert(lines, " m = solver.model()")
table.insert(lines, " for i in range(len(m)):")
table.insert(lines, " print('%s,%s' % (m[i], m[m[i]]))")
table.insert(lines, "")
return table.concat(lines, "\n")
end
local function z3execute (code)
local f = io.open('z.py', 'w')
f:write(code)
f:close()
local p = io.popen('python z.py')
local status = p:read()
if status == 'sat' then
local ret = {}
for line in p:lines() do
table.insert(ret, line)
end
p:close()
return ret
else
p:close()
return nil
end
end
-- package functions
function symbolic.eval (f)
local solution = nil
local seed = nil
print "thinking..."
for k = 1, 1000 do
symbols = {}
constraints = {}
properties = {}
path = {}
randomizer:setseed(k)
local stdout = io.stdout
io.stdout = io.open('/dev/null', 'w')
local r, e = pcall(f)
io.stdout:flush()
io.stdout:close()
io.stdout = stdout
if r then
local code = z3code(symbols, constraints)
local s = z3execute(code)
if s then
solution = {}
seed = k
for i, w in ipairs(s) do
local k, v = w:match("(%w+),(%w+)")
solution[tonumber(k:sub(2))] = tonumber(v)
end
break
end
else
-- For debug
-- print(e)
end
end
if solution then
print "solution found."
for i, sym in ipairs(symbols) do
if properties[sym].t == "table" then
print(string.format("%s : {}", sym))
solution[i] = {}
elseif properties[sym].t == "number" then
print(string.format("%s : %f", sym, solution[i]))
end
end
print "running with stubs..."
_ENV.solution = solution
randomizer:setseed(seed)
symbols = {}
f()
else
print "no solution."
end
end
function symbolic.value ()
return Symbol:new()
end
function symbolic.eq (a, b)
if not issymbol(a) and not issymbol(b) then
return a == b
end
if issymbol(a) and not properties[a].t then settype(a, gettype(b)) end
if issymbol(b) and not properties[b].t then settype(b, gettype(a)) end
local i = randomizer:int(2) + 1
local expr = string.format("%s%s%s",
tostring(a), ({'==', '!='})[i], tostring(b))
table.insert(constraints, expr)
return ({true, false})[i]
end
-- Symbol methods
function Symbol:new ()
local id = #symbols + 1
local v = setmetatable({}, self)
symbols[id] = v
properties[v] = { id = id, t = False }
return v
end
function Symbol:__tostring ()
if solution then
return tostring(solution[properties[self].id])
end
return 'x' .. tostring(properties[self].id)
end
function Symbol.__add (a, b)
local newval = Symbol:new()
if issymbol(a) then settype(a, "number") end
if issymbol(b) then settype(b, "number") end
settype(newval, "number")
local expr = string.format("%s==%s+%s", tostring(newval), tostring(a), tostring(b))
table.insert(constraints, expr)
return newval
end
function Symbol.__index (a, k)
local newval = Symbol:new()
settype(a, "table")
rawset(a, k, newval)
return newval
end
return symbolic
|
local symbolic = {} -- package
--[[
Symbol metatable.
Symbol objects must not have any properties
in order to protect properties from user code.
Instead `properties` tables should be used.
--]]
local Symbol = {}
-- package global private variables
local symbols = {} -- list of symbols
local properties = {} -- symbol -> type
local constraints = {} -- list of constraints of an execution path
local solution = nil -- solution for constraints
-- libraries
local table, string, tostring = table, string, tostring
print = function (...)
io.stdout:write(table.concat({...}, "\t"))
io.stdout:write("\n")
end
-- random int generator
local randomizer = { x = 0, mod = 2^32 }
function randomizer:setseed (x)
self.x = x
for i = 1,10 do self:int() end
end
function randomizer:int (n)
self.x = (self.x * 16654525 + 1013904223) % self.mod
return n and self.x % n or self.x
end
local function issymbol (v)
return getmetatable(v) == Symbol
end
local function gettype (v)
return issymbol(v) and properties[v].t or type(v)
end
local function settype (v, t)
if properties[v].t then
assert(properties[v].t == t)
else
properties[v].t = t
end
end
local function z3code (symbols, constraints)
local lines = {}
table.insert(lines, "from z3 import *")
table.insert(lines, "solver = Solver()")
for i, v in ipairs(symbols) do
if properties[v].t == "number" then
table.insert(lines, string.format("%s = Real('%s')", v, v))
end
-- ignore table here
end
for i, v in ipairs(constraints) do
table.insert(lines, string.format("solver.add(%s)", v))
end
table.insert(lines, "r = solver.check()")
table.insert(lines, "print(r)")
table.insert(lines, "if repr(r) == 'sat':")
table.insert(lines, " m = solver.model()")
table.insert(lines, " for i in range(len(m)):")
table.insert(lines, " print('%s,%s' % (m[i], m[m[i]]))")
table.insert(lines, "")
return table.concat(lines, "\n")
end
local function z3execute (code)
local f = io.open('z.py', 'w')
f:write(code)
f:close()
local p = io.popen('python z.py')
local status = p:read()
if status == 'sat' then
local ret = {}
for line in p:lines() do
table.insert(ret, line)
end
p:close()
return ret
else
p:close()
return nil
end
end
-- package functions
function symbolic.eval (f)
local sol = nil
local seed = nil
print "thinking..."
for k = 1, 1000 do
symbols = {}
constraints = {}
properties = {}
path = {}
randomizer:setseed(k)
local stdout = io.stdout
io.stdout = io.open('/dev/null', 'w')
local r, e = pcall(f)
io.stdout:flush()
io.stdout:close()
io.stdout = stdout
if r then
local code = z3code(symbols, constraints)
local s = z3execute(code)
if s then
sol = {}
seed = k
for i, w in ipairs(s) do
local k, v = w:match("(%w+),(%w+)")
sol[tonumber(k:sub(2))] = tonumber(v)
end
break
end
else
-- For debug
-- print(e)
end
end
if sol then
print "solution found."
for i, sym in ipairs(symbols) do
if properties[sym].t == "table" then
print(string.format("%s : {}", sym))
sol[i] = {}
elseif properties[sym].t == "number" then
print(string.format("%s : %f", sym, sol[i]))
else
sol[i] = nil
end
end
print "running with stubs..."
solution = sol
randomizer:setseed(seed)
symbols = {}
f()
else
print "no solution."
end
end
function symbolic.value ()
return Symbol:new()
end
function symbolic.eq (a, b)
if not issymbol(a) and not issymbol(b) then
return a == b
end
if issymbol(a) and not properties[a].t then settype(a, gettype(b)) end
if issymbol(b) and not properties[b].t then settype(b, gettype(a)) end
local i = randomizer:int(2) + 1
local expr = string.format("%s%s%s",
tostring(a), ({'==', '!='})[i], tostring(b))
table.insert(constraints, expr)
return ({true, false})[i]
end
-- Symbol methods
function Symbol:new ()
local id = #symbols + 1
local v = setmetatable({}, self)
symbols[id] = v
properties[v] = { id = id, t = False }
return v
end
function Symbol:__tostring ()
if solution then
local id = properties[self].id
return tostring(solution[id] or nil)
end
return 'x' .. tostring(properties[self].id)
end
function Symbol.__add (a, b)
local newval = Symbol:new()
if issymbol(a) then settype(a, "number") end
if issymbol(b) then settype(b, "number") end
settype(newval, "number")
local expr = string.format("%s==%s+%s", tostring(newval), tostring(a), tostring(b))
table.insert(constraints, expr)
return newval
end
function Symbol.__index (a, k)
local newval = Symbol:new()
settype(a, "table")
rawset(a, k, newval)
return newval
end
return symbolic
|
fix name bug
|
fix name bug
|
Lua
|
mit
|
kohyatoh/symboliclua,kohyatoh/symboliclua
|
c99928d98d118b881e4bea1c3d4fbbed933aa7ce
|
app/commands/make.lua
|
app/commands/make.lua
|
local log = require('../lib/log')
local config = require('../lib/config')
local uv = require('uv')
local pathJoin = require('luvi').path.join
local db = config.db
local readPackageFs = require('../lib/read-package').readFs
local fs = require('coro-fs')
local git = require('git')
local parseDeps = require('../lib/parse-deps')
local miniz = require('miniz')
local function importGraph(files, root, hash)
local function walk(path, hash)
local raw = assert(db.load(hash))
local kind, data = git.deframe(raw)
data = git.decoders[kind](data)
if kind == "tag" then
return walk(path, data.object)
elseif kind == "tree" then
files["modules/" .. path .. "/"] = ""
for i = 1, #data do
local entry = data[i]
local newPath = #path > 0 and path .. "/" .. entry.name or entry.name
walk(newPath, entry.hash)
end
else
if path == root then path = path .. ".lua" end
files["modules/" .. path] = data
end
end
walk(root, hash)
end
local ignores = {
[".git"] = true,
["modules"] = true,
}
local function importFolder(fs, files, path)
for entry in fs.scandir(path) do
if not ignores[entry.name] then
local newPath = #path > 0 and path .. "/" ..entry.name or entry.name
if entry.type == "directory" then
log("importing directory", newPath)
files[newPath .. "/"] = ""
importFolder(fs, files, newPath)
elseif entry.type == "file" then
log("importing file", newPath)
local data = assert(fs.readFile(newPath))
files[newPath] = data
end
end
end
end
local function makeApp(path)
local meta
meta, path = assert(readPackageFs(path))
local fs = fs.chroot(pathJoin(path, ".."))
if not fs.readFile("main.lua") then
error("Missing main.lua in app: " .. path)
end
meta.dependencies = meta.dependencies or {}
log("processing deps", #meta.dependencies)
local deps = parseDeps(meta.dependencies)
local target = pathJoin(uv.cwd(), meta.target or meta.name:match("[^/]+$"))
if require('ffi').os == "Windows" then
target = target .. ".exe"
end
log("creating binary", target)
local fd = assert(uv.fs_open(target, "w", 511)) -- 0777
-- Copy base binary
local binSize
do
local source = uv.exepath()
local reader = miniz.new_reader(source)
if reader then
-- If contains a zip, find where the zip starts
binSize = reader:get_offset()
else
-- Otherwise just read the file size
binSize = uv.fs_stat(source).size
end
local fd2 = assert(uv.fs_open(source, "r", 384)) -- 0600
log("copying binary prefix", binSize .. " bytes")
uv.fs_sendfile(fd, fd2, 0, binSize)
uv.fs_close(fd2)
end
local files = {}
-- Import all the dependencies.
files["modules/"] = ""
for name, dep in pairs(deps) do
log("installing dep", name .. "@" .. dep.version)
importGraph(files, name, dep.hash)
end
-- import the local files on top
importFolder(fs, files, "")
local keys = {}
for path in pairs(files) do
keys[#keys + 1] = path
end
table.sort(keys)
local writer = miniz.new_writer()
for i = 1, #keys do
local key = keys[i]
local data = files[key]
writer:add(key, data, #data > 0 and 9 or nil)
end
uv.fs_write(fd, writer:finalize(), binSize)
uv.fs_close(fd)
log("done building", target)
end
local cwd = uv.cwd()
if #args > 1 then
for i = 2, #args do
makeApp(pathJoin(cwd, args[i]))
end
else
makeApp(cwd)
end
|
local log = require('../lib/log')
local config = require('../lib/config')
local uv = require('uv')
local pathJoin = require('luvi').path.join
local db = config.db
local readPackageFs = require('../lib/read-package').readFs
local fs = require('coro-fs')
local git = require('git')
local parseDeps = require('../lib/parse-deps')
local miniz = require('miniz')
local function importGraph(files, root, hash)
local function walk(path, hash)
local raw = assert(db.load(hash))
local kind, data = git.deframe(raw)
data = git.decoders[kind](data)
if kind == "tag" then
return walk(path, data.object)
elseif kind == "tree" then
files["modules/" .. path .. "/"] = ""
for i = 1, #data do
local entry = data[i]
local newPath = #path > 0 and path .. "/" .. entry.name or entry.name
walk(newPath, entry.hash)
end
else
if path == root then path = path .. ".lua" end
files["modules/" .. path] = data
end
end
walk(root, hash)
end
local ignores = {
[".git"] = true,
["modules"] = true,
}
local function importFolder(fs, files, path)
for entry in fs.scandir(path) do
if not ignores[entry.name] then
local newPath = #path > 0 and path .. "/" ..entry.name or entry.name
if not entry.type then
-- Windows doesn't seem to get type from libuv at all in scandir.
entry.type = fs.stat(newPath).type
end
if entry.type == "directory" then
log("importing directory", newPath)
files[newPath .. "/"] = ""
importFolder(fs, files, newPath)
elseif entry.type == "file" then
log("importing file", newPath)
local data = assert(fs.readFile(newPath))
files[newPath] = data
end
end
end
end
local function makeApp(path)
local meta
meta, path = assert(readPackageFs(path))
local fs = fs.chroot(pathJoin(path, ".."))
if not fs.readFile("main.lua") then
error("Missing main.lua in app: " .. path)
end
meta.dependencies = meta.dependencies or {}
log("processing deps", #meta.dependencies)
local deps = parseDeps(meta.dependencies)
local target = pathJoin(uv.cwd(), meta.target or meta.name:match("[^/]+$"))
if require('ffi').os == "Windows" then
target = target .. ".exe"
end
log("creating binary", target)
local fd = assert(uv.fs_open(target, "w", 511)) -- 0777
-- Copy base binary
local binSize
do
local source = uv.exepath()
local reader = miniz.new_reader(source)
if reader then
-- If contains a zip, find where the zip starts
binSize = reader:get_offset()
else
-- Otherwise just read the file size
binSize = uv.fs_stat(source).size
end
local fd2 = assert(uv.fs_open(source, "r", 384)) -- 0600
log("copying binary prefix", binSize .. " bytes")
uv.fs_sendfile(fd, fd2, 0, binSize)
uv.fs_close(fd2)
end
local files = {}
-- Import all the dependencies.
files["modules/"] = ""
for name, dep in pairs(deps) do
log("installing dep", name .. "@" .. dep.version)
importGraph(files, name, dep.hash)
end
-- import the local files on top
importFolder(fs, files, "")
local keys = {}
for path in pairs(files) do
keys[#keys + 1] = path
end
table.sort(keys)
local writer = miniz.new_writer()
for i = 1, #keys do
local key = keys[i]
local data = files[key]
writer:add(key, data, #data > 0 and 9 or nil)
end
uv.fs_write(fd, writer:finalize(), binSize)
uv.fs_close(fd)
log("done building", target)
end
local cwd = uv.cwd()
if #args > 1 then
for i = 2, #args do
makeApp(pathJoin(cwd, args[i]))
end
else
makeApp(cwd)
end
|
Fix lit make on windows
|
Fix lit make on windows
|
Lua
|
apache-2.0
|
zhaozg/lit,1yvT0s/lit,kaustavha/lit,lduboeuf/lit,luvit/lit,DBarney/lit,squeek502/lit,kidaa/lit,james2doyle/lit
|
1a965238a27b163ff19e5ed709e65314d6bca44f
|
atoms.lua
|
atoms.lua
|
function list_pop()
local l = redis.call('LRANGE', KEYS[1], 0, -1)
local i = tonumber(ARGV[1]) + 1
local v = table.remove(l, i)
redis.call('DEL', KEYS[1])
redis.call('RPUSH', KEYS[1], unpack(l))
return v
end
function list_insert()
local l = redis.call('LRANGE', KEYS[1], 0, -1)
local i = tonumber(ARGV[1]) + 1
table.insert(l, i, ARGV[2])
redis.call('DEL', KEYS[1])
redis.call('RPUSH', KEYS[1], unpack(l))
end
function list_reverse()
local l = redis.call('LRANGE', KEYS[1], 0, -1)
redis.call('DEL', KEYS[1])
redis.call('LPUSH', KEYS[1], unpack(l))
end
function list_multiply()
local l = redis.call('LRANGE', KEYS[1], 0, -1)
redis.call('DEL', KEYS[1])
if l[1] then
local i = tonumber(ARGV[1])
while i > 0 do
i = i - 1
redis.call('RPUSH', KEYS[1], unpack(l))
end
end
end
function set_intersection_update()
local temp_key = KEYS[1] .. 'set_intersection_update'
redis.call('SADD', temp_key, unpack(ARGV))
redis.call('SINTERSTORE', KEYS[1], KEYS[1], temp_key)
redis.call('DEL', temp_key)
end
function set_difference_update()
local temp_key = KEYS[1] .. 'set_difference_update'
redis.call('SADD', temp_key, unpack(ARGV))
redis.call('SDIFFSTORE', KEYS[1], KEYS[1], temp_key)
redis.call('DEL', temp_key)
end
function set_symmetric_difference()
local action = table.remove(ARGV, 1)
local other_key = ARGV[1]
local temp_key1 = KEYS[1] .. 'set_symmetric_difference_temp1'
local temp_key2 = KEYS[1] .. 'set_symmetric_difference_temp2'
local result = nil
if action == 'create' then
other_key = KEYS[1] .. 'set_symmetric_difference_create'
redis.call('SADD', other_key, unpack(ARGV))
end
redis.call('SDIFFSTORE', temp_key1, KEYS[1], other_key)
redis.call('SDIFFSTORE', temp_key2, other_key, KEYS[1])
if action == 'update' then
redis.call('SUNIONSTORE', KEYS[1], temp_key1, temp_key2)
else
result = redis.call('SUNION', temp_key1, temp_key2)
if action == 'create' then
redis.call('DEL', other_key)
end
end
redis.call('DEL', temp_key1)
redis.call('DEL', temp_key2)
return result
end
|
function list_pop()
local l = redis.call('LRANGE', KEYS[1], 0, -1)
local i = tonumber(ARGV[1]) + 1
local v = table.remove(l, i)
redis.call('DEL', KEYS[1])
redis.call('RPUSH', KEYS[1], unpack(l))
return v
end
function list_insert()
local l = redis.call('LRANGE', KEYS[1], 0, -1)
local i = tonumber(ARGV[1]) + 1
table.insert(l, i, ARGV[2])
redis.call('DEL', KEYS[1])
redis.call('RPUSH', KEYS[1], unpack(l))
end
function list_reverse()
local l = redis.call('LRANGE', KEYS[1], 0, -1)
redis.call('DEL', KEYS[1])
redis.call('LPUSH', KEYS[1], unpack(l))
end
function list_multiply()
local l = redis.call('LRANGE', KEYS[1], 0, -1)
redis.call('DEL', KEYS[1])
if l[1] then
local i = tonumber(ARGV[1])
while i > 0 do
i = i - 1
redis.call('RPUSH', KEYS[1], unpack(l))
end
end
end
function set_intersection_update()
local temp_key = KEYS[1] .. 'set_intersection_update'
redis.call('SADD', temp_key, unpack(ARGV))
redis.call('SINTERSTORE', KEYS[1], KEYS[1], temp_key)
redis.call('DEL', temp_key)
end
function set_difference_update()
local temp_key = KEYS[1] .. 'set_difference_update'
for i, v in pairs(ARGV) do
redis.call('SADD', temp_key, unpack(ARGV[i]))
redis.call('SDIFFSTORE', KEYS[1], KEYS[1], temp_key)
redis.call('DEL', temp_key)
end
end
function set_symmetric_difference()
local action = table.remove(ARGV, 1)
local other_key = ARGV[1]
local temp_key1 = KEYS[1] .. 'set_symmetric_difference_temp1'
local temp_key2 = KEYS[1] .. 'set_symmetric_difference_temp2'
local result = nil
if action == 'create' then
other_key = KEYS[1] .. 'set_symmetric_difference_create'
redis.call('SADD', other_key, unpack(ARGV))
end
redis.call('SDIFFSTORE', temp_key1, KEYS[1], other_key)
redis.call('SDIFFSTORE', temp_key2, other_key, KEYS[1])
if action == 'update' then
redis.call('SUNIONSTORE', KEYS[1], temp_key1, temp_key2)
else
result = redis.call('SUNION', temp_key1, temp_key2)
if action == 'create' then
redis.call('DEL', other_key)
end
end
redis.call('DEL', temp_key1)
redis.call('DEL', temp_key2)
return result
end
|
Fix set_difference_update
|
Fix set_difference_update
|
Lua
|
bsd-2-clause
|
stephenmcd/hot-redis,hwms/hot-redis,jmizgajski/hot-redis
|
ed48242f4f08b7608e3db39f6379f857026054f8
|
premake5.lua
|
premake5.lua
|
include("tools/build")
require("third_party/premake-export-compile-commands/export-compile-commands")
location(build_root)
targetdir(build_bin)
objdir(build_obj)
-- Define an ARCH variable
-- Only use this to enable architecture-specific functionality.
if os.is("linux") then
ARCH = os.outputof("uname -p")
else
ARCH = "unknown"
end
includedirs({
".",
"src",
"third_party",
})
defines({
"_UNICODE",
"UNICODE",
-- TODO(benvanik): find a better place for this stuff.
"GLEW_NO_GLU=1",
})
-- TODO(DrChat): Find a way to disable this on other architectures.
if ARCH ~= "ppc64" then
filter("architecture:x86_64")
vectorextensions("AVX")
filter({})
end
characterset("Unicode")
flags({
--"ExtraWarnings", -- Sets the compiler's maximum warning level.
"FatalWarnings", -- Treat warnings as errors.
})
filter("kind:StaticLib")
defines({
"_LIB",
})
filter("configurations:Checked")
runtime("Debug")
defines({
"DEBUG",
})
runtime("Debug")
filter({"configurations:Checked", "platforms:Windows"})
buildoptions({
"/RTCsu", -- Full Run-Time Checks.
})
filter("configurations:Debug")
runtime("Debug")
defines({
"DEBUG",
"_NO_DEBUG_HEAP=1",
})
runtime("Release")
filter({"configurations:Debug", "platforms:Windows"})
linkoptions({
"/NODEFAULTLIB:MSVCRTD",
})
filter("configurations:Release")
runtime("Release")
defines({
"NDEBUG",
"_NO_DEBUG_HEAP=1",
})
optimize("On")
flags({
"LinkTimeOptimization",
})
runtime("Release")
filter({"configurations:Release", "platforms:Windows"})
linkoptions({
"/NODEFAULTLIB:MSVCRTD",
})
filter("platforms:Linux")
system("linux")
toolset("clang")
buildoptions({
-- "-mlzcnt", -- (don't) Assume lzcnt is supported.
"`pkg-config --cflags gtk+-x11-3.0`",
"-fno-lto", -- Premake doesn't support LTO on clang
})
links({
"pthread",
"dl",
"lz4",
"rt",
})
linkoptions({
"`pkg-config --libs gtk+-3.0`",
})
filter({"platforms:Linux", "kind:*App"})
linkgroups("On")
filter({"platforms:Linux", "toolset:gcc"})
buildoptions({
"-std=c++14",
})
links({
})
if ARCH == "ppc64" then
buildoptions({
"-m32",
"-mpowerpc64"
})
linkoptions({
"-m32",
"-mpowerpc64"
})
end
filter({"platforms:Linux", "toolset:clang"})
buildoptions({
"-std=c++14",
"-stdlib=libstdc++",
})
links({
"c++",
"c++abi"
})
disablewarnings({
"deprecated-register"
})
filter("platforms:Windows")
system("windows")
toolset("msc")
buildoptions({
"/MP", -- Multiprocessor compilation.
"/wd4100", -- Unreferenced parameters are ok.
"/wd4201", -- Nameless struct/unions are ok.
"/wd4512", -- 'assignment operator was implicitly defined as deleted'.
"/wd4127", -- 'conditional expression is constant'.
"/wd4324", -- 'structure was padded due to alignment specifier'.
"/wd4189", -- 'local variable is initialized but not referenced'.
"/utf-8", -- 'build correctly on systems with non-Latin codepages'.
})
flags({
"NoMinimalRebuild", -- Required for /MP above.
})
symbols("On")
defines({
"_CRT_NONSTDC_NO_DEPRECATE",
"_CRT_SECURE_NO_WARNINGS",
"WIN32",
"_WIN64=1",
"_AMD64=1",
})
linkoptions({
"/ignore:4006", -- Ignores complaints about empty obj files.
"/ignore:4221",
})
links({
"ntdll",
"wsock32",
"ws2_32",
"xinput",
"xaudio2",
"glu32",
"opengl32",
"comctl32",
"shcore",
"shlwapi",
})
-- Create scratch/ path and dummy flags file if needed.
if not os.isdir("scratch") then
os.mkdir("scratch")
local flags_file = io.open("scratch/flags.txt", "w")
flags_file:write("# Put flags, one on each line.\n")
flags_file:write("# Launch executables with --flags_file=scratch/flags.txt\n")
flags_file:write("\n")
flags_file:write("--cpu=x64\n")
flags_file:write("#--enable_haswell_instructions=false\n")
flags_file:write("\n")
flags_file:write("--debug\n")
flags_file:write("#--protect_zero=false\n")
flags_file:write("\n")
flags_file:write("#--mute\n")
flags_file:write("\n")
flags_file:write("--fast_stdout\n")
flags_file:write("#--flush_stdout=false\n")
flags_file:write("\n")
flags_file:write("#--vsync=false\n")
flags_file:write("#--gl_debug\n")
flags_file:write("#--gl_debug_output\n")
flags_file:write("#--gl_debug_output_synchronous\n")
flags_file:write("#--trace_gpu_prefix=scratch/gpu/gpu_trace_\n")
flags_file:write("#--trace_gpu_stream\n")
flags_file:write("#--disable_framebuffer_readback\n")
flags_file:write("\n")
flags_file:close()
end
solution("xenia")
uuid("931ef4b0-6170-4f7a-aaf2-0fece7632747")
startproject("xenia-app")
architecture("x86_64")
if os.is("linux") then
platforms({"Linux"})
elseif os.is("windows") then
platforms({"Windows"})
end
configurations({"Checked", "Debug", "Release"})
-- Include third party files first so they don't have to deal with gflags.
include("third_party/capstone.lua")
include("third_party/gflags.lua")
include("third_party/glew.lua")
include("third_party/glslang-spirv.lua")
include("third_party/imgui.lua")
include("third_party/libav.lua")
include("third_party/snappy.lua")
include("third_party/spirv-tools.lua")
include("third_party/vulkan/loader")
include("third_party/xxhash.lua")
include("third_party/yaml-cpp.lua")
include("src/xenia")
include("src/xenia/app")
include("src/xenia/apu")
include("src/xenia/apu/nop")
include("src/xenia/base")
include("src/xenia/cpu")
include("src/xenia/cpu/backend/x64")
include("src/xenia/debug/ui")
include("src/xenia/gpu")
include("src/xenia/gpu/null")
include("src/xenia/gpu/gl4")
include("src/xenia/gpu/vulkan")
include("src/xenia/hid")
include("src/xenia/hid/nop")
include("src/xenia/kernel")
include("src/xenia/ui")
include("src/xenia/ui/gl")
include("src/xenia/ui/spirv")
include("src/xenia/ui/vulkan")
include("src/xenia/vfs")
if os.is("windows") then
include("src/xenia/apu/xaudio2")
include("src/xenia/hid/winkey")
include("src/xenia/hid/xinput")
end
|
include("tools/build")
require("third_party/premake-export-compile-commands/export-compile-commands")
location(build_root)
targetdir(build_bin)
objdir(build_obj)
-- Define an ARCH variable
-- Only use this to enable architecture-specific functionality.
if os.is("linux") then
ARCH = os.outputof("uname -p")
else
ARCH = "unknown"
end
includedirs({
".",
"src",
"third_party",
})
defines({
"_UNICODE",
"UNICODE",
-- TODO(benvanik): find a better place for this stuff.
"GLEW_NO_GLU=1",
})
-- TODO(DrChat): Find a way to disable this on other architectures.
if ARCH ~= "ppc64" then
filter("architecture:x86_64")
vectorextensions("AVX")
filter({})
end
characterset("Unicode")
flags({
--"ExtraWarnings", -- Sets the compiler's maximum warning level.
"FatalWarnings", -- Treat warnings as errors.
})
filter("kind:StaticLib")
defines({
"_LIB",
})
filter("configurations:Checked")
runtime("Debug")
defines({
"DEBUG",
})
runtime("Debug")
filter({"configurations:Checked", "platforms:Windows"})
buildoptions({
"/RTCsu", -- Full Run-Time Checks.
})
filter("configurations:Debug")
runtime("Debug")
defines({
"DEBUG",
"_NO_DEBUG_HEAP=1",
})
runtime("Release")
filter({"configurations:Debug", "platforms:Windows"})
linkoptions({
"/NODEFAULTLIB:MSVCRTD",
})
filter("configurations:Release")
runtime("Release")
defines({
"NDEBUG",
"_NO_DEBUG_HEAP=1",
})
optimize("On")
flags({
"LinkTimeOptimization",
})
runtime("Release")
filter({"configurations:Release", "platforms:Windows"})
linkoptions({
"/NODEFAULTLIB:MSVCRTD",
})
filter("platforms:Linux")
system("linux")
toolset("clang")
buildoptions({
-- "-mlzcnt", -- (don't) Assume lzcnt is supported.
"`pkg-config --cflags gtk+-x11-3.0`",
"-fno-lto", -- Premake doesn't support LTO on clang
})
links({
"pthread",
"dl",
"lz4",
"rt",
})
linkoptions({
"`pkg-config --libs gtk+-3.0`",
})
filter({"platforms:Linux", "kind:*App"})
linkgroups("On")
filter({"platforms:Linux", "language:C++", "toolset:gcc"})
buildoptions({
"-std=c++14",
})
links({
})
filter({"platforms:Linux", "toolset:gcc"})
if ARCH == "ppc64" then
buildoptions({
"-m32",
"-mpowerpc64"
})
linkoptions({
"-m32",
"-mpowerpc64"
})
end
filter({"platforms:Linux", "language:C++", "toolset:clang"})
buildoptions({
"-std=c++14",
"-stdlib=libstdc++",
})
links({
"c++",
"c++abi"
})
disablewarnings({
"deprecated-register"
})
filter("platforms:Windows")
system("windows")
toolset("msc")
buildoptions({
"/MP", -- Multiprocessor compilation.
"/wd4100", -- Unreferenced parameters are ok.
"/wd4201", -- Nameless struct/unions are ok.
"/wd4512", -- 'assignment operator was implicitly defined as deleted'.
"/wd4127", -- 'conditional expression is constant'.
"/wd4324", -- 'structure was padded due to alignment specifier'.
"/wd4189", -- 'local variable is initialized but not referenced'.
"/utf-8", -- 'build correctly on systems with non-Latin codepages'.
})
flags({
"NoMinimalRebuild", -- Required for /MP above.
})
symbols("On")
defines({
"_CRT_NONSTDC_NO_DEPRECATE",
"_CRT_SECURE_NO_WARNINGS",
"WIN32",
"_WIN64=1",
"_AMD64=1",
})
linkoptions({
"/ignore:4006", -- Ignores complaints about empty obj files.
"/ignore:4221",
})
links({
"ntdll",
"wsock32",
"ws2_32",
"xinput",
"xaudio2",
"glu32",
"opengl32",
"comctl32",
"shcore",
"shlwapi",
})
-- Create scratch/ path and dummy flags file if needed.
if not os.isdir("scratch") then
os.mkdir("scratch")
local flags_file = io.open("scratch/flags.txt", "w")
flags_file:write("# Put flags, one on each line.\n")
flags_file:write("# Launch executables with --flags_file=scratch/flags.txt\n")
flags_file:write("\n")
flags_file:write("--cpu=x64\n")
flags_file:write("#--enable_haswell_instructions=false\n")
flags_file:write("\n")
flags_file:write("--debug\n")
flags_file:write("#--protect_zero=false\n")
flags_file:write("\n")
flags_file:write("#--mute\n")
flags_file:write("\n")
flags_file:write("--fast_stdout\n")
flags_file:write("#--flush_stdout=false\n")
flags_file:write("\n")
flags_file:write("#--vsync=false\n")
flags_file:write("#--gl_debug\n")
flags_file:write("#--gl_debug_output\n")
flags_file:write("#--gl_debug_output_synchronous\n")
flags_file:write("#--trace_gpu_prefix=scratch/gpu/gpu_trace_\n")
flags_file:write("#--trace_gpu_stream\n")
flags_file:write("#--disable_framebuffer_readback\n")
flags_file:write("\n")
flags_file:close()
end
solution("xenia")
uuid("931ef4b0-6170-4f7a-aaf2-0fece7632747")
startproject("xenia-app")
architecture("x86_64")
if os.is("linux") then
platforms({"Linux"})
elseif os.is("windows") then
platforms({"Windows"})
end
configurations({"Checked", "Debug", "Release"})
-- Include third party files first so they don't have to deal with gflags.
include("third_party/capstone.lua")
include("third_party/gflags.lua")
include("third_party/glew.lua")
include("third_party/glslang-spirv.lua")
include("third_party/imgui.lua")
include("third_party/libav.lua")
include("third_party/snappy.lua")
include("third_party/spirv-tools.lua")
include("third_party/vulkan/loader")
include("third_party/xxhash.lua")
include("third_party/yaml-cpp.lua")
include("src/xenia")
include("src/xenia/app")
include("src/xenia/apu")
include("src/xenia/apu/nop")
include("src/xenia/base")
include("src/xenia/cpu")
include("src/xenia/cpu/backend/x64")
include("src/xenia/debug/ui")
include("src/xenia/gpu")
include("src/xenia/gpu/null")
include("src/xenia/gpu/gl4")
include("src/xenia/gpu/vulkan")
include("src/xenia/hid")
include("src/xenia/hid/nop")
include("src/xenia/kernel")
include("src/xenia/ui")
include("src/xenia/ui/gl")
include("src/xenia/ui/spirv")
include("src/xenia/ui/vulkan")
include("src/xenia/vfs")
if os.is("windows") then
include("src/xenia/apu/xaudio2")
include("src/xenia/hid/winkey")
include("src/xenia/hid/xinput")
end
|
Fix Travis
|
Fix Travis
|
Lua
|
bsd-3-clause
|
sephiroth99/xenia,sephiroth99/xenia,sephiroth99/xenia
|
924b47dfa0705ce3741bba59cac80ba0a3d491be
|
contrib/package/iwinfo/src/iwinfo.lua
|
contrib/package/iwinfo/src/iwinfo.lua
|
#!/usr/bin/lua
require "iwinfo"
function printf(fmt, ...)
print(string.format(fmt, ...))
end
function s(x)
if x == nil then
return "?"
else
return tostring(x)
end
end
function n(x)
if x == nil then
return 0
else
return tonumber(x)
end
end
function print_info(api, dev)
local iw = iwinfo[api]
printf("%-9s Type: %s ESSID: \"%s\"", dev, api, iw.ssid(dev))
printf(" Access Point: %s", iw.bssid(dev))
printf(" Mode: %s Channel: %d (%.3f GHz)",
iw.mode(dev), iw.channel(dev), n(iw.frequency(dev)) / 1000)
printf(" Tx-Power: %s dBm Link Quality: %s/%s",
s(iw.txpower(dev)), s(iw.quality(dev)), s(iw.quality_max(dev)))
printf(" Signal: %s dBm Noise: %s dBm",
s(iw.signal(dev)), s(iw.noise(dev)))
printf(" Bit Rate: %.1f MBit/s",
n(iw.bitrate(dev)) / 1000)
printf(" Encryption: %s",
iw.encryption(dev).description)
print("")
end
function print_scan(api, dev)
local iw = iwinfo[api]
local sr = iw.scanlist(dev)
local si, se
if sr and #sr > 0 then
for si, se in ipairs(sr) do
printf("Cell %02d - Address: %s", si, se.bssid)
printf(" ESSID: \"%s\"",
s(se.ssid))
printf(" Mode: %s Channel: %d",
s(se.mode), n(se.channel))
printf(" Signal: %s dBm Quality: %d/%d",
s(se.signal), n(se.quality), n(se.quality_max))
printf(" Encryption: %s",
s(se.encryption.description))
print("")
end
else
print("No scan results or scanning not possible")
print("")
end
end
function print_txpwrlist(api, dev)
local iw = iwinfo[api]
local pl = iw.txpwrlist(dev)
local cp = n(iw.txpower(dev))
local pe
if pl and #pl > 0 then
for _, pe in ipairs(pl) do
printf("%s%3d dBm (%4d mW)",
(cp == pe.dbm) and "*" or " ",
pe.dbm, pe.mw)
end
else
print("No TX power information available")
end
print("")
end
function print_freqlist(api, dev)
local iw = iwinfo[api]
local fl = iw.freqlist(dev)
local cc = n(iw.channel(dev))
local fe
if fl and #fl > 0 then
for _, fe in ipairs(fl) do
printf("%s %.3f GHz (Channel %d)",
(cc == fe.channel) and "*" or " ",
n(fe.mhz) / 1000, n(fe.channel))
end
else
print("No frequency information available")
end
print("")
end
function print_assoclist(api, dev)
local iw = iwinfo[api]
local al = iw.assoclist(dev)
local ai, ae
if al and next(al) then
for ai, ae in pairs(al) do
printf("%s %s dBm", ai, s(ae.signal))
end
else
print("No client connected or no information available")
end
print("")
end
if #arg ~= 2 then
print("Usage:")
print(" iwinfo <device> info")
print(" iwinfo <device> scan")
print(" iwinfo <device> txpowerlist")
print(" iwinfo <device> freqlist")
print(" iwinfo <device> assoclist")
os.exit(1)
end
local dev = arg[1]
local api = iwinfo.type(dev)
if not api then
print("No such wireless device: " .. dev)
os.exit(1)
end
if arg[2]:match("^i") then
print_info(api, dev)
elseif arg[2]:match("^s") then
print_scan(api, dev)
elseif arg[2]:match("^t") then
print_txpwrlist(api, dev)
elseif arg[2]:match("^f") then
print_freqlist(api, dev)
elseif arg[2]:match("^a") then
print_assoclist(api, dev)
else
print("Unknown command: " .. arg[2])
end
|
#!/usr/bin/lua
require "iwinfo"
function printf(fmt, ...)
print(string.format(fmt, ...))
end
function s(x)
if x == nil then
return "?"
else
return tostring(x)
end
end
function n(x)
if x == nil then
return 0
else
return tonumber(x)
end
end
function print_info(api, dev)
local iw = iwinfo[api]
local enc = iw.encryption(dev)
printf("%-9s Type: %s ESSID: \"%s\"",
dev, api, s(iw.ssid(dev)))
printf(" Access Point: %s",
s(iw.bssid(dev)))
printf(" Mode: %s Channel: %d (%.3f GHz)",
iw.mode(dev), n(iw.channel(dev)), n(iw.frequency(dev)) / 1000)
printf(" Tx-Power: %s dBm Link Quality: %s/%s",
s(iw.txpower(dev)), s(iw.quality(dev)), s(iw.quality_max(dev)))
printf(" Signal: %s dBm Noise: %s dBm",
s(iw.signal(dev)), s(iw.noise(dev)))
printf(" Bit Rate: %.1f MBit/s",
n(iw.bitrate(dev)) / 1000)
printf(" Encryption: %s",
s(enc and enc.description))
print("")
end
function print_scan(api, dev)
local iw = iwinfo[api]
local sr = iw.scanlist(dev)
local si, se
if sr and #sr > 0 then
for si, se in ipairs(sr) do
printf("Cell %02d - Address: %s", si, se.bssid)
printf(" ESSID: \"%s\"",
s(se.ssid))
printf(" Mode: %s Channel: %d",
s(se.mode), n(se.channel))
printf(" Signal: %s dBm Quality: %d/%d",
s(se.signal), n(se.quality), n(se.quality_max))
printf(" Encryption: %s",
s(se.encryption.description))
print("")
end
else
print("No scan results or scanning not possible")
print("")
end
end
function print_txpwrlist(api, dev)
local iw = iwinfo[api]
local pl = iw.txpwrlist(dev)
local cp = n(iw.txpower(dev))
local pe
if pl and #pl > 0 then
for _, pe in ipairs(pl) do
printf("%s%3d dBm (%4d mW)",
(cp == pe.dbm) and "*" or " ",
n(pe.dbm), n(pe.mw))
end
else
print("No TX power information available")
end
print("")
end
function print_freqlist(api, dev)
local iw = iwinfo[api]
local fl = iw.freqlist(dev)
local cc = n(iw.channel(dev))
local fe
if fl and #fl > 0 then
for _, fe in ipairs(fl) do
printf("%s %.3f GHz (Channel %d)",
(cc == fe.channel) and "*" or " ",
n(fe.mhz) / 1000, n(fe.channel))
end
else
print("No frequency information available")
end
print("")
end
function print_assoclist(api, dev)
local iw = iwinfo[api]
local al = iw.assoclist(dev)
local ai, ae
if al and next(al) then
for ai, ae in pairs(al) do
printf("%s %s dBm", ai, s(ae.signal))
end
else
print("No client connected or no information available")
end
print("")
end
if #arg ~= 2 then
print("Usage:")
print(" iwinfo <device> info")
print(" iwinfo <device> scan")
print(" iwinfo <device> txpowerlist")
print(" iwinfo <device> freqlist")
print(" iwinfo <device> assoclist")
os.exit(1)
end
local dev = arg[1]
local api = iwinfo.type(dev)
if not api then
print("No such wireless device: " .. dev)
os.exit(1)
end
if arg[2]:match("^i") then
print_info(api, dev)
elseif arg[2]:match("^s") then
print_scan(api, dev)
elseif arg[2]:match("^t") then
print_txpwrlist(api, dev)
elseif arg[2]:match("^f") then
print_freqlist(api, dev)
elseif arg[2]:match("^a") then
print_assoclist(api, dev)
else
print("Unknown command: " .. arg[2])
end
|
[libiwinfo] fix crash in iwinfo cli when operating on monitor interfaces
|
[libiwinfo] fix crash in iwinfo cli when operating on monitor interfaces
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@6257 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
|
5f646bbb2a50ab84602360dd907622495aea2d03
|
lua/testdriver.lua
|
lua/testdriver.lua
|
require 'libinjection'
require 'Test.More'
require 'Test.Builder.Tester'
function print_token_string(tok)
local out = ''
if tok.str_open ~= '\0' then
out = out .. tok.str_open
end
out = out .. tok.val
if tok.str_close ~= '\0' then
out = out .. tok.str_close
end
return(out)
end
function print_token(tok)
local out = '\n'
out = out .. tok.type
out = out .. ' '
if tok.type == 's' then
out = out .. print_token_string(tok)
elseif tok.type == 'v' then
if tok.count == 1 then
out = out .. '@'
elseif tok.count == 2 then
out = out .. '@@'
end
out = out .. print_token_string(tok)
else
out = out .. tok.val
end
return out
end
function test_tokens(input)
local out = ''
local sql_state = libinjection.sqli_state()
libinjection.sqli_init(sql_state, input, input:len(),
libinjection.FLAG_QUOTE_NONE + libinjection.FLAG_SQL_ANSI)
while (libinjection.sqli_tokenize(sql_state) == 1) do
out = out .. print_token(sql_state.current)
end
return(out)
end
function test_tokens_mysql(input)
local out = ''
local sql_state = libinjection.sqli_state()
libinjection.sqli_init(sql_state, input, input:len(),
libinjection.FLAG_QUOTE_NONE + libinjection.FLAG_SQL_MYSQL)
while (libinjection.sqli_tokenize(sql_state) == 1) do
out = out .. print_token(sql_state.current)
end
return(out)
end
function test_folding(input)
local out = ''
local sql_state = libinjection.sqli_state()
libinjection.sqli_init(sql_state, input, input:len(), 0)
libinjection.sqli_fingerprint(sql_state,
libinjection.FLAG_QUOTE_NONE + libinjection.FLAG_SQL_ANSI)
local vec = sql_state.tokenvec
for i = 1, sql_state.fingerprint:len() do
out = out .. print_token(vec[i])
end
-- hack for when there is no output
if out == '' then
out = '\n'
end
return(out)
end
function test_fingerprints(input)
local out = ''
local sql_state = libinjection.sqli_state()
libinjection.sqli_init(sql_state, input, input:len(), 0)
local issqli = libinjection.is_sqli(sql_state)
if issqli == 1 then
out = sql_state.fingerprint
end
return(out)
end
|
require 'libinjection'
require 'Test.More'
require 'Test.Builder.Tester'
function trim(s)
return s:find'^%s*$' and '' or s:match'^%s*(.*%S)'
end
function print_token_string(tok)
local out = ''
if tok.str_open ~= '\0' then
out = out .. tok.str_open
end
out = out .. tok.val
if tok.str_close ~= '\0' then
out = out .. tok.str_close
end
return trim(out)
end
function print_token(tok)
local out = ''
out = out .. tok.type
out = out .. ' '
if tok.type == 's' then
out = out .. print_token_string(tok)
elseif tok.type == 'v' then
if tok.count == 1 then
out = out .. '@'
elseif tok.count == 2 then
out = out .. '@@'
end
out = out .. print_token_string(tok)
else
out = out .. tok.val
end
return '\n' .. trim(out)
end
function test_tokens(input)
local out = ''
local sql_state = libinjection.sqli_state()
libinjection.sqli_init(sql_state, input, input:len(),
libinjection.FLAG_QUOTE_NONE + libinjection.FLAG_SQL_ANSI)
while (libinjection.sqli_tokenize(sql_state) == 1) do
out = out .. print_token(sql_state.current)
end
return out
end
function test_tokens_mysql(input)
local out = ''
local sql_state = libinjection.sqli_state()
libinjection.sqli_init(sql_state, input, input:len(),
libinjection.FLAG_QUOTE_NONE + libinjection.FLAG_SQL_MYSQL)
while (libinjection.sqli_tokenize(sql_state) == 1) do
out = out .. print_token(sql_state.current)
end
return out
end
function test_folding(input)
local out = ''
local sql_state = libinjection.sqli_state()
libinjection.sqli_init(sql_state, input, input:len(), 0)
libinjection.sqli_fingerprint(sql_state,
libinjection.FLAG_QUOTE_NONE + libinjection.FLAG_SQL_ANSI)
local vec = sql_state.tokenvec
for i = 1, sql_state.fingerprint:len() do
out = out .. print_token(vec[i])
end
-- hack for when there is no output
if out == '' then
out = '\n'
end
return out
end
function test_fingerprints(input)
local out = ''
local sql_state = libinjection.sqli_state()
libinjection.sqli_init(sql_state, input, input:len(), 0)
local issqli = libinjection.is_sqli(sql_state)
if issqli == 1 then
out = sql_state.fingerprint
end
return out
end
|
fix testdriver
|
fix testdriver
|
Lua
|
bsd-3-clause
|
ppliu1979/libinjection,fengjian/libinjection,fengjian/libinjection,dijkstracula/libinjection,ppliu1979/libinjection,fengjian/libinjection,fengjian/libinjection,ppliu1979/libinjection,fengjian/libinjection,fengjian/libinjection,dijkstracula/libinjection,ppliu1979/libinjection,fengjian/libinjection,dijkstracula/libinjection,ppliu1979/libinjection,ppliu1979/libinjection,dijkstracula/libinjection,dijkstracula/libinjection,dijkstracula/libinjection
|
78b453d58a92c2ff34a80bf610d2c1c120eedc38
|
languages/unicode.lua
|
languages/unicode.lua
|
local icu = require("justenoughicu")
require("char-def")
local chardata = characters.data
SILE.nodeMakers.base = std.object {
makeToken = function (self)
if #self.contents>0 then
coroutine.yield(SILE.shaper:formNnode(self.contents, self.token, self.options))
SU.debug("tokenizer", "Token: "..self.token)
self.contents = {} ; self.token = "" ; self.lastnode = "nnode"
end
end,
addToken = function (self, char, item)
self.token = self.token .. char
self.contents[#self.contents+1] = item
end,
makeGlue = function (self, item)
if SILE.settings.get("typesetter.obeyspaces") or self.lastnode ~= "glue" then
SU.debug("tokenizer", "Space node")
coroutine.yield(SILE.shaper:makeSpaceNode(self.options, item))
end
self.lastnode = "glue"
end,
makePenalty = function (self, p)
if self.lastnode ~= "penalty" and self.lastnode ~= "glue" then
coroutine.yield( SILE.nodefactory.newPenalty({ penalty = p or 0 }) )
end
self.lastnode = "penalty"
end,
init = function (self)
self.contents = {}
self.token = ""
self.lastnode = false
self.lasttype = false
end,
iterator = function (_, _)
SU.error("Abstract function nodemaker:iterator called", true)
end,
charData = function (_, char)
local cp = SU.codepoint(char)
if not chardata[cp] then return {} end
return chardata[cp]
end,
isPunctuation = function (self, char)
return self.isPunctuationType[self:charData(char).category]
end,
isSpace = function (self, char)
return self.isSpaceType[self:charData(char).linebreak]
end,
isBreaking = function (self, char)
return self.isBreakingType[self:charData(char).linebreak]
end
}
SILE.nodeMakers.unicode = SILE.nodeMakers.base {
isWordType = { cm = true },
isSpaceType = { sp = true },
isBreakingType = { ba = true, zw = true },
isPunctuationType = { po = true },
dealWith = function (self, item)
local char = item.text
local cp = SU.codepoint(char)
local thistype = chardata[cp] and chardata[cp].linebreak
if self:isSpace(item.text) then
self:makeToken()
self:makeGlue(item)
elseif self:isBreaking(item.text) then
self:addToken(char, item)
self:makeToken()
self:makePenalty(0)
elseif self.lasttype and (self.thistype and thistype ~= lasttype and not self.isWordType[thistype]) then
self:makeToken()
self:addToken(char, item)
else
self:letterspace()
self:addToken(char, item)
end
if not self.isWordType[thistype] then lasttype = chardata[cp] and chardata[cp].linebreak end
self.lasttype = thistype
end,
handleInitialGlue = function (self, items)
local i = 1
while i <= #items do
local item = items[i]
if self:isSpace(item.text) then self:makeGlue(item) else break end
i = i + 1
end
return i, items
end,
letterspace = function (self)
if not SILE.settings.get("document.letterspaceglue") then return end
if self.token then self:makeToken() end
if self.lastnode and self.lastnode ~= "glue" then
local w = SILE.settings.get("document.letterspaceglue").width
SU.debug("tokenizer", "Letter space glue: "..w)
coroutine.yield(SILE.nodefactory.newKern({ width = w }))
self.lastnode = "glue"
end
end,
isICUBreakHere = function (_, chunks, item)
return chunks[1] and (item.index >= chunks[1].index)
end,
handleICUBreak = function (self, chunks, item)
-- The ICU library has told us there is a breakpoint at
-- this index. We need to...
local bp = chunks[1]
-- ... remove this breakpoint (and any out of order ones)
-- from the ICU breakpoints array so that chunks[1] is
-- the next index point for comparison against the string...
while chunks[1] and item.index >= chunks[1].index do
table.remove(chunks, 1)
end
-- ...decide which kind of breakpoint we have here and
-- handle it appropriately.
if bp.type == "word" then
self:handleWordBreak(item)
elseif bp.type == "line" then
self:handleLineBreak(item, bp.subtype)
end
return chunks
end,
handleWordBreak = function (self, item)
self:makeToken()
if self:isSpace(item.text) then
-- Spacing word break
self:makeGlue(item)
else -- a word break which isn't a space
self:addToken(item.text, item)
end
end,
handleLineBreak = function (self, item, subtype)
-- Because we are in charge of paragraphing, we
-- will override space-type line breaks, and treat
-- them just as ordinary word spaces.
if self:isSpace(item.text) then
self:handleWordBreak(item)
return
end
-- But explicit line breaks we will turn into
-- soft and hard breaks.
self:makeToken()
self:makePenalty(subtype == "soft" and 0 or -1000)
self:addToken(item.text, item)
end,
iterator = function (self, items)
local fulltext = ""
for i = 1, #items do
fulltext = fulltext .. items[i].text
end
local chunks = { icu.breakpoints(fulltext, self.options.language) }
self:init()
table.remove(chunks, 1)
return coroutine.wrap(function ()
local i
i, self.items = self:handleInitialGlue(items)
for j = i, #items do
self.i = j
self.item = self.items[self.i]
if self:isICUBreakHere(chunks, self.item) then
chunks = self:handleICUBreak(chunks, self.item)
else
self:dealWith(self.item)
end
end
self:makeToken()
end)
end
}
|
local icu = require("justenoughicu")
require("char-def")
local chardata = characters.data
SILE.nodeMakers.base = std.object {
makeToken = function (self)
if #self.contents>0 then
coroutine.yield(SILE.shaper:formNnode(self.contents, self.token, self.options))
SU.debug("tokenizer", "Token: "..self.token)
self.contents = {} ; self.token = "" ; self.lastnode = "nnode"
end
end,
addToken = function (self, char, item)
self.token = self.token .. char
self.contents[#self.contents+1] = item
end,
makeGlue = function (self, item)
if SILE.settings.get("typesetter.obeyspaces") or self.lastnode ~= "glue" then
SU.debug("tokenizer", "Space node")
coroutine.yield(SILE.shaper:makeSpaceNode(self.options, item))
end
self.lastnode = "glue"
self.lasttype = "sp"
end,
makePenalty = function (self, p)
if self.lastnode ~= "penalty" and self.lastnode ~= "glue" then
coroutine.yield( SILE.nodefactory.newPenalty({ penalty = p or 0 }) )
end
self.lastnode = "penalty"
end,
init = function (self)
self.contents = {}
self.token = ""
self.lastnode = false
self.lasttype = false
end,
iterator = function (_, _)
SU.error("Abstract function nodemaker:iterator called", true)
end,
charData = function (_, char)
local cp = SU.codepoint(char)
if not chardata[cp] then return {} end
return chardata[cp]
end,
isPunctuation = function (self, char)
return self.isPunctuationType[self:charData(char).category]
end,
isSpace = function (self, char)
return self.isSpaceType[self:charData(char).linebreak]
end,
isBreaking = function (self, char)
return self.isBreakingType[self:charData(char).linebreak]
end
}
SILE.nodeMakers.unicode = SILE.nodeMakers.base {
isWordType = { cm = true },
isSpaceType = { sp = true },
isBreakingType = { ba = true, zw = true },
isPunctuationType = { po = true },
dealWith = function (self, item)
local char = item.text
local cp = SU.codepoint(char)
local thistype = chardata[cp] and chardata[cp].linebreak
if self:isSpace(item.text) then
self:makeToken()
self:makeGlue(item)
elseif self:isBreaking(item.text) then
self:makeToken()
self:makePenalty(0)
elseif self.lasttype and (thistype and thistype ~= self.lasttype and not self.isWordType[thistype]) then
self:addToken(char, item)
else
self:letterspace()
self:addToken(char, item)
end
if not self.isWordType[thistype] then self.lasttype = chardata[cp] and chardata[cp].linebreak end
self.lasttype = thistype
end,
handleInitialGlue = function (self, items)
local i = 1
while i <= #items do
local item = items[i]
if self:isSpace(item.text) then self:makeGlue(item) else break end
i = i + 1
end
return i, items
end,
letterspace = function (self)
if not SILE.settings.get("document.letterspaceglue") then return end
if self.token then self:makeToken() end
if self.lastnode and self.lastnode ~= "glue" then
local w = SILE.settings.get("document.letterspaceglue").width
SU.debug("tokenizer", "Letter space glue: "..w)
coroutine.yield(SILE.nodefactory.newKern({ width = w }))
self.lastnode = "glue"
self.lasttype = "sp"
end
end,
isICUBreakHere = function (_, chunks, item)
return chunks[1] and (item.index >= chunks[1].index)
end,
handleICUBreak = function (self, chunks, item)
-- The ICU library has told us there is a breakpoint at
-- this index. We need to...
local bp = chunks[1]
-- ... remove this breakpoint (and any out of order ones)
-- from the ICU breakpoints array so that chunks[1] is
-- the next index point for comparison against the string...
while chunks[1] and item.index >= chunks[1].index do
table.remove(chunks, 1)
end
-- ...decide which kind of breakpoint we have here and
-- handle it appropriately.
if bp.type == "word" then
self:handleWordBreak(item)
elseif bp.type == "line" then
self:handleLineBreak(item, bp.subtype)
end
return chunks
end,
handleWordBreak = function (self, item)
self:makeToken()
if self:isSpace(item.text) then
-- Spacing word break
self:makeGlue(item)
else -- a word break which isn't a space
self:addToken(item.text, item)
end
end,
handleLineBreak = function (self, item, subtype)
-- Because we are in charge of paragraphing, we
-- will override space-type line breaks, and treat
-- them just as ordinary word spaces.
if self:isSpace(item.text) then
self:handleWordBreak(item)
return
end
-- But explicit line breaks we will turn into
-- soft and hard breaks.
self:makeToken()
self:makePenalty(subtype == "soft" and 0 or -1000)
local char = item.text
self:addToken(char, item)
local cp = SU.codepoint(char)
self.lasttype = chardata[cp] and chardata[cp].linebreak
end,
iterator = function (self, items)
local fulltext = ""
for i = 1, #items do
fulltext = fulltext .. items[i].text
end
local chunks = { icu.breakpoints(fulltext, self.options.language) }
self:init()
table.remove(chunks, 1)
return coroutine.wrap(function ()
local i
i, self.items = self:handleInitialGlue(items)
for j = i, #items do
self.i = j
self.item = self.items[self.i]
if self:isICUBreakHere(chunks, self.item) then
chunks = self:handleICUBreak(chunks, self.item)
else
self:dealWith(self.item)
end
end
self:makeToken()
end)
end
}
|
fix(languages): Tidy up variable scope in languages/unicode.lua
|
fix(languages): Tidy up variable scope in languages/unicode.lua
Fixes #699
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
daa5c27ce8aa988436fc81c4e67d59d591cef411
|
model.lua
|
model.lua
|
local _ = require 'moses'
local nn = require 'nn'
require 'modules/GradientRescale'
local image = require 'image'
local model = {}
local cudnn = false -- cuDNN flag
pcall(require, 'cudnn') -- Overwrites flag with cuDNN module if available
local fbcunn = pcall(require, 'fbcunn') -- fbcunn flag (cuDNN is a dependency)
local bestModule = function(mod, ...)
if mod == 'relu' then
if cudnn then
return cudnn.ReLU(...)
else
return nn.ReLU(...)
end
elseif mod == 'conv' then
if fbcunn then
return nn.SpatialConvolutionCuFFT(...)
elseif cudnn then
return cudnn.SpatialConvolution(...)
else
return nn.SpatialConvolution(...)
end
end
end
-- Calculates the output size of a network (returns LongStorage)
local calcOutputSize = function(network, inputSize)
if cudnn then
return network:cuda():forward(torch.CudaTensor(inputSize)):size()
else
return network:forward(torch.Tensor(inputSize)):size()
end
end
-- Processes the full screen for DQN input
model.preprocess = function(observation, opt)
local input = opt.Tensor(observation:size(1), opt.nChannels, opt.height, opt.width)
-- Loop over received frames
for f = 1, observation:size(1) do
-- Load frame
local frame = observation:select(1, f) -- Note: image does not work with CudaTensor
-- Perform colour conversion
if opt.colorSpace ~= 'rgb' then
frame = image['rgb2' .. opt.colorSpace](frame)
end
-- Resize 210x160 screen
input[{{f}, {}, {}, {}}] = image.scale(frame, opt.width, opt.height)
end
return input
end
-- TODO: Work out how to get 4 observations
-- Creates a dueling DQN
model.create = function(A, opt)
-- Number of discrete actions
local m = _.size(A)
-- Network starting with convolutional layers
local net = nn.Sequential()
net:add(bestModule('conv', opt.nChannels, 32, 8, 8, 4, 4))
net:add(bestModule('relu', true))
net:add(bestModule('conv', 32, 64, 4, 4, 2, 2))
net:add(bestModule('relu', true))
net:add(bestModule('conv', 64, 64, 3, 3, 1, 1))
net:add(bestModule('relu', true))
-- Calculate convolutional network output size
local convOutputSize = torch.prod(torch.Tensor(calcOutputSize(net, torch.LongStorage({opt.nChannels, opt.height, opt.width})):totable()))
-- Value approximator V^(s)
local valStream = nn.Sequential()
valStream:add(nn.Linear(convOutputSize, 512))
valStream:add(bestModule('relu', true))
valStream:add(nn.Linear(512, 1)) -- Predicts value for state
-- Advantage approximator A^(s, a)
local advStream = nn.Sequential()
advStream:add(nn.Linear(convOutputSize, 512))
advStream:add(bestModule('relu', true))
advStream:add(nn.Linear(512, m)) -- Predicts action-conditional advantage
-- Streams container
local streams = nn.ConcatTable()
streams:add(valStream)
streams:add(advStream)
-- Aggregator module
local aggregator = nn.Sequential()
local aggParallel = nn.ParallelTable()
-- Value duplicator (for each action)
local valDuplicator = nn.Sequential()
local valConcat = nn.ConcatTable()
for a = 1, m do
valConcat:add(nn.Identity())
end
valDuplicator:add(valConcat)
valDuplicator:add(nn.JoinTable(1, 1))
-- Add value duplicator
aggParallel:add(valDuplicator)
-- Advantage duplicator (for calculating and subtracting mean)
local advDuplicator = nn.Sequential()
local advConcat = nn.ConcatTable()
advConcat:add(nn.Identity())
-- Advantage mean duplicator
local advMeanDuplicator = nn.Sequential()
advMeanDuplicator:add(nn.Mean(1, 1))
local advMeanConcat = nn.ConcatTable()
for a = 1, m do
advMeanConcat:add(nn.Identity())
end
advMeanDuplicator:add(advMeanConcat)
advMeanDuplicator:add(nn.JoinTable(1, 1))
advConcat:add(advMeanDuplicator)
advDuplicator:add(advConcat)
-- Subtract mean from advantage values
advDuplicator:add(nn.CSubTable())
aggParallel:add(advDuplicator)
-- Calculate Q^ from V^ and A^
aggregator:add(aggParallel)
aggregator:add(nn.CAddTable())
-- Network finishing with fully connected layers
net:add(nn.View(convOutputSize))
net:add(nn.GradientRescale(1 / math.sqrt(2))) -- Heuristic that mildly increases stability for duel
-- Create dueling streams
net:add(streams)
-- Join dueling streams
net:add(aggregator)
if opt.gpu > 0 then
require 'cunn'
net:cuda()
end
return net
end
return model
|
local _ = require 'moses'
local nn = require 'nn'
require 'modules/GradientRescale'
local image = require 'image'
local model = {}
pcall(require, 'cudnn')
local cudnn = cudnn or false -- cuDNN flag
pcall(require, 'fbcunn')
local fbcunn = nn.SpatialConvolutionCuFFT and true or false -- fbcunn flag (cuDNN is a dependency)
local bestModule = function(mod, ...)
if mod == 'relu' then
if cudnn then
return cudnn.ReLU(...)
else
return nn.ReLU(...)
end
elseif mod == 'conv' then
if fbcunn then
return nn.SpatialConvolutionCuFFT(...)
elseif cudnn then
return cudnn.SpatialConvolution(...)
else
return nn.SpatialConvolution(...)
end
end
end
-- Calculates the output size of a network (returns LongStorage)
local calcOutputSize = function(network, inputSize)
if cudnn then
return network:cuda():forward(torch.CudaTensor(inputSize)):size()
else
return network:forward(torch.Tensor(inputSize)):size()
end
end
-- Processes the full screen for DQN input
model.preprocess = function(observation, opt)
local input = opt.Tensor(observation:size(1), opt.nChannels, opt.height, opt.width)
-- Loop over received frames
for f = 1, observation:size(1) do
-- Load frame
local frame = observation:select(1, f) -- Note: image does not work with CudaTensor
-- Perform colour conversion
if opt.colorSpace ~= 'rgb' then
frame = image['rgb2' .. opt.colorSpace](frame)
end
-- Resize 210x160 screen
input[{{f}, {}, {}, {}}] = image.scale(frame, opt.width, opt.height)
end
return input
end
-- TODO: Work out how to get 4 observations
-- Creates a dueling DQN
model.create = function(A, opt)
-- Number of discrete actions
local m = _.size(A)
-- Network starting with convolutional layers
local net = nn.Sequential()
net:add(bestModule('conv', opt.nChannels, 32, 8, 8, 4, 4))
net:add(bestModule('relu', true))
net:add(bestModule('conv', 32, 64, 4, 4, 2, 2))
net:add(bestModule('relu', true))
net:add(bestModule('conv', 64, 64, 3, 3, 1, 1))
net:add(bestModule('relu', true))
-- Calculate convolutional network output size
local convOutputSize = torch.prod(torch.Tensor(calcOutputSize(net, torch.LongStorage({opt.nChannels, opt.height, opt.width})):totable()))
-- Value approximator V^(s)
local valStream = nn.Sequential()
valStream:add(nn.Linear(convOutputSize, 512))
valStream:add(bestModule('relu', true))
valStream:add(nn.Linear(512, 1)) -- Predicts value for state
-- Advantage approximator A^(s, a)
local advStream = nn.Sequential()
advStream:add(nn.Linear(convOutputSize, 512))
advStream:add(bestModule('relu', true))
advStream:add(nn.Linear(512, m)) -- Predicts action-conditional advantage
-- Streams container
local streams = nn.ConcatTable()
streams:add(valStream)
streams:add(advStream)
-- Aggregator module
local aggregator = nn.Sequential()
local aggParallel = nn.ParallelTable()
-- Value duplicator (for each action)
local valDuplicator = nn.Sequential()
local valConcat = nn.ConcatTable()
for a = 1, m do
valConcat:add(nn.Identity())
end
valDuplicator:add(valConcat)
valDuplicator:add(nn.JoinTable(1, 1))
-- Add value duplicator
aggParallel:add(valDuplicator)
-- Advantage duplicator (for calculating and subtracting mean)
local advDuplicator = nn.Sequential()
local advConcat = nn.ConcatTable()
advConcat:add(nn.Identity())
-- Advantage mean duplicator
local advMeanDuplicator = nn.Sequential()
advMeanDuplicator:add(nn.Mean(1, 1))
local advMeanConcat = nn.ConcatTable()
for a = 1, m do
advMeanConcat:add(nn.Identity())
end
advMeanDuplicator:add(advMeanConcat)
advMeanDuplicator:add(nn.JoinTable(1, 1))
advConcat:add(advMeanDuplicator)
advDuplicator:add(advConcat)
-- Subtract mean from advantage values
advDuplicator:add(nn.CSubTable())
aggParallel:add(advDuplicator)
-- Calculate Q^ from V^ and A^
aggregator:add(aggParallel)
aggregator:add(nn.CAddTable())
-- Network finishing with fully connected layers
net:add(nn.View(convOutputSize))
net:add(nn.GradientRescale(1 / math.sqrt(2))) -- Heuristic that mildly increases stability for duel
-- Create dueling streams
net:add(streams)
-- Join dueling streams
net:add(aggregator)
if opt.gpu > 0 then
require 'cunn'
net:cuda()
end
return net
end
return model
|
Fix cuDNN flag
|
Fix cuDNN flag
|
Lua
|
mit
|
Kaixhin/Atari
|
f51b5b8f8e5bdfb3cb19e05cdb0f595881aef67f
|
src/dns.resolvers.lua
|
src/dns.resolvers.lua
|
local loader = function(loader, ...)
local resolver = require"cqueues.dns.resolver"
local config = require"cqueues.dns.config"
local condition = require"cqueues.condition"
local monotime = require"cqueues".monotime
local random = require"cqueues.dns".random
local errno = require"cqueues.errno"
local ETIMEDOUT = errno.ETIMEDOUT
local function todeadline(timeout)
return (timeout and (monotime() + timeout)) or nil
end -- todeadline
local function totimeout(deadline)
return (deadline and math.max(0, deadline - monotime())) or nil
end -- totimeout
--
-- NOTE: Keep track of an unordered collection of objects, and in
-- particular a count of objects in the collection. If an object is
-- garbage collected automatically decrement the count and signal
-- the condition variable.
--
local alive = {}
function alive.new(condvar)
local self = setmetatable({}, { __index = alive })
self.n = 0
self.table = setmetatable({}, { __mode = "k" })
self.condvar = condvar
self.hooks = {}
self.hookmt = { __gc = function (hook)
self.n = self.n - 1
self.condvar:signal()
if self.leakcb then
pcall(self.leakcb)
end
end }
return self
end -- alive.new
function alive:newhook()
if not self._newhook then
if _G._VERSION == "Lua 5.1" then
-- Lua 5.1 does not support __gc on tables, so we need to use newproxy
self._newhook = function(mt)
local u = newproxy(false)
debug.setmetatable(u, mt)
return u
end
else
self._newhook = function(mt)
return setmetatable({}, mt)
end
end
end
return self._newhook(self.hookmt)
end -- alive:newhook
function alive:add(x)
if not self.table[x] then
local hook = self.hooks[#self.hooks]
if hook then
self.hooks[#self.hooks] = nil
else
hook = self:newhook()
end
self.table[x] = hook
self.n = self.n + 1
end
end -- alive:add
function alive:delete(x)
if self.table[x] then
self.hooks[#self.hooks + 1] = self.table[x]
self.table[x] = nil
self.n = self.n - 1
self.condvar:signal()
end
end -- alive:delete
function alive:check()
local n = 0
for _ in pairs(self.table) do
n = n + 1
end
return assert(n == self.n, "resolver registry corrupt")
end -- alive:check
function alive:onleak(f)
local old = self.onleak
self.leakcb = f
return old
end -- alive:onleak
local pool = {}
local function getby(self, deadline)
local res
while true do
local cache_len = #self.cache
if cache_len > 1 then
res = self.cache[cache_len]
self.cache[cache_len] = nil
if res then
break
else
self.condvar:wait(totimeout(deadline))
if deadline and deadline <= monotime() then
return nil, ETIMEDOUT
end
end
elseif self.alive.n < self.hiwat then
local why
res, why = resolver.new(self.resconf, self.hosts, self.hints)
if not res then
return nil, why
end
break
end
end
self.alive:add(res)
return res
end -- getby
function pool:get(timeout)
return getby(self, todeadline(timeout))
end -- pool:get
function pool:put(res)
self.alive:delete(res)
local cache_len = #self.cache
if cache_len < self.lowat and res:stat().queries < self.querymax then
if not self.lifo and cache_len > 0 then
local i = random(cache_len+1) + 1
self.cache[cache_len+1] = self.cache[i]
self.cache[i] = res
else
self.cache[cache_len+1] = res
end
else
res:close()
end
end -- pool:put
function pool:signal()
self.condvar:signal()
end -- pool:signal
function pool:query(name, type, class, timeout)
local deadline = todeadline(timeout or self.timeout)
local res, why = getby(self, deadline)
if not res then
return nil, why
end
return res:query(name, type, class, totimeout(deadline))
end -- pool:query
function pool:check()
return self.alive:check()
end -- pool:check
function pool:onleak(f)
return self.alive:onleak(f)
end -- pool:onleak
local resolvers = {}
resolvers.lowat = 1
resolvers.hiwat = 32
resolvers.querymax = 2048
resolvers.onleak = nil
resolvers.lifo = false
function resolvers.new(resconf, hosts, hints)
local self = {}
self.resconf = (type(resconf) == "table" and config.new(resconf)) or resconf
self.hosts = hosts
self.hints = hints
self.condvar = condition.new()
self.lowat = resolvers.lowat
self.hiwat = resolvers.hiwat
self.timeout = resolvers.timeout
self.querymax = resolvers.querymax
self.onleak = resolvers.onleak
self.lifo = resolvers.lifo
self.cache = {}
self.alive = alive.new(self.condvar)
return setmetatable(self, { __index = pool })
end -- resolvers.new
function resolvers.stub(cfg)
return resolvers.new(config.stub(cfg))
end -- resolvers.stub
function resolvers.root(cfg)
return resolvers.new(config.root(cfg))
end -- resolvers.root
function resolvers.type(o)
local mt = getmetatable(o)
if mt and mt.__index == pool then
return "dns resolver pool"
end
end -- resolvers.type
resolvers.loader = loader
return resolvers
end
return loader(loader, ...)
|
local loader = function(loader, ...)
local resolver = require"cqueues.dns.resolver"
local config = require"cqueues.dns.config"
local condition = require"cqueues.condition"
local monotime = require"cqueues".monotime
local random = require"cqueues.dns".random
local errno = require"cqueues.errno"
local ETIMEDOUT = errno.ETIMEDOUT
local function todeadline(timeout)
return (timeout and (monotime() + timeout)) or nil
end -- todeadline
local function totimeout(deadline)
return (deadline and math.max(0, deadline - monotime())) or nil
end -- totimeout
--
-- NOTE: Keep track of an unordered collection of objects, and in
-- particular a count of objects in the collection. If an object is
-- garbage collected automatically decrement the count and signal
-- the condition variable.
--
local alive = {}
function alive.new(condvar)
local self = setmetatable({}, { __index = alive })
self.n = 0
self.table = setmetatable({}, { __mode = "k" })
self.condvar = condvar
self.hooks = {}
self.hookmt = { __gc = function (hook)
self.n = self.n - 1
self.condvar:signal()
if self.leakcb then
pcall(self.leakcb)
end
end }
return self
end -- alive.new
function alive:newhook()
if not self._newhook then
if _G._VERSION == "Lua 5.1" then
-- Lua 5.1 does not support __gc on tables, so we need to use newproxy
self._newhook = function(mt)
local u = newproxy(false)
debug.setmetatable(u, mt)
return u
end
else
self._newhook = function(mt)
return setmetatable({}, mt)
end
end
end
return self._newhook(self.hookmt)
end -- alive:newhook
function alive:add(x)
if not self.table[x] then
local hook = self.hooks[#self.hooks]
if hook then
self.hooks[#self.hooks] = nil
else
hook = self:newhook()
end
self.table[x] = hook
self.n = self.n + 1
end
end -- alive:add
function alive:delete(x)
if self.table[x] then
self.hooks[#self.hooks + 1] = self.table[x]
self.table[x] = nil
self.n = self.n - 1
self.condvar:signal()
end
end -- alive:delete
function alive:check()
local n = 0
for _ in pairs(self.table) do
n = n + 1
end
return assert(n == self.n, "resolver registry corrupt")
end -- alive:check
function alive:onleak(f)
local old = self.onleak
self.leakcb = f
return old
end -- alive:onleak
local pool = {}
local function getby(self, deadline)
local res
while true do
local cache_len = #self.cache
if cache_len > 1 then
res = self.cache[cache_len]
self.cache[cache_len] = nil
if res then
break
else
self.condvar:wait(totimeout(deadline))
if deadline and deadline <= monotime() then
return nil, ETIMEDOUT
end
end
elseif self.alive.n < self.hiwat then
local why
res, why = resolver.new(self.resconf, self.hosts, self.hints)
if not res then
return nil, why
end
break
end
end
self.alive:add(res)
return res
end -- getby
function pool:get(timeout)
return getby(self, todeadline(timeout))
end -- pool:get
function pool:put(res)
self.alive:delete(res)
local cache_len = #self.cache
if cache_len < self.lowat and res:stat().queries < self.querymax then
if not self.lifo and cache_len > 0 then
local i = random(cache_len+1) + 1
self.cache[cache_len+1] = self.cache[i]
self.cache[i] = res
else
self.cache[cache_len+1] = res
end
else
res:close()
end
end -- pool:put
function pool:signal()
self.condvar:signal()
end -- pool:signal
function pool:query(name, type, class, timeout)
local deadline = todeadline(timeout or self.timeout)
local res, why = getby(self, deadline)
if not res then
return nil, why
end
local r, y = res:query(name, type, class, totimeout(deadline))
self:put(res)
if not r then
return nil, y
end
return r
end -- pool:query
function pool:check()
return self.alive:check()
end -- pool:check
function pool:onleak(f)
return self.alive:onleak(f)
end -- pool:onleak
local resolvers = {}
resolvers.lowat = 1
resolvers.hiwat = 32
resolvers.querymax = 2048
resolvers.onleak = nil
resolvers.lifo = false
function resolvers.new(resconf, hosts, hints)
local self = {}
self.resconf = (type(resconf) == "table" and config.new(resconf)) or resconf
self.hosts = hosts
self.hints = hints
self.condvar = condition.new()
self.lowat = resolvers.lowat
self.hiwat = resolvers.hiwat
self.timeout = resolvers.timeout
self.querymax = resolvers.querymax
self.onleak = resolvers.onleak
self.lifo = resolvers.lifo
self.cache = {}
self.alive = alive.new(self.condvar)
return setmetatable(self, { __index = pool })
end -- resolvers.new
function resolvers.stub(cfg)
return resolvers.new(config.stub(cfg))
end -- resolvers.stub
function resolvers.root(cfg)
return resolvers.new(config.root(cfg))
end -- resolvers.root
function resolvers.type(o)
local mt = getmetatable(o)
if mt and mt.__index == pool then
return "dns resolver pool"
end
end -- resolvers.type
resolvers.loader = loader
return resolvers
end
return loader(loader, ...)
|
dns.resolvers: Put resolvers back into pool when queried
|
dns.resolvers: Put resolvers back into pool when queried
Fixes stall when garbage collector doesn't get called
Reported by @torhve
|
Lua
|
mit
|
wahern/cqueues,daurnimator/cqueues,daurnimator/cqueues,wahern/cqueues
|
a9f65fda1e6fdf15d8e695308e39859141373503
|
core/src/lua-cjson/xmake.lua
|
core/src/lua-cjson/xmake.lua
|
target("lua-cjson")
set_kind("static")
set_warnings("all")
add_deps("luajit")
if is_plat("windows") then
set_languages("c89")
end
add_files("lua-cjson/*.c|fpconv.c")
-- Use internal strtod() / g_fmt() code for performance and disable multi-thread
add_defines("NDEBUG", "USE_INTERNAL_FPCONV")
if is_plat("windows") then
-- Windows sprintf()/strtod() handle NaN/inf differently. Not supported.
add_defines("DISABLE_INVALID_NUMBERS")
end
|
target("lua-cjson")
set_kind("static")
set_warnings("all")
add_deps("luajit")
if is_plat("windows") then
set_languages("c89")
end
add_files("lua-cjson/*.c|fpconv.c")
-- Use internal strtod() / g_fmt() code for performance and disable multi-thread
add_defines("NDEBUG", "USE_INTERNAL_FPCONV")
if is_plat("windows") then
-- Windows sprintf()/strtod() handle NaN/inf differently. Not supported.
add_defines("DISABLE_INVALID_NUMBERS")
add_defines("strncasecmp=_strnicmp")
end
|
fix strncasecmp for cjson
|
fix strncasecmp for cjson
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
c316675292571cdbab0a71b3823e4e9b274eb3af
|
MMOCoreORB/bin/scripts/mobile/naboo/plodding_falumpaset.lua
|
MMOCoreORB/bin/scripts/mobile/naboo/plodding_falumpaset.lua
|
plodding_falumpaset = Creature:new {
objectName = "@mob/creature_names:domestic_falumpaset",
socialGroup = "self",
pvpFaction = "",
faction = "",
level = 10,
chanceHit = 0.28,
damageMin = 80,
damageMax = 90,
baseXp = 292,
baseHAM = 1200,
baseHAMmax = 1400,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "meat_domesticated",
meatAmount = 230,
hideType = "hide_leathery",
hideAmount = 130,
boneType = "bone_mammal",
boneAmount = 80,
milkType = "milk_domesticated",
milk = 125,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = HERD,
optionsBitmask = 128,
diet = CARNIVORE,
templates = {"object/mobile/falumpaset_hue.iff"},
lootGroups = {},
weapons = {"creature_spit_small_yellow"},
conversationTemplate = "",
attacks = {
{"stunattack","stunChance=50"}
}
}
CreatureTemplates:addCreatureTemplate(plodding_falumpaset, "plodding_falumpaset")
|
plodding_falumpaset = Creature:new {
objectName = "@mob/creature_names:domestic_falumpaset",
socialGroup = "self",
pvpFaction = "",
faction = "",
level = 10,
chanceHit = 0.28,
damageMin = 80,
damageMax = 90,
baseXp = 292,
baseHAM = 1200,
baseHAMmax = 1400,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "meat_domesticated",
meatAmount = 230,
hideType = "hide_leathery",
hideAmount = 130,
boneType = "bone_mammal",
boneAmount = 80,
milkType = "milk_domesticated",
milk = 125,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = HERD,
optionsBitmask = 128,
diet = CARNIVORE,
templates = {"object/mobile/falumpaset_hue.iff"},
controlDeviceTemplate = "object/intangible/pet/falumpaset_hue.iff",
lootGroups = {},
weapons = {"creature_spit_small_yellow"},
conversationTemplate = "",
attacks = {
{"stunattack","stunChance=50"}
}
}
CreatureTemplates:addCreatureTemplate(plodding_falumpaset, "plodding_falumpaset")
|
[Fixed] plodding falumpaset to be tamable
|
[Fixed] plodding falumpaset to be tamable
Change-Id: I2c174093c05cf8be34fd3dc01725a8b0f234c47f
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
|
7c66bfd6172a7c26dcdd479ec21331f265bf0f64
|
src/cosy/email.lua
|
src/cosy/email.lua
|
local loader = require "cosy.loader"
local ssl = require "ssl"
local smtp = loader.hotswap "socket.smtp"
if _G.js then
error "Not available"
end
local Email = {}
-- First case: detection, using blocking sockets
-- Second case: email sending, using non-blocking sockets
local make_socket = {}
function make_socket.sync ()
local socket = loader.hotswap "socket"
local result = socket.tcp ()
result:settimeout (loader.configuration.smtp.timeout._)
result:setoption ("keepalive", true)
result:setoption ("reuseaddr", true)
result:setoption ("tcp-nodelay", true)
return result
end
function make_socket.async ()
local result = loader.socket ()
result:settimeout (loader.configuration.smtp.timeout._)
result:setoption ("keepalive", true)
result:setoption ("reuseaddr", true)
result:setoption ("tcp-nodelay", true)
return result
end
-- http://lua-users.org/wiki/StringRecipes
local email_pattern = "<[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?>"
local tls_alias = {
["TLS v1.2"] = "tlsv1_2",
["TLS v1.1"] = "tlsv1_1",
["TLS v1.0"] = "tlsv1",
["SSL v3" ] = "sslv3",
["SSL v2" ] = "sslv23",
}
-- http://stackoverflow.com/questions/11070623/lua-send-mail-with-gmail-account
local Tcp = {}
local function forward__index (self, key)
return getmetatable (self) [key]
or function (_, ...)
return self.socket [key] (self.socket, ...)
end
end
function Tcp.PLAINTEXT ()
return function (_, make)
return make ()
end
end
local TLS_mt = {
__index = forward__index,
dohandshake = dohandshake,
}
function TLS_mt:connect (host, port)
self.socket = self.make ()
if not self.socket:connect (host, port) then
return false
end
self.socket = ssl.wrap (self.socket, {
mode = "client",
protocol = tls_alias [self.protocol],
})
return self.socket:dohandshake ()
end
function Tcp.TLS (protocol, make)
return function ()
return setmetatable ({
socket = make (),
protocol = protocol,
make = make,
}, TLS_mt)
end
end
local STARTTLS_mt = {
__index = forward__index,
dohandshake = dohandshake,
}
function STARTTLS_mt:connect (host, port)
self.socket = self.make ()
if not self.socket:connect (host, port) then
print "connection failed"
return nil, "connection failed"
end
self.socket:send ("EHLO cosy\r\n")
repeat
local line = self.socket:receive "*l"
until line == nil
self.socket:send "STARTTLS\r\n"
self.socket:receive "*l"
self.socket = ssl.wrap (self.socket, {
mode = "client",
protocol = tls_alias [self.protocol],
})
local result = self.socket:dohandshake ()
self.socket:send ("EHLO cosy\r\n")
return result
end
function Tcp.STARTTLS (protocol, make)
return function ()
return setmetatable ({
socket = make (),
protocol = protocol,
make = make,
}, STARTTLS_mt)
end
end
function Email.discover ()
local logger = loader.logger
local configuration = loader.configuration
local domain = configuration.server.root._
local host = configuration.smtp.host._
local username = configuration.smtp.username._
local password = configuration.smtp.password._
local methods = { configuration.smtp.method._ }
if #methods == 0 then
methods = {
"STARTTLS",
"TLS",
"PLAINTEXT",
}
end
local protocols = { configuration.smtp.protocol._ }
if #protocols == 0 then
protocols = {
"TLS v1.2",
"TLS v1.1",
"TLS v1.0",
"SSL v3",
"SSL v2",
}
end
local ports = { configuration.smtp.port._ }
if #ports == 0 then
ports = {
25,
587,
465
}
end
for _, method in ipairs (methods) do
local protos = (method == "PLAIN") and { "nothing" } or protocols
for _, protocol in ipairs (protos) do
for _, port in ipairs (ports) do
logger.debug {
_ = "smtp:discover",
host = host,
port = port,
method = method,
protocol = protocol,
}
local ok, s = pcall (smtp.open, host, port, Tcp [method] (protocol, make_socket.sync))
if ok then
local ok = pcall (s.auth, s, username, password, s:greet (domain))
if ok then
configuration.smtp.port = port
configuration.smtp.method = method
configuration.smtp.protocol = protocol
return true
else
s:close ()
end
end
end
end
end
end
function Email.send (message)
local i18n = loader.i18n
local configuration = loader.configuration
local locale = message.locale or configuration.locale.default._
message.from .locale = locale
message.to .locale = locale
message.subject.locale = locale
message.body .locale = locale
message.from = i18n (message.from )
message.to = i18n (message.to )
message.subject = i18n (message.subject)
message.body = i18n (message.body )
return smtp.send {
from = message.from:match (email_pattern),
rcpt = message.to :match (email_pattern),
source = smtp.message {
headers = {
from = message.from,
to = message.to,
subject = message.subject,
},
body = message.body
},
user = configuration.smtp.username._,
password = configuration.smtp.password._,
server = configuration.smtp.host._,
port = configuration.smtp.port._,
create = Tcp [configuration.smtp.method._]
(configuration.smtp.protocol._, make_socket.async),
}
end
do
local logger = loader.logger
local configuration = loader.configuration
if not Email.discover () then
logger.warning {
_ = "smtp:not-available",
}
else
logger.info {
_ = "smtp:available",
host = configuration.smtp.host._,
port = configuration.smtp.port._,
method = configuration.smtp.method._,
protocol = configuration.smtp.protocol._,
}
end
end
return Email
|
local loader = require "cosy.loader"
local ssl = require "ssl"
local smtp = loader.hotswap "socket.smtp"
if _G.js then
error "Not available"
end
local Email = {}
-- First case: detection, using blocking sockets
-- Second case: email sending, using non-blocking sockets
local make_socket = {}
function make_socket.sync ()
local socket = loader.hotswap "socket"
local result = socket.tcp ()
result:settimeout (loader.configuration.smtp.timeout._)
result:setoption ("keepalive", true)
result:setoption ("reuseaddr", true)
result:setoption ("tcp-nodelay", true)
return result
end
function make_socket.async ()
local result = loader.socket ()
result:settimeout (loader.configuration.smtp.timeout._)
result:setoption ("keepalive", true)
result:setoption ("reuseaddr", true)
result:setoption ("tcp-nodelay", true)
return result
end
-- http://lua-users.org/wiki/StringRecipes
local email_pattern = "<[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?>"
local tls_alias = {
["TLS v1.2"] = "tlsv1_2",
["TLS v1.1"] = "tlsv1_1",
["TLS v1.0"] = "tlsv1",
["SSL v3" ] = "sslv3",
["SSL v2" ] = "sslv23",
}
-- http://stackoverflow.com/questions/11070623/lua-send-mail-with-gmail-account
local Tcp = {}
local function forward__index (self, key)
return getmetatable (self) [key]
or function (_, ...)
return self.socket [key] (self.socket, ...)
end
end
function Tcp.PLAINTEXT ()
return function (_, make)
return make ()
end
end
local TLS_mt = {
__index = forward__index,
}
function TLS_mt:connect (host, port)
self.socket = self.make ()
if not self.socket:connect (host, port) then
return false
end
self.socket = ssl.wrap (self.socket, {
mode = "client",
protocol = tls_alias [self.protocol],
})
return self.socket:dohandshake ()
end
function Tcp.TLS (protocol, make)
return function ()
return setmetatable ({
socket = make (),
protocol = protocol,
make = make,
}, TLS_mt)
end
end
local STARTTLS_mt = {
__index = forward__index,
}
function STARTTLS_mt:connect (host, port)
self.socket = self.make ()
if not self.socket:connect (host, port) then
print "connection failed"
return nil, "connection failed"
end
self.socket:send ("EHLO cosy\r\n")
repeat
local line = self.socket:receive "*l"
until line == nil
self.socket:send "STARTTLS\r\n"
self.socket:receive "*l"
self.socket = ssl.wrap (self.socket, {
mode = "client",
protocol = tls_alias [self.protocol],
})
local result = self.socket:dohandshake ()
self.socket:send ("EHLO cosy\r\n")
return result
end
function Tcp.STARTTLS (protocol, make)
return function ()
return setmetatable ({
socket = make (),
protocol = protocol,
make = make,
}, STARTTLS_mt)
end
end
function Email.discover ()
local logger = loader.logger
local configuration = loader.configuration
local domain = configuration.server.root._
local host = configuration.smtp.host._
local username = configuration.smtp.username._
local password = configuration.smtp.password._
local methods = { configuration.smtp.method._ }
if #methods == 0 then
methods = {
"STARTTLS",
"TLS",
"PLAINTEXT",
}
end
local protocols = { configuration.smtp.protocol._ }
if #protocols == 0 then
protocols = {
"TLS v1.2",
"TLS v1.1",
"TLS v1.0",
"SSL v3",
"SSL v2",
}
end
local ports = { configuration.smtp.port._ }
if #ports == 0 then
ports = {
25,
587,
465
}
end
for _, method in ipairs (methods) do
local protos = (method == "PLAIN") and { "nothing" } or protocols
for _, protocol in ipairs (protos) do
for _, port in ipairs (ports) do
logger.debug {
_ = "smtp:discover",
host = host,
port = port,
method = method,
protocol = protocol,
}
local ok, s = pcall (smtp.open, host, port, Tcp [method] (protocol, make_socket.sync))
if ok then
local ok = pcall (s.auth, s, username, password, s:greet (domain))
if ok then
configuration.smtp.port = port
configuration.smtp.method = method
configuration.smtp.protocol = protocol
return true
else
s:close ()
end
end
end
end
end
end
function Email.send (message)
local i18n = loader.i18n
local configuration = loader.configuration
local locale = message.locale or configuration.locale.default._
message.from .locale = locale
message.to .locale = locale
message.subject.locale = locale
message.body .locale = locale
message.from = i18n (message.from )
message.to = i18n (message.to )
message.subject = i18n (message.subject)
message.body = i18n (message.body )
return smtp.send {
from = message.from:match (email_pattern),
rcpt = message.to :match (email_pattern),
source = smtp.message {
headers = {
from = message.from,
to = message.to,
subject = message.subject,
},
body = message.body
},
user = configuration.smtp.username._,
password = configuration.smtp.password._,
server = configuration.smtp.host._,
port = configuration.smtp.port._,
create = Tcp [configuration.smtp.method._]
(configuration.smtp.protocol._, make_socket.async),
}
end
do
local logger = loader.logger
local configuration = loader.configuration
if not Email.discover () then
logger.warning {
_ = "smtp:not-available",
}
else
logger.info {
_ = "smtp:available",
host = configuration.smtp.host._,
port = configuration.smtp.port._,
method = configuration.smtp.method._,
protocol = configuration.smtp.protocol._,
}
end
end
return Email
|
Fix warnings.
|
Fix warnings.
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
9ad20f6b44f178dc5696b41012c337c0efe809f2
|
applications/luci-livestats/luasrc/controller/livestats.lua
|
applications/luci-livestats/luasrc/controller/livestats.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: openvpn.lua 3549 2008-10-09 22:24:21Z jow $
]]--
module("luci.controller.livestats", package.seeall)
function index()
require("luci.i18n")
luci.i18n.loadc("livestats")
entry( {"admin", "status", "wifistat"}, template("livestats/wireless"), luci.i18n.translate("livestat_wireless", "Live Wireless Statistics") ).i18n = "livestat"
entry( {"admin", "status", "trafstat"}, template("livestats/traffic"), luci.i18n.translate("livestat_traffic", "Live Traffic Statistics") ).i18n = "livestat"
entry( {"admin", "status", "loadavg"}, template("livestats/loadavg"), luci.i18n.translate("livestat_loadavg", "Live Load Statistics") ).i18n = "livestat"
end
|
--[[
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$
]]--
module("luci.controller.livestats", package.seeall)
function index()
require("luci.i18n")
luci.i18n.loadc("livestats")
entry( {"admin", "status", "wifistat"}, template("livestats/wireless"), luci.i18n.translate("livestat_wireless", "Live Wireless Statistics") ).i18n = "livestat"
entry( {"admin", "status", "trafstat"}, template("livestats/traffic"), luci.i18n.translate("livestat_traffic", "Live Traffic Statistics") ).i18n = "livestat"
entry( {"admin", "status", "loadavg"}, template("livestats/loadavg"), luci.i18n.translate("livestat_loadavg", "Live Load Statistics") ).i18n = "livestat"
end
|
* luci/app/livestats: property fixup
|
* luci/app/livestats: property fixup
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci
|
9e0cc9c7e4470d69ccda156f67940ee479161ffb
|
xmake.lua
|
xmake.lua
|
set_xmakever("2.5.4")
-- project
set_project("hikyuu")
add_rules("mode.debug", "mode.release")
if not is_plat("windows") then
add_rules("mode.coverage", "mode.asan", "mode.msan", "mode.tsan", "mode.lsan")
end
-- version
set_version("1.2.4", {build="%Y%m%d%H%M"})
set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--if is_mode("debug") then
-- set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--else
-- set_configvar("LOG_ACTIVE_LEVEL", 2) -- 激活的日志级别
--end
set_configvar("USE_SPDLOG_LOGGER", 1) -- 是否使用spdlog作为日志输出
set_configvar("USE_SPDLOG_ASYNC_LOGGER", 0) -- 使用异步的spdlog
set_configvar("CHECK_ACCESS_BOUND", 1)
if is_plat("macosx") then
set_configvar("SUPPORT_SERIALIZATION", 0)
else
set_configvar("SUPPORT_SERIALIZATION", is_mode("release") and 1 or 0)
end
set_configvar("SUPPORT_TEXT_ARCHIVE", 0)
set_configvar("SUPPORT_XML_ARCHIVE", 1)
set_configvar("SUPPORT_BINARY_ARCHIVE", 1)
set_configvar("HKU_DISABLE_ASSERT", 0)
-- set warning all as error
if is_plat("windows") then
set_warnings("all", "error")
else
set_warnings("all")
end
-- set language: C99, c++ standard
set_languages("cxx17", "C99")
add_plugindirs("./xmake_plugins")
local hdf5_version = "1.10.4"
local mysql_version = "8.0.21"
if is_plat("windows") then
add_repositories("project-repo hikyuu_extern_libs")
if is_mode("release") then
add_requires("hdf5 " .. hdf5_version)
else
add_requires("hdf5_D " .. hdf5_version)
end
add_requires("mysql " .. mysql_version)
end
add_requires("fmt 8.1.1", {system=false, configs = {header_only = true, vs_runtime = "MD"}})
add_requires("spdlog", {system=false, configs = {header_only = true, fmt_external=true, vs_runtime = "MD"}})
add_requireconfs("spdlog.fmt", {override = true, version = "8.1.1"})
add_requires("flatbuffers", {system=false, configs = {vs_runtime="MD"}})
add_requires("nng", {system=false, configs = {vs_runtime="MD", cxflags="-fPIC"}})
add_requires("nlohmann_json", {system=false})
add_requires("cpp-httplib", {system=false})
add_requires("zlib", {system=false})
if is_plat("linux") and linuxos.name() == "ubuntu" then
add_requires("apt::libhdf5-dev", "apt::libmysqlclient-dev", "apt::libsqlite3-dev")
elseif is_plat("macosx") then
add_requires("brew::hdf5")
else
add_requires("sqlite3", {configs = {shared=true, vs_runtime="MD", cxflags="-fPIC"}})
end
add_defines("SPDLOG_DISABLE_DEFAULT_LOGGER") -- 禁用 spdlog 默认 logger
set_objectdir("$(buildir)/$(mode)/$(plat)/$(arch)/.objs")
set_targetdir("$(buildir)/$(mode)/$(plat)/$(arch)/lib")
add_includedirs("$(env BOOST_ROOT)")
add_linkdirs("$(env BOOST_LIB)")
-- modifed to use boost static library, except boost.python, serialization
--add_defines("BOOST_ALL_DYN_LINK")
add_defines("BOOST_SERIALIZATION_DYN_LINK")
if is_host("linux") then
if is_arch("x86_64") then
add_linkdirs("/usr/lib64")
if os.exists("/usr/lib/x86_64-linux-gnu") then
add_linkdirs("/usr/lib/x86_64-linux-gnu")
end
end
end
-- is release now
if is_mode("release") then
if is_plat("windows") then
--Unix-like systems hidden symbols will cause the link dynamic libraries to failed!
set_symbols("hidden")
end
end
-- for the windows platform (msvc)
if is_plat("windows") then
-- add some defines only for windows
add_defines("NOCRYPT", "NOGDI")
add_cxflags("-EHsc", "/Zc:__cplusplus", "/utf-8")
add_cxflags("-wd4819") --template dll export warning
add_defines("WIN32_LEAN_AND_MEAN")
if is_mode("release") then
add_cxflags("-MD")
elseif is_mode("debug") then
add_cxflags("-Gs", "-RTC1", "/bigobj")
add_cxflags("-MDd")
end
end
if not is_plat("windows") then
-- disable some compiler errors
add_cxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing")
add_cxflags("-ftemplate-depth=1023", "-pthread")
add_shflags("-pthread")
add_ldflags("-pthread")
end
--add_vectorexts("sse", "sse2", "sse3", "ssse3", "mmx", "avx")
add_subdirs("./hikyuu_cpp/hikyuu")
add_subdirs("./hikyuu_pywrap")
add_subdirs("./hikyuu_cpp/unit_test")
add_subdirs("./hikyuu_cpp/demo")
add_subdirs("./hikyuu_cpp/hikyuu_server")
before_install("scripts.before_install")
on_install("scripts.on_install")
before_run("scripts.before_run")
|
set_xmakever("2.5.4")
-- project
set_project("hikyuu")
add_rules("mode.debug", "mode.release")
if not is_plat("windows") then
add_rules("mode.coverage", "mode.asan", "mode.msan", "mode.tsan", "mode.lsan")
end
-- version
set_version("1.2.4", {build="%Y%m%d%H%M"})
set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--if is_mode("debug") then
-- set_configvar("LOG_ACTIVE_LEVEL", 0) -- 激活的日志级别
--else
-- set_configvar("LOG_ACTIVE_LEVEL", 2) -- 激活的日志级别
--end
set_configvar("USE_SPDLOG_LOGGER", 1) -- 是否使用spdlog作为日志输出
set_configvar("USE_SPDLOG_ASYNC_LOGGER", 0) -- 使用异步的spdlog
set_configvar("CHECK_ACCESS_BOUND", 1)
if is_plat("macosx") then
set_configvar("SUPPORT_SERIALIZATION", 0)
else
set_configvar("SUPPORT_SERIALIZATION", is_mode("release") and 1 or 0)
end
set_configvar("SUPPORT_TEXT_ARCHIVE", 0)
set_configvar("SUPPORT_XML_ARCHIVE", 1)
set_configvar("SUPPORT_BINARY_ARCHIVE", 1)
set_configvar("HKU_DISABLE_ASSERT", 0)
-- set warning all as error
if is_plat("windows") then
set_warnings("all", "error")
else
set_warnings("all")
end
-- set language: C99, c++ standard
set_languages("cxx17", "C99")
add_plugindirs("./xmake_plugins")
local hdf5_version = "1.10.4"
local mysql_version = "8.0.21"
if is_plat("windows") then
add_repositories("project-repo hikyuu_extern_libs")
if is_mode("release") then
add_requires("hdf5 " .. hdf5_version)
else
add_requires("hdf5_D " .. hdf5_version)
end
add_requires("mysql " .. mysql_version)
end
add_requires("fmt 8.1.1", {system=false, configs = {header_only = true, vs_runtime = "MD"}})
add_requires("spdlog", {system=false, configs = {header_only = true, fmt_external=true, vs_runtime = "MD"}})
add_requireconfs("spdlog.fmt", {override = true, version = "8.1.1", system=false, configs = {header_only = true, vs_runtime = "MD"}})
add_requires("flatbuffers", {system=false, configs = {vs_runtime="MD"}})
add_requires("nng", {system=false, configs = {vs_runtime="MD", cxflags="-fPIC"}})
add_requires("nlohmann_json", {system=false})
add_requires("cpp-httplib", {system=false})
add_requires("zlib", {system=false})
if is_plat("linux") and linuxos.name() == "ubuntu" then
add_requires("apt::libhdf5-dev", "apt::libmysqlclient-dev", "apt::libsqlite3-dev")
elseif is_plat("macosx") then
add_requires("brew::hdf5")
else
add_requires("sqlite3", {configs = {shared=true, vs_runtime="MD", cxflags="-fPIC"}})
end
add_defines("SPDLOG_DISABLE_DEFAULT_LOGGER") -- 禁用 spdlog 默认 logger
set_objectdir("$(buildir)/$(mode)/$(plat)/$(arch)/.objs")
set_targetdir("$(buildir)/$(mode)/$(plat)/$(arch)/lib")
add_includedirs("$(env BOOST_ROOT)")
add_linkdirs("$(env BOOST_LIB)")
-- modifed to use boost static library, except boost.python, serialization
--add_defines("BOOST_ALL_DYN_LINK")
add_defines("BOOST_SERIALIZATION_DYN_LINK")
if is_host("linux") then
if is_arch("x86_64") then
add_linkdirs("/usr/lib64")
if os.exists("/usr/lib/x86_64-linux-gnu") then
add_linkdirs("/usr/lib/x86_64-linux-gnu")
end
end
end
-- is release now
if is_mode("release") then
if is_plat("windows") then
--Unix-like systems hidden symbols will cause the link dynamic libraries to failed!
set_symbols("hidden")
end
end
-- for the windows platform (msvc)
if is_plat("windows") then
-- add some defines only for windows
add_defines("NOCRYPT", "NOGDI")
add_cxflags("-EHsc", "/Zc:__cplusplus", "/utf-8")
add_cxflags("-wd4819") --template dll export warning
add_defines("WIN32_LEAN_AND_MEAN")
if is_mode("release") then
add_cxflags("-MD")
elseif is_mode("debug") then
add_cxflags("-Gs", "-RTC1", "/bigobj")
add_cxflags("-MDd")
end
end
if not is_plat("windows") then
-- disable some compiler errors
add_cxflags("-Wno-error=deprecated-declarations", "-fno-strict-aliasing")
add_cxflags("-ftemplate-depth=1023", "-pthread")
add_shflags("-pthread")
add_ldflags("-pthread")
end
--add_vectorexts("sse", "sse2", "sse3", "ssse3", "mmx", "avx")
add_subdirs("./hikyuu_cpp/hikyuu")
add_subdirs("./hikyuu_pywrap")
add_subdirs("./hikyuu_cpp/unit_test")
add_subdirs("./hikyuu_cpp/demo")
add_subdirs("./hikyuu_cpp/hikyuu_server")
before_install("scripts.before_install")
on_install("scripts.on_install")
before_run("scripts.before_run")
|
fixed fmt
|
fixed fmt
|
Lua
|
mit
|
fasiondog/hikyuu
|
f2b64fa882580e491025f880f11cf6c1038954ca
|
examples/table_align_fix.lua
|
examples/table_align_fix.lua
|
-- Replaces all "align" attributes with the CSS "text-align" property.
-- This can be used to filter Pandoc HTML output, which uses the
-- (deprecated) "align" attribute on th and td elements.
local gumbo = require "gumbo"
local document = assert(gumbo.parseFile(arg[1] or io.stdin))
local function fixAlignAttr(elements)
for i, element in ipairs(elements) do
local align = element:getAttribute("align")
if align then
if align ~= "left" then -- left is the default for ltr languages
local css = "text-align:" .. align
local style = element:getAttribute("style")
if style then
css = style .. "; " .. css
end
element:setAttribute("style", css)
end
element:removeAttribute("align")
end
end
end
fixAlignAttr(document:getElementsByTagName("td"))
fixAlignAttr(document:getElementsByTagName("th"))
document:serialize(io.stdout)
|
-- Replaces all "align" attributes on td/th elements with a "style"
-- attribute containing the equivalent CSS "text-align" property.
-- This can be used to fix Pandoc HTML output.
local gumbo = require "gumbo"
local Set = require "gumbo.Set"
local document = assert(gumbo.parseFile(arg[1] or io.stdin))
local alignments = Set{"left", "right", "center", "start", "end"}
local function fixAlignAttr(element)
local align = element:getAttribute("align")
if align and alignments[align] then
local style = element:getAttribute("style")
if style then
element:setAttribute("style", style .. "; text-align:" .. align)
else
element:setAttribute("style", "text-align:" .. align)
end
element:removeAttribute("align")
end
end
for node in document.body:walk() do
if node.localName == "td" or node.localName == "th" then
fixAlignAttr(node)
end
end
document:serialize(io.stdout)
|
Clean up table_align_fix example and rewrite to use Node:walk()
|
Clean up table_align_fix example and rewrite to use Node:walk()
|
Lua
|
apache-2.0
|
craigbarnes/lua-gumbo,craigbarnes/lua-gumbo,craigbarnes/lua-gumbo
|
4bffaf0337c87a35bbf8e886cb14ef4c1e6aaa5d
|
plugins/help_plug.lua
|
plugins/help_plug.lua
|
do
function pairsByKeys(t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
-- Returns true if is not empty
local function has_usage_data(dict)
if (dict.usage == nil or dict.usage == '') then
return false
end
return true
end
-- Get commands for that plugin
local function plugin_helpssssssssss(name,number,requester)
local plugin = ""
if number then
local i = 0
for name in pairsByKeys(plugins) do
if plugins[name].hidden then
name = nil
else
i = i + 1
if i == tonumber(number) then
plugin = plugins[name]
end
end
end
else
plugin = plugins[name]
if not plugin then return nil end
end
local text = ""
if (type(plugin.usage) == "table") then
for ku,usage in pairs(plugin.usage) do
if ku == 'user' then -- usage for user
if (type(plugin.usage.user) == "table") then
for k,v in pairs(plugin.usage.user) do
text = text..v..'\n'
end
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage.user..'\n'
end
elseif ku == 'moderator' then -- usage for moderator
if requester == 'moderator' or requester == 'admin' or requester == 'sudo' then
if (type(plugin.usage.moderator) == "table") then
for k,v in pairs(plugin.usage.moderator) do
text = text..v..'\n'
end
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage.moderator..'\n'
end
end
elseif ku == 'admin' then -- usage for admin
if requester == 'admin' or requester == 'sudo' then
if (type(plugin.usage.admin) == "table") then
for k,v in pairs(plugin.usage.admin) do
text = text..v..'\n'
end
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage.admin..'\n'
end
end
elseif ku == 'sudo' then -- usage for sudo
if requester == 'sudo' then
if (type(plugin.usage.sudo) == "table") then
for k,v in pairs(plugin.usage.sudo) do
text = text..v..'\n'
end
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage.sudo..'\n'
end
end
else
text = text..usage..'\n'
end
end
text = text..'=========================\n'
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage..'\n=========================\n'
end
return text
end
-- !helpssssssssss command
local function telegram_helpssssssssss()
local i = 0
local text = "Plugins list:\n\n"
-- Plugins names
for name in pairsByKeys(plugins) do
if plugins[name].hidden then
name = nil
else
i = i + 1
text = text..i..'. '..name..'\n'
end
end
text = text..'\n'..'There are '..i..' plugins helpssssssssss available.'
text = text..'\n'..'Write "!helpssssssssss [plugin name]" or "!helpssssssssss [plugin number]" for more info.'
text = text..'\n'..'Or "!helpssssssssss all" to show all info.'
return text
end
-- !helpssssssssss all command
local function helpssssssssss_all(requester)
local ret = ""
for name in pairsByKeys(plugins) do
if plugins[name].hidden then
name = nil
else
ret = ret .. plugin_helpssssssssss(name, nil, requester)
end
end
return ret
end
local function run(msg, matches)
if is_sudo(msg) then
requester = "sudo"
elseif is_admin(msg) then
requester = "admin"
elseif is_mod(msg) then
requester = "moderator"
else
requester = "user"
end
if matches[1] == "!helpssssssssss" then
return telegram_helpssssssssss()
elseif matches[1] == "!helpssssssssss all" then
return helpssssssssss_all(requester)
else
local text = ""
if tonumber(matches[1]) then
text = plugin_helpssssssssss(nil, matches[1], requester)
else
text = plugin_helpssssssssss(matches[1], nil, requester)
end
if not text then
text = telegram_helpssssssssss()
end
return text
end
end
return {
description = "Help plugin. Get info from other plugins.",
usage = {
"!helps: Show list of plugins.",
"!helps all: Show all commands for every plugin.",
"!helps [plugin name]: Commands for that plugin.",
"!helps [number]: Commands for that plugin. Type !helpssssssssss to get the plugin number."
},
patterns = {
"^!helps$",
"^!helps all",
"^!helps (.+)"
},
run = run
}
end
|
do
function pairsByKeys(t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
-- Returns true if is not empty
local function has_usage_data(dict)
if (dict.usage == nil or dict.usage == '') then
return false
end
return true
end
-- Get commands for that plugin
local function plugin_help(name,number,requester)
local plugin = ""
if number then
local i = 0
for name in pairsByKeys(plugins) do
if plugins[name].hidden then
name = nil
else
i = i + 1
if i == tonumber(number) then
plugin = plugins[name]
end
end
end
else
plugin = plugins[name]
if not plugin then return nil end
end
local text = ""
if (type(plugin.usage) == "table") then
for ku,usage in pairs(plugin.usage) do
if ku == 'user' then -- usage for user
if (type(plugin.usage.user) == "table") then
for k,v in pairs(plugin.usage.user) do
text = text..v..'\n'
end
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage.user..'\n'
end
elseif ku == 'moderator' then -- usage for moderator
if requester == 'moderator' or requester == 'admin' or requester == 'sudo' then
if (type(plugin.usage.moderator) == "table") then
for k,v in pairs(plugin.usage.moderator) do
text = text..v..'\n'
end
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage.moderator..'\n'
end
end
elseif ku == 'admin' then -- usage for admin
if requester == 'admin' or requester == 'sudo' then
if (type(plugin.usage.admin) == "table") then
for k,v in pairs(plugin.usage.admin) do
text = text..v..'\n'
end
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage.admin..'\n'
end
end
elseif ku == 'sudo' then -- usage for sudo
if requester == 'sudo' then
if (type(plugin.usage.sudo) == "table") then
for k,v in pairs(plugin.usage.sudo) do
text = text..v..'\n'
end
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage.sudo..'\n'
end
end
else
text = text..usage..'\n'
end
end
text = text..'=========================\n'
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage..'\n=========================\n'
end
return text
end
-- !help command
local function telegram_help()
local i = 0
local text = "Plugins list:\n\n"
-- Plugins names
for name in pairsByKeys(plugins) do
if plugins[name].hidden then
name = nil
else
i = i + 1
text = text..i..'. '..name..'\n'
end
end
text = text..'\n'..'There are '..i..' plugins help available.'
text = text..'\n'..'Write "!help [plugin name]" or "!help [plugin number]" for more info.'
text = text..'\n'..'Or "!help all" to show all info.'
return text
end
-- !help all command
local function help_all(requester)
local ret = ""
for name in pairsByKeys(plugins) do
if plugins[name].hidden then
name = nil
else
ret = ret .. plugin_help(name, nil, requester)
end
end
return ret
end
local function run(msg, matches)
if is_sudo(msg) then
requester = "sudo"
elseif is_admin(msg) then
requester = "admin"
elseif is_mod(msg) then
requester = "moderator"
else
requester = "user"
end
if matches[1] == "!help" then
return telegram_help()
elseif matches[1] == "!help all" then
return help_all(requester)
else
local text = ""
if tonumber(matches[1]) then
text = plugin_help(nil, matches[1], requester)
else
text = plugin_help(matches[1], nil, requester)
end
if not text then
text = telegram_help()
end
return text
end
end
return {
description = "Help plugin. Get info from other plugins.",
usage = {
"!helps: Show list of plugins.",
"!helps all: Show all commands for every plugin.",
"!helps [plugin name]: Commands for that plugin.",
"!helps [number]: Commands for that plugin. Type !help to get the plugin number."
},
patterns = {
"^!helps$",
"^!helps all",
"^!helps (.+)"
},
run = run
}
end
|
Updated Help_Plug.lua & Fixed bugs
|
Updated Help_Plug.lua & Fixed bugs
|
Lua
|
mit
|
araeisy/araeisy,araeisy/araeisy,araeisy/araeisy,araeisy/araeisy,alomina007/botsgp,MAXrobotTelegram/abbas,WebShark025/NortTM,WebShark025/NortTM,alomina007/botsgp,WebShark025/NortTM,WebShark025/NortTM
|
372493d38cdc4c8a85f21eb311ea08ba717e6603
|
genie/toolchain.lua
|
genie/toolchain.lua
|
--
-- Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
-- License: https://github.com/taylor001/crown/blob/master/LICENSE
--
function toolchain(build_dir, lib_dir)
newoption
{
trigger = "compiler",
value = "COMPILER",
description = "Choose compiler",
allowed =
{
{ "android-arm", "Android - ARM" },
{ "linux-gcc", "Linux (GCC compiler)" }
}
}
if (_ACTION == nil) then return end
location (build_dir .. "projects/" .. _ACTION)
if _ACTION == "clean" then
os.rmdir(BUILD_DIR)
end
if _ACTION == "gmake" then
if nil == _OPTIONS["compiler"] then
print("Choose a compiler!")
os.exit(1)
end
if "linux-gcc" == _OPTIONS["compiler"] then
if not os.is("linux") then print("Action not valid in current OS.") end
if not os.getenv("PHYSX_SDK_LINUX") then
print("Set PHYSX_SDK_LINUX environment variable.")
end
location(build_dir .. "projects/" .. "linux")
end
if "android-arm" == _OPTIONS["compiler"] then
if not os.getenv("ANDROID_NDK_ROOT") then
print("Set ANDROID_NDK_ROOT environment variable.")
end
if not os.getenv("ANDROID_NDK_ARM") then
print("Set ANDROID_NDK_ARM environment variables.")
end
if not os.getenv("PHYSX_SDK_ANDROID") then
print("Set PHYSX_SDK_ANDROID environment variable.")
end
premake.gcc.cc = "$(ANDROID_NDK_ARM)/bin/arm-linux-androideabi-gcc"
premake.gcc.cxx = "$(ANDROID_NDK_ARM)/bin/arm-linux-androideabi-g++"
premake.gcc.ar = "$(ANDROID_NDK_ARM)/bin/arm-linux-androideabi-ar"
location(build_dir .. "projects/" .. "android")
end
end
if _ACTION == "vs2012" or _ACTION == "vs2013" then
if not os.is("windows") then print("Action not valid in current OS.") end
if not os.getenv("PHYSX_SDK_WINDOWS") then
print("Set PHYSX_SDK_WINDOWS environment variable.")
end
if not os.getenv("DXSDK_DIR") then
print("Set DXSDK_DIR environment variable.")
end
location(build_dir .. "projects/" .. "windows")
end
flags {
"StaticRuntime",
"NoPCH",
"NoRTTI",
"NoExceptions",
"NoEditAndContinue",
"Symbols",
}
defines {
"__STDC_FORMAT_MACROS",
"__STDC_CONSTANT_MACROS",
"__STDC_LIMIT_MACROS",
}
configuration { "development or release" }
flags {
"OptimizeSpeed"
}
configuration { "debug", "x32" }
targetsuffix "-debug-32"
configuration { "debug", "x64" }
targetsuffix "-debug-64"
configuration { "development", "x32" }
targetsuffix "-development-32"
configuration { "development", "x64" }
targetsuffix "-development-64"
configuration { "release", "x32" }
targetsuffix "-release-32"
configuration { "release", "x64" }
targetsuffix "-release-64"
configuration { "debug", "native" }
targetsuffix "-debug"
configuration { "development", "native" }
targetsuffix "-development"
configuration { "release", "native" }
targetsuffix "-release"
configuration { "x32", "linux-*" }
targetdir (build_dir .. "linux32" .. "/bin")
objdir (build_dir .. "linux32" .. "/obj")
libdirs {
lib_dir .. "../.build/linux32/bin",
"$(PHYSX_SDK_LINUX)/Lib/linux32"
}
buildoptions {
"-m32",
"-malign-double", -- Required by PhysX
}
configuration { "x64", "linux-*" }
targetdir (build_dir .. "linux64" .. "/bin")
objdir (build_dir .. "linux64" .. "/obj")
libdirs {
lib_dir .. "../.build/linux64/bin",
"$(PHYSX_SDK_LINUX)/Lib/linux64"
}
buildoptions {
"-m64",
}
configuration { "linux-*" }
buildoptions {
"-Wall",
"-Wextra",
"-msse2",
-- "-Werror",
-- "-pedantic",
"-Wno-unknown-pragmas",
"-Wno-unused-local-typedefs",
}
buildoptions_cpp {
"-std=c++03",
}
linkoptions {
"-Wl,-rpath=\\$$ORIGIN",
"-Wl,--no-as-needed",
}
configuration { "android-*" }
flags {
"NoImportLib"
}
includedirs {
"$(ANDROID_NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/4.8/include",
"$(ANDROID_NDK_ROOT)/sources/android/native_app_glue",
}
linkoptions {
"-nostdlib",
"-static-libgcc",
}
links {
"c",
"dl",
"m",
"android",
"log",
"gnustl_static",
"gcc",
}
buildoptions {
"-fPIC",
"-no-canonical-prefixes",
"-Wa,--noexecstack",
"-fstack-protector",
"-ffunction-sections",
"-Wno-psabi", -- note: the mangling of 'va_list' has changed in GCC 4.4.0
"-Wunused-value",
-- "-Wundef", -- note: avoids PhysX warnings
}
buildoptions_cpp {
"-std=c++03",
}
linkoptions {
"-no-canonical-prefixes",
"-Wl,--no-undefined",
"-Wl,-z,noexecstack",
"-Wl,-z,relro",
"-Wl,-z,now",
}
configuration { "android-arm" }
targetdir (build_dir .. "android-arm" .. "/bin")
objdir (build_dir .. "android-arm" .. "/obj")
libdirs {
lib_dir .. "../.build/android-arm/bin",
"$(ANDROID_NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a",
"$(PHYSX_SDK_ANDROID)/Lib/android9_neon",
}
includedirs {
"$(ANDROID_NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include",
}
buildoptions {
"--sysroot=$(ANDROID_NDK_ROOT)/platforms/android-14/arch-arm",
"-mthumb",
"-march=armv7-a",
"-mfloat-abi=softfp",
"-mfpu=neon",
"-Wunused-value",
-- "-Wundef", -- note: avoids PhysX warnings
}
linkoptions {
"--sysroot=$(ANDROID_NDK_ROOT)/platforms/android-14/arch-arm",
"$(ANDROID_NDK_ROOT)/platforms/android-14/arch-arm/usr/lib/crtbegin_so.o",
"$(ANDROID_NDK_ROOT)/platforms/android-14/arch-arm/usr/lib/crtend_so.o",
"-march=armv7-a",
"-Wl,--fix-cortex-a8",
}
configuration { "vs*" }
includedirs { CROWN_DIR .. "engine/core/compat/msvc" }
defines {
"WIN32",
"_WIN32",
"_HAS_EXCEPTIONS=0",
"_HAS_ITERATOR_DEBUGGING=0",
"_SCL_SECURE=0",
"_SECURE_SCL=0",
"_SCL_SECURE_NO_WARNINGS",
"_CRT_SECURE_NO_WARNINGS",
"_CRT_SECURE_NO_DEPRECATE",
"NOMINMAX",
}
buildoptions {
"/Oy-", -- Suppresses creation of frame pointers on the call stack.
"/Ob2", -- The Inline Function Expansion
}
linkoptions {
"/ignore:4199", -- LNK4199: /DELAYLOAD:*.dll ignored; no imports found from *.dll
"/ignore:4221", -- LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library
"/ignore:4099", -- LNK4099: The linker was unable to find your .pdb file.
}
configuration { "x32", "vs*" }
targetdir (build_dir .. "win32" .. "/bin")
objdir (build_dir .. "win32" .. "/obj")
libdirs {
"$(PHYSX_SDK_WINDOWS)/Lib/win32",
"$(DXSDK_DIR)/Lib/x86",
}
configuration { "x64", "vs*" }
targetdir (build_dir .. "win64" .. "/bin")
objdir (build_dir .. "win64" .. "/obj")
libdirs {
"$(PHYSX_SDK_WINDOWS)/Lib/win64",
"$(DXSDK_DIR)/Lib/x64",
}
configuration {} -- reset configuration
end
function strip()
configuration { "android-arm", "release"}
postbuildcommands {
"$(SILENT) echo Stripping symbols",
"$(SILENT) $(ANDROID_NDK_ARM)/bin/arm-linux-androideabi-strip -s \"$(TARGET)\""
}
configuration { "linux-*", "release" }
postbuildcommands {
"$(SILENT) echo Stripping symbols",
"$(SILENT) strip -s \"$(TARGET)\""
}
configuration {} -- reset configuration
end
|
--
-- Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
-- License: https://github.com/taylor001/crown/blob/master/LICENSE
--
function toolchain(build_dir, lib_dir)
newoption
{
trigger = "compiler",
value = "COMPILER",
description = "Choose compiler",
allowed =
{
{ "android-arm", "Android - ARM" },
{ "linux-gcc", "Linux (GCC compiler)" }
}
}
if (_ACTION == nil) then return end
location (build_dir .. "projects/" .. _ACTION)
if _ACTION == "clean" then
os.rmdir(BUILD_DIR)
end
if _ACTION == "gmake" then
if nil == _OPTIONS["compiler"] then
print("Choose a compiler!")
os.exit(1)
end
if "linux-gcc" == _OPTIONS["compiler"] then
if not os.is("linux") then print("Action not valid in current OS.") end
if not os.getenv("PHYSX_SDK_LINUX") then
print("Set PHYSX_SDK_LINUX environment variable.")
end
location(build_dir .. "projects/" .. "linux")
end
if "android-arm" == _OPTIONS["compiler"] then
if not os.getenv("ANDROID_NDK_ROOT") then
print("Set ANDROID_NDK_ROOT environment variable.")
end
if not os.getenv("ANDROID_NDK_ARM") then
print("Set ANDROID_NDK_ARM environment variables.")
end
if not os.getenv("PHYSX_SDK_ANDROID") then
print("Set PHYSX_SDK_ANDROID environment variable.")
end
premake.gcc.cc = "$(ANDROID_NDK_ARM)/bin/arm-linux-androideabi-gcc"
premake.gcc.cxx = "$(ANDROID_NDK_ARM)/bin/arm-linux-androideabi-g++"
premake.gcc.ar = "$(ANDROID_NDK_ARM)/bin/arm-linux-androideabi-ar"
location(build_dir .. "projects/" .. "android")
end
end
if _ACTION == "vs2013" then
if not os.is("windows") then print("Action not valid in current OS.") end
if not os.getenv("PHYSX_SDK_WINDOWS") then
print("Set PHYSX_SDK_WINDOWS environment variable.")
end
if not os.getenv("DXSDK_DIR") then
print("Set DXSDK_DIR environment variable.")
end
location(build_dir .. "projects/" .. _ACTION)
end
flags {
"StaticRuntime",
"NoPCH",
"NoRTTI",
"NoExceptions",
"NoEditAndContinue",
"Symbols",
}
defines {
"__STDC_FORMAT_MACROS",
"__STDC_CONSTANT_MACROS",
"__STDC_LIMIT_MACROS",
}
configuration { "development or release" }
flags {
"OptimizeSpeed"
}
configuration { "debug", "x32" }
targetsuffix "-debug-32"
configuration { "debug", "x64" }
targetsuffix "-debug-64"
configuration { "development", "x32" }
targetsuffix "-development-32"
configuration { "development", "x64" }
targetsuffix "-development-64"
configuration { "release", "x32" }
targetsuffix "-release-32"
configuration { "release", "x64" }
targetsuffix "-release-64"
configuration { "debug", "native" }
targetsuffix "-debug"
configuration { "development", "native" }
targetsuffix "-development"
configuration { "release", "native" }
targetsuffix "-release"
configuration { "x32", "linux-*" }
targetdir (build_dir .. "linux32" .. "/bin")
objdir (build_dir .. "linux32" .. "/obj")
libdirs {
lib_dir .. "../.build/linux32/bin",
"$(PHYSX_SDK_LINUX)/Lib/linux32"
}
buildoptions {
"-m32",
"-malign-double", -- Required by PhysX
}
configuration { "x64", "linux-*" }
targetdir (build_dir .. "linux64" .. "/bin")
objdir (build_dir .. "linux64" .. "/obj")
libdirs {
lib_dir .. "../.build/linux64/bin",
"$(PHYSX_SDK_LINUX)/Lib/linux64"
}
buildoptions {
"-m64",
}
configuration { "linux-*" }
buildoptions {
"-Wall",
"-Wextra",
"-msse2",
-- "-Werror",
-- "-pedantic",
"-Wno-unknown-pragmas",
"-Wno-unused-local-typedefs",
}
buildoptions_cpp {
"-std=c++03",
}
linkoptions {
"-Wl,-rpath=\\$$ORIGIN",
"-Wl,--no-as-needed",
}
configuration { "android-*" }
flags {
"NoImportLib"
}
includedirs {
"$(ANDROID_NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/4.8/include",
"$(ANDROID_NDK_ROOT)/sources/android/native_app_glue",
}
linkoptions {
"-nostdlib",
"-static-libgcc",
}
links {
"c",
"dl",
"m",
"android",
"log",
"gnustl_static",
"gcc",
}
buildoptions {
"-fPIC",
"-no-canonical-prefixes",
"-Wa,--noexecstack",
"-fstack-protector",
"-ffunction-sections",
"-Wno-psabi", -- note: the mangling of 'va_list' has changed in GCC 4.4.0
"-Wunused-value",
-- "-Wundef", -- note: avoids PhysX warnings
}
buildoptions_cpp {
"-std=c++03",
}
linkoptions {
"-no-canonical-prefixes",
"-Wl,--no-undefined",
"-Wl,-z,noexecstack",
"-Wl,-z,relro",
"-Wl,-z,now",
}
configuration { "android-arm" }
targetdir (build_dir .. "android-arm" .. "/bin")
objdir (build_dir .. "android-arm" .. "/obj")
libdirs {
lib_dir .. "../.build/android-arm/bin",
"$(ANDROID_NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a",
"$(PHYSX_SDK_ANDROID)/Lib/android9_neon",
}
includedirs {
"$(ANDROID_NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include",
}
buildoptions {
"--sysroot=$(ANDROID_NDK_ROOT)/platforms/android-14/arch-arm",
"-mthumb",
"-march=armv7-a",
"-mfloat-abi=softfp",
"-mfpu=neon",
"-Wunused-value",
-- "-Wundef", -- note: avoids PhysX warnings
}
linkoptions {
"--sysroot=$(ANDROID_NDK_ROOT)/platforms/android-14/arch-arm",
"$(ANDROID_NDK_ROOT)/platforms/android-14/arch-arm/usr/lib/crtbegin_so.o",
"$(ANDROID_NDK_ROOT)/platforms/android-14/arch-arm/usr/lib/crtend_so.o",
"-march=armv7-a",
"-Wl,--fix-cortex-a8",
}
configuration { "vs*" }
includedirs { CROWN_DIR .. "engine/core/compat/msvc" }
defines {
"WIN32",
"_WIN32",
"_HAS_EXCEPTIONS=0",
"_HAS_ITERATOR_DEBUGGING=0",
"_SCL_SECURE=0",
"_SECURE_SCL=0",
"_SCL_SECURE_NO_WARNINGS",
"_CRT_SECURE_NO_WARNINGS",
"_CRT_SECURE_NO_DEPRECATE",
"NOMINMAX",
}
buildoptions {
"/Oy-", -- Suppresses creation of frame pointers on the call stack.
"/Ob2", -- The Inline Function Expansion
}
linkoptions {
"/ignore:4199", -- LNK4199: /DELAYLOAD:*.dll ignored; no imports found from *.dll
"/ignore:4221", -- LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library
"/ignore:4099", -- LNK4099: The linker was unable to find your .pdb file.
}
configuration { "x32", "vs*" }
targetdir (build_dir .. "win32" .. "/bin")
objdir (build_dir .. "win32" .. "/obj")
libdirs {
"$(PHYSX_SDK_WINDOWS)/Lib/win32",
"$(DXSDK_DIR)/Lib/x86",
}
configuration { "x64", "vs*" }
targetdir (build_dir .. "win64" .. "/bin")
objdir (build_dir .. "win64" .. "/obj")
libdirs {
"$(PHYSX_SDK_WINDOWS)/Lib/win64",
"$(DXSDK_DIR)/Lib/x64",
}
configuration {} -- reset configuration
end
function strip()
configuration { "android-arm", "release"}
postbuildcommands {
"$(SILENT) echo Stripping symbols",
"$(SILENT) $(ANDROID_NDK_ARM)/bin/arm-linux-androideabi-strip -s \"$(TARGET)\""
}
configuration { "linux-*", "release" }
postbuildcommands {
"$(SILENT) echo Stripping symbols",
"$(SILENT) strip -s \"$(TARGET)\""
}
configuration {} -- reset configuration
end
|
Windows fixes
|
Windows fixes
|
Lua
|
mit
|
dbartolini/crown,taylor001/crown,galek/crown,galek/crown,taylor001/crown,mikymod/crown,mikymod/crown,mikymod/crown,mikymod/crown,taylor001/crown,taylor001/crown,galek/crown,dbartolini/crown,galek/crown,dbartolini/crown,dbartolini/crown
|
67000134f00499aa33b78ed07890edcd16e45370
|
build/scripts/module/audio.lua
|
build/scripts/module/audio.lua
|
if (not _OPTIONS["united"]) then
project "NazaraAudio"
end
files
{
"../include/Nazara/Audio/**.hpp",
"../include/Nazara/Audio/**.inl",
"../src/Nazara/Audio/**.hpp",
"../src/Nazara/Audio/**.cpp"
}
if (os.is("windows")) then
excludes { "../src/Nazara/Audio/Posix/*.hpp", "../src/Nazara/Audio/Posix/*.cpp" }
links "sndfile-1"
else
excludes { "../src/Nazara/Audio/Win32/*.hpp", "../src/Nazara/Audio/Win32/*.cpp" }
-- Link posix ?
end
if (_OPTIONS["united"]) then
excludes "../src/Nazara/Audio/Debug/Leaks.cpp"
else
configuration "DebugStatic"
links "NazaraCore-s-d"
configuration "ReleaseStatic"
links "NazaraCore-s"
configuration "DebugDLL"
links "NazaraCore-d"
configuration "ReleaseDLL"
links "NazaraCore"
end
|
if (not _OPTIONS["united"]) then
project "NazaraAudio"
end
defines "NAZARA_AUDIO_OPENAL"
files
{
"../include/Nazara/Audio/**.hpp",
"../include/Nazara/Audio/**.inl",
"../src/Nazara/Audio/**.hpp",
"../src/Nazara/Audio/**.cpp"
}
if (os.is("windows")) then
excludes { "../src/Nazara/Audio/Posix/*.hpp", "../src/Nazara/Audio/Posix/*.cpp" }
links "sndfile-1"
else
excludes { "../src/Nazara/Audio/Win32/*.hpp", "../src/Nazara/Audio/Win32/*.cpp" }
-- Link posix ?
end
if (_OPTIONS["united"]) then
excludes "../src/Nazara/Audio/Debug/Leaks.cpp"
else
configuration "DebugStatic"
links "NazaraCore-s-d"
configuration "ReleaseStatic"
links "NazaraCore-s"
configuration "DebugDLL"
links "NazaraCore-d"
configuration "ReleaseDLL"
links "NazaraCore"
end
|
Fixed audio build script not defining NAZARA_AUDIO_OPENAL
|
Fixed audio build script not defining NAZARA_AUDIO_OPENAL
Former-commit-id: a2fcdc463e47bc1b6d8a0799fb5f667f96e9dd07
|
Lua
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
2517cdd905aeb28a5b8f47d0c014d4337bf39d61
|
UCDchat/rolePlay.lua
|
UCDchat/rolePlay.lua
|
function doChat( plr, _, ... )
local player = plr
if ( antiSpam[ player ] ) then
exports.UCDdx:new( player, "Your last sent message was less than one second ago!", 255, 0, 0 )
return false
end
local msg = table.concat( { ... }, " " )
if msg == "" or msg == " " then return end
if ( not exports.UCDaccounts:isPlayerLoggedIn( plr ) ) then return false end
local pX, pY, pZ = getElementPosition( plr )
local plrNick = getPlayerName( plr )
for _, v in pairs( getElementsByType( "player" ) ) do
if ( exports.UCDmisc:isPlayerInRangeOfPoint( plr, pX, pY, pZ, range ) ) then
if ( getElementDimension( plr ) == ( getElementDimension( v ) ) ) then
if ( getElementInterior( plr ) == ( getElementInterior( v ) ) ) then
outputChatBox( "* "..msg.." ("..plrNick..")", v, 200, 50, 150 )
end
end
end
end
end
addCommandHandler( "do", doChat )
-- /me is handled in server.lua
|
local antiSpam = {}
local range = 100
function doChat( plr, _, ... )
local player = plr
if ( antiSpam[ player ] ) then
exports.UCDdx:new( player, "Your last sent message was less than one second ago!", 255, 0, 0 )
return false
end
local msg = table.concat( { ... }, " " )
if msg == "" or msg == " " then return end
if ( not exports.UCDaccounts:isPlayerLoggedIn( plr ) ) then return false end
local pX, pY, pZ = getElementPosition( plr )
local plrNick = getPlayerName( plr )
for _, v in pairs( getElementsByType( "player" ) ) do
if ( exports.UCDutil:isPlayerInRangeOfPoint( v, pX, pY, pZ, range ) ) then
if ( getElementDimension( plr ) == ( getElementDimension( v ) ) ) then
if ( getElementInterior( plr ) == ( getElementInterior( v ) ) ) then
outputChatBox( "* "..msg.." ("..plrNick..")", v, 200, 50, 150 )
end
end
end
end
end
addCommandHandler( "do", doChat )
-- /me is handled in server.lua
|
UCDchat
|
UCDchat
- Fixed isPlayerInRangeOfPoint using wrong player in doChat.
|
Lua
|
mit
|
nokizorque/ucd,nokizorque/ucd
|
4f8e5ed9b6fb0a76f3a674605200506722aa090f
|
MMOCoreORB/bin/scripts/object/tangible/lair/base/objective_banner_rebel.lua
|
MMOCoreORB/bin/scripts/object/tangible/lair/base/objective_banner_rebel.lua
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_lair_base_objective_banner_rebel = object_tangible_lair_base_shared_objective_banner_rebel:new {
objectMenuComponent = {"cpp", "LairMenuComponent"},
}
ObjectTemplates:addTemplate(object_tangible_lair_base_objective_banner_rebel, "object/tangible/lair/base/objective_banner_rebel.iff")
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_lair_base_objective_banner_rebel = object_tangible_lair_base_shared_objective_banner_rebel:new {
objectMenuComponent = {"cpp", "LairMenuComponent"},
objectName = "@obj_n:rebel_banner",
}
ObjectTemplates:addTemplate(object_tangible_lair_base_objective_banner_rebel, "object/tangible/lair/base/objective_banner_rebel.iff")
|
[Fixed] name of rebel banner lairs
|
[Fixed] name of rebel banner lairs
Change-Id: I25228e6962413170b1fe836e94d59c650c75f953
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
|
61edb6493f8241a5ae850980f90748173f6baf1d
|
mod_ircd/mod_ircd.lua
|
mod_ircd/mod_ircd.lua
|
local irc_listener = { default_port = 6667, default_mode = "*l" };
local sessions = {};
local commands = {};
local nicks = {};
local st = require "util.stanza";
local conference_server = module:get_option("conference_server") or "conference.jabber.org";
local function irc_close_session(session)
session.conn:close();
end
function irc_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { conn = conn, host = module.host, reset_stream = function () end,
close = irc_close_session, log = logger.init("irc"..(conn.id or "1")),
roster = {} };
sessions[conn] = session;
function session.data(data)
module:log("debug", "Received: %s", data);
local command, args = data:match("^%s*([^ ]+) *(.*)%s*$");
if not command then
module:log("warn", "Invalid command: %s", data);
return;
end
command = command:upper();
module:log("debug", "Received command: %s", command);
if commands[command] then
local ret = commands[command](session, args);
if ret then
session.send(ret.."\r\n");
end
end
end
function session.send(data)
module:log("debug", "sending: %s", data);
return conn:write(data.."\r\n");
end
end
if data then
session.data(data);
end
end
function irc_listener.ondisconnect(conn, error)
module:log("debug", "Client disconnected");
sessions[conn] = nil;
end
function commands.NICK(session, nick)
nick = nick:match("^[%w_]+");
if nicks[nick] then
session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use");
return;
end
nicks[nick] = session;
session.nick = nick;
session.full_jid = nick.."@"..module.host.."/ircd";
session.type = "c2s";
module:log("debug", "Client bound to %s", session.full_jid);
session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick);
end
local joined_mucs = {};
function commands.JOIN(session, channel)
if not joined_mucs[channel] then
joined_mucs[channel] = { occupants = {}, sessions = {} };
end
joined_mucs[channel].sessions[session] = true;
local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick });
core_process_stanza(session, join_stanza);
session.send(":"..session.nick.." JOIN :"..channel);
session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress...");
session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..session.nick);
session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list.");
end
function commands.PART(session, channel)
local channel, part_message = channel:match("^([^:]+):?(.*)$");
channel = channel:match("^([%S]*)");
core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message));
session.send(":"..session.nick.." PART :"..channel);
end
function commands.PRIVMSG(session, message)
local who, message = message:match("^(%S+) :(.+)$");
if joined_mucs[who] then
core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message));
end
end
function commands.PING(session, server)
session.send(":"..session.host..": PONG "..server);
end
function commands.WHO(session, channel)
if joined_mucs[channel] then
for nick in pairs(joined_mucs[channel].occupants) do
--n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild
session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick);
end
session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list");
end
end
function commands.MODE(session, channel)
session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J");
end
--- Component (handle stanzas from the server for IRC clients)
function irc_component(origin, stanza)
local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from);
local from_node = "#"..jid.split(stanza.attr.from);
if joined_mucs[from_node] and from_bare == from then
-- From room itself
local joined_muc = joined_mucs[from_node];
if stanza.name == "message" then
local subject = stanza:get_child("subject");
if subject then
local subject_text = subject:get_text();
for session in pairs(joined_muc.sessions) do
session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject_text);
end
end
end
elseif joined_mucs[from_node] then
-- From room occupant
local joined_muc = joined_mucs[from_node];
local nick = select(3, jid.split(from)):gsub(" ", "_");
if stanza.name == "presence" then
local what;
if not stanza.attr.type then
if joined_muc.occupants[nick] then
return;
end
joined_muc.occupants[nick] = true;
what = "JOIN";
else
joined_muc.occupants[nick] = nil;
what = "PART";
end
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick then
session.send(":"..nick.."!"..nick.." "..what.." :"..from_node);
end
end
elseif stanza.name == "message" then
local body = stanza:get_child("body");
local hasdelay = stanza:get_child("delay", "urn:xmpp:delay");
if body then
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick or hasdelay then
session.send(":"..nick.." PRIVMSG "..from_node.." :"..body:get_text());
end
end
end
end
end
end
require "core.componentmanager".register_component(module.host, irc_component);
prosody.events.add_handler("server-stopping", function (shutdown)
module:log("debug", "Closing IRC connections prior to shutdown");
for channel, joined_muc in pairs(joined_mucs) do
for session in pairs(joined_muc.sessions) do
core_process_stanza(session,
st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }
:tag("status")
:text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or "")));
session:close();
end
end
end);
require "net.connlisteners".register("irc", irc_listener);
require "net.connlisteners".start("irc", { port = module:get_option("port") });
|
local irc_listener = { default_port = 6667, default_mode = "*l" };
local sessions = {};
local commands = {};
local nicks = {};
local st = require "util.stanza";
local conference_server = module:get_option("conference_server") or "conference.jabber.org";
local function irc_close_session(session)
session.conn:close();
end
function irc_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { conn = conn, host = module.host, reset_stream = function () end,
close = irc_close_session, log = logger.init("irc"..(conn.id or "1")),
roster = {} };
sessions[conn] = session;
function session.data(data)
module:log("debug", "Received: %s", data);
local command, args = data:match("^%s*([^ ]+) *(.*)%s*$");
if not command then
module:log("warn", "Invalid command: %s", data);
return;
end
command = command:upper();
module:log("debug", "Received command: %s", command);
if commands[command] then
local ret = commands[command](session, args);
if ret then
session.send(ret.."\r\n");
end
end
end
function session.send(data)
module:log("debug", "sending: %s", data);
return conn:write(data.."\r\n");
end
end
if data then
session.data(data);
end
end
function irc_listener.ondisconnect(conn, error)
module:log("debug", "Client disconnected");
sessions[conn] = nil;
end
function commands.NICK(session, nick)
nick = nick:match("^[%w_]+");
if nicks[nick] then
session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use");
return;
end
nicks[nick] = session;
session.nick = nick;
session.full_jid = nick.."@"..module.host.."/ircd";
session.type = "c2s";
module:log("debug", "Client bound to %s", session.full_jid);
session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick);
end
local joined_mucs = {};
function commands.JOIN(session, channel)
if not joined_mucs[channel] then
joined_mucs[channel] = { occupants = {}, sessions = {} };
end
joined_mucs[channel].sessions[session] = true;
local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick });
core_process_stanza(session, join_stanza);
session.send(":"..session.nick.." JOIN :"..channel);
session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress...");
session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..session.nick);
session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list.");
end
function commands.PART(session, channel)
local channel, part_message = channel:match("^([^:]+):?(.*)$");
channel = channel:match("^([%S]*)");
core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message));
session.send(":"..session.nick.." PART :"..channel);
end
function commands.PRIVMSG(session, message)
local who, message = message:match("^(%S+) :(.+)$");
if joined_mucs[who] then
core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message));
end
end
function commands.PING(session, server)
session.send(":"..session.host..": PONG "..server);
end
function commands.WHO(session, channel)
if joined_mucs[channel] then
for nick in pairs(joined_mucs[channel].occupants) do
--n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild
session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick);
end
session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list");
end
end
function commands.MODE(session, channel)
session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J");
end
--- Component (handle stanzas from the server for IRC clients)
function irc_component(origin, stanza)
local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from);
local from_node = "#"..jid.split(stanza.attr.from);
if joined_mucs[from_node] and from_bare == from then
-- From room itself
local joined_muc = joined_mucs[from_node];
if stanza.name == "message" then
local subject = stanza:get_child("subject");
if subject then
local subject_text = subject:get_text();
for session in pairs(joined_muc.sessions) do
session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject_text);
end
end
end
elseif joined_mucs[from_node] then
-- From room occupant
local joined_muc = joined_mucs[from_node];
local nick = select(3, jid.split(from)):gsub(" ", "_");
if stanza.name == "presence" then
local what;
if not stanza.attr.type then
if joined_muc.occupants[nick] then
return;
end
joined_muc.occupants[nick] = true;
what = "JOIN";
else
joined_muc.occupants[nick] = nil;
what = "PART";
end
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick then
session.send(":"..nick.."!"..nick.." "..what.." :"..from_node);
end
end
elseif stanza.name == "message" then
local body = stanza:get_child("body");
body = body and body:get_text() or "";
local hasdelay = stanza:get_child("delay", "urn:xmpp:delay");
if body ~= "" then
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick or hasdelay then
session.send(":"..nick.." PRIVMSG "..from_node.." :"..body);
end
end
end
end
end
end
require "core.componentmanager".register_component(module.host, irc_component);
prosody.events.add_handler("server-stopping", function (shutdown)
module:log("debug", "Closing IRC connections prior to shutdown");
for channel, joined_muc in pairs(joined_mucs) do
for session in pairs(joined_muc.sessions) do
core_process_stanza(session,
st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }
:tag("status")
:text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or "")));
session:close();
end
end
end);
require "net.connlisteners".register("irc", irc_listener);
require "net.connlisteners".start("irc", { port = module:get_option("port") });
|
mod_ircd: Fixed handling of empty <body/> elements.
|
mod_ircd: Fixed handling of empty <body/> elements.
|
Lua
|
mit
|
Craige/prosody-modules,heysion/prosody-modules,joewalker/prosody-modules,BurmistrovJ/prosody-modules,apung/prosody-modules,Craige/prosody-modules,asdofindia/prosody-modules,olax/prosody-modules,stephen322/prosody-modules,mmusial/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,jkprg/prosody-modules,BurmistrovJ/prosody-modules,prosody-modules/import,apung/prosody-modules,vfedoroff/prosody-modules,stephen322/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,softer/prosody-modules,dhotson/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,1st8/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,drdownload/prosody-modules,drdownload/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,asdofindia/prosody-modules,jkprg/prosody-modules,heysion/prosody-modules,guilhem/prosody-modules,prosody-modules/import,brahmi2/prosody-modules,apung/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,mardraze/prosody-modules,cryptotoad/prosody-modules,NSAKEY/prosody-modules,1st8/prosody-modules,NSAKEY/prosody-modules,drdownload/prosody-modules,NSAKEY/prosody-modules,softer/prosody-modules,vfedoroff/prosody-modules,iamliqiang/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,guilhem/prosody-modules,mmusial/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,mardraze/prosody-modules,mardraze/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,dhotson/prosody-modules,apung/prosody-modules,BurmistrovJ/prosody-modules,jkprg/prosody-modules,LanceJenkinZA/prosody-modules,mmusial/prosody-modules,1st8/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,mardraze/prosody-modules,dhotson/prosody-modules,heysion/prosody-modules,asdofindia/prosody-modules,NSAKEY/prosody-modules,vfedoroff/prosody-modules,obelisk21/prosody-modules,softer/prosody-modules,joewalker/prosody-modules,olax/prosody-modules,softer/prosody-modules,drdownload/prosody-modules,amenophis1er/prosody-modules,Craige/prosody-modules,either1/prosody-modules,brahmi2/prosody-modules,LanceJenkinZA/prosody-modules,amenophis1er/prosody-modules,brahmi2/prosody-modules,BurmistrovJ/prosody-modules,cryptotoad/prosody-modules,obelisk21/prosody-modules,drdownload/prosody-modules,syntafin/prosody-modules,dhotson/prosody-modules,prosody-modules/import,jkprg/prosody-modules,vince06fr/prosody-modules,Craige/prosody-modules,vince06fr/prosody-modules,crunchuser/prosody-modules,Craige/prosody-modules,1st8/prosody-modules,crunchuser/prosody-modules,1st8/prosody-modules,either1/prosody-modules,either1/prosody-modules,mardraze/prosody-modules,asdofindia/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,softer/prosody-modules,LanceJenkinZA/prosody-modules,dhotson/prosody-modules,syntafin/prosody-modules,olax/prosody-modules,iamliqiang/prosody-modules,stephen322/prosody-modules,cryptotoad/prosody-modules,crunchuser/prosody-modules,vfedoroff/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,vfedoroff/prosody-modules,LanceJenkinZA/prosody-modules,heysion/prosody-modules,crunchuser/prosody-modules,NSAKEY/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,mmusial/prosody-modules,syntafin/prosody-modules,iamliqiang/prosody-modules,iamliqiang/prosody-modules,BurmistrovJ/prosody-modules,crunchuser/prosody-modules,syntafin/prosody-modules
|
2ef91a08b349a56f3c4dcabb4a4760fca7babbd7
|
xupnpd/src/plugins/xupnpd_youtube.lua
|
xupnpd/src/plugins/xupnpd_youtube.lua
|
-- Copyright (C) 2011 Anton Burdinuk
-- [email protected]
-- https://tsdemuxer.googlecode.com/svn/trunk/xupnpd
-- 18 - 360p (MP4,h.264/AVC)
-- 22 - 720p (MP4,h.264/AVC) hd
-- 37 - 1080p (MP4,h.264/AVC) hd
-- 82 - 360p (MP4,h.264/AVC) stereo3d
-- 83 - 480p (MP4,h.264/AVC) hq stereo3d
-- 84 - 720p (MP4,h.264/AVC) hd stereo3d
-- 85 - 1080p (MP4,h.264/AVC) hd stereo3d
cfg.youtube_fmt=22
cfg.youtube_region='*'
youtube_api_url='http://gdata.youtube.com/feeds/mobile/'
youtube_common='alt=json&start-index=1&max-results=50' -- &racy=include&restriction=??
function youtube_find_playlist(user,playlist)
local start_index=1
local max_results=50
while(true) do
local feed_data=http.download(youtube_api_url..'users/'..user..'/playlists?alt=json&start-index='..start_index..'&max-results='..max_results)
if not feed_data then break end
local x=json.decode(feed_data)
feed_data=nil
if not x or not x.feed or not x.feed.entry then break end
for i,j in ipairs(x.feed.entry) do
if j.title['$t']==playlist then
return string.match(j.id['$t'],'.+/(%w+)$')
end
end
start_index=start_index+max_results
end
return nil
end
-- username, favorites/username, playlist/username/playlistname, channel/channelname, search/searchstring
-- channels: top_rated, top_favorites, most_viewed, most_recent, recently_featured
function youtube_updatefeed(feed,friendly_name)
local rc=false
local feed_url=nil
local feed_urn=nil
local tfeed=split_string(feed,'/')
local feed_name='youtube_'..string.lower(string.gsub(feed,"[/ :\'\"]",'_'))
if tfeed[1]=='channel' then
local region=''
if cfg.youtube_region and cfg.youtube_region~='*' then region=cfg.youtube_region..'/' end
feed_urn='standardfeeds/'..region..tfeed[2]..'?'..youtube_common
elseif tfeed[1]=='favorites' then
feed_urn='users/'..tfeed[2]..'/favorites'..'?'..youtube_common
elseif tfeed[1]=='playlist' then
local playlist_id=youtube_find_playlist(tfeed[2],tfeed[3])
if not playlist_id then return false end
feed_urn='playlists/'..playlist_id..'?'..youtube_common
elseif tfeed[1]=='search' then
feed_urn='videos?vq='..util.urlencode(tfeed[2])..'&'..youtube_common
else
feed_urn='users/'..tfeed[1]..'/uploads?orderby=published&'..youtube_common
end
local feed_m3u_path=cfg.feeds_path..feed_name..'.m3u'
local tmp_m3u_path=cfg.tmp_path..feed_name..'.m3u'
local feed_data=http.download(youtube_api_url..feed_urn)
if feed_data then
local x=json.decode(feed_data)
feed_data=nil
if x and x.feed and x.feed.entry then
local dfd=io.open(tmp_m3u_path,'w+')
if dfd then
dfd:write('#EXTM3U name=\"',friendly_name or feed_name,'\" type=mp4 plugin=youtube\n')
for i,j in ipairs(x.feed.entry) do
local title=j.title['$t']
local url=nil
for ii,jj in ipairs(j.link) do
if jj['type']=='text/html' then url=jj.href break end
end
local logo=nil
for ii,jj in ipairs(j['media$group']['media$thumbnail']) do
if tonumber(jj['width'])<480 then logo=jj.url break end
end
if cfg.feeds_fetch_length==false then
dfd:write('#EXTINF:0 logo=',logo,' ,',title,'\n',url,'\n')
else
dfd:write('#EXTINF:0 logo=',logo)
local real_url=youtube_get_video_url(url)
if real_url~=nil then
local len=plugin_get_length(real_url)
if len>0 then dfd:write(' length=',len) end
end
dfd:write(' ,',title,'\n',url,'\n')
end
end
dfd:close()
if util.md5(tmp_m3u_path)~=util.md5(feed_m3u_path) then
if os.execute(string.format('mv %s %s',tmp_m3u_path,feed_m3u_path))==0 then
if cfg.debug>0 then print('YouTube feed \''..feed_name..'\' updated') end
rc=true
end
else
util.unlink(tmp_m3u_path)
end
end
end
end
return rc
end
function youtube_sendurl(youtube_url,range)
local url=nil
if plugin_sendurl_from_cache(youtube_url,range) then return end
url=youtube_get_video_url(youtube_url)
if url then
if cfg.debug>0 then print('YouTube Real URL: '..url) end
plugin_sendurl(youtube_url,url,range)
else
if cfg.debug>0 then print('YouTube clip is not found') end
plugin_sendfile('www/corrupted.mp4')
end
end
function youtube_get_video_url(youtube_url)
local url=nil
local clip_page=plugin_download(youtube_url)
if clip_page then
-- local stream_map=util.urldecode(string.match(clip_page,'url_encoded_fmt_stream_map=(.-)&'))
local stream_map=util.urldecode(string.match(clip_page,'url_encoded_fmt_stream_map=(.-)\\u0026amp;'))
clip_page=nil
local fmt=string.match(youtube_url,'&fmt=(%w+)$')
if not fmt then fmt=cfg.youtube_fmt end
if stream_map then
local url_18=nil
for i in string.gmatch(stream_map,'([^,]+)') do
local item={}
for j in string.gmatch(i,'([^&]+)') do
local name,value=string.match(j,'(%w+)=(.+)')
if name then
--print(name,util.urldecode(value))
item[name]=util.urldecode(value)
end
end
if item['itag']==tostring(fmt) then
url=item['url']
break
elseif item['itag']=="18" then
url_18=item['url']
end
--print('\n')
end
if not url then url=url_18 end
end
return url
else
if cfg.debug>0 then print('YouTube clip is not found') end
return nil
end
end
plugins['youtube']={}
plugins.youtube.sendurl=youtube_sendurl
plugins.youtube.updatefeed=youtube_updatefeed
plugins.youtube.getvideourl=youtube_get_video_url
|
-- Copyright (C) 2011 Anton Burdinuk
-- [email protected]
-- https://tsdemuxer.googlecode.com/svn/trunk/xupnpd
-- 18 - 360p (MP4,h.264/AVC)
-- 22 - 720p (MP4,h.264/AVC) hd
-- 37 - 1080p (MP4,h.264/AVC) hd
-- 82 - 360p (MP4,h.264/AVC) stereo3d
-- 83 - 480p (MP4,h.264/AVC) hq stereo3d
-- 84 - 720p (MP4,h.264/AVC) hd stereo3d
-- 85 - 1080p (MP4,h.264/AVC) hd stereo3d
cfg.youtube_fmt=22
cfg.youtube_region='*'
youtube_api_url='http://gdata.youtube.com/feeds/mobile/'
youtube_common='alt=json&start-index=1&max-results=50' -- &racy=include&restriction=??
function youtube_find_playlist(user,playlist)
local start_index=1
local max_results=50
while(true) do
local feed_data=http.download(youtube_api_url..'users/'..user..'/playlists?alt=json&start-index='..start_index..'&max-results='..max_results)
if not feed_data then break end
local x=json.decode(feed_data)
feed_data=nil
if not x or not x.feed or not x.feed.entry then break end
for i,j in ipairs(x.feed.entry) do
if j.title['$t']==playlist then
return string.match(j.id['$t'],'.+/(%w+)$')
end
end
start_index=start_index+max_results
end
return nil
end
-- username, favorites/username, playlist/username/playlistname, channel/channelname, search/searchstring
-- channels: top_rated, top_favorites, most_viewed, most_recent, recently_featured
function youtube_updatefeed(feed,friendly_name)
local rc=false
local feed_url=nil
local feed_urn=nil
local tfeed=split_string(feed,'/')
local feed_name='youtube_'..string.lower(string.gsub(feed,"[/ :\'\"]",'_'))
if tfeed[1]=='channel' then
local region=''
if cfg.youtube_region and cfg.youtube_region~='*' then region=cfg.youtube_region..'/' end
feed_urn='standardfeeds/'..region..tfeed[2]..'?'..youtube_common
elseif tfeed[1]=='favorites' then
feed_urn='users/'..tfeed[2]..'/favorites'..'?'..youtube_common
elseif tfeed[1]=='playlist' then
local playlist_id=youtube_find_playlist(tfeed[2],tfeed[3])
if not playlist_id then return false end
feed_urn='playlists/'..playlist_id..'?'..youtube_common
elseif tfeed[1]=='search' then
feed_urn='videos?vq='..util.urlencode(tfeed[2])..'&'..youtube_common
else
feed_urn='users/'..tfeed[1]..'/uploads?orderby=published&'..youtube_common
end
local feed_m3u_path=cfg.feeds_path..feed_name..'.m3u'
local tmp_m3u_path=cfg.tmp_path..feed_name..'.m3u'
local feed_data=http.download(youtube_api_url..feed_urn)
if feed_data then
local x=json.decode(feed_data)
feed_data=nil
if x and x.feed and x.feed.entry then
local dfd=io.open(tmp_m3u_path,'w+')
if dfd then
dfd:write('#EXTM3U name=\"',friendly_name or feed_name,'\" type=mp4 plugin=youtube\n')
for i,j in ipairs(x.feed.entry) do
local title=j.title['$t']
local url=nil
for ii,jj in ipairs(j.link) do
if jj['type']=='text/html' then url=jj.href break end
end
local logo=nil
for ii,jj in ipairs(j['media$group']['media$thumbnail']) do
if tonumber(jj['width'])<480 then logo=jj.url break end
end
if cfg.feeds_fetch_length==false then
dfd:write('#EXTINF:0 logo=',logo,' ,',title,'\n',url,'\n')
else
dfd:write('#EXTINF:0 logo=',logo)
local real_url=youtube_get_video_url(url)
if real_url~=nil then
local len=plugin_get_length(real_url)
if len>0 then dfd:write(' length=',len) end
end
dfd:write(' ,',title,'\n',url,'\n')
end
end
dfd:close()
if util.md5(tmp_m3u_path)~=util.md5(feed_m3u_path) then
if os.execute(string.format('mv %s %s',tmp_m3u_path,feed_m3u_path))==0 then
if cfg.debug>0 then print('YouTube feed \''..feed_name..'\' updated') end
rc=true
end
else
util.unlink(tmp_m3u_path)
end
end
end
end
return rc
end
function youtube_sendurl(youtube_url,range)
local url=nil
if plugin_sendurl_from_cache(youtube_url,range) then return end
url=youtube_get_video_url(youtube_url)
if url then
if cfg.debug>0 then print('YouTube Real URL: '..url) end
plugin_sendurl(youtube_url,url,range)
else
if cfg.debug>0 then print('YouTube clip is not found') end
plugin_sendfile('www/corrupted.mp4')
end
end
function youtube_get_video_url(youtube_url)
local url=nil
local clip_page=plugin_download(youtube_url)
if clip_page then
local stream_map=util.urldecode(string.match(clip_page,'url_encoded_fmt_stream_map=(.-)\\u0026amp;'))
clip_page=nil
local fmt=string.match(youtube_url,'&fmt=(%w+)$')
if not fmt then fmt=cfg.youtube_fmt end
if stream_map then
local url_18=nil
for i in string.gmatch(stream_map,'([^,]+)') do
local item={}
for j in string.gmatch(i,'([^&]+)') do
local name,value=string.match(j,'(%w+)=(.+)')
if name then
--print(name,util.urldecode(value))
item[name]=util.urldecode(value)
end
end
if item['itag']==tostring(fmt) then
url=item['url']..'&signature='..item['sig']
break
elseif item['itag']=="18" then
url_18=item['url']..'&signature='..item['sig']
end
--print('\n')
end
if not url then url=url_18 end
end
return url
else
if cfg.debug>0 then print('YouTube clip is not found') end
return nil
end
end
plugins['youtube']={}
plugins.youtube.sendurl=youtube_sendurl
plugins.youtube.updatefeed=youtube_updatefeed
plugins.youtube.getvideourl=youtube_get_video_url
|
YouTube hotfix
|
YouTube hotfix
|
Lua
|
mit
|
rollokb/tsdemuxer,lapayx/tsdemuxer,lapayx/tsdemuxer,cgommel/tsdemuxer,cgommel/tsdemuxer,johnymarek/tsdemuxer,cgommel/tsdemuxer,rollokb/tsdemuxer,johnymarek/tsdemuxer,lapayx/tsdemuxer,johnymarek/tsdemuxer,johnymarek/tsdemuxer,rollokb/tsdemuxer,rollokb/tsdemuxer,lapayx/tsdemuxer,cgommel/tsdemuxer
|
9058d903180457ca977e874323ce044d579f0909
|
train.lua
|
train.lua
|
require 'torch'
require 'cutorch'
require 'nn'
require 'cunn'
require 'image'
require 'optim'
local DataLoader = require 'dataloader'
display = require('display')
require 'src/utils'
require 'src/descriptor_net'
----------------------------------------------------------
-- Parameters
----------------------------------------------------------
local cmd = torch.CmdLine()
cmd:option('-content_layers', 'relu4_2', 'Layer to attach content loss. Only one supported for now.')
cmd:option('-style_layers', 'relu1_1,relu2_1,relu3_1,relu4_1', 'Layer to attach content loss. Only one supported for now.')
cmd:option('-learning_rate', 1e-3)
cmd:option('-num_iterations', 50000)
cmd:option('-batch_size', 1)
cmd:option('-image_size', 256)
cmd:option('-content_weight',1)
cmd:option('-style_weight', 1)
cmd:option('-style_image', '')
cmd:option('-style_size', 256)
cmd:option('-mode', 'style', 'style|texture')
cmd:option('-checkpoints_path', 'data/checkpoints/', 'Directory to store intermediate results.')
cmd:option('-model', 'pyramid', 'Path to generator model description file.')
cmd:option('-normalize_gradients', 'false', 'L1 gradient normalization inside descriptor net. ')
cmd:option('-vgg_no_pad', 'false')
cmd:option('-proto_file', 'data/pretrained/VGG_ILSVRC_19_layers_deploy.prototxt', 'Pretrained')
cmd:option('-model_file', 'data/pretrained/VGG_ILSVRC_19_layers.caffemodel')
cmd:option('-backend', 'cudnn', 'nn|cudnn')
-- Dataloader
cmd:option('-dataset', 'style')
cmd:option('-data', '', 'Path to dataset. Structure like in fb.resnet.torch repo.')
cmd:option('-manualSeed', 0)
cmd:option('-nThreads', 4, 'Data loading threads.')
cmd:option('-prefix', '')
params = cmd:parse(arg)
params.normalize_gradients = params.normalize_gradients ~= 'false'
params.vgg_no_pad = params.vgg_no_pad ~= 'false'
params.circular_padding = params.circular_padding ~= 'false'
-- For compatibility with Justin Johnsons code
params.texture_weight = params.style_weight
params.texture_layers = params.style_layers
params.texture = params.style_image
if params.mode == 'texture' then
params.content_layers = ''
pad = nn.SpatialCircularPadding
-- Use circular padding
conv = convc
else
pad = nn.SpatialReplicationPadding
params.in_iter = params.batch_size
params.batch_size = 1
end
trainLoader, valLoader = DataLoader.create(params)
if params.backend == 'cudnn' then
require 'cudnn'
cudnn.fastest = true
cudnn.benchmark = true
backend = cudnn
else
backend = nn
end
-- Define model
local net = require('models/' .. params.model):cuda()
local crit = nn.ArtisticCriterion(params)
----------------------------------------------------------
-- feval
----------------------------------------------------------
local iteration = 0
local parameters, gradParameters = net:getParameters()
local loss_history = {}
function feval(x)
iteration = iteration + 1
if x ~= parameters then
parameters:copy(x)
end
gradParameters:zero()
local loss = 0
for hh = 1, params.in_iter do
-- Get batch
local images = trainLoader:get()
target_for_display = images.target
local images_target = preprocess1(images.target):cuda()
local images_input = images.input:cuda()
-- Forward
local out = net:forward(images_input)
loss = loss + crit:forward({out, images_target})
-- Backward
local grad = crit:backward({out, images_target}, nil)
net:backward(images_input, grad[1])
end
loss = loss/params.batch_size/params.in_iter
table.insert(loss_history, {iteration,loss})
print('#it: ', iteration, 'loss: ', loss)
return loss, gradParameters
end
----------------------------------------------------------
-- Optimize
----------------------------------------------------------
print(' Optimize ')
style_weight_cur = params.style_weight
content_weight_cur = params.content_weight
local optim_method = optim.adam
local state = {
learningRate = params.learning_rate,
}
for it = 1, params.num_iterations do
-- Optimization step
optim_method(feval, parameters, state)
-- Visualize
if it%50 == 0 then
collectgarbage()
local output = net.output:double()
local imgs = {}
for i = 1, output:size(1) do
local img = deprocess(output[i])
table.insert(imgs, torch.clamp(img,0,1))
end
display.image(target_for_display, {win=1, width=512,title = 'Target'})
display.image(imgs, {win=0, width=512,title = params.prefix})
display.plot(loss_history, {win=2, labels={'iteration', 'Loss'}, title='Gpu ' .. params.prefix .. ' Loss'})
end
if it%2000 == 0 then
state.learningRate = state.learningRate*0.8
end
-- Dump net
if it%1000 == 0 then
torch.save(params.checkpoints_path .. '/model_' .. it .. '.t7', net:clearState())
end
end
torch.save(params.checkpoints_path .. 'model.t7', net:clearState())
|
require 'torch'
require 'cutorch'
require 'nn'
require 'cunn'
require 'image'
require 'optim'
local DataLoader = require 'dataloader'
use_display, display = pcall(require, 'display')
if not use_display then
print('torch.display not found. unable to plot')
end
require 'src/utils'
require 'src/descriptor_net'
----------------------------------------------------------
-- Parameters
----------------------------------------------------------
local cmd = torch.CmdLine()
cmd:option('-content_layers', 'relu4_2', 'Layer to attach content loss. Only one supported for now.')
cmd:option('-style_layers', 'relu1_1,relu2_1,relu3_1,relu4_1', 'Layer to attach content loss. Only one supported for now.')
cmd:option('-learning_rate', 1e-3)
cmd:option('-num_iterations', 50000)
cmd:option('-batch_size', 1)
cmd:option('-image_size', 256)
cmd:option('-content_weight',1)
cmd:option('-style_weight', 1)
cmd:option('-style_image', '')
cmd:option('-style_size', 256)
cmd:option('-mode', 'style', 'style|texture')
cmd:option('-checkpoints_path', 'data/checkpoints/', 'Directory to store intermediate results.')
cmd:option('-model', 'pyramid', 'Path to generator model description file.')
cmd:option('-normalize_gradients', 'false', 'L1 gradient normalization inside descriptor net. ')
cmd:option('-vgg_no_pad', 'false')
cmd:option('-proto_file', 'data/pretrained/VGG_ILSVRC_19_layers_deploy.prototxt', 'Pretrained')
cmd:option('-model_file', 'data/pretrained/VGG_ILSVRC_19_layers.caffemodel')
cmd:option('-backend', 'cudnn', 'nn|cudnn')
-- Dataloader
cmd:option('-dataset', 'style')
cmd:option('-data', '', 'Path to dataset. Structure like in fb.resnet.torch repo.')
cmd:option('-manualSeed', 0)
cmd:option('-nThreads', 4, 'Data loading threads.')
cmd:option('-prefix', '')
params = cmd:parse(arg)
params.normalize_gradients = params.normalize_gradients ~= 'false'
params.vgg_no_pad = params.vgg_no_pad ~= 'false'
params.circular_padding = params.circular_padding ~= 'false'
-- For compatibility with Justin Johnsons code
params.texture_weight = params.style_weight
params.texture_layers = params.style_layers
params.texture = params.style_image
if params.mode == 'texture' then
params.content_layers = ''
pad = nn.SpatialCircularPadding
-- Use circular padding
conv = convc
else
pad = nn.SpatialReplicationPadding
params.in_iter = params.batch_size
params.batch_size = 1
end
trainLoader, valLoader = DataLoader.create(params)
if params.backend == 'cudnn' then
require 'cudnn'
cudnn.fastest = true
cudnn.benchmark = true
backend = cudnn
else
backend = nn
end
-- Define model
local net = require('models/' .. params.model):cuda()
local crit = nn.ArtisticCriterion(params)
----------------------------------------------------------
-- feval
----------------------------------------------------------
local iteration = 0
local parameters, gradParameters = net:getParameters()
local loss_history = {}
function feval(x)
iteration = iteration + 1
if x ~= parameters then
parameters:copy(x)
end
gradParameters:zero()
local loss = 0
for hh = 1, params.in_iter do
-- Get batch
local images = trainLoader:get()
target_for_display = images.target
local images_target = preprocess1(images.target):cuda()
local images_input = images.input:cuda()
-- Forward
local out = net:forward(images_input)
loss = loss + crit:forward({out, images_target})
-- Backward
local grad = crit:backward({out, images_target}, nil)
net:backward(images_input, grad[1])
end
loss = loss/params.batch_size/params.in_iter
table.insert(loss_history, {iteration,loss})
print('#it: ', iteration, 'loss: ', loss)
return loss, gradParameters
end
----------------------------------------------------------
-- Optimize
----------------------------------------------------------
print(' Optimize ')
style_weight_cur = params.style_weight
content_weight_cur = params.content_weight
local optim_method = optim.adam
local state = {
learningRate = params.learning_rate,
}
for it = 1, params.num_iterations do
-- Optimization step
optim_method(feval, parameters, state)
-- Visualize
if it%50 == 0 then
collectgarbage()
local output = net.output:double()
local imgs = {}
for i = 1, output:size(1) do
local img = deprocess(output[i])
table.insert(imgs, torch.clamp(img,0,1))
end
if use_display then
display.image(target_for_display, {win=1, width=512,title = 'Target'})
display.image(imgs, {win=0, width=512,title = params.prefix})
display.plot(loss_history, {win=2, labels={'iteration', 'Loss'}, title='Gpu ' .. params.prefix .. ' Loss'})
end
end
if it%2000 == 0 then
state.learningRate = state.learningRate*0.8
end
-- Dump net
if it%1000 == 0 then
torch.save(params.checkpoints_path .. '/model_' .. it .. '.t7', net:clearState())
end
end
torch.save(params.checkpoints_path .. 'model.t7', net:clearState())
|
fixes #18, #31
|
fixes #18, #31
|
Lua
|
apache-2.0
|
DmitryUlyanov/texture_nets
|
cfc0210a1a2e99d2551460ce311bfdd2a9b26289
|
kong/plugins/rate-limiting/policies/init.lua
|
kong/plugins/rate-limiting/policies/init.lua
|
local policy_cluster = require "kong.plugins.rate-limiting.policies.cluster"
local timestamp = require "kong.tools.timestamp"
local reports = require "kong.reports"
local redis = require "resty.redis"
local kong = kong
local pairs = pairs
local null = ngx.null
local shm = ngx.shared.kong_rate_limiting_counters
local fmt = string.format
local EMPTY_UUID = "00000000-0000-0000-0000-000000000000"
local function is_present(str)
return str and str ~= "" and str ~= null
end
local function get_service_and_route_ids(conf)
conf = conf or {}
local service_id = conf.service_id
local route_id = conf.route_id
if not service_id or service_id == null then
service_id = EMPTY_UUID
end
if not route_id or route_id == null then
route_id = EMPTY_UUID
end
return service_id, route_id
end
local get_local_key = function(conf, identifier, period, period_date)
local service_id, route_id = get_service_and_route_ids(conf)
return fmt("ratelimit:%s:%s:%s:%s:%s", route_id, service_id, identifier,
period_date, period)
end
local sock_opts = {}
local EXPIRATION = require "kong.plugins.rate-limiting.expiration"
local function get_redis_connection(conf)
local red = redis:new()
red:set_timeout(conf.redis_timeout)
sock_opts.ssl = conf.redis_ssl
sock_opts.ssl_verify = conf.redis_ssl_verify
sock_opts.server_name = conf.redis_server_name
-- use a special pool name only if redis_database is set to non-zero
-- otherwise use the default pool name host:port
sock_opts.pool = conf.redis_database and
conf.redis_host .. ":" .. conf.redis_port ..
":" .. conf.redis_database
local ok, err = red:connect(conf.redis_host, conf.redis_port,
sock_opts)
if not ok then
kong.log.err("failed to connect to Redis: ", err)
return nil, err
end
local times, err = red:get_reused_times()
if err then
kong.log.err("failed to get connect reused times: ", err)
return nil, err
end
if times == 0 then
if is_present(conf.redis_password) then
local ok, err
if is_present(conf.redis_username) then
ok, err = red:auth(conf.redis_username, conf.redis_password)
else
ok, err = red:auth(conf.redis_password)
end
if not ok then
kong.log.err("failed to auth Redis: ", err)
return nil, err
end
end
if conf.redis_database ~= 0 then
-- Only call select first time, since we know the connection is shared
-- between instances that use the same redis database
local ok, err = red:select(conf.redis_database)
if not ok then
kong.log.err("failed to change Redis database: ", err)
return nil, err
end
end
end
return red
end
return {
["local"] = {
increment = function(conf, limits, identifier, current_timestamp, value)
local periods = timestamp.get_timestamps(current_timestamp)
for period, period_date in pairs(periods) do
if limits[period] then
local cache_key = get_local_key(conf, identifier, period, period_date)
local newval, err = shm:incr(cache_key, value, 0, EXPIRATION[period])
if not newval then
kong.log.err("could not increment counter for period '", period, "': ", err)
return nil, err
end
end
end
return true
end,
usage = function(conf, identifier, period, current_timestamp)
local periods = timestamp.get_timestamps(current_timestamp)
local cache_key = get_local_key(conf, identifier, period, periods[period])
local current_metric, err = shm:get(cache_key)
if err then
return nil, err
end
return current_metric or 0
end
},
["cluster"] = {
increment = function(conf, limits, identifier, current_timestamp, value)
local db = kong.db
local service_id, route_id = get_service_and_route_ids(conf)
local policy = policy_cluster[db.strategy]
local ok, err = policy.increment(db.connector, limits, identifier,
current_timestamp, service_id, route_id,
value)
if not ok then
kong.log.err("cluster policy: could not increment ", db.strategy,
" counter: ", err)
end
return ok, err
end,
usage = function(conf, identifier, period, current_timestamp)
local db = kong.db
local service_id, route_id = get_service_and_route_ids(conf)
local policy = policy_cluster[db.strategy]
local row, err = policy.find(identifier, period, current_timestamp,
service_id, route_id)
if err then
return nil, err
end
if row and row.value ~= null and row.value > 0 then
return row.value
end
return 0
end
},
["redis"] = {
increment = function(conf, limits, identifier, current_timestamp, value)
local red, err = get_redis_connection(conf)
if not red then
return nil, err
end
local keys = {}
local expiration = {}
local idx = 0
local periods = timestamp.get_timestamps(current_timestamp)
for period, period_date in pairs(periods) do
if limits[period] then
local cache_key = get_local_key(conf, identifier, period, period_date)
local exists, err = red:exists(cache_key)
if err then
kong.log.err("failed to query Redis: ", err)
return nil, err
end
idx = idx + 1
keys[idx] = cache_key
if not exists or exists == 0 then
expiration[idx] = EXPIRATION[period]
end
red:init_pipeline()
for i = 1, idx do
red:incrby(keys[i], value)
if expiration[i] then
red:expire(keys[i], expiration[i])
end
end
end
end
local _, err = red:commit_pipeline()
if err then
kong.log.err("failed to commit increment pipeline in Redis: ", err)
return nil, err
end
local ok, err = red:set_keepalive(10000, 100)
if not ok then
kong.log.err("failed to set Redis keepalive: ", err)
return nil, err
end
return true
end,
usage = function(conf, identifier, period, current_timestamp)
local red, err = get_redis_connection(conf)
if not red then
return nil, err
end
reports.retrieve_redis_version(red)
local periods = timestamp.get_timestamps(current_timestamp)
local cache_key = get_local_key(conf, identifier, period, periods[period])
local current_metric, err = red:get(cache_key)
if err then
return nil, err
end
if current_metric == null then
current_metric = nil
end
local ok, err = red:set_keepalive(10000, 100)
if not ok then
kong.log.err("failed to set Redis keepalive: ", err)
end
return current_metric or 0
end
}
}
|
local policy_cluster = require "kong.plugins.rate-limiting.policies.cluster"
local timestamp = require "kong.tools.timestamp"
local reports = require "kong.reports"
local redis = require "resty.redis"
local kong = kong
local pairs = pairs
local null = ngx.null
local shm = ngx.shared.kong_rate_limiting_counters
local fmt = string.format
local EMPTY_UUID = "00000000-0000-0000-0000-000000000000"
local function is_present(str)
return str and str ~= "" and str ~= null
end
local function get_service_and_route_ids(conf)
conf = conf or {}
local service_id = conf.service_id
local route_id = conf.route_id
if not service_id or service_id == null then
service_id = EMPTY_UUID
end
if not route_id or route_id == null then
route_id = EMPTY_UUID
end
return service_id, route_id
end
local get_local_key = function(conf, identifier, period, period_date)
local service_id, route_id = get_service_and_route_ids(conf)
return fmt("ratelimit:%s:%s:%s:%s:%s", route_id, service_id, identifier,
period_date, period)
end
local sock_opts = {}
local EXPIRATION = require "kong.plugins.rate-limiting.expiration"
local function get_redis_connection(conf)
local red = redis:new()
red:set_timeout(conf.redis_timeout)
sock_opts.ssl = conf.redis_ssl
sock_opts.ssl_verify = conf.redis_ssl_verify
sock_opts.server_name = conf.redis_server_name
-- use a special pool name only if redis_database is set to non-zero
-- otherwise use the default pool name host:port
if conf.redis_database ~= 0 then
sock_opts.pool = fmt( "%s:%d;%d",
conf.redis_host,
conf.redis_port,
conf.redis_database)
end
local ok, err = red:connect(conf.redis_host, conf.redis_port,
sock_opts)
if not ok then
kong.log.err("failed to connect to Redis: ", err)
return nil, err
end
local times, err = red:get_reused_times()
if err then
kong.log.err("failed to get connect reused times: ", err)
return nil, err
end
if times == 0 then
if is_present(conf.redis_password) then
local ok, err
if is_present(conf.redis_username) then
ok, err = red:auth(conf.redis_username, conf.redis_password)
else
ok, err = red:auth(conf.redis_password)
end
if not ok then
kong.log.err("failed to auth Redis: ", err)
return nil, err
end
end
if conf.redis_database ~= 0 then
-- Only call select first time, since we know the connection is shared
-- between instances that use the same redis database
local ok, err = red:select(conf.redis_database)
if not ok then
kong.log.err("failed to change Redis database: ", err)
return nil, err
end
end
end
return red
end
return {
["local"] = {
increment = function(conf, limits, identifier, current_timestamp, value)
local periods = timestamp.get_timestamps(current_timestamp)
for period, period_date in pairs(periods) do
if limits[period] then
local cache_key = get_local_key(conf, identifier, period, period_date)
local newval, err = shm:incr(cache_key, value, 0, EXPIRATION[period])
if not newval then
kong.log.err("could not increment counter for period '", period, "': ", err)
return nil, err
end
end
end
return true
end,
usage = function(conf, identifier, period, current_timestamp)
local periods = timestamp.get_timestamps(current_timestamp)
local cache_key = get_local_key(conf, identifier, period, periods[period])
local current_metric, err = shm:get(cache_key)
if err then
return nil, err
end
return current_metric or 0
end
},
["cluster"] = {
increment = function(conf, limits, identifier, current_timestamp, value)
local db = kong.db
local service_id, route_id = get_service_and_route_ids(conf)
local policy = policy_cluster[db.strategy]
local ok, err = policy.increment(db.connector, limits, identifier,
current_timestamp, service_id, route_id,
value)
if not ok then
kong.log.err("cluster policy: could not increment ", db.strategy,
" counter: ", err)
end
return ok, err
end,
usage = function(conf, identifier, period, current_timestamp)
local db = kong.db
local service_id, route_id = get_service_and_route_ids(conf)
local policy = policy_cluster[db.strategy]
local row, err = policy.find(identifier, period, current_timestamp,
service_id, route_id)
if err then
return nil, err
end
if row and row.value ~= null and row.value > 0 then
return row.value
end
return 0
end
},
["redis"] = {
increment = function(conf, limits, identifier, current_timestamp, value)
local red, err = get_redis_connection(conf)
if not red then
return nil, err
end
local keys = {}
local expiration = {}
local idx = 0
local periods = timestamp.get_timestamps(current_timestamp)
for period, period_date in pairs(periods) do
if limits[period] then
local cache_key = get_local_key(conf, identifier, period, period_date)
local exists, err = red:exists(cache_key)
if err then
kong.log.err("failed to query Redis: ", err)
return nil, err
end
idx = idx + 1
keys[idx] = cache_key
if not exists or exists == 0 then
expiration[idx] = EXPIRATION[period]
end
red:init_pipeline()
for i = 1, idx do
red:incrby(keys[i], value)
if expiration[i] then
red:expire(keys[i], expiration[i])
end
end
end
end
local _, err = red:commit_pipeline()
if err then
kong.log.err("failed to commit increment pipeline in Redis: ", err)
return nil, err
end
local ok, err = red:set_keepalive(10000, 100)
if not ok then
kong.log.err("failed to set Redis keepalive: ", err)
return nil, err
end
return true
end,
usage = function(conf, identifier, period, current_timestamp)
local red, err = get_redis_connection(conf)
if not red then
return nil, err
end
reports.retrieve_redis_version(red)
local periods = timestamp.get_timestamps(current_timestamp)
local cache_key = get_local_key(conf, identifier, period, periods[period])
local current_metric, err = red:get(cache_key)
if err then
return nil, err
end
if current_metric == null then
current_metric = nil
end
local ok, err = red:set_keepalive(10000, 100)
if not ok then
kong.log.err("failed to set Redis keepalive: ", err)
end
return current_metric or 0
end
}
}
|
fix(plugin/rate-limiting) correctly handle `config.redis_database`
|
fix(plugin/rate-limiting) correctly handle `config.redis_database`
Use the default connection pool if `config.redis_database` is `0`.
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
a1b1fd337f99aed98e62bfe4fcf305927735b07a
|
src/plugins/finalcutpro/watchfolders/media/init.lua
|
src/plugins/finalcutpro/watchfolders/media/init.lua
|
--- === plugins.finalcutpro.watchfolders.media ===
---
--- Final Cut Pro Media Watch Folder Plugin.
local require = require
local config = require "cp.config"
local fcp = require "cp.apple.finalcutpro"
local MediaFolder = require "MediaFolder"
local panel = require "panel"
local insert = table.insert
local mod = {}
-- The storage for the media folders.
local savedMediaFolders = config.prop("fcp.watchFolders.mediaFolders", {})
--- plugins.finalcutpro.watchfolders.media.mediaFolders -> table
--- Variable
--- The table of MediaFolders currently configured.
local mediaFolders = nil
-- TODO: Add documentation
function mod.addMediaFolder(path, videoTag, audioTag, imageTag)
insert(mediaFolders, MediaFolder.new(mod, path, videoTag, audioTag, imageTag):init())
mod.saveMediaFolders()
end
-- TODO: Add documentation
function mod.removeMediaFolder(path)
for i,f in ipairs(mediaFolders) do
if f.path == path then
f:destroy()
table.remove(mediaFolders, i)
break
end
end
end
-- TODO: Add documentation
function mod.hasMediaFolder(path)
for _,folder in ipairs(mediaFolders) do
if folder.path == path then
return true
end
end
end
-- TODO: Add documentation
function mod.mediaFolders()
return mediaFolders
end
--- plugins.finalcutpro.watchfolders.media.saveMediaFolders()
--- Function
--- Saves the current state of the media folders, including notifications, etc.
---
--- Parameters:
--- * None
---
--- Returns:
--- * Nothing
function mod.saveMediaFolders()
local details = {}
for _,folder in ipairs(mediaFolders) do
insert(details, folder:freeze())
end
savedMediaFolders(details)
end
--- plugins.finalcutpro.watchfolders.media.loadMediaFolders()
--- Function
--- Loads the MediaFolder list from storage. Any existing MediaFolder instances
--- will be destroyed before loading.
function mod.loadMediaFolders()
if mediaFolders then
for _,folder in ipairs(mediaFolders) do
folder:destroy()
end
end
local details = savedMediaFolders()
-- delete any existing ones.
mediaFolders = {}
for _,frozen in ipairs(details) do
insert(mediaFolders, MediaFolder.thaw(mod, frozen):init())
end
end
--- plugins.finalcutpro.watchfolders.media.SECONDS_UNTIL_DELETE -> number
--- Constant
--- Seconds until a file is deleted.
mod.SECONDS_UNTIL_DELETE = 30
--- plugins.finalcutpro.watchfolders.media.automaticallyImport <cp.prop: boolean>
--- Variable
--- Boolean that sets whether or not new generated voice file are automatically added to the timeline or not.
mod.automaticallyImport = config.prop("fcp.watchFolders.automaticallyImport", false)
--- plugins.finalcutpro.watchfolders.media.insertIntoTimeline <cp.prop: boolean>
--- Variable
--- Boolean that sets whether or not the files are automatically added to the timeline or not.
mod.insertIntoTimeline = config.prop("fcp.watchFolders.insertIntoTimeline", true)
--- plugins.finalcutpro.watchfolders.media.deleteAfterImport <cp.prop: boolean>
--- Variable
--- Boolean that sets whether or not you want to delete file after they've been imported.
mod.deleteAfterImport = config.prop("fcp.watchFolders.deleteAfterImport", false)
--- plugins.finalcutpro.watchfolders.media.init(deps, env) -> table
--- Function
--- Initialises the module.
---
--- Parameters:
--- * deps - The dependencies environment
--- * env - The plugin environment
---
--- Returns:
--- * Table of the module.
function mod.init(deps)
--------------------------------------------------------------------------------
-- Ignore Panel if Final Cut Pro isn't installed.
--------------------------------------------------------------------------------
fcp.isSupported:watch(function(installed)
--------------------------------------------------------------------------------
-- Setup Watchers:
--------------------------------------------------------------------------------
mod.loadMediaFolders()
if installed then
panel.init(mod, deps.panelManager)
end
end, true)
--------------------------------------------------------------------------------
-- Define Plugins:
--------------------------------------------------------------------------------
mod.pasteboardManager = deps.pasteboardManager
return mod
end
local plugin = {
id = "finalcutpro.watchfolders.media",
group = "finalcutpro",
dependencies = {
["core.watchfolders.manager"] = "panelManager",
["finalcutpro.pasteboard.manager"] = "pasteboardManager",
}
}
function plugin.init(deps, env)
--------------------------------------------------------------------------------
-- Only load plugin if Final Cut Pro is supported:
--------------------------------------------------------------------------------
if not fcp:isSupported() then return end
return mod.init(deps, env)
end
return plugin
|
--- === plugins.finalcutpro.watchfolders.media ===
---
--- Final Cut Pro Media Watch Folder Plugin.
local require = require
--local log = require "hs.logger".new "WatchFolderMedia"
local config = require "cp.config"
local fcp = require "cp.apple.finalcutpro"
local MediaFolder = require "MediaFolder"
local panel = require "panel"
local insert = table.insert
local mod = {}
-- The storage for the media folders.
local savedMediaFolders = config.prop("fcp.watchFolders.mediaFolders", {})
--- plugins.finalcutpro.watchfolders.media.mediaFolders -> table
--- Variable
--- The table of MediaFolders currently configured.
local mediaFolders = nil
--- plugins.finalcutpro.watchfolders.media.addMediaFolder(path, videoTag, audioTag, imageTag) -> none
--- Function
--- Removes a media folder.
---
--- Parameters:
--- * path - The path of the folder to remove.
--- * videoTag - An optional video tag as a string.
--- * audioTag - An optional audio tag as a string.
--- * imageTag - An optional image tag as a string.
---
--- Returns:
--- * None
function mod.addMediaFolder(path, videoTag, audioTag, imageTag)
insert(mediaFolders, MediaFolder.new(mod, path, videoTag, audioTag, imageTag):init())
mod.saveMediaFolders()
end
--- plugins.finalcutpro.watchfolders.media.removeMediaFolder(path) -> boolean
--- Function
--- Removes a media folder.
---
--- Parameters:
--- * path - The path of the folder to remove.
---
--- Returns:
--- * None
function mod.removeMediaFolder(path)
for i,f in ipairs(mediaFolders) do
if f.path == path then
f:destroy()
table.remove(mediaFolders, i)
mod.saveMediaFolders()
break
end
end
end
--- plugins.finalcutpro.watchfolders.media.hasMediaFolder(path) -> boolean
--- Function
--- Checks to see if a path has a media folder already saved.
---
--- Parameters:
--- * path - The path to check.
---
--- Returns:
--- * A boolean
function mod.hasMediaFolder(path)
for _,folder in ipairs(mediaFolders) do
if folder.path == path then
return true
end
end
end
--- plugins.finalcutpro.watchfolders.media.mediaFolders() -> table
--- Function
--- Gets a table of all the media folders.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A table of all the media folders.
function mod.mediaFolders()
return mediaFolders
end
--- plugins.finalcutpro.watchfolders.media.saveMediaFolders()
--- Function
--- Saves the current state of the media folders, including notifications, etc.
---
--- Parameters:
--- * None
---
--- Returns:
--- * Nothing
function mod.saveMediaFolders()
local details = {}
for _,folder in ipairs(mediaFolders) do
insert(details, folder:freeze())
end
savedMediaFolders(details)
end
--- plugins.finalcutpro.watchfolders.media.loadMediaFolders()
--- Function
--- Loads the MediaFolder list from storage. Any existing MediaFolder instances
--- will be destroyed before loading.
function mod.loadMediaFolders()
if mediaFolders then
for _,folder in ipairs(mediaFolders) do
folder:destroy()
end
end
local details = savedMediaFolders()
-- delete any existing ones.
mediaFolders = {}
for _,frozen in ipairs(details) do
insert(mediaFolders, MediaFolder.thaw(mod, frozen):init())
end
end
--- plugins.finalcutpro.watchfolders.media.SECONDS_UNTIL_DELETE -> number
--- Constant
--- Seconds until a file is deleted.
mod.SECONDS_UNTIL_DELETE = 30
--- plugins.finalcutpro.watchfolders.media.automaticallyImport <cp.prop: boolean>
--- Variable
--- Boolean that sets whether or not new generated voice file are automatically added to the timeline or not.
mod.automaticallyImport = config.prop("fcp.watchFolders.automaticallyImport", false)
--- plugins.finalcutpro.watchfolders.media.insertIntoTimeline <cp.prop: boolean>
--- Variable
--- Boolean that sets whether or not the files are automatically added to the timeline or not.
mod.insertIntoTimeline = config.prop("fcp.watchFolders.insertIntoTimeline", true)
--- plugins.finalcutpro.watchfolders.media.deleteAfterImport <cp.prop: boolean>
--- Variable
--- Boolean that sets whether or not you want to delete file after they've been imported.
mod.deleteAfterImport = config.prop("fcp.watchFolders.deleteAfterImport", false)
--- plugins.finalcutpro.watchfolders.media.init(deps, env) -> table
--- Function
--- Initialises the module.
---
--- Parameters:
--- * deps - The dependencies environment
--- * env - The plugin environment
---
--- Returns:
--- * Table of the module.
function mod.init(deps)
--------------------------------------------------------------------------------
-- Ignore Panel if Final Cut Pro isn't installed.
--------------------------------------------------------------------------------
fcp.isSupported:watch(function(installed)
--------------------------------------------------------------------------------
-- Setup Watchers:
--------------------------------------------------------------------------------
mod.loadMediaFolders()
if installed then
panel.init(mod, deps.panelManager)
end
end, true)
--------------------------------------------------------------------------------
-- Define Plugins:
--------------------------------------------------------------------------------
mod.pasteboardManager = deps.pasteboardManager
return mod
end
local plugin = {
id = "finalcutpro.watchfolders.media",
group = "finalcutpro",
dependencies = {
["core.watchfolders.manager"] = "panelManager",
["finalcutpro.pasteboard.manager"] = "pasteboardManager",
}
}
function plugin.init(deps, env)
--------------------------------------------------------------------------------
-- Only load plugin if Final Cut Pro is supported:
--------------------------------------------------------------------------------
if not fcp:isSupported() then return end
return mod.init(deps, env)
end
return plugin
|
Fixed a bug where a deleted media watch folder would reappear on app restart
|
Fixed a bug where a deleted media watch folder would reappear on app restart
- Added missing documentation.
- Closes #2283
|
Lua
|
mit
|
fcpxhacks/fcpxhacks,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost
|
68f5298e8136d8744a7c9d224e7c06884f40a836
|
src/websocket/client_lluv.lua
|
src/websocket/client_lluv.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-websocket library.
--
------------------------------------------------------------------
local uv = require 'lluv'
local ut = require 'lluv.utils'
local websocket = require 'lluv.websocket'
local ocall = function (f, ...) if f then return f(...) end end
local TEXT, BINARY = websocket.TEXT, websocket.BINARY
local Client = ut.class() do
local cleanup = function(self)
if self._sock then self._sock:close() end
self._sock = nil
end
local on_close = function(self, was_clean, code, reason)
cleanup(self)
ocall(self._on_close, self, was_clean, code, reason or '')
end
local on_error = function(self, err, dont_cleanup)
if not dont_cleanup then cleanup(self) end
ocall(self._on_error, self, err)
end
local on_open = function(self)
self._state = 'OPEN'
ocall(self._on_open, self)
end
local handle_socket_err = function(self, err)
self._sock:close(function(self, clean, code, reason)
on_error(self, err)
end)
end
function Client:__init(ws)
self._ws = ws or {}
self._on_send_done = function(sock, err)
if err then handle_socket_err(self, err) end
end
return self
end
function Client:connect(url, proto)
if self._sock then return end
self._sock = websocket.new{ssl = self._ws.ssl, utf8 = self._ws.utf8}
self._sock:connect(url, proto, function(sock, err)
if err then return on_error(self, err) end
on_open(self)
sock:start_read(function(sock, err, message, opcode)
if err then
return self._sock:close(function(sock, clean, code, reason)
on_close(self, clean, code, reason)
end)
end
if opcode == TEXT or opcode == BINARY then
return ocall(self._on_message, self, message, opcode)
end
end)
end)
return self
end
function Client:on_close(handler)
self._on_close = handler
end
function Client:on_error(handler)
self._on_error = handler
end
function Client:on_open(handler)
self._on_open = handler
end
function Client:on_message(handler)
self._on_message = handler
end
function Client:send(message, opcode)
self._sock:write(message, opcode, self._on_send_done)
end
function Client:close(code, reason, timeout)
self._sock:close(code, reason, function(sock, clean, code, reason)
on_close(self, clean, code, reason)
end)
return self
end
end
local ok, sync = pcall(require, 'websocket.client_lluv_sync')
return setmetatable({sync = sync},{__call = function(_, ...)
return Client.new(...)
end})
|
------------------------------------------------------------------
--
-- 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-websocket library.
--
------------------------------------------------------------------
local uv = require 'lluv'
local ut = require 'lluv.utils'
local websocket = require 'lluv.websocket'
local ocall = function (f, ...) if f then return f(...) end end
local TEXT, BINARY = websocket.TEXT, websocket.BINARY
local Client = ut.class() do
local cleanup = function(self)
if self._sock then self._sock:close() end
self._sock = nil
end
local on_close = function(self, was_clean, code, reason)
cleanup(self)
ocall(self._on_close, self, was_clean, code, reason or '')
end
local on_error = function(self, err, dont_cleanup)
if not dont_cleanup then cleanup(self) end
ocall(self._on_error, self, err)
end
local on_open = function(self)
self._state = 'OPEN'
ocall(self._on_open, self)
end
local handle_socket_err = function(self, err)
self._sock:close(function(self, clean, code, reason)
on_error(self, err)
end)
end
function Client:__init(ws)
self._ws = ws or {}
self._on_send_done = function(sock, err)
if err then handle_socket_err(self, err) end
end
return self
end
function Client:connect(url, proto)
if self._sock then return end
self._sock = websocket.new{ssl = self._ws.ssl, utf8 = self._ws.utf8}
self._sock:connect(url, proto, function(sock, err)
if err then return on_error(self, err) end
on_open(self)
sock:start_read(function(sock, err, message, opcode)
if err then
return self._sock:close(function(sock, clean, code, reason)
on_close(self, clean, code, reason)
end)
end
if opcode == TEXT or opcode == BINARY then
return ocall(self._on_message, self, message, opcode)
end
end)
end)
return self
end
function Client:on_close(handler)
self._on_close = handler
end
function Client:on_error(handler)
self._on_error = handler
end
function Client:on_open(handler)
self._on_open = handler
end
function Client:on_message(handler)
self._on_message = handler
end
function Client:send(message, opcode)
self._sock:write(message, opcode, self._on_send_done)
end
function Client:close(code, reason, timeout)
self._sock:close(code, reason, function(sock, clean, code, reason)
on_close(self, clean, code, reason)
end)
return self
end
end
local ok, sync = pcall(require, 'websocket.client_lluv_sync')
if not ok then sync = nil end
return setmetatable({sync = sync},{__call = function(_, ...)
return Client.new(...)
end})
|
Fix. Set sync to `nil` if there error load.
|
Fix. Set sync to `nil` if there error load.
|
Lua
|
mit
|
moteus/lua-lluv-websocket,moteus/lua-lluv-websocket,moteus/lua-lluv-websocket
|
221966d43487d5bc47477a762be8ae446911b15a
|
net/http/server.lua
|
net/http/server.lua
|
local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
local parser_new = require "net.http.parser".new;
local events = require "util.events".new();
local addserver = require "net.server".addserver;
local log = require "util.logger".init("http.server");
local os_date = os.date;
local pairs = pairs;
local s_upper = string.upper;
local setmetatable = setmetatable;
local xpcall = xpcall;
local debug = debug;
local tostring = tostring;
local codes = require "net.http.codes";
local _G = _G;
local _M = {};
local sessions = {};
local handlers = {};
local listener = {};
local handle_request;
local _1, _2, _3;
local function _handle_request() return handle_request(_1, _2, _3); end
local function _traceback_handler(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug.traceback()); end
function listener.onconnect(conn)
local secure = conn:ssl() and true or nil;
local pending = {};
local waiting = false;
local function process_next(last_response)
--if waiting then log("debug", "can't process_next, waiting"); return; end
if sessions[conn] and #pending > 0 then
local request = t_remove(pending);
--log("debug", "process_next: %s", request.path);
waiting = true;
--handle_request(conn, request, process_next);
_1, _2, _3 = conn, request, process_next;
if not xpcall(_handle_request, _traceback_handler) then
conn:write("HTTP/1.0 503 Internal Server Error\r\n\r\nAn error occured during the processing of this request.");
conn:close();
end
else
--log("debug", "ready for more");
waiting = false;
end
end
local function success_cb(request)
--log("debug", "success_cb: %s", request.path);
request.secure = secure;
t_insert(pending, request);
if not waiting then
process_next();
end
end
local function error_cb(err)
log("debug", "error_cb: %s", err or "<nil>");
-- FIXME don't close immediately, wait until we process current stuff
-- FIXME if err, send off a bad-request response
sessions[conn] = nil;
conn:close();
end
sessions[conn] = parser_new(success_cb, error_cb);
end
function listener.ondisconnect(conn)
sessions[conn] = nil;
end
function listener.onincoming(conn, data)
sessions[conn]:feed(data);
end
local headerfix = setmetatable({}, {
__index = function(t, k)
local v = "\r\n"..k:gsub("_", "-"):gsub("%f[%w].", s_upper)..": ";
t[k] = v;
return v;
end
});
function _M.hijack_response(response, listener)
error("TODO");
end
function handle_request(conn, request, finish_cb)
--log("debug", "handler: %s", request.path);
local headers = {};
for k,v in pairs(request.headers) do headers[k:gsub("-", "_")] = v; end
request.headers = headers;
request.conn = conn;
local date_header = os_date('!%a, %d %b %Y %H:%M:%S GMT'); -- FIXME use
local conn_header = request.headers.connection;
local keep_alive = conn_header == "Keep-Alive" or (request.httpversion == "1.1" and conn_header ~= "close");
local response = {
request = request;
status_code = 200;
headers = { date = date_header, connection = (keep_alive and "Keep-Alive" or "close") };
conn = conn;
send = _M.send_response;
finish_cb = finish_cb;
};
if not request.headers.host then
response.status_code = 400;
response.headers.content_type = "text/html";
response:send("<html><head>400 Bad Request</head><body>400 Bad Request: No Host header.</body></html>");
else
-- TODO call handler
--response.headers.content_type = "text/plain";
--response:send("host="..(request.headers.host or "").."\npath="..request.path.."\n"..(request.body or ""));
local host = request.headers.host;
if host then
host = host:match("[^:]*"):lower();
local event = request.method.." "..host..request.path:match("[^?]*");
local payload = { request = request, response = response };
--[[repeat
if events.fire_event(event, payload) ~= nil then return; end
event = (event:sub(-1) == "/") and event:sub(1, -1) or event:gsub("[^/]*$", "");
if event:sub(-1) == "/" then
event = event:sub(1, -1);
else
event = event:gsub("[^/]*$", "");
end
until not event:find("/", 1, true);]]
--log("debug", "Event: %s", event);
if events.fire_event(event, payload) ~= nil then return; end
-- TODO try adding/stripping / at the end, but this needs to work via an HTTP redirect
if events.fire_event("*", payload) ~= nil then return; end
end
-- if handler not called, fallback to legacy httpserver handlers
_M.legacy_handler(request, response);
end
end
function _M.send_response(response, body)
local status_line = "HTTP/"..response.request.httpversion.." "..(response.status or codes[response.status_code]);
local headers = response.headers;
body = body or "";
headers.content_length = #body;
local output = { status_line };
for k,v in pairs(headers) do
t_insert(output, headerfix[k]..v);
end
t_insert(output, "\r\n\r\n");
t_insert(output, body);
response.conn:write(t_concat(output));
if headers.connection == "Keep-Alive" then
response:finish_cb();
else
response.conn:close();
end
end
function _M.legacy_handler(request, response)
log("debug", "Invoking legacy handler");
local base = request.path:match("^/([^/?]+)");
local legacy_server = _G.httpserver and _G.httpserver.new.http_servers[5280];
local handler = legacy_server and legacy_server.handlers[base];
if not handler then handler = _G.httpserver and _G.httpserver.set_default_handler.default_handler; end
if handler then
-- add legacy properties to request object
request.url = { path = request.path };
request.handler = response.conn;
request.id = tostring{}:match("%x+$");
local headers = {};
for k,v in pairs(request.headers) do
headers[k:gsub("_", "-")] = v;
end
request.headers = headers;
function request:send(resp)
if self.destroyed then return; end
if resp.body or resp.headers then
if resp.headers then
for k,v in pairs(resp.headers) do response.headers[k] = v; end
end
response:send(resp.body)
else
response:send(resp)
end
self.sent = true;
self:destroy();
end
function request:destroy()
if self.destroyed then return; end
if not self.sent then return self:send(""); end
self.destroyed = true;
if self.on_destroy then
log("debug", "Request has destroy callback");
self:on_destroy();
else
log("debug", "Request has no destroy callback");
end
end
local r = handler(request.method, request.body, request);
if r ~= true then
request:send(r);
end
else
log("debug", "No handler found");
response.status_code = 404;
response.headers.content_type = "text/html";
response:send("<html><head><title>404 Not Found</title></head><body>404 Not Found: No such page.</body></html>");
end
end
function _M.add_handler(event, handler, priority)
events.add_handler(event, handler, priority);
end
function _M.remove_handler(event, handler)
events.remove_handler(event, handler);
end
function _M.listen_on(port, interface, ssl)
addserver(interface or "*", port, listener, "*a", ssl);
end
_M.listener = listener;
_M.codes = codes;
return _M;
|
local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
local parser_new = require "net.http.parser".new;
local events = require "util.events".new();
local addserver = require "net.server".addserver;
local log = require "util.logger".init("http.server");
local os_date = os.date;
local pairs = pairs;
local s_upper = string.upper;
local setmetatable = setmetatable;
local xpcall = xpcall;
local debug = debug;
local tostring = tostring;
local codes = require "net.http.codes";
local _G = _G;
local legacy_httpserver = require "net.httpserver";
local _M = {};
local sessions = {};
local handlers = {};
local listener = {};
local handle_request;
local _1, _2, _3;
local function _handle_request() return handle_request(_1, _2, _3); end
local function _traceback_handler(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug.traceback()); end
function listener.onconnect(conn)
local secure = conn:ssl() and true or nil;
local pending = {};
local waiting = false;
local function process_next(last_response)
--if waiting then log("debug", "can't process_next, waiting"); return; end
if sessions[conn] and #pending > 0 then
local request = t_remove(pending);
--log("debug", "process_next: %s", request.path);
waiting = true;
--handle_request(conn, request, process_next);
_1, _2, _3 = conn, request, process_next;
if not xpcall(_handle_request, _traceback_handler) then
conn:write("HTTP/1.0 503 Internal Server Error\r\n\r\nAn error occured during the processing of this request.");
conn:close();
end
else
--log("debug", "ready for more");
waiting = false;
end
end
local function success_cb(request)
--log("debug", "success_cb: %s", request.path);
request.secure = secure;
t_insert(pending, request);
if not waiting then
process_next();
end
end
local function error_cb(err)
log("debug", "error_cb: %s", err or "<nil>");
-- FIXME don't close immediately, wait until we process current stuff
-- FIXME if err, send off a bad-request response
sessions[conn] = nil;
conn:close();
end
sessions[conn] = parser_new(success_cb, error_cb);
end
function listener.ondisconnect(conn)
sessions[conn] = nil;
end
function listener.onincoming(conn, data)
sessions[conn]:feed(data);
end
local headerfix = setmetatable({}, {
__index = function(t, k)
local v = "\r\n"..k:gsub("_", "-"):gsub("%f[%w].", s_upper)..": ";
t[k] = v;
return v;
end
});
function _M.hijack_response(response, listener)
error("TODO");
end
function handle_request(conn, request, finish_cb)
--log("debug", "handler: %s", request.path);
local headers = {};
for k,v in pairs(request.headers) do headers[k:gsub("-", "_")] = v; end
request.headers = headers;
request.conn = conn;
local date_header = os_date('!%a, %d %b %Y %H:%M:%S GMT'); -- FIXME use
local conn_header = request.headers.connection;
local keep_alive = conn_header == "Keep-Alive" or (request.httpversion == "1.1" and conn_header ~= "close");
local response = {
request = request;
status_code = 200;
headers = { date = date_header, connection = (keep_alive and "Keep-Alive" or "close") };
conn = conn;
send = _M.send_response;
finish_cb = finish_cb;
};
if not request.headers.host then
response.status_code = 400;
response.headers.content_type = "text/html";
response:send("<html><head>400 Bad Request</head><body>400 Bad Request: No Host header.</body></html>");
else
-- TODO call handler
--response.headers.content_type = "text/plain";
--response:send("host="..(request.headers.host or "").."\npath="..request.path.."\n"..(request.body or ""));
local host = request.headers.host;
if host then
host = host:match("[^:]*"):lower();
local event = request.method.." "..host..request.path:match("[^?]*");
local payload = { request = request, response = response };
--[[repeat
if events.fire_event(event, payload) ~= nil then return; end
event = (event:sub(-1) == "/") and event:sub(1, -1) or event:gsub("[^/]*$", "");
if event:sub(-1) == "/" then
event = event:sub(1, -1);
else
event = event:gsub("[^/]*$", "");
end
until not event:find("/", 1, true);]]
--log("debug", "Event: %s", event);
if events.fire_event(event, payload) ~= nil then return; end
-- TODO try adding/stripping / at the end, but this needs to work via an HTTP redirect
if events.fire_event("*", payload) ~= nil then return; end
end
-- if handler not called, fallback to legacy httpserver handlers
_M.legacy_handler(request, response);
end
end
function _M.send_response(response, body)
local status_line = "HTTP/"..response.request.httpversion.." "..(response.status or codes[response.status_code]);
local headers = response.headers;
body = body or "";
headers.content_length = #body;
local output = { status_line };
for k,v in pairs(headers) do
t_insert(output, headerfix[k]..v);
end
t_insert(output, "\r\n\r\n");
t_insert(output, body);
response.conn:write(t_concat(output));
if headers.connection == "Keep-Alive" then
response:finish_cb();
else
response.conn:close();
end
end
function _M.legacy_handler(request, response)
log("debug", "Invoking legacy handler");
local base = request.path:match("^/([^/?]+)");
local legacy_server = legacy_httpserver and legacy_httpserver.new.http_servers[5280];
local handler = legacy_server and legacy_server.handlers[base];
if not handler then handler = legacy_httpserver and legacy_httpserver.set_default_handler.default_handler; end
if handler then
-- add legacy properties to request object
request.url = { path = request.path };
request.handler = response.conn;
request.id = tostring{}:match("%x+$");
local headers = {};
for k,v in pairs(request.headers) do
headers[k:gsub("_", "-")] = v;
end
request.headers = headers;
function request:send(resp)
if self.destroyed then return; end
if resp.body or resp.headers then
if resp.headers then
for k,v in pairs(resp.headers) do response.headers[k] = v; end
end
response:send(resp.body)
else
response:send(resp)
end
self.sent = true;
self:destroy();
end
function request:destroy()
if self.destroyed then return; end
if not self.sent then return self:send(""); end
self.destroyed = true;
if self.on_destroy then
log("debug", "Request has destroy callback");
self:on_destroy();
else
log("debug", "Request has no destroy callback");
end
end
local r = handler(request.method, request.body, request);
if r ~= true then
request:send(r);
end
else
log("debug", "No handler found");
response.status_code = 404;
response.headers.content_type = "text/html";
response:send("<html><head><title>404 Not Found</title></head><body>404 Not Found: No such page.</body></html>");
end
end
function _M.add_handler(event, handler, priority)
events.add_handler(event, handler, priority);
end
function _M.remove_handler(event, handler)
events.remove_handler(event, handler);
end
function _M.listen_on(port, interface, ssl)
addserver(interface or "*", port, listener, "*a", ssl);
end
_M.listener = listener;
_M.codes = codes;
return _M;
|
net.http.server: Fix legacy net.httpserver fallback (httpserver is no longer a global).
|
net.http.server: Fix legacy net.httpserver fallback (httpserver is no longer a global).
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
076229381209d653720d8d35c76d2f6781b98b42
|
Modules/Shared/Promise/Promise.lua
|
Modules/Shared/Promise/Promise.lua
|
--- Promises, but without error handling as this screws with stack traces, using Roblox signals
-- @classmod Promise
-- See: https://promisesaplus.com/
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local fastSpawn = require("fastSpawn")
local function isPromise(value)
return type(value) == "table" and value.ClassName == "Promise"
end
local Promise = {}
Promise.ClassName = "Promise"
Promise.__index = Promise
Promise.IsPromise = isPromise
--- Construct a new promise
-- @constructor Promise.new()
-- @treturn Promise
function Promise.new(func)
local self = setmetatable({}, Promise)
self._pendingExecuteList = {}
self._uncaughtException = true
self._source = debug.traceback()
if type(func) == "function" then
func(self:_getResolveReject())
end
return self
end
--- Initializes a new promise with the given function in a fastSpawn wrapper
function Promise.spawn(func)
local self = Promise.new()
fastSpawn(func, self:_getResolveReject())
return self
end
function Promise.resolved(...)
local promise = Promise.new()
promise:Resolve(...)
return promise
end
function Promise.rejected(...)
local promise = Promise.new()
promise:Reject(...)
return promise
end
--- Returns whether or not the promise is pending
-- @treturn bool True if pending, false otherwise
function Promise:IsPending()
return self._pendingExecuteList ~= nil
end
function Promise:IsFulfilled()
return self._fulfilled ~= nil
end
function Promise:IsRejected()
return self._rejected ~= nil
end
--- Yield until the promise is complete
function Promise:Wait()
if self._fulfilled then
return unpack(self._fulfilled, 1, self._valuesLength)
elseif self._rejected then
return error(tostring(self._rejected[1]), 2)
else
local bindable = Instance.new("BindableEvent")
self:Then(function()
bindable:Fire()
end, function()
bindable:Fire()
end)
bindable.Event:Wait()
bindable:Destroy()
if self._rejected then
return error(tostring(self._rejected[1]), 2)
else
return unpack(self._fulfilled, 1, self._valuesLength)
end
end
end
--- Promise resolution procedure
-- Resolves a promise
-- @return self
function Promise:Resolve(...)
if not self._pendingExecuteList then
return
end
if self == (...) then
self:Reject("TypeError: Resolved to self")
elseif isPromise(...) then
if select("#", ...) > 1 then
local message = ("When resolving a promise, extra arguments are discarded! See:\n\n%s")
:format(self._source)
warn(message)
end
local promise2 = (...)
if promise2._pendingExecuteList then
promise2:Then(self:_getResolveReject())
elseif promise2._rejected then
self:Reject(unpack(promise2._rejected, 1, promise2._valuesLength))
elseif promise2._fulfilled then
self:_fulfill(unpack(promise2._fulfilled, 1, promise2._valuesLength))
else
error("[Promise.Resolve] - Bad promise2 state")
end
else -- TODO: Handle thenable promises
self:_fulfill(...)
end
end
--- Fulfills the promise with the value
-- @param ... Params to _fulfill with
-- @return self
function Promise:_fulfill(...)
if not self._pendingExecuteList then
return
end
self._valuesLength = select("#", ...)
self._fulfilled = {...}
local list = self._pendingExecuteList
self._pendingExecuteList = nil
for _, data in pairs(list) do
self:_executeThen(data.promise, data.onFulfilled, data.onRejected)
end
end
--- Rejects the promise with the value given
-- @param ... Params to reject with
-- @return self
function Promise:Reject(...)
if not self._pendingExecuteList then
return
end
self._valuesLength = select("#", ...)
self._rejected = {...}
local list = self._pendingExecuteList
self._pendingExecuteList = nil
for _, data in pairs(list) do
self:_executeThen(data.promise, data.onFulfilled, data.onRejected)
end
-- Check for uncaught exceptions
if self._uncaughtException then
spawn(function()
if self._uncaughtException then
warn(("[Promise] - Uncaught exception in promise\n\n%s\n\n%s"):format(tostring(self._rejected[1]), self._source))
end
end)
end
end
--- Handlers when promise is fulfilled/rejected. It takes up to two arguments, callback functions
-- for the success and failure cases of the Promise. May return the same promise if certain behavior
-- is met.
-- @tparam[opt=nil] function onFulfilled Called when fulfilled with parameters
-- @tparam[opt=nil] function onRejected Called when rejected with parameters
-- @treturn Promise
function Promise:Then(onFulfilled, onRejected)
self._uncaughtException = false
if self._pendingExecuteList then
local promise = Promise.new()
table.insert(self._pendingExecuteList, {
promise = promise,
onFulfilled = onFulfilled,
onRejected = onRejected,
})
return promise
else
return self:_executeThen(nil, onFulfilled, onRejected)
end
end
function Promise:Finally(func)
return self:Then(func, func)
end
--- Catch errors from the promise
-- @treturn Promise
function Promise:Catch(func)
return self:Then(nil, func)
end
--- Rejects the current promise.
-- Utility left for Maid task
-- @treturn nil
function Promise:Destroy()
self:Reject()
end
function Promise:_getResolveReject()
return function(...)
self:Resolve(...)
end, function(...)
self:Reject(...)
end
end
-- @param promise2 May be nil. If it is, then we have the option to return self
function Promise:_executeThen(promise2, onFulfilled, onRejected)
if self._fulfilled then
if type(onFulfilled) == "function" then
if not promise2 then
promise2 = Promise.new()
end
-- Technically undefined behavior from A+, but we'll resolve to nil like ES6 promises
promise2:Resolve(onFulfilled(unpack(self._fulfilled, 1, self._valuesLength)))
return promise2
else
-- Promise2 Fulfills with promise1 (self) value
if promise2 then
promise2:_fulfill(unpack(self._fulfilled, 1, self._valuesLength))
return promise2
else
return self
end
end
elseif self._rejected then
if type(onRejected) == "function" then
if not promise2 then
promise2 = Promise.new()
end
-- Technically undefined behavior from A+, but we'll resolve to nil like ES6 promises
promise2:Resolve(onRejected(unpack(self._rejected, 1, self._valuesLength)))
return promise2
else
-- Promise2 Rejects with promise1 (self) value
if promise2 then
promise2:Reject(unpack(self._rejected, 1, self._valuesLength))
return promise2
else
return self
end
end
else
error("Internal error: still pending")
end
end
return Promise
|
--- Promises, but without error handling as this screws with stack traces, using Roblox signals
-- @classmod Promise
-- See: https://promisesaplus.com/
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local fastSpawn = require("fastSpawn")
local function isPromise(value)
return type(value) == "table" and value.ClassName == "Promise"
end
local Promise = {}
Promise.ClassName = "Promise"
Promise.__index = Promise
Promise.IsPromise = isPromise
--- Construct a new promise
-- @constructor Promise.new()
-- @treturn Promise
function Promise.new(func)
local self = setmetatable({}, Promise)
self._pendingExecuteList = {}
self._uncaughtException = true
self._source = debug.traceback()
if type(func) == "function" then
func(self:_getResolveReject())
end
return self
end
--- Initializes a new promise with the given function in a fastSpawn wrapper
function Promise.spawn(func)
local self = Promise.new()
fastSpawn(func, self:_getResolveReject())
return self
end
function Promise.resolved(...)
local promise = Promise.new()
promise:Resolve(...)
return promise
end
function Promise.rejected(...)
local promise = Promise.new()
promise:Reject(...)
return promise
end
--- Returns whether or not the promise is pending
-- @treturn bool True if pending, false otherwise
function Promise:IsPending()
return self._pendingExecuteList ~= nil
end
function Promise:IsFulfilled()
return self._fulfilled ~= nil
end
function Promise:IsRejected()
return self._rejected ~= nil
end
--- Yield until the promise is complete
function Promise:Wait()
if self._fulfilled then
return unpack(self._fulfilled, 1, self._valuesLength)
elseif self._rejected then
return error(tostring(self._rejected[1]), 2)
else
local bindable = Instance.new("BindableEvent")
self:Then(function()
bindable:Fire()
end, function()
bindable:Fire()
end)
bindable.Event:Wait()
bindable:Destroy()
if self._rejected then
return error(tostring(self._rejected[1]), 2)
else
return unpack(self._fulfilled, 1, self._valuesLength)
end
end
end
--- Promise resolution procedure
-- Resolves a promise
-- @return self
function Promise:Resolve(...)
if not self._pendingExecuteList then
return
end
if self == (...) then
self:Reject("TypeError: Resolved to self")
elseif isPromise(...) then
if select("#", ...) > 1 then
local message = ("When resolving a promise, extra arguments are discarded! See:\n\n%s")
:format(self._source)
warn(message)
end
local promise2 = (...)
if promise2._pendingExecuteList then
promise2:Then(self:_getResolveReject())
elseif promise2._rejected then
promise2._uncaughtException = false
self:Reject(unpack(promise2._rejected, 1, promise2._valuesLength))
elseif promise2._fulfilled then
promise2._uncaughtException = false
self:_fulfill(unpack(promise2._fulfilled, 1, promise2._valuesLength))
else
error("[Promise.Resolve] - Bad promise2 state")
end
else -- TODO: Handle thenable promises
self:_fulfill(...)
end
end
--- Fulfills the promise with the value
-- @param ... Params to _fulfill with
-- @return self
function Promise:_fulfill(...)
if not self._pendingExecuteList then
return
end
self._valuesLength = select("#", ...)
self._fulfilled = {...}
local list = self._pendingExecuteList
self._pendingExecuteList = nil
for _, data in pairs(list) do
self:_executeThen(data.promise, data.onFulfilled, data.onRejected)
end
end
--- Rejects the promise with the value given
-- @param ... Params to reject with
-- @return self
function Promise:Reject(...)
if not self._pendingExecuteList then
return
end
self._valuesLength = select("#", ...)
self._rejected = {...}
local list = self._pendingExecuteList
self._pendingExecuteList = nil
for _, data in pairs(list) do
self:_executeThen(data.promise, data.onFulfilled, data.onRejected)
end
-- Check for uncaught exceptions
if self._uncaughtException then
spawn(function()
if self._uncaughtException then
warn(("[Promise] - Uncaught exception in promise\n\n%s\n\n%s"):format(tostring(self._rejected[1]), self._source))
end
end)
end
end
--- Handlers when promise is fulfilled/rejected. It takes up to two arguments, callback functions
-- for the success and failure cases of the Promise. May return the same promise if certain behavior
-- is met.
-- @tparam[opt=nil] function onFulfilled Called when fulfilled with parameters
-- @tparam[opt=nil] function onRejected Called when rejected with parameters
-- @treturn Promise
function Promise:Then(onFulfilled, onRejected)
self._uncaughtException = false
if self._pendingExecuteList then
local promise = Promise.new()
table.insert(self._pendingExecuteList, {
promise = promise,
onFulfilled = onFulfilled,
onRejected = onRejected,
})
return promise
else
return self:_executeThen(nil, onFulfilled, onRejected)
end
end
function Promise:Finally(func)
return self:Then(func, func)
end
--- Catch errors from the promise
-- @treturn Promise
function Promise:Catch(func)
return self:Then(nil, func)
end
--- Rejects the current promise.
-- Utility left for Maid task
-- @treturn nil
function Promise:Destroy()
self:Reject()
end
function Promise:_getResolveReject()
return function(...)
self:Resolve(...)
end, function(...)
self:Reject(...)
end
end
-- @param promise2 May be nil. If it is, then we have the option to return self
function Promise:_executeThen(promise2, onFulfilled, onRejected)
if self._fulfilled then
if type(onFulfilled) == "function" then
if not promise2 then
promise2 = Promise.new()
end
-- Technically undefined behavior from A+, but we'll resolve to nil like ES6 promises
promise2:Resolve(onFulfilled(unpack(self._fulfilled, 1, self._valuesLength)))
return promise2
else
-- Promise2 Fulfills with promise1 (self) value
if promise2 then
promise2:_fulfill(unpack(self._fulfilled, 1, self._valuesLength))
return promise2
else
return self
end
end
elseif self._rejected then
if type(onRejected) == "function" then
if not promise2 then
promise2 = Promise.new()
end
-- Technically undefined behavior from A+, but we'll resolve to nil like ES6 promises
promise2:Resolve(onRejected(unpack(self._rejected, 1, self._valuesLength)))
return promise2
else
-- Promise2 Rejects with promise1 (self) value
if promise2 then
promise2:Reject(unpack(self._rejected, 1, self._valuesLength))
return promise2
else
return self
end
end
else
error("Internal error: still pending")
end
end
return Promise
|
Fix uncaught exceptions when resolving to another promise
|
Fix uncaught exceptions when resolving to another promise
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
a23b2000a2675f005b6a60b3c2bd0a5917970fb8
|
xmake/modules/private/action/build/object.lua
|
xmake/modules/private/action/build/object.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-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file object.lua
--
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.tool.compiler")
import("core.project.depend")
import("private.tools.ccache")
import("private.async.runjobs")
-- do build file
function _do_build_file(target, sourcefile, opt)
-- get build info
local objectfile = opt.objectfile
local dependfile = opt.dependfile
local sourcekind = opt.sourcekind
local progress = opt.progress
-- load compiler
local compinst = compiler.load(sourcekind, {target = target})
-- get compile flags
local compflags = compinst:compflags({target = target, sourcefile = sourcefile, configs = opt.configs})
-- load dependent info
local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {})
-- need build this object?
local depvalues = {compinst:program(), compflags}
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(objectfile), values = depvalues}) then
return
end
-- is verbose?
local verbose = option.get("verbose")
-- exists ccache?
local exists_ccache = ccache.exists()
-- trace progress info
if not opt.quiet then
local progress_prefix = "${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} "
if verbose then
cprint(progress_prefix .. "${dim color.build.object}%scompiling.$(mode) %s", progress, exists_ccache and "ccache " or "", sourcefile)
else
cprint(progress_prefix .. "${color.build.object}%scompiling.$(mode) %s", progress, exists_ccache and "ccache " or "", sourcefile)
end
end
-- trace verbose info
if verbose then
print(compinst:compcmd(sourcefile, objectfile, {compflags = compflags}))
end
-- compile it
dependinfo.files = {}
if not option.get("dry-run") then
assert(compinst:compile(sourcefile, objectfile, {dependinfo = dependinfo, compflags = compflags}))
end
-- update files and values to the dependent file
dependinfo.values = depvalues
table.join2(dependinfo.files, sourcefile, target:pcoutputfile("cxx") or {}, target:pcoutputfile("c"))
depend.save(dependinfo, dependfile)
end
-- build object
function _build_object(target, sourcefile, opt)
local script = target:script("build_file", _do_build_file)
if script then
script(target, sourcefile, opt)
end
end
-- build the source files
function build(target, sourcebatch, opt)
for i = 1, #sourcebatch.sourcefiles do
local sourcefile = sourcebatch.sourcefiles[i]
local objectfile = sourcebatch.objectfiles[i]
local dependfile = sourcebatch.dependfiles[i]
local sourcekind = assert(sourcebatch.sourcekind, "%s: sourcekind not found!", sourcefile)
_build_object(target, sourcefile, {objectfile = objectfile, dependfile = dependfile, sourcekind = sourcekind, progress = opt.progress})
end
end
-- add batch jobs to build the source files
function main(target, batchjobs, sourcebatch, opt)
local rootjob = opt.rootjob
for i = 1, #sourcebatch.sourcefiles do
local sourcefile = sourcebatch.sourcefiles[i]
local objectfile = sourcebatch.objectfiles[i]
local dependfile = sourcebatch.dependfiles[i]
local sourcekind = assert(sourcebatch.sourcekind, "%s: sourcekind not found!", sourcefile)
batchjobs:addjob(sourcefile, function (index, total)
_build_object(target, sourcefile, {objectfile = objectfile, dependfile = dependfile, sourcekind = sourcekind, progress = (index * 100) / total})
end, rootjob)
end
end
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file object.lua
--
-- imports
import("core.base.option")
import("core.theme.theme")
import("core.tool.compiler")
import("core.project.depend")
import("private.tools.ccache")
import("private.async.runjobs")
-- do build file
function _do_build_file(target, sourcefile, opt)
-- get build info
local objectfile = opt.objectfile
local dependfile = opt.dependfile
local sourcekind = opt.sourcekind
local progress = opt.progress
-- load compiler
local compinst = compiler.load(sourcekind, {target = target})
-- get compile flags
local compflags = compinst:compflags({target = target, sourcefile = sourcefile, configs = opt.configs})
-- load dependent info
local dependinfo = option.get("rebuild") and {} or (depend.load(dependfile) or {})
-- need build this object?
local depvalues = {compinst:program(), compflags}
if not depend.is_changed(dependinfo, {lastmtime = os.mtime(objectfile), values = depvalues}) then
return
end
-- is verbose?
local verbose = option.get("verbose")
-- exists ccache?
local exists_ccache = ccache.exists()
-- trace progress info
if not opt.quiet then
local progress_prefix = "${color.build.progress}" .. theme.get("text.build.progress_format") .. ":${clear} "
if verbose then
cprint(progress_prefix .. "${dim color.build.object}%scompiling.$(mode) %s", progress, exists_ccache and "ccache " or "", sourcefile)
else
cprint(progress_prefix .. "${color.build.object}%scompiling.$(mode) %s", progress, exists_ccache and "ccache " or "", sourcefile)
end
end
-- trace verbose info
if verbose then
print(compinst:compcmd(sourcefile, objectfile, {compflags = compflags}))
end
-- compile it
dependinfo.files = {}
if not option.get("dry-run") then
assert(compinst:compile(sourcefile, objectfile, {dependinfo = dependinfo, compflags = compflags}))
end
-- update files and values to the dependent file
dependinfo.values = depvalues
table.join2(dependinfo.files, sourcefile, target:pcoutputfile("cxx") or {}, target:pcoutputfile("c"))
depend.save(dependinfo, dependfile)
end
-- build object
function _build_object(target, sourcefile, opt)
local script = target:script("build_file", _do_build_file)
if script then
script(target, sourcefile, opt)
end
end
-- build the source files
function build(target, sourcebatch, opt)
for i = 1, #sourcebatch.sourcefiles do
local sourcefile = sourcebatch.sourcefiles[i]
opt.objectfile = sourcebatch.objectfiles[i]
opt.dependfile = sourcebatch.dependfiles[i]
opt.sourcekind = assert(sourcebatch.sourcekind, "%s: sourcekind not found!", sourcefile)
_build_object(target, sourcefile, opt)
end
end
-- add batch jobs to build the source files
function main(target, batchjobs, sourcebatch, opt)
local rootjob = opt.rootjob
for i = 1, #sourcebatch.sourcefiles do
local sourcefile = sourcebatch.sourcefiles[i]
opt.objectfile = sourcebatch.objectfiles[i]
opt.dependfile = sourcebatch.dependfiles[i]
opt.sourcekind = assert(sourcebatch.sourcekind, "%s: sourcekind not found!", sourcefile)
batchjobs:addjob(sourcefile, function (index, total)
opt.progress = (index * 100) / total
_build_object(target, sourcefile, opt)
end, rootjob)
end
end
|
fix pass object opt
|
fix pass object opt
|
Lua
|
apache-2.0
|
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
|
838238d3a45f85c0d75bc00ac2ffc82d65afa548
|
Modules/Utility/os.lua
|
Modules/Utility/os.lua
|
-- @author Narrev
local function date(formatString, unix)
--- Allows you to use os.date in RobloxLua!
-- date ([format [, time]])
-- This doesn't include the explanations for the math. If you want to see how the numbers work, see the following:
-- http://howardhinnant.github.io/date_algorithms.html#weekday_from_days
--
-- @param string formatString
-- If present, function date returns a string formatted by the tags in formatString.
-- If formatString starts with "!", date is formatted in UTC.
-- If formatString is "*t", date returns a table
-- Placing "_" in the middle of a tag (e.g. "%_d" "%_I") removes padding
-- String Reference: https://github.com/Narrev/NevermoreEngine/blob/patch-5/Modules/Utility/readme.md
-- @default "%c"
--
-- @param number unix
-- If present, unix is the time to be formatted. Otherwise, date formats the current time.
-- The amount of seconds since 1970 (negative numbers are occasionally supported)
-- @default tick()
-- @returns a string or a table containing date and time, formatted according to the given string format. If called without arguments, returns the equivalent of date("%c").
-- Localize functions
local floor, sub, find, gsub, format = math.floor, string.sub, string.find, string.gsub, string.format
local function suffix(Number)
--- Returns st, nd (Like 1st, 2nd)
-- @param number Number The number to get the suffix of [1-31]
if Number < 21 and Number > 3 or Number > 23 and Number < 31 then return "th" end
return ({"st", "nd", "rd"})[Number % 10]
end
-- Find whether formatString was used
if formatString then
if type(formatString) == "number" then -- If they didn't pass a formatString, and only passed unix through
assert(type(unix) ~= "string", "Invalid parameters passed to os.date. Your parameters might be in the wrong order")
unix, formatString = formatString, "%c"
elseif type(formatString) == "string" then
assert(find(formatString, "*t") or find(formatString, "%%[_cxXTrRaAbBdHIjMmpsSuwyY]"), "Invalid string passed to os.date")
local UTC
formatString, UTC = gsub(formatString, "^!", "") -- If formatString begins in '!', use os.time()
assert(UTC == 0 or not unix, "Cannot determine time to format for os.date. Use either an \"!\" at the beginning of the string or pass a time parameter")
unix = UTC == 1 and os.time() or unix
end
else -- If they did not pass a formatting string
formatString = "%c"
end
-- Set unix
local unix = type(tonumber(unix)) == "number" and unix or tick()
-- Get hours, minutes, and seconds
local hours, minutes, seconds = floor(unix / 3600 % 24), floor(unix / 60 % 60), floor(unix % 60)
-- Get days, month and year
local days = floor(unix / 86400) + 719468
local wday = (days + 3) % 7
local year = floor((days >= 0 and days or days - 146096) / 146097) -- 400 Year bracket
days = (days - year * 146097) -- Days into 400 year bracket [0, 146096]
local years = floor((days - floor(days/1460) + floor(days/36524) - floor(days/146096))/365) -- Years into 400 Year bracket[0, 399]
days = days - (365*years + floor(years/4) - floor(years/100)) -- Days into year (March 1st is first day) [0, 365]
local month = floor((5*days + 2)/153) -- Month of year (March is month 0) [0, 11]
local yDay = days -- Hi readers :)
days = days - floor((153*month + 2)/5) + 1 -- Days into month [1, 31]
month = month + (month < 10 and 3 or -9) -- Real life month [1, 12]
year = years + year*400 + (month < 3 and 1 or 0) -- Actual year (Shift 1st month from March to January)
if formatString == "*t" then -- Return a table if "*t" was used
return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds}
end
-- Necessary string tables
local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
local months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
-- Return formatted string
return (gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(formatString,
"%%c", "%%x %%X"),
"%%_c", "%%_x %%_X"),
"%%x", "%%m/%%d/%%y"),
"%%_x", "%%_m/%%_d/%%y"),
"%%X", "%%H:%%M:%%S"),
"%%_X", "%%_H:%%M:%%S"),
"%%T", "%%I:%%M %%p"),
"%%_T", "%%_I:%%M %%p"),
"%%r", "%%I:%%M:%%S %%p"),
"%%_r", "%%_I:%%M:%%S %%p"),
"%%R", "%%H:%%M"),
"%%_R", "%%_H:%%M"),
"%%a", sub(dayNames[wday + 1], 1, 3)),
"%%A", dayNames[wday + 1]),
"%%b", sub(months[month], 1, 3)),
"%%B", months[month]),
"%%d", format("%02d", days)),
"%%_d", days),
"%%H", format("%02d", hours)),
"%%_H", hours),
"%%I", format("%02d", hours > 12 and hours - 12 or hours == 0 and 12 or hours)),
"%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours),
"%%j", format("%02d", yDay)),
"%%_j", yDay),
"%%M", format("%02d", minutes)),
"%%_M", minutes),
"%%m", format("%02d", month)),
"%%_m", month),
"%%n", "\n"),
"%%p", hours >= 12 and "pm" or "am"),
"%%_p", hours >= 12 and "PM" or "AM"),
"%%s", (days < 21 and days > 3 or days > 23 and days < 31) and "th" or ({"st", "nd", "rd"})[days % 10]),
"%%S", format("%02d", seconds)),
"%%_S", seconds),
"%%t", "\t"),
"%%u", wday == 0 and 7 or wday),
"%%w", wday),
"%%Y", year),
"%%y", format("%02d", year % 100)),
"%%_y", year % 100),
"%%%%", "%%")
)
end
local function clock()
local timeYielded, timeServerHasBeenRunning = wait()
return timeServerHasBeenRunning
end
return setmetatable({date = date, clock = clock}, {__index = os})
|
-- @author Narrev
local function date(formatString, unix)
--- Allows you to use os.date in RobloxLua!
-- date ([format [, time]])
-- This doesn't include the explanations for the math. If you want to see how the numbers work, see the following:
-- http://howardhinnant.github.io/date_algorithms.html#weekday_from_days
--
-- @param string formatString
-- If present, function date returns a string formatted by the tags in formatString.
-- If formatString starts with "!", date is formatted in UTC.
-- If formatString is "*t", date returns a table
-- Placing "_" in the middle of a tag (e.g. "%_d" "%_I") removes padding
-- String Reference: https://github.com/Narrev/NevermoreEngine/blob/patch-5/Modules/Utility/readme.md
-- @default "%c"
--
-- @param number unix
-- If present, unix is the time to be formatted. Otherwise, date formats the current time.
-- The amount of seconds since 1970 (negative numbers are occasionally supported)
-- @default tick()
-- @returns a string or a table containing date and time, formatted according to the given string format. If called without arguments, returns the equivalent of date("%c").
-- Localize functions
local floor, sub, find, gsub, format = math.floor, string.sub, string.find, string.gsub, string.format
-- Find whether formatString was used
if formatString then
if type(formatString) == "number" then -- If they didn't pass a formatString, and only passed unix through
assert(type(unix) ~= "string", "Invalid parameters passed to os.date. Your parameters might be in the wrong order")
unix, formatString = formatString, "%c"
elseif type(formatString) == "string" then
assert(find(formatString, "*t") or find(formatString, "%%[_cxXTrRaAbBdHIjMmpsSuwyY]"), "Invalid string passed to os.date")
local UTC
formatString, UTC = gsub(formatString, "^!", "") -- If formatString begins in '!', use os.time()
assert(UTC == 0 or not unix, "Cannot determine time to format for os.date. Use either an \"!\" at the beginning of the string or pass a time parameter")
unix = UTC == 1 and os.time() or unix
end
else -- If they did not pass a formatting string
formatString = "%c"
end
-- Set unix
local unix = type(tonumber(unix)) == "number" and unix or tick()
-- Get hours, minutes, and seconds
local hours, minutes, seconds = floor(unix / 3600 % 24), floor(unix / 60 % 60), floor(unix % 60)
-- Get days, month and year
local days = floor(unix / 86400) + 719468
local wday = (days + 3) % 7
local year = floor((days >= 0 and days or days - 146096) / 146097) -- 400 Year bracket
days = (days - year * 146097) -- Days into 400 year bracket [0, 146096]
local years = floor((days - floor(days/1460) + floor(days/36524) - floor(days/146096))/365) -- Years into 400 Year bracket[0, 399]
days = days - (365*years + floor(years/4) - floor(years/100)) -- Days into year (March 1st is first day) [0, 365]
local month = floor((5*days + 2)/153) -- Month of year (March is month 0) [0, 11]
local yDay = days -- Hi readers :)
days = days - floor((153*month + 2)/5) + 1 -- Days into month [1, 31]
month = month + (month < 10 and 3 or -9) -- Real life month [1, 12]
year = years + year*400 + (month < 3 and 1 or 0) -- Actual year (Shift 1st month from March to January)
if formatString == "*t" then -- Return a table if "*t" was used
return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds}
end
-- Necessary string tables
local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
local months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
-- Return formatted string
return (gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(gsub(formatString,
"%%c", "%%x %%X"),
"%%_c", "%%_x %%_X"),
"%%x", "%%m/%%d/%%y"),
"%%_x", "%%_m/%%_d/%%y"),
"%%X", "%%H:%%M:%%S"),
"%%_X", "%%_H:%%M:%%S"),
"%%T", "%%I:%%M %%p"),
"%%_T", "%%_I:%%M %%p"),
"%%r", "%%I:%%M:%%S %%p"),
"%%_r", "%%_I:%%M:%%S %%p"),
"%%R", "%%H:%%M"),
"%%_R", "%%_H:%%M"),
"%%a", sub(dayNames[wday + 1], 1, 3)),
"%%A", dayNames[wday + 1]),
"%%b", sub(months[month], 1, 3)),
"%%B", months[month]),
"%%d", format("%02d", days)),
"%%_d", days),
"%%H", format("%02d", hours)),
"%%_H", hours),
"%%I", format("%02d", hours > 12 and hours - 12 or hours == 0 and 12 or hours)),
"%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours),
"%%j", format("%02d", yDay)),
"%%_j", yDay),
"%%M", format("%02d", minutes)),
"%%_M", minutes),
"%%m", format("%02d", month)),
"%%_m", month),
"%%n", "\n"),
"%%p", hours >= 12 and "pm" or "am"),
"%%_p", hours >= 12 and "PM" or "AM"),
"%%s", (days < 21 and days > 3 or days > 23 and days < 31) and "th" or ({"st", "nd", "rd"})[days % 10]),
"%%S", format("%02d", seconds)),
"%%_S", seconds),
"%%t", "\t"),
"%%u", wday == 0 and 7 or wday),
"%%w", wday),
"%%Y", year),
"%%y", format("%02d", year % 100)),
"%%_y", year % 100),
"%%%%", "%%")
)
end
local function clock()
local timeYielded, timeServerHasBeenRunning = wait()
return timeServerHasBeenRunning
end
return setmetatable({date = date, clock = clock}, {__index = os})
|
Remove suffix function
|
Remove suffix function
os now runs without any additional functions!
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
68545546ccad5bce0ea86be2baffdfe514663528
|
src/lua/browser.lua
|
src/lua/browser.lua
|
-- © 2008 David Given.
-- WordGrinder is licensed under the MIT open source license. See the COPYING
-- file in this distribution for the full text.
local min = min
local max = max
local int = math.floor
local string_rep = string.rep
local Write = wg.write
local GotoXY = wg.gotoxy
local SetNormal = wg.setnormal
local SetBold = wg.setbold
local SetUnderline = wg.setunderline
local SetReverse = wg.setreverse
local SetDim = wg.setdim
local GetStringWidth = wg.getstringwidth
local GetBytesOfCharacter = wg.getbytesofcharacter
function FileBrowser(title, message, saving, default)
local files = {}
for i in lfs.dir(".") do
if (i ~= ".") and ((i == "..") or not i:match("^%.")) then
local attr = lfs.attributes(i)
if attr then
attr.name = i
files[#files+1] = attr
end
end
end
table.sort(files, function(a, b)
if (a.mode == b.mode) then
return a.name < b.name
end
if (a.mode == "directory") then
return true
end
return false
end)
local labels = {}
local defaultn = 1
for _, attr in ipairs(files) do
local dmarker = " "
if (attr.mode == "directory") then
dmarker = "◇ "
end
labels[#labels+1] = {
data = attr.name,
label = dmarker..attr.name
}
if (attr.name == default) then
defaultn = #labels
end
end
local f = Browser(title, lfs.currentdir(), message, labels,
default, defaultn)
if not f then
return nil
end
if (ARCH == "windows") and f:match("^%a:$") then
-- The user has typed a drive specifier; turn it into a path.
f = f.."/"
end
local attr, e = lfs.attributes(f)
if not saving and e then
ModalMessage("File inaccessible", "The file '"..f.."' could not be accessed: "..e)
return FileBrowser(title, message, saving)
end
if attr and (attr.mode == "directory") then
lfs.chdir(f)
return FileBrowser(title, message, saving)
end
if saving and not e then
local r = PromptForYesNo("Overwrite file?", "The file '"..f.."' already exists. Do you want to overwrite it?")
if (r == nil) then
return nil
elseif r then
return lfs.currentdir().."/"..f
else
return FileBrowser(title, message, saving)
end
end
return lfs.currentdir().."/"..f
end
function Browser(title, topmessage, bottommessage, data, default, defaultn)
local browser = Form.Browser {
focusable = false,
type = Form.Browser,
x1 = 1, y1 = 2,
x2 = -1, y2 = -5,
data = data,
cursor = defaultn or 1
}
local textfield = Form.TextField {
x1 = GetStringWidth(bottommessage) + 3, y1 = -3,
x2 = -1, y2 = -2,
value = default or data[1].data,
}
local function navigate(self, key)
local action = browser[key](browser)
textfield.value = data[browser.cursor].data
textfield.cursor = textfield.value:len() + 1
textfield.offset = 1
textfield:draw()
return action
end
local helptext
if (ARCH == "windows") then
helptext = "enter an absolute path or drive letter ('c:') to go there"
else
helptext = "enter an absolute path to go there"
end
local dialogue =
{
title = title,
width = Form.Large,
height = Form.Large,
stretchy = false,
["KEY_^C"] = "cancel",
["KEY_RETURN"] = "confirm",
["KEY_ENTER"] = "confirm",
["KEY_UP"] = navigate,
["KEY_DOWN"] = navigate,
["KEY_NPAGE"] = navigate,
["KEY_PPAGE"] = navigate,
Form.Label {
x1 = 1, y1 = 1,
x2 = -1, y2 = 1,
value = topmessage
},
textfield,
browser,
Form.Label {
x1 = 1, y1 = -3,
x2 = GetStringWidth(bottommessage) + 1, y2 = -3,
value = bottommessage
},
Form.Label {
x1 = 1, y1 = -1,
x2 = -1, y2 = -1,
value = helptext
}
}
local result = Form.Run(dialogue, RedrawScreen,
"RETURN to confirm, CTRL+C to cancel")
QueueRedraw()
if result then
return textfield.value
else
return nil
end
end
|
-- © 2008 David Given.
-- WordGrinder is licensed under the MIT open source license. See the COPYING
-- file in this distribution for the full text.
local min = min
local max = max
local int = math.floor
local string_rep = string.rep
local Write = wg.write
local GotoXY = wg.gotoxy
local SetNormal = wg.setnormal
local SetBold = wg.setbold
local SetUnderline = wg.setunderline
local SetReverse = wg.setreverse
local SetDim = wg.setdim
local GetStringWidth = wg.getstringwidth
local GetBytesOfCharacter = wg.getbytesofcharacter
function FileBrowser(title, message, saving, default)
local files = {}
for i in lfs.dir(".") do
if (i ~= ".") and ((i == "..") or not i:match("^%.")) then
local attr = lfs.attributes(i)
if attr then
attr.name = i
files[#files+1] = attr
end
end
end
table.sort(files, function(a, b)
if (a.mode == b.mode) then
return a.name < b.name
end
if (a.mode == "directory") then
return true
end
return false
end)
local labels = {}
local defaultn = 1
for _, attr in ipairs(files) do
local dmarker = " "
if (attr.mode == "directory") then
dmarker = "◇ "
end
labels[#labels+1] = {
data = attr.name,
label = dmarker..attr.name
}
if (attr.name == default) then
defaultn = #labels
end
end
-- Windows will sometimes give you a directory with no entries
-- in it at all (e.g. Documents and Settings on Win7). This is
-- annoying.
if (#labels == 0) then
labels[#labels+1] = {
data = "..",
label = "◇ .."
}
end
local f = Browser(title, lfs.currentdir(), message, labels,
default, defaultn)
if not f then
return nil
end
if (ARCH == "windows") and f:match("^%a:$") then
-- The user has typed a drive specifier; turn it into a path.
f = f.."/"
end
local attr, e = lfs.attributes(f)
if not saving and e then
ModalMessage("File inaccessible", "The file '"..f.."' could not be accessed: "..e)
return FileBrowser(title, message, saving)
end
if attr and (attr.mode == "directory") then
lfs.chdir(f)
return FileBrowser(title, message, saving)
end
if saving and not e then
local r = PromptForYesNo("Overwrite file?", "The file '"..f.."' already exists. Do you want to overwrite it?")
if (r == nil) then
return nil
elseif r then
return lfs.currentdir().."/"..f
else
return FileBrowser(title, message, saving)
end
end
return lfs.currentdir().."/"..f
end
function Browser(title, topmessage, bottommessage, data, default, defaultn)
local browser = Form.Browser {
focusable = false,
type = Form.Browser,
x1 = 1, y1 = 2,
x2 = -1, y2 = -5,
data = data,
cursor = defaultn or 1
}
local textfield = Form.TextField {
x1 = GetStringWidth(bottommessage) + 3, y1 = -3,
x2 = -1, y2 = -2,
value = default or data[1].data,
}
local function navigate(self, key)
local action = browser[key](browser)
textfield.value = data[browser.cursor].data
textfield.cursor = textfield.value:len() + 1
textfield.offset = 1
textfield:draw()
return action
end
local helptext
if (ARCH == "windows") then
helptext = "enter an absolute path or drive letter ('c:') to go there"
else
helptext = "enter an absolute path to go there"
end
local dialogue =
{
title = title,
width = Form.Large,
height = Form.Large,
stretchy = false,
["KEY_^C"] = "cancel",
["KEY_RETURN"] = "confirm",
["KEY_ENTER"] = "confirm",
["KEY_UP"] = navigate,
["KEY_DOWN"] = navigate,
["KEY_NPAGE"] = navigate,
["KEY_PPAGE"] = navigate,
Form.Label {
x1 = 1, y1 = 1,
x2 = -1, y2 = 1,
value = topmessage
},
textfield,
browser,
Form.Label {
x1 = 1, y1 = -3,
x2 = GetStringWidth(bottommessage) + 1, y2 = -3,
value = bottommessage
},
Form.Label {
x1 = 1, y1 = -1,
x2 = -1, y2 = -1,
value = helptext
}
}
local result = Form.Run(dialogue, RedrawScreen,
"RETURN to confirm, CTRL+C to cancel")
QueueRedraw()
if result then
return textfield.value
else
return nil
end
end
|
Fix annoying crash on Win7 where fake directories don't get a .. entry.
|
Fix annoying crash on Win7 where fake directories don't get a ..
entry.
|
Lua
|
mit
|
rodoviario/wordgrinder,Munchotaur/wordgrinder,rodoviario/wordgrinder,NRauh/wordgrinder,Munchotaur/wordgrinder,NRauh/wordgrinder
|
21b6bb5e8baca9baba4a56fa51b4ce62a3483972
|
hymn/inputhandler.lua
|
hymn/inputhandler.lua
|
local Class = require "shared.middleclass"
local GameMath = require "shared.gamemath"
local InputHandler = Class "InputHandler"
local EntityStatics = require "hymn.staticdata.entitystatics"
function InputHandler:initialize(logicCore)
self.logicCore = logicCore
self.translate = GameMath.Vector2:new(0, 0)
end
local borderWidth = 20
local scrollSpeed = 2000
function InputHandler:update(dt)
local width, height = love.graphics.getDimensions()
local x, y = love.mouse.getPosition()
-- border scrolling
if x < borderWidth then
self.translate.x = self.translate.x + scrollSpeed * dt
elseif x > width - borderWidth then
self.translate.x = self.translate.x - scrollSpeed * dt
end
if y < borderWidth then
self.translate.y = self.translate.y + scrollSpeed * dt
elseif y > height - borderWidth then
self.translate.y = self.translate.y - scrollSpeed * dt
end
-- dragging
if self.dragAnchor then
-- dbgprint
self.translate.x = x - self.dragAnchor.x
self.translate.y = y - self.dragAnchor.y
end
local w, h = self.logicCore.map:size()
self.translate.x = GameMath.clamp(self.translate.x, -w + width, 0)
self.translate.y = GameMath.clamp(self.translate.y, -h + height, 0)
end
function InputHandler:centerOn(x, y)
local width, height = love.graphics.getDimensions()
self.translate.x = -x + width/2
self.translate.y = -y + height/2
end
-- click-through prevention. sucky, sucky Quickie! ;)
function InputHandler:isToolBar(x, y)
local width, height = love.graphics.getDimensions()
return y > height - 50
end
function InputHandler:mousePressed(x, y, button)
if self:isToolBar(x, y) then
return
end
if button == "l" then
local position = GameMath.Vector2:new(x, y) - self.translate
self.dragClick = GameMath.Vector2:new(x, y)
self.dragAnchor = position
end
end
function InputHandler:mouseReleased(x, y, button)
if self.dragAnchor then
local d = GameMath.Vector2.distance(GameMath.Vector2:new(x,y), self.dragClick)
self.dragAnchor = false
if d > 5 then
return
end
end
if self:isToolBar(x, y) then
return
end
local function isSelectable(entity)
return entity.player == self.logicCore.players[1] and entity.selectable
end
local position = GameMath.Vector2:new(x, y) - self.translate
local entityManager = self.logicCore.entityManager
local logicCore = self.logicCore
if button == "l" then
if self.mode == "build" then
local building = self.logicCore.entityManager:spawnFromEntityStatic(EntityStatics.spawnPortal, logicCore.players[1])
building:setPosition(position.x, position.y)
self:selectEntity(building.id)
self.mode = false
else
local entity, distance = entityManager:findClosestEntity(position, isSelectable)
self:selectEntity(entity and distance < 40 and entity.id)
end
elseif button == "r" then
if self.selection then
local entity = entityManager:entity(self.selection)
if self.mode ~= "path" then
self:setMode("path")
end
entity:addPathPoint(position)
end
end
end
function InputHandler:setMode(mode)
local entityManager = self.logicCore.entityManager
if mode == "path" then
local entity = entityManager:entity(self.selection)
entity:clearPath()
end
self.mode = mode
end
function InputHandler:keyPressed(key, unicode)
end
function InputHandler:selectEntity(entityId)
if self.selection ~= entityId then
self:setMode("selected")
self.selection = entityId
end
end
return InputHandler
|
local Class = require "shared.middleclass"
local GameMath = require "shared.gamemath"
local InputHandler = Class "InputHandler"
local EntityStatics = require "hymn.staticdata.entitystatics"
function InputHandler:initialize(logicCore)
self.logicCore = logicCore
self.translate = GameMath.Vector2:new(0, 0)
end
local borderWidth = 20
local scrollSpeed = 2000
function InputHandler:update(dt)
local width, height = love.graphics.getDimensions()
local x, y = love.mouse.getPosition()
-- border scrolling
if x < borderWidth then
self.translate.x = self.translate.x + scrollSpeed * dt
elseif x > width - borderWidth then
self.translate.x = self.translate.x - scrollSpeed * dt
end
if y < borderWidth then
self.translate.y = self.translate.y + scrollSpeed * dt
elseif y > height - borderWidth then
self.translate.y = self.translate.y - scrollSpeed * dt
end
-- dragging
if self.dragAnchor then
-- dbgprint
self.translate.x = x - self.dragAnchor.x
self.translate.y = y - self.dragAnchor.y
end
local w, h = self.logicCore.map:size()
self.translate.x = GameMath.clamp(self.translate.x, -w + width, 0)
self.translate.y = GameMath.clamp(self.translate.y, -h + height, 0)
end
function InputHandler:centerOn(x, y)
local width, height = love.graphics.getDimensions()
self.translate.x = -x + width/2
self.translate.y = -y + height/2
end
-- click-through prevention. sucky, sucky Quickie! ;)
function InputHandler:isToolBar(x, y)
local width, height = love.graphics.getDimensions()
return y > height - 50
end
function InputHandler:mousePressed(x, y, button)
if self:isToolBar(x, y) then
return
end
if button == "l" then
local position = GameMath.Vector2:new(x, y) - self.translate
self.dragClick = GameMath.Vector2:new(x, y)
self.dragAnchor = position
end
end
function InputHandler:mouseReleased(x, y, button)
if self.dragAnchor then
local d = GameMath.Vector2.distance(GameMath.Vector2:new(x,y), self.dragClick)
self.dragAnchor = false
if d > 5 then
return
end
end
if self:isToolBar(x, y) then
return
end
local function isSelectable(entity)
return entity.player == self.logicCore.players[1] and entity.selectable
end
local position = GameMath.Vector2:new(x, y) - self.translate
local entityManager = self.logicCore.entityManager
local logicCore = self.logicCore
if button == "l" then
if self.mode == "build" then
local building = self.logicCore.entityManager:spawnFromEntityStatic(EntityStatics.spawnPortal, logicCore.players[1])
building:setPosition(position.x, position.y)
self:selectEntity(building.id)
self.mode = false
else
local entity, distance = entityManager:findClosestEntity(position, isSelectable)
self:selectEntity(entity and distance < 40 and entity.id)
end
elseif button == "r" then
if self.selection then
local entity = entityManager:entity(self.selection)
if self.mode ~= "path" then
self:setMode("path")
end
entity:addPathPoint(position)
end
end
end
function InputHandler:setMode(mode)
local entityManager = self.logicCore.entityManager
if mode == "path" then
local entity = entityManager:entity(self.selection)
if entity then
entity:clearPath()
end
end
self.mode = mode
end
function InputHandler:keyPressed(key, unicode)
end
function InputHandler:selectEntity(entityId)
if self.selection ~= entityId then
self:setMode("selected")
self.selection = entityId
end
end
return InputHandler
|
Fix: Possible crash when deselecting
|
Fix: Possible crash when deselecting
|
Lua
|
mit
|
ExcelF/project-navel
|
7358a06ba23b42abb133cbc548666e0caa79a095
|
src/pf/lang.lua
|
src/pf/lang.lua
|
module("pf.lang",package.seeall)
local function skip_whitespace(str, pos)
while pos <= #str and str:match('^%s', pos) do
pos = pos + 1
end
return pos
end
local punctuation = {
'(', ')', '[', ']', '!', '!=', '<', '<=', '>', '>=', '=',
'+', '-', '*', '/', '%', '&', '|', '^', '&&', '||', '<<', '>>'
}
for k, v in ipairs(punctuation) do
punctuation[v] = true
end
local function lex_host_or_keyword(str, pos)
local name, next_pos = str:match("^([%w.-]+)()", pos)
assert(name, "failed to parse hostname or keyword at "..pos)
assert(name:match("^%w", 1, 1), "bad hostname or keyword "..name)
assert(name:match("^%w", #name, #name), "bad hostname or keyword "..name)
return tonumber(name, 10) or name, next_pos
end
local function lex_ipv4_or_host(str, pos)
local function lex_byte(str)
local byte = tonumber(str, 10)
if byte >= 256 then return nil end
return byte
end
local digits, dot = str:match("^(%d%d?%d?)()%.", pos)
if not digits then return lex_host_or_keyword(str, start_pos) end
local addr = { type='ipv4' }
local byte = lex_byte(digits)
if not byte then return lex_host_or_keyword(str, pos) end
table.insert(addr, byte)
pos = dot
for i=1,3 do
local digits, dot = str:match("^%.(%d%d?%d?)()", pos)
if not digits then break end
table.insert(addr, assert(lex_byte(digits), "failed to parse ipv4 addr"))
pos = dot
end
local terminators = " \t\r\n)/"
assert(pos > #str or terminators:find(str:sub(pos, pos), 1, true),
"unexpected terminator for ipv4 address")
return addr, pos
end
local function lex_ipv6(str, pos)
local addr = { type='ipv6' }
-- FIXME: Currently only supporting fully-specified IPV6 names.
local digits, dot = str:match("^(%x%x?)()%:", pos)
assert(digits, "failed to parse ipv6 address at "..pos)
table.insert(addr, tonumber(digits, 16))
pos = dot
for i=1,15 do
local digits, dot = str:match("^%:(%x%x?)()", pos)
assert(digits, "failed to parse ipv6 address at "..pos)
table.insert(addr, tonumber(digits, 16))
pos = dot
end
local terminators = " \t\r\n)/"
assert(pos > #str or terminators:find(str:sub(pos, pos), 1, true),
"unexpected terminator for ipv6 address")
return addr, pos
end
local function lex_addr(str, pos)
local start_pos = pos
if str:match("^%d%d?%d?%.", pos) then
return lex_ipv4_or_host(str, pos)
elseif str:match("^%x?%x?%:", pos) then
return lex_ipv6(str, pos)
else
return lex_host_or_keyword(str, pos)
end
end
local number_terminators = " \t\r\n)]!<>=+-*/%&|^"
local function lex_number(str, pos, base)
local res = 0
local i = pos
while i <= #str do
local chr = str:sub(i,i)
local n = tonumber(chr, base)
if n then
res = res * base + n
i = i + 1
elseif str:match("^[%a_.]", i) then
return nil, i
else
return res, i
end
end
return res, i -- EOS
end
local function lex_hex(str, pos)
local ret, next_pos = lex_number(str, pos, 16)
assert(ret, "unexpected end of hex literal at "..pos)
return ret, next_pos
end
local function lex_octal_or_addr(str, pos, in_brackets)
local ret, next_pos = lex_number(str, pos, 8)
if not ret then
if in_brackets then return lex_host_or_keyword(str, pos) end
return lex_addr(str, pos)
end
return ret, next_pos
end
local function lex_decimal_or_addr(str, pos, in_brackets)
local ret, next_pos = lex_number(str, pos, 10)
if not ret then
if in_brackets then return lex_host_or_keyword(str, pos) end
return lex_addr(str, pos)
end
return ret, next_pos
end
local function lex(str, pos, opts, in_brackets)
-- EOF.
if pos > #str then return nil, pos end
-- Non-alphanumeric tokens.
local two = str:sub(pos,pos+1)
if punctuation[two] then return two, pos+2 end
local one = str:sub(pos,pos)
if punctuation[one] then return one, pos+1 end
if in_brackets and one == ':' then return one, pos+1 end
-- Numeric literals or net addresses.
if opts.maybe_arithmetic and one:match('^%d') then
if two == ('0x') then
return lex_hex(str, pos+2)
elseif two:match('^0%d') then
return lex_octal_or_addr(str, pos, in_brackets)
else
return lex_decimal_or_addr(str, pos, in_brackets)
end
end
-- IPV6 net address beginning with [a-fA-F].
if not in_brackets and str:match('^%x?%x?%:', pos) then
return lex_ipv6(str, pos)
end
-- "len" is the only bare name that can appear in an arithmetic
-- expression. "len-1" lexes as { 'len', '-', 1 } in arithmetic
-- contexts, but { "len-1" } otherwise.
if opts.maybe_arithmetic and str:match("^len", pos) then
if pos + 3 > #str or not str:match("^[%w.]", pos+3) then
return 'len', pos+3
end
end
-- Keywords or hostnames.
return lex_host_or_keyword(str, pos)
end
function tokens(str)
local pos, next_pos = 1, nil
local peeked = nil
local brackets = 0
local function peek(opts)
if not next_pos then
pos = skip_whitespace(str, pos)
peeked, next_pos = lex(str, pos, opts or {}, brackets > 0)
if peeked == '[' then brackets = brackets + 1 end
if peeked == ']' then brackets = brackets - 1 end
assert(next_pos, "next pos is nil")
end
return peeked
end
local function next(opts)
local tok = assert(peek(opts), "unexpected end of filter string")
pos, next_pos = next_pos, nil
return tok
end
return { peek = peek, next = next }
end
function compile(str)
local ast = parse(str)
end
function selftest ()
print("selftest: pf.lang")
local function lex_test(str, elts, opts)
local lexer = tokens(str)
for i, val in pairs(elts) do
local tok = lexer.next(opts)
assert(tok == val, "expected "..val.." but got "..tok)
end
assert(not lexer.peek(opts), "more tokens, yo")
end
lex_test("ip", {"ip"}, {maybe_arithmetic=true})
lex_test("len", {"len"}, {maybe_arithmetic=true})
lex_test("len", {"len"}, {})
lex_test("len-1", {"len-1"}, {})
lex_test("len-1", {"len", "-", 1}, {maybe_arithmetic=true})
lex_test("tcp port 80", {"tcp", "port", 80}, {})
lex_test("tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)",
{ 'tcp', 'port', 80, 'and',
'(', '(',
'(',
'ip', '[', 2, ':', 2, ']', '-',
'(', '(', 'ip', '[', 0, ']', '&', 15, ')', '<<', 2, ')',
')',
'-',
'(', '(', 'tcp', '[', 12, ']', '&', 240, ')', '>>', 2, ')',
')', '!=', 0, ')'
}, {maybe_arithmetic=true})
print("OK")
end
|
module("pf.lang",package.seeall)
local function skip_whitespace(str, pos)
while pos <= #str and str:match('^%s', pos) do
pos = pos + 1
end
return pos
end
local punctuation = {}
do
local ops = {
'(', ')', '[', ']', '!', '!=', '<', '<=', '>', '>=', '=',
'+', '-', '*', '/', '%', '&', '|', '^', '&&', '||', '<<', '>>'
}
for k, v in pairs(ops) do punctuation[v] = true end
end
local function lex_host_or_keyword(str, pos)
local name, next_pos = str:match("^([%w.-]+)()", pos)
assert(name, "failed to parse hostname or keyword at "..pos)
assert(name:match("^%w", 1, 1), "bad hostname or keyword "..name)
assert(name:match("^%w", #name, #name), "bad hostname or keyword "..name)
return tonumber(name, 10) or name, next_pos
end
local function lex_ipv4_or_host(str, pos)
local function lex_byte(str)
local byte = tonumber(str, 10)
if byte >= 256 then return nil end
return byte
end
local digits, dot = str:match("^(%d%d?%d?)()%.", pos)
if not digits then return lex_host_or_keyword(str, start_pos) end
local addr = { type='ipv4' }
local byte = lex_byte(digits)
if not byte then return lex_host_or_keyword(str, pos) end
table.insert(addr, byte)
pos = dot
for i=1,3 do
local digits, dot = str:match("^%.(%d%d?%d?)()", pos)
if not digits then break end
table.insert(addr, assert(lex_byte(digits), "failed to parse ipv4 addr"))
pos = dot
end
local terminators = " \t\r\n)/"
assert(pos > #str or terminators:find(str:sub(pos, pos), 1, true),
"unexpected terminator for ipv4 address")
return addr, pos
end
local function lex_ipv6(str, pos)
local addr = { type='ipv6' }
-- FIXME: Currently only supporting fully-specified IPV6 names.
local digits, dot = str:match("^(%x%x?)()%:", pos)
assert(digits, "failed to parse ipv6 address at "..pos)
table.insert(addr, tonumber(digits, 16))
pos = dot
for i=1,15 do
local digits, dot = str:match("^%:(%x%x?)()", pos)
assert(digits, "failed to parse ipv6 address at "..pos)
table.insert(addr, tonumber(digits, 16))
pos = dot
end
local terminators = " \t\r\n)/"
assert(pos > #str or terminators:find(str:sub(pos, pos), 1, true),
"unexpected terminator for ipv6 address")
return addr, pos
end
local function lex_addr(str, pos)
local start_pos = pos
if str:match("^%d%d?%d?%.", pos) then
return lex_ipv4_or_host(str, pos)
elseif str:match("^%x?%x?%:", pos) then
return lex_ipv6(str, pos)
else
return lex_host_or_keyword(str, pos)
end
end
local number_terminators = " \t\r\n)]!<>=+-*/%&|^"
local function lex_number(str, pos, base)
local res = 0
local i = pos
while i <= #str do
local chr = str:sub(i,i)
local n = tonumber(chr, base)
if n then
res = res * base + n
i = i + 1
elseif str:match("^[%a_.]", i) then
return nil, i
else
return res, i
end
end
return res, i -- EOS
end
local function lex_hex(str, pos)
local ret, next_pos = lex_number(str, pos, 16)
assert(ret, "unexpected end of hex literal at "..pos)
return ret, next_pos
end
local function lex_octal_or_addr(str, pos, in_brackets)
local ret, next_pos = lex_number(str, pos, 8)
if not ret then
if in_brackets then return lex_host_or_keyword(str, pos) end
return lex_addr(str, pos)
end
return ret, next_pos
end
local function lex_decimal_or_addr(str, pos, in_brackets)
local ret, next_pos = lex_number(str, pos, 10)
if not ret then
if in_brackets then return lex_host_or_keyword(str, pos) end
return lex_addr(str, pos)
end
return ret, next_pos
end
local function lex(str, pos, opts, in_brackets)
-- EOF.
if pos > #str then return nil, pos end
-- Non-alphanumeric tokens.
local two = str:sub(pos,pos+1)
if punctuation[two] then return two, pos+2 end
local one = str:sub(pos,pos)
if punctuation[one] then return one, pos+1 end
if in_brackets and one == ':' then return one, pos+1 end
-- Numeric literals or net addresses.
if opts.maybe_arithmetic and one:match('^%d') then
if two == ('0x') then
return lex_hex(str, pos+2)
elseif two:match('^0%d') then
return lex_octal_or_addr(str, pos, in_brackets)
else
return lex_decimal_or_addr(str, pos, in_brackets)
end
end
-- IPV6 net address beginning with [a-fA-F].
if not in_brackets and str:match('^%x?%x?%:', pos) then
return lex_ipv6(str, pos)
end
-- "len" is the only bare name that can appear in an arithmetic
-- expression. "len-1" lexes as { 'len', '-', 1 } in arithmetic
-- contexts, but { "len-1" } otherwise.
if opts.maybe_arithmetic and str:match("^len", pos) then
if pos + 3 > #str or not str:match("^[%w.]", pos+3) then
return 'len', pos+3
end
end
-- Keywords or hostnames.
return lex_host_or_keyword(str, pos)
end
function tokens(str)
local pos, next_pos = 1, nil
local peeked = nil
local brackets = 0
local function peek(opts)
if not next_pos then
pos = skip_whitespace(str, pos)
peeked, next_pos = lex(str, pos, opts or {}, brackets > 0)
if peeked == '[' then brackets = brackets + 1 end
if peeked == ']' then brackets = brackets - 1 end
assert(next_pos, "next pos is nil")
end
return peeked
end
local function next(opts)
local tok = assert(peek(opts), "unexpected end of filter string")
pos, next_pos = next_pos, nil
return tok
end
return { peek = peek, next = next }
end
function compile(str)
local ast = parse(str)
end
function selftest ()
print("selftest: pf.lang")
local function lex_test(str, elts, opts)
local lexer = tokens(str)
for i, val in pairs(elts) do
local tok = lexer.next(opts)
assert(tok == val, "expected "..val.." but got "..tok)
end
assert(not lexer.peek(opts), "more tokens, yo")
end
lex_test("ip", {"ip"}, {maybe_arithmetic=true})
lex_test("len", {"len"}, {maybe_arithmetic=true})
lex_test("len", {"len"}, {})
lex_test("len-1", {"len-1"}, {})
lex_test("len-1", {"len", "-", 1}, {maybe_arithmetic=true})
lex_test("tcp port 80", {"tcp", "port", 80}, {})
lex_test("tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)",
{ 'tcp', 'port', 80, 'and',
'(', '(',
'(',
'ip', '[', 2, ':', 2, ']', '-',
'(', '(', 'ip', '[', 0, ']', '&', 15, ')', '<<', 2, ')',
')',
'-',
'(', '(', 'tcp', '[', 12, ']', '&', 240, ')', '>>', 2, ')',
')', '!=', 0, ')'
}, {maybe_arithmetic=true})
print("OK")
end
|
Fix punctuation table
|
Fix punctuation table
* src/pf/lang.lua: Fix punctuation table to not contain integers.
|
Lua
|
apache-2.0
|
mpeterv/pflua,SnabbCo/pflua
|
49be4b7f1a762b1cdaa203828f1ff8f4e213d4b6
|
interface/configenv/packet.lua
|
interface/configenv/packet.lua
|
local Dynvars = require "configenv.dynvars"
local Packet = {}
function Packet.new(proto, tbl, error)
local self = {
proto = proto,
fillTbl = {},
dynvars = Dynvars.new()
}
for i,v in pairs(tbl) do
local pkt, var = string.match(i, "^([%l%d]+)(%u[%l%d]*)$");
if pkt then
if type(v) == "function" then
var = string.lower(var)
v = self.dynvars:add(pkt, var, v).value
end
self.fillTbl[i] = v
else
error("Invalid packet field %q. Format is 'layerField' (e.g. ip4Dst).", i)
end
end
return setmetatable(self, { __index = Packet })
end
function Packet:inherit(other)
if other then
for i,v in pairs(other.fillTbl) do
if not self.fillTbl[i] then
self.fillTbl[i] = v
end
end
self.dynvars:inherit(other.dynvars)
end
return self
end
function Packet:size()
return self.fillTbl.pktLength
end
function Packet:prepare()
self.dynvars:finalize()
end
function Packet:validate(val)
val:assert(type(self.fillTbl.pktLength) == "number",
"Packet field pktLength has to be set to a valid number.")
end
return Packet
|
local Dynvars = require "configenv.dynvars"
local Packet = {}
function Packet.new(proto, tbl, error)
local self = {
proto = proto,
fillTbl = {},
dynvars = Dynvars.new()
}
for i,v in pairs(tbl) do
local pkt, var = string.match(i, "^([%l%d]+)(%u[%l%d]*)$");
if pkt then
if type(v) == "function" then
var = string.lower(var)
v = self.dynvars:add(pkt, var, v).value
end
self.fillTbl[i] = v
else
error("Invalid packet field %q. Format is 'layerField' (e.g. ip4Dst).", i)
end
end
return setmetatable(self, { __index = Packet })
end
function Packet:inherit(other)
if other then
for i,v in pairs(other.fillTbl) do
if not self.fillTbl[i] then
self.fillTbl[i] = v
end
end
self.dynvars:inherit(other.dynvars)
end
return self
end
function Packet:size()
return self.fillTbl.pktLength
end
function Packet:prepare()
if not self.prepared then
self.dynvars:finalize()
self.prepared = true
end
end
function Packet:validate(val)
val:assert(type(self.fillTbl.pktLength) == "number",
"Packet field pktLength has to be set to a valid number.")
end
return Packet
|
Fix inability to instance one flow twice.
|
Fix inability to instance one flow twice.
|
Lua
|
mit
|
gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,emmericp/MoonGen,scholzd/MoonGen,dschoeffm/MoonGen,dschoeffm/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,emmericp/MoonGen
|
4cccaa0b93b665768e314bb0387cfd9eef03eb0c
|
lua/include/stats.lua
|
lua/include/stats.lua
|
local mod = {}
local dpdk = require "dpdk"
local device = require "device"
function mod.average(data)
local sum = 0
for i, v in ipairs(data) do
sum = sum + v
end
return sum / #data
end
function mod.median(data)
return mod.percentile(data, 50)
end
function mod.percentile(data, p)
local sortedData = { }
for k, v in ipairs(data) do
sortedData[k] = v
end
table.sort(sortedData)
return data[math.ceil(#data * p / 100)]
end
function mod.stdDev(data)
local avg = mod.average(data)
local sum = 0
for i, v in ipairs(data) do
sum = sum + (v - avg) ^ 2
end
return (sum / (#data - 1)) ^ 0.5
end
function mod.addStats(data, ignoreFirstAndLast)
local copy = { }
for i = 2, #data - 1 do
copy[i - 1] = data[i]
end
data.avg = mod.average(copy)
data.stdDev = mod.stdDev(copy)
data.median = mod.median(copy)
end
local function getPlainUpdate(direction)
return function(stats, file, total, mpps, mbit, wireMbit)
file:write(("%s %s %d packets, current rate %.2f Mpps, %.2f MBit/s, %.2f MBit/s wire rate.\n"):format(stats.dev, direction, total, mpps, mbit, wireMbit))
file:flush()
end
end
local function getPlainFinal(direction)
return function(stats, file)
file:write(("%s %s %d packets with %d bytes payload (including CRC).\n"):format(stats.dev, direction, stats.total, stats.totalBytes))
file:write(("%s %s %f (StdDev %f) Mpps, %f (StdDev %f) MBit/s, %f (StdDev %f) MBit/s wire rate on average.\n"):format(
stats.dev, direction,
stats.mpps.avg, stats.mpps.stdDev,
stats.mbit.avg, stats.mbit.stdDev,
stats.wireMbit.avg, stats.wireMbit.stdDev
))
file:flush()
end
end
local formatters = {}
formatters["plain"] = {
rxStatsInit = function() end, -- nothing for plain, machine-readable formats can print a header here
rxStatsUpdate = getPlainUpdate("Received"),
rxStatsFinal = getPlainFinal("Received"),
txStatsInit = function() end,
txStatsUpdate = getPlainUpdate("Sent"),
txStatsFinal = getPlainFinal("Sent"),
}
formatters["CSV"] = formatters["plain"] -- TODO
-- base 'class' for rx and tx counters
local function newCounter(dev, pktSize, format, file)
if type(dev) == "table" then
-- case 1: (device, format, file)
return newCounter(dev, nil, pktSize, format)
end -- else: (description, size, format, file)
if type(dev) == "table" and dev.qid then
-- device is a queue, use the queue's device instead
-- TODO: per-queue statistics (tricky as the abstraction in DPDK sucks)
dev = dev.dev
end
file = file or io.stdout
local closeFile = false
if type(file) == "string" then
file = io.open("w+")
closeFile = true
end
format = format or "CSV"
if not formatters[format] then
error("unsupported output format " .. format)
end
return {
dev = dev,
pktSize = pktSize,
format = format or "CSV",
file = file,
closeFile = closeFile,
total = 0,
totalBytes = 0,
manualPkts = 0,
mpps = {},
mbit = {},
wireMbit = {},
}, type(dev) ~= "table"
end
local function printStats(self, statsType, event, ...)
local func = formatters[self.format][statsType .. event]
if func then
func(self, self.file, ...)
else
print("[Missing formatter for " .. self.format .. "]", self.dev, statsType, event, ...)
end
end
local function updateCounter(self, time, pkts, bytes)
if not self.lastUpdate then
-- very first call, save current stats but do not print anything
self.total, self.totalBytes = pkts, bytes
self.lastTotal = self.total
self.lastTotalBytes = self.totalBytes
self.lastUpdate = time
self:print("Init")
return
end
local elapsed = time - self.lastUpdate
self.lastUpdate = time
self.total = self.total + pkts
self.totalBytes = self.totalBytes + bytes
local mpps = (self.total - self.lastTotal) / elapsed / 10^6
local mbit = (self.totalBytes - self.lastTotalBytes) / elapsed / 10^6 * 8
local wireRate = mbit + (mpps * 20 * 8)
self:print("Update", self.total, mpps, mbit, wireRate)
table.insert(self.mpps, mpps)
table.insert(self.mbit, mbit)
table.insert(self.wireMbit, wireRate)
self.lastTotal = self.total
self.lastTotalBytes = self.totalBytes
end
local function finalizeCounter(self)
mod.addStats(self.mpps, true)
mod.addStats(self.mbit, true)
mod.addStats(self.wireMbit, true)
self:print("Final")
if self.closeFile then
self.file:close()
end
end
local rxCounter = {}
rxCounter.__index = rxCounter
--- Create a new rx counter
-- @param dev the device to track
-- @param format the output format, "CSV" (default) and "plain" are currently supported
-- @param file the output file, defaults to standard out
function mod:newRxCounter(...)
local obj, isManual = newCounter(...)
if isManual then
obj.update = rxCounter.updateManual
end
return setmetatable(obj, rxCounter)
end
function rxCounter:update()
local time = dpdk.getTime()
if self.lastUpdate and time <= self.lastUpdate + 1 then
return
end
local pkts, bytes = self.dev:getRxStats()
updateCounter(self, time, pkts, bytes)
end
function rxCounter:updateManual(pkts)
self.manualPkts = self.manualPkts + pkts
local time = dpdk.getTime()
if self.lastUpdate and time <= self.lastUpdate + 1 then
return
end
local pkts, bytes = self.manualPkts, self.manualPkts * (self.pktSize + 4)
updateCounter(self, time, pkts, bytes)
end
function rxCounter:print(event, ...)
printStats(self, "rxStats", event, ...)
end
function rxCounter:finalize()
finalizeCounter(self)
end
local txCounter = {}
txCounter.__index = txCounter
--- Create a new rx counter
-- FIXME: this is slightly off when using queue:sendWithDelay() (error seems to be below 0.5%)
-- @param dev the device to track
-- @param format the output format, "CSV" (default) and "plain" are currently supported
-- @param file the file to write to, defaults to standard out
function mod:newTxCounter(...)
local obj, isManual = newCounter(...)
if isManual then
obj.update = txCounter.updateManual
end
return setmetatable(obj, txCounter)
end
function txCounter:update()
local time = dpdk.getTime()
if self.lastUpdate and time <= self.lastUpdate + 1 then
return
end
local pkts, bytes = self.dev:getTxStats()
updateCounter(self, time, pkts, bytes)
end
function txCounter:updateManual(pkts)
self.manualPkts = self.manualPkts + pkts
local time = dpdk.getTime()
if self.lastUpdate and time <= self.lastUpdate + 1 then
return
end
local pkts, bytes = self.manualPkts, self.manualPkts * (self.pktSize + 4)
self.manualPkts = 0
updateCounter(self, time, pkts, bytes)
end
function txCounter:print(event, ...)
printStats(self, "txStats", event, ...)
end
function txCounter:finalize()
finalizeCounter(self)
end
return mod
|
local mod = {}
local dpdk = require "dpdk"
local device = require "device"
function mod.average(data)
local sum = 0
for i, v in ipairs(data) do
sum = sum + v
end
return sum / #data
end
function mod.median(data)
return mod.percentile(data, 50)
end
function mod.percentile(data, p)
local sortedData = { }
for k, v in ipairs(data) do
sortedData[k] = v
end
table.sort(sortedData)
return data[math.ceil(#data * p / 100)]
end
function mod.stdDev(data)
local avg = mod.average(data)
local sum = 0
for i, v in ipairs(data) do
sum = sum + (v - avg) ^ 2
end
return (sum / (#data - 1)) ^ 0.5
end
function mod.addStats(data, ignoreFirstAndLast)
local copy = { }
if ignoreFirstAndLast then
for i = 2, #data - 1 do
copy[i - 1] = data[i]
end
else
for i = 1, #data do
copy[i] = data[i]
end
end
data.avg = mod.average(copy)
data.stdDev = mod.stdDev(copy)
data.median = mod.median(copy)
end
local function getPlainUpdate(direction)
return function(stats, file, total, mpps, mbit, wireMbit)
file:write(("%s %s %d packets, current rate %.2f Mpps, %.2f MBit/s, %.2f MBit/s wire rate.\n"):format(stats.dev, direction, total, mpps, mbit, wireMbit))
file:flush()
end
end
local function getPlainFinal(direction)
return function(stats, file)
file:write(("%s %s %d packets with %d bytes payload (including CRC).\n"):format(stats.dev, direction, stats.total, stats.totalBytes))
file:write(("%s %s %f (StdDev %f) Mpps, %f (StdDev %f) MBit/s, %f (StdDev %f) MBit/s wire rate on average.\n"):format(
stats.dev, direction,
stats.mpps.avg, stats.mpps.stdDev,
stats.mbit.avg, stats.mbit.stdDev,
stats.wireMbit.avg, stats.wireMbit.stdDev
))
file:flush()
end
end
local formatters = {}
formatters["plain"] = {
rxStatsInit = function() end, -- nothing for plain, machine-readable formats can print a header here
rxStatsUpdate = getPlainUpdate("Received"),
rxStatsFinal = getPlainFinal("Received"),
txStatsInit = function() end,
txStatsUpdate = getPlainUpdate("Sent"),
txStatsFinal = getPlainFinal("Sent"),
}
formatters["CSV"] = formatters["plain"] -- TODO
-- base 'class' for rx and tx counters
local function newCounter(dev, pktSize, format, file)
if type(dev) == "table" then
-- case 1: (device, format, file)
return newCounter(dev, nil, pktSize, format)
end -- else: (description, size, format, file)
if type(dev) == "table" and dev.qid then
-- device is a queue, use the queue's device instead
-- TODO: per-queue statistics (tricky as the abstraction in DPDK sucks)
dev = dev.dev
end
file = file or io.stdout
local closeFile = false
if type(file) == "string" then
file = io.open("w+")
closeFile = true
end
format = format or "CSV"
if not formatters[format] then
error("unsupported output format " .. format)
end
return {
dev = dev,
pktSize = pktSize,
format = format or "CSV",
file = file,
closeFile = closeFile,
total = 0,
totalBytes = 0,
manualPkts = 0,
mpps = {},
mbit = {},
wireMbit = {},
}, type(dev) ~= "table"
end
local function printStats(self, statsType, event, ...)
local func = formatters[self.format][statsType .. event]
if func then
func(self, self.file, ...)
else
print("[Missing formatter for " .. self.format .. "]", self.dev, statsType, event, ...)
end
end
local function updateCounter(self, time, pkts, bytes)
if not self.lastUpdate then
-- very first call, save current stats but do not print anything
self.total, self.totalBytes = pkts, bytes
self.lastTotal = self.total
self.lastTotalBytes = self.totalBytes
self.lastUpdate = time
self:print("Init")
return
end
local elapsed = time - self.lastUpdate
self.lastUpdate = time
self.total = self.total + pkts
self.totalBytes = self.totalBytes + bytes
local mpps = (self.total - self.lastTotal) / elapsed / 10^6
local mbit = (self.totalBytes - self.lastTotalBytes) / elapsed / 10^6 * 8
local wireRate = mbit + (mpps * 20 * 8)
self:print("Update", self.total, mpps, mbit, wireRate)
table.insert(self.mpps, mpps)
table.insert(self.mbit, mbit)
table.insert(self.wireMbit, wireRate)
self.lastTotal = self.total
self.lastTotalBytes = self.totalBytes
end
local function finalizeCounter(self)
mod.addStats(self.mpps, true)
mod.addStats(self.mbit, true)
mod.addStats(self.wireMbit, true)
self:print("Final")
if self.closeFile then
self.file:close()
end
end
local rxCounter = {}
rxCounter.__index = rxCounter
--- Create a new rx counter
-- @param dev the device to track
-- @param format the output format, "CSV" (default) and "plain" are currently supported
-- @param file the output file, defaults to standard out
function mod:newRxCounter(...)
local obj, isManual = newCounter(...)
if isManual then
obj.update = rxCounter.updateManual
end
return setmetatable(obj, rxCounter)
end
function rxCounter:update()
local time = dpdk.getTime()
if self.lastUpdate and time <= self.lastUpdate + 1 then
return
end
local pkts, bytes = self.dev:getRxStats()
updateCounter(self, time, pkts, bytes)
end
function rxCounter:updateManual(pkts)
self.manualPkts = self.manualPkts + pkts
local time = dpdk.getTime()
if self.lastUpdate and time <= self.lastUpdate + 1 then
return
end
local pkts, bytes = self.manualPkts, self.manualPkts * (self.pktSize + 4)
updateCounter(self, time, pkts, bytes)
end
function rxCounter:print(event, ...)
printStats(self, "rxStats", event, ...)
end
function rxCounter:finalize()
finalizeCounter(self)
end
local txCounter = {}
txCounter.__index = txCounter
--- Create a new rx counter
-- FIXME: this is slightly off when using queue:sendWithDelay() (error seems to be below 0.5%)
-- @param dev the device to track
-- @param format the output format, "CSV" (default) and "plain" are currently supported
-- @param file the file to write to, defaults to standard out
function mod:newTxCounter(...)
local obj, isManual = newCounter(...)
if isManual then
obj.update = txCounter.updateManual
end
return setmetatable(obj, txCounter)
end
function txCounter:update()
local time = dpdk.getTime()
if self.lastUpdate and time <= self.lastUpdate + 1 then
return
end
local pkts, bytes = self.dev:getTxStats()
updateCounter(self, time, pkts, bytes)
end
function txCounter:updateManual(pkts)
self.manualPkts = self.manualPkts + pkts
local time = dpdk.getTime()
if self.lastUpdate and time <= self.lastUpdate + 1 then
return
end
local pkts, bytes = self.manualPkts, self.manualPkts * (self.pktSize + 4)
self.manualPkts = 0
updateCounter(self, time, pkts, bytes)
end
function txCounter:print(event, ...)
printStats(self, "txStats", event, ...)
end
function txCounter:finalize()
finalizeCounter(self)
end
return mod
|
fix ignoreFirstAndLast parameter
|
fix ignoreFirstAndLast parameter
|
Lua
|
mit
|
slyon/MoonGen,dschoeffm/MoonGen,emmericp/MoonGen,wenhuizhang/MoonGen,werpat/MoonGen,gallenmu/MoonGen,pavel-odintsov/MoonGen,dschoeffm/MoonGen,atheurer/MoonGen,bmichalo/MoonGen,NetronomeMoongen/MoonGen,wenhuizhang/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,duk3luk3/MoonGen,schoenb/MoonGen,werpat/MoonGen,scholzd/MoonGen,duk3luk3/MoonGen,atheurer/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,kidaa/MoonGen,pavel-odintsov/MoonGen,bmichalo/MoonGen,pavel-odintsov/MoonGen,gallenmu/MoonGen,kidaa/MoonGen,slyon/MoonGen,scholzd/MoonGen,atheurer/MoonGen,slyon/MoonGen,NetronomeMoongen/MoonGen,NetronomeMoongen/MoonGen,dschoeffm/MoonGen,kidaa/MoonGen,emmericp/MoonGen,schoenb/MoonGen,duk3luk3/MoonGen,gallenmu/MoonGen,werpat/MoonGen,gallenmu/MoonGen,wenhuizhang/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,schoenb/MoonGen,slyon/MoonGen,bmichalo/MoonGen
|
70a0bd1826f9907e897f04c6b4f13809da77b2b9
|
vanilla/v/request.lua
|
vanilla/v/request.lua
|
-- Request moudle
-- @since 2015-08-17 10:54
-- @author idevz <[email protected]>
-- version $Id$
-- perf
local error = error
local pairs = pairs
local setmetatable = setmetatable
local Reqargs = require 'vanilla.v.libs.reqargs'
local Request = {}
function Request:new()
-- local headers = ngx.req.get_headers()
-- url:http://zj.com:9210/di0000/111?aa=xx
local instance = {
uri = ngx.var.uri, -- /di0000/111
-- req_uri = ngx.var.request_uri, -- /di0000/111?aa=xx
-- req_args = ngx.var.args, -- aa=xx
-- params = params,
-- uri_args = ngx.req.get_uri_args(), -- { aa = "xx" }
-- method = ngx.req.get_method(),
-- headers = headers,
-- body_raw = ngx.req.get_body_data()
}
setmetatable(instance, {__index = self})
return instance
end
function Request:getControllerName()
return self.controller_name
end
function Request:getActionName()
return self.action_name
end
function Request:getHeaders()
local headers = self.headers or ngx.req.get_headers()
return headers
end
function Request:getHeader(key)
local headers = self.headers or ngx.req.get_headers()
if headers[key] ~= nil then
return headers[key]
else
return false
end
end
function Request:buildParams()
local GET, POST, FILE = Reqargs:getRequestData({})
local params = GET
if #POST >= 1 then for k,v in pairs(POST) do params[k] = v end end
if #FILE >= 1 then params['VA_FILE']=FILE end
self.params = params
return self.params
end
function Request:getParams()
return self.params or self:buildParams()
end
function Request:getParam(key)
return self.params[key] or self:buildParams()[key]
end
function Request:setParam(key, value)
self.params[key] = value
end
function Request:getMethod()
local method = self.method or ngx.req.get_method()
return method
end
function Request:isGet()
if self.method == 'GET' then return true else return false end
end
return Request
|
-- Request moudle
-- @since 2015-08-17 10:54
-- @author idevz <[email protected]>
-- version $Id$
-- perf
local error = error
local pairs = pairs
local pcall = pcall
local setmetatable = setmetatable
local Reqargs = require 'vanilla.v.libs.reqargs'
local Request = {}
function Request:new()
-- local headers = ngx.req.get_headers()
-- url:http://zj.com:9210/di0000/111?aa=xx
local instance = {
uri = ngx.var.uri, -- /di0000/111
-- req_uri = ngx.var.request_uri, -- /di0000/111?aa=xx
-- req_args = ngx.var.args, -- aa=xx
-- params = params,
-- uri_args = ngx.req.get_uri_args(), -- { aa = "xx" }
-- method = ngx.req.get_method(),
-- headers = headers,
-- body_raw = ngx.req.get_body_data()
}
setmetatable(instance, {__index = self})
return instance
end
function Request:getControllerName()
return self.controller_name
end
function Request:getActionName()
return self.action_name
end
function Request:getHeaders()
local headers = self.headers or ngx.req.get_headers()
return headers
end
function Request:getHeader(key)
local headers = self.headers or ngx.req.get_headers()
if headers[key] ~= nil then
return headers[key]
else
return false
end
end
function Request:buildParams()
local GET, POST, FILE = Reqargs:getRequestData({})
local params = GET
if #POST >= 1 then for k,v in pairs(POST) do params[k] = v end end
if #FILE >= 1 then params['VA_FILE']=FILE end
self.params = params
return self.params
end
function Request:getParams()
return self.params or self:buildParams()
end
function Request:getParam(key)
local ok, params_or_err = pcall(function(self) return self.params[key] end)
if ok then return params_or_err else return self:buildParams()[key] end
end
function Request:setParam(key, value)
self.params[key] = value
end
function Request:getMethod()
local method = self.method or ngx.req.get_method()
return method
end
function Request:isGet()
if self.method == 'GET' then return true else return false end
end
return Request
|
Request:getParam key nil bug
|
Request:getParam key nil bug
|
Lua
|
mit
|
idevz/vanilla,idevz/vanilla
|
963645e268900a78c2d25733410d1c30923337b4
|
mod_ircd/mod_ircd.lua
|
mod_ircd/mod_ircd.lua
|
local irc_listener = { default_port = 6667, default_mode = "*l" };
local sessions = {};
local commands = {};
local nicks = {};
local st = require "util.stanza";
local conference_server = module:get_option("conference_server") or "conference.jabber.org";
local function irc_close_session(session)
session.conn:close();
end
function irc_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { conn = conn, host = module.host, reset_stream = function () end,
close = irc_close_session, log = logger.init("irc"..(conn.id or "1")),
roster = {} };
sessions[conn] = session;
function session.data(data)
module:log("debug", "Received: %s", data);
local command, args = data:match("^%s*([^ ]+) *(.*)%s*$");
if not command then
module:log("warn", "Invalid command: %s", data);
return;
end
command = command:upper();
module:log("debug", "Received command: %s", command);
if commands[command] then
local ret = commands[command](session, args);
if ret then
session.send(ret.."\r\n");
end
end
end
function session.send(data)
module:log("debug", "sending: %s", data);
return conn:write(data.."\r\n");
end
end
if data then
session.data(data);
end
end
function irc_listener.ondisconnect(conn, error)
module:log("debug", "Client disconnected");
sessions[conn] = nil;
end
function commands.NICK(session, nick)
nick = nick:match("^[%w_]+");
if nicks[nick] then
session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use");
return;
end
nicks[nick] = session;
session.nick = nick;
session.full_jid = nick.."@"..module.host.."/ircd";
session.type = "c2s";
module:log("debug", "Client bound to %s", session.full_jid);
session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick);
end
local joined_mucs = {};
function commands.JOIN(session, channel)
if not joined_mucs[channel] then
joined_mucs[channel] = { occupants = {}, sessions = {} };
end
joined_mucs[channel].sessions[session] = true;
local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick });
core_process_stanza(session, join_stanza);
session.send(":"..session.nick.." JOIN :"..channel);
session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress...");
local nicks = session.nick;
for nick in pairs(joined_mucs[channel].occupants) do
nicks = nicks.." "..nick;
end
session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..nicks);
session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list.");
end
function commands.PART(session, channel)
local channel, part_message = channel:match("^([^:]+):?(.*)$");
channel = channel:match("^([%S]*)");
core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message));
session.send(":"..session.nick.." PART :"..channel);
end
function commands.PRIVMSG(session, message)
local who, message = message:match("^(%S+) :(.+)$");
if joined_mucs[who] then
core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message));
end
end
function commands.PING(session, server)
session.send(":"..session.host..": PONG "..server);
end
function commands.WHO(session, channel)
if joined_mucs[channel] then
for nick in pairs(joined_mucs[channel].occupants) do
--n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild
session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick);
end
session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list");
end
end
function commands.MODE(session, channel)
session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J");
end
--- Component (handle stanzas from the server for IRC clients)
function irc_component(origin, stanza)
local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from);
local from_node = "#"..jid.split(stanza.attr.from);
if joined_mucs[from_node] and from_bare == from then
-- From room itself
local joined_muc = joined_mucs[from_node];
if stanza.name == "message" then
local subject = stanza:get_child("subject");
subject = subject and (subject:get_text() or "");
if subject then
for session in pairs(joined_muc.sessions) do
session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject);
end
end
end
elseif joined_mucs[from_node] then
-- From room occupant
local joined_muc = joined_mucs[from_node];
local nick = select(3, jid.split(from)):gsub(" ", "_");
if stanza.name == "presence" then
local what;
if not stanza.attr.type then
if joined_muc.occupants[nick] then
return;
end
joined_muc.occupants[nick] = true;
what = "JOIN";
else
joined_muc.occupants[nick] = nil;
what = "PART";
end
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick then
session.send(":"..nick.."!"..nick.." "..what.." :"..from_node);
end
end
elseif stanza.name == "message" then
local body = stanza:get_child("body");
body = body and body:get_text() or "";
local hasdelay = stanza:get_child("delay", "urn:xmpp:delay");
if body ~= "" and nick then
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick or hasdelay then
session.send(":"..nick.." PRIVMSG "..from_node.." :"..body);
end
end
end
if not nick then
module:log("error", "Invalid nick from JID: %s", from);
end
end
end
end
require "core.componentmanager".register_component(module.host, irc_component);
prosody.events.add_handler("server-stopping", function (shutdown)
module:log("debug", "Closing IRC connections prior to shutdown");
for channel, joined_muc in pairs(joined_mucs) do
for session in pairs(joined_muc.sessions) do
core_process_stanza(session,
st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }
:tag("status")
:text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or "")));
session:close();
end
end
end);
require "net.connlisteners".register("irc", irc_listener);
require "net.connlisteners".start("irc", { port = module:get_option("port") });
|
local irc_listener = { default_port = 6667, default_mode = "*l" };
local sessions = {};
local commands = {};
local nicks = {};
local st = require "util.stanza";
local conference_server = module:get_option("conference_server") or "conference.jabber.org";
local function irc_close_session(session)
session.conn:close();
end
function irc_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { conn = conn, host = module.host, reset_stream = function () end,
close = irc_close_session, log = logger.init("irc"..(conn.id or "1")),
roster = {} };
sessions[conn] = session;
function session.data(data)
module:log("debug", "Received: %s", data);
local command, args = data:match("^%s*([^ ]+) *(.*)%s*$");
if not command then
module:log("warn", "Invalid command: %s", data);
return;
end
command = command:upper();
module:log("debug", "Received command: %s", command);
if commands[command] then
local ret = commands[command](session, args);
if ret then
session.send(ret.."\r\n");
end
end
end
function session.send(data)
module:log("debug", "sending: %s", data);
return conn:write(data.."\r\n");
end
end
if data then
session.data(data);
end
end
function irc_listener.ondisconnect(conn, error)
module:log("debug", "Client disconnected");
sessions[conn] = nil;
end
function commands.NICK(session, nick)
nick = nick:match("^[%w_]+");
if nicks[nick] then
session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use");
return;
end
nicks[nick] = session;
session.nick = nick;
session.full_jid = nick.."@"..module.host.."/ircd";
session.type = "c2s";
module:log("debug", "Client bound to %s", session.full_jid);
session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick);
end
local joined_mucs = {};
function commands.JOIN(session, channel)
if not joined_mucs[channel] then
joined_mucs[channel] = { occupants = {}, sessions = {} };
end
joined_mucs[channel].sessions[session] = true;
local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick });
core_process_stanza(session, join_stanza);
session.send(":"..session.nick.." JOIN :"..channel);
session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress...");
local nicks = session.nick;
for nick in pairs(joined_mucs[channel].occupants) do
nicks = nicks.." "..nick;
end
session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..nicks);
session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list.");
end
function commands.PART(session, channel)
local channel, part_message = channel:match("^([^:]+):?(.*)$");
channel = channel:match("^([%S]*)");
core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message));
session.send(":"..session.nick.." PART :"..channel);
end
function commands.PRIVMSG(session, message)
local who, message = message:match("^(%S+) :(.+)$");
if joined_mucs[who] then
core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message));
end
end
function commands.PING(session, server)
session.send(":"..session.host..": PONG "..server);
end
function commands.WHO(session, channel)
if joined_mucs[channel] then
for nick in pairs(joined_mucs[channel].occupants) do
--n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild
session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick);
end
session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list");
end
end
function commands.MODE(session, channel)
session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J");
end
--- Component (handle stanzas from the server for IRC clients)
function irc_component(origin, stanza)
local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from);
local from_node = "#"..jid.split(stanza.attr.from);
if joined_mucs[from_node] and from_bare == from then
-- From room itself
local joined_muc = joined_mucs[from_node];
if stanza.name == "message" then
local subject = stanza:get_child("subject");
subject = subject and (subject:get_text() or "");
if subject then
for session in pairs(joined_muc.sessions) do
session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject);
end
end
end
elseif joined_mucs[from_node] then
-- From room occupant
local joined_muc = joined_mucs[from_node];
local nick = select(3, jid.split(from)):gsub(" ", "_");
if stanza.name == "presence" then
local what;
if not stanza.attr.type then
if joined_muc.occupants[nick] then
return;
end
joined_muc.occupants[nick] = true;
what = "JOIN";
else
joined_muc.occupants[nick] = nil;
what = "PART";
end
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick then
session.send(":"..nick.."!"..nick.." "..what.." :"..from_node);
end
end
elseif stanza.name == "message" then
local body = stanza:get_child("body");
body = body and body:get_text() or "";
local hasdelay = stanza:get_child("delay", "urn:xmpp:delay");
if body ~= "" and nick then
local to_nick = jid.split(stanza.attr.to);
local session = nicks[to_nick];
if nick ~= session.nick or hasdelay then
session.send(":"..nick.." PRIVMSG "..from_node.." :"..body);
end
end
if not nick then
module:log("error", "Invalid nick from JID: %s", from);
end
end
end
end
require "core.componentmanager".register_component(module.host, irc_component);
prosody.events.add_handler("server-stopping", function (shutdown)
module:log("debug", "Closing IRC connections prior to shutdown");
for channel, joined_muc in pairs(joined_mucs) do
for session in pairs(joined_muc.sessions) do
core_process_stanza(session,
st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }
:tag("status")
:text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or "")));
session:close();
end
end
end);
require "net.connlisteners".register("irc", irc_listener);
require "net.connlisteners".start("irc", { port = module:get_option("port") });
|
fixed broadcast PRIVMSG bug
|
fixed broadcast PRIVMSG bug
|
Lua
|
mit
|
brahmi2/prosody-modules,1st8/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,asdofindia/prosody-modules,jkprg/prosody-modules,obelisk21/prosody-modules,stephen322/prosody-modules,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,BurmistrovJ/prosody-modules,vfedoroff/prosody-modules,apung/prosody-modules,heysion/prosody-modules,mardraze/prosody-modules,vince06fr/prosody-modules,heysion/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,iamliqiang/prosody-modules,apung/prosody-modules,amenophis1er/prosody-modules,joewalker/prosody-modules,softer/prosody-modules,cryptotoad/prosody-modules,syntafin/prosody-modules,asdofindia/prosody-modules,vince06fr/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,NSAKEY/prosody-modules,olax/prosody-modules,dhotson/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,crunchuser/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,crunchuser/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,mmusial/prosody-modules,olax/prosody-modules,softer/prosody-modules,LanceJenkinZA/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,BurmistrovJ/prosody-modules,prosody-modules/import,asdofindia/prosody-modules,joewalker/prosody-modules,mardraze/prosody-modules,apung/prosody-modules,drdownload/prosody-modules,either1/prosody-modules,brahmi2/prosody-modules,either1/prosody-modules,vfedoroff/prosody-modules,stephen322/prosody-modules,obelisk21/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,BurmistrovJ/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,1st8/prosody-modules,prosody-modules/import,stephen322/prosody-modules,apung/prosody-modules,mmusial/prosody-modules,brahmi2/prosody-modules,joewalker/prosody-modules,dhotson/prosody-modules,asdofindia/prosody-modules,obelisk21/prosody-modules,heysion/prosody-modules,syntafin/prosody-modules,iamliqiang/prosody-modules,prosody-modules/import,softer/prosody-modules,heysion/prosody-modules,either1/prosody-modules,guilhem/prosody-modules,asdofindia/prosody-modules,softer/prosody-modules,Craige/prosody-modules,heysion/prosody-modules,olax/prosody-modules,softer/prosody-modules,olax/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,Craige/prosody-modules,amenophis1er/prosody-modules,cryptotoad/prosody-modules,NSAKEY/prosody-modules,jkprg/prosody-modules,apung/prosody-modules,prosody-modules/import,mmusial/prosody-modules,mardraze/prosody-modules,mardraze/prosody-modules,guilhem/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,obelisk21/prosody-modules,crunchuser/prosody-modules,vfedoroff/prosody-modules,1st8/prosody-modules,prosody-modules/import,olax/prosody-modules,cryptotoad/prosody-modules,dhotson/prosody-modules,dhotson/prosody-modules,jkprg/prosody-modules,guilhem/prosody-modules,BurmistrovJ/prosody-modules,1st8/prosody-modules,vfedoroff/prosody-modules,jkprg/prosody-modules,mmusial/prosody-modules,dhotson/prosody-modules,either1/prosody-modules,LanceJenkinZA/prosody-modules,NSAKEY/prosody-modules,vfedoroff/prosody-modules,drdownload/prosody-modules,syntafin/prosody-modules,amenophis1er/prosody-modules,stephen322/prosody-modules,LanceJenkinZA/prosody-modules,guilhem/prosody-modules
|
0b6940cba71fbde9be463bce62445247c7d4d7a1
|
plugins/delword.lua
|
plugins/delword.lua
|
local function get_censorships_hash(msg)
if msg.to.type == 'channel' then
return 'channel:' .. msg.to.id .. ':censorships'
end
if msg.to.type == 'chat' then
return 'chat:' .. msg.to.id .. ':censorships'
end
return false
end
local function setunset_delword(msg, var_name)
var_name = var_name:gsub(' ', '_')
local hash = get_censorships_hash(msg)
if hash then
if redis:hget(hash, var_name) then
redis:hdel(hash, var_name)
return langs[msg.lang].delwordRemoved .. var_name
else
redis:hset(hash, var_name, true)
return langs[msg.lang].delwordAdded .. var_name
end
end
end
local function list_censorships(msg)
local hash = get_censorships_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = langs[msg.lang].delwordList
for i = 1, #names do
text = text .. names[i]:gsub('_', ' ') .. '\n'
end
return text
end
end
local function run(msg, matches)
if matches[1]:lower() == 'dellist' or matches[1]:lower() == 'sasha lista censure' or matches[1]:lower() == 'lista censure' then
return list_censorships(msg)
end
if (matches[1]:lower() == 'delword' or matches[1]:lower() == 'sasha censura' or matches[1]:lower() == 'censura') and matches[2] then
if is_momod(msg) then
return setunset_delword(msg, matches[2])
else
return langs[msg.lang].require_mod
end
end
end
local function pre_process(msg, matches)
if not is_momod(msg) then
local found = false
local vars = list_censorships(msg)
if vars ~= nil then
local t = vars:split('\n')
for i, word in pairs(t) do
local temp = word:lower()
if msg.text then
if not string.match(msg.text, "^[#!/]([Dd][Ee][Ll][Ww][Oo][Rr][Dd]) (.*)$") then
if string.find(msg.text:lower(), temp) then
found = true
end
end
end
if msg.media then
if msg.media.title then
if not string.match(msg.media.title, "^[#!/]([Dd][Ee][Ll][Ww][Oo][Rr][Dd]) (.*)$") then
if string.find(msg.media.title:lower(), temp) then
found = true
end
end
end
if msg.media.description then
if not string.match(msg.media.description, "^[#!/]([Dd][Ee][Ll][Ww][Oo][Rr][Dd]) (.*)$") then
if string.find(msg.media.description:lower(), temp) then
found = true
end
end
end
if msg.media.caption then
if not string.match(msg.media.caption, "^[#!/]([Dd][Ee][Ll][Ww][Oo][Rr][Dd]) (.*)$") then
if string.find(msg.media.caption:lower(), temp) then
found = true
end
end
end
end
if msg.fwd_from then
if msg.fwd_from.title then
if not string.match(msg.fwd_from.title, "^[#!/]([Dd][Ee][Ll][Ww][Oo][Rr][Dd]) (.*)$") then
if string.find(msg.fwd_from.title:lower(), temp) then
found = true
end
end
end
end
if found then
if msg.to.type == 'chat' then
kick_user(msg.from.id, msg.to.id)
end
if msg.to.type == 'channel' then
delete_msg(msg.id, ok_cb, false)
end
end
end
end
end
return msg
end
return {
description = "DELWORD",
patterns =
{
"^[#!/]([Dd][Ee][Ll][Ww][Oo][Rr][Dd]) (.*)$",
"^[#!/]([Dd][Ee][Ll][Ll][Ii][Ss][Tt])$",
-- delword
"^([Ss][Aa][Ss][Hh][Aa] [Cc][Ee][Nn][Ss][Uu][Rr][Aa]) (.*)$",
"^([Cc][Ee][Nn][Ss][Uu][Rr][Aa]) (.*)$",
-- dellist
"^([Ss][Aa][Ss][Hh][Aa] [Ll][Ii][Ss][Tt][Aa] [Cc][Ee][Nn][Ss][Uu][Rr][Ee])$",
"^([Ll][Ii][Ss][Tt][Aa] [Cc][Ee][Nn][Ss][Uu][Rr][Ee])$",
},
pre_process = pre_process,
run = run,
min_rank = 0
-- usage
-- USER
-- (#dellist|[sasha] lista censura)
-- OWNER
-- (#delword|[sasha] censura) <word>|<pattern>
}
|
local function get_censorships_hash(msg)
if msg.to.type == 'channel' then
return 'channel:' .. msg.to.id .. ':censorships'
end
if msg.to.type == 'chat' then
return 'chat:' .. msg.to.id .. ':censorships'
end
return false
end
local function setunset_delword(msg, var_name)
local hash = get_censorships_hash(msg)
if hash then
if redis:hget(hash, var_name) then
redis:hdel(hash, var_name)
return langs[msg.lang].delwordRemoved .. var_name
else
redis:hset(hash, var_name, true)
return langs[msg.lang].delwordAdded .. var_name
end
end
end
local function list_censorships(msg)
local hash = get_censorships_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = langs[msg.lang].delwordList
for i = 1, #names do
text = text .. names[i] .. '\n'
end
return text
end
end
local function run(msg, matches)
if matches[1]:lower() == 'dellist' or matches[1]:lower() == 'sasha lista censure' or matches[1]:lower() == 'lista censure' then
return list_censorships(msg)
end
if (matches[1]:lower() == 'delword' or matches[1]:lower() == 'sasha censura' or matches[1]:lower() == 'censura') and matches[2] then
if is_momod(msg) then
return setunset_delword(msg, matches[2])
else
return langs[msg.lang].require_mod
end
end
end
local function pre_process(msg, matches)
if not is_momod(msg) then
local found = false
local vars = list_censorships(msg)
if vars ~= nil then
local t = vars:split('\n')
for i, word in pairs(t) do
local temp = word:lower()
if msg.text then
if not string.match(msg.text, "^[#!/]([Dd][Ee][Ll][Ww][Oo][Rr][Dd]) (.*)$") then
if string.find(msg.text:lower(), temp) then
found = true
end
end
end
if msg.media then
if msg.media.title then
if not string.match(msg.media.title, "^[#!/]([Dd][Ee][Ll][Ww][Oo][Rr][Dd]) (.*)$") then
if string.find(msg.media.title:lower(), temp) then
found = true
end
end
end
if msg.media.description then
if not string.match(msg.media.description, "^[#!/]([Dd][Ee][Ll][Ww][Oo][Rr][Dd]) (.*)$") then
if string.find(msg.media.description:lower(), temp) then
found = true
end
end
end
if msg.media.caption then
if not string.match(msg.media.caption, "^[#!/]([Dd][Ee][Ll][Ww][Oo][Rr][Dd]) (.*)$") then
if string.find(msg.media.caption:lower(), temp) then
found = true
end
end
end
end
if msg.fwd_from then
if msg.fwd_from.title then
if not string.match(msg.fwd_from.title, "^[#!/]([Dd][Ee][Ll][Ww][Oo][Rr][Dd]) (.*)$") then
if string.find(msg.fwd_from.title:lower(), temp) then
found = true
end
end
end
end
if found then
if msg.to.type == 'chat' then
kick_user(msg.from.id, msg.to.id)
end
if msg.to.type == 'channel' then
delete_msg(msg.id, ok_cb, false)
end
end
end
end
end
return msg
end
return {
description = "DELWORD",
patterns =
{
"^[#!/]([Dd][Ee][Ll][Ww][Oo][Rr][Dd]) (.*)$",
"^[#!/]([Dd][Ee][Ll][Ll][Ii][Ss][Tt])$",
-- delword
"^([Ss][Aa][Ss][Hh][Aa] [Cc][Ee][Nn][Ss][Uu][Rr][Aa]) (.*)$",
"^([Cc][Ee][Nn][Ss][Uu][Rr][Aa]) (.*)$",
-- dellist
"^([Ss][Aa][Ss][Hh][Aa] [Ll][Ii][Ss][Tt][Aa] [Cc][Ee][Nn][Ss][Uu][Rr][Ee])$",
"^([Ll][Ii][Ss][Tt][Aa] [Cc][Ee][Nn][Ss][Uu][Rr][Ee])$",
},
pre_process = pre_process,
run = run,
min_rank = 0
-- usage
-- USER
-- (#dellist|[sasha] lista censura)
-- OWNER
-- (#delword|[sasha] censura) <word>|<pattern>
}
|
fix useless gsub
|
fix useless gsub
|
Lua
|
agpl-3.0
|
xsolinsx/AISasha
|
d8a90e7417658f17da678798393f8d9f8719b146
|
btCommandScripts/move.lua
|
btCommandScripts/move.lua
|
local Logger = VFS.Include(LUAUI_DIRNAME .. "Widgets/BtUtils/debug_utils/logger.lua", nil, VFS.RAW_FIRST)
--local baseCommand = VFS.Include(LUAUI_DIRNAME .. "Widgets/btCommandScripts/command.lua", nil, VFS.RAW_FIRST)
local cmdClass = VFS.Include(LUAUI_DIRNAME .. "Widgets/btCommandScripts/command.lua", nil, VFS.RAW_FIRST)
function cmdClass:New()
self.targets = {}
self.n = 0
self.lastPositions = {}
end
function cmdClass:UnitMoved(unitID)
x, _, z = Spring.GetUnitPosition(unitID)
lastPos = self.lastPositions[unitID]
if not lastPos then
lastPos = {x,z}
self.lastPositions[unitID] = lastPos
Logger.log("move-command","unit:", unitID, "x: ", x ,", z: ", z)
return true
end
Logger.log("move-command", "unit:", unitID, " x: ", x ,", lastX: ", lastPos[1], ", z: ", z, ", lastZ: ", lastPos[2])
moved = x ~= lastPos[1] or z ~= lastPos[2]
self.lastPositions[unitID] = {x,z}
return moved
end
function cmdClass:Run(unitIds, parameter)
dx = parameter.x
dz = parameter.y
Logger.log("move-command", "Lua MOVE command run, unitIds: ", unitIds, ", dx: " .. dx .. ", dz: " .. dz .. ", tick: "..self.n)
self.n = self.n + 1
done = true
x,y,z = 0,0,0
for i = 1, #unitIds do
unitID = unitIds[i]
x, y, z = Spring.GetUnitPosition(unitID)
tarX = x + dx
tarZ = z + dz
if not self.targets[unitID] then
self.targets[unitID] = {tarX,y,tarZ}
Spring.GiveOrderToUnit(unitID, CMD.MOVE, self.targets[unitID], {})
done = false
else
Logger.log("move-command", "AtX: " .. x .. ", TargetX: " .. self.targets[unitID][1] .. " AtZ: " .. z .. ", TargetZ: " .. self.targets[unitID][2])
if not self:UnitIdle(unitID) then
done = false
end
if not self:UnitMoved(unitID) then -- cannot get to target location
return "F"
end
end
end
if done then
return "S"
else
return "R"
end
end
function cmdClass:Reset()
Logger.log("move-command", "Lua command reset")
self.targets = {}
self.n = 0
self.lastPositions = {}
end
return cmdClass
|
local Logger = VFS.Include(LUAUI_DIRNAME .. "Widgets/BtUtils/debug_utils/logger.lua", nil, VFS.RAW_FIRST)
--local baseCommand = VFS.Include(LUAUI_DIRNAME .. "Widgets/btCommandScripts/command.lua", nil, VFS.RAW_FIRST)
local cmdClass = VFS.Include(LUAUI_DIRNAME .. "Widgets/btCommandScripts/command.lua", nil, VFS.RAW_FIRST)
function cmdClass:New()
self.targets = {}
self.n = 0
self.lastPositions = {}
end
function cmdClass:UnitMoved(unitID)
x, _, z = Spring.GetUnitPosition(unitID)
lastPos = self.lastPositions[unitID]
if not lastPos then
lastPos = {x,z}
self.lastPositions[unitID] = lastPos
Logger.log("move-command","unit:", unitID, "x: ", x ,", z: ", z)
return true
end
Logger.log("move-command", "unit:", unitID, " x: ", x ,", lastX: ", lastPos[1], ", z: ", z, ", lastZ: ", lastPos[2])
moved = x ~= lastPos[1] or z ~= lastPos[2]
self.lastPositions[unitID] = {x,z}
return moved
end
function cmdClass:Run(unitIds, parameter)
dx = parameter.x
dz = parameter.y
Logger.log("move-command", "Lua MOVE command run, unitIds: ", unitIds, ", dx: " .. dx .. ", dz: " .. dz .. ", tick: "..self.n)
self.n = self.n + 1
done = true
noneMoved = true
x,y,z = 0,0,0
for i = 1, #unitIds do
unitID = unitIds[i]
x, y, z = Spring.GetUnitPosition(unitID)
tarX = x + dx
tarZ = z + dz
if not self.targets[unitID] then
self.targets[unitID] = {tarX,y,tarZ}
Spring.GiveOrderToUnit(unitID, CMD.MOVE, self.targets[unitID], {})
done = false
noneMoved = false
else
Logger.log("move-command", "AtX: " .. x .. ", TargetX: " .. self.targets[unitID][1] .. " AtZ: " .. z .. ", TargetZ: " .. self.targets[unitID][2])
if not self:UnitIdle(unitID) then
done = false
end
if self:UnitMoved(unitID) then -- cannot get to target location
noneMoved = false
end
end
end
if done then
return "S"
elseif noneMoved then
return "F"
else
return "R"
end
end
function cmdClass:Reset()
Logger.log("move-command", "Lua command reset")
self.targets = {}
self.n = 0
self.lastPositions = {}
end
return cmdClass
|
Excessive move fails fixed.
|
Excessive move fails fixed.
|
Lua
|
mit
|
MartinFrancu/BETS
|
e07ee5a4f644a03ba52f9be74c7b9d3486acf5d5
|
plugins/mod_posix.lua
|
plugins/mod_posix.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 want_pposix_version = "0.3.1";
local pposix = assert(require "util.pposix");
if pposix._VERSION ~= want_pposix_version then module:log("warn", "Unknown version (%s) of binary pposix module, expected %s", tostring(pposix._VERSION), want_pposix_version); end
local signal = select(2, pcall(require, "util.signal"));
if type(signal) == "string" then
module:log("warn", "Couldn't load signal library, won't respond to SIGTERM");
end
local logger_set = require "util.logger".setwriter;
local prosody = _G.prosody;
module.host = "*"; -- we're a global module
-- Allow switching away from root, some people like strange ports.
module:add_event_hook("server-started", function ()
local uid = module:get_option("setuid");
local gid = module:get_option("setgid");
if gid then
local success, msg = pposix.setgid(gid);
if success then
module:log("debug", "Changed group to "..gid.." successfully.");
else
module:log("error", "Failed to change group to "..gid..". Error: "..msg);
prosody.shutdown("Failed to change group to "..gid);
end
end
if uid then
local success, msg = pposix.setuid(uid);
if success then
module:log("debug", "Changed user to "..uid.." successfully.");
else
module:log("error", "Failed to change user to "..uid..". Error: "..msg);
prosody.shutdown("Failed to change user to "..uid);
end
end
end);
-- Don't even think about it!
module:add_event_hook("server-starting", function ()
local suid = module:get_option("setuid");
if not suid or suid == 0 or suid == "root" then
if pposix.getuid() == 0 and not module:get_option("run_as_root") then
module:log("error", "Danger, Will Robinson! Prosody doesn't need to be run as root, so don't do it!");
module:log("error", "For more information on running Prosody as root, see http://prosody.im/doc/root");
prosody.shutdown("Refusing to run as root");
end
end
end);
local pidfile_written;
local function remove_pidfile()
if pidfile_written then
os.remove(pidfile_written);
pidfile_written = nil;
end
end
local function write_pidfile()
if pidfile_written then
remove_pidfile();
end
local pidfile = module:get_option("pidfile");
if pidfile then
local pf, err = io.open(pidfile, "w+");
if not pf then
module:log("error", "Couldn't write pidfile; %s", err);
else
pf:write(tostring(pposix.getpid()));
pf:close();
pidfile_written = pidfile;
end
end
end
local syslog_opened
function syslog_sink_maker(config)
if not syslog_opened then
pposix.syslog_open("prosody");
syslog_opened = true;
end
local syslog, format = pposix.syslog_log, string.format;
return function (name, level, message, ...)
if ... then
syslog(level, format(message, ...));
else
syslog(level, message);
end
end;
end
require "core.loggingmanager".register_sink_type("syslog", syslog_sink_maker);
local daemonize = module:get_option("daemonize");
if daemonize == nil then
local no_daemonize = module:get_option("no_daemonize"); --COMPAT w/ 0.5
daemonize = not no_daemonize;
if no_daemonize ~= nil then
module:log("warn", "The 'no_daemonize' option is now replaced by 'daemonize'");
module:log("warn", "Update your config from 'no_daemonize = %s' to 'daemonize = %s'", tostring(no_daemonize), tostring(daemonize));
end
end
if daemonize then
local function daemonize_server()
local ok, ret = pposix.daemonize();
if not ok then
module:log("error", "Failed to daemonize: %s", ret);
elseif ret and ret > 0 then
os.exit(0);
else
module:log("info", "Successfully daemonized to PID %d", pposix.getpid());
write_pidfile();
end
end
module:add_event_hook("server-starting", daemonize_server);
else
-- Not going to daemonize, so write the pid of this process
write_pidfile();
end
module:add_event_hook("server-stopped", remove_pidfile);
-- Set signal handlers
if signal.signal then
signal.signal("SIGTERM", function ()
module:log("warn", "Received SIGTERM");
prosody.unlock_globals();
prosody.shutdown("Received SIGTERM");
prosody.lock_globals();
end);
signal.signal("SIGHUP", function ()
module:log("info", "Received SIGHUP");
prosody.reload_config();
prosody.reopen_logfiles();
end);
signal.signal("SIGINT", function ()
module:log("info", "Received SIGINT");
signal.signal("SIGINT", function () end); -- Fixes us getting into some kind of loop
prosody.unlock_globals();
prosody.shutdown("Received SIGINT");
prosody.lock_globals();
end);
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 want_pposix_version = "0.3.1";
local pposix = assert(require "util.pposix");
if pposix._VERSION ~= want_pposix_version then module:log("warn", "Unknown version (%s) of binary pposix module, expected %s", tostring(pposix._VERSION), want_pposix_version); end
local signal = select(2, pcall(require, "util.signal"));
if type(signal) == "string" then
module:log("warn", "Couldn't load signal library, won't respond to SIGTERM");
end
local logger_set = require "util.logger".setwriter;
local prosody = _G.prosody;
module.host = "*"; -- we're a global module
-- Allow switching away from root, some people like strange ports.
module:add_event_hook("server-started", function ()
local uid = module:get_option("setuid");
local gid = module:get_option("setgid");
if gid then
local success, msg = pposix.setgid(gid);
if success then
module:log("debug", "Changed group to "..gid.." successfully.");
else
module:log("error", "Failed to change group to "..gid..". Error: "..msg);
prosody.shutdown("Failed to change group to "..gid);
end
end
if uid then
local success, msg = pposix.setuid(uid);
if success then
module:log("debug", "Changed user to "..uid.." successfully.");
else
module:log("error", "Failed to change user to "..uid..". Error: "..msg);
prosody.shutdown("Failed to change user to "..uid);
end
end
end);
-- Don't even think about it!
module:add_event_hook("server-starting", function ()
local suid = module:get_option("setuid");
if not suid or suid == 0 or suid == "root" then
if pposix.getuid() == 0 and not module:get_option("run_as_root") then
module:log("error", "Danger, Will Robinson! Prosody doesn't need to be run as root, so don't do it!");
module:log("error", "For more information on running Prosody as root, see http://prosody.im/doc/root");
prosody.shutdown("Refusing to run as root");
end
end
end);
local pidfile_written;
local function remove_pidfile()
if pidfile_written then
os.remove(pidfile_written);
pidfile_written = nil;
end
end
local function write_pidfile()
if pidfile_written then
remove_pidfile();
end
local pidfile = module:get_option("pidfile");
if pidfile then
local pf, err = io.open(pidfile, "w+");
if not pf then
module:log("error", "Couldn't write pidfile; %s", err);
else
pf:write(tostring(pposix.getpid()));
pf:close();
pidfile_written = pidfile;
end
end
end
local syslog_opened
function syslog_sink_maker(config)
if not syslog_opened then
pposix.syslog_open("prosody");
syslog_opened = true;
end
local syslog, format = pposix.syslog_log, string.format;
return function (name, level, message, ...)
if ... then
syslog(level, format(message, ...));
else
syslog(level, message);
end
end;
end
require "core.loggingmanager".register_sink_type("syslog", syslog_sink_maker);
local daemonize = module:get_option("daemonize");
if daemonize == nil then
local no_daemonize = module:get_option("no_daemonize"); --COMPAT w/ 0.5
daemonize = not no_daemonize;
if no_daemonize ~= nil then
module:log("warn", "The 'no_daemonize' option is now replaced by 'daemonize'");
module:log("warn", "Update your config from 'no_daemonize = %s' to 'daemonize = %s'", tostring(no_daemonize), tostring(daemonize));
end
end
if daemonize then
local function daemonize_server()
local ok, ret = pposix.daemonize();
if not ok then
module:log("error", "Failed to daemonize: %s", ret);
elseif ret and ret > 0 then
os.exit(0);
else
module:log("info", "Successfully daemonized to PID %d", pposix.getpid());
write_pidfile();
end
end
module:add_event_hook("server-starting", daemonize_server);
else
-- Not going to daemonize, so write the pid of this process
write_pidfile();
end
module:add_event_hook("server-stopped", remove_pidfile);
-- Set signal handlers
if signal.signal then
signal.signal("SIGTERM", function ()
module:log("warn", "Received SIGTERM");
signal.signal("SIGTERM", function () end); -- Fixes us getting into some kind of loop
prosody.unlock_globals();
prosody.shutdown("Received SIGTERM");
prosody.lock_globals();
end);
signal.signal("SIGHUP", function ()
module:log("info", "Received SIGHUP");
prosody.reload_config();
prosody.reopen_logfiles();
end);
signal.signal("SIGINT", function ()
module:log("info", "Received SIGINT");
signal.signal("SIGINT", function () end); -- Fix to not loop
prosody.unlock_globals();
prosody.shutdown("Received SIGINT");
prosody.lock_globals();
end);
end
|
mod_posix: Fix to not loop in SIGTERM either, but the same happens with SIGHUP (where the same 'fix' can't be applied) - shall investigate tomorrow
|
mod_posix: Fix to not loop in SIGTERM either, but the same happens with SIGHUP (where the same 'fix' can't be applied) - shall investigate tomorrow
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
3b1eabc2a2c8a71ed3b4dedfba44ff5c74390532
|
lua/wincent/commandt/private/ui.lua
|
lua/wincent/commandt/private/ui.lua
|
-- SPDX-FileCopyrightText: Copyright 2022-present Greg Hurrell and contributors.
-- SPDX-License-Identifier: BSD-2-Clause
local ui = {}
local MatchListing = require('wincent.commandt.private.match_listing').MatchListing
local Prompt = require('wincent.commandt.private.prompt').Prompt
local cmdline_enter_autocmd = nil
local current_finder = nil -- Reference to avoid premature garbage collection.
local match_listing = nil
local prompt = nil
-- Reverses `list` in place.
local reverse = function(list)
local i = 1
local j = #list
while i < j do
list[i], list[j] = list[j], list[i]
i = i + 1
j = j - 1
end
end
-- TODO: reasons to delete a window
-- 1. [DONE] user explicitly closes it with ESC
-- 2. [DONE] user explicitly accepts a selection
-- 3. [DONE] user navigates out of the window (WinLeave)
-- 4. [DONE] user uses a Vim command to close the window or the buffer
-- (we get this "for free" kind of thanks to WinLeave happening as soon as you
-- do anything that would move you out)
local close = function()
if match_listing then
match_listing:close()
match_listing = nil
end
if prompt then
prompt:close()
prompt = nil
end
if cmdline_enter_autocmd ~= nil then
vim.api.nvim_del_autocmd(cmdline_enter_autocmd)
cmdline_enter_autocmd = nil
end
end
-- TODO save/restore global options, like `hlsearch' (which we want to turn off
-- temporarily when our windows are visible) — either that, or figure out how to
-- make the highlighting not utterly suck.
-- in any case, review the list at ruby/command-t/lib/command-t/match_window.rb
ui.show = function(finder, options)
-- TODO validate options
current_finder = finder
assert(current_finder) -- Avoid Lua warning about unused local.
match_listing = MatchListing.new({
height = options.height,
margin = options.margin,
position = options.position,
selection_highlight = options.selection_highlight,
})
match_listing:show()
local results = nil
local selected = nil
prompt = Prompt.new({
height = options.height,
mappings = options.mappings,
margin = options.margin,
name = options.name,
on_change = function(query)
results = finder.run(query)
if #results == 0 then
selected = nil
else
if options.order == 'reverse' then
reverse(results)
selected = #results
else
selected = 1
end
end
match_listing:update(results, { selected = selected })
end,
on_leave = close,
-- TODO: decide whether we want an `index`, a string, or just to base it off
-- our notion of current selection
on_open = function(kind)
if results and #results then
close()
finder.open(results[selected], kind)
end
end,
on_select = function(choice)
if results and #results > 0 then
if choice.absolute then
if choice.absolute > 0 then
selected = math.min(choice.absolute, #results)
elseif choice.absolute < 0 then
selected = math.max(#results + choice.absolute + 1, 1)
else -- Absolute "middle".
selected = math.min(math.floor(#results / 2) + 1, #results)
end
elseif choice.relative then
if choice.relative > 0 then
selected = math.min(selected + choice.relative, #results)
else
selected = math.max(selected + choice.relative, 1)
end
end
match_listing:select(selected)
end
end,
position = options.position,
})
prompt:show()
if cmdline_enter_autocmd == nil then
cmdline_enter_autocmd = vim.api.nvim_create_autocmd('CmdlineEnter', {
callback = close,
})
end
end
return ui
|
-- SPDX-FileCopyrightText: Copyright 2022-present Greg Hurrell and contributors.
-- SPDX-License-Identifier: BSD-2-Clause
local ui = {}
local MatchListing = require('wincent.commandt.private.match_listing').MatchListing
local Prompt = require('wincent.commandt.private.prompt').Prompt
local cmdline_enter_autocmd = nil
local current_finder = nil -- Reference to avoid premature garbage collection.
local match_listing = nil
local prompt = nil
-- Reverses `list` in place.
local reverse = function(list)
local i = 1
local j = #list
while i < j do
list[i], list[j] = list[j], list[i]
i = i + 1
j = j - 1
end
end
-- TODO: reasons to delete a window
-- 1. [DONE] user explicitly closes it with ESC
-- 2. [DONE] user explicitly accepts a selection
-- 3. [DONE] user navigates out of the window (WinLeave)
-- 4. [DONE] user uses a Vim command to close the window or the buffer
-- (we get this "for free" kind of thanks to WinLeave happening as soon as you
-- do anything that would move you out)
local close = function()
if match_listing then
match_listing:close()
match_listing = nil
end
if prompt then
prompt:close()
prompt = nil
end
if cmdline_enter_autocmd ~= nil then
vim.api.nvim_del_autocmd(cmdline_enter_autocmd)
cmdline_enter_autocmd = nil
end
end
-- TODO save/restore global options, like `hlsearch' (which we want to turn off
-- temporarily when our windows are visible) — either that, or figure out how to
-- make the highlighting not utterly suck.
-- in any case, review the list at ruby/command-t/lib/command-t/match_window.rb
ui.show = function(finder, options)
-- TODO validate options
current_finder = finder
assert(current_finder) -- Avoid Lua warning about unused local.
match_listing = MatchListing.new({
height = options.height,
margin = options.margin,
position = options.position,
selection_highlight = options.selection_highlight,
})
match_listing:show()
local results = nil
local selected = nil
prompt = Prompt.new({
height = options.height,
mappings = options.mappings,
margin = options.margin,
name = options.name,
on_change = function(query)
results = finder.run(query)
if #results == 0 then
selected = nil
else
if options.order == 'reverse' then
reverse(results)
selected = #results
else
selected = 1
end
end
match_listing:update(results, { selected = selected })
end,
on_leave = close,
-- TODO: decide whether we want an `index`, a string, or just to base it off
-- our notion of current selection
on_open = function(kind)
close()
if results and #results > 0 then
finder.open(results[selected], kind)
end
end,
on_select = function(choice)
if results and #results > 0 then
if choice.absolute then
if choice.absolute > 0 then
selected = math.min(choice.absolute, #results)
elseif choice.absolute < 0 then
selected = math.max(#results + choice.absolute + 1, 1)
else -- Absolute "middle".
selected = math.min(math.floor(#results / 2) + 1, #results)
end
elseif choice.relative then
if choice.relative > 0 then
selected = math.min(selected + choice.relative, #results)
else
selected = math.max(selected + choice.relative, 1)
end
end
match_listing:select(selected)
end
end,
position = options.position,
})
prompt:show()
if cmdline_enter_autocmd == nil then
cmdline_enter_autocmd = vim.api.nvim_create_autocmd('CmdlineEnter', {
callback = close,
})
end
end
return ui
|
fix(lua): don't try to open nothing
|
fix(lua): don't try to open nothing
No, that's not a double negative.
|
Lua
|
bsd-2-clause
|
wincent/command-t,wincent/command-t,wincent/command-t
|
74d0303dc3cd490183bbaff8ef2302ee64d27efd
|
mods/invtweak/init.lua
|
mods/invtweak/init.lua
|
local auto_refill = minetest.setting_getbool("invtweak_auto_refill") or true
local tweak = {}
tweak.formspec = {}
tweak.buttons = {
--sort_asc
"0.8,0.6;sort_asc;^]".."tooltip[sort_asc;sort Items asc.;#30434C;#FFF]",
--sort_desc
"0.8,0.6;sort_desc;v]".."tooltip[sort_desc;sort Items desc.;#30434C;#FFF]",
--concatenate
"0.8,0.6;sort;·»]".."tooltip[sort;stack Items and sort asc.;#30434C;#FFF]"
}
local function get_formspec_size(formspec)
local w = 8
local h = 7.5
local sstring = string.find(formspec,"size[",1,true)
if sstring ~= nil then
sstring = string.sub(formspec, sstring+5)
local p = string.find(sstring,",")
w = string.sub(sstring,1,p-1)
sstring = string.sub(sstring,p+1,string.find(sstring,"]")+2)
p = string.find(sstring,",")
if p == nil then p = string.find(sstring,"]") end
h = string.sub(sstring,1,p-1)
end
return w,h
end
local function add_buttons(player, formspec)
local name = player:get_player_name()
if not formspec then
formspec = player:get_inventory_formspec()
end
local w,h = get_formspec_size(formspec)
for i=1,#tweak.buttons do
formspec = formspec .. "button["..w-(0.8+(i*0.8))..",0.2;" .. tweak.buttons[i]
end
player:set_inventory_formspec(formspec)
return formspec
end
local armor_mod = minetest.get_modpath("3d_armor")
local ui_mod = minetest.get_modpath("unified_inventory")
-- override mods formspec function
if ui_mod then
local org = unified_inventory.get_formspec
unified_inventory.get_formspec = function(player, page)
local formspec = org(player, page)
return add_buttons(player, formspec)
end
end
if armor_mod and not ui_mod then
local org = armor.get_armor_formspec
armor.get_armor_formspec = function(self, name)
local formspec = org(self, name)
return add_buttons(minetest.get_player_by_name(name), formspec)
end
end
minetest.register_on_joinplayer(function(player)
local formspec = nil
if armor_mod and not ui_mod then
formspec = armor.get_armor_formspec(self, player:get_player_name())
end
minetest.after(0.65,function()
add_buttons(player, formspec)
end)
end)
local function comp_asc(w1,w2)
if w1.name < w2.name then
return true
end
end
local function comp_desc(w1,w2)
if w1.name > w2.name then
return true
end
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
if fields.sort_asc then
tweak.sort(player, comp_asc)
end
if fields.sort_desc then
tweak.sort(player, comp_desc)
end
if fields.sort then
tweak.sort(player, comp_asc, true)
end
-- player inventory
if minetest.setting_getbool("creative_mode") then
add_buttons(player)
end
end)
-- sort asc without mod prefix
local function comp_in(w1, w2)
local w11 = string.find(w1.name, ":")
local w22 = string.find(w2.name, ":")
if w11 ~= nil then
w11 = string.sub(w1.name,w11)
else
w11 = w1.name
end
if w22 ~= nil then
w22 = string.sub(w2.name,w22)
else
w22 = w2.name
end
if w11 < w22 then
return true
end
end
tweak.concatenate = function(list)
local last = nil
local last_cnt = 100
local refresh = false
for _,stack in ipairs(list) do
local i = _
if refresh then
refresh = false
table.sort(list, comp_asc)
list = tweak.concatenate(list)
break
end
if stack.name ~= "zztmpsortname" and last == stack.name then
if last_cnt < stack.max then
local diff = stack.max - last_cnt
local add = stack.count
if stack.count > diff then
stack.count = stack.count - diff
add = diff
else
stack.name = "zztmpsortname"
refresh = true
end
list[i-1].count = list[i-1].count + add
end
end
last = stack.name
last_cnt = stack.count
end
return list
end
tweak.sort = function(player, mode, con)
local inv = player:get_inventory()
if inv then
local list = inv:get_list("main")
local tmp_list = {}
--write whole list as table
for _,stack in ipairs(list) do
local tbl_stack = stack:to_table()
if tbl_stack == nil then tbl_stack = {name="zztmpsortname"} end
tbl_stack.max = stack:get_stack_max()
tmp_list[_]=tbl_stack
end
-- sort asc/desc
table.sort(tmp_list, mode)
if con then
tmp_list = tweak.concatenate(tmp_list)
table.sort(tmp_list, mode)
end
--write back to inventory
for _,stack in ipairs(tmp_list) do
stack.max = nil
if stack.name ~= "zztmpsortname" then
inv:set_stack("main", _, ItemStack(stack))
else
inv:set_stack("main", _, ItemStack(nil))
end
end
end
end
-- tool break sound + autorefill
function refill(player, stck_name, index)
local inv = player:get_inventory()
for i,stack in ipairs(inv:get_list("main")) do
if stack:get_name() == stck_name then
inv:set_stack("main", index, stack)
stack:clear()
inv:set_stack("main", i, stack)
minetest.log("action", "Inventory Tweaks: refilled stack("..stck_name..") of " .. player:get_player_name() )
return
end
end
end
if auto_refill == true then
minetest.register_on_placenode(function(pos, newnode, placer, oldnode)
if not placer then return end
local index = placer:get_wield_index()
local cnt = placer:get_wielded_item():get_count()-1
if minetest.setting_getbool("creative_mode") then
return
else
if cnt == 0 then
minetest.after(0.01, refill, placer, newnode.name, index)
end
end
end)
end
local wielded = {}
wielded.name = {}
wielded.wear = {}
minetest.register_on_punchnode(function(pos, node, puncher)
if not puncher or minetest.setting_getbool("creative_mode") then
return
end
local name = puncher:get_player_name()
local item = puncher:get_wielded_item()
local tname = item:get_name()
local def = minetest.registered_tools[tname]
wielded.name[name] = tname
if not item or not tname or tname == "" or not def then
return
end
local typ = def.type
if not typ or typ ~= "tool" then
return
end
wielded.wear[name] = item:get_wear()
-- TODO: re-add for custom tools like lighter
end)
minetest.register_on_dignode(function(pos, oldnode, digger)
if not digger then return end
local name = digger:get_player_name()
local item = digger:get_wielded_item()
local index = digger:get_wield_index()
local tname = item:get_name()
local def = minetest.registered_tools[tname]
if not item then
return
end
if tname ~= "" then
if not def then
return
end
end
local old_name = wielded.name[name]
if tname == old_name and tname == "" then
return
end
local old = wielded.wear[name]
if not old and tname == "" then
old = 0
end
local new = item:get_wear()
if old ~= new then
if old and old > 0 and new == 0 then
wielded.wear[name] = new
minetest.sound_play("invtweak_tool_break", {
pos = digger:getpos(),
gain = 0.9,
max_hear_distance = 5
})
if auto_refill == true then
minetest.after(0.01, refill, digger, old_name, index)
end
end
end
end)
|
local auto_refill = minetest.setting_getbool("invtweak_auto_refill") or true
local tweak = {}
tweak.formspec = {}
tweak.buttons = {
--sort_asc
"0.8,0.6;sort_asc;^]".."tooltip[sort_asc;sort Items asc.;#30434C;#FFF]",
--sort_desc
"0.8,0.6;sort_desc;v]".."tooltip[sort_desc;sort Items desc.;#30434C;#FFF]",
--concatenate
"0.8,0.6;sort;·»]".."tooltip[sort;stack Items and sort asc.;#30434C;#FFF]"
}
local function get_formspec_size(formspec)
local w = 8
local h = 7.5
if not formspec then return end
local sstring = string.find(formspec,"size[",1,true)
if sstring ~= nil then
sstring = string.sub(formspec, sstring+5)
local p = string.find(sstring,",")
w = string.sub(sstring,1,p-1)
sstring = string.sub(sstring,p+1,string.find(sstring,"]")+2)
p = string.find(sstring,",")
if p == nil then p = string.find(sstring,"]") end
h = string.sub(sstring,1,p-1)
end
return w,h
end
local function add_buttons(player, formspec)
local name = player:get_player_name()
if not formspec then
formspec = player:get_inventory_formspec()
end
local w,h = get_formspec_size(formspec)
for i=1,#tweak.buttons do
formspec = formspec .. "button["..w-(0.8+(i*0.8))..",0.2;" .. tweak.buttons[i]
end
player:set_inventory_formspec(formspec)
return formspec
end
local armor_mod = minetest.get_modpath("3d_armor")
local ui_mod = minetest.get_modpath("unified_inventory")
-- override mods formspec function
if ui_mod then
local org = unified_inventory.get_formspec
unified_inventory.get_formspec = function(player, page)
local formspec = org(player, page)
return add_buttons(player, formspec)
end
end
if armor_mod and not ui_mod then
local org = armor.get_armor_formspec
armor.get_armor_formspec = function(self, name)
local formspec = org(self, name)
return add_buttons(minetest.get_player_by_name(name), formspec)
end
end
minetest.register_on_joinplayer(function(player)
local formspec = nil
if armor_mod and not ui_mod then
formspec = armor.get_armor_formspec(self, player:get_player_name())
end
minetest.after(0.65,function()
add_buttons(player, formspec)
end)
end)
local function comp_asc(w1,w2)
if w1.name < w2.name then
return true
end
end
local function comp_desc(w1,w2)
if w1.name > w2.name then
return true
end
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
if fields.sort_asc then
tweak.sort(player, comp_asc)
end
if fields.sort_desc then
tweak.sort(player, comp_desc)
end
if fields.sort then
tweak.sort(player, comp_asc, true)
end
-- player inventory
if minetest.setting_getbool("creative_mode") then
add_buttons(player)
end
end)
-- sort asc without mod prefix
local function comp_in(w1, w2)
local w11 = string.find(w1.name, ":")
local w22 = string.find(w2.name, ":")
if w11 ~= nil then
w11 = string.sub(w1.name,w11)
else
w11 = w1.name
end
if w22 ~= nil then
w22 = string.sub(w2.name,w22)
else
w22 = w2.name
end
if w11 < w22 then
return true
end
end
tweak.concatenate = function(list)
local last = nil
local last_cnt = 100
local refresh = false
for _,stack in ipairs(list) do
local i = _
if refresh then
refresh = false
table.sort(list, comp_asc)
list = tweak.concatenate(list)
break
end
if stack.name ~= "zztmpsortname" and last == stack.name then
if last_cnt < stack.max then
local diff = stack.max - last_cnt
local add = stack.count
if stack.count > diff then
stack.count = stack.count - diff
add = diff
else
stack.name = "zztmpsortname"
refresh = true
end
list[i-1].count = list[i-1].count + add
end
end
last = stack.name
last_cnt = stack.count
end
return list
end
tweak.sort = function(player, mode, con)
local inv = player:get_inventory()
if inv then
local list = inv:get_list("main")
local tmp_list = {}
--write whole list as table
for _,stack in ipairs(list) do
local tbl_stack = stack:to_table()
if tbl_stack == nil then tbl_stack = {name="zztmpsortname"} end
tbl_stack.max = stack:get_stack_max()
tmp_list[_]=tbl_stack
end
-- sort asc/desc
table.sort(tmp_list, mode)
if con then
tmp_list = tweak.concatenate(tmp_list)
table.sort(tmp_list, mode)
end
--write back to inventory
for _,stack in ipairs(tmp_list) do
stack.max = nil
if stack.name ~= "zztmpsortname" then
inv:set_stack("main", _, ItemStack(stack))
else
inv:set_stack("main", _, ItemStack(nil))
end
end
end
end
-- tool break sound + autorefill
function refill(player, stck_name, index)
local inv = player:get_inventory()
for i,stack in ipairs(inv:get_list("main")) do
if stack:get_name() == stck_name then
inv:set_stack("main", index, stack)
stack:clear()
inv:set_stack("main", i, stack)
minetest.log("action", "Inventory Tweaks: refilled stack("..stck_name..") of " .. player:get_player_name() )
return
end
end
end
if auto_refill == true then
minetest.register_on_placenode(function(pos, newnode, placer, oldnode)
if not placer then return end
local index = placer:get_wield_index()
local cnt = placer:get_wielded_item():get_count()-1
if minetest.setting_getbool("creative_mode") then
return
else
if cnt == 0 then
minetest.after(0.01, refill, placer, newnode.name, index)
end
end
end)
end
local wielded = {}
wielded.name = {}
wielded.wear = {}
minetest.register_on_punchnode(function(pos, node, puncher)
if not puncher or minetest.setting_getbool("creative_mode") then
return
end
local name = puncher:get_player_name()
local item = puncher:get_wielded_item()
local tname = item:get_name()
local def = minetest.registered_tools[tname]
wielded.name[name] = tname
if not item or not tname or tname == "" or not def then
return
end
local typ = def.type
if not typ or typ ~= "tool" then
return
end
wielded.wear[name] = item:get_wear()
-- TODO: re-add for custom tools like lighter
end)
minetest.register_on_dignode(function(pos, oldnode, digger)
if not digger then return end
local name = digger:get_player_name()
local item = digger:get_wielded_item()
local index = digger:get_wield_index()
local tname = item:get_name()
local def = minetest.registered_tools[tname]
if not item then
return
end
if tname ~= "" then
if not def then
return
end
end
local old_name = wielded.name[name]
if tname == old_name and tname == "" then
return
end
local old = wielded.wear[name]
if not old and tname == "" then
old = 0
end
local new = item:get_wear()
if old ~= new then
if old and old > 0 and new == 0 then
wielded.wear[name] = new
minetest.sound_play("invtweak_tool_break", {
pos = digger:getpos(),
gain = 0.9,
max_hear_distance = 5
})
if auto_refill == true then
minetest.after(0.01, refill, digger, old_name, index)
end
end
end
end)
|
Fixed very rare occurrence with invtweak's formspec - Solves #70 and crash on May 30th, 2015, 18h58
|
Fixed very rare occurrence with invtweak's formspec
- Solves #70 and crash on May 30th, 2015, 18h58
|
Lua
|
unlicense
|
Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,paly2/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,paly2/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Coethium/server-minetestforfun,sys4-fr/server-minetestforfun
|
795ba58832217e5716fe15f88bffeeded364f422
|
src/modules/time_service/utils/best.lua
|
src/modules/time_service/utils/best.lua
|
redis.replicate_commands()
-- REDIS SYNTAX == EVAL {script} layer_prefix:layer_name , date_time
-- Routine called by Redis. If best_layer exists, script will update :best key
-- GITC mod: Add new date and only update if there was a change
if ARGV[1] ~= nil then
local result = 0
if ARGV[1]:match("(%d+)-(%d+)-(%d+)") then
result = redis.call("ZADD", KEYS[1] .. ":dates", 0, ARGV[1])
end
if result == 0 then
--return
end
end
-- End GITC mod
if redis.call("EXISTS", KEYS[1] .. ":best_layer") == 1 and ARGV[1] ~= nil then
local best_layer = redis.call("GET", KEYS[1] .. ":best_layer")
local index = KEYS[1]:match("^.*():")
local layerPrefix = KEYS[1]:sub(1,index)
local best_key = layerPrefix .. best_layer
redis.call("ZADD", best_key .. "_BEST:dates", 0, ARGV[1])
local layers = redis.call("ZREVRANGE", best_key .. ":best_config", 0, -1)
local found = false
for i, layer in ipairs(layers) do
if redis.call("ZRANK", layer, ARGV[1]) ~= nil then
redis.call("HMSET", best_key .. "_BEST:best", ARGV[1], layer)
local hget = redis.call("HGET", best_key .. "_BEST:best", ARGV[1])
redis.call('ECHO', 'the value of hget is ' .. hget)
found = true
break
end
end
if not found then
redis.call("HDEL", best_key .. "_BEST:best", ARGV[1])
redis.call("ZREM", best_key .. "_BEST:dates", ARGV[1])
end
end
|
redis.replicate_commands()
-- REDIS SYNTAX == EVAL {script} layer_prefix:layer_name , date_time
-- Routine called by Redis. If best_layer exists, script will update :best key
-- GITC mod: Add new date and only update if there was a change
if ARGV[1] ~= nil then
local result = 0
if ARGV[1]:match("(%d+)-(%d+)-(%d+)") then
result = redis.call("ZADD", KEYS[1] .. ":dates", 0, ARGV[1])
end
if result == 0 then
--return
end
end
-- End GITC mod
if redis.call("EXISTS", KEYS[1] .. ":best_layer") == 1 and ARGV[1] ~= nil then
local best_layer = redis.call("GET", KEYS[1] .. ":best_layer")
local index = KEYS[1]:match("^.*():")
local layerPrefix = KEYS[1]:sub(1,index)
local best_key = layerPrefix .. best_layer
redis.call("ZADD", best_key .. "_BEST:dates", 0, ARGV[1])
local layers = redis.call("ZREVRANGE", best_key .. ":best_config", 0, -1)
local found = false
for i, layer in ipairs(layers) do
if redis.call("ZRANK", layerPrefix .. layer, ARGV[1]) ~= nil then
redis.call("HMSET", best_key .. "_BEST:best", ARGV[1], layer)
found = true
break
end
end
if not found then
redis.call("HDEL", best_key .. "_BEST:best", ARGV[1])
redis.call("ZREM", best_key .. "_BEST:dates", ARGV[1])
end
end
|
best bug
|
best bug
|
Lua
|
apache-2.0
|
nasa-gibs/onearth,nasa-gibs/onearth,nasa-gibs/onearth,nasa-gibs/onearth,nasa-gibs/onearth,nasa-gibs/onearth
|
f7ea7b13e9a5caa6749ccfa3ba1522a2c0bd126b
|
_glua-tests/issues.lua
|
_glua-tests/issues.lua
|
-- issue #10
local function inspect(options)
options = options or {}
return type(options)
end
assert(inspect(nil) == "table")
local function inspect(options)
options = options or setmetatable({}, {__mode = "test"})
return type(options)
end
assert(inspect(nil) == "table")
-- issue #16
local ok, msg = pcall(function()
local a = {}
a[nil] = 1
end)
assert(not ok and string.find(msg, "table index is nil", 1, true))
-- issue #19
local tbl = {1,2,3,4,5}
assert(#tbl == 5)
assert(table.remove(tbl) == 5)
assert(#tbl == 4)
assert(table.remove(tbl, 3) == 3)
assert(#tbl == 3)
-- issue #24
local tbl = {string.find('hello.world', '.', 0)}
assert(tbl[1] == 1 and tbl[2] == 1)
assert(string.sub('hello.world', 0, 2) == "he")
-- issue 33
local a,b
a = function ()
pcall(function()
end)
coroutine.yield("a")
return b()
end
b = function ()
return "b"
end
local co = coroutine.create(a)
assert(select(2, coroutine.resume(co)) == "a")
assert(select(2, coroutine.resume(co)) == "b")
assert(coroutine.status(co) == "dead")
-- issue 37
function test(a, b, c)
b = b or string.format("b%s", a)
c = c or string.format("c%s", a)
assert(a == "test")
assert(b == "btest")
assert(c == "ctest")
end
test("test")
-- issue 39
assert(string.match("あいうえお", ".*あ.*") == "あいうえお")
assert(string.match("あいうえお", "あいうえお") == "あいうえお")
-- issue 47
assert(string.gsub("A\nA", ".", "A") == "AAA")
-- issue 62
local function level4() error("error!") end
local function level3() level4() end
local function level2() level3() end
local function level1() level2() end
local ok, result = xpcall(level1, function(err)
return debug.traceback("msg", 10)
end)
assert(result == [[msg
stack traceback:]])
ok, result = xpcall(level1, function(err)
return debug.traceback("msg", 9)
end)
assert(result == string.gsub([[msg
stack traceback:
@TAB@[G]: ?]], "@TAB@", "\t"))
local ok, result = xpcall(level1, function(err)
return debug.traceback("msg", 0)
end)
assert(result == string.gsub([[msg
stack traceback:
@TAB@[G]: in function 'traceback'
@[email protected]:87: in function <issues.lua:86>
@TAB@[G]: in function 'error'
@[email protected]:71: in function 'level4'
@[email protected]:72: in function 'level3'
@[email protected]:73: in function 'level2'
@[email protected]:74: in function <issues.lua:74>
@TAB@[G]: in function 'xpcall'
@[email protected]:86: in main chunk
@TAB@[G]: ?]], "@TAB@", "\t"))
local ok, result = xpcall(level1, function(err)
return debug.traceback("msg", 3)
end)
assert(result == string.gsub([[msg
stack traceback:
@[email protected]:71: in function 'level4'
@[email protected]:72: in function 'level3'
@[email protected]:73: in function 'level2'
@[email protected]:74: in function <issues.lua:74>
@TAB@[G]: in function 'xpcall'
@[email protected]:103: in main chunk
@TAB@[G]: ?]], "@TAB@", "\t"))
-- issue 81
local tbl = {
[-1] = "a",
[0] = "b",
[1] = "c",
}
local a, b = next(tbl, nil)
assert( a == -1 and b == "a" or a == 0 and b == "b" or a == 1 and b == "c")
local a, b = next(tbl, a)
assert( a == -1 and b == "a" or a == 0 and b == "b" or a == 1 and b == "c")
local a, b = next(tbl, a)
assert( a == -1 and b == "a" or a == 0 and b == "b" or a == 1 and b == "c")
local a, b = next(tbl, a)
assert( a == nil and b == nil)
local tbl = {'a', 'b'}
local a, b = next(tbl, nil)
assert(a == 1 and b == "a")
local a, b = next(tbl, a)
assert(a == 2 and b == "b")
local a, b = next(tbl, a)
assert(a == nil and b == nil)
-- issue 82
local cr = function()
return coroutine.wrap(function()
coroutine.yield(1, "a")
coroutine.yield(2, "b")
end)
end
local f = cr()
local a, b = f()
assert(a == 1 and b == "a")
local a, b = f()
assert(a == 2 and b == "b")
-- issue 91, 92
local url = "www.aaa.bbb_abc123-321-cba_abc123"
assert(string.match(url, ".-([%w-]*)[.]*") == "www")
local s = "hello.world"
assert(s:match("([^.]+).world") == "hello")
local s = "hello-world"
assert(s:match("([^-]+)-world") == "hello")
-- issue 93
local t = {}
local ok, msg = pcall(function() t.notfound() end)
assert(not ok and string.find(msg, "attempt to call a non-function object", 1, true))
-- issue 150
local util = {
fn = function() end
}
local b
local x = util.fn(
1,
(b or {}).x)
local s = [=[["a"]['b'][9] - ["a"]['b'][8] > ]=]
local result = {}
for i in s:gmatch([=[[[][^%s,]*[]]]=]) do
table.insert(result, i)
end
assert(result[1] == [=[["a"]['b'][9]]=])
assert(result[2] == [=[["a"]['b'][8]]=])
-- issue 168
local expected = 1
local result = math.random(1)
assert(result == expected)
|
-- issue #10
local function inspect(options)
options = options or {}
return type(options)
end
assert(inspect(nil) == "table")
local function inspect(options)
options = options or setmetatable({}, {__mode = "test"})
return type(options)
end
assert(inspect(nil) == "table")
-- issue #16
local ok, msg = pcall(function()
local a = {}
a[nil] = 1
end)
assert(not ok and string.find(msg, "table index is nil", 1, true))
-- issue #19
local tbl = {1,2,3,4,5}
assert(#tbl == 5)
assert(table.remove(tbl) == 5)
assert(#tbl == 4)
assert(table.remove(tbl, 3) == 3)
assert(#tbl == 3)
-- issue #24
local tbl = {string.find('hello.world', '.', 0)}
assert(tbl[1] == 1 and tbl[2] == 1)
assert(string.sub('hello.world', 0, 2) == "he")
-- issue 33
local a,b
a = function ()
pcall(function()
end)
coroutine.yield("a")
return b()
end
b = function ()
return "b"
end
local co = coroutine.create(a)
assert(select(2, coroutine.resume(co)) == "a")
assert(select(2, coroutine.resume(co)) == "b")
assert(coroutine.status(co) == "dead")
-- issue 37
function test(a, b, c)
b = b or string.format("b%s", a)
c = c or string.format("c%s", a)
assert(a == "test")
assert(b == "btest")
assert(c == "ctest")
end
test("test")
-- issue 39
assert(string.match("あいうえお", ".*あ.*") == "あいうえお")
assert(string.match("あいうえお", "あいうえお") == "あいうえお")
-- issue 47
assert(string.gsub("A\nA", ".", "A") == "AAA")
-- issue 62
local function level4() error("error!") end
local function level3() level4() end
local function level2() level3() end
local function level1() level2() end
local ok, result = xpcall(level1, function(err)
return debug.traceback("msg", 10)
end)
assert(result == [[msg
stack traceback:]])
ok, result = xpcall(level1, function(err)
return debug.traceback("msg", 9)
end)
assert(result == string.gsub([[msg
stack traceback:
@TAB@[G]: ?]], "@TAB@", "\t"))
local ok, result = xpcall(level1, function(err)
return debug.traceback("msg", 0)
end)
assert(result == string.gsub([[msg
stack traceback:
@TAB@[G]: in function 'traceback'
@[email protected]:87: in function <issues.lua:86>
@TAB@[G]: in function 'error'
@[email protected]:71: in function 'level4'
@[email protected]:72: in function 'level3'
@[email protected]:73: in function 'level2'
@[email protected]:74: in function <issues.lua:74>
@TAB@[G]: in function 'xpcall'
@[email protected]:86: in main chunk
@TAB@[G]: ?]], "@TAB@", "\t"))
local ok, result = xpcall(level1, function(err)
return debug.traceback("msg", 3)
end)
assert(result == string.gsub([[msg
stack traceback:
@[email protected]:71: in function 'level4'
@[email protected]:72: in function 'level3'
@[email protected]:73: in function 'level2'
@[email protected]:74: in function <issues.lua:74>
@TAB@[G]: in function 'xpcall'
@[email protected]:103: in main chunk
@TAB@[G]: ?]], "@TAB@", "\t"))
-- issue 81
local tbl = {
[-1] = "a",
[0] = "b",
[1] = "c",
}
local a, b = next(tbl, nil)
assert( a == -1 and b == "a" or a == 0 and b == "b" or a == 1 and b == "c")
local a, b = next(tbl, a)
assert( a == -1 and b == "a" or a == 0 and b == "b" or a == 1 and b == "c")
local a, b = next(tbl, a)
assert( a == -1 and b == "a" or a == 0 and b == "b" or a == 1 and b == "c")
local a, b = next(tbl, a)
assert( a == nil and b == nil)
local tbl = {'a', 'b'}
local a, b = next(tbl, nil)
assert(a == 1 and b == "a")
local a, b = next(tbl, a)
assert(a == 2 and b == "b")
local a, b = next(tbl, a)
assert(a == nil and b == nil)
-- issue 82
local cr = function()
return coroutine.wrap(function()
coroutine.yield(1, "a")
coroutine.yield(2, "b")
end)
end
local f = cr()
local a, b = f()
assert(a == 1 and b == "a")
local a, b = f()
assert(a == 2 and b == "b")
-- issue 91, 92
local url = "www.aaa.bbb_abc123-321-cba_abc123"
assert(string.match(url, ".-([%w-]*)[.]*") == "www")
local s = "hello.world"
assert(s:match("([^.]+).world") == "hello")
local s = "hello-world"
assert(s:match("([^-]+)-world") == "hello")
-- issue 93
local t = {}
local ok, msg = pcall(function() t.notfound() end)
assert(not ok and string.find(msg, "attempt to call a non-function object", 1, true))
-- issue 150
local util = {
fn = function() end
}
local b
local x = util.fn(
1,
(b or {}).x)
local s = [=[["a"]['b'][9] - ["a"]['b'][8] > ]=]
local result = {}
for i in s:gmatch([=[[[][^%s,]*[]]]=]) do
table.insert(result, i)
end
assert(result[1] == [=[["a"]['b'][9]]=])
assert(result[2] == [=[["a"]['b'][8]]=])
-- issue 168
local expected = 1
local result = math.random(1)
assert(result == expected)
-- issue 202
local t = {}
ok, res = pcall(table.remove, t)
if not ok or not res then
table.insert(t, {})
else
assert(false)
end
ok, res = pcall(table.remove, t)
ok, res = pcall(table.remove, t)
assert(not ok or not res)
|
Issue #202 : fixed a bug when try to remove elements from a table with 0 length
|
Issue #202 : fixed a bug when try to remove elements from a table with 0 length
|
Lua
|
mit
|
yuin/gopher-lua,kohkimakimoto/gopher-lua,kohkimakimoto/gopher-lua,yuin/gopher-lua
|
ff6d3d7056234188208de520f67b110f53dff038
|
plugins/mod_motd.lua
|
plugins/mod_motd.lua
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
-- Copyright (C) 2010 Jeff Mitchell
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local host = module:get_host();
local motd_text = module:get_option_string("motd_text");
local motd_jid = module:get_option_string("motd_jid", host);
if not motd_text then return; end
local jid_join = require "util.jid".join;
local st = require "util.stanza";
motd_text = motd_text:gsub("^%s*(.-)%s*$", "%1"):gsub("\n%s+", "\n"); -- Strip indentation from the config
module:hook("resource-bind", function (event)
local session = event.session;
local motd_stanza =
st.message({ to = jid_join(session.username, session.host, session.resource), from = motd_jid })
:tag("body"):text(motd_text);
core_route_stanza(hosts[host], motd_stanza);
module:log("debug", "MOTD send to user %s@%s", session.username, session.host);
end);
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
-- Copyright (C) 2010 Jeff Mitchell
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local host = module:get_host();
local motd_text = module:get_option_string("motd_text");
local motd_jid = module:get_option_string("motd_jid", host);
if not motd_text then return; end
local jid_join = require "util.jid".join;
local st = require "util.stanza";
motd_text = motd_text:gsub("^%s*(.-)%s*$", "%1"):gsub("\n%s+", "\n"); -- Strip indentation from the config
module:hook("presence/bare", function (event)
local session, stanza = event.origin, event.stanza;
if not session.presence and not stanza.attr.type then
local motd_stanza =
st.message({ to = session.full_jid, from = motd_jid })
:tag("body"):text(motd_text);
core_route_stanza(hosts[host], motd_stanza);
module:log("debug", "MOTD send to user %s", session.full_jid);
end
end, 1);
|
mod_motd: Use presence/bare to catch a client's initial presence and send the MOTD then (fixes #282)
|
mod_motd: Use presence/bare to catch a client's initial presence and send the MOTD then (fixes #282)
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
a5f0c015346c90906e7bbfe76f39a64e262c3c6a
|
spec/helpers/perf/drivers/local.lua
|
spec/helpers/perf/drivers/local.lua
|
local perf = require("spec.helpers.perf")
local pl_path = require("pl.path")
local tools = require("kong.tools.utils")
local helpers
local _M = {}
local mt = {__index = _M}
local UPSTREAM_PORT = 62412
local WRK_SCRIPT_PREFIX = "/tmp/perf-wrk-"
local KONG_ERROR_LOG_PATH = "/tmp/error.log"
function _M.new(opts)
return setmetatable({
opts = opts,
log = perf.new_logger("[local]"),
upstream_nginx_pid = nil,
nginx_bin = nil,
wrk_bin = nil,
git_head = nil,
git_stashed = false,
systemtap_sanity_checked = false,
systemtap_dest_path = nil,
}, mt)
end
function _M:setup()
local bin
for _, test in ipairs({"nginx", "/usr/local/openresty/nginx/sbin/nginx"}) do
bin, _ = perf.execute("which " .. test)
if bin then
self.nginx_bin = bin
break
end
end
if not self.nginx_bin then
return nil, "nginx binary not found, either install nginx package or Kong"
end
bin = perf.execute("which wrk")
if not bin then
return nil, "wrk binary not found"
end
self.wrk_bin = bin
bin = perf.execute("which git")
if not bin then
return nil, "git binary not found"
end
package.loaded["spec.helpers"] = nil
helpers = require("spec.helpers")
return helpers
end
function _M:teardown()
if self.upstream_nginx_pid then
local _, err = perf.execute("kill " .. self.upstream_nginx_pid)
if err then
return false, "stopping upstream: " .. err
end
self.upstream_nginx_pid = nil
end
perf.git_restore()
perf.execute("rm -v " .. WRK_SCRIPT_PREFIX .. "*.lua",
{ logger = self.log.log_exec })
return self:stop_kong()
end
function _M:start_upstreams(conf, port_count)
local listeners = {}
for i=1,port_count do
listeners[i] = ("listen %d reuseport;"):format(UPSTREAM_PORT+i-1)
end
listeners = table.concat(listeners, "\n")
local nginx_conf_path = "/tmp/perf-test-nginx.conf"
local nginx_prefix = "/tmp/perf-test-nginx"
pl_path.mkdir(nginx_prefix .. "/logs")
local f = io.open(nginx_conf_path, "w")
f:write(([[
events {}
pid nginx.pid;
error_log error.log;
http {
access_log off;
server {
%s
%s
}
}
]]):format(listeners, conf))
f:close()
local res, err = perf.execute("nginx -c " .. nginx_conf_path ..
" -p " .. nginx_prefix,
{ logger = self.log.log_exec })
if err then
return false, "failed to start nginx: " .. err .. ": " .. (res or "nil")
end
f = io.open(nginx_prefix .. "/nginx.pid")
local pid = f:read()
f:close()
if not tonumber(pid) then
return false, "pid is not a number: " .. pid
end
self.upstream_nginx_pid = pid
self.log.info("upstream started at PID: " .. pid)
local uris = {}
for i=1,port_count do
uris[i] = "http://127.0.0.1:" .. UPSTREAM_PORT+i-1
end
return uris
end
function _M:start_kong(version, kong_conf)
if not version:startswith("git:") then
return nil, "\"local\" driver only support testing between git commits, " ..
"version should be prefixed with \"git:\""
end
version = version:sub(#("git:")+1)
perf.git_checkout(version)
-- cleanup log file
perf.execute("echo > /tmp/kong_error.log")
kong_conf = kong_conf or {}
kong_conf['proxy_access_log'] = "/dev/null"
kong_conf['proxy_error_log'] = KONG_ERROR_LOG_PATH
kong_conf['admin_error_log'] = KONG_ERROR_LOG_PATH
return helpers.start_kong(kong_conf)
end
function _M:stop_kong()
helpers.stop_kong()
return true
end
function _M:get_start_load_cmd(stub, script, uri)
if not uri then
uri = string.format("http://%s:%s",
helpers.get_proxy_ip(),
helpers.get_proxy_port())
end
local script_path
if script then
script_path = WRK_SCRIPT_PREFIX .. tools.random_string() .. ".lua"
local f = assert(io.open(script_path, "w"))
assert(f:write(script))
assert(f:close())
end
script_path = script_path and ("-s " .. script_path) or ""
return stub:format(script_path, uri)
end
local function check_systemtap_sanity(self)
local bin, _ = perf.execute("which stap")
if not bin then
return nil, "systemtap binary not found"
end
-- try compile the kernel module
local out, err = perf.execute("sudo stap -ve 'probe begin { print(\"hello\\n\"); exit();}'")
if err then
return nil, "systemtap failed to compile kernel module: " .. (out or "nil") ..
" err: " .. (err or "nil") .. "\n Did you install gcc and kernel headers?"
end
local cmds = {
"stat /tmp/stapxx || git clone https://github.com/Kong/stapxx /tmp/stapxx",
"stat /tmp/perf-ost || git clone https://github.com/openresty/openresty-systemtap-toolkit /tmp/perf-ost",
"stat /tmp/perf-fg || git clone https://github.com/brendangregg/FlameGraph /tmp/perf-fg"
}
for _, cmd in ipairs(cmds) do
local _, err = perf.execute(cmd, { logger = self.log.log_exec })
if err then
return nil, cmd .. " failed: " .. err
end
end
return true
end
function _M:get_start_stapxx_cmd(sample, ...)
if not self.systemtap_sanity_checked then
local ok, err = check_systemtap_sanity(self)
if not ok then
return nil, err
end
self.systemtap_sanity_checked = true
end
-- find one of kong's child process hopefully it's a worker
-- (does kong have cache loader/manager?)
local pid, err = perf.execute("pid=$(cat servroot/pids/nginx.pid);" ..
"cat /proc/$pid/task/$pid/children | awk '{print $1}'")
if not pid then
return nil, "failed to get Kong worker PID: " .. (err or "nil")
end
local args = table.concat({...}, " ")
self.systemtap_dest_path = "/tmp/" .. tools.random_string()
return "sudo /tmp/stapxx/stap++ /tmp/stapxx/samples/" .. sample ..
" --skip-badvars -D MAXSKIPPED=1000000 -x " .. pid ..
" " .. args ..
" > " .. self.systemtap_dest_path .. ".bt"
end
function _M:get_wait_stapxx_cmd(timeout)
return "lsmod | grep stap_"
end
function _M:generate_flamegraph(title, opts)
local path = self.systemtap_dest_path
self.systemtap_dest_path = nil
local f = io.open(path .. ".bt")
if not f or f:seek("end") == 0 then
return nil, "systemtap output is empty, possibly no sample are captured"
end
f:close()
local cmds = {
"/tmp/perf-ost/fix-lua-bt " .. path .. ".bt > " .. path .. ".fbt",
"/tmp/perf-fg/stackcollapse-stap.pl " .. path .. ".fbt > " .. path .. ".cbt",
"/tmp/perf-fg/flamegraph.pl --title='" .. title .. "' " .. (opts or "") .. " " .. path .. ".cbt > " .. path .. ".svg",
}
local err
for _, cmd in ipairs(cmds) do
_, err = perf.execute(cmd, { logger = self.log.log_exec })
if err then
return nil, cmd .. " failed: " .. err
end
end
local out, _ = perf.execute("cat " .. path .. ".svg")
perf.execute("rm " .. path .. ".*")
return out
end
function _M:save_error_log(path)
return perf.execute("mv " .. KONG_ERROR_LOG_PATH .. " '" .. path .. "'",
{ logger = self.log.log_exec })
end
return _M
|
local perf = require("spec.helpers.perf")
local pl_path = require("pl.path")
local tools = require("kong.tools.utils")
local helpers
local _M = {}
local mt = {__index = _M}
local UPSTREAM_PORT = 62412
local WRK_SCRIPT_PREFIX = "/tmp/perf-wrk-"
local KONG_ERROR_LOG_PATH = "/tmp/error.log"
function _M.new(opts)
return setmetatable({
opts = opts,
log = perf.new_logger("[local]"),
upstream_nginx_pid = nil,
nginx_bin = nil,
wrk_bin = nil,
git_head = nil,
git_stashed = false,
systemtap_sanity_checked = false,
systemtap_dest_path = nil,
}, mt)
end
function _M:setup()
local bin
for _, test in ipairs({"nginx", "/usr/local/openresty/nginx/sbin/nginx"}) do
bin, _ = perf.execute("which " .. test)
if bin then
self.nginx_bin = bin
break
end
end
if not self.nginx_bin then
return nil, "nginx binary not found, either install nginx package or Kong"
end
bin = perf.execute("which wrk")
if not bin then
return nil, "wrk binary not found"
end
self.wrk_bin = bin
bin = perf.execute("which git")
if not bin then
return nil, "git binary not found"
end
package.loaded["spec.helpers"] = nil
helpers = require("spec.helpers")
return helpers
end
function _M:teardown()
if self.upstream_nginx_pid then
local _, err = perf.execute("kill " .. self.upstream_nginx_pid)
if err then
return false, "stopping upstream: " .. err
end
self.upstream_nginx_pid = nil
end
perf.git_restore()
perf.execute("rm -vf " .. WRK_SCRIPT_PREFIX .. "*.lua",
{ logger = self.log.log_exec })
return self:stop_kong()
end
function _M:start_upstreams(conf, port_count)
local listeners = {}
for i=1,port_count do
listeners[i] = ("listen %d reuseport;"):format(UPSTREAM_PORT+i-1)
end
listeners = table.concat(listeners, "\n")
local nginx_conf_path = "/tmp/perf-test-nginx.conf"
local nginx_prefix = "/tmp/perf-test-nginx"
pl_path.mkdir(nginx_prefix)
pl_path.mkdir(nginx_prefix .. "/logs")
local f = io.open(nginx_conf_path, "w")
f:write(([[
events {}
pid nginx.pid;
error_log error.log;
http {
access_log off;
server {
%s
%s
}
}
]]):format(listeners, conf))
f:close()
local res, err = perf.execute("nginx -c " .. nginx_conf_path ..
" -p " .. nginx_prefix,
{ logger = self.log.log_exec })
if err then
return false, "failed to start nginx: " .. err .. ": " .. (res or "nil")
end
f = io.open(nginx_prefix .. "/nginx.pid")
local pid = f:read()
f:close()
if not tonumber(pid) then
return false, "pid is not a number: " .. pid
end
self.upstream_nginx_pid = pid
self.log.info("upstream started at PID: " .. pid)
local uris = {}
for i=1,port_count do
uris[i] = "http://127.0.0.1:" .. UPSTREAM_PORT+i-1
end
return uris
end
function _M:start_kong(version, kong_conf)
if not version:startswith("git:") then
return nil, "\"local\" driver only support testing between git commits, " ..
"version should be prefixed with \"git:\""
end
version = version:sub(#("git:")+1)
perf.git_checkout(version)
-- cleanup log file
perf.execute("echo > /tmp/kong_error.log")
kong_conf = kong_conf or {}
kong_conf['proxy_access_log'] = "/dev/null"
kong_conf['proxy_error_log'] = KONG_ERROR_LOG_PATH
kong_conf['admin_error_log'] = KONG_ERROR_LOG_PATH
return helpers.start_kong(kong_conf)
end
function _M:stop_kong()
helpers.stop_kong()
return true
end
function _M:get_start_load_cmd(stub, script, uri)
if not uri then
uri = string.format("http://%s:%s",
helpers.get_proxy_ip(),
helpers.get_proxy_port())
end
local script_path
if script then
script_path = WRK_SCRIPT_PREFIX .. tools.random_string() .. ".lua"
local f = assert(io.open(script_path, "w"))
assert(f:write(script))
assert(f:close())
end
script_path = script_path and ("-s " .. script_path) or ""
return stub:format(script_path, uri)
end
local function check_systemtap_sanity(self)
local bin, _ = perf.execute("which stap")
if not bin then
return nil, "systemtap binary not found"
end
-- try compile the kernel module
local out, err = perf.execute("sudo stap -ve 'probe begin { print(\"hello\\n\"); exit();}'")
if err then
return nil, "systemtap failed to compile kernel module: " .. (out or "nil") ..
" err: " .. (err or "nil") .. "\n Did you install gcc and kernel headers?"
end
local cmds = {
"stat /tmp/stapxx || git clone https://github.com/Kong/stapxx /tmp/stapxx",
"stat /tmp/perf-ost || git clone https://github.com/openresty/openresty-systemtap-toolkit /tmp/perf-ost",
"stat /tmp/perf-fg || git clone https://github.com/brendangregg/FlameGraph /tmp/perf-fg"
}
for _, cmd in ipairs(cmds) do
local _, err = perf.execute(cmd, { logger = self.log.log_exec })
if err then
return nil, cmd .. " failed: " .. err
end
end
return true
end
function _M:get_start_stapxx_cmd(sample, ...)
if not self.systemtap_sanity_checked then
local ok, err = check_systemtap_sanity(self)
if not ok then
return nil, err
end
self.systemtap_sanity_checked = true
end
-- find one of kong's child process hopefully it's a worker
-- (does kong have cache loader/manager?)
local pid, err = perf.execute("pid=$(cat servroot/pids/nginx.pid);" ..
"cat /proc/$pid/task/$pid/children | awk '{print $1}'")
if not pid then
return nil, "failed to get Kong worker PID: " .. (err or "nil")
end
local args = table.concat({...}, " ")
self.systemtap_dest_path = "/tmp/" .. tools.random_string()
return "sudo /tmp/stapxx/stap++ /tmp/stapxx/samples/" .. sample ..
" --skip-badvars -D MAXSKIPPED=1000000 -x " .. pid ..
" " .. args ..
" > " .. self.systemtap_dest_path .. ".bt"
end
function _M:get_wait_stapxx_cmd(timeout)
return "lsmod | grep stap_"
end
function _M:generate_flamegraph(title, opts)
local path = self.systemtap_dest_path
self.systemtap_dest_path = nil
local f = io.open(path .. ".bt")
if not f or f:seek("end") == 0 then
return nil, "systemtap output is empty, possibly no sample are captured"
end
f:close()
local cmds = {
"/tmp/perf-ost/fix-lua-bt " .. path .. ".bt > " .. path .. ".fbt",
"/tmp/perf-fg/stackcollapse-stap.pl " .. path .. ".fbt > " .. path .. ".cbt",
"/tmp/perf-fg/flamegraph.pl --title='" .. title .. "' " .. (opts or "") .. " " .. path .. ".cbt > " .. path .. ".svg",
}
local err
for _, cmd in ipairs(cmds) do
_, err = perf.execute(cmd, { logger = self.log.log_exec })
if err then
return nil, cmd .. " failed: " .. err
end
end
local out, _ = perf.execute("cat " .. path .. ".svg")
perf.execute("rm " .. path .. ".*")
return out
end
function _M:save_error_log(path)
return perf.execute("mv " .. KONG_ERROR_LOG_PATH .. " '" .. path .. "'",
{ logger = self.log.log_exec })
end
return _M
|
fix(tests) add pl_path.mkdir(nginx_prefix) (#8272)
|
fix(tests) add pl_path.mkdir(nginx_prefix) (#8272)
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
8be1423276d1993887bfd9c365ec31a86e515494
|
MMOCoreORB/bin/scripts/mobile/lair/tatooine_eopie_lair_neutral_small.lua
|
MMOCoreORB/bin/scripts/mobile/lair/tatooine_eopie_lair_neutral_small.lua
|
-- Generated by LairTool
tatooine_eopie_lair_neutral_small = Lair:new {
mobiles = {{"eopie", 0}},
spawnLimit = 15,
buildingsVeryEasy = {"object/tangible/lair/base/poi_all_lair_insecthill_small.iff"},
buildingsEasy = {"object/tangible/lair/base/poi_all_lair_insecthill_small.iff"},
buildingsMedium = {"object/tangible/lair/base/poi_all_lair_insecthill_small.iff"},
buildingsHard = {"object/tangible/lair/base/poi_all_lair_insecthill_small.iff"},
buildingsVeryHard = {"object/tangible/lair/base/poi_all_lair_insecthill_small.iff"}
}
addLairTemplate("tatooine_eopie_lair_neutral_small", tatooine_eopie_lair_neutral_small)
|
-- Generated by LairTool
tatooine_eopie_lair_neutral_small = Lair:new {
mobiles = {{"eopie", 0}},
spawnLimit = 15,
buildingsVeryEasy = {"object/tangible/lair/eopie/lair_eopie.iff"},
buildingsEasy = {"object/tangible/lair/eopie/lair_eopie.iff"},
buildingsMedium = {"object/tangible/lair/eopie/lair_eopie.iff"},
buildingsHard = {"object/tangible/lair/eopie/lair_eopie.iff"},
buildingsVeryHard = {"object/tangible/lair/eopie/lair_eopie.iff"}
}
addLairTemplate("tatooine_eopie_lair_neutral_small", tatooine_eopie_lair_neutral_small)
|
[fixed] Mantis 3076: Eopie lair type
|
[fixed] Mantis 3076: Eopie lair type
Change-Id: I596f3e3cecc8bf58e0a5b7165122755d518ab96d
|
Lua
|
agpl-3.0
|
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
|
d4867ba654b20ac684ce401bd56daf65cddc66b1
|
Boilerplate_!Base/src/lib/LoadingEnd.lua
|
Boilerplate_!Base/src/lib/LoadingEnd.lua
|
--------------------------------------------------------
-- This file is part of the JX3 Plugin Project.
-- @desc : ɴ
-- @copyright: Copyright (c) 2009 Kingsoft Co., Ltd.
--------------------------------------------------------
-------------------------------------------------------------------------------------------------------
-- these global functions are accessed all the time by the event handler
-- so caching them is worth the effort
-------------------------------------------------------------------------------------------------------
local ipairs, pairs, next, pcall, select = ipairs, pairs, next, pcall, select
local string, math, table = string, math, table
-- lib apis caching
local X = Boilerplate
local UI, GLOBAL, CONSTANT, wstring, lodash = X.UI, X.GLOBAL, X.CONSTANT, X.wstring, X.lodash
-------------------------------------------------------------------------------------------------------
local PROXY = {}
if IsDebugClient() then
function PROXY.DebugSetVal(szKey, oVal)
PROXY[szKey] = oVal
end
end
for k, v in pairs(X) do
PROXY[k] = v
X[k] = nil
end
setmetatable(X, {
__metatable = true,
__index = PROXY,
__newindex = function() assert(false, X.NSFormatString('DO NOT modify {$NS} after initialized!!!')) end,
__tostring = function(t) return X.NSFormatString('{$NS} (base library)') end,
})
FireUIEvent(X.NSFormatString('{$NS}_BASE_LOADING_END'))
X.RegisterInit(X.NSFormatString('{$NS}#AUTHOR_TIP'), function()
local Farbnamen = _G.MY_Farbnamen
if Farbnamen and Farbnamen.RegisterHeader then
for dwID, szName in X.pairs_c(X.PACKET_INFO.AUTHOR_ROLES) do
Farbnamen.RegisterHeader(szName, dwID, X.PACKET_INFO.AUTHOR_HEADER)
end
for szName, _ in X.pairs_c(X.PACKET_INFO.AUTHOR_PROTECT_NAMES) do
Farbnamen.RegisterHeader(szName, '*', X.PACKET_INFO.AUTHOR_FAKE_HEADER)
end
end
end)
do
local function OnKeyPanelBtnLButtonUp()
local frame = Station.SearchFrame('KeyPanel')
local btn = frame:Lookup('Btn_Sure')
local edit = frame:Lookup('Edit_Key')
if not btn or not edit then
return
end
local szText = X.DecryptString('2,' .. edit:GetText())
if not szText then
return
end
local aParam = X.DecodeLUAData(szText)
if not X.IsTable(aParam) then
return
end
local szCRC = aParam[1]
local szCorrect = X.PACKET_INFO.NAME_SPACE .. GetStringCRC(X.GetUserRoleName() .. '65e33433-d13c-4269-adac-f091d4a57d4b')
if szCRC ~= szCorrect then
return
end
local nExpire = tonumber(aParam[2] or '')
if not nExpire or (nExpire ~= 0 and nExpire < GetCurrentTime()) then
return
end
local szCmd = aParam[3]
if szCmd == 'R' then
for _, szKey in ipairs(aParam[4]) do
X.IsRestricted(szKey, false)
end
end
frame:Destroy()
PlaySound(SOUND.UI_SOUND, g_sound.LevelUp)
end
local function HookKeyPanel()
local frame = Station.SearchFrame('KeyPanel')
local btn = frame:Lookup('Btn_Sure')
local edit = frame:Lookup('Edit_Key')
if not btn or not edit then
return
end
edit:SetLimit(-1)
HookTableFunc(btn, 'OnLButtonUp', OnKeyPanelBtnLButtonUp)
end
local function UnhookPanel()
local frame = Station.SearchFrame('KeyPanel')
local btn = frame:Lookup('Btn_Sure')
local edit = frame:Lookup('Edit_Key')
if not btn or not edit then
return
end
UnhookTableFunc(btn, 'OnLButtonUp', OnKeyPanelBtnLButtonUp)
end
X.RegisterFrameCreate('KeyPanel', 'LIB.KeyPanel_Restriction', HookKeyPanel)
X.RegisterInit('LIB.KeyPanel_Restriction', HookKeyPanel)
X.RegisterReload('LIB.KeyPanel_Restriction', UnhookPanel)
end
|
--------------------------------------------------------
-- This file is part of the JX3 Plugin Project.
-- @desc : ɴ
-- @copyright: Copyright (c) 2009 Kingsoft Co., Ltd.
--------------------------------------------------------
-------------------------------------------------------------------------------------------------------
-- these global functions are accessed all the time by the event handler
-- so caching them is worth the effort
-------------------------------------------------------------------------------------------------------
local ipairs, pairs, next, pcall, select = ipairs, pairs, next, pcall, select
local string, math, table = string, math, table
-- lib apis caching
local X = Boilerplate
local UI, GLOBAL, CONSTANT, wstring, lodash = X.UI, X.GLOBAL, X.CONSTANT, X.wstring, X.lodash
-------------------------------------------------------------------------------------------------------
local PROXY = {}
if IsDebugClient() then
function PROXY.DebugSetVal(szKey, oVal)
PROXY[szKey] = oVal
end
end
for k, v in pairs(X) do
PROXY[k] = v
X[k] = nil
end
setmetatable(X, {
__metatable = true,
__index = PROXY,
__newindex = function() assert(false, X.NSFormatString('DO NOT modify {$NS} after initialized!!!')) end,
__tostring = function(t) return X.NSFormatString('{$NS} (base library)') end,
})
FireUIEvent(X.NSFormatString('{$NS}_BASE_LOADING_END'))
X.RegisterInit(X.NSFormatString('{$NS}#AUTHOR_TIP'), function()
local Farbnamen = _G.MY_Farbnamen
if Farbnamen and Farbnamen.RegisterHeader then
for dwID, szName in X.pairs_c(X.PACKET_INFO.AUTHOR_ROLES) do
Farbnamen.RegisterHeader(szName, dwID, X.PACKET_INFO.AUTHOR_HEADER)
end
for szName, _ in X.pairs_c(X.PACKET_INFO.AUTHOR_PROTECT_NAMES) do
Farbnamen.RegisterHeader(szName, '*', X.PACKET_INFO.AUTHOR_FAKE_HEADER)
end
end
end)
do
local function OnKeyPanelBtnLButtonUp()
local frame = Station.SearchFrame('KeyPanel')
if not frame then
return
end
local btn = frame:Lookup('Btn_Sure')
local edit = frame:Lookup('Edit_Key')
if not btn or not edit then
return
end
local szText = X.DecryptString('2,' .. edit:GetText())
if not szText then
return
end
local aParam = X.DecodeLUAData(szText)
if not X.IsTable(aParam) then
return
end
local szCRC = aParam[1]
local szCorrect = X.PACKET_INFO.NAME_SPACE .. GetStringCRC(X.GetUserRoleName() .. '65e33433-d13c-4269-adac-f091d4a57d4b')
if szCRC ~= szCorrect then
return
end
local nExpire = tonumber(aParam[2] or '')
if not nExpire or (nExpire ~= 0 and nExpire < GetCurrentTime()) then
return
end
local szCmd = aParam[3]
if szCmd == 'R' then
for _, szKey in ipairs(aParam[4]) do
X.IsRestricted(szKey, false)
end
end
frame:Destroy()
PlaySound(SOUND.UI_SOUND, g_sound.LevelUp)
end
local function HookKeyPanel()
local frame = Station.SearchFrame('KeyPanel')
if not frame then
return
end
local btn = frame:Lookup('Btn_Sure')
local edit = frame:Lookup('Edit_Key')
if not btn or not edit then
return
end
edit:SetLimit(-1)
HookTableFunc(btn, 'OnLButtonUp', OnKeyPanelBtnLButtonUp)
end
local function UnhookPanel()
local frame = Station.SearchFrame('KeyPanel')
if not frame then
return
end
local btn = frame:Lookup('Btn_Sure')
local edit = frame:Lookup('Edit_Key')
if not btn or not edit then
return
end
UnhookTableFunc(btn, 'OnLButtonUp', OnKeyPanelBtnLButtonUp)
end
X.RegisterFrameCreate('KeyPanel', 'LIB.KeyPanel_Restriction', HookKeyPanel)
X.RegisterInit('LIB.KeyPanel_Restriction', HookKeyPanel)
X.RegisterReload('LIB.KeyPanel_Restriction', UnhookPanel)
end
|
fix: 修复加载完成报错问题
|
fix: 修复加载完成报错问题
|
Lua
|
bsd-3-clause
|
tinymins/MY
|
c8b699c068c96bf8d8e7181c47246072c74c8460
|
frontend/document/document.lua
|
frontend/document/document.lua
|
--[[
This is a registry for document providers
]]--
DocumentRegistry = {
providers = { }
}
function DocumentRegistry:addProvider(extension, mimetype, provider)
table.insert(self.providers, { extension = extension, mimetype = mimetype, provider = provider })
end
function DocumentRegistry:getProvider(file)
-- TODO: some implementation based on mime types?
local extension = string.lower(string.match(file, ".+%.([^.]+)") or "")
for _, provider in ipairs(self.providers) do
if extension == provider.extension then
return provider.provider
end
end
end
function DocumentRegistry:openDocument(file)
return self:getProvider(file):new{file = file}
end
--[[
This is an abstract interface to a document
]]--
Document = {
-- file name
file = nil,
info = {
-- whether the document is pageable
has_pages = false,
-- whether words can be provided
has_words = false,
-- whether hyperlinks can be provided
has_hyperlinks = false,
-- whether (native to format) annotations can be provided
has_annotations = false,
-- whether pages can be rotated
is_rotatable = false,
number_of_pages = 0,
-- if not pageable, length of the document in pixels
doc_height = 0,
-- other metadata
title = "",
author = "",
date = ""
},
-- flag to show whether the document was opened successfully
is_open = false,
error_message = nil,
-- flag to show that the document needs to be unlocked by a password
is_locked = false,
}
function Document:new(o)
local o = o or {}
setmetatable(o, self)
self.__index = self
if o.init then o:init() end
return o
end
-- override this method to open a document
function Document:init()
end
-- this might be overridden by a document implementation
function Document:unlock(password)
-- return true instead when the password provided unlocked the document
return false
end
-- this might be overridden by a document implementation
function Document:close()
if self.is_open then
self.is_open = false
self._document:close()
end
end
-- this might be overridden by a document implementation
function Document:getNativePageDimensions(pageno)
local hash = "pgdim|"..self.file.."|"..pageno
local cached = Cache:check(hash)
if cached then
return cached[1]
end
local page = self._document:openPage(pageno)
local page_size_w, page_size_h = page:getSize(self.dc_null)
local page_size = Geom:new{ w = page_size_w, h = page_size_h }
Cache:insert(hash, CacheItem:new{ page_size })
page:close()
return page_size
end
function Document:_readMetadata()
if self.info.has_pages then
self.info.number_of_pages = self._document:getPages()
else
self.info.doc_height = self._document:getFullHeight()
end
return true
end
-- calculates page dimensions
function Document:getPageDimensions(pageno, zoom, rotation)
local native_dimen = self:getNativePageDimensions(pageno):copy()
if rotation == 90 or rotation == 270 then
-- switch orientation
native_dimen.w, native_dimen.h = native_dimen.h, native_dimen.w
end
native_dimen:scaleBy(zoom)
DEBUG("dimen for pageno", pageno, "zoom", zoom, "rotation", rotation, "is", native_dimen)
return native_dimen
end
--[[
This method returns pagesize if bbox is corrupted
--]]
function Document:getUsedBBoxDimensions(pageno, zoom, rotation)
ubbox = self:getUsedBBox(pageno)
if ubbox.x0 < 0 or ubbox.y0 < 0 or ubbox.x1 < 0 or ubbox.y1 < 0 then
-- if document's bbox info is corrupted, we use the page size
ubbox_dimen = self:getPageDimensions(pageno, zoom, rotation)
else
ubbox_dimen = Geom:new{
x = ubbox.x0,
y = ubbox.y0,
w = ubbox.x1 - ubbox.x0,
h = ubbox.y1 - ubbox.y0,
}
if zoom ~= 1 then
ubbox_dimen:transformByScale(zoom)
end
end
return ubbox_dimen
end
function Document:getToc()
return self._document:getToc()
end
function Document:renderPage(pageno, rect, zoom, rotation, render_mode)
local hash = "renderpg|"..self.file.."|"..pageno.."|"..zoom.."|"..rotation
local page_size = self:getPageDimensions(pageno, zoom, rotation)
-- this will be the size we actually render
local size = page_size
-- we prefer to render the full page, if it fits into cache
if not Cache:willAccept(size.w * size.h / 2) then
-- whole page won't fit into cache
DEBUG("rendering only part of the page")
-- TODO: figure out how to better segment the page
if not rect then
DEBUG("aborting, since we do not have a specification for that part")
-- required part not given, so abort
return
end
-- only render required part
hash = "renderpg|"..self.file.."|"..pageno.."|"..zoom.."|"..rotation.."|"..tostring(rect)
size = rect
end
-- prepare cache item with contained blitbuffer
local tile = CacheItem:new{
size = size.w * size.h / 2 + 64, -- estimation
excerpt = size,
pageno = pageno,
bb = Blitbuffer.new(size.w, size.h)
}
-- create a draw context
local dc = DrawContext.new()
dc:setRotate(rotation)
-- correction of rotation
if rotation == 90 then
dc:setOffset(page_size.w, 0)
elseif rotation == 180 then
dc:setOffset(page_size.w, page_size.h)
elseif rotation == 270 then
dc:setOffset(0, page_size.h)
end
dc:setZoom(zoom)
-- render
local page = self._document:openPage(pageno)
page:draw(dc, tile.bb, size.x, size.y, render_mode)
page:close()
Cache:insert(hash, tile)
return tile
end
-- a hint for the cache engine to paint a full page to the cache
-- TODO: this should trigger a background operation
function Document:hintPage(pageno, zoom, rotation)
self:renderPage(pageno, nil, zoom, rotation)
end
--[[
Draw page content to blitbuffer.
1. find tile in cache
2. if not found, call renderPage
@target: target blitbuffer
@rect: visible_area inside document page
--]]
function Document:drawPage(target, x, y, rect, pageno, zoom, rotation, render_mode)
local hash_full_page = "renderpg|"..self.file.."|"..pageno.."|"..zoom.."|"..rotation
local hash_excerpt = "renderpg|"..self.file.."|"..pageno.."|"..zoom.."|"..rotation.."|"..tostring(rect)
local tile = Cache:check(hash_full_page)
if not tile then
tile = Cache:check(hash_excerpt)
if not tile then
DEBUG("rendering")
tile = self:renderPage(pageno, rect, zoom, rotation, render_mode)
end
end
DEBUG("now painting", tile, rect)
target:blitFrom(tile.bb,
x, y,
rect.x - tile.excerpt.x,
rect.y - tile.excerpt.y,
rect.w, rect.h)
end
function Document:getPageText(pageno)
-- is this worth caching? not done yet.
local page = self._document:openPage(pageno)
local text = page:getPageText()
page:close()
return text
end
-- load implementations:
require "document/pdfdocument"
require "document/djvudocument"
require "document/credocument"
|
--[[
This is a registry for document providers
]]--
DocumentRegistry = {
providers = { }
}
function DocumentRegistry:addProvider(extension, mimetype, provider)
table.insert(self.providers, { extension = extension, mimetype = mimetype, provider = provider })
end
function DocumentRegistry:getProvider(file)
-- TODO: some implementation based on mime types?
local extension = string.lower(string.match(file, ".+%.([^.]+)") or "")
for _, provider in ipairs(self.providers) do
if extension == provider.extension then
return provider.provider
end
end
end
function DocumentRegistry:openDocument(file)
return self:getProvider(file):new{file = file}
end
--[[
This is an abstract interface to a document
]]--
Document = {
-- file name
file = nil,
info = {
-- whether the document is pageable
has_pages = false,
-- whether words can be provided
has_words = false,
-- whether hyperlinks can be provided
has_hyperlinks = false,
-- whether (native to format) annotations can be provided
has_annotations = false,
-- whether pages can be rotated
is_rotatable = false,
number_of_pages = 0,
-- if not pageable, length of the document in pixels
doc_height = 0,
-- other metadata
title = "",
author = "",
date = ""
},
-- flag to show whether the document was opened successfully
is_open = false,
error_message = nil,
-- flag to show that the document needs to be unlocked by a password
is_locked = false,
}
function Document:new(o)
local o = o or {}
setmetatable(o, self)
self.__index = self
if o.init then o:init() end
return o
end
-- override this method to open a document
function Document:init()
end
-- this might be overridden by a document implementation
function Document:unlock(password)
-- return true instead when the password provided unlocked the document
return false
end
-- this might be overridden by a document implementation
function Document:close()
if self.is_open then
self.is_open = false
self._document:close()
end
end
-- this might be overridden by a document implementation
function Document:getNativePageDimensions(pageno)
local hash = "pgdim|"..self.file.."|"..pageno
local cached = Cache:check(hash)
if cached then
return cached[1]
end
local page = self._document:openPage(pageno)
local page_size_w, page_size_h = page:getSize(self.dc_null)
local page_size = Geom:new{ w = page_size_w, h = page_size_h }
Cache:insert(hash, CacheItem:new{ page_size })
page:close()
return page_size
end
function Document:_readMetadata()
if self.info.has_pages then
self.info.number_of_pages = self._document:getPages()
else
self.info.doc_height = self._document:getFullHeight()
end
return true
end
-- calculates page dimensions
function Document:getPageDimensions(pageno, zoom, rotation)
local native_dimen = self:getNativePageDimensions(pageno):copy()
if rotation == 90 or rotation == 270 then
-- switch orientation
native_dimen.w, native_dimen.h = native_dimen.h, native_dimen.w
end
native_dimen:scaleBy(zoom)
DEBUG("dimen for pageno", pageno, "zoom", zoom, "rotation", rotation, "is", native_dimen)
return native_dimen
end
--[[
This method returns pagesize if bbox is corrupted
--]]
function Document:getUsedBBoxDimensions(pageno, zoom, rotation)
ubbox = self:getUsedBBox(pageno)
if ubbox.x0 < 0 or ubbox.y0 < 0 or ubbox.x1 < 0 or ubbox.y1 < 0 then
-- if document's bbox info is corrupted, we use the page size
ubbox_dimen = self:getPageDimensions(pageno, zoom, rotation)
else
ubbox_dimen = Geom:new{
x = ubbox.x0,
y = ubbox.y0,
w = ubbox.x1 - ubbox.x0,
h = ubbox.y1 - ubbox.y0,
}
if zoom ~= 1 then
ubbox_dimen:transformByScale(zoom)
end
end
return ubbox_dimen
end
function Document:getToc()
return self._document:getToc()
end
function Document:renderPage(pageno, rect, zoom, rotation, render_mode)
local hash = "renderpg|"..self.file.."|"..pageno.."|"..zoom.."|"..rotation
local page_size = self:getPageDimensions(pageno, zoom, rotation)
-- this will be the size we actually render
local size = page_size
-- we prefer to render the full page, if it fits into cache
if not Cache:willAccept(size.w * size.h / 2) then
-- whole page won't fit into cache
DEBUG("rendering only part of the page")
-- TODO: figure out how to better segment the page
if not rect then
DEBUG("aborting, since we do not have a specification for that part")
-- required part not given, so abort
return
end
-- only render required part
hash = "renderpg|"..self.file.."|"..pageno.."|"..zoom.."|"..rotation.."|"..tostring(rect)
size = rect
end
-- prepare cache item with contained blitbuffer
local tile = CacheItem:new{
size = size.w * size.h / 2 + 64, -- estimation
excerpt = size,
pageno = pageno,
bb = Blitbuffer.new(size.w, size.h)
}
-- create a draw context
local dc = DrawContext.new()
dc:setRotate(rotation)
-- correction of rotation
if rotation == 90 then
dc:setOffset(page_size.w, 0)
elseif rotation == 180 then
dc:setOffset(page_size.w, page_size.h)
elseif rotation == 270 then
dc:setOffset(0, page_size.h)
end
dc:setZoom(zoom)
-- render
local page = self._document:openPage(pageno)
page:draw(dc, tile.bb, size.x, size.y, render_mode)
page:close()
Cache:insert(hash, tile)
return tile
end
-- a hint for the cache engine to paint a full page to the cache
-- TODO: this should trigger a background operation
function Document:hintPage(pageno, zoom, rotation)
local hash_full_page = "renderpg|"..self.file.."|"..pageno.."|"..zoom.."|"..rotation
local tile = Cache:check(hash_full_page)
if not tile then
self:renderPage(pageno, nil, zoom, rotation)
end
end
--[[
Draw page content to blitbuffer.
1. find tile in cache
2. if not found, call renderPage
@target: target blitbuffer
@rect: visible_area inside document page
--]]
function Document:drawPage(target, x, y, rect, pageno, zoom, rotation, render_mode)
local hash_full_page = "renderpg|"..self.file.."|"..pageno.."|"..zoom.."|"..rotation
local hash_excerpt = "renderpg|"..self.file.."|"..pageno.."|"..zoom.."|"..rotation.."|"..tostring(rect)
local tile = Cache:check(hash_full_page)
if not tile then
tile = Cache:check(hash_excerpt)
if not tile then
DEBUG("rendering")
tile = self:renderPage(pageno, rect, zoom, rotation, render_mode)
end
end
DEBUG("now painting", tile, rect)
target:blitFrom(tile.bb,
x, y,
rect.x - tile.excerpt.x,
rect.y - tile.excerpt.y,
rect.w, rect.h)
end
function Document:getPageText(pageno)
-- is this worth caching? not done yet.
local page = self._document:openPage(pageno)
local text = page:getPageText()
page:close()
return text
end
-- load implementations:
require "document/pdfdocument"
require "document/djvudocument"
require "document/credocument"
|
bugfix: check renderpg hash before hinting page
|
bugfix: check renderpg hash before hinting page
|
Lua
|
agpl-3.0
|
mwoz123/koreader,Markismus/koreader,NiLuJe/koreader,koreader/koreader,pazos/koreader,koreader/koreader-base,NiLuJe/koreader-base,noname007/koreader,NiLuJe/koreader-base,koreader/koreader-base,frankyifei/koreader,frankyifei/koreader-base,ashhher3/koreader,Hzj-jie/koreader-base,NiLuJe/koreader,Frenzie/koreader-base,Frenzie/koreader-base,houqp/koreader-base,Hzj-jie/koreader-base,houqp/koreader-base,chihyang/koreader,apletnev/koreader-base,apletnev/koreader-base,frankyifei/koreader-base,Hzj-jie/koreader-base,Hzj-jie/koreader,frankyifei/koreader-base,NickSavage/koreader,apletnev/koreader-base,poire-z/koreader,Frenzie/koreader,poire-z/koreader,chrox/koreader,Frenzie/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,koreader/koreader,mihailim/koreader,apletnev/koreader-base,Hzj-jie/koreader-base,houqp/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,lgeek/koreader,houqp/koreader,Frenzie/koreader-base,ashang/koreader,Frenzie/koreader,robert00s/koreader,koreader/koreader-base,apletnev/koreader
|
fa994c7900b6331092c2262116ecc7410621e4ac
|
libremap-agent/luasrc/libremap/plugins/olsr.lua
|
libremap-agent/luasrc/libremap/plugins/olsr.lua
|
--[[
Copyright 2013 Patrick Grimm <[email protected]>
Copyright 2013-2014 André Gaul <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local json = require 'luci.json'
local nixio = require 'nixio'
local string = require 'string'
local uci = (require 'uci').cursor()
local utl = require 'luci.util'
local libremap = require 'luci.libremap'
local util = require 'luci.libremap.util'
-- get jsoninfo
function fetch_jsoninfo(ip, port, cmd)
local resp = utl.exec('echo /'..cmd..' | nc '..ip..' '..port)
return json.decode(resp)
end
-- reverse lookup with stripping of mid.
function lookup_olsr_ip(ip, version)
if version==4 then
local inet = 'inet'
elseif version==6 then
local inet = 'inet6'
else
error('ip version '..version..' unknown.')
end
-- get name
local name = nixio.getnameinfo(ip, inet)
if name ~= nil then
-- remove 'midX.' from name
return string.gsub(name, 'mid[0-9]*\.', '')
else
return nil
end
end
-- get links for specified ip version (4 or 6)
function fetch_links(version)
-- set variables that depend on ip version
local ip
local type
if version==4 then
ip = '127.0.0.1' -- for jsoninfo
type = 'olsr4' -- type of alias/link
elseif version==6 then
ip = '::1'
type = 'olsr6'
else
error('ip version '..version..' unknown.')
end
-- retrieve links data from jsoninfo
local jsoninfo = fetch_jsoninfo(ip, '9090', 'links')
if not jsoninfo or not jsoninfo.links then
return {}, {}
end
local olsr_links = jsoninfo.links
-- init return values
local aliases = {}
local links = {}
-- step through olsr_links
for _, link in ipairs(olsr_links) do
local ip_local = link['localIP']
local ip_remote = link['remoteIP']
-- unused at the moment:
--local name_local = lookup_olsr_ip(ip_local, version)
--local name_remote = lookup_olsr_ip(ip_remote, version)
-- insert aliases
aliases[ip_local] = 1
-- process link quality
local quality = link['linkQuality']
-- TODO: process quality properly
if quality<0 then
quality = 0
elseif quality>1 then
quality = 1
elseif not (quality>=0 and quality<=1) then
quality = 0
end
-- insert links
links[#links+1] = {
type = type,
alias_local = ip_local,
alias_remote = ip_remote,
quality = quality,
attributes = link
}
end
-- retrieve interfaces data from jsoninfo for aliases
local jsoninfo = fetch_jsoninfo(ip, '9090', 'interfaces')
if jsoninfo and jsoninfo.interfaces then
for _, interface in ipairs(jsoninfo.interfaces) do
aliases[interface['ipv'..version..'Address']] = 1
end
end
-- fill in aliases
local aliases_arr = {}
for alias, _ in pairs(aliases) do
aliases_arr[#aliases_arr+1] = {
type = type,
alias = alias
}
end
return aliases_arr, links
end
-- appent array b to array a
function append(a, b)
local a = a or {}
for _, v in ipairs(b) do
a[#a+1] = v
end
return a
end
-- insert olsr info into doc
function insert(doc)
-- init fields in doc (if not yet present)
doc.aliases = doc.aliases or {}
doc.links = doc.links or {}
-- get used ip version(s) from config
local IpVersion = uci:get_first("olsrd", "olsrd","IpVersion")
local versions = {}
if IpVersion == '4' then
versions = {4}
elseif IpVersion == '6' then
versions = {6}
elseif IpVersion == '6and4' then
versions = {6, 4}
end
-- fetch links for used ip versions
for _, version in pairs(versions) do
local aliases, links = fetch_links(version)
append(doc.aliases, aliases)
append(doc.links, links)
end
end
return {
insert = insert
}
|
--[[
Copyright 2013 Patrick Grimm <[email protected]>
Copyright 2013-2014 André Gaul <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local json = require 'luci.json'
local nixio = require 'nixio'
local string = require 'string'
local uci = (require 'uci').cursor()
local utl = require 'luci.util'
local libremap = require 'luci.libremap'
local util = require 'luci.libremap.util'
-- get jsoninfo
function fetch_jsoninfo(ip, port, cmd)
local resp = utl.exec('echo /'..cmd..' | nc '..ip..' '..port)
return json.decode(resp)
end
-- reverse lookup with stripping of mid.
function lookup_olsr_ip(ip, version)
if version==4 then
local inet = 'inet'
elseif version==6 then
local inet = 'inet6'
else
error('ip version '..version..' unknown.')
end
-- get name
local name = nixio.getnameinfo(ip, inet)
if name ~= nil then
-- remove 'midX.' from name
return string.gsub(name, 'mid[0-9]*\.', '')
else
return nil
end
end
-- get links for specified ip version (4 or 6)
function fetch_links(version)
-- set variables that depend on ip version
local ip
local type
if version==4 then
ip = '127.0.0.1' -- for jsoninfo
type = 'olsr4' -- type of alias/link
elseif version==6 then
ip = '::1'
type = 'olsr6'
else
error('ip version '..version..' unknown.')
end
-- retrieve links data from jsoninfo
local jsoninfo = fetch_jsoninfo(ip, '9090', 'links')
if not jsoninfo or not jsoninfo.links then
return {}, {}
end
local olsr_links = jsoninfo.links
-- init return values
local aliases = {}
local links = {}
-- step through olsr_links
for _, link in ipairs(olsr_links) do
local ip_local = link['localIP']
local ip_remote = link['remoteIP']
-- unused at the moment:
--local name_local = lookup_olsr_ip(ip_local, version)
--local name_remote = lookup_olsr_ip(ip_remote, version)
-- insert aliases
aliases[ip_local] = 1
-- process link quality
local quality = link['linkQuality']
-- TODO: process quality properly
if quality<0 then
quality = 0
elseif quality>1 then
quality = 1
elseif not (quality>=0 and quality<=1) then
quality = 0
end
-- insert links
links[#links+1] = {
type = type,
alias_local = ip_local,
alias_remote = ip_remote,
quality = quality,
attributes = link
}
end
-- retrieve interfaces data from jsoninfo for aliases
local jsoninfo = fetch_jsoninfo(ip, '9090', 'interfaces')
if jsoninfo and jsoninfo.interfaces then
for _, interface in ipairs(jsoninfo.interfaces) do
local address = interface['ipv'..version..'Address']
if address ~= nil then
aliases[address] = 1
end
end
end
-- fill in aliases
local aliases_arr = {}
for alias, _ in pairs(aliases) do
aliases_arr[#aliases_arr+1] = {
type = type,
alias = alias
}
end
return aliases_arr, links
end
-- appent array b to array a
function append(a, b)
local a = a or {}
for _, v in ipairs(b) do
a[#a+1] = v
end
return a
end
-- insert olsr info into doc
function insert(doc)
-- init fields in doc (if not yet present)
doc.aliases = doc.aliases or {}
doc.links = doc.links or {}
-- get used ip version(s) from config
local IpVersion = uci:get_first("olsrd", "olsrd","IpVersion")
local versions = {}
if IpVersion == '4' then
versions = {4}
elseif IpVersion == '6' then
versions = {6}
elseif IpVersion == '6and4' then
versions = {6, 4}
end
-- fetch links for used ip versions
for _, version in pairs(versions) do
local aliases, links = fetch_links(version)
append(doc.aliases, aliases)
append(doc.links, links)
end
end
return {
insert = insert
}
|
[olsr] fix tiny bug
|
[olsr] fix tiny bug
|
Lua
|
apache-2.0
|
libre-mesh/libremap-agent,libremap/libremap-agent-openwrt,rogerpueyo/libremap-agent-openwrt
|
8a167f30072b12c3063116e4ae31960bec2b2b09
|
check/plugin.lua
|
check/plugin.lua
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[
Module for running custom agent plugins written in an arbitrary programing
/ scripting language. This module is backward compatibile with Cloudkick agent
plugins (https://support.cloudkick.com/Creating_a_plugin).
All the plugins must output information to the standard output in the
format defined bellow:
status <status string>
metric <name 1> <type> <value> [<unit>]
metric <name 2> <type> <value> [<unit>]
metric <name 3> <type> <value> [<unit>]
* <status string> - A status string which includes a summary of the results.
* <name> Name of the metric. No spaces are allowed. If a name contains a dot,
string before the dot is considered to be a metric dimension.
* <type> - Metric type which can be one of:
* string
* gauge
* float
* int
* [<unit>] - Metric unit, optional. A string representing the units of the metric
measurement. Units may only be provided on non-string metrics, and may not
contain any spaces. Examples: 'bytes', 'milliseconds', 'percent'.
--]]
local table = require('table')
local childprocess = require('childprocess')
local timer = require('timer')
local path = require('path')
local string = require('string')
local fmt = string.format
local logging = require('logging')
local LineEmitter = require('line-emitter').LineEmitter
local ChildCheck = require('./base').ChildCheck
local CheckResult = require('./base').CheckResult
local Metric = require('./base').Metric
local split = require('/base/util/misc').split
local tableContains = require('/base/util/misc').tableContains
local lastIndexOf = require('/base/util/misc').lastIndexOf
local constants = require('/constants')
local loggingUtil = require('/base/util/logging')
local toString = require('/base/util/misc').toString
local PluginCheck = ChildCheck:extend()
--[[
Constructor.
params.details - Table with the following keys:
- file (string) - Name of the plugin file.
- args (table) - Command-line arguments which get passed to the plugin.
- timeout (number) - Plugin execution timeout in milliseconds.
--]]
function PluginCheck:initialize(params)
ChildCheck.initialize(self, params)
if params.details.file == nil then
params.details.file = ''
end
local file = path.basename(params.details.file)
local args = params.details.args and params.details.args or {}
local timeout = params.details.timeout and params.details.timeout or constants:get('DEFAULT_PLUGIN_TIMEOUT')
self._full_path = params.details.file or ''
self._file = file
self._pluginPath = path.join(constants:get('DEFAULT_CUSTOM_PLUGINS_PATH'), file)
self._pluginArgs = args
self._timeout = timeout
self._log = loggingUtil.makeLogger(fmt('(plugin=%s, id=%s, iid=%s)', file, self.id, self._iid))
end
function PluginCheck:getType()
return 'agent.plugin'
end
function PluginCheck:run(callback)
local exePath = self._pluginPath
local exeArgs = self._pluginArgs
local ext = path.extname(exePath)
if virgo.win32_get_associated_exe ~= nil and ext ~= "" then
-- If we are on windows, we want to suport custom plugins like "foo.py",
-- but this means we need to map the .py file ending to the Python Executable,
-- and mutate our run path to be like: C:/Python27/python.exe custom_plugins_path/foo.py
local assocExe, err = virgo.win32_get_associated_exe(ext)
if assocExe ~= nil then
table.insert(exeArgs, 1, self._pluginPath)
exePath = assocExe
else
self._log(logging.WARNING, fmt('error getting associated executable for "%s": %s', ext, err))
end
end
local cenv = self:_childEnv()
local child = self:_runChild(exePath, exeArgs, cenv, callback)
if child.stdin._closed ~= true then
child.stdin:close()
end
end
local exports = {}
exports.PluginCheck = PluginCheck
return exports
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[
Module for running custom agent plugins written in an arbitrary programing
/ scripting language. This module is backward compatibile with Cloudkick agent
plugins (https://support.cloudkick.com/Creating_a_plugin).
All the plugins must output information to the standard output in the
format defined bellow:
status <status string>
metric <name 1> <type> <value> [<unit>]
metric <name 2> <type> <value> [<unit>]
metric <name 3> <type> <value> [<unit>]
* <status string> - A status string which includes a summary of the results.
* <name> Name of the metric. No spaces are allowed. If a name contains a dot,
string before the dot is considered to be a metric dimension.
* <type> - Metric type which can be one of:
* string
* gauge
* float
* int
* [<unit>] - Metric unit, optional. A string representing the units of the metric
measurement. Units may only be provided on non-string metrics, and may not
contain any spaces. Examples: 'bytes', 'milliseconds', 'percent'.
--]]
local table = require('table')
local childprocess = require('childprocess')
local timer = require('timer')
local path = require('path')
local string = require('string')
local fmt = string.format
local logging = require('logging')
local LineEmitter = require('line-emitter').LineEmitter
local ChildCheck = require('./base').ChildCheck
local CheckResult = require('./base').CheckResult
local Metric = require('./base').Metric
local split = require('/base/util/misc').split
local tableContains = require('/base/util/misc').tableContains
local lastIndexOf = require('/base/util/misc').lastIndexOf
local constants = require('/constants')
local loggingUtil = require('/base/util/logging')
local toString = require('/base/util/misc').toString
local PluginCheck = ChildCheck:extend()
--[[
Constructor.
params.details - Table with the following keys:
- file (string) - Name of the plugin file.
- args (table) - Command-line arguments which get passed to the plugin.
- timeout (number) - Plugin execution timeout in milliseconds.
--]]
function PluginCheck:initialize(params)
ChildCheck.initialize(self, params)
if params.details.file == nil then
params.details.file = ''
end
local file = path.basename(params.details.file)
local args = params.details.args and params.details.args or {}
local timeout = params.details.timeout and params.details.timeout or constants:get('DEFAULT_PLUGIN_TIMEOUT')
self._full_path = params.details.file or ''
self._file = file
self._pluginPath = path.join(constants:get('DEFAULT_CUSTOM_PLUGINS_PATH'), file)
self._pluginArgs = args
self._timeout = timeout
self._log = loggingUtil.makeLogger(fmt('(plugin=%s, id=%s, iid=%s)', file, self.id, self._iid))
end
function PluginCheck:getType()
return 'agent.plugin'
end
function PluginCheck:run(callback)
local exePath = self._pluginPath
local exeArgs = self._pluginArgs
local ext = path.extname(exePath)
if virgo.win32_get_associated_exe ~= nil and ext ~= "" then
-- If we are on windows, we want to suport custom plugins like "foo.py",
-- but this means we need to map the .py file ending to the Python Executable,
-- and mutate our run path to be like: C:/Python27/python.exe custom_plugins_path/foo.py
local assocExe, err = virgo.win32_get_associated_exe(ext)
if assocExe ~= nil then
table.insert(exeArgs, 1, self._pluginPath)
exePath = assocExe
else
self._log(logging.WARNING, fmt('error getting associated executable for "%s": %s', ext, err))
end
end
local cenv = self:_childEnv()
-- Ruby 1.9.1p0 crashes when stdin is closed, so we let luvit take care of
-- closing the pipe after the process runs.
local child = self:_runChild(exePath, exeArgs, cenv, callback)
end
local exports = {}
exports.PluginCheck = PluginCheck
return exports
|
fix(plugins): ruby 1.9.1p0 crashes when stdin is closed
|
fix(plugins): ruby 1.9.1p0 crashes when stdin is closed
|
Lua
|
apache-2.0
|
AlphaStaxLLC/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
|
a4af35f442ca4779d1320a6dd4a38eba5a7e4e33
|
lualib/snax/interface.lua
|
lualib/snax/interface.lua
|
local skynet = require "skynet"
return function (name , G, loader)
loader = loader or loadfile
local mainfunc
local function func_id(id, group)
local tmp = {}
local function count( _, name, func)
if type(name) ~= "string" then
error (string.format("%s method only support string", group))
end
if type(func) ~= "function" then
error (string.format("%s.%s must be function"), group, name)
end
if tmp[name] then
error (string.format("%s.%s duplicate definition", group, name))
end
tmp[name] = true
table.insert(id, { #id + 1, group, name, func} )
end
return setmetatable({}, { __newindex = count })
end
do
assert(getmetatable(G) == nil)
assert(G.init == nil)
assert(G.exit == nil)
assert(G.accept == nil)
assert(G.response == nil)
end
local temp_global = {}
local env = setmetatable({} , { __index = temp_global })
local func = {}
local system = { "init", "exit", "hotfix" }
do
for k, v in ipairs(system) do
system[v] = k
func[k] = { k , "system", v }
end
end
env.accept = func_id(func, "accept")
env.response = func_id(func, "response")
local function init_system(t, name, f)
local index = system[name]
if index then
if type(f) ~= "function" then
error (string.format("%s must be a function", name))
end
func[index][4] = f
else
temp_global[name] = f
end
end
setmetatable(G, { __index = env , __newindex = init_system })
local pattern
do
local path = assert(skynet.getenv "snax" , "please set snax in config file")
local errlist = {}
for pat in string.gmatch(path,"[^;]+") do
local filename = string.gsub(pat, "?", name)
local f , err = loader(filename, "bt", G)
if f then
pattern = pat
mainfunc = f
break
else
table.insert(errlist, err)
end
end
if mainfunc == nil then
error(table.concat(errlist, "\n"))
end
end
mainfunc()
setmetatable(G, nil)
for k,v in pairs(temp_global) do
G[k] = v
end
return func, pattern
end
|
local skynet = require "skynet"
return function (name , G, loader)
loader = loader or loadfile
local mainfunc
local function func_id(id, group)
local tmp = {}
local function count( _, name, func)
if type(name) ~= "string" then
error (string.format("%s method only support string", group))
end
if type(func) ~= "function" then
error (string.format("%s.%s must be function"), group, name)
end
if tmp[name] then
error (string.format("%s.%s duplicate definition", group, name))
end
tmp[name] = true
table.insert(id, { #id + 1, group, name, func} )
end
return setmetatable({}, { __newindex = count })
end
do
assert(getmetatable(G) == nil)
assert(G.init == nil)
assert(G.exit == nil)
assert(G.accept == nil)
assert(G.response == nil)
end
local temp_global = {}
local env = setmetatable({} , { __index = temp_global })
local func = {}
local system = { "init", "exit", "hotfix" }
do
for k, v in ipairs(system) do
system[v] = k
func[k] = { k , "system", v }
end
end
env.accept = func_id(func, "accept")
env.response = func_id(func, "response")
local function init_system(t, name, f)
local index = system[name]
if index then
if type(f) ~= "function" then
error (string.format("%s must be a function", name))
end
func[index][4] = f
else
temp_global[name] = f
end
end
local pattern
do
local path = assert(skynet.getenv "snax" , "please set snax in config file")
local errlist = {}
for pat in string.gmatch(path,"[^;]+") do
local filename = string.gsub(pat, "?", name)
local f , err = loader(filename, "bt", G)
if f then
pattern = pat
mainfunc = f
break
else
table.insert(errlist, err)
end
end
if mainfunc == nil then
error(table.concat(errlist, "\n"))
end
end
setmetatable(G, { __index = env , __newindex = init_system })
local ok, err = pcall(mainfunc)
setmetatable(G, nil)
assert(ok,err)
for k,v in pairs(temp_global) do
G[k] = v
end
return func, pattern
end
|
fix issue #364
|
fix issue #364
|
Lua
|
mit
|
chuenlungwang/skynet,lawnight/skynet,letmefly/skynet,bttscut/skynet,ag6ag/skynet,cloudwu/skynet,jxlczjp77/skynet,lawnight/skynet,Ding8222/skynet,letmefly/skynet,nightcj/mmo,zhangshiqian1214/skynet,bingo235/skynet,sundream/skynet,pigparadise/skynet,czlc/skynet,catinred2/skynet,zhangshiqian1214/skynet,gitfancode/skynet,kyle-wang/skynet,zhangshiqian1214/skynet,wangyi0226/skynet,zhangshiqian1214/skynet,xinjuncoding/skynet,rainfiel/skynet,bigrpg/skynet,cmingjian/skynet,chuenlungwang/skynet,JiessieDawn/skynet,MRunFoss/skynet,lawnight/skynet,cdd990/skynet,kyle-wang/skynet,bigrpg/skynet,ypengju/skynet_comment,QuiQiJingFeng/skynet,zhangshiqian1214/skynet,hongling0/skynet,chuenlungwang/skynet,rainfiel/skynet,MRunFoss/skynet,liuxuezhan/skynet,wangyi0226/skynet,catinred2/skynet,fztcjjl/skynet,zhouxiaoxiaoxujian/skynet,Ding8222/skynet,fztcjjl/skynet,zhoukk/skynet,iskygame/skynet,codingabc/skynet,liuxuezhan/skynet,hongling0/skynet,firedtoad/skynet,puXiaoyi/skynet,gitfancode/skynet,QuiQiJingFeng/skynet,liuxuezhan/skynet,sanikoyes/skynet,nightcj/mmo,icetoggle/skynet,nightcj/mmo,xinjuncoding/skynet,korialuo/skynet,cmingjian/skynet,sanikoyes/skynet,zhoukk/skynet,great90/skynet,liuxuezhan/skynet,fztcjjl/skynet,great90/skynet,cloudwu/skynet,asanosoyokaze/skynet,xjdrew/skynet,korialuo/skynet,letmefly/skynet,KAndQ/skynet,zhouxiaoxiaoxujian/skynet,ilylia/skynet,asanosoyokaze/skynet,rainfiel/skynet,bigrpg/skynet,firedtoad/skynet,asanosoyokaze/skynet,sanikoyes/skynet,xcjmine/skynet,jxlczjp77/skynet,xjdrew/skynet,zhoukk/skynet,puXiaoyi/skynet,icetoggle/skynet,bttscut/skynet,pigparadise/skynet,letmefly/skynet,zhangshiqian1214/skynet,ag6ag/skynet,cdd990/skynet,bingo235/skynet,codingabc/skynet,pigparadise/skynet,cdd990/skynet,xinjuncoding/skynet,jxlczjp77/skynet,wangyi0226/skynet,kyle-wang/skynet,xcjmine/skynet,ilylia/skynet,sundream/skynet,lawnight/skynet,czlc/skynet,MRunFoss/skynet,codingabc/skynet,xjdrew/skynet,catinred2/skynet,QuiQiJingFeng/skynet,LiangMa/skynet,czlc/skynet,ypengju/skynet_comment,zhouxiaoxiaoxujian/skynet,samael65535/skynet,LiangMa/skynet,cmingjian/skynet,iskygame/skynet,samael65535/skynet,LiangMa/skynet,firedtoad/skynet,icetoggle/skynet,hongling0/skynet,samael65535/skynet,ag6ag/skynet,korialuo/skynet,ypengju/skynet_comment,JiessieDawn/skynet,gitfancode/skynet,KAndQ/skynet,sundream/skynet,iskygame/skynet,xcjmine/skynet,great90/skynet,bingo235/skynet,puXiaoyi/skynet,JiessieDawn/skynet,bttscut/skynet,ilylia/skynet,Ding8222/skynet,cloudwu/skynet,KAndQ/skynet
|
2cf9380b1826a547abe79694f826a734d36b966b
|
packages/lime-webui/luasrc/controller/lime.lua
|
packages/lime-webui/luasrc/controller/lime.lua
|
--[[
Copyright (C) libremesh.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
--]]
module("luci.controller.lime", package.seeall)
-- Flashing accessory functions
local function image_supported(image)
return (os.execute("sysupgrade -T %q >/dev/null" % image) == 0)
end
local function image_checksum(image)
return (luci.sys.exec("md5sum %q" % image):match("^([^%s]+)"))
end
local function image_sha256_checksum(image)
return (luci.sys.exec("sha256sum %q" % image):match("^([^%s]+)"))
end
local function supports_sysupgrade()
return nixio.fs.access("/lib/upgrade/platform.sh")
end
local function supports_reset()
return (os.execute([[grep -sqE '"rootfs_data"|"ubi"' /proc/mtd]]) == 0)
end
function fork_exec(command)
local pid = nixio.fork()
if pid > 0 then
return
elseif pid == 0 then
-- change to root dir
nixio.chdir("/")
-- patch stdin, out, err to /dev/null
local null = nixio.open("/dev/null", "w+")
if null then
nixio.dup(null, nixio.stderr)
nixio.dup(null, nixio.stdout)
nixio.dup(null, nixio.stdin)
if null:fileno() > 2 then
null:close()
end
end
-- replace with target command
nixio.exec("/bin/sh", "-c", command)
end
end
local function storage_size()
local size = 0
if nixio.fs.access("/proc/mtd") then
for l in io.lines("/proc/mtd") do
local d, s, e, n = l:match('^([^%s]+)%s+([^%s]+)%s+([^%s]+)%s+"([^%s]+)"')
if n == "linux" or n == "firmware" then
size = tonumber(s, 16)
break
end
end
elseif nixio.fs.access("/proc/partitions") then
for l in io.lines("/proc/partitions") do
local x, y, b, n = l:match('^%s*(%d+)%s+(%d+)%s+([^%s]+)%s+([^%s]+)')
if b and n and not n:match('[0-9]') then
size = tonumber(b) * 1024
break
end
end
end
return size
end
-- /Flashing accessory functions
function index()
-- Making lime as default
local root = node()
root.target = alias("lime")
root.index = true
-- Main window with auth enabled
status = entry({"lime"}, firstchild(), _("Simple Config"), 9.5)
status.dependent = false
status.sysauth = "root"
status.sysauth_authenticator = "htmlauth"
-- Rest of entries
entry({"lime","essentials"}, cbi("lime/essentials"), _("Advanced"), 70).dependent=false
entry({"lime","Notes"}, cbi("lime/notes"), _("Notes"), 70).dependent=false
entry({"lime","about"}, call("action_about"), _("About"), 80).dependent=false
entry({"lime","logout"}, call("action_logout"), _("Logout"), 90)
entry({"lime", "flashops"}, call("action_flashops"), _("Flash Firmware"), 70)
entry({"lime", "flashops", "sysupgrade"}, call("action_sysupgrade"))
end
function action_about()
-- package.path = package.path .. ";/etc/lime/?.lua"
luci.template.render("lime/about",{})
end
function action_logout()
local dsp = require "luci.dispatcher"
local sauth = require "luci.sauth"
if dsp.context.authsession then
sauth.kill(dsp.context.authsession)
dsp.context.urltoken.stok = nil
end
luci.http.header("Set-Cookie", "sysauth=; path=" .. dsp.build_url())
luci.http.redirect(luci.dispatcher.build_url())
end
function action_flashops()
luci.template.render("lime/flashops", {
reset_avail = supports_reset(),
upgrade_avail = supports_sysupgrade()
})
end
function action_sysupgrade()
local fs = require "nixio.fs"
local http = require "luci.http"
local image_tmp = "/tmp/firmware.img"
local fp
http.setfilehandler(
function(meta, chunk, eof)
if not fp and meta and meta.name == "image" then
fp = io.open(image_tmp, "w")
end
if fp and chunk then
fp:write(chunk)
end
if fp and eof then
fp:close()
end
end
)
if not luci.dispatcher.test_post_security() then
fs.unlink(image_tmp)
return
end
if http.formvalue("cancel") then
fs.unlink(image_tmp)
http.redirect(luci.dispatcher.build_url('lime/flashops'))
return
end
local step = tonumber(http.formvalue("step") or 1)
if step == 1 then
if image_supported(image_tmp) then
luci.template.render("lime/upgrade", {
checksum = image_checksum(image_tmp),
sha256ch = image_sha256_checksum(image_tmp),
storage = storage_size(),
size = (fs.stat(image_tmp, "size") or 0),
keep = (not not http.formvalue("keep"))
})
else
fs.unlink(image_tmp)
luci.template.render("lime/flashops", {
reset_avail = supports_reset(),
upgrade_avail = supports_sysupgrade(),
image_invalid = true
})
end
elseif step == 2 then
local keep = (http.formvalue("keep") == "1") and "" or "-n"
luci.template.render("admin_system/applyreboot", {
title = luci.i18n.translate("Flashing..."),
msg = luci.i18n.translate("The system is flashing now.<br /> DO NOT POWER OFF THE DEVICE!<br /> Wait a few minutes before you try to reconnect. It might be necessary to renew the address of your computer to reach the device again, depending on your settings."),
addr = (#keep > 0) and "192.168.1.1" or nil
})
fork_exec("sleep 1; killall dropbear uhttpd; sleep 1; FORCE=1 /usr/bin/lime-sysupgrade %q > /tmp/lime-sysupgrade.log" %{ image_tmp })
end
end
|
--[[
Copyright (C) libremesh.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
--]]
module("luci.controller.lime", package.seeall)
-- Flashing accessory functions
local function image_supported(image)
return (os.execute("sysupgrade -T %q >/dev/null" % image) == 0)
end
local function image_checksum(image)
return (luci.sys.exec("md5sum %q" % image):match("^([^%s]+)"))
end
local function image_sha256_checksum(image)
return (luci.sys.exec("sha256sum %q" % image):match("^([^%s]+)"))
end
local function supports_sysupgrade()
return nixio.fs.access("/lib/upgrade/platform.sh")
end
local function supports_reset()
return (os.execute([[grep -sqE '"rootfs_data"|"ubi"' /proc/mtd]]) == 0)
end
function fork_exec(command)
local pid = nixio.fork()
if pid > 0 then
return
elseif pid == 0 then
-- change to root dir
nixio.chdir("/")
-- patch stdin, out, err to /dev/null
local null = nixio.open("/dev/null", "w+")
if null then
nixio.dup(null, nixio.stderr)
nixio.dup(null, nixio.stdout)
nixio.dup(null, nixio.stdin)
if null:fileno() > 2 then
null:close()
end
end
-- replace with target command
nixio.exec("/bin/sh", "-c", command)
end
end
local function storage_size()
local size = 0
if nixio.fs.access("/proc/mtd") then
for l in io.lines("/proc/mtd") do
local d, s, e, n = l:match('^([^%s]+)%s+([^%s]+)%s+([^%s]+)%s+"([^%s]+)"')
if n == "linux" or n == "firmware" then
size = tonumber(s, 16)
break
end
end
elseif nixio.fs.access("/proc/partitions") then
for l in io.lines("/proc/partitions") do
local x, y, b, n = l:match('^%s*(%d+)%s+(%d+)%s+([^%s]+)%s+([^%s]+)')
if b and n and not n:match('[0-9]') then
size = tonumber(b) * 1024
break
end
end
end
return size
end
-- /Flashing accessory functions
function index()
-- Making lime as default
local root = node()
root.target = alias("lime")
root.index = true
-- Main window with auth enabled
status = entry({"lime"}, firstchild(), _("Simple Config"), 9.5)
status.dependent = false
status.sysauth = "root"
status.sysauth_authenticator = "htmlauth"
-- Rest of entries
entry({"lime","essentials"}, cbi("lime/essentials"), _("Advanced"), 70).dependent=false
entry({"lime","Notes"}, cbi("lime/notes"), _("Notes"), 70).dependent=false
entry({"lime","about"}, call("action_about"), _("About"), 80).dependent=false
entry({"lime","logout"}, call("action_logout"), _("Logout"), 90)
entry({"lime", "flashops"}, call("action_flashops"), _("Flash Firmware"), 70)
entry({"lime", "flashops", "sysupgrade"}, call("action_sysupgrade"))
end
function action_about()
-- package.path = package.path .. ";/etc/lime/?.lua"
luci.template.render("lime/about",{})
end
function action_logout()
local dsp = require "luci.dispatcher"
local utl = require "luci.util"
local sid = dsp.context.authsession
if sid then
utl.ubus("session", "destroy", { ubus_rpc_session = sid })
luci.http.header("Set-Cookie", "sysauth=%s; expires=%s; path=%s/" %{
sid, 'Thu, 01 Jan 1970 01:00:00 GMT', dsp.build_url()
})
end
luci.http.redirect(dsp.build_url())
end
function action_flashops()
luci.template.render("lime/flashops", {
reset_avail = supports_reset(),
upgrade_avail = supports_sysupgrade()
})
end
function action_sysupgrade()
local fs = require "nixio.fs"
local http = require "luci.http"
local image_tmp = "/tmp/firmware.img"
local fp
http.setfilehandler(
function(meta, chunk, eof)
if not fp and meta and meta.name == "image" then
fp = io.open(image_tmp, "w")
end
if fp and chunk then
fp:write(chunk)
end
if fp and eof then
fp:close()
end
end
)
if not luci.dispatcher.test_post_security() then
fs.unlink(image_tmp)
return
end
if http.formvalue("cancel") then
fs.unlink(image_tmp)
http.redirect(luci.dispatcher.build_url('lime/flashops'))
return
end
local step = tonumber(http.formvalue("step") or 1)
if step == 1 then
if image_supported(image_tmp) then
luci.template.render("lime/upgrade", {
checksum = image_checksum(image_tmp),
sha256ch = image_sha256_checksum(image_tmp),
storage = storage_size(),
size = (fs.stat(image_tmp, "size") or 0),
keep = (not not http.formvalue("keep"))
})
else
fs.unlink(image_tmp)
luci.template.render("lime/flashops", {
reset_avail = supports_reset(),
upgrade_avail = supports_sysupgrade(),
image_invalid = true
})
end
elseif step == 2 then
local keep = (http.formvalue("keep") == "1") and "" or "-n"
luci.template.render("admin_system/applyreboot", {
title = luci.i18n.translate("Flashing..."),
msg = luci.i18n.translate("The system is flashing now.<br /> DO NOT POWER OFF THE DEVICE!<br /> Wait a few minutes before you try to reconnect. It might be necessary to renew the address of your computer to reach the device again, depending on your settings."),
addr = (#keep > 0) and "192.168.1.1" or nil
})
fork_exec("sleep 1; killall dropbear uhttpd; sleep 1; FORCE=1 /usr/bin/lime-sysupgrade %q > /tmp/lime-sysupgrade.log" %{ image_tmp })
end
end
|
Fix #141 - Logout error on Simple Config area
|
Fix #141 - Logout error on Simple Config area
|
Lua
|
agpl-3.0
|
libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages
|
a91693e5b58dead9919f7fb39251fa84a2ea594d
|
.config/nvim/lua/cmp_config.lua
|
.config/nvim/lua/cmp_config.lua
|
local cmp = require("cmp")
local lspkind = require("lspkind")
local luasnip = require("luasnip")
local has_words_before = function()
local line, col = unpack(vim.api.nvim_win_get_cursor(0))
return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil
end
cmp.setup {
mapping = {
["<CR>"] = cmp.mapping.confirm({ select = false }),
["<Tab>"] = cmp.mapping(function(fallback)
if luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif has_words_before() then
cmp.confirm()
else
fallback()
end
end, { "i", "s" }),
["<S-Tab>"] = cmp.mapping(function(fallback)
if luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, { "i", "s" }),
},
-- the order of your sources matter (by default). That gives them priority
-- you can configure:
-- keyword_length
-- priority
-- max_item_count
-- (more?)
sources = {
-- Could enable this only for lua, but nvim_lua handles that already.
{ name = "nvim_lua" },
{ name = "nvim_lsp" },
{ name = "path" },
{ name = "luasnip" },
{ name = "buffer", keyword_length = 2 },
{ name = "spell", keyword_length = 4 },
},
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body)
end,
},
documentation = {
border = { "╭", "─", "╮", "│", "╯", "─", "╰", "│" },
},
completion = {
-- completeopt = "menu,menuone,noinsert",
completeopt = "menu,menuone",
},
formatting = {
format = lspkind.cmp_format {
menu = {
buffer = '[buf]',
nvim_lsp = '[lsp]',
nvim_lua = '[lua]',
path = '[path]',
luasnip = '[snip]',
spell = '[spl]',
},
},
},
experimental = {
native_menu = false,
ghost_text = false,
},
}
|
local cmp = require("cmp")
local lspkind = require("lspkind")
local luasnip = require("luasnip")
local has_words_before = function()
local line, col = unpack(vim.api.nvim_win_get_cursor(0))
return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil
end
cmp.setup {
mapping = {
["<CR>"] = cmp.mapping.confirm({ select = false }),
["<Tab>"] = cmp.mapping(function(fallback)
if luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif has_words_before() then
cmp.confirm()
else
fallback()
end
end, { "i", "s" }),
["<S-Tab>"] = cmp.mapping(function(fallback)
if luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, { "i", "s" }),
},
-- the order of your sources matter (by default). That gives them priority
-- you can configure:
-- keyword_length
-- priority
-- max_item_count
-- (more?)
sources = {
-- Could enable this only for lua, but nvim_lua handles that already.
{ name = "nvim_lua" },
{ name = "nvim_lsp" },
{ name = "path" },
{ name = "luasnip" },
{ name = "buffer", keyword_length = 2 },
{ name = "spell", keyword_length = 4 },
},
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body)
end,
},
documentation = {
border = { "╭", "─", "╮", "│", "╯", "─", "╰", "│" },
},
completion = {
-- completeopt = "menu,menuone,noinsert",
completeopt = "menu,menuone",
},
formatting = {
format = lspkind.cmp_format {
menu = {
buffer = '[buf]',
nvim_lsp = '[lsp]',
nvim_lua = '[lua]',
path = '[path]',
luasnip = '[snip]',
spell = '[spl]',
},
},
},
matching = {
disallow_prefix_unmatching = true,
},
experimental = {
native_menu = false,
ghost_text = false,
},
}
|
nvim: disallow prefix unmatching for completion
|
nvim: disallow prefix unmatching for completion
|
Lua
|
mit
|
nkcfan/Dotfiles,nkcfan/Dotfiles,nkcfan/Dotfiles
|
5a92e2b753faa69fabdc8dd4671eaf2e5cad2a87
|
.config/nvim/lua/config/cmp.lua
|
.config/nvim/lua/config/cmp.lua
|
local cmp_status_ok, cmp = pcall(require, "cmp")
if not cmp_status_ok then
return
end
local snip_status_ok, luasnip = pcall(require, "luasnip")
if not snip_status_ok then
return
end
require("luasnip/loaders/from_vscode").lazy_load()
local check_backspace = function()
local col = vim.fn.col(".") - 1
return col == 0 or vim.fn.getline("."):sub(col, col):match("%s")
end
-- פּ ﯟ some other good icons
local kind_icons = {
Text = "",
Method = "m",
Function = "",
Constructor = "",
Field = "",
Variable = "",
Class = "",
Interface = "",
Module = "",
Property = "",
Unit = "",
Value = "",
Enum = "",
Keyword = "",
Snippet = "",
Color = "",
File = "",
Reference = "",
Folder = "",
EnumMember = "",
Constant = "",
Struct = "",
Event = "",
Operator = "",
TypeParameter = "",
}
-- find more here: https://www.nerdfonts.com/cheat-sheet
cmp.setup({
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body) -- For `luasnip` users.
end,
},
mapping = cmp.mapping.preset.insert({
["<C-n>"] = cmp.mapping.select_next_item(),
["<C-p>"] = cmp.mapping.select_prev_item(),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(1), { "i", "c" }),
["<C-b>"] = cmp.mapping(cmp.mapping.scroll_docs(-1), { "i", "c" }),
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
["<C-e>"] = cmp.mapping.confirm({ select = false }, { "c" }),
-- Accept currently selected item. If none selected, `select` first item.
-- Set `select` to `false` to only confirm explicitly selected items.
["<CR>"] = cmp.mapping.confirm({ select = true }),
["<C-j>"] = cmp.mapping.confirm({ select = true }),
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expandable() then
luasnip.expand()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif check_backspace() then
fallback()
else
fallback()
end
end, {
"i",
"s",
}),
["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, {
"i",
"s",
}),
}),
formatting = {
fields = { "kind", "abbr", "menu" },
format = function(entry, vim_item)
-- Kind icons
vim_item.kind = string.format("%s ", kind_icons[vim_item.kind])
-- vim_item.kind = string.format('%s %s', kind_icons[vim_item.kind], vim_item.kind) -- This concatonates the icons with the name of the item kind
vim_item.menu = ({
nvim_lsp = "[LSP]",
luasnip = "[Snippet]",
buffer = "[Buffer]",
path = "[Path]",
})[entry.source.name]
return vim_item
end,
},
-- sources = {
sources = cmp.config.sources({
{ name = "nvim_lsp" },
{ name = "luasnip" },
{ name = "path" },
}, {
{ name = "buffer" },
{ name = "spell" },
}),
confirm_opts = {
behavior = cmp.ConfirmBehavior.Replace,
select = false,
},
experimental = {
ghost_text = false,
native_menu = false,
},
})
cmp.setup.cmdline(":", {
mapping = cmp.mapping.preset.cmdline(),
sources = cmp.config.sources({
{ name = "path" },
}, {
{ name = "cmdline" },
}),
})
cmp.setup.cmdline("/", {
mapping = cmp.mapping.preset.cmdline(),
sources = {
{ name = "buffer" },
},
})
-- cmp-spell
-- ref. https://github.com/f3fora/cmp-spell#setup
vim.opt.spell = true
vim.opt.spelllang = { "en_us", "cjk" }
|
local cmp_status_ok, cmp = pcall(require, "cmp")
if not cmp_status_ok then
return
end
local snip_status_ok, luasnip = pcall(require, "luasnip")
if not snip_status_ok then
return
end
require("luasnip/loaders/from_vscode").lazy_load()
local check_backspace = function()
local col = vim.fn.col(".") - 1
return col == 0 or vim.fn.getline("."):sub(col, col):match("%s")
end
-- פּ ﯟ some other good icons
local kind_icons = {
Text = "",
Method = "m",
Function = "",
Constructor = "",
Field = "",
Variable = "",
Class = "",
Interface = "",
Module = "",
Property = "",
Unit = "",
Value = "",
Enum = "",
Keyword = "",
Snippet = "",
Color = "",
File = "",
Reference = "",
Folder = "",
EnumMember = "",
Constant = "",
Struct = "",
Event = "",
Operator = "",
TypeParameter = "",
}
-- find more here: https://www.nerdfonts.com/cheat-sheet
cmp.setup({
snippet = {
expand = function(args)
luasnip.lsp_expand(args.body) -- For `luasnip` users.
end,
},
mapping = cmp.mapping.preset.insert({
["<C-n>"] = cmp.mapping.select_next_item(),
["<C-p>"] = cmp.mapping.select_prev_item(),
["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(1), { "i", "c" }),
["<C-b>"] = cmp.mapping(cmp.mapping.scroll_docs(-1), { "i", "c" }),
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }),
["<C-e>"] = cmp.mapping.confirm({ select = false }, { "c" }),
-- Accept currently selected item. If none selected, `select` first item.
-- Set `select` to `false` to only confirm explicitly selected items.
["<CR>"] = cmp.mapping.confirm({ select = true }),
["<C-j>"] = cmp.mapping.confirm({ select = true }),
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expandable() then
luasnip.expand()
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif check_backspace() then
fallback()
else
fallback()
end
end, {
"i",
"s",
}),
["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, {
"i",
"s",
}),
["<C-x><C-x>"] = cmp.mapping.complete({
config = {
sources = {
{ name = "spell" },
},
},
}, { "i", "c" }),
}),
formatting = {
fields = { "kind", "abbr", "menu" },
format = function(entry, vim_item)
-- Kind icons
vim_item.kind = string.format("%s ", kind_icons[vim_item.kind])
-- vim_item.kind = string.format('%s %s', kind_icons[vim_item.kind], vim_item.kind) -- This concatonates the icons with the name of the item kind
vim_item.menu = ({
nvim_lsp = "[LSP]",
luasnip = "[Snippet]",
buffer = "[Buffer]",
path = "[Path]",
})[entry.source.name]
return vim_item
end,
},
-- sources = {
sources = cmp.config.sources({
{ name = "nvim_lsp" },
{ name = "luasnip" },
{ name = "path" },
}, {
{ name = "buffer" },
}),
confirm_opts = {
behavior = cmp.ConfirmBehavior.Replace,
select = false,
},
experimental = {
ghost_text = false,
native_menu = false,
},
})
cmp.setup.cmdline(":", {
mapping = cmp.mapping.preset.cmdline(),
sources = cmp.config.sources({
{ name = "path" },
}, {
{ name = "cmdline" },
}),
})
cmp.setup.cmdline("/", {
mapping = cmp.mapping.preset.cmdline(),
sources = {
{ name = "buffer" },
},
})
-- cmp-spell
-- ref. https://github.com/f3fora/cmp-spell#setup
vim.opt.spell = true
vim.opt.spelllang = { "en_us", "cjk" }
|
[nvim] Fix cmp config
|
[nvim] Fix cmp config
|
Lua
|
mit
|
masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles,masa0x80/dotfiles
|
5d2c2ad61da94987ef8d534f07836b916bb5861e
|
src_trunk/resources/realism-system/c_nametags.lua
|
src_trunk/resources/realism-system/c_nametags.lua
|
local localPlayer = getLocalPlayer()
local show = true
function startRes(res)
if (res==getThisResource()) then
for key, value in ipairs(getElementsByType("player")) do
setPlayerNametagShowing(value, false)
end
end
end
addEventHandler("onClientResourceStart", getRootElement(), startRes)
function setNametagOnJoin()
setPlayerNametagShowing(source, false)
end
addEventHandler("onClientPlayerJoin", getRootElement(), setNametagOnJoin)
function renderNametags()
if (show) then
for key, player in ipairs(getElementsByType("player")) do
if (isElement(player)) then
local lx, ly, lz = getElementPosition(localPlayer)
local rx, ry, rz = getElementPosition(player)
local distance = getDistanceBetweenPoints3D(lx, ly, lz, rx, ry, rz)
local limitdistance = 20
local reconx = getElementData(localPlayer, "reconx")
if (player~=localPlayer) and (isElementOnScreen(player)) and ((distance<limitdistance) or reconx) then
if not getElementData(player, "reconx") and not getElementData(player, "freecam:state") then
local lx, ly, lz = getPedBonePosition(localPlayer, 7)
local vehicle = getPedOccupiedVehicle(player)
local collision = processLineOfSight(lx, ly, lz+1, rx, ry, rz, true, true, false, true, false, false, true, false, vehicle)
if not (collision) or (reconx) then
local x, y, z = getPedBonePosition(player, 7)
local sx, sy = getScreenFromWorldPosition(x, y, z+0.45, 100, false)
-- HP
if (sx) and (sy) then
local health = getElementHealth(player)
if (health>0) then
distance = distance / 5
if (distance<1) then distance = 1 end
if (distance>2) then distance = 2 end
if (reconx) then distance = 1 end
local offset = 45 / distance
-- DRAW BG
dxDrawRectangle(sx-offset-5, sy, 95 / distance, 20 / distance, tocolor(0, 0, 0, 100), false)
-- DRAW HEALTH
local width = 85
local hpsize = (width / 100) * health
local barsize = (width / 100) * (100-health)
local color
if (health>70) then
color = tocolor(0, 255, 0, 130)
elseif (health>35 and health<=70) then
color = tocolor(255, 255, 0, 130)
else
color = tocolor(255, 0, 0, 130)
end
if (distance<1.2) then
dxDrawRectangle(sx-offset, sy+5, hpsize/distance, 10 / distance, color, false)
dxDrawRectangle((sx-offset)+(hpsize/distance), sy+5, barsize/distance, 10 / distance, tocolor(162, 162, 162, 100), false)
else
dxDrawRectangle(sx-offset, sy+5, hpsize/distance-5, 10 / distance-3, color, false)
dxDrawRectangle((sx-offset)+(hpsize/distance-5), sy+5, barsize/distance-5, 10 / distance-3, tocolor(162, 162, 162, 100), false)
end
end
end
-- ARMOR
sx, sy = getScreenFromWorldPosition(x, y, z+0.25, 100, false)
if (sx) and (sy) then
local armor = getPedArmor(player)
if (armor>0) then
local offset = 45 / distance
-- DRAW BG
dxDrawRectangle(sx-offset-5, sy, 95 / distance, 20 / distance, tocolor(0, 0, 0, 100), false)
-- DRAW HEALTH
local width = 85
local armorsize = (width / 100) * armor
local barsize = (width / 100) * (100-armor)
if (distance<1.2) then
dxDrawRectangle(sx-offset, sy+5, armorsize/distance, 10 / distance, tocolor(197, 197, 197, 130), false)
dxDrawRectangle((sx-offset)+(armorsize/distance), sy+5, barsize/distance, 10 / distance, tocolor(162, 162, 162, 100), false)
else
dxDrawRectangle(sx-offset, sy+5, armorsize/distance-5, 10 / distance-3, tocolor(197, 197, 197, 130), false)
dxDrawRectangle((sx-offset)+(armorsize/distance-5), sy+5, barsize/distance-5, 10 / distance-3, tocolor(162, 162, 162, 100), false)
end
end
end
-- NAME
sx, sy = getScreenFromWorldPosition(x, y, z+0.6, 100, false)
if (sx) and (sy) then
local offset = 65 / distance
local scale = 0.6 / distance
local font = "bankgothic"
local r, g, b = getPlayerNametagColor(player)
dxDrawText(getPlayerNametagText(player), sx-offset+2, sy+2, (sx-offset)+130 / distance, sy+20 / distance, tocolor(0, 0, 0, 220), scale, font, "center", "middle", false, false, false)
dxDrawText(getPlayerNametagText(player), sx-offset, sy, (sx-offset)+130 / distance, sy+20 / distance, tocolor(r, g, b, 220), scale, font, "center", "middle", false, false, false)
end
end
end
end
end
end
end
end
addEventHandler("onClientRender", getRootElement(), renderNametags)
function hideNametags()
show = false
end
addEvent("hidenametags", true)
addEventHandler("hidenametags", getRootElement(), hideNametags)
function showNametags()
show = true
end
addEvent("shownametags", true)
addEventHandler("shownametags", getRootElement(), showNametags)
|
local localPlayer = getLocalPlayer()
local show = true
function startRes(res)
if (res==getThisResource()) then
for key, value in ipairs(getElementsByType("player")) do
setPlayerNametagShowing(value, false)
end
end
end
addEventHandler("onClientResourceStart", getRootElement(), startRes)
function setNametagOnJoin()
setPlayerNametagShowing(source, false)
end
addEventHandler("onClientPlayerJoin", getRootElement(), setNametagOnJoin)
function renderNametags()
if (show) then
for key, player in ipairs(getElementsByType("player")) do
if (isElement(player)) then
local lx, ly, lz = getElementPosition(localPlayer)
local rx, ry, rz = getElementPosition(player)
local distance = getDistanceBetweenPoints3D(lx, ly, lz, rx, ry, rz)
local limitdistance = 20
local reconx = getElementData(localPlayer, "reconx")
if (player~=localPlayer) and (isElementOnScreen(player)) and ((distance<limitdistance) or reconx) then
if not getElementData(player, "reconx") and not getElementData(player, "freecam:state") then
local lx, ly, lz = getPedBonePosition(localPlayer, 7)
local vehicle = getPedOccupiedVehicle(player)
local collision = processLineOfSight(lx, ly, lz+1, rx, ry, rz, true, true, false, true, false, false, true, false, vehicle)
if not (collision) or (reconx) then
local x, y, z = getPedBonePosition(player, 7)
local sx, sy = getScreenFromWorldPosition(x, y, z+0.45, 100, false)
-- HP
if (sx) and (sy) then
local health = getElementHealth(player)
if (health>0) then
distance = distance / 5
if (distance<1) then distance = 1 end
if (distance>2) then distance = 2 end
if (reconx) then distance = 1 end
local offset = 45 / distance
-- DRAW BG
dxDrawRectangle(sx-offset-5, sy, 95 / distance, 20 / distance, tocolor(0, 0, 0, 100), false)
-- DRAW HEALTH
local width = 85
local hpsize = (width / 100) * health
local barsize = (width / 100) * (100-health)
local color
if (health>70) then
color = tocolor(0, 255, 0, 130)
elseif (health>35 and health<=70) then
color = tocolor(255, 255, 0, 130)
else
color = tocolor(255, 0, 0, 130)
end
if (distance<1.2) then
dxDrawRectangle(sx-offset, sy+5, hpsize/distance, 10 / distance, color, false)
dxDrawRectangle((sx-offset)+(hpsize/distance), sy+5, barsize/distance, 10 / distance, tocolor(162, 162, 162, 100), false)
else
dxDrawRectangle(sx-offset, sy+5, hpsize/distance-5, 10 / distance-3, color, false)
dxDrawRectangle((sx-offset)+(hpsize/distance-5), sy+5, barsize/distance-5, 10 / distance-3, tocolor(162, 162, 162, 100), false)
end
end
end
-- ARMOR
sx, sy = getScreenFromWorldPosition(x, y, z+0.25, 100, false)
if (sx) and (sy) then
local armor = getPedArmor(player)
if (armor>0) then
local offset = 45 / distance
-- DRAW BG
dxDrawRectangle(sx-offset-5, sy, 95 / distance, 20 / distance, tocolor(0, 0, 0, 100), false)
-- DRAW HEALTH
local width = 85
local armorsize = (width / 100) * armor
local barsize = (width / 100) * (100-armor)
if (distance<1.2) then
dxDrawRectangle(sx-offset, sy+5, armorsize/distance, 10 / distance, tocolor(197, 197, 197, 130), false)
dxDrawRectangle((sx-offset)+(armorsize/distance), sy+5, barsize/distance, 10 / distance, tocolor(162, 162, 162, 100), false)
else
dxDrawRectangle(sx-offset, sy+5, armorsize/distance-5, 10 / distance-3, tocolor(197, 197, 197, 130), false)
dxDrawRectangle((sx-offset)+(armorsize/distance-5), sy+5, barsize/distance-5, 10 / distance-3, tocolor(162, 162, 162, 100), false)
end
end
end
-- NAME
sx, sy = getScreenFromWorldPosition(x, y, z+0.6, 100, false)
if (sx) and (sy) then
if (distance < 1) then distance = 1 end
if (distance > 2) then distance = 2 end
local offset = 65 / distance
local scale = 0.6 / distance
local font = "bankgothic"
local r, g, b = getPlayerNametagColor(player)
dxDrawText(getPlayerNametagText(player), sx-offset+2, sy+2, (sx-offset)+130 / distance, sy+20 / distance, tocolor(0, 0, 0, 220), scale, font, "center", "middle", false, false, false)
dxDrawText(getPlayerNametagText(player), sx-offset, sy, (sx-offset)+130 / distance, sy+20 / distance, tocolor(r, g, b, 220), scale, font, "center", "middle", false, false, false)
end
end
end
end
end
end
end
end
addEventHandler("onClientRender", getRootElement(), renderNametags)
function hideNametags()
show = false
end
addEvent("hidenametags", true)
addEventHandler("hidenametags", getRootElement(), hideNametags)
function showNametags()
show = true
end
addEvent("shownametags", true)
addEventHandler("shownametags", getRootElement(), showNametags)
|
Few bug fixes to nametags
|
Few bug fixes to nametags
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1169 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
ff8e5847a9b109f0826124ba646d20ee77b329ea
|
lua/mediaplayer/players/components/voteskip.lua
|
lua/mediaplayer/players/components/voteskip.lua
|
--[[--------------------------------------------
Voteskip Manager
----------------------------------------------]]
local VoteskipManager = {}
VoteskipManager.__index = VoteskipManager
local VOTESKIP_REQ_VOTE_RATIO = 2/3
---
-- Initialize the Voteskip Manager object.
--
function VoteskipManager:New( ratio )
local obj = setmetatable({}, self)
obj._votes = {}
obj._value = 0
obj._ratio = VOTESKIP_REQ_VOTE_RATIO
return obj
end
function VoteskipManager:GetNumVotes()
return self._value
end
function VoteskipManager:GetNumRequiredVotes( totalPlayers )
return math.ceil( totalPlayers * self._ratio )
end
function VoteskipManager:GetNumRemainingVotes( totalPlayers )
local numVotes = self:GetNumVotes()
local reqVotes = self:GetNumRequiredVotes( totalPlayers )
return ( reqVotes - numVotes )
end
function VoteskipManager:ShouldSkip( totalPlayers )
self:Invalidate()
local reqVotes = self:GetNumRequiredVotes( totalPlayers )
return ( self._value >= reqVotes )
end
---
-- Clears all votes.
--
function VoteskipManager:Clear()
self._votes = {}
self._value = 0
end
---
-- Add vote.
--
-- @param ply Player.
-- @param value Vote value.
--
function VoteskipManager:AddVote( ply, value )
if not IsValid(ply) then return end
if not value then value = 1 end
-- value can't be negative
value = math.max( 0, value )
local uid = ply:SteamID64()
local vote = self._votes[ uid ]
if vote then
-- update existing vote
if value == 0 then
-- clear player vote
self._votes[ uid ] = nil
else
vote.value = value
end
else
vote = VOTE:New( ply, value )
self._votes[ uid ] = vote
end
self:Invalidate()
end
---
-- Remove the player's vote.
--
-- @param ply Player.
--
function VoteskipManager:RemoveVote( ply )
self:AddVote( ply, 0 )
end
---
-- Get whether the player has already voted.
--
-- @param ply Player.
-- @return Whether the player has voted.
--
function VoteskipManager:HasVoted( ply )
if not IsValid( ply ) then return false end
local uid = ply:SteamID64()
local vote = self._votes[ uid ]
return ( vote ~= nil )
end
---
-- Iterate through all votes and determine if they're still valid. This should
-- called prior to getting the top vote.
--
-- @return Whether any votes were invalid and removed.
--
function VoteskipManager:Invalidate()
local value = 0
local changed = false
for uid, vote in pairs(self._votes) do
if not IsValid( vote.player ) then
self._votes[ uid ] = nil
changed = true
continue
end
value = value + vote.value
end
if self._value ~= value then
self._value = value
changed = true
end
return changed
end
MediaPlayer.VoteskipManager = VoteskipManager
|
--[[--------------------------------------------
Voteskip Manager
----------------------------------------------]]
local VoteskipManager = {}
VoteskipManager.__index = VoteskipManager
local VOTESKIP_REQ_VOTE_RATIO = 2/3
---
-- Initialize the Voteskip Manager object.
--
function VoteskipManager:New( ratio )
local obj = setmetatable({}, self)
obj._votes = {}
obj._value = 0
obj._ratio = VOTESKIP_REQ_VOTE_RATIO
return obj
end
function VoteskipManager:GetNumVotes()
return self._value
end
function VoteskipManager:GetNumRequiredVotes( totalPlayers )
return math.ceil( totalPlayers * self._ratio )
end
function VoteskipManager:GetNumRemainingVotes( totalPlayers )
local numVotes = self:GetNumVotes()
local reqVotes = self:GetNumRequiredVotes( totalPlayers )
return ( reqVotes - numVotes )
end
function VoteskipManager:ShouldSkip( totalPlayers )
if totalPlayers <= 0 then
return false
end
self:Invalidate()
local reqVotes = self:GetNumRequiredVotes( totalPlayers )
return ( self._value >= reqVotes )
end
---
-- Clears all votes.
--
function VoteskipManager:Clear()
self._votes = {}
self._value = 0
end
---
-- Add vote.
--
-- @param ply Player.
-- @param value Vote value.
--
function VoteskipManager:AddVote( ply, value )
if not IsValid(ply) then return end
if not value then value = 1 end
-- value can't be negative
value = math.max( 0, value )
local uid = ply:SteamID64()
local vote = self._votes[ uid ]
if vote then
-- update existing vote
if value == 0 then
-- clear player vote
self._votes[ uid ] = nil
else
vote.value = value
end
else
vote = VOTE:New( ply, value )
self._votes[ uid ] = vote
end
self:Invalidate()
end
---
-- Remove the player's vote.
--
-- @param ply Player.
--
function VoteskipManager:RemoveVote( ply )
self:AddVote( ply, 0 )
end
---
-- Get whether the player has already voted.
--
-- @param ply Player.
-- @return Whether the player has voted.
--
function VoteskipManager:HasVoted( ply )
if not IsValid( ply ) then return false end
local uid = ply:SteamID64()
local vote = self._votes[ uid ]
return ( vote ~= nil )
end
---
-- Iterate through all votes and determine if they're still valid. This should
-- called prior to getting the top vote.
--
-- @return Whether any votes were invalid and removed.
--
function VoteskipManager:Invalidate()
local value = 0
local changed = false
for uid, vote in pairs(self._votes) do
if not IsValid( vote.player ) then
self._votes[ uid ] = nil
changed = true
continue
end
value = value + vote.value
end
if self._value ~= value then
self._value = value
changed = true
end
return changed
end
MediaPlayer.VoteskipManager = VoteskipManager
|
Fixed voteskips occuring when there are 0 players.
|
Fixed voteskips occuring when there are 0 players.
|
Lua
|
mit
|
pixeltailgames/gm-mediaplayer,pixeltailgames/gm-mediaplayer
|
3e31b22e85bd9e3ceeeb88295c9b4f03f576a0ff
|
src/luarocks/show.lua
|
src/luarocks/show.lua
|
--- Module implementing the LuaRocks "show" command.
-- Shows information about an installed rock.
module("luarocks.show", package.seeall)
local search = require("luarocks.search")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local path = require("luarocks.path")
local dir = require("luarocks.dir")
local deps = require("luarocks.deps")
local fetch = require("luarocks.fetch")
local manif = require("luarocks.manif")
help_summary = "Shows information about an installed rock."
help = [[
<argument> is an existing package name.
Without any flags, show all module information.
With these flags, return only the desired information:
--home home page of project
--modules all modules provided by this package as used by require()
--deps packages this package depends on
--rockspec the full path of the rockspec file
--mversion the package version
--tree local tree where rock is installed
--rock-dir data directory of the installed rock
]]
local function keys_as_string(t, sep)
return table.concat(util.keys(t), sep or " ")
end
local function word_wrap(line)
local width = tonumber(os.getenv("COLUMNS")) or 80
if width > 80 then width = 80 end
if #line > width then
local brk = width
while brk > 0 and line:sub(brk, brk) ~= " " do
brk = brk - 1
end
if brk > 0 then
return line:sub(1, brk-1) .. "\n" .. word_wrap(line:sub(brk+1))
end
end
return line
end
local function format_text(text)
text = text:gsub("^%s*",""):gsub("%s$", ""):gsub("\n[ \t]+","\n"):gsub("([^\n])\n([^\n])","%1 %2")
local paragraphs = util.split_string(text, "\n\n")
for n, line in ipairs(paragraphs) do
paragraphs[n] = word_wrap(line)
end
return (table.concat(paragraphs, "\n\n"):gsub("%s$", ""))
end
--- Driver function for "show" command.
-- @param name or nil: an existing package name.
-- @param version string or nil: a version may also be passed.
-- @return boolean: True if succeeded, nil on errors.
function run(...)
local flags, name, version = util.parse_flags(...)
if not name then
return nil, "Argument missing, see help."
end
local results = {}
local query = search.make_query(name, version)
query.exact_name = true
local tree_map = {}
for _, tree in ipairs(cfg.rocks_trees) do
local rocks_dir = path.rocks_dir(tree)
tree_map[rocks_dir] = tree
search.manifest_search(results, rocks_dir, query)
end
if not next(results) then --
return nil,"cannot find package "..name.."\nUse 'list' to find installed rocks"
end
local version,repo_url
local package, versions = util.sortedpairs(results)()
--question: what do we do about multiple versions? This should
--give us the latest version on the last repo (which is usually the global one)
for vs, repos in util.sortedpairs(versions, deps.compare_versions) do
version = vs
for _, rp in ipairs(repos) do repo_url = rp.repo end
end
local repo = tree_map[repo_url]
local directory = path.install_dir(name,version,repo)
local rockspec_file = path.rockspec_file(name, version, repo)
local rockspec, err = fetch.load_local_rockspec(rockspec_file)
if not rockspec then return nil,err end
local descript = rockspec.description
local manifest, err = manif.load_manifest(repo_url)
if not manifest then return nil,err end
local minfo = manifest.repository[name][version][1]
if flags["tree"] then print(repo)
elseif flags["rock-dir"] then print(directory)
elseif flags["home"] then print(descript.homepage)
elseif flags["modules"] then print(keys_as_string(minfo.modules))
elseif flags["deps"] then print(keys_as_string(minfo.dependencies))
elseif flags["rockspec"] then print(rockspec_file)
elseif flags["mversion"] then print(version)
else
print()
print(rockspec.package.." "..rockspec.version.." - "..descript.summary)
print()
print(format_text(descript.detailed))
print()
if descript.license then
print("License: ", descript.license)
end
if descript.homepage then
print("Homepage: ", descript.homepage)
end
print("Installed in: ", repo)
if next(minfo.modules) then
print()
print("Modules:")
print("\t"..keys_as_string(minfo.modules, "\n\t"))
end
if next(minfo.dependencies) then
print()
print("Depends on:")
print("\t"..keys_as_string(minfo.dependencies, "\n\t"))
end
print()
end
return true
end
|
--- Module implementing the LuaRocks "show" command.
-- Shows information about an installed rock.
module("luarocks.show", package.seeall)
local search = require("luarocks.search")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local path = require("luarocks.path")
local dir = require("luarocks.dir")
local deps = require("luarocks.deps")
local fetch = require("luarocks.fetch")
local manif = require("luarocks.manif")
help_summary = "Shows information about an installed rock."
help = [[
<argument> is an existing package name.
Without any flags, show all module information.
With these flags, return only the desired information:
--home home page of project
--modules all modules provided by this package as used by require()
--deps packages this package depends on
--rockspec the full path of the rockspec file
--mversion the package version
--tree local tree where rock is installed
--rock-dir data directory of the installed rock
]]
local function keys_as_string(t, sep)
return table.concat(util.keys(t), sep or " ")
end
local function word_wrap(line)
local width = tonumber(os.getenv("COLUMNS")) or 80
if width > 80 then width = 80 end
if #line > width then
local brk = width
while brk > 0 and line:sub(brk, brk) ~= " " do
brk = brk - 1
end
if brk > 0 then
return line:sub(1, brk-1) .. "\n" .. word_wrap(line:sub(brk+1))
end
end
return line
end
local function format_text(text)
text = text:gsub("^%s*",""):gsub("%s$", ""):gsub("\n[ \t]+","\n"):gsub("([^\n])\n([^\n])","%1 %2")
local paragraphs = util.split_string(text, "\n\n")
for n, line in ipairs(paragraphs) do
paragraphs[n] = word_wrap(line)
end
return (table.concat(paragraphs, "\n\n"):gsub("%s$", ""))
end
--- Driver function for "show" command.
-- @param name or nil: an existing package name.
-- @param version string or nil: a version may also be passed.
-- @return boolean: True if succeeded, nil on errors.
function run(...)
local flags, name, version = util.parse_flags(...)
if not name then
return nil, "Argument missing, see help."
end
local results = {}
local query = search.make_query(name, version)
query.exact_name = true
local tree_map = {}
for _, tree in ipairs(cfg.rocks_trees) do
local rocks_dir = path.rocks_dir(tree)
tree_map[rocks_dir] = tree
search.manifest_search(results, rocks_dir, query)
end
if not next(results) then --
return nil,"cannot find package "..name.."\nUse 'list' to find installed rocks"
end
local version,repo_url
local package, versions = util.sortedpairs(results)()
--question: what do we do about multiple versions? This should
--give us the latest version on the last repo (which is usually the global one)
for vs, repos in util.sortedpairs(versions, deps.compare_versions) do
version = vs
for _, rp in ipairs(repos) do repo_url = rp.repo end
end
local repo = tree_map[repo_url]
local directory = path.install_dir(name,version,repo)
local rockspec_file = path.rockspec_file(name, version, repo)
local rockspec, err = fetch.load_local_rockspec(rockspec_file)
if not rockspec then return nil,err end
local descript = rockspec.description
local manifest, err = manif.load_manifest(repo_url)
if not manifest then return nil,err end
local minfo = manifest.repository[name][version][1]
if flags["tree"] then print(repo)
elseif flags["rock-dir"] then print(directory)
elseif flags["home"] then print(descript.homepage)
elseif flags["modules"] then print(keys_as_string(minfo.modules))
elseif flags["deps"] then print(keys_as_string(minfo.dependencies))
elseif flags["rockspec"] then print(rockspec_file)
elseif flags["mversion"] then print(version)
else
print()
print(rockspec.package.." "..rockspec.version.." - "..descript.summary)
print()
if descript.detailed then
print(format_text(descript.detailed))
print()
end
if descript.license then
print("License: ", descript.license)
end
if descript.homepage then
print("Homepage: ", descript.homepage)
end
print("Installed in: ", repo)
if next(minfo.modules) then
print()
print("Modules:")
print("\t"..keys_as_string(minfo.modules, "\n\t"))
end
if next(minfo.dependencies) then
print()
print("Depends on:")
print("\t"..keys_as_string(minfo.dependencies, "\n\t"))
end
print()
end
return true
end
|
Only show detailed field if present in rockspec (Fix to bug reported by Steve Donovan)
|
Only show detailed field if present in rockspec
(Fix to bug reported by Steve Donovan)
|
Lua
|
mit
|
rrthomas/luarocks,xpol/luarocks,xiaq/luarocks,ignacio/luarocks,luarocks/luarocks,aryajur/luarocks,xpol/luainstaller,starius/luarocks,aryajur/luarocks,coderstudy/luarocks,coderstudy/luarocks,ignacio/luarocks,luarocks/luarocks,xpol/luavm,xpol/luainstaller,keplerproject/luarocks,coderstudy/luarocks,robooo/luarocks,xpol/luarocks,xiaq/luarocks,xpol/luavm,tarantool/luarocks,xpol/luainstaller,coderstudy/luarocks,aryajur/luarocks,starius/luarocks,leafo/luarocks,xpol/luavm,robooo/luarocks,ignacio/luarocks,tarantool/luarocks,xpol/luavm,keplerproject/luarocks,xpol/luarocks,lxbgit/luarocks,xpol/luarocks,tst2005/luarocks,rrthomas/luarocks,xpol/luainstaller,xiaq/luarocks,keplerproject/luarocks,tst2005/luarocks,keplerproject/luarocks,usstwxy/luarocks,starius/luarocks,leafo/luarocks,lxbgit/luarocks,tst2005/luarocks,starius/luarocks,rrthomas/luarocks,lxbgit/luarocks,aryajur/luarocks,usstwxy/luarocks,lxbgit/luarocks,tarantool/luarocks,xiaq/luarocks,ignacio/luarocks,usstwxy/luarocks,xpol/luavm,robooo/luarocks,rrthomas/luarocks,leafo/luarocks,robooo/luarocks,tst2005/luarocks,luarocks/luarocks,usstwxy/luarocks
|
0ce3015cf0884ec4e6b1f33b71b50f2bbfdc6601
|
src/base/detoken.lua
|
src/base/detoken.lua
|
--
-- detoken.lua
--
-- Expands tokens.
--
-- Copyright (c) 2011-2014 Jason Perkins and the Premake project
--
premake.detoken = {}
local p = premake
local detoken = p.detoken
--
-- Expand tokens in a value.
--
-- @param value
-- The value containing the tokens to be expanded.
-- @param environ
-- An execution environment for any token expansion. This is a list of
-- key-value pairs that will be inserted as global variables into the
-- token expansion runtime environment.
-- @param field
-- The definition of the field which stores the value.
-- @param basedir
-- If provided, path tokens encountered in non-path fields (where
-- field.paths is set to false) will be made relative to this location.
-- @return
-- The value with any contained tokens expanded.
--
function detoken.expand(value, environ, field, basedir)
field = field or {}
-- fetch the path variable from the action, if needed
local varMap = {}
if field.pathVars then
local action = p.action.current()
if action then
varMap = action.pathVars or {}
end
end
-- enable access to the global environment
setmetatable(environ, {__index = _G})
function expandtoken(token, e)
-- convert the token into a function to execute
local func, err = loadstring("return " .. token)
if not func then
return nil, "load error: " .. err
end
-- give the function access to the project objects
setfenv(func, e)
-- run it and get the result
local success, result = pcall(func)
if not success then
err = result
result = nil
else
err = nil
end
-- If the result is an absolute path, and it is being inserted into
-- a NON-path value, I need to make it relative to the project that
-- will contain it. Otherwise I ended up with an absolute path in
-- the generated project, and it can no longer be moved around.
local isAbs = false
if result ~= nil then
isAbs = path.isabsolute(result)
if isAbs and not field.paths and basedir then
result = path.getrelative(basedir, result)
end
end
-- If this token is in my path variable mapping table, replace the
-- value with the one from the map. This needs to go here because
-- I don't want to make the result relative, but I don't want the
-- absolute path handling below.
if varMap[token] then
err = nil
result = varMap[token]
if type(result) == "function" then
success, result = pcall(result, e)
if not success then
return nil, result
end
end
if (type(result) == "table") then
isAbs = result.absolute
result = result.token
else
isAbs = path.isabsolute(result)
end
end
-- If the result is an absolute path, and it is being inserted into
-- a path value, place a special marker at the start of it. After
-- all results have been processed, I can look for these markers to
-- find the last absolute path expanded.
--
-- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to:
-- "/home/user/myprj//home/user/myprj/obj/Debug".
--
-- By inserting a marker this becomes:
-- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug".
--
-- I can now trim everything before the marker to get the right
-- result, which should always be the last absolute path specified:
-- "/home/user/myprj/obj/Debug"
if result ~= nil and isAbs and field.paths then
result = "\0" .. result
end
return result, err
end
function expandvalue(value, e)
if type(value) ~= "string" then
return value
end
local count
repeat
value, count = value:gsub("%%{(.-)}", function(token)
local result, err = expandtoken(token:gsub("\\", "\\\\"), e)
if err then
error(err .. " in token: " .. token, 0)
end
if not result then
error("Token returned nil, it may not exist: " .. token, 0)
end
return result
end)
until count == 0
-- if a path, look for a split out embedded absolute paths
if field.paths then
local i, j
repeat
i, j = value:find("\0")
if i then
value = value:sub(i + 1)
end
until not i
end
return value
end
function recurse(value, e)
if type(value) == "table" then
local res_table = {}
for k, v in pairs(value) do
if tonumber(k) ~= nil then
res_table[k] = recurse(v, e)
else
local nk = recurse(k, e);
res_table[nk] = recurse(v, e)
end
end
return res_table
else
return expandvalue(value, e)
end
end
return recurse(value, environ)
end
|
--
-- detoken.lua
--
-- Expands tokens.
--
-- Copyright (c) 2011-2014 Jason Perkins and the Premake project
--
premake.detoken = {}
local p = premake
local detoken = p.detoken
--
-- Expand tokens in a value.
--
-- @param value
-- The value containing the tokens to be expanded.
-- @param environ
-- An execution environment for any token expansion. This is a list of
-- key-value pairs that will be inserted as global variables into the
-- token expansion runtime environment.
-- @param field
-- The definition of the field which stores the value.
-- @param basedir
-- If provided, path tokens encountered in non-path fields (where
-- field.paths is set to false) will be made relative to this location.
-- @return
-- The value with any contained tokens expanded.
--
function detoken.expand(value, environ, field, basedir)
field = field or {}
-- fetch the path variable from the action, if needed
local varMap = {}
if field.pathVars then
local action = p.action.current()
if action then
varMap = action.pathVars or {}
end
end
-- enable access to the global environment
setmetatable(environ, {__index = _G})
function expandtoken(token, e)
-- convert the token into a function to execute
local func, err = loadstring("return " .. token)
if not func then
return nil, "load error: " .. err
end
-- give the function access to the project objects
setfenv(func, e)
-- run it and get the result
local success, result = pcall(func)
if not success then
err = result
result = nil
else
err = nil
result = result or ""
end
-- If the result is an absolute path, and it is being inserted into
-- a NON-path value, I need to make it relative to the project that
-- will contain it. Otherwise I ended up with an absolute path in
-- the generated project, and it can no longer be moved around.
local isAbs = false
if result ~= nil then
isAbs = path.isabsolute(result)
if isAbs and not field.paths and basedir then
result = path.getrelative(basedir, result)
end
end
-- If this token is in my path variable mapping table, replace the
-- value with the one from the map. This needs to go here because
-- I don't want to make the result relative, but I don't want the
-- absolute path handling below.
if varMap[token] then
err = nil
result = varMap[token]
if type(result) == "function" then
success, result = pcall(result, e)
if not success then
return nil, result
end
end
if (type(result) == "table") then
isAbs = result.absolute
result = result.token
else
isAbs = path.isabsolute(result)
end
end
-- If the result is an absolute path, and it is being inserted into
-- a path value, place a special marker at the start of it. After
-- all results have been processed, I can look for these markers to
-- find the last absolute path expanded.
--
-- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to:
-- "/home/user/myprj//home/user/myprj/obj/Debug".
--
-- By inserting a marker this becomes:
-- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug".
--
-- I can now trim everything before the marker to get the right
-- result, which should always be the last absolute path specified:
-- "/home/user/myprj/obj/Debug"
if result ~= nil and isAbs and field.paths then
result = "\0" .. result
end
return result, err
end
function expandvalue(value, e)
if type(value) ~= "string" then
return value
end
local count
repeat
value, count = value:gsub("%%{(.-)}", function(token)
local result, err = expandtoken(token:gsub("\\", "\\\\"), e)
if err then
error(err .. " in token: " .. token, 0)
end
if not result then
error("Token returned nil, it may not exist: " .. token, 0)
end
return result
end)
until count == 0
-- if a path, look for a split out embedded absolute paths
if field.paths then
local i, j
repeat
i, j = value:find("\0")
if i then
value = value:sub(i + 1)
end
until not i
end
return value
end
function recurse(value, e)
if type(value) == "table" then
local res_table = {}
for k, v in pairs(value) do
if tonumber(k) ~= nil then
res_table[k] = recurse(v, e)
else
local nk = recurse(k, e);
res_table[nk] = recurse(v, e)
end
end
return res_table
else
return expandvalue(value, e)
end
end
return recurse(value, environ)
end
|
Fix regression in expandtoken
|
Fix regression in expandtoken
|
Lua
|
bsd-3-clause
|
dcourtois/premake-core,resetnow/premake-core,jstewart-amd/premake-core,mendsley/premake-core,starkos/premake-core,xriss/premake-core,lizh06/premake-core,mendsley/premake-core,aleksijuvani/premake-core,sleepingwit/premake-core,aleksijuvani/premake-core,CodeAnxiety/premake-core,lizh06/premake-core,starkos/premake-core,dcourtois/premake-core,CodeAnxiety/premake-core,starkos/premake-core,lizh06/premake-core,CodeAnxiety/premake-core,LORgames/premake-core,premake/premake-core,resetnow/premake-core,mendsley/premake-core,tvandijck/premake-core,aleksijuvani/premake-core,mandersan/premake-core,premake/premake-core,Blizzard/premake-core,dcourtois/premake-core,CodeAnxiety/premake-core,jstewart-amd/premake-core,Blizzard/premake-core,aleksijuvani/premake-core,tvandijck/premake-core,mandersan/premake-core,noresources/premake-core,noresources/premake-core,sleepingwit/premake-core,Blizzard/premake-core,dcourtois/premake-core,soundsrc/premake-core,jstewart-amd/premake-core,jstewart-amd/premake-core,mandersan/premake-core,premake/premake-core,TurkeyMan/premake-core,sleepingwit/premake-core,LORgames/premake-core,resetnow/premake-core,dcourtois/premake-core,mendsley/premake-core,starkos/premake-core,sleepingwit/premake-core,TurkeyMan/premake-core,Zefiros-Software/premake-core,Zefiros-Software/premake-core,xriss/premake-core,mandersan/premake-core,starkos/premake-core,aleksijuvani/premake-core,mandersan/premake-core,soundsrc/premake-core,LORgames/premake-core,bravnsgaard/premake-core,LORgames/premake-core,Blizzard/premake-core,bravnsgaard/premake-core,tvandijck/premake-core,resetnow/premake-core,dcourtois/premake-core,tvandijck/premake-core,noresources/premake-core,TurkeyMan/premake-core,Zefiros-Software/premake-core,starkos/premake-core,noresources/premake-core,xriss/premake-core,noresources/premake-core,Blizzard/premake-core,soundsrc/premake-core,xriss/premake-core,resetnow/premake-core,Zefiros-Software/premake-core,noresources/premake-core,premake/premake-core,xriss/premake-core,LORgames/premake-core,premake/premake-core,bravnsgaard/premake-core,lizh06/premake-core,TurkeyMan/premake-core,starkos/premake-core,mendsley/premake-core,soundsrc/premake-core,tvandijck/premake-core,Blizzard/premake-core,Zefiros-Software/premake-core,jstewart-amd/premake-core,premake/premake-core,premake/premake-core,dcourtois/premake-core,TurkeyMan/premake-core,bravnsgaard/premake-core,soundsrc/premake-core,sleepingwit/premake-core,noresources/premake-core,bravnsgaard/premake-core,CodeAnxiety/premake-core
|
674e33fb69beac030ba90be039e614b387821998
|
pud/view/GameCam.lua
|
pud/view/GameCam.lua
|
require 'pud.util'
local Class = require 'lib.hump.class'
local Camera = require 'lib.hump.camera'
local vector = require 'lib.hump.vector'
local Rect = require 'pud.kit.Rect'
local math_max, math_min = math.max, math.min
local _zoomLevels = {1, 0.5, 0.25}
local _isVector = function(...)
local n = select('#',...)
for i=1,n do
local v = select(i,...)
assert(vector.isvector(v), 'vector expected, got %s (%s)',
tostring(v), type(v))
end
return n > 0
end
local GameCam = Class{name='GameCam',
function(self, v, zoom)
v = v or vector(0,0)
if _isVector(v) then
self._zoom = math_max(1, math_min(#_zoomLevels, zoom or 1))
self._home = v
self._cam = Camera(v, _zoomLevels[self._zoom])
end
end
}
-- destructor
function GameCam:destroy()
self:unfollowTarget()
self._cam = nil
self._home = nil
self._zoom = nil
for k,v in pairs(self._limits) do self._limits[k] = nil end
self._limits = nil
end
function GameCam:_setAnimating(b)
verify('boolean', b)
self._isAnimating = b
end
function GameCam:isAnimating()
return self._isAnimating == true
end
-- zoom in smoothly
-- allows a callback to be passed in that will be called after the animation
-- is complete.
function GameCam:zoomIn(...)
if self._zoom > 1 and not self:isAnimating() then
self._zoom = self._zoom - 1
self:_setAnimating(true)
tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack',
function(self, ...)
self:_setAnimating(false)
if select('#', ...) > 0 then
local callback = select(1, ...)
callback(select(2, ...))
end
end, self, ...)
else
self:_bumpZoom(1.1)
end
end
-- zoom out smoothly
-- allows a callback to be passed in that will be called after the animation
-- is complete.
function GameCam:zoomOut(...)
if self._zoom < #_zoomLevels and not self:isAnimating() then
self._zoom = self._zoom + 1
self:_setAnimating(true)
tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack',
function(self, ...)
self:_setAnimating(false)
if select('#', ...) > 0 then
local callback = select(1, ...)
callback(select(2, ...))
end
end, self, ...)
else
self:_bumpZoom(0.9)
end
end
-- bump the zoom but don't change it
function GameCam:_bumpZoom(mult)
if not self:isAnimating() then
self:_setAnimating(true)
tween(0.1, self._cam, {zoom = _zoomLevels[self._zoom] * mult}, 'inQuad',
tween, 0.1, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outQuad',
self._setAnimating, self, false)
end
end
-- return zoom level
function GameCam:getZoom()
return self._zoom, _zoomLevels[self._zoom]
end
-- follow a target Rect
function GameCam:followTarget(rect)
assert(rect and rect.is_a and rect:is_a(Rect),
'GameCam can only follow a Rect (tried to follow %s)', tostring(rect))
self._target = rect
self._targetFuncs = {
setX = rect.setX,
setY = rect.setY,
setPosition = rect.setPosition,
setCenter = rect.setCenter,
}
local function _follow(self, theRect)
self._cam.pos = theRect:getCenterVector()
self:_correctPos(self._cam.pos)
end
rect.setX = function(theRect, x)
self._targetFuncs.setX(theRect, x)
_follow(self, theRect)
end
rect.setY = function(theRect, y)
self._targetFuncs.setY(theRect, y)
_follow(self, theRect)
end
rect.setPosition = function(theRect, x, y)
self._targetFuncs.setPosition(theRect, x, y)
_follow(self, theRect)
end
rect.setCenter = function(theRect, x, y, flag)
self._targetFuncs.setCenter(theRect, x, y, flag)
_follow(self, theRect)
end
end
-- unfollow a target Rect
function GameCam:unfollowTarget()
if self._target then
self._target.setX = self._targetFuncs.setX
self._target.setY = self._targetFuncs.setY
self._target.setPosition = self._targetFuncs.setPosition
self._target.setCenter = self._targetFuncs.setCenter
self._targetFuncs.setX = nil
self._targetFuncs.setY = nil
self._targetFuncs.setPosition = nil
self._targetFuncs.setCenter = nil
self._targetFuncs = nil
self._target = nil
end
end
-- center on initial vector
function GameCam:home()
self:unfollowTarget()
self._cam.pos = self._home
self:_correctPos(self._cam.pos)
end
-- change home vector
function GameCam:setHome(home)
if _isVector(home) then
self._home = home
end
end
-- translate along v
-- allows a callback to be passed in that will be called after the animation
-- is complete.
function GameCam:translate(v, ...)
if _isVector(v) and not self:isAnimating() then
local target = self._cam.pos + v
if self:_shouldTranslate(v) then
self:_setAnimating(true)
tween(0.15, self._cam.pos, target, 'outQuint',
function(self, ...)
self:_setAnimating(false)
if select('#', ...) > 0 then
local callback = select(1, ...)
callback(select(2, ...))
end
end, self, ...)
end
end
end
function GameCam:_shouldTranslate(v)
local pos = self._cam.pos + v
return not (pos.x > self._limits.max.x or pos.x < self._limits.min.x
or pos.y > self._limits.max.y or pos.y < self._limits.min.y)
end
-- set x and y limits for camera
function GameCam:setLimits(minV, maxV)
if _isVector(minV, maxV) then
self._limits = {min = minV, max = maxV}
end
end
-- correct the camera position if it is beyond the limits
function GameCam:_correctPos(p)
if p.x > self._limits.max.x then
p.x = self._limits.max.x
end
if p.x < self._limits.min.x then
p.x = self._limits.min.x
end
if p.y > self._limits.max.y then
p.y = self._limits.max.y
end
if p.y < self._limits.min.y then
p.y = self._limits.min.y
end
end
-- camera draw callbacks
function GameCam:predraw() self._cam:predraw() end
function GameCam:postdraw() self._cam:postdraw() end
function GameCam:draw(...) self._cam:draw(...) end
function GameCam:toWorldCoords(campos, zoom, p)
local p = vector((p.x-WIDTH/2) / zoom, (p.y-HEIGHT/2) / zoom)
return p + campos
end
-- get a rect representing the camera viewport
function GameCam:getViewport(translate, zoom)
translate = translate or vector(0,0)
zoom = self._zoom + (zoom or 0)
zoom = math_max(1, math_min(#_zoomLevels, zoom))
-- pretend to translate and zoom
local pos = self._cam.pos:clone()
pos = pos + translate
self:_correctPos(pos)
zoom = _zoomLevels[zoom]
local tl, br = vector(0,0), vector(WIDTH, HEIGHT)
local vp1 = self:toWorldCoords(pos, zoom, tl)
local vp2 = self:toWorldCoords(pos, zoom, br)
return Rect(vp1, vp2-vp1)
end
-- the class
return GameCam
|
require 'pud.util'
local Class = require 'lib.hump.class'
local Camera = require 'lib.hump.camera'
local vector = require 'lib.hump.vector'
local Rect = require 'pud.kit.Rect'
local math_max, math_min = math.max, math.min
local _zoomLevels = {1, 0.5, 0.25}
local _isVector = function(...)
local n = select('#',...)
for i=1,n do
local v = select(i,...)
assert(vector.isvector(v), 'vector expected, got %s (%s)',
tostring(v), type(v))
end
return n > 0
end
local GameCam = Class{name='GameCam',
function(self, v, zoom)
v = v or vector(0,0)
if _isVector(v) then
self._zoom = math_max(1, math_min(#_zoomLevels, zoom or 1))
self._home = v
self._cam = Camera(v, _zoomLevels[self._zoom])
end
end
}
-- destructor
function GameCam:destroy()
self:unfollowTarget()
self._cam = nil
self._home = nil
self._zoom = nil
for k,v in pairs(self._limits) do self._limits[k] = nil end
self._limits = nil
end
function GameCam:_setAnimating(b)
verify('boolean', b)
self._isAnimating = b
end
function GameCam:isAnimating()
return self._isAnimating == true
end
-- zoom in smoothly
-- allows a callback to be passed in that will be called after the animation
-- is complete.
function GameCam:zoomIn(...)
if self._zoom > 1 and not self:isAnimating() then
self._zoom = self._zoom - 1
self:_setAnimating(true)
tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack',
function(self, ...)
self:_setAnimating(false)
if select('#', ...) > 0 then
local callback = select(1, ...)
callback(select(2, ...))
end
end, self, ...)
else
self:_bumpZoom(1.1)
end
end
-- zoom out smoothly
-- allows a callback to be passed in that will be called after the animation
-- is complete.
function GameCam:zoomOut(...)
if self._zoom < #_zoomLevels and not self:isAnimating() then
self._zoom = self._zoom + 1
self:_setAnimating(true)
tween(0.25, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outBack',
function(self, ...)
self:_setAnimating(false)
if select('#', ...) > 0 then
local callback = select(1, ...)
callback(select(2, ...))
end
end, self, ...)
else
self:_bumpZoom(0.9)
end
end
-- bump the zoom but don't change it
function GameCam:_bumpZoom(mult)
if not self:isAnimating() then
self:_setAnimating(true)
tween(0.1, self._cam, {zoom = _zoomLevels[self._zoom] * mult}, 'inQuad',
tween, 0.1, self._cam, {zoom = _zoomLevels[self._zoom]}, 'outQuad',
self._setAnimating, self, false)
end
end
-- return zoom level
function GameCam:getZoom()
return self._zoom, _zoomLevels[self._zoom]
end
-- follow a target Rect
function GameCam:followTarget(rect)
assert(rect and rect.is_a and rect:is_a(Rect),
'GameCam can only follow a Rect (tried to follow %s)', tostring(rect))
self._target = rect
self._targetFuncs = {
setX = rect.setX,
setY = rect.setY,
setPosition = rect.setPosition,
setCenter = rect.setCenter,
}
local function _follow(self, theRect)
self._cam.pos = theRect:getCenterVector()
self:_correctPos(self._cam.pos)
end
rect.setX = function(theRect, x)
self._targetFuncs.setX(theRect, x)
_follow(self, theRect)
end
rect.setY = function(theRect, y)
self._targetFuncs.setY(theRect, y)
_follow(self, theRect)
end
rect.setPosition = function(theRect, x, y)
self._targetFuncs.setPosition(theRect, x, y)
_follow(self, theRect)
end
rect.setCenter = function(theRect, x, y, flag)
self._targetFuncs.setCenter(theRect, x, y, flag)
_follow(self, theRect)
end
end
-- unfollow a target Rect
function GameCam:unfollowTarget()
if self._target then
self._target.setX = self._targetFuncs.setX
self._target.setY = self._targetFuncs.setY
self._target.setPosition = self._targetFuncs.setPosition
self._target.setCenter = self._targetFuncs.setCenter
self._targetFuncs.setX = nil
self._targetFuncs.setY = nil
self._targetFuncs.setPosition = nil
self._targetFuncs.setCenter = nil
self._targetFuncs = nil
self._target = nil
end
end
-- center on initial vector
function GameCam:home()
self:unfollowTarget()
self._cam.pos = self._home
self:_correctPos(self._cam.pos)
end
-- change home vector
function GameCam:setHome(home)
if _isVector(home) then
self._home = home
end
end
-- translate along v
-- allows a callback to be passed in that will be called after the animation
-- is complete.
function GameCam:translate(v, ...)
if _isVector(v) and not self:isAnimating() then
self:_checkLimits(v)
if v:len2() ~= 0 then
local target = self._cam.pos + v
self:_setAnimating(true)
tween(0.15, self._cam.pos, target, 'outQuint',
function(self, ...)
self:_setAnimating(false)
if select('#', ...) > 0 then
local callback = select(1, ...)
callback(select(2, ...))
end
end, self, ...)
end
end
end
function GameCam:_checkLimits(v)
local pos = self._cam.pos + v
if pos.x > self._limits.max.x then
v.x = self._limits.max.x - self._cam.pos.x
end
if pos.x < self._limits.min.x then
v.x = self._limits.min.x - self._cam.pos.x
end
if pos.y > self._limits.max.y then
v.y = self._limits.max.y - self._cam.pos.y
end
if pos.y < self._limits.min.y then
v.y = self._limits.min.y - self._cam.pos.y
end
end
-- set x and y limits for camera
function GameCam:setLimits(minV, maxV)
if _isVector(minV, maxV) then
self._limits = {min = minV, max = maxV}
end
end
-- correct the camera position if it is beyond the limits
function GameCam:_correctPos(p)
if p.x > self._limits.max.x then
p.x = self._limits.max.x
end
if p.x < self._limits.min.x then
p.x = self._limits.min.x
end
if p.y > self._limits.max.y then
p.y = self._limits.max.y
end
if p.y < self._limits.min.y then
p.y = self._limits.min.y
end
end
-- camera draw callbacks
function GameCam:predraw() self._cam:predraw() end
function GameCam:postdraw() self._cam:postdraw() end
function GameCam:draw(...) self._cam:draw(...) end
function GameCam:toWorldCoords(campos, zoom, p)
local p = vector((p.x-WIDTH/2) / zoom, (p.y-HEIGHT/2) / zoom)
return p + campos
end
-- get a rect representing the camera viewport
function GameCam:getViewport(translate, zoom)
translate = translate or vector(0,0)
zoom = self._zoom + (zoom or 0)
zoom = math_max(1, math_min(#_zoomLevels, zoom))
-- pretend to translate and zoom
local pos = self._cam.pos:clone()
pos = pos + translate
self:_correctPos(pos)
zoom = _zoomLevels[zoom]
local tl, br = vector(0,0), vector(WIDTH, HEIGHT)
local vp1 = self:toWorldCoords(pos, zoom, tl)
local vp2 = self:toWorldCoords(pos, zoom, br)
return Rect(vp1, vp2-vp1)
end
-- the class
return GameCam
|
fix camera limits
|
fix camera limits
|
Lua
|
mit
|
scottcs/wyx
|
382bed6aea286d775479bda5f0186b43798f8e83
|
core/pagebuilder.lua
|
core/pagebuilder.lua
|
local awful_bad = 1073741823
local inf_bad = 10000
local eject_penalty = -inf_bad
local deplorable = 100000
SILE.pagebuilder = {
collateVboxes = function(vboxlist)
local i
local output = SILE.nodefactory.newVbox({nodes = {} })
local h = SILE.length.new({})
for i=1,#vboxlist do
table.insert(output.nodes, vboxlist[i])
h = h + vboxlist[i].height + vboxlist[i].depth
end
output.ratio = 1
output.height = h
output.depth = 0
return output
end,
findBestBreak = function(vboxlist, target)
local i
local totalHeight = SILE.length.new()
local bestBreak = nil
local leastC = inf_bad
SU.debug("pagebuilder", "Page builder called with "..#vboxlist.." nodes, "..target)
for i = 1,#vboxlist do local vbox = vboxlist[i]
SU.debug("pagebuilder", "Dealing with VBox " .. vbox)
if (vbox:isVbox()) then
totalHeight = totalHeight + vbox.height + vbox.depth;
elseif vbox:isVglue() then
totalHeight = totalHeight + vbox.height.length;
end
local left = target - totalHeight.length
SU.debug("pagebuilder", "I have " .. tostring(left) .. "pts left");
-- if (left < -20) then SU.error("\nCatastrophic page breaking failure!"); end
local pi = 0
if vbox:isPenalty() then
pi = vbox.penalty
end
if vbox:isPenalty() and vbox.penalty < inf_bad or (vbox:isVglue() and i > 1 and not vboxlist[i-1]:isDiscardable()) then
local badness = left > 0 and left * left * left or awful_bad;
local c
if badness < awful_bad then
if pi <= eject_penalty then c = pi
elseif badness < inf_bad then c = badness + pi -- plus insert
else c = deplorable
end
else c = badness end
if c < leastC then
leastC = c
bestBreak = i
end
SU.debug("pagebuilder", "Badness: "..c);
if c == awful_bad or pi <= eject_penalty then
SU.debug("pagebuilder", "outputting");
local onepage = {}
if not bestBreak then bestBreak = i-1 end
for j=1,bestBreak do
onepage[j] = table.remove(vboxlist,1)
end
return onepage, pi
end
end
end
SU.debug("pagebuilder", "No page break here")
return
end,
}
|
local awful_bad = 1073741823
local inf_bad = 10000
local eject_penalty = -inf_bad
local deplorable = 100000
SILE.pagebuilder = {
collateVboxes = function(vboxlist)
local i
local output = SILE.nodefactory.newVbox({nodes = {} })
local h = SILE.length.new({})
for i=1,#vboxlist do
table.insert(output.nodes, vboxlist[i])
h = h + vboxlist[i].height + vboxlist[i].depth
end
output.ratio = 1
output.height = h
output.depth = 0
return output
end,
findBestBreak = function(vboxlist, target)
local i
local totalHeight = SILE.length.new()
local bestBreak = nil
local leastC = inf_bad
SU.debug("pagebuilder", "Page builder called with "..#vboxlist.." nodes, "..target)
for i = 1,#vboxlist do local vbox = vboxlist[i]
SU.debug("pagebuilder", "Dealing with VBox " .. vbox)
if (vbox:isVbox()) then
totalHeight = totalHeight + vbox.height + vbox.depth;
elseif vbox:isVglue() then
totalHeight = totalHeight + vbox.height
end
local left = target - totalHeight.length
SU.debug("pagebuilder", "I have " .. tostring(left) .. "pts left");
-- if (left < -20) then SU.error("\nCatastrophic page breaking failure!"); end
local pi = 0
if vbox:isPenalty() then
pi = vbox.penalty
end
if vbox:isPenalty() and vbox.penalty < inf_bad or (vbox:isVglue() and i > 1 and not vboxlist[i-1]:isDiscardable()) then
local b1 = (left/totalHeight.stretch)
local badness = left > 0 and b1*b1*b1 or awful_bad;
local c
if badness < awful_bad then
if pi <= eject_penalty then c = pi
elseif badness < inf_bad then c = badness + pi -- plus insert
else c = deplorable
end
else c = badness end
if c < leastC then
leastC = c
bestBreak = i
end
SU.debug("pagebuilder", "Badness: "..c);
if c == awful_bad or pi <= eject_penalty then
SU.debug("pagebuilder", "outputting");
local onepage = {}
if not bestBreak then bestBreak = i-1 end
for j=1,bestBreak do
onepage[j] = table.remove(vboxlist,1)
end
return onepage, pi
end
end
end
SU.debug("pagebuilder", "No page break here")
return
end,
}
|
*EXPERIMENTAL* fix to page breaking algorithm.
|
*EXPERIMENTAL* fix to page breaking algorithm.
|
Lua
|
mit
|
anthrotype/sile,WAKAMAZU/sile_fe,alerque/sile,simoncozens/sile,neofob/sile,simoncozens/sile,shirat74/sile,alerque/sile,Nathan22Miles/sile,anthrotype/sile,WAKAMAZU/sile_fe,neofob/sile,shirat74/sile,neofob/sile,Nathan22Miles/sile,shirat74/sile,anthrotype/sile,anthrotype/sile,shirat74/sile,WAKAMAZU/sile_fe,Nathan22Miles/sile,neofob/sile,Nathan22Miles/sile,simoncozens/sile,alerque/sile,alerque/sile,simoncozens/sile,WAKAMAZU/sile_fe,Nathan22Miles/sile
|
e485aae55bddf605f9984757c734e1b9ea4ac21c
|
service/clusterd.lua
|
service/clusterd.lua
|
local skynet = require "skynet"
require "skynet.manager"
local cluster = require "skynet.cluster.core"
local config_name = skynet.getenv "cluster"
local node_address = {}
local node_sender = {}
local command = {}
local config = {}
local nodename = cluster.nodename()
local connecting = {}
local function open_channel(t, key)
local ct = connecting[key]
if ct then
local co = coroutine.running()
table.insert(ct, co)
skynet.wait(co)
return assert(ct.channel)
end
ct = {}
connecting[key] = ct
local address = node_address[key]
if address == nil and not config.nowaiting then
local co = coroutine.running()
assert(ct.namequery == nil)
ct.namequery = co
skynet.error("Waiting for cluster node [".. key.."]")
skynet.wait(co)
address = node_address[key]
end
local succ, err, c
if address then
local host, port = string.match(address, "([^:]+):(.*)$")
c = node_sender[key]
if c == nil then
c = skynet.newservice("clustersender", key, nodename)
if node_sender[key] then
-- double check
skynet.kill(c)
c = node_sender[key]
else
node_sender[key] = c
end
end
succ = pcall(skynet.call, c, "lua", "changenode", host, port)
if succ then
t[key] = c
ct.channel = c
else
err = string.format("changenode [%s] (%s:%s) failed", key, host, port)
end
else
err = string.format("cluster node [%s] is %s.", key, address == false and "down" or "absent")
end
connecting[key] = nil
for _, co in ipairs(ct) do
skynet.wakeup(co)
end
assert(succ, err)
return c
end
local node_channel = setmetatable({}, { __index = open_channel })
local function loadconfig(tmp)
if tmp == nil then
tmp = {}
if config_name then
local f = assert(io.open(config_name))
local source = f:read "*a"
f:close()
assert(load(source, "@"..config_name, "t", tmp))()
end
end
for name,address in pairs(tmp) do
if name:sub(1,2) == "__" then
name = name:sub(3)
config[name] = address
skynet.error(string.format("Config %s = %s", name, address))
else
assert(address == false or type(address) == "string")
if node_address[name] ~= address then
-- address changed
if rawget(node_channel, name) then
node_channel[name] = nil -- reset connection
end
node_address[name] = address
end
local ct = connecting[name]
if ct and ct.namequery and not config.nowaiting then
skynet.error(string.format("Cluster node [%s] resloved : %s", name, address))
skynet.wakeup(ct.namequery)
end
end
end
if config.nowaiting then
-- wakeup all connecting request
for name, ct in pairs(connecting) do
if ct.namequery then
skynet.wakeup(ct.namequery)
end
end
end
end
function command.reload(source, config)
loadconfig(config)
skynet.ret(skynet.pack(nil))
end
function command.listen(source, addr, port)
local gate = skynet.newservice("gate")
if port == nil then
local address = assert(node_address[addr], addr .. " is down")
addr, port = string.match(address, "([^:]+):(.*)$")
end
skynet.call(gate, "lua", "open", { address = addr, port = port })
skynet.ret(skynet.pack(nil))
end
function command.sender(source, node)
skynet.ret(skynet.pack(node_channel[node]))
end
local proxy = {}
function command.proxy(source, node, name)
if name == nil then
node, name = node:match "^([^@.]+)([@.].+)"
if name == nil then
error ("Invalid name " .. tostring(node))
end
end
local fullname = node .. "." .. name
local p = proxy[fullname]
if p == nil then
p = skynet.newservice("clusterproxy", node, name)
-- double check
if proxy[fullname] then
skynet.kill(p)
p = proxy[fullname]
else
proxy[fullname] = p
end
end
skynet.ret(skynet.pack(p))
end
local cluster_agent = {} -- fd:service
local register_name = {}
local function clearnamecache()
for fd, service in pairs(cluster_agent) do
if type(service) == "number" then
skynet.send(service, "lua", "namechange")
end
end
end
function command.register(source, name, addr)
assert(register_name[name] == nil)
addr = addr or source
local old_name = register_name[addr]
if old_name then
register_name[old_name] = nil
clearnamecache()
end
register_name[addr] = name
register_name[name] = addr
skynet.ret(nil)
skynet.error(string.format("Register [%s] :%08x", name, addr))
end
function command.queryname(source, name)
skynet.ret(skynet.pack(register_name[name]))
end
function command.socket(source, subcmd, fd, msg)
if subcmd == "open" then
skynet.error(string.format("socket accept from %s", msg))
-- new cluster agent
cluster_agent[fd] = false
local agent = skynet.newservice("clusteragent", skynet.self(), source, fd)
local closed = cluster_agent[fd]
cluster_agent[fd] = agent
if closed then
skynet.send(agent, "lua", "exit")
cluster_agent[fd] = nil
end
else
if subcmd == "close" or subcmd == "error" then
-- close cluster agent
local agent = cluster_agent[fd]
if type(agent) == "boolean" then
cluster_agent[fd] = true
elseif agent then
skynet.send(agent, "lua", "exit")
cluster_agent[fd] = nil
end
else
skynet.error(string.format("socket %s %d %s", subcmd, fd, msg or ""))
end
end
end
skynet.start(function()
loadconfig()
skynet.dispatch("lua", function(session , source, cmd, ...)
local f = assert(command[cmd])
f(source, ...)
end)
end)
|
local skynet = require "skynet"
require "skynet.manager"
local cluster = require "skynet.cluster.core"
local config_name = skynet.getenv "cluster"
local node_address = {}
local node_sender = {}
local command = {}
local config = {}
local nodename = cluster.nodename()
local connecting = {}
local function open_channel(t, key)
local ct = connecting[key]
if ct then
local co = coroutine.running()
table.insert(ct, co)
skynet.wait(co)
return assert(ct.channel)
end
ct = {}
connecting[key] = ct
local address = node_address[key]
if address == nil and not config.nowaiting then
local co = coroutine.running()
assert(ct.namequery == nil)
ct.namequery = co
skynet.error("Waiting for cluster node [".. key.."]")
skynet.wait(co)
address = node_address[key]
end
local succ, err, c
if address then
local host, port = string.match(address, "([^:]+):(.*)$")
c = node_sender[key]
if c == nil then
c = skynet.newservice("clustersender", key, nodename)
if node_sender[key] then
-- double check
skynet.kill(c)
c = node_sender[key]
else
node_sender[key] = c
end
end
succ = pcall(skynet.call, c, "lua", "changenode", host, port)
if succ then
t[key] = c
ct.channel = c
else
err = string.format("changenode [%s] (%s:%s) failed", key, host, port)
end
else
err = string.format("cluster node [%s] is %s.", key, address == false and "down" or "absent")
end
connecting[key] = nil
for _, co in ipairs(ct) do
skynet.wakeup(co)
end
assert(succ, err)
if node_address[key] ~= address then
return open_channel(t,key)
end
return c
end
local node_channel = setmetatable({}, { __index = open_channel })
local function loadconfig(tmp)
if tmp == nil then
tmp = {}
if config_name then
local f = assert(io.open(config_name))
local source = f:read "*a"
f:close()
assert(load(source, "@"..config_name, "t", tmp))()
end
end
local reload = {}
for name,address in pairs(tmp) do
if name:sub(1,2) == "__" then
name = name:sub(3)
config[name] = address
skynet.error(string.format("Config %s = %s", name, address))
else
assert(address == false or type(address) == "string")
if node_address[name] ~= address then
-- address changed
if rawget(node_channel, name) then
node_channel[name] = nil -- reset connection
table.insert(reload, name)
end
node_address[name] = address
end
local ct = connecting[name]
if ct and ct.namequery and not config.nowaiting then
skynet.error(string.format("Cluster node [%s] resloved : %s", name, address))
skynet.wakeup(ct.namequery)
end
end
end
if config.nowaiting then
-- wakeup all connecting request
for name, ct in pairs(connecting) do
if ct.namequery then
skynet.wakeup(ct.namequery)
end
end
end
for _, name in ipairs(reload) do
-- open_channel would block
skynet.fork(open_channel, node_channel, name)
end
end
function command.reload(source, config)
loadconfig(config)
skynet.ret(skynet.pack(nil))
end
function command.listen(source, addr, port)
local gate = skynet.newservice("gate")
if port == nil then
local address = assert(node_address[addr], addr .. " is down")
addr, port = string.match(address, "([^:]+):(.*)$")
end
skynet.call(gate, "lua", "open", { address = addr, port = port })
skynet.ret(skynet.pack(nil))
end
function command.sender(source, node)
skynet.ret(skynet.pack(node_channel[node]))
end
local proxy = {}
function command.proxy(source, node, name)
if name == nil then
node, name = node:match "^([^@.]+)([@.].+)"
if name == nil then
error ("Invalid name " .. tostring(node))
end
end
local fullname = node .. "." .. name
local p = proxy[fullname]
if p == nil then
p = skynet.newservice("clusterproxy", node, name)
-- double check
if proxy[fullname] then
skynet.kill(p)
p = proxy[fullname]
else
proxy[fullname] = p
end
end
skynet.ret(skynet.pack(p))
end
local cluster_agent = {} -- fd:service
local register_name = {}
local function clearnamecache()
for fd, service in pairs(cluster_agent) do
if type(service) == "number" then
skynet.send(service, "lua", "namechange")
end
end
end
function command.register(source, name, addr)
assert(register_name[name] == nil)
addr = addr or source
local old_name = register_name[addr]
if old_name then
register_name[old_name] = nil
clearnamecache()
end
register_name[addr] = name
register_name[name] = addr
skynet.ret(nil)
skynet.error(string.format("Register [%s] :%08x", name, addr))
end
function command.queryname(source, name)
skynet.ret(skynet.pack(register_name[name]))
end
function command.socket(source, subcmd, fd, msg)
if subcmd == "open" then
skynet.error(string.format("socket accept from %s", msg))
-- new cluster agent
cluster_agent[fd] = false
local agent = skynet.newservice("clusteragent", skynet.self(), source, fd)
local closed = cluster_agent[fd]
cluster_agent[fd] = agent
if closed then
skynet.send(agent, "lua", "exit")
cluster_agent[fd] = nil
end
else
if subcmd == "close" or subcmd == "error" then
-- close cluster agent
local agent = cluster_agent[fd]
if type(agent) == "boolean" then
cluster_agent[fd] = true
elseif agent then
skynet.send(agent, "lua", "exit")
cluster_agent[fd] = nil
end
else
skynet.error(string.format("socket %s %d %s", subcmd, fd, msg or ""))
end
end
end
skynet.start(function()
loadconfig()
skynet.dispatch("lua", function(session , source, cmd, ...)
local f = assert(command[cmd])
f(source, ...)
end)
end)
|
This may fix #1080
|
This may fix #1080
|
Lua
|
mit
|
korialuo/skynet,pigparadise/skynet,icetoggle/skynet,cloudwu/skynet,pigparadise/skynet,icetoggle/skynet,sanikoyes/skynet,bigrpg/skynet,wangyi0226/skynet,wangyi0226/skynet,xcjmine/skynet,bigrpg/skynet,jxlczjp77/skynet,JiessieDawn/skynet,sanikoyes/skynet,wangyi0226/skynet,bigrpg/skynet,korialuo/skynet,hongling0/skynet,xcjmine/skynet,cloudwu/skynet,xjdrew/skynet,korialuo/skynet,hongling0/skynet,JiessieDawn/skynet,JiessieDawn/skynet,cloudwu/skynet,sanikoyes/skynet,jxlczjp77/skynet,xjdrew/skynet,hongling0/skynet,ag6ag/skynet,xcjmine/skynet,ag6ag/skynet,pigparadise/skynet,icetoggle/skynet,xjdrew/skynet,ag6ag/skynet,jxlczjp77/skynet
|
25e94bd5cf4f4ea80bc247f625e921092a674f33
|
src/instructions.lua
|
src/instructions.lua
|
local Gamestate = require 'vendor/gamestate'
local window = require 'window'
local camera = require 'camera'
local sound = require 'vendor/TEsound'
local fonts = require 'fonts'
local controls = require 'controls'
local VerticalParticles = require "verticalparticles"
local Menu = require 'menu'
local state = Gamestate.new()
local menu = Menu.new({
'UP',
'DOWN',
'LEFT',
'RIGHT',
'SELECT',
'START',
'JUMP',
'ACTION'})
menu:onSelect(function()
controls.enableRemap = true end)
function state:init()
VerticalParticles.init()
self.arrow = love.graphics.newImage("images/menu/arrow.png")
self.background = love.graphics.newImage("images/menu/pause.png")
self.instructions = {}
-- The X coordinates of the columns
self.left_column = 160
self.right_column = 300
-- The Y coordinate of the top key
self.top = 93
-- Vertical spacing between keys
self.spacing = 20
self.statusText = 'TEST'
end
function state:enter(previous)
fonts.set( 'big' )
sound.playMusic( "daybreak" )
camera:setPosition(0, 0)
self.instructions = controls.getButtonmap()
self.previous = previous
self.option = 0
end
function state:leave()
fonts.reset()
end
function state:keypressed( button )
if controls.enableRemap then self:remapKey(button) end
if controls.getButton then menu:keypressed(button) end
if button == 'START' then Gamestate.switch(self.previous) end
end
function state:update(dt)
VerticalParticles.update(dt)
end
function state:draw()
VerticalParticles.draw()
love.graphics.draw(self.background,
camera:getWidth() / 2 - self.background:getWidth() / 2,
camera:getHeight() / 2 - self.background:getHeight() / 2)
local n = 1
love.graphics.setColor(255, 255, 255)
local back = controls.getKey("START") .. ": BACK TO MENU"
local howto = controls.getKey("ACTION") .. " OR " .. controls.getKey("SELECT") .. ": REASSIGN CONTROL"
love.graphics.print(back, 25, 25)
love.graphics.print(howto, 25, 55)
love.graphics.print(self.statusText, self.left_column, 280)
love.graphics.setColor( 0, 0, 0, 255 )
for i, button in ipairs(menu.options) do
local y = self.top + self.spacing * (i - 1)
local key = controls.getKey(button)
love.graphics.print(button, self.left_column, y, 0, 0.8)
love.graphics.print(key, self.right_column, y, 0, 0.8)
end
love.graphics.setColor( 255, 255, 255, 255 )
love.graphics.draw(self.arrow, 135, 87 + self.spacing * menu:selected())
end
function state:remapKey(key)
local button = menu.options[menu:selected() + 1]
self.statusText = button .. ": " .. key
if controls.newButton(key, button) then
assert(controls.getKey(button) == key)
else
self.statusText = "KEY IS ALREADY IN USE"
end
controls.enableRemap = false
end
return state
|
local Gamestate = require 'vendor/gamestate'
local window = require 'window'
local camera = require 'camera'
local sound = require 'vendor/TEsound'
local fonts = require 'fonts'
local controls = require 'controls'
local VerticalParticles = require "verticalparticles"
local Menu = require 'menu'
local state = Gamestate.new()
local menu = Menu.new({
'UP',
'DOWN',
'LEFT',
'RIGHT',
'SELECT',
'START',
'JUMP',
'ACTION'})
menu:onSelect(function()
controls.enableRemap = true
state.statusText = "PRESS NEW KEY" end)
function state:init()
VerticalParticles.init()
self.arrow = love.graphics.newImage("images/menu/arrow.png")
self.background = love.graphics.newImage("images/menu/pause.png")
self.instructions = {}
-- The X coordinates of the columns
self.left_column = 160
self.right_column = 300
-- The Y coordinate of the top key
self.top = 93
-- Vertical spacing between keys
self.spacing = 20
self.statusText = ''
end
function state:enter(previous)
fonts.set( 'big' )
sound.playMusic( "daybreak" )
camera:setPosition(0, 0)
self.instructions = controls.getButtonmap()
self.previous = previous
self.option = 0
end
function state:leave()
fonts.reset()
end
function state:keypressed( button )
if controls.enableRemap then self:remapKey(button) end
if controls.getButton then menu:keypressed(button) end
if button == 'START' then Gamestate.switch(self.previous) end
end
function state:update(dt)
VerticalParticles.update(dt)
end
function state:draw()
VerticalParticles.draw()
love.graphics.draw(self.background,
camera:getWidth() / 2 - self.background:getWidth() / 2,
camera:getHeight() / 2 - self.background:getHeight() / 2)
local n = 1
love.graphics.setColor(255, 255, 255)
local back = controls.getKey("START") .. ": BACK TO MENU"
local howto = controls.getKey("ACTION") .. " OR " .. controls.getKey("JUMP") .. ": REASSIGN CONTROL"
love.graphics.print(back, 25, 25)
love.graphics.print(howto, 25, 55)
love.graphics.print(self.statusText, self.left_column, 280)
love.graphics.setColor( 0, 0, 0, 255 )
for i, button in ipairs(menu.options) do
local y = self.top + self.spacing * (i - 1)
local key = controls.getKey(button)
love.graphics.print(button, self.left_column, y, 0, 0.8)
love.graphics.print(key, self.right_column, y, 0, 0.8)
end
love.graphics.setColor( 255, 255, 255, 255 )
love.graphics.draw(self.arrow, 135, 87 + self.spacing * menu:selected())
end
function state:remapKey(key)
local button = menu.options[menu:selected() + 1]
if not controls.newButton(key, button) then
self.statusText = "KEY IS ALREADY IN USE"
else
if key == ' ' then key = 'space' end
assert(controls.getKey(button) == key)
self.statusText = button .. ": " .. key
end
controls.enableRemap = false
end
return state
|
Prompts player for input and fixes assert failure
|
Prompts player for input and fixes assert failure
|
Lua
|
mit
|
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-client-lua
|
b80ca7eb2fd2b7236e50d2297e42f779902384c2
|
test/lua/unit/url.lua
|
test/lua/unit/url.lua
|
-- URL parser tests
context("URL check functions", function()
local mpool = require("rspamd_mempool")
local ffi = require("ffi")
ffi.cdef[[
struct rspamd_url {
char *string;
int protocol;
int ip_family;
char *user;
char *password;
char *host;
char *port;
char *data;
char *query;
char *fragment;
char *post;
char *surbl;
struct rspamd_url *phished_url;
unsigned int protocollen;
unsigned int userlen;
unsigned int passwordlen;
unsigned int hostlen;
unsigned int portlen;
unsigned int datalen;
unsigned int querylen;
unsigned int fragmentlen;
unsigned int surbllen;
/* Flags */
int ipv6; /* URI contains IPv6 host */
int form; /* URI originated from form */
int is_phished; /* URI maybe phishing */
};
struct rspamd_url* rspamd_url_get_next (void *pool,
const char *start, char const **pos);
void * rspamd_mempool_new (unsigned long size);
]]
test("Extract urls from text", function()
local pool = ffi.C.rspamd_mempool_new(4096)
local cases = {
{"test.com text", {"test.com", nil}},
{"mailto:[email protected] text", {"example.com", "A.User"}},
{"http://тест.рф:18 text", {"тест.рф", nil}},
{"http://user:password@тест.рф:18 text", {"тест.рф", "user"}},
}
for _,c in ipairs(cases) do
local res = ffi.C.rspamd_url_get_next(pool, c[1], nil)
assert_not_nil(res)
assert_equal(c[2][1], ffi.string(res.host, res.hostlen))
if c[2][2] then
assert_equal(c[2][2], ffi.string(res.user, res.userlen))
end
end
end)
end)
|
-- URL parser tests
context("URL check functions", function()
local mpool = require("rspamd_mempool")
local ffi = require("ffi")
ffi.cdef[[
struct rspamd_url {
char *string;
int protocol;
int ip_family;
char *user;
char *password;
char *host;
char *port;
char *data;
char *query;
char *fragment;
char *post;
char *surbl;
struct rspamd_url *phished_url;
unsigned int protocollen;
unsigned int userlen;
unsigned int passwordlen;
unsigned int hostlen;
unsigned int portlen;
unsigned int datalen;
unsigned int querylen;
unsigned int fragmentlen;
unsigned int surbllen;
/* Flags */
int ipv6; /* URI contains IPv6 host */
int form; /* URI originated from form */
int is_phished; /* URI maybe phishing */
};
struct rspamd_url* rspamd_url_get_next (void *pool,
const char *start, char const **pos);
void * rspamd_mempool_new (unsigned long size);
]]
test("Extract urls from text", function()
local pool = ffi.C.rspamd_mempool_new(4096)
local cases = {
{"test.com text", {"test.com", nil}},
{"mailto:[email protected] text", {"example.com", "A.User"}},
{"http://Тест.Рф:18 text", {"тест.рф", nil}},
{"http://user:password@тест2.РФ:18 text", {"тест2.рф", "user"}},
}
for _,c in ipairs(cases) do
local res = ffi.C.rspamd_url_get_next(pool, c[1], nil)
assert_not_nil(res, "cannot parse " .. c[1])
assert_equal(c[2][1], ffi.string(res.host, res.hostlen))
if c[2][2] then
assert_equal(c[2][2], ffi.string(res.user, res.userlen))
end
end
end)
end)
|
Fix url extraction tests.
|
Fix url extraction tests.
|
Lua
|
apache-2.0
|
amohanta/rspamd,minaevmike/rspamd,minaevmike/rspamd,awhitesong/rspamd,amohanta/rspamd,amohanta/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,dark-al/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,awhitesong/rspamd,awhitesong/rspamd,andrejzverev/rspamd,dark-al/rspamd,andrejzverev/rspamd,dark-al/rspamd,AlexeySa/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,amohanta/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,awhitesong/rspamd,andrejzverev/rspamd,dark-al/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,amohanta/rspamd,minaevmike/rspamd,AlexeySa/rspamd,dark-al/rspamd,andrejzverev/rspamd,andrejzverev/rspamd
|
b73efc6a916f862b7d381758bce42d87fa77723b
|
test_scripts/RC/GetInteriorVehicleData/007.lua
|
test_scripts/RC/GetInteriorVehicleData/007.lua
|
---------------------------------------------------------------------------------------------------
-- RPC: GetInteriorVehicleData
-- Script: 007
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local commonRC = require('test_scripts/RC/commonRC')
local runner = require('user_modules/script_runner')
--[[ Local Functions ]]
local function step1(self)
local cid = self.mobileSession:SendRPC("GetInteriorVehicleData", {
moduleDescription = {
moduleType = "CLIMATE"
},
subscribe = true
})
EXPECT_HMICALL("RC.GetInteriorVehicleData", {
appID = self.applications["Test Application"],
moduleDescription = {
moduleType = "CLIMATE"
},
subscribe = true
})
:Do(function(_, data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {
moduleData = {
moduleType = "CLIMATE",
climateControlData = commonRC.getClimateControlData()
},
isSubscribed = "yes" -- invalid type of parameter
})
end)
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
end
local function step2(self)
local cid = self.mobileSession:SendRPC("GetInteriorVehicleData", {
moduleDescription = {
moduleType = "RADIO"
},
subscribe = true
})
EXPECT_HMICALL("RC.GetInteriorVehicleData", {
appID = self.applications["Test Application"],
moduleDescription = {
moduleType = "RADIO"
},
subscribe = true
})
:Do(function(_, data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {
isSubscribed = "yes", -- invalid type of parameter
moduleData = {
moduleType = "RADIO",
radioControlData = commonRC.getRadioControlData()
}
})
end)
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
end
local function step3(self)
local cid = self.mobileSession:SendRPC("GetInteriorVehicleData", {
moduleDescription = {
moduleType = "CLIMATE"
},
subscribe = true
})
EXPECT_HMICALL("RC.GetInteriorVehicleData", {
appID = self.applications["Test Application"],
moduleDescription = {
moduleType = "CLIMATE"
},
subscribe = true
})
:Do(function(_, data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {
moduleData = {
moduleType = "CLIMATE"
-- climateControlData = commonRC.getClimateControlData() -- missing mandatory parameter
},
isSubscribed = true
})
end)
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
end
local function step4(self)
local cid = self.mobileSession:SendRPC("GetInteriorVehicleData", {
moduleDescription = {
moduleType = "RADIO"
},
subscribe = true
})
EXPECT_HMICALL("RC.GetInteriorVehicleData", {
appID = self.applications["Test Application"],
moduleDescription = {
moduleType = "RADIO"
},
subscribe = true
})
:Do(function(_, data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {
isSubscribed = true,
moduleData = {
moduleType = "RADIO"
-- radioControlData = commonRC.getRadioControlData() -- missing mandatory parameter
}
})
end)
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", commonRC.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start)
runner.Step("RAI, PTU", commonRC.rai_ptu)
runner.Title("Test")
runner.Step("GetInteriorVehicleData_CLIMATE (Invalid response from HMI-Invalid type of parameter)", step1)
runner.Step("GetInteriorVehicleData_RADIO (Invalid response from HMI-Invalid type of parameter)", step2)
runner.Step("GetInteriorVehicleData_CLIMATE (Invalid response from HMI-Missing mandatory parameter)", step3)
runner.Step("GetInteriorVehicleData_RADIO (Invalid response from HMI-Missing mandatory parameter)", step4)
runner.Title("Postconditions")
runner.Step("Stop SDL", commonRC.postconditions)
|
---------------------------------------------------------------------------------------------------
-- RPC: GetInteriorVehicleData
-- Script: 007
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local commonRC = require('test_scripts/RC/commonRC')
local runner = require('user_modules/script_runner')
--[[ Local Functions ]]
local function step1(self)
local cid = self.mobileSession:SendRPC("GetInteriorVehicleData", {
moduleDescription = {
moduleType = "CLIMATE"
},
subscribe = true
})
EXPECT_HMICALL("RC.GetInteriorVehicleData", {
appID = self.applications["Test Application"],
moduleDescription = {
moduleType = "CLIMATE"
},
subscribe = true
})
:Do(function(_, data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {
moduleData = {
moduleType = "CLIMATE",
climateControlData = commonRC.getClimateControlData()
},
isSubscribed = "yes" -- invalid type of parameter
})
end)
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
end
local function step2(self)
local cid = self.mobileSession:SendRPC("GetInteriorVehicleData", {
moduleDescription = {
moduleType = "RADIO"
},
subscribe = true
})
EXPECT_HMICALL("RC.GetInteriorVehicleData", {
appID = self.applications["Test Application"],
moduleDescription = {
moduleType = "RADIO"
},
subscribe = true
})
:Do(function(_, data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {
isSubscribed = "yes", -- invalid type of parameter
moduleData = {
moduleType = "RADIO",
radioControlData = commonRC.getRadioControlData()
}
})
end)
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
end
local function step3(self)
local cid = self.mobileSession:SendRPC("GetInteriorVehicleData", {
moduleDescription = {
moduleType = "CLIMATE"
},
subscribe = true
})
EXPECT_HMICALL("RC.GetInteriorVehicleData", {
appID = self.applications["Test Application"],
moduleDescription = {
moduleType = "CLIMATE"
},
subscribe = true
})
:Do(function(_, data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {
moduleData = {
-- moduleType = "CLIMATE" -- missing mandatory parameter
climateControlData = commonRC.getClimateControlData()
},
isSubscribed = true
})
end)
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
end
local function step4(self)
local cid = self.mobileSession:SendRPC("GetInteriorVehicleData", {
moduleDescription = {
moduleType = "RADIO"
},
subscribe = true
})
EXPECT_HMICALL("RC.GetInteriorVehicleData", {
appID = self.applications["Test Application"],
moduleDescription = {
moduleType = "RADIO"
},
subscribe = true
})
:Do(function(_, data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {
isSubscribed = true,
moduleData = {
-- moduleType = "RADIO" -- missing mandatory parameter
radioControlData = commonRC.getRadioControlData()
}
})
end)
EXPECT_RESPONSE(cid, { success = false, resultCode = "GENERIC_ERROR", info = "Invalid message received from vehicle"})
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", commonRC.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", commonRC.start)
runner.Step("RAI, PTU", commonRC.rai_ptu)
runner.Title("Test")
runner.Step("GetInteriorVehicleData_CLIMATE (Invalid response from HMI-Invalid type of parameter)", step1)
runner.Step("GetInteriorVehicleData_RADIO (Invalid response from HMI-Invalid type of parameter)", step2)
runner.Step("GetInteriorVehicleData_CLIMATE (Invalid response from HMI-Missing mandatory parameter)", step3)
runner.Step("GetInteriorVehicleData_RADIO (Invalid response from HMI-Missing mandatory parameter)", step4)
runner.Title("Postconditions")
runner.Step("Stop SDL", commonRC.postconditions)
|
Fix obligation of parameter
|
Fix obligation of parameter
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
cfaf294a8b44dff2821cc13823862d8cf750bad5
|
test_scripts/Polices/Policy_Table_Update/050_ATF_P_User_Trigger_PTU_While_Another_Is_In_Progress.lua
|
test_scripts/Polices/Policy_Table_Update/050_ATF_P_User_Trigger_PTU_While_Another_Is_In_Progress.lua
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- User triggering PTU while another PTU request is still in progress
--
-- Description:
-- If a user triggers a policy table update while another request is currently in progress (in the timeout window),
-- Policy Manager must wait for a response from the current on-going request/times-out/succeed, before the new one request will be sent out.
-- 1. Used preconditions:
-- a) SDL and HMI are running
-- b) App is connected to SDL.
-- c) The device the app is running on is consented
-- d) Policy Table Update procedure is in progress (merge of received PTU not yet happend)
-- 2. Performed steps:
-- a) User initiates PT Update from HMI (press the appropriate button) HMI->SDL: SDL.UpdateSDL
--
-- Expected result:
-- a) SDL->HMI:SDL.UpdateSDL()
-- b) Policy Manager must wait for a response from the current on-going PTU request/times-out/succeed
-- c) PoliciesManager starts the PTU sequence:
-- d) PTS is created by SDL: SDL-> HMI: SDL.PolicyUpdate() //PTU sequence started
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require ('user_modules/shared_testcases/commonSteps')
local testCasesForPolicyTable = require ('user_modules/shared_testcases/testCasesForPolicyTable')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_Activate_App_And_Consent_Device_To_Start_PTU()
local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = self.applications["Test Application"]})
EXPECT_HMIRESPONSE(RequestId, { result = {
code = 0,
isSDLAllowed = false},
method = "SDL.ActivateApp"})
:Do(function(_,_)
local RequestIdGetUserFriendlyMessage = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}})
EXPECT_HMIRESPONSE(RequestIdGetUserFriendlyMessage,{result = {code = 0, method = "SDL.GetUserFriendlyMessage"}})
:Do(function(_,_)
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}})
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_,data)
self.hmiConnection:SendResponse(data.id,"BasicCommunication.ActivateApp", "SUCCESS", {})
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"})
end)
EXPECT_NOTIFICATION("OnPermissionsChange", {})
end)
end)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_Start_Update_First_Time_And_Trigger_New_PTU_Via_UpdateSDL()
local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestIdGetURLS,{result = {code = 0, method = "SDL.GetURLS", urls = {{url = "http://policies.telematics.ford.com/api/policies"}}}})
:Do(function()
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = "filename"} )
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY" })
-- Reuest for new PTU
local RequestIdUpdateSDL = self.hmiConnection:SendRequest("SDL.UpdateSDL")
EXPECT_HMIRESPONSE(RequestIdUpdateSDL,{result = {code = 0, method = "SDL.UpdateSDL"}})
local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest",
{
fileName = "PolicyTableUpdate",
requestType = "PROPRIETARY"
}, "files/ptu_general.json")
local systemRequestId
EXPECT_HMICALL("BasicCommunication.SystemRequest")
:Do(function(_,data)
systemRequestId = data.id
self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate", { policyfile = "/tmp/fs/mp/images/ivsu_cache/PolicyTableUpdate" })
local function to_run()
self.hmiConnection:SendResponse(systemRequestId,"BasicCommunication.SystemRequest", "SUCCESS", {})
end
RUN_AFTER(to_run, 800)
self.mobileSession:ExpectResponse(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"})
-- New PTU is triggered
:Do(function(_,_)
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
:Do(function(_,_data1) self.hmiConnection:SendResponse(_data1.id, _data1.method, "SUCCESS", {}) end)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"})
:Do(function() end)
end)
EXPECT_NOTIFICATION("OnPermissionsChange", {})
end)
end)
end
function Test:TestStep_Second_Successful_Policy_Update()
local RequestIdGetURLS = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestIdGetURLS,{result = {code = 0, method = "SDL.GetURLS", urls = {{url = "http://policies.telematics.ford.com/api/policies"}}}})
:Do(function()
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",
{
requestType = "PROPRIETARY",
fileName = "filename"
}
)
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY" })
local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest",
{
fileName = "PolicyTableUpdate",
requestType = "PROPRIETARY"
}, "files/ptu_general.json")
local systemRequestId
EXPECT_HMICALL("BasicCommunication.SystemRequest")
:Do(function(_,data)
systemRequestId = data.id
self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate",
{
policyfile = "/tmp/fs/mp/images/ivsu_cache/PolicyTableUpdate"
})
local function to_run()
self.hmiConnection:SendResponse(systemRequestId,"BasicCommunication.SystemRequest", "SUCCESS", {})
end
RUN_AFTER(to_run, 800)
self.mobileSession:ExpectResponse(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"})
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"})
end)
end)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
testCasesForPolicyTable:Restore_preloaded_pt()
function Test.Postcondition_Stop()
StopSDL()
end
return Test
|
---------------------------------------------------------------------------------------------
-- Requirement summary:
-- User triggering PTU while another PTU request is still in progress
--
-- Description:
-- If a user triggers a policy table update while another request is currently in progress (in the timeout window),
-- Policy Manager must wait for a response from the current on-going request/times-out/succeed, before the new one request will be sent out.
-- 1. Used preconditions:
-- a) SDL and HMI are running
-- b) App is connected to SDL.
-- c) The device the app is running on is consented
-- d) Policy Table Update procedure is in progress (merge of received PTU not yet happend)
-- 2. Performed steps:
-- a) User initiates PT Update from HMI (press the appropriate button) HMI->SDL: SDL.UpdateSDL
--
-- Expected result:
-- a) SDL->HMI:SDL.UpdateSDL()
-- b) Policy Manager must wait for a response from the current on-going PTU request/times-out/succeed
-- c) PoliciesManager starts the PTU sequence:
-- d) PTS is created by SDL: SDL-> HMI: SDL.PolicyUpdate() //PTU sequence started
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
--ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require ('user_modules/shared_testcases/commonSteps')
local testCasesForPolicyTable = require ('user_modules/shared_testcases/testCasesForPolicyTable')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_Activate_App_And_Consent_Device_To_Start_PTU()
local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = self.applications["Test Application"]})
EXPECT_HMIRESPONSE(RequestId, { result = {
code = 0,
isSDLAllowed = false},
method = "SDL.ActivateApp"})
:Do(function(_,_)
local RequestIdGetUserFriendlyMessage = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}})
EXPECT_HMIRESPONSE(RequestIdGetUserFriendlyMessage,{result = {code = 0, method = "SDL.GetUserFriendlyMessage"}})
:Do(function(_,_)
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}})
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_,data)
self.hmiConnection:SendResponse(data.id,"BasicCommunication.ActivateApp", "SUCCESS", {})
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"})
:Do(function()
end)
end)
EXPECT_NOTIFICATION("OnPermissionsChange", {})
end)
end)
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_Start_Update_First_Time_And_Trigger_New_PTU_Via_UpdateSDL()
local RequestId_GetUrls = self.hmiConnection:SendRequest("SDL.GetURLS", { service = 7 })
EXPECT_HMIRESPONSE(RequestId_GetUrls,{result = {code = 0, method = "SDL.GetURLS" } } )
:Do(function(_,_)
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",{ fileName = "PolicyTableUpdate", requestType = "PROPRIETARY"})
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY", fileType = "JSON" } )
:Do(function(_,_)
-- Reuest for new PTU
local RequestIdUpdateSDL = self.hmiConnection:SendRequest("SDL.UpdateSDL")
EXPECT_HMIRESPONSE(RequestIdUpdateSDL,{result = {code = 0, method = "SDL.UpdateSDL"}})
local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest", {requestType = "PROPRIETARY", fileName = "PolicyTableUpdate"},
"files/ptu_general.json")
EXPECT_HMICALL("BasicCommunication.SystemRequest",{
requestType = "PROPRIETARY",
fileName = "/tmp/fs/mp/images/ivsu_cache/PolicyTableUpdate"})
:Do(function(_,_data1)
self.hmiConnection:SendResponse(_data1.id,"BasicCommunication.SystemRequest", "SUCCESS", {})
self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate",
{ policyfile = "/tmp/fs/mp/images/ivsu_cache/PolicyTableUpdate"})
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"})
end)
EXPECT_RESPONSE(CorIdSystemRequest, { success = true, resultCode = "SUCCESS"})
end)
end)
end
function Test:Test_Verify_New_PTU_is_Triggered()
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" })
:Do(function()
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
end)
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
function Test.Postcondition_Stop()
StopSDL()
end
return Test
|
Fix issues in script
|
Fix issues in script
|
Lua
|
bsd-3-clause
|
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
|
d77c9ab5ff10e06bee8022176f9a47a5346c119b
|
mods/invtweak/init.lua
|
mods/invtweak/init.lua
|
local auto_refill = minetest.setting_getbool("invtweak_auto_refill") or true
local tweak = {}
tweak.formspec = {}
tweak.buttons = {
--sort_asc
"0.8,0.6;sort_asc;^]".."tooltip[sort_asc;sort Items asc.;#30434C;#FFF]",
--sort_desc
"0.8,0.6;sort_desc;v]".."tooltip[sort_desc;sort Items desc.;#30434C;#FFF]",
--concatenate
"0.8,0.6;sort;·»]".."tooltip[sort;stack Items and sort asc.;#30434C;#FFF]"
}
local function get_formspec_size(formspec)
local w = 8
local h = 7.5
if not formspec then return end
local sstring = string.find(formspec,"size[",1,true)
if sstring ~= nil then
sstring = string.sub(formspec, sstring+5)
local p = string.find(sstring,",")
w = string.sub(sstring,1,p-1)
sstring = string.sub(sstring,p+1,string.find(sstring,"]")+2)
p = string.find(sstring,",")
if p == nil then p = string.find(sstring,"]") end
h = string.sub(sstring,1,p-1)
end
return w,h
end
local function add_buttons(player, formspec)
local name = player:get_player_name()
if not formspec then
formspec = player:get_inventory_formspec()
end
local w,h = get_formspec_size(formspec)
for i=1,#tweak.buttons do
formspec = formspec .. "button["..w-(0.8+(i*0.8))..",0.2;" .. tweak.buttons[i]
end
player:set_inventory_formspec(formspec)
return formspec
end
local armor_mod = minetest.get_modpath("3d_armor")
local ui_mod = minetest.get_modpath("unified_inventory")
-- override mods formspec function
if ui_mod then
local org = unified_inventory.get_formspec
unified_inventory.get_formspec = function(player, page)
local formspec = org(player, page)
return add_buttons(player, formspec)
end
end
if armor_mod and not ui_mod then
local org = armor.get_armor_formspec
armor.get_armor_formspec = function(self, name)
local formspec = org(self, name)
return add_buttons(minetest.get_player_by_name(name), formspec)
end
end
minetest.register_on_joinplayer(function(player)
local formspec = nil
if armor_mod and not ui_mod then
formspec = armor.get_armor_formspec(self, player:get_player_name())
end
minetest.after(0.65,function()
add_buttons(player, formspec)
end)
end)
local function comp_asc(w1,w2)
if w1.name < w2.name then
return true
end
end
local function comp_desc(w1,w2)
if w1.name > w2.name then
return true
end
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
if fields.sort_asc then
tweak.sort(player, comp_asc)
end
if fields.sort_desc then
tweak.sort(player, comp_desc)
end
if fields.sort then
tweak.sort(player, comp_asc, true)
end
-- player inventory
if minetest.setting_getbool("creative_mode") then
add_buttons(player)
end
end)
-- sort asc without mod prefix
local function comp_in(w1, w2)
local w11 = string.find(w1.name, ":")
local w22 = string.find(w2.name, ":")
if w11 ~= nil then
w11 = string.sub(w1.name,w11)
else
w11 = w1.name
end
if w22 ~= nil then
w22 = string.sub(w2.name,w22)
else
w22 = w2.name
end
if w11 < w22 then
return true
end
end
tweak.concatenate = function(list)
local last = nil
local last_cnt = 100
local refresh = false
for _,stack in ipairs(list) do
local i = _
if refresh then
refresh = false
table.sort(list, comp_asc)
list = tweak.concatenate(list)
break
end
if stack.name ~= "zztmpsortname" and last == stack.name then
if last_cnt < stack.max then
local diff = stack.max - last_cnt
local add = stack.count
if stack.count > diff then
stack.count = stack.count - diff
add = diff
else
stack.name = "zztmpsortname"
refresh = true
end
list[i-1].count = list[i-1].count + add
end
end
last = stack.name
last_cnt = stack.count
end
return list
end
tweak.sort = function(player, mode, con)
local inv = player:get_inventory()
if inv then
local list = inv:get_list("main")
local tmp_list = {}
--write whole list as table
for _,stack in ipairs(list) do
local tbl_stack = stack:to_table()
if tbl_stack == nil then tbl_stack = {name="zztmpsortname"} end
tbl_stack.max = stack:get_stack_max()
tmp_list[_]=tbl_stack
end
-- sort asc/desc
table.sort(tmp_list, mode)
if con then
tmp_list = tweak.concatenate(tmp_list)
table.sort(tmp_list, mode)
end
--write back to inventory
for _,stack in ipairs(tmp_list) do
stack.max = nil
if stack.name ~= "zztmpsortname" then
inv:set_stack("main", _, ItemStack(stack))
else
inv:set_stack("main", _, ItemStack(nil))
end
end
end
end
-- tool break sound + autorefill
function refill(player, stck_name, index)
local inv = player:get_inventory()
for i,stack in ipairs(inv:get_list("main")) do
if stack:get_name() == stck_name then
inv:set_stack("main", index, stack)
stack:clear()
inv:set_stack("main", i, stack)
minetest.log("action", "Inventory Tweaks: refilled stack("..stck_name..") of " .. player:get_player_name() )
return
end
end
end
if auto_refill == true then
minetest.register_on_placenode(function(pos, newnode, placer, oldnode)
if not placer then return end
local index = placer:get_wield_index()
local cnt = placer:get_wielded_item():get_count()-1
if minetest.setting_getbool("creative_mode") then
return
else
if cnt == 0 then
minetest.after(0.01, refill, placer, newnode.name, index)
end
end
end)
end
local wielded = {}
wielded.name = {}
wielded.wear = {}
minetest.register_on_punchnode(function(pos, node, puncher)
if not puncher or minetest.setting_getbool("creative_mode") then
return
end
local name = puncher:get_player_name()
local item = puncher:get_wielded_item()
local tname = item:get_name()
local def = minetest.registered_tools[tname]
wielded.name[name] = tname
if not item or not tname or tname == "" or not def then
return
end
local typ = def.type
if not typ or typ ~= "tool" then
return
end
wielded.wear[name] = item:get_wear()
-- TODO: re-add for custom tools like lighter
end)
minetest.register_on_dignode(function(pos, oldnode, digger)
if not digger then return end
local name = digger:get_player_name()
local item = digger:get_wielded_item()
local index = digger:get_wield_index()
local tname = item:get_name()
local def = minetest.registered_tools[tname]
if not item then
return
end
if tname ~= "" then
if not def then
return
end
end
local old_name = wielded.name[name]
if tname == old_name and tname == "" then
return
end
local old = wielded.wear[name]
if not old and tname == "" then
old = 0
end
local new = item:get_wear()
if old ~= new then
if old and old > 0 and new == 0 then
wielded.wear[name] = new
minetest.sound_play("invtweak_tool_break", {
pos = digger:getpos(),
gain = 0.9,
max_hear_distance = 5
})
if auto_refill == true then
minetest.after(0.01, refill, digger, old_name, index)
end
end
end
end)
|
local auto_refill = minetest.setting_getbool("invtweak_auto_refill") or true
local tweak = {}
tweak.formspec = {}
tweak.buttons = {
--sort_asc
"0.8,0.6;sort_asc;^]".."tooltip[sort_asc;sort Items asc.;#30434C;#FFF]",
--sort_desc
"0.8,0.6;sort_desc;v]".."tooltip[sort_desc;sort Items desc.;#30434C;#FFF]",
--concatenate
"0.8,0.6;sort;·»]".."tooltip[sort;stack Items and sort asc.;#30434C;#FFF]"
}
local function get_formspec_size(formspec)
local w = 8
local h = 7.5
if not formspec then return end
local sstring = string.find(formspec,"size[",1,true)
if sstring ~= nil then
sstring = string.sub(formspec, sstring+5)
local p = string.find(sstring,",")
w = string.sub(sstring,1,p-1)
sstring = string.sub(sstring,p+1,string.find(sstring,"]")+2)
p = string.find(sstring,",")
if p == nil then p = string.find(sstring,"]") end
h = string.sub(sstring,1,p-1)
end
return w,h
end
local function add_buttons(player, formspec)
local name = player:get_player_name()
if not formspec then
formspec = player:get_inventory_formspec()
end
local w,h = get_formspec_size(formspec)
if not w or not h then
return
end
for i=1,#tweak.buttons do
formspec = formspec .. "button["..w-(0.8+(i*0.8))..",0.2;" .. tweak.buttons[i]
end
player:set_inventory_formspec(formspec)
return formspec
end
local armor_mod = minetest.get_modpath("3d_armor")
local ui_mod = minetest.get_modpath("unified_inventory")
-- override mods formspec function
if ui_mod then
local org = unified_inventory.get_formspec
unified_inventory.get_formspec = function(player, page)
local formspec = org(player, page)
return add_buttons(player, formspec)
end
end
if armor_mod and not ui_mod then
local org = armor.get_armor_formspec
armor.get_armor_formspec = function(self, name)
local formspec = org(self, name)
return add_buttons(minetest.get_player_by_name(name), formspec)
end
end
minetest.register_on_joinplayer(function(player)
local formspec = nil
if armor_mod and not ui_mod then
formspec = armor.get_armor_formspec(self, player:get_player_name())
end
minetest.after(0.65,function()
add_buttons(player, formspec)
end)
end)
local function comp_asc(w1,w2)
if w1.name < w2.name then
return true
end
end
local function comp_desc(w1,w2)
if w1.name > w2.name then
return true
end
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
if fields.sort_asc then
tweak.sort(player, comp_asc)
end
if fields.sort_desc then
tweak.sort(player, comp_desc)
end
if fields.sort then
tweak.sort(player, comp_asc, true)
end
-- player inventory
if minetest.setting_getbool("creative_mode") then
add_buttons(player)
end
end)
-- sort asc without mod prefix
local function comp_in(w1, w2)
local w11 = string.find(w1.name, ":")
local w22 = string.find(w2.name, ":")
if w11 ~= nil then
w11 = string.sub(w1.name,w11)
else
w11 = w1.name
end
if w22 ~= nil then
w22 = string.sub(w2.name,w22)
else
w22 = w2.name
end
if w11 < w22 then
return true
end
end
tweak.concatenate = function(list)
local last = nil
local last_cnt = 100
local refresh = false
for _,stack in ipairs(list) do
local i = _
if refresh then
refresh = false
table.sort(list, comp_asc)
list = tweak.concatenate(list)
break
end
if stack.name ~= "zztmpsortname" and last == stack.name then
if last_cnt < stack.max then
local diff = stack.max - last_cnt
local add = stack.count
if stack.count > diff then
stack.count = stack.count - diff
add = diff
else
stack.name = "zztmpsortname"
refresh = true
end
list[i-1].count = list[i-1].count + add
end
end
last = stack.name
last_cnt = stack.count
end
return list
end
tweak.sort = function(player, mode, con)
local inv = player:get_inventory()
if inv then
local list = inv:get_list("main")
local tmp_list = {}
--write whole list as table
for _,stack in ipairs(list) do
local tbl_stack = stack:to_table()
if tbl_stack == nil then tbl_stack = {name="zztmpsortname"} end
tbl_stack.max = stack:get_stack_max()
tmp_list[_]=tbl_stack
end
-- sort asc/desc
table.sort(tmp_list, mode)
if con then
tmp_list = tweak.concatenate(tmp_list)
table.sort(tmp_list, mode)
end
--write back to inventory
for _,stack in ipairs(tmp_list) do
stack.max = nil
if stack.name ~= "zztmpsortname" then
inv:set_stack("main", _, ItemStack(stack))
else
inv:set_stack("main", _, ItemStack(nil))
end
end
end
end
-- tool break sound + autorefill
function refill(player, stck_name, index)
local inv = player:get_inventory()
for i,stack in ipairs(inv:get_list("main")) do
if stack:get_name() == stck_name then
inv:set_stack("main", index, stack)
stack:clear()
inv:set_stack("main", i, stack)
minetest.log("action", "Inventory Tweaks: refilled stack("..stck_name..") of " .. player:get_player_name() )
return
end
end
end
if auto_refill == true then
minetest.register_on_placenode(function(pos, newnode, placer, oldnode)
if not placer then return end
local index = placer:get_wield_index()
local cnt = placer:get_wielded_item():get_count()-1
if minetest.setting_getbool("creative_mode") then
return
else
if cnt == 0 then
minetest.after(0.01, refill, placer, newnode.name, index)
end
end
end)
end
local wielded = {}
wielded.name = {}
wielded.wear = {}
minetest.register_on_punchnode(function(pos, node, puncher)
if not puncher or minetest.setting_getbool("creative_mode") then
return
end
local name = puncher:get_player_name()
local item = puncher:get_wielded_item()
local tname = item:get_name()
local def = minetest.registered_tools[tname]
wielded.name[name] = tname
if not item or not tname or tname == "" or not def then
return
end
local typ = def.type
if not typ or typ ~= "tool" then
return
end
wielded.wear[name] = item:get_wear()
-- TODO: re-add for custom tools like lighter
end)
minetest.register_on_dignode(function(pos, oldnode, digger)
if not digger then return end
local name = digger:get_player_name()
local item = digger:get_wielded_item()
local index = digger:get_wield_index()
local tname = item:get_name()
local def = minetest.registered_tools[tname]
if not item then
return
end
if tname ~= "" then
if not def then
return
end
end
local old_name = wielded.name[name]
if tname == old_name and tname == "" then
return
end
local old = wielded.wear[name]
if not old and tname == "" then
old = 0
end
local new = item:get_wear()
if old ~= new then
if old and old > 0 and new == 0 then
wielded.wear[name] = new
minetest.sound_play("invtweak_tool_break", {
pos = digger:getpos(),
gain = 0.9,
max_hear_distance = 5
})
if auto_refill == true then
minetest.after(0.01, refill, digger, old_name, index)
end
end
end
end)
|
fixed crash when player leave during the join server
|
fixed crash when player leave during the join server
|
Lua
|
unlicense
|
sys4-fr/server-minetestforfun,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,Coethium/server-minetestforfun,Ombridride/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,paly2/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,crabman77/minetest-minetestforfun-server
|
c061236a8af0d027d18b42fd555e7ab543730706
|
src/nodes/platform.lua
|
src/nodes/platform.lua
|
local Timer = require 'vendor/timer'
local Platform = {}
Platform.__index = Platform
function Platform.new(node, collider)
local platform = {}
setmetatable(platform, Platform)
--If the node is a polyline, we need to draw a polygon rather than rectangle
if node.polyline or node.polygon then
local polygon = node.polyline or node.polygon
local vertices = {}
for i, point in ipairs(polygon) do
table.insert(vertices, node.x + point.x)
table.insert(vertices, node.y + point.y)
end
platform.bb = collider:addPolygon(unpack(vertices))
platform.bb.polyline = polygon
else
platform.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
platform.bb.polyline = nil
end
platform.drop = node.properties.drop ~= 'false'
platform.bb.node = platform
collider:setPassive(platform.bb)
return platform
end
function Platform:collide(player, dt, mtv_x, mtv_y)
local _, wy1, _, wy2 = self.bb:bbox()
local px1, py1, px2, py2 = player.bb:bbox()
local distance = math.abs(player.velocity.y * dt) + 0.10
function updatePlayer()
player:moveBoundingBox()
player.jumping = false
player.rebounding = false
end
if self.bb.polyline
and player.velocity.y >= 0
-- Prevent the player from being treadmilled through an object
and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then
if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then
if not self.dropdelay then
self.dropdelay = Timer.add(0.5, function()
self.hasdropped = true
self.dropdelay = nil
end)
end
else
if self.dropdelay then
Timer.cancel(self.dropdelay)
self.dropdelay = nil
end
end
if self.hasdropped then
Timer.add(0.5, function() self.hasdropped = nil end)
player.jumping = true
player.state = 'crouch'
else
player.velocity.y = 0
-- Use the MTV to keep players feet on the ground,
-- fudge the Y a bit to prevent falling into steep angles
player.position.y = (py1 - 1) + mtv_y
updatePlayer()
end
elseif player.velocity.y >= 0 and math.abs(wy1 - py2) <= distance then
if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then
if not self.dropdelay then
self.dropdelay = Timer.add(0.5, function()
self.hasdropped = true
self.dropdelay = nil
end)
end
else
if self.dropdelay then
Timer.cancel(self.dropdelay)
self.dropdelay = nil
end
end
if self.hasdropped then
Timer.add(0.5, function() self.hasdropped = nil end)
player.jumping = true
player.state = 'crouch'
else
player.velocity.y = 0
player.position.y = wy1 - player.height
updatePlayer()
end
end
end
return Platform
|
local Timer = require 'vendor/timer'
local Platform = {}
Platform.__index = Platform
function Platform.new(node, collider)
local platform = {}
setmetatable(platform, Platform)
--If the node is a polyline, we need to draw a polygon rather than rectangle
if node.polyline or node.polygon then
local polygon = node.polyline or node.polygon
local vertices = {}
for i, point in ipairs(polygon) do
table.insert(vertices, node.x + point.x)
table.insert(vertices, node.y + point.y)
end
platform.bb = collider:addPolygon(unpack(vertices))
platform.bb.polyline = polygon
else
platform.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
platform.bb.polyline = nil
end
platform.drop = node.properties.drop ~= 'false'
platform.bb.node = platform
collider:setPassive(platform.bb)
return platform
end
function Platform:collide(player, dt, mtv_x, mtv_y)
local _, wy1, _, wy2 = self.bb:bbox()
local px1, py1, px2, py2 = player.bb:bbox()
local distance = math.abs(player.velocity.y * dt) + 0.10
function updatePlayer()
player:moveBoundingBox()
player.jumping = false
player.rebounding = false
end
if self.bb.polyline
and player.velocity.y >= 0
-- Prevent the player from being treadmilled through an object
and ( self.bb:contains(px2,py2) or self.bb:contains(px1,py2) ) then
if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then
if not self.dropdelay then
self.dropdelay = Timer.add(0.5, function()
self.hasdropped = true
self.dropdelay = nil
end)
end
end
if self.dropdelay and ( player.state ~= 'crouch' or player.jumping ) and not self.hasdropped then
Timer.cancel(self.dropdelay)
self.dropdelay = nil
end
if self.hasdropped then
Timer.add(0.5, function() self.hasdropped = nil end)
player.jumping = true
player.state = 'crouch'
else
player.velocity.y = 0
-- Use the MTV to keep players feet on the ground,
-- fudge the Y a bit to prevent falling into steep angles
player.position.y = (py1 - 1) + mtv_y
updatePlayer()
end
elseif player.velocity.y >= 0 and math.abs(wy1 - py2) <= distance then
if self.drop and player.state == 'crouch' and player.velocity.x == 0 and not self.hasdropped then
if not self.dropdelay then
self.dropdelay = Timer.add(0.5, function()
self.hasdropped = true
self.dropdelay = nil
end)
end
end
if self.dropdelay and ( player.state ~= 'crouch' or player.jumping ) and not self.hasdropped then
Timer.cancel(self.dropdelay)
self.dropdelay = nil
end
if self.hasdropped then
Timer.add(0.5, function() self.hasdropped = nil end)
player.jumping = true
player.state = 'crouch'
else
player.velocity.y = 0
player.position.y = wy1 - player.height
updatePlayer()
end
end
end
return Platform
|
Dropping issue. Fixes #244
|
Dropping issue. Fixes #244
|
Lua
|
mit
|
hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua,hawkthorne/hawkthorne-server-lua,hawkthorne/hawkthorne-client-lua
|
b07cba45976ccfca938d54605a9915f5a06c1821
|
MMOCoreORB/bin/scripts/mobile/lair/tatooine_desert_eopie_lair_neutral_small.lua
|
MMOCoreORB/bin/scripts/mobile/lair/tatooine_desert_eopie_lair_neutral_small.lua
|
-- Generated by LairTool
tatooine_desert_eopie_lair_neutral_small = Lair:new {
mobiles = {{"desert_eopie", 0}},
spawnLimit = 15,
buildingsVeryEasy = {"object/tangible/lair/base/poi_all_lair_insecthill_small_fog_mustard.iff"},
buildingsEasy = {"object/tangible/lair/base/poi_all_lair_insecthill_small_fog_mustard.iff"},
buildingsMedium = {"object/tangible/lair/base/poi_all_lair_insecthill_small_fog_mustard.iff"},
buildingsHard = {"object/tangible/lair/base/poi_all_lair_insecthill_small_fog_mustard.iff"},
buildingsVeryHard = {"object/tangible/lair/base/poi_all_lair_insecthill_small_fog_mustard.iff"}
}
addLairTemplate("tatooine_desert_eopie_lair_neutral_small", tatooine_desert_eopie_lair_neutral_small)
|
-- Generated by LairTool
tatooine_desert_eopie_lair_neutral_small = Lair:new {
mobiles = {{"desert_eopie", 0}},
spawnLimit = 15,
buildingsVeryEasy = {"object/tangible/lair/eopie/lair_eopie.iff"},
buildingsEasy = {"object/tangible/lair/eopie/lair_eopie.iff"},
buildingsMedium = {"object/tangible/lair/eopie/lair_eopie.iff"},
buildingsHard = {"object/tangible/lair/eopie/lair_eopie.iff"},
buildingsVeryHard = {"object/tangible/lair/eopie/lair_eopie.iff"}
}
addLairTemplate("tatooine_desert_eopie_lair_neutral_small", tatooine_desert_eopie_lair_neutral_small)
|
[fixed] Desert Eopie lair's now display the correct lair.
|
[fixed] Desert Eopie lair's now display the correct lair.
Change-Id: I3c9bb4161a0fd09f36857ecd7d2abcc9c8da47f5
|
Lua
|
agpl-3.0
|
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
|
368384e4bbd1b34d00b39d7fb681201e205f7ade
|
third_party/bullet/premake5.lua
|
third_party/bullet/premake5.lua
|
dofile("../../tools/premake/options.lua")
dofile("../../tools/premake/globals.lua")
if _ACTION == "vs2017" or _ACTION == "vs2015" then
platform_dir = _ACTION
end
link_cmd = ""
if platform_dir == "osx" then
link_cmd = "-mmacosx-version-min=10.8"
end
solution "bullet_build"
location ("build/" .. platform_dir )
configurations { "Debug", "Release" }
-- Project
project "bullet_monolithic"
setup_env()
location ("build\\" .. platform_dir)
kind "StaticLib"
language "C++"
includedirs
{
"src\\",
}
if _ACTION == "vs2017" or _ACTION == "vs2015" or ACTION == "vs2019" then
systemversion(windows_sdk_version())
disablewarnings { "4267", "4305", "4244" }
end
setup_env()
files
{
"src\\Bullet3Collision\\**.*",
"src\\Bullet3Common\\**.*",
"src\\Bullet3Dynamics\\**.*",
"src\\Bullet3Geometry\\**.*",
"src\\Bullet3Serialize\\**.*",
"src\\BulletDynamics\\**.*",
"src\\BulletCollision\\**.*",
"src\\LinearMath\\**.*",
}
includedirs { "include" }
configuration "Debug"
defines { "DEBUG" }
entrypoint "WinMainCRTStartup"
linkoptions { link_cmd }
symbols "On"
targetdir ("lib/" .. platform_dir)
targetname "bullet_monolithic_d"
configuration "Release"
defines { "NDEBUG" }
entrypoint "WinMainCRTStartup"
optimize "Speed"
linkoptions { link_cmd }
targetdir ("lib/" .. platform_dir)
targetname "bullet_monolithic"
|
dofile("../../tools/premake/options.lua")
dofile("../../tools/premake/globals.lua")
link_cmd = ""
if platform_dir == "osx" then
link_cmd = "-mmacosx-version-min=10.8"
end
solution "bullet_build"
location ("build/" .. platform_dir )
configurations { "Debug", "Release" }
-- Project
project "bullet_monolithic"
setup_env()
location ("build\\" .. platform_dir)
kind "StaticLib"
language "C++"
includedirs
{
"src\\",
}
if _ACTION == "vs2017" or _ACTION == "vs2015" or ACTION == "vs2019" then
systemversion(windows_sdk_version())
disablewarnings { "4267", "4305", "4244" }
end
setup_env()
files
{
"src\\Bullet3Collision\\**.*",
"src\\Bullet3Common\\**.*",
"src\\Bullet3Dynamics\\**.*",
"src\\Bullet3Geometry\\**.*",
"src\\Bullet3Serialize\\**.*",
"src\\BulletDynamics\\**.*",
"src\\BulletCollision\\**.*",
"src\\LinearMath\\**.*",
}
includedirs { "include" }
configuration "Debug"
defines { "DEBUG" }
entrypoint "WinMainCRTStartup"
linkoptions { link_cmd }
symbols "On"
targetdir ("lib/" .. platform_dir)
targetname "bullet_monolithic_d"
configuration "Release"
defines { "NDEBUG" }
entrypoint "WinMainCRTStartup"
optimize "Speed"
linkoptions { link_cmd }
targetdir ("lib/" .. platform_dir)
targetname "bullet_monolithic"
|
- compile fix for ci win32
|
- compile fix for ci win32
|
Lua
|
mit
|
polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech
|
92fc62fb4bcb459e5fa8a0dc019f1a23ecd1078d
|
MCServer/Plugins/MagicCarpet/plugin.lua
|
MCServer/Plugins/MagicCarpet/plugin.lua
|
local PLUGIN = {}
local Carpets = {}
function Initialize( Plugin )
PLUGIN = Plugin
Plugin:SetName( "MagicCarpet" )
Plugin:SetVersion( 1 )
PluginManager = cRoot:Get():GetPluginManager()
PluginManager:AddHook(Plugin, cPluginManager.HOOK_PLAYER_MOVING)
PluginManager:AddHook(Plugin, cPluginManager.HOOK_DISCONNECT)
PluginManager:BindCommand("/mc", "magiccarpet", HandleCarpetCommand, " - Spawns a magical carpet");
Log( "Initialized " .. Plugin:GetName() .. " v." .. Plugin:GetVersion() )
return true
end
function OnDisable()
Log( PLUGIN:GetName() .. " v." .. PLUGIN:GetVersion() .. " is shutting down..." )
for i, Carpet in pairs( Carpets ) do
Carpet:remove()
end
end
function HandleCarpetCommand( Split, Player )
Carpet = Carpets[ Player ]
if( Carpet == nil ) then
Carpets[ Player ] = cCarpet:new()
Player:SendMessage("You're on a magic carpet!" )
else
Carpet:remove()
Carpets[ Player ] = nil
Player:SendMessage("The carpet vanished!" )
end
return true
end
function OnDisconnect( Reason, Player )
local Carpet = Carpets[ Player ]
if( Carpet ~= nil ) then
Carpet:remove()
end
Carpets[ Player ] = nil
end
function OnPlayerMoving(Player)
local Carpet = Carpets[ Player ]
if( Carpet == nil ) then
return
end
if( Player:GetPitch() == 90 ) then
Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY() - 1, Player:GetPosZ() ) )
else
if( Player:GetPosY() < Carpet:getY() ) then
LOGINFO("Fell tru mc!")
Player:TeleportTo( Player:GetPosX(), Carpet:getY(), Player:GetPosZ() )
end
Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY(), Player:GetPosZ() ) )
end
end
|
local PLUGIN = {}
local Carpets = {}
function Initialize( Plugin )
PLUGIN = Plugin
Plugin:SetName( "MagicCarpet" )
Plugin:SetVersion( 1 )
PluginManager = cRoot:Get():GetPluginManager()
PluginManager:AddHook(Plugin, cPluginManager.HOOK_PLAYER_MOVING)
PluginManager:AddHook(Plugin, cPluginManager.HOOK_DISCONNECT)
PluginManager:BindCommand("/mc", "magiccarpet", HandleCarpetCommand, " - Spawns a magical carpet");
LOG( "Initialized " .. Plugin:GetName() .. " v." .. Plugin:GetVersion() )
return true
end
function OnDisable()
LOG( PLUGIN:GetName() .. " v." .. PLUGIN:GetVersion() .. " is shutting down..." )
for i, Carpet in pairs( Carpets ) do
Carpet:remove()
end
end
function HandleCarpetCommand( Split, Player )
Carpet = Carpets[ Player ]
if( Carpet == nil ) then
Carpets[ Player ] = cCarpet:new()
Player:SendMessage("You're on a magic carpet!" )
else
Carpet:remove()
Carpets[ Player ] = nil
Player:SendMessage("The carpet vanished!" )
end
return true
end
function OnDisconnect( Reason, Player )
local Carpet = Carpets[ Player ]
if( Carpet ~= nil ) then
Carpet:remove()
end
Carpets[ Player ] = nil
end
function OnPlayerMoving(Player)
local Carpet = Carpets[ Player ]
if( Carpet == nil ) then
return
end
if( Player:GetPitch() == 90 ) then
Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY() - 1, Player:GetPosZ() ) )
else
if( Player:GetPosY() < Carpet:getY() ) then
LOGINFO("Fell tru mc!")
Player:TeleportTo( Player:GetPosX(), Carpet:getY(), Player:GetPosZ() )
end
Carpet:moveTo( cLocation:new( Player:GetPosX(), Player:GetPosY(), Player:GetPosZ() ) )
end
end
|
Fixed The MagicCarpet plugin
|
Fixed The MagicCarpet plugin
git-svn-id: ffe80d23790c2318db4f9b6ad70c6163efa9c8e4@1590 0a769ca7-a7f5-676a-18bf-c427514a06d6
|
Lua
|
apache-2.0
|
MuhammadWang/MCServer,mmdk95/cuberite,kevinr/cuberite,johnsoch/cuberite,Frownigami1/cuberite,ionux/MCServer,QUSpilPrgm/cuberite,Frownigami1/cuberite,thetaeo/cuberite,linnemannr/MCServer,guijun/MCServer,zackp30/cuberite,QUSpilPrgm/cuberite,electromatter/cuberite,Haxi52/cuberite,SamOatesPlugins/cuberite,MuhammadWang/MCServer,guijun/MCServer,nicodinh/cuberite,linnemannr/MCServer,marvinkopf/cuberite,Schwertspize/cuberite,QUSpilPrgm/cuberite,nounoursheureux/MCServer,jammet/MCServer,nounoursheureux/MCServer,nounoursheureux/MCServer,thetaeo/cuberite,johnsoch/cuberite,nichwall/cuberite,jammet/MCServer,kevinr/cuberite,tonibm19/cuberite,tonibm19/cuberite,birkett/cuberite,mc-server/MCServer,bendl/cuberite,zackp30/cuberite,birkett/MCServer,tonibm19/cuberite,Tri125/MCServer,mc-server/MCServer,Howaner/MCServer,birkett/MCServer,birkett/cuberite,HelenaKitty/EbooMC,nicodinh/cuberite,Haxi52/cuberite,marvinkopf/cuberite,nichwall/cuberite,guijun/MCServer,bendl/cuberite,guijun/MCServer,Haxi52/cuberite,guijun/MCServer,nounoursheureux/MCServer,nichwall/cuberite,marvinkopf/cuberite,Tri125/MCServer,jammet/MCServer,SamOatesPlugins/cuberite,Tri125/MCServer,nicodinh/cuberite,Frownigami1/cuberite,mc-server/MCServer,nicodinh/cuberite,zackp30/cuberite,Fighter19/cuberite,Fighter19/cuberite,mjssw/cuberite,ionux/MCServer,Fighter19/cuberite,thetaeo/cuberite,mmdk95/cuberite,Howaner/MCServer,johnsoch/cuberite,nevercast/cuberite,Schwertspize/cuberite,Tri125/MCServer,Haxi52/cuberite,Schwertspize/cuberite,nevercast/cuberite,nevercast/cuberite,Frownigami1/cuberite,tonibm19/cuberite,HelenaKitty/EbooMC,mc-server/MCServer,marvinkopf/cuberite,Schwertspize/cuberite,johnsoch/cuberite,zackp30/cuberite,SamOatesPlugins/cuberite,birkett/cuberite,Howaner/MCServer,bendl/cuberite,nichwall/cuberite,mjssw/cuberite,linnemannr/MCServer,mjssw/cuberite,kevinr/cuberite,Fighter19/cuberite,electromatter/cuberite,bendl/cuberite,kevinr/cuberite,nicodinh/cuberite,nounoursheureux/MCServer,mjssw/cuberite,zackp30/cuberite,Fighter19/cuberite,Altenius/cuberite,thetaeo/cuberite,birkett/cuberite,electromatter/cuberite,mmdk95/cuberite,birkett/MCServer,ionux/MCServer,electromatter/cuberite,Howaner/MCServer,bendl/cuberite,jammet/MCServer,electromatter/cuberite,Howaner/MCServer,nounoursheureux/MCServer,Altenius/cuberite,mjssw/cuberite,HelenaKitty/EbooMC,nevercast/cuberite,Haxi52/cuberite,ionux/MCServer,kevinr/cuberite,jammet/MCServer,QUSpilPrgm/cuberite,SamOatesPlugins/cuberite,HelenaKitty/EbooMC,HelenaKitty/EbooMC,MuhammadWang/MCServer,Haxi52/cuberite,guijun/MCServer,birkett/cuberite,marvinkopf/cuberite,MuhammadWang/MCServer,Altenius/cuberite,Altenius/cuberite,MuhammadWang/MCServer,birkett/MCServer,SamOatesPlugins/cuberite,linnemannr/MCServer,Frownigami1/cuberite,birkett/MCServer,jammet/MCServer,mc-server/MCServer,nichwall/cuberite,kevinr/cuberite,mjssw/cuberite,Tri125/MCServer,QUSpilPrgm/cuberite,thetaeo/cuberite,mmdk95/cuberite,thetaeo/cuberite,linnemannr/MCServer,Fighter19/cuberite,linnemannr/MCServer,Schwertspize/cuberite,mmdk95/cuberite,QUSpilPrgm/cuberite,mmdk95/cuberite,birkett/cuberite,nevercast/cuberite,nevercast/cuberite,tonibm19/cuberite,nicodinh/cuberite,marvinkopf/cuberite,tonibm19/cuberite,johnsoch/cuberite,electromatter/cuberite,ionux/MCServer,zackp30/cuberite,ionux/MCServer,nichwall/cuberite,Howaner/MCServer,birkett/MCServer,Tri125/MCServer,Altenius/cuberite,mc-server/MCServer
|
5e3ca2709a877eac01f2aacad7bff5ae796d1aa0
|
modules/lua/commands.lua
|
modules/lua/commands.lua
|
-- Copyright 2007-2008 Mitchell mitchell<att>caladbolg.net. See LICENSE.
---
-- Commands for the lua module.
module('_m.lua.commands', package.seeall)
---
-- 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
buffer:begin_undo_action()
buffer:line_end() buffer:new_line()
local line_num = buffer:line_from_position(buffer.current_pos)
local line = buffer:get_line(line_num - 1)
for _, patt in ipairs(control_structure_patterns) do
if line:match(patt) then
local indent = buffer.line_indentation[line_num - 1]
buffer:add_text( patt:match('repeat') and '\nuntil' or '\nend' )
buffer.line_indentation[line_num + 1] = indent
buffer.line_indentation[line_num] = indent + buffer.indent
buffer:line_up() buffer:line_end()
break
end
end
buffer:end_undo_action()
end
---
-- Determines the Lua file being 'require'd, searches through package.path for
-- that file, and opens it in Textadept.
function goto_required()
local buffer = buffer
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
file = file:sub(2, -2):gsub('%.', '/')
for path in package.path:gmatch('[^;]+') do
path = path:gsub('?', file)
local f = io.open(path)
if f then f:close() textadept.io.open(path) break end
end
end
---
-- Executes the current file.
function run()
local buffer = buffer
local cmd = 'lua "'..buffer.filename..'" 2>&1'
local p = io.popen(cmd)
local out = p:read('*all')
p:close()
textadept.print('> '..cmd..'\n'..out)
end
-- Lua-specific key commands.
local keys = _G.keys
if type(keys) == 'table' then
local m_editing = _m.textadept.editing
keys.lua = {
al = { textadept.io.open, _HOME..'/modules/lua/init.lua' },
ac = {
g = { goto_required }
},
['s\n'] = { try_to_autocomplete_end },
cq = { m_editing.block_comment, '--~' },
cg = { run },
['('] = { function()
buffer.word_chars =
'_.:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
m_editing.show_call_tip(_m.lua.api, true)
buffer:set_chars_default()
return false
end },
}
end
|
-- Copyright 2007-2008 Mitchell mitchell<att>caladbolg.net. See LICENSE.
---
-- Commands for the lua module.
module('_m.lua.commands', package.seeall)
---
-- 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
buffer:begin_undo_action()
buffer:line_end() buffer:new_line()
local line_num = buffer:line_from_position(buffer.current_pos)
local line = buffer:get_line(line_num - 1)
for _, patt in ipairs(control_structure_patterns) do
if line:match(patt) then
local indent = buffer.line_indentation[line_num - 1]
buffer:add_text( patt:match('repeat') and '\nuntil' or '\nend' )
buffer.line_indentation[line_num + 1] = indent
buffer.line_indentation[line_num] = indent + buffer.indent
buffer:line_up() buffer:line_end()
break
end
end
buffer:end_undo_action()
end
---
-- Determines the Lua file being 'require'd, searches through package.path for
-- that file, and opens it in Textadept.
function goto_required()
local buffer = buffer
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)
local f = io.open(path)
if f then f:close() textadept.io.open(path) break end
end
end
---
-- Executes the current file.
function run()
local buffer = buffer
local cmd = 'lua "'..buffer.filename..'" 2>&1'
local p = io.popen(cmd)
local out = p:read('*all')
p:close()
textadept.print('> '..cmd..'\n'..out)
end
-- Lua-specific key commands.
local keys = _G.keys
if type(keys) == 'table' then
local m_editing = _m.textadept.editing
keys.lua = {
al = { textadept.io.open, _HOME..'/modules/lua/init.lua' },
ac = {
g = { goto_required }
},
['s\n'] = { try_to_autocomplete_end },
cq = { m_editing.block_comment, '--~' },
cg = { run },
['('] = { function()
buffer.word_chars =
'_.:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
m_editing.show_call_tip(_m.lua.api, true)
buffer:set_chars_default()
return false
end },
}
end
|
Fix bug when file is not matched in modules/lua/commands.lua.
|
Fix bug when file is not matched in modules/lua/commands.lua.
|
Lua
|
mit
|
rgieseke/textadept,rgieseke/textadept
|
edae4b2a0f26fbef1d23860e5b06f2bffa17c414
|
src/camerastoryutils/src/Client/CameraStoryUtils.lua
|
src/camerastoryutils/src/Client/CameraStoryUtils.lua
|
---
-- @module CameraStoryUtils
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local RunService = game:GetService("RunService")
local InsertServiceUtils = require("InsertServiceUtils")
local Promise = require("Promise")
local Math = require("Math")
local CameraStoryUtils = {}
function CameraStoryUtils.reflectCamera(maid, topCamera)
local camera = Instance.new("Camera")
camera.Name = "ReflectedCamera"
maid:GiveTask(camera)
local function update()
camera.FieldOfView = topCamera.FieldOfView
camera.CFrame = topCamera.CFrame
end
maid:GiveTask(topCamera:GetPropertyChangedSignal("CFrame"):Connect(update))
maid:GiveTask(topCamera:GetPropertyChangedSignal("FieldOfView"):Connect(update))
update()
return camera
end
function CameraStoryUtils.setupViewportFrame(maid, target)
local viewportFrame = Instance.new("ViewportFrame")
viewportFrame.ZIndex = 0
viewportFrame.BorderSizePixel = 0
viewportFrame.BackgroundColor3 = Color3.new(0.7, 0.7, 0.7)
viewportFrame.Size = UDim2.new(1, 0, 1, 0)
maid:GiveTask(viewportFrame)
local reflectedCamera = CameraStoryUtils.reflectCamera(maid, workspace.CurrentCamera)
reflectedCamera.Parent = viewportFrame
viewportFrame.CurrentCamera = reflectedCamera
viewportFrame.Parent = target
return viewportFrame
end
function CameraStoryUtils.promiseCrate(maid, viewportFrame, properties)
return maid:GivePromise(InsertServiceUtils.promiseAsset(182451181)):Then(function(model)
maid:GiveTask(model)
local crate = model:GetChildren()[1]
if not crate then
return Promise.rejected()
end
if properties then
for _, item in pairs(crate:GetDescendants()) do
if item:IsA("BasePart") then
for property, value in pairs(properties) do
item[property] = value
end
end
end
end
crate.Parent = viewportFrame
return Promise.resolved(crate)
end)
end
function CameraStoryUtils.getInterpolationFactory(maid, viewportFrame, low, high, period, toCFrame)
assert(maid, "Bad maid")
assert(viewportFrame, "Bad viewportFrame")
assert(type(low) == "number", "Bad low")
assert(type(high) == "number", "Bad high")
assert(type(period) == "number", "Bad period")
assert(type(toCFrame) == "function", "Bad toCFrame")
return function(interpolate, color)
assert(type(interpolate) == "function", "Bad interpolate")
assert(typeof(color) == "Color3", "Bad color")
maid:GivePromise(CameraStoryUtils.promiseCrate(maid, viewportFrame, {
Color = color;
Transparency = 0.5
}))
:Then(function(crate)
maid:GiveTask(RunService.RenderStepped:Connect(function()
local t = (os.clock()/period % 2/period)*period
if t >= 1 then
t = 1 - (t % 1)
end
t = Math.map(t, 0, 1, low, high)
t = math.clamp(t, low, high)
local cframe = toCFrame(interpolate(t))
crate:SetPrimaryPartCFrame(cframe)
end))
end)
end
end
return CameraStoryUtils
|
---
-- @module CameraStoryUtils
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local RunService = game:GetService("RunService")
local InsertServiceUtils = require("InsertServiceUtils")
local Promise = require("Promise")
local Math = require("Math")
local CameraStoryUtils = {}
function CameraStoryUtils.reflectCamera(maid, topCamera)
local camera = Instance.new("Camera")
camera.Name = "ReflectedCamera"
maid:GiveTask(camera)
local function update()
camera.FieldOfView = topCamera.FieldOfView
camera.CFrame = topCamera.CFrame
end
maid:GiveTask(topCamera:GetPropertyChangedSignal("CFrame"):Connect(update))
maid:GiveTask(topCamera:GetPropertyChangedSignal("FieldOfView"):Connect(update))
update()
return camera
end
function CameraStoryUtils.setupViewportFrame(maid, target)
local viewportFrame = Instance.new("ViewportFrame")
viewportFrame.ZIndex = 0
viewportFrame.BorderSizePixel = 0
viewportFrame.BackgroundColor3 = Color3.new(0.7, 0.7, 0.7)
viewportFrame.Size = UDim2.new(1, 0, 1, 0)
maid:GiveTask(viewportFrame)
local reflectedCamera = CameraStoryUtils.reflectCamera(maid, workspace.CurrentCamera)
reflectedCamera.Parent = viewportFrame
viewportFrame.CurrentCamera = reflectedCamera
viewportFrame.Parent = target
return viewportFrame
end
function CameraStoryUtils.promiseCrate(maid, viewportFrame, properties)
return maid:GivePromise(InsertServiceUtils.promiseAsset(182451181)):Then(function(model)
maid:GiveTask(model)
local crate = model:GetChildren()[1]
if not crate then
return Promise.rejected()
end
if properties then
for _, item in pairs(crate:GetDescendants()) do
if item:IsA("BasePart") then
for property, value in pairs(properties) do
item[property] = value
end
end
end
end
crate.Parent = viewportFrame
local camera = viewportFrame.CurrentCamera
if camera then
local cameraCFrame = camera.CFrame
local cframe = CFrame.new(cameraCFrame.Position + cameraCFrame.lookVector*25)
crate:SetPrimaryPartCFrame(cframe)
end
return Promise.resolved(crate)
end)
end
function CameraStoryUtils.getInterpolationFactory(maid, viewportFrame, low, high, period, toCFrame)
assert(maid, "Bad maid")
assert(viewportFrame, "Bad viewportFrame")
assert(type(low) == "number", "Bad low")
assert(type(high) == "number", "Bad high")
assert(type(period) == "number", "Bad period")
assert(type(toCFrame) == "function", "Bad toCFrame")
return function(interpolate, color)
assert(type(interpolate) == "function", "Bad interpolate")
assert(typeof(color) == "Color3", "Bad color")
maid:GivePromise(CameraStoryUtils.promiseCrate(maid, viewportFrame, {
Color = color;
Transparency = 0.5
}))
:Then(function(crate)
maid:GiveTask(RunService.RenderStepped:Connect(function()
local t = (os.clock()/period % 2/period)*period
if t >= 1 then
t = 1 - (t % 1)
end
t = Math.map(t, 0, 1, low, high)
t = math.clamp(t, low, high)
local cframe = toCFrame(interpolate(t))
crate:SetPrimaryPartCFrame(cframe)
end))
end)
end
end
return CameraStoryUtils
|
fix: camera story parents relative to the camera
|
fix: camera story parents relative to the camera
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
149ea4cc6270649790392c4eb4c6a143714eb1b9
|
src/premake/SchemaCompiler.lua
|
src/premake/SchemaCompiler.lua
|
local function runexe(name)
if (os.get() == "windows") then
return name
else
return './'..name
end
end
filter "files:**.fbs"
buildmessage "flatc: Compiling %{file.relpath}"
buildcommands
{
runexe('flatc')..' -c -o "../../PGTA/public/schema" %{file.relpath}',
runexe('SchemaCompiler')..' %{file.relpath}'
}
filter { "files:**.fbs", "system:not windows" }
buildoutputs { "%{file.name}.h", "%{file.basename}_generated.h" }
filter {}
project "SchemaCompiler"
kind "ConsoleApp"
run_include("flatc_include.lua", "flatbuffers")
files "../tools/SchemaCompiler/SchemaCompiler.cpp"
postbuildcommands "{TOUCH} dummy.cpp"
project "FlatbufCompiler"
kind "StaticLib"
dependson "SchemaCompiler"
files "../PGTA/**.fbs"
files (_ACTION.."/dummy.cpp")
project "*"
|
local function runexe(name)
if (os.get() == "windows") then
return name
else
return './'..name
end
end
filter "files:**.fbs"
buildmessage "flatc: Compiling %{file.relpath}"
buildcommands
{
runexe('flatc')..' -c -o "../../PGTA/public/schema" %{file.relpath}',
runexe('SchemaCompiler')..' %{file.relpath}'
}
-- TODO: add *_generated.h to buildoutputs when
-- multiple output deps are supported by premake
buildoutputs { "%{file.abspath}.h" }
filter {}
project "SchemaCompiler"
kind "ConsoleApp"
run_include("flatc_include.lua", "flatbuffers")
files "../tools/SchemaCompiler/SchemaCompiler.cpp"
postbuildcommands "{TOUCH} dummy.cpp"
project "FlatbufCompiler"
kind "StaticLib"
dependson "SchemaCompiler"
files "../PGTA/**.fbs"
files (_ACTION.."/dummy.cpp")
project "*"
|
Fixed fbs generated files not being generated from VS build
|
Fixed fbs generated files not being generated from VS build
|
Lua
|
mit
|
PGTA/PGTA,PGTA/PGTA,PGTA/PGTA
|
1d2be59be1b849a4bcbe3b1adf38dbba86acd5e3
|
forward/testing/packet_synthesis.lua
|
forward/testing/packet_synthesis.lua
|
local GRE = require("lib.protocol.gre")
local Datagram = require("lib.protocol.datagram")
local Ethernet = require("lib.protocol.ethernet")
local IPV4 = require("lib.protocol.ipv4")
local TCP = require("lib.protocol.tcp")
local ffi = require("ffi")
local networking_magic_numbers = require("networking_magic_numbers")
local function make_payload(len)
local buf = ffi.new('char[?]', len)
for i=0,len-1 do
buf[i] = i % 256
end
return ffi.string(buf, len)
end
-- Returns an array of payload fragments
local function split_payload(payload, payload_len, fragment_len)
-- add fragment_payload_len-1 to handle case when payload_len is divisible by fragment_payload_len
-- want to compute (payload_len + fragment_len - 1) // fragment_payload_len but lua5.1 has no integer division
local dividend = payload_len + fragment_len - 1
local num_fragments = (dividend - dividend % fragment_len) / fragment_len
local fragments = {n = num_fragments}
for i=1,num_fragments do
local curr_fragment_len = fragment_len
if i == num_fragments then
curr_fragment_len = payload_len - fragment_len * (num_fragments-1)
end
local fragment = string.sub(payload, (i-1) * fragment_len + 1, math.min(i * fragment_len, payload_len))
fragments[i] = fragment
end
return fragments
end
-- Arguments:
-- src_mac, dst_mac (binary) -- source and destination MAC addresses;
-- should be the addresses of the router
-- (or last switch) and spike respectively
-- src_addr, dst_addr (binary) -- source and destination IP addresses;
-- should be the addresses of the router
-- and spike respectively
-- payload (binary) -- packet payload, defaults to 100 bytes of
-- generated rubbish
-- payload_length (int, default 100) -- length of payload
-- ip_flags (int, default 0) -- flags field for IP header
-- frag_off (int, default 0) -- fragment offset field
-- ttl (int, default 30) -- TTL field
-- skip_tcp_header (bool, default nil) -- don't include a tcp header
-- add_ip_gre_layer (bool, default nil) -- add a IP-GRE layer to test
-- secondary fragmentation processing
function make_ipv4_packet(config)
local payload_length = config.payload_length or 100
local payload = config.payload or
make_payload(payload_length)
local datagram = Datagram:new(nil, nil, {delayed_commit = true})
datagram:payload(payload, payload_length)
local tcp_header_size = 0
if not config.skip_tcp_header then
local tcp_header = TCP:new({
})
tcp_header_size = tcp_header:sizeof()
-- TCP data offset field is in units of 32-bit words
tcp_header:offset(tcp_header_size / 4)
tcp_header:checksum()
datagram:push(tcp_header)
end
local ttl = config.ttl or 30
local ip_header = IPV4:new({
src = config.src_addr,
dst = config.dst_addr,
protocol = L4_TCP,
flags = config.ip_flags or 0,
frag_off = config.frag_off or 0,
ttl = ttl
})
ip_header:total_length(ip_header:sizeof() + tcp_header_size + payload_length)
ip_header:checksum()
datagram:push(ip_header)
if config.add_ip_gre_layer then
local gre_header = GRE:new({ protocol = L3_IPV4 })
datagram:push(gre_header)
local outer_ip_header = IPV4:new({
src = config.src_addr, -- Should be another spike's address (which should be equal to the inner IP header's dst address), just reusing router's address for now since it doesn't impact testing.
dst = config.dst_addr,
protocol = L4_GRE,
ttl = ttl
})
outer_ip_header:total_length(outer_ip_header:sizeof() + gre_header:sizeof() + ip_header:total_length())
outer_ip_header:checksum()
datagram:push(outer_ip_header)
end
local eth_header = Ethernet:new({
src = config.src_mac,
dst = config.dst_mac,
type = L3_IPV4
})
datagram:push(eth_header)
datagram:commit()
return datagram:packet()
end
-- Arguments:
-- src_mac, dst_mac (binary) -- source and destination MAC addresses;
-- should be the addresses of the router
-- (or last switch) and spike respectively
-- src_addr, dst_addr (binary) -- source and destination IP addresses;
-- should be the addresses of the router
-- and spike respectively
-- payload (binary) -- packet payload, defaults to 500 bytes of
-- generated rubbish
-- payload_length (int, default 500) -- length of payload
-- mtu (int, default 100) -- MTU of network where packets are fragmented
-- add_ip_gre_layer (bool, default nil) -- add a IP-GRE layer to test
-- secondary fragmentation processing
function make_fragmented_ipv4_packets(config)
local payload_length = config.payload_length or 500
local payload = config.payload or
make_payload(payload_length)
local datagram = Datagram:new(nil, nil, {delayed_commit = true})
datagram:payload(payload, payload_length)
local tcp_header = TCP:new({
})
local tcp_header_size = tcp_header:sizeof()
-- TCP data offset field is in units of 32-bit words
tcp_header:offset(tcp_header_size / 4)
tcp_header:checksum()
datagram:push(tcp_header)
local ip_payload_length = payload_length + tcp_header_size
datagram:commit()
local ip_payload = ffi.string(datagram:packet().data, ip_payload_length)
local fragment_len = (config.mtu or 100) - IP_HEADER_LENGTH
-- fragment length must be a multiple of 8
fragment_len = fragment_len - fragment_len % 8
local fragments = split_payload(ip_payload, ip_payload_length, fragment_len)
local num_fragments = fragments.n
local packets = {n = num_fragments}
for i=1,num_fragments do
local ip_flags = 0
if i ~= num_fragments then
ip_flags = IP_MF_FLAG
end
packets[i] = make_ipv4_packet({
payload = fragments[i],
payload_length = fragment_len,
skip_tcp_header = true,
src_mac = config.src_mac,
dst_mac = config.dst_mac,
src_addr = config.src_addr,
dst_addr = config.dst_addr,
ip_flags = ip_flags,
-- fragment offset field is in multiples of 8
frag_off = (i-1) * fragment_len / 8,
add_ip_gre_layer = config.add_ip_gre_layer
})
end
return packets
end
|
local GRE = require("lib.protocol.gre")
local Datagram = require("lib.protocol.datagram")
local Ethernet = require("lib.protocol.ethernet")
local IPV4 = require("lib.protocol.ipv4")
local TCP = require("lib.protocol.tcp")
local ffi = require("ffi")
local networking_magic_numbers = require("networking_magic_numbers")
local function make_payload(len)
local buf = ffi.new('char[?]', len)
for i=0,len-1 do
buf[i] = (i + 128) % 256
end
return ffi.string(buf, len)
end
-- Returns an array of payload fragments.
local function split_payload(payload, payload_len, fragment_len)
-- add fragment_payload_len-1 to handle case when payload_len is divisible by fragment_payload_len
-- want to compute (payload_len + fragment_len - 1) // fragment_payload_len but lua5.1 has no integer division
local dividend = payload_len + fragment_len - 1
local num_fragments = (dividend - dividend % fragment_len) / fragment_len
local fragments = {n = num_fragments}
for i=1,num_fragments do
local curr_fragment_len = fragment_len
if i == num_fragments then
curr_fragment_len = payload_len - fragment_len * (num_fragments-1)
end
local fragment = string.sub(payload, (i-1) * fragment_len + 1, math.min(i * fragment_len, payload_len))
fragments[i] = fragment
end
return fragments
end
-- Arguments:
-- src_mac, dst_mac (binary) -- source and destination MAC addresses;
-- should be the addresses of the router
-- (or last switch) and spike respectively
-- src_addr, dst_addr (binary) -- source and destination IP addresses;
-- should be the addresses of the router
-- and spike respectively
-- payload (binary) -- packet payload, defaults to 100 bytes of
-- generated rubbish
-- payload_length (int, default 100) -- length of payload
-- ip_flags (int, default 0) -- flags field for IP header
-- frag_off (int, default 0) -- fragment offset field
-- ttl (int, default 30) -- TTL field
-- skip_tcp_header (bool, default nil) -- don't include a tcp header
-- add_ip_gre_layer (bool, default nil) -- add a IP-GRE layer to test
-- secondary fragmentation processing
function make_ipv4_packet(config)
local payload_length = config.payload_length or 100
local payload = config.payload or
make_payload(payload_length)
local datagram = Datagram:new(nil, nil, {delayed_commit = true})
datagram:payload(payload, payload_length)
local tcp_header_size = 0
if not config.skip_tcp_header then
local tcp_header = TCP:new({
})
tcp_header_size = tcp_header:sizeof()
-- TCP data offset field is in units of 32-bit words
tcp_header:offset(tcp_header_size / 4)
tcp_header:checksum()
datagram:push(tcp_header)
end
local ttl = config.ttl or 30
local ip_header = IPV4:new({
src = config.src_addr,
dst = config.dst_addr,
protocol = L4_TCP,
flags = config.ip_flags or 0,
frag_off = config.frag_off or 0,
ttl = ttl
})
ip_header:total_length(ip_header:sizeof() + tcp_header_size + payload_length)
ip_header:checksum()
datagram:push(ip_header)
if config.add_ip_gre_layer then
local gre_header = GRE:new({ protocol = L3_IPV4 })
datagram:push(gre_header)
local outer_ip_header = IPV4:new({
src = config.src_addr, -- Should be another spike's address (which should be equal to the inner IP header's dst address), just reusing router's address for now since it doesn't impact testing.
dst = config.dst_addr,
protocol = L4_GRE,
ttl = ttl
})
outer_ip_header:total_length(outer_ip_header:sizeof() + gre_header:sizeof() + ip_header:total_length())
outer_ip_header:checksum()
datagram:push(outer_ip_header)
end
local eth_header = Ethernet:new({
src = config.src_mac,
dst = config.dst_mac,
type = L3_IPV4
})
datagram:push(eth_header)
datagram:commit()
return datagram:packet()
end
-- Arguments:
-- src_mac, dst_mac (binary) -- source and destination MAC addresses;
-- should be the addresses of the router
-- (or last switch) and spike respectively
-- src_addr, dst_addr (binary) -- source and destination IP addresses;
-- should be the addresses of the router
-- and spike respectively
-- payload (binary) -- packet payload, defaults to 500 bytes of
-- generated rubbish
-- payload_length (int, default 500) -- length of payload
-- mtu (int, default 100) -- MTU of network where packets are fragmented
-- add_ip_gre_layer (bool, default nil) -- add a IP-GRE layer to test
-- secondary fragmentation processing
function make_fragmented_ipv4_packets(config)
local payload_length = config.payload_length or 500
local payload = config.payload or
make_payload(payload_length)
local datagram = Datagram:new(nil, nil, {delayed_commit = true})
datagram:payload(payload, payload_length)
local tcp_header = TCP:new({
})
local tcp_header_size = tcp_header:sizeof()
-- TCP data offset field is in units of 32-bit words
tcp_header:offset(tcp_header_size / 4)
tcp_header:checksum()
datagram:push(tcp_header)
local ip_payload_length = payload_length + tcp_header_size
datagram:commit()
local ip_payload = ffi.string(datagram:packet().data, ip_payload_length)
local fragment_len = (config.mtu or 100) - IP_HEADER_LENGTH
-- fragment length must be a multiple of 8
fragment_len = fragment_len - fragment_len % 8
local fragments = split_payload(ip_payload, ip_payload_length, fragment_len)
local num_fragments = fragments.n
local packets = {n = num_fragments}
for i=1,num_fragments do
local ip_flags = 0
if i ~= num_fragments then
ip_flags = IP_MF_FLAG
end
packets[i] = make_ipv4_packet({
payload = fragments[i],
payload_length = string.len(fragments[i]),
skip_tcp_header = true,
src_mac = config.src_mac,
dst_mac = config.dst_mac,
src_addr = config.src_addr,
dst_addr = config.dst_addr,
ip_flags = ip_flags,
-- fragment offset field is units of 8-byte blocks
frag_off = (i-1) * fragment_len / 8,
add_ip_gre_layer = config.add_ip_gre_layer
})
end
return packets
end
|
fix wrong fragment length passed to make_ipv4_packet in fragmented packet synthesis
|
fix wrong fragment length passed to make_ipv4_packet in fragmented packet synthesis
|
Lua
|
mit
|
krawthekrow/spike,krawthekrow/spike
|
664ea594080f717edcd4a1c90216912af3e2965d
|
packages/lime-proto-olsr2/src/olsr2.lua
|
packages/lime-proto-olsr2/src/olsr2.lua
|
#!/usr/bin/lua
local network = require("lime.network")
local config = require("lime.config")
local fs = require("nixio.fs")
local libuci = require("uci")
local wireless = require("lime.wireless")
local utils = require("lime.utils")
local ip = require("luci.ip")
olsr2 = {}
olsr2.configured = false
function olsr2.configure(args)
if olsr2.configured then return end
olsr2.configured = true
local uci = libuci:cursor()
local ipv4, ipv6 = network.primary_address()
local origInterfaceName = network.limeIfNamePrefix.."olsr_originator_lo"
fs.writefile("/etc/config/olsrd2", "")
uci:set("olsrd2", "lime", "global")
uci:set("olsrd2", "lime", "failfast", "no")
uci:set("olsrd2", "lime", "pidfile", "/var/run/olsrd2.pid")
uci:set("olsrd2", "lime", "lockfile", "/var/lock/olsrd2")
uci:set("olsrd2", "limelog", "log")
uci:set("olsrd2", "limejson", "syslog", "true")
uci:set("olsrd2", "limejson", "info", "all")
uci:set("olsrd2", "limetelnet", "telnet")
uci:set("olsrd2", "limetelnet", "port", "2009")
uci:set("olsrd2", owrtInterfaceName, "interface")
uci:set("olsrd2", owrtInterfaceName, "ifname", "loopback")
uci:save("olsrd2")
uci set("network" origInterfaceName, "interface")
uci set("network" origInterfaceName, "ifname", "@loopback")
uci set("network" origInterfaceName, "proto", "static")
uci set("network" origInterfaceName, "ipaddr", ipv4:host():string())
uci set("network" origInterfaceName, "netmask", "255.255.255.255")
uci set("network" origInterfaceName, "ip6addr", ipv6:host():string().."/128")
uci:save("network")
end
function olsr2.setup_interface(ifname, args)
if not args["specific"] then
if ifname:match("^wlan%d+.ap") then return end
end
local vlanId = args[2] or 16
local vlanProto = args[3] or "8021ad"
local nameSuffix = args[4] or "_olsr"
local owrtInterfaceName, linux802adIfName, owrtDeviceName = network.createVlanIface(ifname, vlanId, nameSuffix, vlanProto)
local uci = libuci:cursor()
uci:set("olsrd2", owrtInterfaceName, "interface")
uci:set("olsrd2", owrtInterfaceName, "interface", owrtInterfaceName)
uci:save("olsrd2")
end
return olsr2
|
#!/usr/bin/lua
local network = require("lime.network")
local config = require("lime.config")
local fs = require("nixio.fs")
local libuci = require("uci")
local wireless = require("lime.wireless")
local utils = require("lime.utils")
local ip = require("luci.ip")
olsr2 = {}
olsr2.configured = false
function olsr2.configure(args)
if olsr2.configured then return end
olsr2.configured = true
local uci = libuci:cursor()
local ipv4, ipv6 = network.primary_address()
local origInterfaceName = network.limeIfNamePrefix.."olsr_originator_lo"
fs.writefile("/etc/config/olsrd2", "")
uci:set("olsrd2", "lime", "global")
uci:set("olsrd2", "lime", "failfast", "no")
uci:set("olsrd2", "lime", "pidfile", "/var/run/olsrd2.pid")
uci:set("olsrd2", "lime", "lockfile", "/var/lock/olsrd2")
uci:set("olsrd2", "lime", "olsrv2")
uci:set("olsrd2", "lime", "lan", {ipv4:string(), ipv6:string()})
uci:set("olsrd2", "limelog", "log")
uci:set("olsrd2", "limejson", "syslog", "true")
uci:set("olsrd2", "limejson", "info", "all")
uci:set("olsrd2", "limetelnet", "telnet")
uci:set("olsrd2", "limetelnet", "port", "2009")
uci:set("olsrd2", origInterfaceName, "interface")
uci:set("olsrd2", origInterfaceName, "ifname", "loopback")
uci:save("olsrd2")
uci:set("network", origInterfaceName, "interface")
uci:set("network", origInterfaceName, "ifname", "@loopback")
uci:set("network", origInterfaceName, "proto", "static")
uci:set("network", origInterfaceName, "ipaddr", ipv4:host():string())
uci:set("network", origInterfaceName, "netmask", "255.255.255.255")
uci:set("network", origInterfaceName, "ip6addr", ipv6:host():string().."/128")
uci:save("network")
end
function olsr2.setup_interface(ifname, args)
if not args["specific"] then
if ifname:match("^wlan%d+.ap") then return end
end
local vlanId = args[2] or 16
local vlanProto = args[3] or "8021ad"
local nameSuffix = args[4] or "_olsr"
local owrtInterfaceName, linux802adIfName, owrtDeviceName = network.createVlanIface(ifname, vlanId, nameSuffix, vlanProto)
local uci = libuci:cursor()
uci:set("olsrd2", owrtInterfaceName, "interface")
uci:set("olsrd2", owrtInterfaceName, "ifname", owrtInterfaceName)
uci:save("olsrd2")
end
return olsr2
|
Finished fixing and testing olsrd2 plugin.
|
Finished fixing and testing olsrd2 plugin.
|
Lua
|
agpl-3.0
|
p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages
|
96300693140e1af90a953b74cf8d1341537f2bac
|
libs/http/luasrc/http/protocol/conditionals.lua
|
libs/http/luasrc/http/protocol/conditionals.lua
|
--[[
HTTP protocol implementation for LuCI - RFC2616 / 14.19, 14.24 - 14.28
(c) 2008 Freifunk Leipzig / 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$
]]--
--- LuCI http protocol implementation - HTTP/1.1 bits.
-- This class provides basic ETag handling and implements most of the
-- conditional HTTP/1.1 headers specified in RFC2616 Sct. 14.24 - 14.28 .
module("luci.http.protocol.conditionals", package.seeall)
local date = require("luci.http.protocol.date")
--- Implement 14.19 / ETag.
-- @param stat A file.stat structure
-- @return String containing the generated tag suitable for ETag headers
function mk_etag( stat )
if stat ~= nil then
return string.format( '"%x-%x-%x"', stat.ino, stat.size, stat.mtime )
end
end
--- 14.24 / If-Match
-- Test whether the given message object contains an "If-Match" header and
-- compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
function if_match( req, stat )
local h = req.headers
local etag = mk_etag( stat )
-- Check for matching resource
if type(h['If-Match']) == "string" then
for ent in h['If-Match']:gmatch("([^, ]+)") do
if ( ent == '*' or ent == etag ) and stat ~= nil then
return true
end
end
return false, 412
end
return true
end
--- 14.25 / If-Modified-Since
-- Test whether the given message object contains an "If-Modified-Since" header
-- and compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
-- @return Table containing extra HTTP headers if the precondition failed
function if_modified_since( req, stat )
local h = req.headers
-- Compare mtimes
if type(h['If-Modified-Since']) == "string" then
local since = date.to_unix( h['If-Modified-Since'] )
if stat == nil or since < stat.mtime then
return true
end
return false, 304, {
["ETag"] = mk_etag( stat );
["Date"] = date.to_http( os.time() );
["Last-Modified"] = date.to_http( stat.mtime )
}
end
return true
end
--- 14.26 / If-None-Match
-- Test whether the given message object contains an "If-None-Match" header and
-- compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
-- @return Table containing extra HTTP headers if the precondition failed
function if_none_match( req, stat )
local h = req.headers
local etag = mk_etag( stat )
-- Check for matching resource
if type(h['If-None-Match']) == "string" then
for ent in h['If-None-Match']:gmatch("([^, ]+)") do
if ( ent == '*' or ent == etag ) and stat ~= nil then
if req.request_method == "get" or
req.request_method == "head"
then
return false, 304, {
["ETag"] = mk_etag( stat );
["Date"] = date.to_http( os.time() );
["Last-Modified"] = date.to_http( stat.mtime )
}
else
return false, 412
end
end
end
end
return true
end
--- 14.27 / If-Range
-- The If-Range header is currently not implemented due to the lack of general
-- byte range stuff in luci.http.protocol . This function will always return
-- false, 412 to indicate a failed precondition.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
function if_range( req, stat )
-- Sorry, no subranges (yet)
return false, 412
end
--- 14.28 / If-Unmodified-Since
-- Test whether the given message object contains an "If-Unmodified-Since"
-- header and compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
function if_unmodified_since( req, stat )
local h = req.headers
-- Compare mtimes
if type(h['If-Unmodified-Since']) == "string" then
local since = date.to_unix( h['If-Unmodified-Since'] )
if stat ~= nil and since <= stat.mtime then
return false, 412
end
end
return true
end
|
--[[
HTTP protocol implementation for LuCI - RFC2616 / 14.19, 14.24 - 14.28
(c) 2008 Freifunk Leipzig / 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$
]]--
--- LuCI http protocol implementation - HTTP/1.1 bits.
-- This class provides basic ETag handling and implements most of the
-- conditional HTTP/1.1 headers specified in RFC2616 Sct. 14.24 - 14.28 .
module("luci.http.protocol.conditionals", package.seeall)
local date = require("luci.http.protocol.date")
--- Implement 14.19 / ETag.
-- @param stat A file.stat structure
-- @return String containing the generated tag suitable for ETag headers
function mk_etag( stat )
if stat ~= nil then
return string.format( '"%x-%x-%x"', stat.ino, stat.size, stat.mtime )
end
end
--- 14.24 / If-Match
-- Test whether the given message object contains an "If-Match" header and
-- compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
function if_match( req, stat )
local h = req.headers
local etag = mk_etag( stat )
-- Check for matching resource
if type(h['If-Match']) == "string" then
for ent in h['If-Match']:gmatch("([^, ]+)") do
if ( ent == '*' or ent == etag ) and stat ~= nil then
return true
end
end
return false, 412
end
return true
end
--- 14.25 / If-Modified-Since
-- Test whether the given message object contains an "If-Modified-Since" header
-- and compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
-- @return Table containing extra HTTP headers if the precondition failed
function if_modified_since( req, stat )
local h = req.headers
-- Compare mtimes
if type(h['If-Modified-Since']) == "string" then
local since = date.to_unix( h['If-Modified-Since'] )
if stat == nil or since < stat.mtime then
return true
end
return false, 304, {
["ETag"] = mk_etag( stat );
["Date"] = date.to_http( os.time() );
["Last-Modified"] = date.to_http( stat.mtime )
}
end
return true
end
--- 14.26 / If-None-Match
-- Test whether the given message object contains an "If-None-Match" header and
-- compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
-- @return Table containing extra HTTP headers if the precondition failed
function if_none_match( req, stat )
local h = req.headers
local etag = mk_etag( stat )
local method = req.env and req.env.REQUEST_METHOD or "GET"
-- Check for matching resource
if type(h['If-None-Match']) == "string" then
for ent in h['If-None-Match']:gmatch("([^, ]+)") do
if ( ent == '*' or ent == etag ) and stat ~= nil then
if method == "GET" or method == "HEAD" then
return false, 304, {
["ETag"] = mk_etag( stat );
["Date"] = date.to_http( os.time() );
["Last-Modified"] = date.to_http( stat.mtime )
}
else
return false, 412
end
end
end
end
return true
end
--- 14.27 / If-Range
-- The If-Range header is currently not implemented due to the lack of general
-- byte range stuff in luci.http.protocol . This function will always return
-- false, 412 to indicate a failed precondition.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
function if_range( req, stat )
-- Sorry, no subranges (yet)
return false, 412
end
--- 14.28 / If-Unmodified-Since
-- Test whether the given message object contains an "If-Unmodified-Since"
-- header and compare it against the given stat object.
-- @param req HTTP request message object
-- @param stat A file.stat object
-- @return Boolean indicating wheather the precondition is ok
-- @return Alternative status code if the precondition failed
function if_unmodified_since( req, stat )
local h = req.headers
-- Compare mtimes
if type(h['If-Unmodified-Since']) == "string" then
local since = date.to_unix( h['If-Unmodified-Since'] )
if stat ~= nil and since <= stat.mtime then
return false, 412
end
end
return true
end
|
libs/http: fix incorrent treatment of If-None-Match (#100)
|
libs/http: fix incorrent treatment of If-None-Match (#100)
|
Lua
|
apache-2.0
|
8devices/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.