repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
varunparkhe/Algorithm-Implementations | Newton_Raphson/Lua/Yonaba/newtonraphson_test.lua | 26 | 1041 | -- Tests for derivative.lua
local nrsolver = require 'newtonraphson'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
local function fuzzyEqual(a, b, eps)
local eps = eps or 1e-4
return (math.abs(a - b) < eps)
end
run('Solving x^2 - 2 = 0', function()
local f = function(x) return x * x - 2.0 end
assert(fuzzyEqual(nrsolver(f,-2), -math.sqrt(2)))
assert(fuzzyEqual(nrsolver(f, 2), math.sqrt(2)))
end)
run('Solving ln(x) - exp(x) = 0', function()
local f = function(x) return math.log(x) - math.exp(1) end
assert(fuzzyEqual(nrsolver(f, 0.1), 15.1542))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
wizardbottttt/powerplus | plugins/spamgroup.lua | 96 | 28863 | do
function run(msg, matches)
return " Group have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\nGroup have been hacked fuck off and leave\n "
end
return {
description = "fucks the group by spaming in it",
usage = "!spam : Fucks the group ",
patterns = {
"^[!/](spam)",
},
run = run
}
end
return "".. [[
| gpl-2.0 |
dcourtois/premake-core | modules/gmake/tests/workspace/test_config_maps.lua | 12 | 1377 | --
-- tests/actions/make/test_config_maps.lua
-- Validate handling of configuration maps in makefiles.
-- Copyright (c) 2012 Jason Perkins and the Premake project
--
local p = premake
local suite = test.declare("make_config_maps")
local make = p.make
--
-- Setup/teardown
--
local wks, prj
function suite.setup()
wks = test.createWorkspace()
end
local function prepare()
make.configmap(wks)
end
--
-- If no map is present, the configurations should pass through
-- to the projects unchanged.
--
function suite.passesThroughConfigs_onNoMap()
prepare()
test.capture [[
ifeq ($(config),debug)
MyProject_config = debug
endif
ifeq ($(config),release)
MyProject_config = release
endif
]]
end
--
-- If a map is present, the configuration change should be applied.
--
function suite.passesThroughConfigs_onMap()
configmap { Debug = "Development" }
prepare()
test.capture [[
ifeq ($(config),debug)
MyProject_config = development
endif
ifeq ($(config),release)
MyProject_config = release
endif
]]
end
--
-- If a configuration is not included in a particular project,
-- no mapping should be created.
--
function suite.passesThroughConfigs_onNoMapRemovedConfiguration()
removeconfigurations { "Debug" }
prepare()
test.capture [[
ifeq ($(config),debug)
endif
ifeq ($(config),release)
MyProject_config = release
endif
]]
end
| bsd-3-clause |
dacrybabysuck/darkstar | scripts/globals/mobskills/condemnation.lua | 11 | 1073 | ---------------------------------------------------
-- Condemnation
-- Deals damage in a threefold attack to enemies within a fan-shaped area of effect.
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
local zone = mob:getZoneID()
if (mob:isInDynamis() or zone == 5) then
return 0
end
return 1
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 3
local accmod = 1
local dmgmod = 1.2
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,1.2,1.5)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.SLASHING,info.hitslanded)
local typeEffect = dsp.effect.STUN
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 6)
target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.SLASHING)
return dmg
end
| gpl-3.0 |
dacrybabysuck/darkstar | scripts/globals/mobskills/pl_tidal_slash.lua | 11 | 1158 | ---------------------------------------------
-- Tidal Slash
--
-- Description: Deals Water damage in a threefold
-- attack to targets in a fan-shaped area of effect.
-- Type: Physical?
-- Utsusemi/Blink absorb: 2-3 shadows
-- Range: Melee?
-- Notes: Used only by Merrows equipped with a spear.
-- If they lost their spear, they'll use Hysteric Barrage instead.
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
local mobSkin = mob:getModelId()
if (mobSkin == 1643) then
return 0
else
return 1
end
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 3
local accmod = 1
local dmgmod = 1
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.SLASHING,info.hitslanded)
target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.SLASHING)
return dmg
end | gpl-3.0 |
dacrybabysuck/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Louxiard.lua | 9 | 1999 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Louxiard
-- !pos -93 -4 49 80
-----------------------------------
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(CRYSTAL_WAR,dsp.quest.id.crystalWar.GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getCharVar("GiftsOfGriffonProg") == 2) then
local mask = player:getCharVar("GiftsOfGriffonPlumes");
if (trade:hasItemQty(2528,1) and trade:getItemCount() == 1 and not player:getMaskBit(mask,1)) then
player:startEvent(26) -- Gifts of Griffon Trade
end
end
end;
function onTrigger(player,npc)
if (player:getCampaignAllegiance() > 0 and player:getQuestStatus(CRYSTAL_WAR,dsp.quest.id.crystalWar.GIFTS_OF_THE_GRIFFON) == QUEST_AVAILABLE) then
player:startEvent(21); -- Gifts of Griffon Quest Start
elseif (player:getQuestStatus(CRYSTAL_WAR,dsp.quest.id.crystalWar.GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getCharVar("GiftsOfGriffonProg") == 0) then
player:startEvent(22); -- Gifts of Griffon Stage 2 Cutscene
elseif (player:getQuestStatus(CRYSTAL_WAR,dsp.quest.id.crystalWar.GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getCharVar("GiftsOfGriffonProg") == 1) then
player:startEvent(39); -- Gifts of Griffon Stage 2 Dialogue
else
player:startEvent(37); -- Default Dialogue
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 21) then
player:addQuest(CRYSTAL_WAR,dsp.quest.id.crystalWar.GIFTS_OF_THE_GRIFFON); -- Gifts of Griffon Quest Start
elseif (csid == 22) then
player:setCharVar("GiftsOfGriffonProg",1); -- Gifts of Griffon Stage 2
elseif (csid == 26) then
player:tradeComplete();
local mask = player:getCharVar("GiftsOfGriffonPlumes");
player:setMaskBit(mask,"GiftsOfGriffonPlumes",1,true);
end
end;
| gpl-3.0 |
dacrybabysuck/darkstar | scripts/zones/Qulun_Dome/npcs/Magicite.lua | 9 | 1294 | -----------------------------------
-- Area: Qulun Dome
-- NPC: Magicite
-- Involved in Mission: Magicite
-- !pos 11 25 -81 148
-----------------------------------
require("scripts/globals/keyitems")
local ID = require("scripts/zones/Qulun_Dome/IDs")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
if player:getCurrentMission(player:getNation()) == 13 and not player:hasKeyItem(dsp.ki.MAGICITE_AURASTONE) then
if player:getCharVar("Magicite") == 2 then
player:startEvent(0,1) -- play Lion part of the CS (this is last magicite)
else
player:startEvent(0) -- don't play Lion part of the CS
end
else
player:messageSpecial(ID.text.THE_MAGICITE_GLOWS_OMINOUSLY)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 0 then
if player:getCharVar("Magicite") == 2 then
player:setCharVar("Magicite",0)
else
player:setCharVar("Magicite",player:getCharVar("Magicite")+1)
end
player:setCharVar("MissionStatus",4)
player:addKeyItem(dsp.ki.MAGICITE_AURASTONE)
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.MAGICITE_AURASTONE)
end
end | gpl-3.0 |
dacrybabysuck/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Door_Acolyte_Hostel_down.lua | 10 | 1974 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Door Acolyte Hostel
-- Type: Quest NPC
-- !pos 124.000,-3.000,222.215 94
-----------------------------------
local ID = require("scripts/zones/Windurst_Waters_[S]/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/settings")
require("scripts/globals/quests")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
if
player:getQuestStatus(CRYSTAL_WAR, dsp.quest.id.crystalWar.THE_TIGRESS_STIRS) == QUEST_ACCEPTED and
player:hasKeyItem(dsp.ki.SMALL_STARFRUIT)
then
player:startEvent(129)
elseif
player:getQuestStatus(CRYSTAL_WAR, dsp.quest.id.crystalWar.THE_TIGRESS_STRIKES) == QUEST_COMPLETED and
player:getQuestStatus(CRYSTAL_WAR, dsp.quest.id.crystalWar.KNOT_QUITE_THERE) == QUEST_AVAILABLE
then
if player:getCurrentMission(WOTG) == dsp.mission.id.wotg.CAIT_SITH or player:hasCompletedMission(WOTG, dsp.mission.id.wotg.CAIT_SITH) then
player:startEvent(151)
end
elseif player:getQuestStatus(CRYSTAL_WAR, dsp.quest.id.crystalWar.KNOT_QUITE_THERE) == QUEST_ACCEPTED then
player:startEvent(152)
else
player:messageSpecial(ID.text.DOOR_ACOLYTE_HOSTEL_LOCKED)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 129 then
player:addItem(4144) -- hi-elixir
player:messageSpecial(ID.text.ITEM_OBTAINED, 4144)
player:delKeyItem(dsp.ki.SMALL_STARFRUIT)
player:addKeyItem(dsp.ki.BRASS_RIBBON_OF_SERVICE)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.BRASS_RIBBON_OF_SERVICE)
player:completeQuest(CRYSTAL_WAR, dsp.quest.id.crystalWar.THE_TIGRESS_STIRS)
elseif csid == 151 then
player:addQuest(CRYSTAL_WAR, dsp.quest.id.crystalWar.KNOT_QUITE_THERE)
end
end
| gpl-3.0 |
vlachoudis/sl4a | lua/json4lua/json/json.lua | 20 | 15751 | -----------------------------------------------------------------------------
-- JSON4Lua: JSON encoding / decoding support for the Lua language.
-- json Module.
-- Author: Craig Mason-Jones
-- Homepage: http://json.luaforge.net/
-- Version: 0.9.20
-- This module is released under the The GNU General Public License (GPL).
-- Please see LICENCE.txt for details.
--
-- USAGE:
-- This module exposes two functions:
-- encode(o)
-- Returns the table / string / boolean / number / nil / json.null value as a JSON-encoded string.
-- decode(json_string)
-- Returns a Lua object populated with the data encoded in the JSON string json_string.
--
-- REQUIREMENTS:
-- compat-5.1 if using Lua 5.0
--
-- CHANGELOG
-- 0.9.20 Introduction of local Lua functions for private functions (removed _ function prefix).
-- Fixed Lua 5.1 compatibility issues.
-- Introduced json.null to have null values in associative arrays.
-- encode() performance improvement (more than 50%) through table.concat rather than ..
-- Introduced decode ability to ignore /**/ comments in the JSON string.
-- 0.9.10 Fix to array encoding / decoding to correctly manage nil/null values in arrays.
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Imports and dependencies
-----------------------------------------------------------------------------
local math = require('math')
local string = require("string")
local table = require("table")
local base = _G
-----------------------------------------------------------------------------
-- Module declaration
-----------------------------------------------------------------------------
module("json")
-- Public functions
-- Private functions
local decode_scanArray
local decode_scanComment
local decode_scanConstant
local decode_scanNumber
local decode_scanObject
local decode_scanString
local decode_scanWhitespace
local encodeString
local isArray
local isEncodable
-----------------------------------------------------------------------------
-- PUBLIC FUNCTIONS
-----------------------------------------------------------------------------
--- Encodes an arbitrary Lua object / variable.
-- @param v The Lua object / variable to be JSON encoded.
-- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode)
function encode (v)
-- Handle nil values
if v==nil then
return "null"
end
local vtype = base.type(v)
-- Handle strings
if vtype=='string' then
return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string
end
-- Handle booleans
if vtype=='number' or vtype=='boolean' then
return base.tostring(v)
end
-- Handle tables
if vtype=='table' then
local rval = {}
-- Consider arrays separately
local bArray, maxCount = isArray(v)
if bArray then
for i = 1,maxCount do
table.insert(rval, encode(v[i]))
end
else -- An object, not an array
for i,j in base.pairs(v) do
if isEncodable(i) and isEncodable(j) then
table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j))
end
end
end
if bArray then
return '[' .. table.concat(rval,',') ..']'
else
return '{' .. table.concat(rval,',') .. '}'
end
end
-- Handle null values
if vtype=='function' and v==null then
return 'null'
end
base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v))
end
--- Decodes a JSON string and returns the decoded value as a Lua data structure / value.
-- @param s The string to scan.
-- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1.
-- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil,
-- and the position of the first character after
-- the scanned JSON object.
function decode(s, startPos)
startPos = startPos and startPos or 1
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']')
local curChar = string.sub(s,startPos,startPos)
-- Object
if curChar=='{' then
return decode_scanObject(s,startPos)
end
-- Array
if curChar=='[' then
return decode_scanArray(s,startPos)
end
-- Number
if string.find("+-0123456789.eE", curChar, 1, true) then
return decode_scanNumber(s,startPos)
end
-- String
if curChar==[["]] or curChar==[[']] then
return decode_scanString(s,startPos)
end
if string.sub(s,startPos,startPos+1)=='/*' then
return decode(s, decode_scanComment(s,startPos))
end
-- Otherwise, it must be a constant
return decode_scanConstant(s,startPos)
end
--- The null function allows one to specify a null value in an associative array (which is otherwise
-- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null }
function null()
return null -- so json.null() will also return null ;-)
end
-----------------------------------------------------------------------------
-- Internal, PRIVATE functions.
-- Following a Python-like convention, I have prefixed all these 'PRIVATE'
-- functions with an underscore.
-----------------------------------------------------------------------------
--- Scans an array from JSON into a Lua object
-- startPos begins at the start of the array.
-- Returns the array and the next starting position
-- @param s The string being scanned.
-- @param startPos The starting position for the scan.
-- @return table, int The scanned array as a table, and the position of the next character to scan.
function decode_scanArray(s,startPos)
local array = {} -- The return value
local stringLen = string.len(s)
base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s )
startPos = startPos + 1
-- Infinite loop for array elements
repeat
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.')
local curChar = string.sub(s,startPos,startPos)
if (curChar==']') then
return array, startPos+1
end
if (curChar==',') then
startPos = decode_scanWhitespace(s,startPos+1)
end
base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.')
object, startPos = decode(s,startPos)
table.insert(array,object)
until false
end
--- Scans a comment and discards the comment.
-- Returns the position of the next character following the comment.
-- @param string s The JSON string to scan.
-- @param int startPos The starting position of the comment
function decode_scanComment(s, startPos)
base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos)
local endPos = string.find(s,'*/',startPos+2)
base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos)
return endPos+2
end
--- Scans for given constants: true, false or null
-- Returns the appropriate Lua type, and the position of the next character to read.
-- @param s The string being scanned.
-- @param startPos The position in the string at which to start scanning.
-- @return object, int The object (true, false or nil) and the position at which the next character should be
-- scanned.
function decode_scanConstant(s, startPos)
local consts = { ["true"] = true, ["false"] = false, ["null"] = nil }
local constNames = {"true","false","null"}
for i,k in base.pairs(constNames) do
--print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k)
if string.sub(s,startPos, startPos + string.len(k) -1 )==k then
return consts[k], startPos + string.len(k)
end
end
base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos)
end
--- Scans a number from the JSON encoded string.
-- (in fact, also is able to scan numeric +- eqns, which is not
-- in the JSON spec.)
-- Returns the number, and the position of the next character
-- after the number.
-- @param s The string being scanned.
-- @param startPos The position at which to start scanning.
-- @return number, int The extracted number and the position of the next character to scan.
function decode_scanNumber(s,startPos)
local endPos = startPos+1
local stringLen = string.len(s)
local acceptableChars = "+-0123456789.eE"
while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true)
and endPos<=stringLen
) do
endPos = endPos + 1
end
local stringValue = 'return ' .. string.sub(s,startPos, endPos-1)
local stringEval = base.loadstring(stringValue)
base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos)
return stringEval(), endPos
end
--- Scans a JSON object into a Lua object.
-- startPos begins at the start of the object.
-- Returns the object and the next starting position.
-- @param s The string being scanned.
-- @param startPos The starting position of the scan.
-- @return table, int The scanned object as a table and the position of the next character to scan.
function decode_scanObject(s,startPos)
local object = {}
local stringLen = string.len(s)
local key, value
base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s)
startPos = startPos + 1
repeat
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.')
local curChar = string.sub(s,startPos,startPos)
if (curChar=='}') then
return object,startPos+1
end
if (curChar==',') then
startPos = decode_scanWhitespace(s,startPos+1)
end
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.')
-- Scan the key
key, startPos = decode(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
startPos = decode_scanWhitespace(s,startPos)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos)
startPos = decode_scanWhitespace(s,startPos+1)
base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
value, startPos = decode(s,startPos)
object[key]=value
until false -- infinite loop while key-value pairs are found
end
--- Scans a JSON string from the opening inverted comma or single quote to the
-- end of the string.
-- Returns the string extracted as a Lua string,
-- and the position of the next non-string character
-- (after the closing inverted comma or single quote).
-- @param s The string being scanned.
-- @param startPos The starting position of the scan.
-- @return string, int The extracted string as a Lua string, and the next character to parse.
function decode_scanString(s,startPos)
base.assert(startPos, 'decode_scanString(..) called without start position')
local startChar = string.sub(s,startPos,startPos)
base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string')
local escaped = false
local endPos = startPos + 1
local bEnded = false
local stringLen = string.len(s)
repeat
local curChar = string.sub(s,endPos,endPos)
if not escaped then
if curChar==[[\]] then
escaped = true
else
bEnded = curChar==startChar
end
else
-- If we're escaped, we accept the current character come what may
escaped = false
end
endPos = endPos + 1
base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos)
until bEnded
local stringValue = 'return ' .. string.sub(s, startPos, endPos-1)
local stringEval = base.loadstring(stringValue)
base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos)
return stringEval(), endPos
end
--- Scans a JSON string skipping all whitespace from the current start position.
-- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached.
-- @param s The string being scanned
-- @param startPos The starting position where we should begin removing whitespace.
-- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string
-- was reached.
function decode_scanWhitespace(s,startPos)
local whitespace=" \n\r\t"
local stringLen = string.len(s)
while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do
startPos = startPos + 1
end
return startPos
end
--- Encodes a string to be JSON-compatible.
-- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-)
-- @param s The string to return as a JSON encoded (i.e. backquoted string)
-- @return The string appropriately escaped.
function encodeString(s)
s = string.gsub(s,'\\','\\\\')
s = string.gsub(s,'"','\\"')
s = string.gsub(s,"'","\\'")
s = string.gsub(s,'\n','\\n')
s = string.gsub(s,'\t','\\t')
return s
end
-- Determines whether the given Lua type is an array or a table / dictionary.
-- We consider any table an array if it has indexes 1..n for its n items, and no
-- other data in the table.
-- I think this method is currently a little 'flaky', but can't think of a good way around it yet...
-- @param t The table to evaluate as an array
-- @return boolean, number True if the table can be represented as an array, false otherwise. If true,
-- the second returned value is the maximum
-- number of indexed elements in the array.
function isArray(t)
-- Next we count all the elements, ensuring that any non-indexed elements are not-encodable
-- (with the possible exception of 'n')
local maxIndex = 0
for k,v in base.pairs(t) do
if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair
if (not isEncodable(v)) then return false end -- All array elements must be encodable
maxIndex = math.max(maxIndex,k)
else
if (k=='n') then
if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements
else -- Else of (k=='n')
if isEncodable(v) then return false end
end -- End of (k~='n')
end -- End of k,v not an indexed pair
end -- End of loop across all pairs
return true, maxIndex
end
--- Determines whether the given Lua object / table / variable can be JSON encoded. The only
-- types that are JSON encodable are: string, boolean, number, nil, table and json.null.
-- In this implementation, all other types are ignored.
-- @param o The object to examine.
-- @return boolean True if the object should be JSON encoded, false if it should be ignored.
function isEncodable(o)
local t = base.type(o)
return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null)
end
| apache-2.0 |
hussian1997/hk-_bot | tg/test.lua | 210 | 2571 | started = 0
our_id = 0
function vardump(value, depth, key)
local linePrefix = ""
local spaces = ""
if key ~= nil then
linePrefix = "["..key.."] = "
end
if depth == nil then
depth = 0
else
depth = depth + 1
for i=1, depth do spaces = spaces .. " " end
end
if type(value) == 'table' then
mTable = getmetatable(value)
if mTable == nil then
print(spaces ..linePrefix.."(table) ")
else
print(spaces .."(metatable) ")
value = mTable
end
for tableKey, tableValue in pairs(value) do
vardump(tableValue, depth, tableKey)
end
elseif type(value) == 'function' or
type(value) == 'thread' or
type(value) == 'userdata' or
value == nil
then
print(spaces..tostring(value))
else
print(spaces..linePrefix.."("..type(value)..") "..tostring(value))
end
end
print ("HI, this is lua script")
function ok_cb(extra, success, result)
end
-- Notification code {{{
function get_title (P, Q)
if (Q.type == 'user') then
return P.first_name .. " " .. P.last_name
elseif (Q.type == 'chat') then
return Q.title
elseif (Q.type == 'encr_chat') then
return 'Secret chat with ' .. P.first_name .. ' ' .. P.last_name
else
return ''
end
end
local lgi = require ('lgi')
local notify = lgi.require('Notify')
notify.init ("Telegram updates")
local icon = os.getenv("HOME") .. "/.telegram-cli/telegram-pics/telegram_64.png"
function do_notify (user, msg)
local n = notify.Notification.new(user, msg, icon)
n:show ()
end
-- }}}
function on_msg_receive (msg)
if started == 0 then
return
end
if msg.out then
return
end
do_notify (get_title (msg.from, msg.to), msg.text)
if (msg.text == 'ping') then
if (msg.to.id == our_id) then
send_msg (msg.from.print_name, 'pong', ok_cb, false)
else
send_msg (msg.to.print_name, 'pong', ok_cb, false)
end
return
end
if (msg.text == 'PING') then
if (msg.to.id == our_id) then
fwd_msg (msg.from.print_name, msg.id, ok_cb, false)
else
fwd_msg (msg.to.print_name, msg.id, ok_cb, false)
end
return
end
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
function cron()
-- do something
postpone (cron, false, 1.0)
end
function on_binlog_replay_end ()
started = 1
postpone (cron, false, 1.0)
end
| gpl-2.0 |
dkogan/notion.xfttest | mod_xrandr/mod_xrandr.lua | 4 | 1077 | --
if package.loaded["mod_xrandr"] then return end
if not notioncore.load_module("mod_xrandr") then
return
end
local mod_xrandr=_G["mod_xrandr"]
assert(mod_xrandr)
if not package.loaded["mod_xinerama"] then
dopath("mod_xinerama")
end
function filter(t, predicate)
local result = {}
for k,v in pairs(t) do
if predicate(v) then
result[k]=v
end
end
return result
end
function mod_xrandr.get_outputs(screen)
-- get outputs based on geometry of this screen
return mod_xrandr.get_outputs_for_geom(screen:geom())
end
function falls_within(geom)
return function(output)
local result = output.x >= geom.x and output.y <= geom.y
and output.x + output.w <= geom.x + geom.w
and output.y + output.h <= geom.y + geom.h
return result;
end
end
function mod_xrandr.get_outputs_within(all_outputs, screen)
return filter(all_outputs, falls_within(screen:geom()))
end
-- Mark ourselves loaded.
package.loaded["mod_xrandr"]=true
-- Load configuration file
dopath("cfg_xrandr", true)
| lgpl-2.1 |
dkogan/notion.xfttest | contrib/styles/look_awesome_yaarg.lua | 4 | 5383 | -- Authors: James Gray <j.gray@ed.ac.uk>
-- License: Unknown
-- Last Changed: 2006-02-03
--
--[[
look_awesome_yaarg.lua (based on look awesome )
To completely yaargify Ion, the terminal emulator background is recommended to
be set to gray25 as does the root window. Transparent frames by default
wallpaper can be good sometimes... Also note this theme uses terminus font.
Setup: Drop into ~/.ion3/ or install in the relevant system-wide directory
Author: James Gray <j dot gray at ed dot ac dot uk> (yaarg in #ion)
Date: Fri Feb 3 00:13:43 GMT 2006
]]
if not gr.select_engine("de") then return end
de.reset()
de.defstyle("*", {
shadow_colour = "gray25",
highlight_colour = "gray25",
padding_colour = "gray25",
foreground_colour = "white",
background_colour = "gray25",
border_style = "inlaid",
highlight_pixels = 0,
shadow_pixels = 0,
padding_pixels = 0,
spacing = 0,
font = "-*-terminus-*-*-normal--12-*-*-*-*-*-*-*",
text_align = "center",
})
de.defstyle("frame", {
based_on = "*",
background_colour = "gray25",
transparent_background = true,
shadow_pixels = 1,
padding_pixels = 0,
highlight_pixels = 0,
spacing = 1,
shadow_colour = "gray30",
highlight_colour = "gray28",
})
de.defstyle("frame-floatframe", {
based_on = "frame",
padding_pixels = 1,
de.substyle("active", {
padding_colour = "gray30",
}),
de.substyle("inactive", {
padding_colour = "#808080",
}),
})
de.defstyle("tab", {
based_on = "*",
highlight_pixels = 1,
shadow_pixels = 1,
padding_pixels = 0,
spacing = 0,
transparent_background = false,
text_align = "center",
de.substyle("active-selected", {
shadow_colour = "#808080",
highlight_colour = "#808080",
background_colour = "gray33",
foreground_colour = "white",
}),
de.substyle("active-unselected", {
shadow_colour = "#808080",
highlight_colour = "#808080",
background_colour = "gray30",
foreground_colour = "white",
}),
de.substyle("inactive-selected", {
shadow_colour = "#808080",
highlight_colour = "#808080",
background_colour = "gray33",
foreground_colour = "white",
}),
de.substyle("inactive-unselected", {
shadow_colour = "#808080",
highlight_colour = "#808080",
background_colour = "gray30",
foreground_colour = "white",
}),
})
de.defstyle("stdisp", {
padding = 0,
shadow_pixels = 0,
padding_pixels = 0,
spacing = 1,
highlight_pixels = 0,
shadow_colour = "black",
highlight_colour = "black",
background_colour = "gray40",
foreground_colour = "white",
})
de.defstyle("tab-frame", {
based_on = "tab",
font = "-*-terminus-*-*-normal--12-*-*-*-*-*-*-*",
padding_pixels = 1,
spacing = 0,
shadow_colour = "red",
padding_colour = "red",
highlight_colour = "red",
background_colour = "red",
de.substyle("active-*-*-*-activity", {
shadow_colour = "red",
highlight_colour = "red",
background_colour = "#808080",
foreground_colour = "white",
}),
de.substyle("inactive-*-*-*-activity", {
shadow_colour = "#808080",
highlight_colour = "#808080",
background_colour = "#808080",
foreground_colour = "#808080",
}),
})
de.defstyle("tab-frame-ionframe", {
based_on = "tab-frame",
})
de.defstyle("tab-frame-floatframe", {
based_on = "tab-frame",
padding_pixels = 0,
})
de.defstyle("tab-menuentry", {
based_on = "tab",
padding_pixels = 1,
spacing = 2,
text_align = "left",
})
de.defstyle("tab-menuentry-bigmenu", {
based_on = "tab-menuentry",
padding_pixels = 7,
})
de.defstyle("tab-menuentry-pmenu", {
based_on = "tab-menuentry",
de.substyle("inactive-selected", {
shadow_colour = "#808080",
highlight_colour = "#808080",
background_colour = "#CCCCCC",
foreground_colour = "#FFF",
}),
de.substyle("inactive-unselected", {
shadow_colour = "#667",
highlight_colour = "#667",
background_colour = "#334",
foreground_colour = "#999",
}),
})
de.defstyle("input", {
based_on = "*",
foreground_colour = "white",
background_colour = "grey30",
padding_colour = "white",
transparent_background = false,
border_style = "elevated",
padding_pixels = 2,
})
de.defstyle("input-edln", {
based_on = "input",
de.substyle("*-cursor", {
background_colour = "white",
foreground_colour = "black",
}),
de.substyle("*-selection", {
background_colour = "#AAA",
foreground_colour = "#334",
}),
})
de.defstyle("input-message", {
based_on = "input",
})
de.defstyle("input-menu", {
based_on = "input",
transparent_background = false,
highlight_pixels = 0,
shadow_pixels = 0,
padding_pixels = 0,
spacing = 0,
})
de.defstyle("input-menu-bigmenu", {
based_on = "input-menu",
})
de.defstyle("moveres_display", {
based_on = "input",
})
de.defstyle("dock", {
based_on = "*",
})
gr.refresh()
| lgpl-2.1 |
dacrybabysuck/darkstar | scripts/zones/Meriphataud_Mountains_[S]/npcs/Indescript_Markings.lua | 9 | 1037 | ----------------------------------
-- Area: Meriphataud_Mountains_[S]
-- NPC: Indescript Markings
-- Type: Quest
-- !pos -389 -9 92 97
-----------------------------------
local ID = require("scripts/zones/Meriphataud_Mountains_[S]/IDs")
require("scripts/globals/keyitems")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local loafersQuestProgress = player:getCharVar("AF_SCH_BOOTS")
player:delStatusEffect(dsp.effect.SNEAK)
-- SCH AF Quest - Boots
if loafersQuestProgress > 0 and loafersQuestProgress < 3 and not player:hasKeyItem(dsp.ki.DROGAROGAN_BONEMEAL) then
player:addKeyItem(dsp.ki.DROGAROGAN_BONEMEAL)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.DROGAROGAN_BONEMEAL)
player:setCharVar("AF_SCH_BOOTS", loafersQuestProgress + 1)
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
| gpl-3.0 |
willswang/vlc | share/lua/sd/jamendo.lua | 58 | 6732 | --[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Fabio Ritrovato <sephiroth87 at videolan dot org>
Rémi Duraffort <ivoire at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
require "simplexml"
function descriptor()
return { title="Jamendo Selections" }
end
function main()
add_top_tracks( "ratingweek_desc", "rock", 100 )
add_top_tracks( "ratingweek_desc", "pop", 100 )
add_top_tracks( "ratingweek_desc", "jazz", 100 )
add_top_tracks( "ratingweek_desc", "dance", 100 )
add_top_tracks( "ratingweek_desc", "hipop+rap", 100 )
add_top_tracks( "ratingweek_desc", "world+reggae", 100 )
add_top_tracks( "ratingweek_desc", "lounge+ambient", 100 )
add_top_tracks( "ratingweek_desc", nil, 100 )
add_top_albums( "ratingweek_desc", nil, 20 )
add_radio_from_id( "9", 20 )
add_radio_from_id( "8", 20 )
add_radio_from_id( "6", 20 )
add_radio_from_id( "5", 20 )
add_radio_from_id( "7", 20 )
add_radio_from_id( "4", 20 )
end
function add_top_albums( album_order, tag, max_results )
local url = "http://api.jamendo.com/get2/id+name+artist_name+album_image/album/xml/?imagesize=500&order=" .. album_order .. "&n=" .. max_results
if tag ~= nil then
url = url .. "&tag_idstr=" .. tag
end
local tree = simplexml.parse_url( url )
local node_name = "Top " .. max_results
if album_order == "rating_desc" then node_name = node_name .. " most popular albums"
elseif album_order == "ratingmonth_desc" then node_name = node_name .. " most popular albums this month"
elseif album_order == "ratingweek_desc" then node_name = node_name .. " most popular albums this week"
elseif album_order == "releasedate_desc" then node_name = node_name .. " latest released albums"
elseif album_order == "downloaded_desc" then node_name = node_name .. " most downloaded albums"
elseif album_order == "listened_desc" then node_name = node_name .. " most listened to albums"
elseif album_order == "starred_desc" then node_name = node_name .. " most starred albums"
elseif album_order == "playlisted_desc" then node_name = node_name .. " most playlisted albums"
elseif album_order == "needreviews_desc" then node_name = node_name .. " albums requiring review"
end
if tag ~= nil then
node_name = tag .. " - " .. node_name
end
local node = vlc.sd.add_node( {title=node_name} )
for _, album in ipairs( tree.children ) do
simplexml.add_name_maps( album )
local album_node = node:add_subitem(
{ path = 'http://api.jamendo.com/get2/id+name+duration+artist_name+album_name+album_genre+album_dates+album_image/track/xml/track_album+album_artist/?album_id=' .. album.children_map["id"][1].children[1],
title = album.children_map["artist_name"][1].children[1] .. ' - ' .. album.children_map["name"][1].children[1],
arturl = album.children_map["album_image"][1].children[1] })
end
end
function add_top_tracks( track_order, tag, max_results )
local url = "http://api.jamendo.com/get2/id+name+duration+artist_name+album_name+genre+album_image+album_dates/track/xml/track_album+album_artist/?imagesize=500&order=" .. track_order .. "&n=" .. max_results
if tag ~= nil then
url = url .. "&tag_minweight=0.35&tag_idstr=" .. tag
end
local tree = simplexml.parse_url( url )
local node_name = "Top " .. max_results
if track_order == "rating_desc" then node_name = node_name .. " most popular tracks"
elseif track_order == "ratingmonth_desc" then node_name = node_name .. " most popular tracks this month"
elseif track_order == "ratingweek_desc" then node_name = node_name .. " most popular tracks this week"
elseif track_order == "releasedate_desc" then node_name = node_name .. " latest released tracks"
elseif track_order == "downloaded_desc" then node_name = node_name .. " most downloaded tracks"
elseif track_order == "listened_desc" then node_name = node_name .. " most listened to tracks"
elseif track_order == "starred_desc" then node_name = node_name .. " most starred tracks"
elseif track_order == "playlisted_desc" then node_name = node_name .. " most playlisted tracks"
elseif track_order == "needreviews_desc" then node_name = node_name .. " tracks requiring review"
end
if tag ~= nil then
node_name = string.upper(tag) .. " - " .. node_name
end
local node = vlc.sd.add_node( {title=node_name} )
for _, track in ipairs( tree.children ) do
simplexml.add_name_maps( track )
node:add_subitem( {path="http://api.jamendo.com/get2/stream/track/redirect/?id=" .. track.children_map["id"][1].children[1],
title=track.children_map["artist_name"][1].children[1].." - "..track.children_map["name"][1].children[1],
artist=track.children_map["artist_name"][1].children[1],
album=track.children_map["album_name"][1].children[1],
genre=track.children_map["genre"][1].children[1],
date=track.children_map["album_dates"][1].children_map["year"][1].children[1],
arturl=track.children_map["album_image"][1].children[1],
duration=track.children_map["duration"][1].children[1]} )
end
end
function add_radio_from_id( id, max_results )
local radio_name
if id == "9" then radio_name="Rock"
elseif id == "8" then radio_name="Pop / Songwriting"
elseif id == "6" then radio_name="Jazz"
elseif id == "5" then radio_name="Hip-Hop"
elseif id == "7" then radio_name="Lounge"
elseif id == "4" then radio_name="Dance / Electro"
end
vlc.sd.add_item( {path="http://api.jamendo.com/get2/id+name+artist_name+album_name+duration+album_genre+album_image+album_dates/track/xml/radio_track_inradioplaylist+track_album+album_artist/?imagesize=500&order=random_desc&radio_id=" .. id .. "&n=" .. max_results,
title=radio_name} )
end
| gpl-2.0 |
dacrybabysuck/darkstar | scripts/zones/Balgas_Dais/bcnms/shattering_stars.lua | 9 | 1740 | -----------------------------------
-- Area: Balga's Dais
-- Name: Shattering stars - Maat Fight
-- !pos 299 -123 345 146
-----------------------------------
local ID = require("scripts/zones/Balgas_Dais/IDs")
require("scripts/globals/battlefield")
require("scripts/globals/quests")
require("scripts/globals/titles")
-----------------------------------
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 0)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32001 then
if player:getQuestStatus(JEUNO, dsp.quest.id.jeuno.SHATTERING_STARS) == QUEST_ACCEPTED and player:getFreeSlotsCount() > 0 then
player:addItem(4181)
player:messageSpecial(ID.text.ITEM_OBTAINED, 4181)
end
local pjob = player:getMainJob()
player:setCharVar("maatDefeated", pjob)
local maatsCap = player:getCharVar("maatsCap")
if bit.band(maatsCap, bit.lshift(1, pjob - 1)) ~= 1 then
player:setCharVar("maatsCap", bit.bor(maatsCap, bit.lshift(1, pjob - 1)))
end
player:addTitle(dsp.title.MAAT_MASHER)
end
end
| gpl-3.0 |
MrTheSoulz/NerdPack | conditions/azerite.lua | 1 | 1616 | local NeP, g = NeP, NeP._G
local Azerite = {}
local empowered = g.C_AzeriteEmpoweredItem.IsAzeriteEmpoweredItem
local selected = g.C_AzeriteEmpoweredItem.IsPowerSelected
local tierInfo = g.C_AzeriteEmpoweredItem.GetAllTierInfo
local PowerInfo = g.C_AzeriteEmpoweredItem.GetPowerInfo
local EquipType = {
[1] = "Head",
[3] = "Shoulder",
[5] = "Chest"
}
local function AzeriteScan()
g.wipe(Azerite)
if not g.IsEquippedItem(158075) then return end
for i = 1, 5, 2 do
if g.IsEquippedItemType(EquipType[i]) then
local item = g.ItemLocation:CreateFromEquipmentSlot(i)
if empowered(item) then
local info = tierInfo(item)
for _, v in pairs(info) do
for j = 1, #v.azeritePowerIDs do
if v.azeritePowerIDs[j] ~= 13
and selected(item, v.azeritePowerIDs[j]) then
local Name = g.GetSpellInfo(PowerInfo(v.azeritePowerIDs[j]).spellID):lower()
Azerite[Name] = (Azerite[Name] or 0) + 1
end
end
end
end
end
end
end
-- /dump NeP.DSL.Parse("azerite(Font of Life).count", "", "")
NeP.DSL:Register("azerite.count", function(_, spell)
return Azerite[spell:lower()] or 0
end)
-- /dump NeP.DSL.Parse("azerite(Overflowing Mists).active", "", "")
-- /dump NeP.DSL.Parse("azerite(Font of Life).active", "", "")
NeP.DSL:Register("azerite.active", function(_, spell)
spell = spell:lower()
return Azerite[spell] and Azerite[spell] > 0
end)
NeP.Listener:Add(n_name .. "_Azerite", "UNIT_INVENTORY_CHANGED", function()
AzeriteScan()
end)
NeP.Listener:Add(n_name .. "_Azerite", "AZERITE_EMPOWERED_ITEM_SELECTION_UPDATED", function()
AzeriteScan()
end)
AzeriteScan()
| mit |
dacrybabysuck/darkstar | scripts/globals/abilities/equanimity.lua | 12 | 1039 | -----------------------------------
-- Ability: Equanimity
-- Your next black magic spell will generate less enmity.
-- Obtained: Scholar Level 75
-- Recast Time: Stratagem Charge
-- Duration: 1 black magic spell or 60 seconds, whichever occurs first
--
-- Level |Charges |Recharge Time per Charge
-- ----- -------- ---------------
-- 10 |1 |4:00 minutes
-- 30 |2 |2:00 minutes
-- 50 |3 |1:20 minutes
-- 70 |4 |1:00 minute
-- 90 |5 |48 seconds
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------
function onAbilityCheck(player,target,ability)
if player:hasStatusEffect(dsp.effect.EQUANIMITY) then
return dsp.msg.basic.EFFECT_ALREADY_ACTIVE, 0
end
return 0,0
end
function onUseAbility(player,target,ability)
player:addStatusEffect(dsp.effect.EQUANIMITY,player:getMerit(dsp.merit.EQUANIMITY),0,60)
return dsp.effect.EQUANIMITY
end | gpl-3.0 |
dacrybabysuck/darkstar | scripts/globals/spells/cursna.lua | 12 | 2355 | -----------------------------------------
-- Spell: Cursna
-- Removes curse and bane from target.
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local curse = target:getStatusEffect(dsp.effect.CURSE_I)
local curse2 = target:getStatusEffect(dsp.effect.CURSE_II)
local bane = target:getStatusEffect(dsp.effect.BANE)
local bonus = caster:getMod(dsp.mod.ENHANCES_CURSNA) + target:getMod(dsp.mod.ENHANCES_CURSNA_RCVD)
local power = 25*((100+bonus)/100) -- This 25 is temp until the skill calculation is in.
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT)
if (target:hasStatusEffect(dsp.effect.DOOM) and power > math.random(1, 100)) then
-- remove doom
final = dsp.effect.DOOM
target:delStatusEffect(dsp.effect.DOOM)
spell:setMsg(dsp.msg.basic.NARROWLY_ESCAPE)
elseif (curse ~= nil and curse2 ~= nil and bane ~= nil) then
target:delStatusEffect(dsp.effect.CURSE_I)
target:delStatusEffect(dsp.effect.CURSE_II)
target:delStatusEffect(dsp.effect.BANE)
final = dsp.effect.CURSE_II
spell:setMsg(dsp.msg.basic.MAGIC_REMOVE_EFFECT)
elseif (curse ~= nil and bane ~= nil) then
target:delStatusEffect(dsp.effect.CURSE_I)
target:delStatusEffect(dsp.effect.BANE)
final = dsp.effect.CURSE_I
spell:setMsg(dsp.msg.basic.MAGIC_REMOVE_EFFECT)
elseif (curse2 ~= nil and bane ~= nil) then
target:delStatusEffect(dsp.effect.CURSE_II)
target:delStatusEffect(dsp.effect.BANE)
final = dsp.effect.CURSE_II
spell:setMsg(dsp.msg.basic.MAGIC_REMOVE_EFFECT)
elseif (curse ~= nil) then
target:delStatusEffect(dsp.effect.CURSE_I)
final = dsp.effect.CURSE_I
spell:setMsg(dsp.msg.basic.MAGIC_REMOVE_EFFECT)
elseif (curse2 ~= nil) then
target:delStatusEffect(dsp.effect.CURSE_II)
final = dsp.effect.CURSE_II
spell:setMsg(dsp.msg.basic.MAGIC_REMOVE_EFFECT)
elseif (bane ~= nil) then
target:delStatusEffect(dsp.effect.BANE)
final = dsp.effect.BANE
spell:setMsg(dsp.msg.basic.MAGIC_REMOVE_EFFECT)
end
return final
end
| gpl-3.0 |
dacrybabysuck/darkstar | scripts/globals/weaponskills/combo.lua | 10 | 1459 | -----------------------------------
-- Combo
-- Hand-to-Hand weapon skill
-- Skill level: 5
-- Delivers a threefold attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Thunder Gorget.
-- Aligned with the Thunder Belt.
-- Element: None
-- Modifiers: STR:20% DEX:20%
-- 100%TP 200%TP 300%TP
-- 1.00 1.50 2.00
-----------------------------------
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 3
params.ftp100 = 1 params.ftp200 = 1.5 params.ftp300 = 2
params.str_wsc = 0.2 params.dex_wsc = 0.2 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.crit100 = 0.0 params.crit200 = 0.0 params.crit300 = 0.0
params.canCrit = false
params.acc100 = 0.0 params.acc200= 0.0 params.acc300= 0.0
params.atk100 = 1; params.atk200 = 1; params.atk300 = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1 params.ftp200 = 3.75 params.ftp300 = 5.5
params.str_wsc = 0.3 params.dex_wsc = 0.3
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
andeandr100/Crumbled-World | Lua/Menu/MainMenu/mapListPanel.lua | 1 | 6086 | require("Menu/MainMenu/mainMenuStyle.lua")
require("Menu/MainMenu/mapInformation.lua")
--this = SceneNode()
MapListPanel = {}
function MapListPanel.new(panel, changeMapCallback)
local self = {}
local mapTable = {}
local worker
local firstButton = nil
local curentDirectory = "Map"
local mapListPanel
local addRowFunction
local labels = {}
function self.getFirstMapButton()
return firstButton
end
function self.languageChanged()
for i=1, #labels do
labels[i]:setText(language:getText(labels[i]:getTag()))
end
end
local function splitString(str,sep)
local array = {}
local reg = string.format("([^%s]+)",sep)
for mem in string.gmatch(str,reg) do
table.insert(array, mem)
end
return array
end
local function mapInfoLoaded()
local mapFolder = Core.getDataFolder(curentDirectory)
local files = mapFolder:getFiles()
local mapConfig = Config("mapsInfo")
local mapInfoTable = mapConfig:get("data"):getTable()
for i=1, #files do
local file = files[i]
--file = File()
local panels = mapTable[file:getPath()]
local mapInfoItem = mapInfoTable[file:getPath()]
if panels and mapInfoItem then
panels.mapSize:setText(mapInfoItem.mapSize)
panels.player:setText(tostring(mapInfoItem.players))
end
end
end
local function updateMapList()
local mapFolder = Core.getDataFolder(curentDirectory)
local files = mapFolder:getFiles()
local count = 0
mapListPanel:clear()
if curentDirectory ~= "Map" then
count = count + 1
addRowFunction(nil, count%2 == 0)
end
for i=1, #files do
if files[i]:isDirectory() and files[i]:getName() ~= "hidden" and files[i]:getName() ~= "Campaign" then
count = count + 1
addRowFunction( files[i], count%2 == 0 )
end
end
for i=1, #files do
if files[i]:isFile() then
local mapInfoItem = MapInformation.getMapInfoFromFileName(files[i]:getName(), files[i]:getPath())
if mapInfoItem.players > 1 then
count = count + 1
addRowFunction( files[i], count%2 == 0 )
end
end
end
end
local function changeFolder(button)
curentDirectory = button:getTag():toString()
updateMapList()
end
local function addRowButton(file, evenRow)
local button = mapListPanel:add(Button(PanelSize(Vec2(-1,0.03)), "", ButtonStyle.SQUARE))
button:setTextColor(Vec3(0.7))
button:setTextHoverColor(Vec3(0.92))
button:setTextDownColor(Vec3(1))
if evenRow then
button:setEdgeColor(Vec4(1,1,1,0.05), Vec4(1,1,1,0.05))
button:setInnerColor(Vec4(1,1,1,0.05), Vec4(1,1,1,0.05), Vec4(1,1,1,0.05))
else
button:setEdgeColor(Vec4(0), Vec4(0))
button:setInnerColor(Vec4(0), Vec4(0), Vec4(0))
end
button:setEdgeHoverColor(Vec4(1,1,1,0.4), Vec4(1,1,1,0.4))
button:setEdgeDownColor(Vec4(1,1,1,0.4), Vec4(1,1,1,0.4))
button:setInnerHoverColor(Vec4(1,1,1,0.4), Vec4(1,1,1,0.45), Vec4(1,1,1,0.4))
button:setInnerDownColor(Vec4(1,1,1,0.3), Vec4(1,1,1,0.4), Vec4(1,1,1,0.3))
button:setLayout(FlowLayout(Alignment.TOP_LEFT))
if file then
if file:isDirectory() then
button:setTag(curentDirectory.."/"..file:getName())
button:addEventCallbackExecute(changeFolder)
local img = button:add(Image(PanelSize(Vec2(-1), Vec2(1)), Text("icon_table.tga") ))
img:setUvCoord(Vec2(0.75,0.0),Vec2(0.875,0.0625))
elseif file:isFile() then
button:setTag(file:getPath())
button:addEventCallbackExecute(changeMapCallback)
button:add(Panel(PanelSize(Vec2(-1), Vec2(1))))
if firstButton == nil then
firstButton = button
end
end
local label = button:add(Label(PanelSize(Vec2(-0.65, -1)), file:getName(), Vec4(0.85)))
label:setCanHandleInput(false)
local mapInfoItem = MapInformation.getMapInfoFromFileName(file:getName(), file:getPath())
if mapInfoItem == nil then
mapInfoItem = {mapSize = "-", players = 1}
end
local mapSizeLabel = button:add(Label(PanelSize(Vec2(-0.5, -1)), mapInfoItem.mapSize, Vec3(0.85), Alignment.MIDDLE_CENTER))
mapSizeLabel:setCanHandleInput(false)
local playerLabel = button:add(Label(PanelSize(Vec2(-1, -1)), tostring(mapInfoItem.players), Vec3(0.85), Alignment.MIDDLE_CENTER))
playerLabel:setCanHandleInput(false)
mapTable[file:getPath()] = {mapSize = mapSizeLabel, player = playerLabel}
else
local folders = splitString(curentDirectory, "/")
local strDirectory = folders[1]
for i=2, #folders - 1 do
strDirectory = strDirectory.."/"..folders[i]
end
button:setTag(strDirectory)
local img = button:add(Image(PanelSize(Vec2(-1), Vec2(1)), Text("icon_table.tga") ))
img:setUvCoord(Vec2(0.75,0.0),Vec2(0.875,0.0625))
button:addEventCallbackExecute(changeFolder)
local label = button:add(Label(PanelSize(Vec2(-0.65, -1)), " ..", Vec4(0.85)))
label:setCanHandleInput(false)
end
end
local function init()
local mapFolder = Core.getDataFolder(curentDirectory)
local files = mapFolder:getFiles()
local mapsPanel = panel:add(Panel(PanelSize(Vec2(-1, -1))))
mapsPanel:setBackground(Gradient(Vec4(1,1,1,0.01), Vec4(1,1,1,0.025)))
local headerPanel = mapsPanel:add(Panel(PanelSize(Vec2(-1, 0.035))))
headerPanel:setBackground(Gradient(Vec4(1,1,1,0.05), Vec4(1,1,1,0.1)))
labels[1] = headerPanel:add(Label(PanelSize(Vec2(-0.65, -1)), language:getText("name"), Vec4(0.95)))
labels[2] = headerPanel:add(Label(PanelSize(Vec2(-0.5, -1)), language:getText("size"), Vec3(0.95)))
labels[3] = headerPanel:add(Label(PanelSize(Vec2(-1, -1)), language:getText("players"), Vec3(0.95)))
labels[1]:setTag("name")
labels[2]:setTag("size")
labels[3]:setTag("players")
mapListPanel = mapsPanel:add(Panel(PanelSize(Vec2(-1, -1))))
mapListPanel:setEnableYScroll()
addRowFunction = addRowButton
updateMapList()
MapInformation.setMapInfoLoadedFunction(mapInfoLoaded)
end
init()
return self
end | mit |
dacrybabysuck/darkstar | scripts/globals/items/behemoth_steak.lua | 11 | 1728 | -----------------------------------------
-- ID: 6464
-- Item: behemoth_steak
-- Food Effect: 180Min, All Races
-----------------------------------------
-- HP +40
-- STR +7
-- DEX +7
-- INT -3
-- Attack +23% (cap 160)
-- Ranged Attack +23% (cap 160)
-- Triple Attack +1%
-- Lizard Killer +4
-- hHP +4
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,10800,6464)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.HP, 40)
target:addMod(dsp.mod.STR, 7)
target:addMod(dsp.mod.DEX, 7)
target:addMod(dsp.mod.INT, -3)
target:addMod(dsp.mod.FOOD_ATTP, 23)
target:addMod(dsp.mod.FOOD_ATT_CAP, 160)
target:addMod(dsp.mod.FOOD_RATTP, 23)
target:addMod(dsp.mod.FOOD_RATT_CAP, 160)
target:addMod(dsp.mod.TRIPLE_ATTACK, 1)
target:addMod(dsp.mod.LIZARD_KILLER, 4)
target:addMod(dsp.mod.HPHEAL, 4)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.HP, 40)
target:delMod(dsp.mod.STR, 7)
target:delMod(dsp.mod.DEX, 7)
target:delMod(dsp.mod.INT, -3)
target:delMod(dsp.mod.FOOD_ATTP, 23)
target:delMod(dsp.mod.FOOD_ATT_CAP, 160)
target:delMod(dsp.mod.FOOD_RATTP, 23)
target:delMod(dsp.mod.FOOD_RATT_CAP, 160)
target:delMod(dsp.mod.TRIPLE_ATTACK, 1)
target:delMod(dsp.mod.LIZARD_KILLER, 4)
target:delMod(dsp.mod.HPHEAL, 4)
end
| gpl-3.0 |
Dev-TLN/T_L_N | libs/fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| gpl-2.0 |
dacrybabysuck/darkstar | scripts/commands/promote.lua | 22 | 1862 | ---------------------------------------------------------------------------------------------------
-- func: promote
-- desc: Promotes the player to a new GM level.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "si"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!promote <player> <level>");
end;
function onTrigger(player, target, level)
-- determine maximum level player can promote to
local maxLevel = player:getGMLevel() - 1;
if (maxLevel < 1) then
maxLevel = 0;
end
-- validate target
local targ;
if (target == nil) then
error(player, "You must provide a player name.");
return;
else
targ = GetPlayerByName(target);
if (targ == nil) then
error(player, string.format( "Player named '%s' not found!", target ) );
return;
end
end
-- catch players trying to change level of equal or higher tiered GMs.
if (targ:getGMLevel() >= player:getGMLevel()) then
printf( "%s attempting to adjust same or higher tier GM %s.", player:getName(), targ:getName() );
targ:PrintToPlayer(string.format( "%s attempted to adjust your GM rank.", player:getName() ));
error(player, "You can not use this command on same or higher tiered GMs.");
return;
end
-- validate level
if (level == nil or level < 0 or level > maxLevel) then
error(player, string.format("Invalid level. Must be 0 to %i.", maxLevel ));
return;
end
-- change target gm level
targ:setGMLevel(level);
player:PrintToPlayer(string.format( "%s set to tier %i.", targ:getName(), level ));
targ:PrintToPlayer(string.format( "You have been set to tier %i.", level ));
end; | gpl-3.0 |
sdgdsffdsfff/WizRouter | resty/redis_iresty.lua | 2 | 6264 | local redis_c = require "resty.redis"
local ok, new_tab = pcall(require, "table.new")
if not ok or type(new_tab) ~= "function" then
new_tab = function (narr, nrec) return {} end
end
local _M = new_tab(0, 155)
_M._VERSION = '0.01'
local commands = {
"append", "auth", "bgrewriteaof",
"bgsave", "bitcount", "bitop",
"blpop", "brpop",
"brpoplpush", "client", "config",
"dbsize",
"debug", "decr", "decrby",
"del", "discard", "dump",
"echo",
"eval", "exec", "exists",
"expire", "expireat", "flushall",
"flushdb", "get", "getbit",
"getrange", "getset", "hdel",
"hexists", "hget", "hgetall",
"hincrby", "hincrbyfloat", "hkeys",
"hlen",
"hmget", "hmset", "hscan",
"hset",
"hsetnx", "hvals", "incr",
"incrby", "incrbyfloat", "info",
"keys",
"lastsave", "lindex", "linsert",
"llen", "lpop", "lpush",
"lpushx", "lrange", "lrem",
"lset", "ltrim", "mget",
"migrate",
"monitor", "move", "mset",
"msetnx", "multi", "object",
"persist", "pexpire", "pexpireat",
"ping", "psetex", "psubscribe",
"pttl",
"publish", --[[ "punsubscribe", ]] "pubsub",
"quit",
"randomkey", "rename", "renamenx",
"restore",
"rpop", "rpoplpush", "rpush",
"rpushx", "sadd", "save",
"scan", "scard", "script",
"sdiff", "sdiffstore",
"select", "set", "setbit",
"setex", "setnx", "setrange",
"shutdown", "sinter", "sinterstore",
"sismember", "slaveof", "slowlog",
"smembers", "smove", "sort",
"spop", "srandmember", "srem",
"sscan",
"strlen", --[[ "subscribe", ]] "sunion",
"sunionstore", "sync", "time",
"ttl",
"type", --[[ "unsubscribe", ]] "unwatch",
"watch", "zadd", "zcard",
"zcount", "zincrby", "zinterstore",
"zrange", "zrangebyscore", "zrank",
"zrem", "zremrangebyrank", "zremrangebyscore",
"zrevrange", "zrevrangebyscore", "zrevrank",
"zscan",
"zscore", "zunionstore", "evalsha"
}
local mt = { __index = _M }
local function is_redis_null( res )
if type(res) == "table" then
for k,v in pairs(res) do
if v ~= ngx.null then
return false
end
end
return true
elseif res == ngx.null then
return true
elseif res == nil then
return true
end
return false
end
-- change connect address as you need
function _M.connect_mod( self, redis )
redis:set_timeout(self.timeout)
return redis:connect("127.0.0.1", 6379)
end
function _M.set_keepalive_mod( redis )
-- put it into the connection pool of size 100, with 60 seconds max idle time
return redis:set_keepalive(60000, 1000)
end
function _M.init_pipeline( self )
self._reqs = {}
end
function _M.commit_pipeline( self )
local reqs = self._reqs
if nil == reqs or 0 == #reqs then
return {}, "no pipeline"
else
self._reqs = nil
end
local redis, err = redis_c:new()
if not redis then
return nil, err
end
local ok, err = self:connect_mod(redis)
if not ok then
return {}, err
end
redis:init_pipeline()
for _, vals in ipairs(reqs) do
local fun = redis[vals[1]]
table.remove(vals , 1)
fun(redis, unpack(vals))
end
local results, err = redis:commit_pipeline()
if not results or err then
return {}, err
end
if is_redis_null(results) then
results = {}
ngx.log(ngx.WARN, "is null")
end
-- table.remove (results , 1)
self.set_keepalive_mod(redis)
for i,value in ipairs(results) do
if is_redis_null(value) then
results[i] = nil
end
end
return results, err
end
function _M.subscribe( self, channel )
local redis, err = redis_c:new()
if not redis then
return nil, err
end
local ok, err = self:connect_mod(redis)
if not ok or err then
return nil, err
end
local res, err = redis:subscribe(channel)
if not res then
return nil, err
end
res, err = redis:read_reply()
if not res then
return nil, err
end
redis:unsubscribe(channel)
self.set_keepalive_mod(redis)
return res, err
end
local function do_command(self, cmd, ... )
if self._reqs then
table.insert(self._reqs, {cmd, ...})
return
end
local redis, err = redis_c:new()
if not redis then
return nil, err
end
local ok, err = self:connect_mod(redis)
if not ok or err then
return nil, err
end
local fun = redis[cmd]
local result, err = fun(redis, ...)
if not result or err then
-- ngx.log(ngx.ERR, "pipeline result:", result, " err:", err)
return nil, err
end
if is_redis_null(result) then
result = nil
end
self.set_keepalive_mod(redis)
return result, err
end
function _M.new(self, opts)
opts = opts or {}
local timeout = (opts.timeout and opts.timeout * 1000) or 1000
local db_index= opts.db_index or 0
for i = 1, #commands do
local cmd = commands[i]
_M[cmd] =
function (self, ...)
return do_command(self, cmd, ...)
end
end
return setmetatable({
timeout = timeout,
db_index = db_index,
_reqs = nil }, mt)
end
return _M
| apache-2.0 |
dacrybabysuck/darkstar | scripts/globals/mobskills/double_kick.lua | 11 | 1061 | ---------------------------------------------
-- Double Kick
--
-- Description: Deals damage to a single target. Additional effect: Stun
-- Type: Physical
-- Utsusemi/Blink absorb: 1 shadow
-- Range: Melee
-- Notes: Stun may or may not take dsp.effect.
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 1
local accmod = 1
local dmgmod = 2.8
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.BLUNT,info.hitslanded)
target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.BLUNT)
local typeEffect = dsp.effect.STUN
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 4)
return dmg
end
| gpl-3.0 |
fiskio/dp | propagator/experiment.lua | 1 | 9395 | ------------------------------------------------------------------------
--[[ Experiment ]]--
-- An experiment propagates DataSets through Models. The specifics
-- such propagations are handled by Propagators. The propagation of
-- a DataSet is called an epoch. At the end of each epoch, a monitoring
-- step is performed where a report is generated for all observers.
-- The experiment keeps a log of the report of the experiment after
-- every epoch. This is done by calling the report() method of
-- every contained object, except Observers. The report is a read-only
-- table that is passed to Observers along with the Mediator through
-- Channels for which they are Subscribers. The report is also passed
-- to sub-objects during propagation in case they need to act upon
-- data found in other branches of the experiment tree.
------------------------------------------------------------------------
local Experiment = torch.class("dp.Experiment")
Experiment.isExperiment = true
function Experiment:__init(config)
assert(type(config) == 'table', "Constructor requires key-value arguments")
local args, id, model, optimizer, validator, tester,
observer, random_seed, epoch, mediator, overwrite, max_epoch, description, always_test
= xlua.unpack(
{config},
'Experiment',
'An Experiment to be performed using a Model, Propagators '..
'and a DataSource',
{arg='id', type='dp.ObjectID',
help='uniquely identifies the experiment. '..
'Defaults to using dp.uniqueID() to initialize a dp.ObjectID'},
{arg='model', type='dp.Model | nn.Module', req=true,
help='Model instance shared by all Propagators.'},
{arg='optimizer', type='dp.Optimizer',
help='Optimizer instance used for propagating the train set'},
{arg='validator', type='dp.Evaluator',
help='Evaluator instance used for propagating the valid set'},
{arg='tester', type='dp.Evaluator',
help='Evaluator instance used for propagating the test set'},
{arg='observer', type='dp.Observer',
help='Observer instance used for extending the Experiment'},
{arg='random_seed', type='number', default=7,
help='number used to initialize the random number generator'},
{arg='epoch', type='number', default=0,
help='Epoch at which to start the experiment.'},
{arg='mediator', type='dp.Mediator',
help='used for inter-object communication. defaults to dp.Mediator()'},
{arg='overwrite', type='boolean', default=false,
help='Overwrite existing values. For example, if a ' ..
'datasource is provided, and optimizer is already ' ..
'initialized with a dataset, and overwrite is true, ' ..
'then optimizer would be setup with datasource:trainSet()'},
{arg='max_epoch', type='number', default=1000,
help='Maximum number of epochs allocated to the experiment'},
{arg='description', type='string', default='',
help='A short description of the experiment'},
{arg='always_test', type='boolean', default=true,
help='Should the test set be evalutated at every epoch or only at the end?'}
)
self:setRandomSeed(random_seed)
self._is_done_experiment = false
self._id = id or dp.ObjectID(dp.uniqueID())
assert(self._id.isObjectID)
self:setModel(model)
self._epoch = epoch
self:setObserver(observer)
self._optimizer = optimizer
self._validator = validator
self._tester = tester
self._mediator = mediator or dp.Mediator()
self._description = description
self:setMaxEpoch(max_epoch)
self._always_test = always_test
end
function Experiment:setup(datasource)
--publishing to this channel will terminate the experimental loop
self._mediator:subscribe("doneExperiment", self, "doneExperiment")
-- Even though the model is used by different propagators, the
-- model uses the experiment's namespace:
self._model:setup{mediator=self._mediator,
id=self:id():create('model')}
if self._optimizer then
self._optimizer:setup{mediator=self._mediator, model=self._model,
id=self:id():create('optimizer'),
dataset=datasource:trainSet()}
end
if self._validator then
self._validator:setup{mediator=self._mediator, model=self._model,
id=self:id():create('validator'),
dataset=datasource:validSet()}
end
if self._tester then
self._tester:setup{mediator=self._mediator, model=self._model,
id=self:id():create('tester'),
dataset=datasource:testSet()}
end
if self._observer then
self._observer:setup{mediator=self._mediator, subject=self}
end
self._setup = true
end
--loops through the propagators until a doneExperiment is received or
--experiment reaches max_epochs
function Experiment:run(datasource, once)
if not self._setup then
self:setup(datasource)
end
local report = self:report()
local train_set = datasource:trainSet()
local valid_set = datasource:validSet()
local test_set = datasource:testSet()
local atleastonce = false
repeat
self._epoch = self._epoch + 1
if self._optimizer and train_set then
self._optimizer:propagateEpoch(train_set, report)
end
if self._validator and valid_set then
self._validator:propagateEpoch(valid_set, report)
end
if self._tester and test_set and self._always_test then
self._tester:propagateEpoch(test_set, report)
end
report = self:report()
self._mediator:publish("doneEpoch", report)
atleastonce = true
until (self:isDoneExperiment() or self._epoch >= self._max_epoch or (once and atleastonce))
-- final test?
if self._tester and not self._always_test then
self._epoch = 'test'
self._tester:propagateEpoch(test_set, report)
report = self:report()
self._mediator:publish("doneEpoch", report)
end
self._mediator:publish("finalizeExperiment")
end
--an observer should call this when the experiment is complete
function Experiment:doneExperiment()
self._is_done_experiment = true
end
function Experiment:isDoneExperiment()
return self._is_done_experiment
end
function Experiment:id()
return self._id
end
function Experiment:name()
return self._id:name()
end
function Experiment:model()
return self._model
end
function Experiment:optimizer()
return self._optimizer
end
function Experiment:validator()
return self._validator
end
function Experiment:tester()
return self._tester
end
function Experiment:mediator()
return self._mediator
end
function Experiment:randomSeed()
return self._random_seed
end
function Experiment:report()
local report = {
optimizer = self:optimizer() and self:optimizer():report(),
validator = self:validator() and self:validator():report(),
tester = self:tester() and self:tester():report(),
epoch = self:epoch(),
random_seed = self:randomSeed(),
model = self._model:report(),
id = self._id:toString(),
description = self._description
}
return report
end
function Experiment:observers()
return self._observers
end
function Experiment:epoch()
return self._epoch
end
function Experiment:setMaxEpoch(max_epoch)
self._max_epoch = max_epoch
end
function Experiment:setObserver(observer)
if torch.type(observer) == 'table' then
-- if list, make composite observer
observer = dp.CompositeObserver(observer)
end
self._observer = observer
end
function Experiment:setRandomSeed(random_seed)
torch.manualSeed(random_seed)
math.randomseed(random_seed)
self._random_seed = random_seed
end
function Experiment:setModel(model)
if not model.isModel then
print("Experiment:setModel Warning : "..
"'model' argument isn't an instance of dp.Model."..
"Assuming it's a nn.Module instance."..
"Wrapping it in dp.Module (this doesn't always work as-is)"
)
model = dp.Module{module=model}
end
self._model = model
end
function Experiment:verbose(verbose)
self._verbose = (verbose == nil) and true or verbose
if self._optimizer then
self._optimizer:verbose(self._verbose)
end
if self._validator then
self._validator:verbose(self._verbose)
end
if self._tester then
self._tester:verbose(self._verbose)
end
if self._model then
self._model:verbose(self._verbose)
end
if self._observer then
self._observer:verbose(self._verbose)
end
end
function Experiment:silent()
self:verbose(false)
end
function Experiment:type(new_type)
if self._model then
self._model:type(new_type)
end
if self._optimizer then
self._optimizer:type(new_type)
end
if self._validator then
self._validator:type(new_type)
end
if self._tester then
self._tester:type(new_type)
end
end
function Experiment:float()
return self:type('torch.FloatTensor')
end
function Experiment:double()
return self:type('torch.DoubleTensor')
end
function Experiment:cuda()
return self:type('torch.CudaTensor')
end
function Experiment:int()
return self:type('torch.IntTensor')
end
function Experiment:long()
return self:type('torch.LongTensor')
end
| bsd-3-clause |
dacrybabysuck/darkstar | scripts/zones/Mhaura/npcs/Nereus.lua | 9 | 2918 | -----------------------------------
-- Area: Mhaura
-- NPC: Nereus
-- Starts and ends repeteable quest A_POTTER_S_PREFERENCE
-----------------------------------
local ID = require("scripts/zones/Mhaura/IDs")
require("scripts/globals/npc_util")
require("scripts/globals/settings")
require("scripts/globals/quests")
-----------------------------------
-- player:startEvent(110); -- standar dialog
-- player:startEvent(115); -- i have enough for now, come later
-- player:startEvent(114); -- get me x as soon as you can
-- player:startEvent(111); -- start quest A Potter's Preference
-- player:startEvent(113); -- quest done!
-- player:startEvent(112); -- repeat quest
function onTrade(player,npc,trade)
if player:getQuestStatus(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.A_POTTER_S_PREFERENCE) == QUEST_ACCEPTED or player:getCharVar("QuestAPotterPrefeRepeat_var") == 1 then
if npcUtil.tradeHas(trade, 569) then
player:startEvent(113) -- quest done!
end
end
end
function onTrigger(player,npc)
if player:getQuestStatus(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.A_POTTER_S_PREFERENCE) == QUEST_AVAILABLE and player:getFameLevel(WINDURST) > 5 then
player:startEvent(111,569) -- start quest A Potter's Preference
elseif player:getQuestStatus(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.A_POTTER_S_PREFERENCE) == QUEST_ACCEPTED then
player:startEvent(114,569) -- get me dish_of_gusgen_clay as soon as you can
elseif player:getQuestStatus(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.A_POTTER_S_PREFERENCE) == QUEST_COMPLETED then
if player:getCharVar("QuestAPotterPrefeCompDay_var")+7 < VanadielDayOfTheYear() or player:getCharVar("QuestAPotterPrefeCompYear_var") < VanadielYear() then
-- seven days after copletition, allow to do the quest again
player:startEvent(112) -- repeat quest
else
player:startEvent(115) -- i have enough for now, come later
end
else
player:startEvent(110) --standar dialog
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 111 and option == 1 then --accept quest
player:addQuest(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.A_POTTER_S_PREFERENCE)
elseif csid == 113 then --quest completed
player:confirmTrade()
player:addFame(WINDURST,120)
player:addGil(GIL_RATE*2160)
player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*2160)
player:setCharVar("QuestAPotterPrefeRepeat_var",0)
player:setCharVar("QuestAPotterPrefeCompDay_var",VanadielDayOfTheYear())
player:setCharVar("QuestAPotterPrefeCompYear_var",VanadielYear())
player:completeQuest(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.A_POTTER_S_PREFERENCE)
elseif csid == 112 then --repeat quest
player:setCharVar("QuestAPotterPrefeRepeat_var",1)
end
end | gpl-3.0 |
skryabiin/core | engine/lua-core/texture-facet.lua | 1 | 1724 |
TextureFacet = Facet:new()
function TextureFacet:new(entity, o)
o = o or {}
return self:create(entity, o)
end
function TextureFacet:getType()
return "TextureFacet"
end
function TextureFacet:isRenderableFacet()
return true
end
function TextureFacet:setTextureName(textureName)
self.name = textureName
end
function TextureFacet:setTextureCoordinates(sourceRect)
self.coordinates = sourceRect
end
function TextureFacet:getTextureName()
return self.name
end
function TextureFacet:getTextureCoordinates()
return self.coordinates or {0,0,0,0}
end
function TextureFacet:getVisualOffset()
return self.offset or {0,0}
end
function TextureFacet:setVisualOffset(offset)
self.offset = offset
end
function TextureFacet:setVisualScale(scale)
self.scale = scale
end
function TextureFacet:getVisualScale()
return self.scale or {1,1}
end
function TextureFacet:getColor()
return self.color or {255,255,255,255}
end
function TextureFacet:setColor(color)
self.color = color
if self:isCoreFacet() then
local colorChangeEvent = {
typeName = "ColorChangeEvent",
entityId = self.of:getId(),
color = self:getColor(),
doModulateColor = true,
blendMode = 1,
facetId = self:getId()
}
EventProcessor.process(colorChangeEvent)
end
end
function TextureFacet:createFacetInCore()
if self:isCoreFacet() == false then
local facet = {
source = self:getTextureCoordinates(),
textureName = self:getTextureName(),
position = self.of:getPosition(),
dimensions = self.of:getDimensions(),
scale = self:getVisualScale(),
offset = self:getVisualOffset()
}
self.id = addTextureFacet_bind(self.systemName, self.of:getId(), facet)
self:setIsCoreFacet(true)
end
end
| mit |
dylanhart/PONG | main.lua | 1 | 4168 | function love.load()
config = {
psize = 50,
poffset = 20,
pwidth = 10,
pspeed = 200,
bspeed = 400,
swidth = love.window.getWidth(),
sheight = love.window.getHeight()
}
ball = {
x = config.swidth/2,
y = config.sheight/2,
angle = math.pi
}
paddles = {
a = {
y = config.sheight/2,
score = 0
},
b = {
y = config.sheight/2,
score = 0
}
}
love.graphics.setNewFont("8bit-wonder/8bit-wonder.ttf", 48)
distortion = love.graphics.newShader([[
extern number time;
extern number size;
vec4 effect(vec4 color, Image tex, vec2 tc, vec2 pc)
{
vec2 p = tc;
p.y = p.y + sin(p.x * size + time) * 0.03;
return Texel(tex, p);
}
]])
distortion:send("size", 5)
size = 5
canvas = love.graphics.newCanvas()
end
time = 0
function love.update(delta)
time = time + delta
distortion:send("time", time)
-- player paddle
local top = config.psize/2
local bot = config.sheight - top
local up = love.keyboard.isDown("up")
local down = love.keyboard.isDown("down")
if (up ~= down) then
if (up) then
paddles.a.y = paddles.a.y - config.pspeed * delta
else
paddles.a.y = paddles.a.y + config.pspeed * delta
end
if (paddles.a.y < top) then
paddles.a.y = top
end
if (paddles.a.y > bot) then
paddles.a.y = bot
end
end
-- ai paddle
local pdist = delta * config.pspeed
if (math.abs(ball.y - paddles.b.y) < pdist) then
paddles.b.y = ball.y
else
if (paddles.b.y > ball.y) then
paddles.b.y = paddles.b.y - pdist
else
paddles.b.y = paddles.b.y + pdist
end
end
if (paddles.b.y < top) then
paddles.b.y = top
end
if (paddles.b.y > bot) then
paddles.b.y = bot
end
-- ball
local dist = delta * config.bspeed
ball.x = ball.x + dist * math.cos(ball.angle)
ball.y = ball.y - dist * math.sin(ball.angle)
if (ball.y < 0) then
ball.y = 0
ball.angle = math.atan2(-math.sin(ball.angle), math.cos(ball.angle))
end
if (ball.y > config.sheight) then
ball.y = config.sheight
ball.angle = math.atan2(-math.sin(ball.angle), math.cos(ball.angle))
end
if (ball.x < config.poffset + config.pwidth and ball.x > config.poffset) then
if (math.abs(ball.y - paddles.a.y) < config.psize / 2) then
size = size + 1
distortion:send("size", size)
ball.x = config.poffset + config.pwidth
ball.angle = math.atan2(math.sin(ball.angle), -math.cos(ball.angle))
ball.angle = ball.angle + math.pi/2 * (paddles.a.y - ball.y)/config.psize
end
end
if (ball.x > config.swidth - (config.poffset + config.pwidth) and ball.x < config.swidth - config.poffset) then
if (math.abs(ball.y - paddles.b.y) < config.psize / 2) then
size = size + 1
distortion:send("size", size)
ball.x = config.swidth - (config.poffset + config.pwidth)
ball.angle = math.atan2(math.sin(ball.angle), -math.cos(ball.angle))
ball.angle = ball.angle + math.pi/3 * (ball.y - paddles.b.y)/config.psize
end
end
if (ball.x < 0) then
size = 5
distortion:send("size", size)
ball = {
x = config.swidth/2,
y = config.sheight/2,
angle = math.pi
}
paddles.b.score = paddles.b.score + 1
end
if (ball.x > config.swidth) then
size = 5
distortion:send("size", size)
ball = {
x = config.swidth/2,
y = config.sheight/2,
angle = 0
}
paddles.a.score = paddles.a.score + 1
end
end
function love.draw()
canvas:clear()
love.graphics.setCanvas(canvas)
love.graphics.circle("fill", ball.x, ball.y, 5, 8)
local w = config.pwidth
local h = config.psize
local off = config.poffset
local y = paddles.a.y
love.graphics.rectangle("fill", off, y - h/2, w, h)
y = paddles.b.y
love.graphics.rectangle("fill", config.swidth-off-w, y - h/2, w, h)
love.graphics.setCanvas()
love.graphics.setShader(distortion)
love.graphics.draw(canvas)
love.graphics.setShader()
love.graphics.printf(paddles.a.score, 10, 10, config.swidth/2 - 10, "right")
love.graphics.printf(paddles.b.score, config.swidth/2 + 10, 10, config.swidth - 10, "left")
end
function love.quit()
end
function love.focus(f)
end
function love.mousepressed(x, y, btn)
end
function love.mousereleased(x, y, btn)
end
function love.keypressed(key)
end
function love.keyreleased(key)
end
| mit |
kikito/Algorithm-Implementations | Levenshtein_distance/Lua/Yonaba/levenshtein.lua | 25 | 1670 | -- Levenshtein distance implementation
-- See: http://en.wikipedia.org/wiki/Levenshtein_distance
-- Iterative matrix-based method
-- See: http://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_full_matrix
-- Return the minimum of three elements
local function min(a, b, c)
return math.min(math.min(a, b), c)
end
-- Creates a 2D matrix
local function matrix(row,col)
local m = {}
for i = 1,row do m[i] = {}
for j = 1,col do m[i][j] = 0 end
end
return m
end
-- Calculates the Levenshtein distance between two strings
local function lev_iter_based(strA,strB)
local M = matrix(#strA+1,#strB+1)
local i,j,cost
local row,col = #M,#M[1]
for i = 1,row do M[i][1] = i-1 end
for j = 1,col do M[1][j] = j-1 end
for i = 2,row do
for j = 2,col do
if (strA:sub(i-1,i-1) == strB:sub(j-1,j-1)) then cost = 0
else cost = 1
end
M[i][j] = min(M[i-1][j]+1,M[i][j-1]+1,M[i-1][j-1]+cost)
end
end
return M[row][col]
end
-- Recursive method
-- See: http://en.wikipedia.org/wiki/Levenshtein_distance#Recursive
-- Calculates the Levenshtein distance between two strings
local function lev_recursive_based(strA, strB, s, t)
s, t = s or #strA, t or #strB
if s == 0 then return t end
if t == 0 then return s end
local cost = strA:sub(s,s) == strB:sub(t,t) and 0 or 1
return min(
lev_recursive_based(strA, strB, s - 1, t) + 1,
lev_recursive_based(strA, strB, s, t - 1) + 1,
lev_recursive_based(strA, strB, s - 1, t - 1) + cost
)
end
return {
lev_iter = lev_iter_based,
lev_recursive = function(strA, strB) -- Wrapped to shadow access to s and t args
return lev_recursive_based(strA, strB)
end
}
| mit |
vlachoudis/sl4a | lua/luasocket/etc/forward.lua | 61 | 2077 | -- load our favourite library
local dispatch = require("dispatch")
local handler = dispatch.newhandler()
-- make sure the user knows how to invoke us
if table.getn(arg) < 1 then
print("Usage")
print(" lua forward.lua <iport:ohost:oport> ...")
os.exit(1)
end
-- function to move data from one socket to the other
local function move(foo, bar)
local live
while 1 do
local data, error, partial = foo:receive(2048)
live = data or error == "timeout"
data = data or partial
local result, error = bar:send(data)
if not live or not result then
foo:close()
bar:close()
break
end
end
end
-- for each tunnel, start a new server
for i, v in ipairs(arg) do
-- capture forwarding parameters
local _, _, iport, ohost, oport = string.find(v, "([^:]+):([^:]+):([^:]+)")
assert(iport, "invalid arguments")
-- create our server socket
local server = assert(handler.tcp())
assert(server:setoption("reuseaddr", true))
assert(server:bind("*", iport))
assert(server:listen(32))
-- handler for the server object loops accepting new connections
handler:start(function()
while 1 do
local client = assert(server:accept())
assert(client:settimeout(0))
-- for each new connection, start a new client handler
handler:start(function()
-- handler tries to connect to peer
local peer = assert(handler.tcp())
assert(peer:settimeout(0))
assert(peer:connect(ohost, oport))
-- if sucessful, starts a new handler to send data from
-- client to peer
handler:start(function()
move(client, peer)
end)
-- afte starting new handler, enter in loop sending data from
-- peer to client
move(peer, client)
end)
end
end)
end
-- simply loop stepping the server
while 1 do
handler:step()
end
| apache-2.0 |
kikito/Algorithm-Implementations | Bubble_Sort/Lua/Yonaba/bubble_sort_test.lua | 27 | 2172 | -- Tests for bubble_sort.lua
local bubble_sort = require 'bubble_sort'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
-- Wrap for Lua's table sort so that it returns
-- the passed-in table
local function sort(t, comp)
table.sort(t, comp)
return t
end
-- Returns a copy of a an array
local function clone(t)
local _t = {}
for k,v in ipairs(t) do _t[k] = v end
return _t
end
-- Checks if t1 and t2 arrays are the same
local function same(t1, t2)
for k,v in ipairs(t1) do
if t2[k] ~= v then return false end
end
return true
end
-- Generates an array of n values in random order
local function gen(n)
local t = {}
for i = 1, n do t[i] = math.random(n) end
return t
end
-- Note: Let's add a bit of randomness
math.randomseed(os.time())
run('Empty arrays', function()
local t = {}
assert(same(sort(clone(t)),bubble_sort(t)))
end)
run('Sorted array', function()
local t = {1, 2, 3, 4, 5}
assert(same(sort(clone(t)),bubble_sort(t)))
end)
run('Array sorted in reverse', function()
local t = {5, 4, 3, 2, 1}
assert(same(sort(clone(t)),bubble_sort(t)))
local t = {5, 4, 3, 2, 1}
local comp = function(a,b) return a>b end
assert(same(sort(clone(t), comp),bubble_sort(t, comp)))
end)
run('Array containing multiple occurences of the same value', function()
local t = {4, 4, 8, 2, 2}
local comp = function(a,b) return a <= b end
assert(same(sort(clone(t)),bubble_sort(t, comp)))
local t = {0, 0, 0, 0, 0}
local comp = function(a,b) return a <= b end
assert(same(sort(clone(t)),bubble_sort(t, comp)))
end)
run('Large array of random values (1e3 values)', function()
local t = gen(1e3)
local comp = function(a,b) return a <= b end
assert(same(sort(clone(t)),bubble_sort(t, comp)))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total))) | mit |
eagle14/kia12 | plugins/media.lua | 297 | 1590 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
andreasmcdermott/tiny-world | anim.lua | 1 | 1261 | anim = {}
function anim:handle(dt)
local anims = entitymgr:getEntitiesByComponent(cAnim.name)
-- images
for i, v in ipairs(anims) do
local drw = entitymgr:getComponent(v.uid, cDraw.name)
local ani = entitymgr:getComponent(v.uid, cAnim.name)
if drw ~= nil and ani ~= nil then
ani.time = ani.time + dt
if ani.time > (1 / ani.fps) then
ani.currFrame = ani.currFrame + 1
if ani.currFrame > ani.frames then
if ani.loop == true then ani.currFrame = 1
else
if ani.remove then entitymgr:remove(v.uid) end
ani.currFrame = ani.frames
end
end
ani.time = 0
local img = factory:getImage(drw.file)
local w = img:getWidth() / ani.frames
drw.quad = love.graphics.newQuad(w * ani.currFrame - w, 0, drw.w, drw.h, img:getWidth(), img:getHeight())
end
end
end
-- shapes
local anims = entitymgr:getEntitiesByComponent(cDrawShape.name)
for i, v in ipairs(anims) do
local drw = entitymgr:getComponent(v.uid, cDrawShape.name)
if drw ~= nil then
drw.elapsed = drw.elapsed + dt
if drw.shape == "circle" and drw.e.r ~= drw.s.r then
drw.r = drw.s.r + (drw.e.r - drw.s.r) * (drw.elapsed / drw.time)
if drw.r > drw.e.r then
entitymgr:remove(v.uid)
end
end
end
end
end | mit |
hamed9898/xxbot | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
dacrybabysuck/darkstar | scripts/globals/mobskills/astral_flow_pet.lua | 11 | 2217 | ---------------------------------------------
-- Astral Flow
-- make existing pet use astral flow skill
---------------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
---------------------------------------------
local function petInactive(pet)
return
pet:hasStatusEffect(dsp.effect.LULLABY) or
pet:hasStatusEffect(dsp.effect.STUN) or
pet:hasStatusEffect(dsp.effect.PETRIFICATION) or
pet:hasStatusEffect(dsp.effect.SLEEP_II) or
pet:hasStatusEffect(dsp.effect.SLEEP_I) or
pet:hasStatusEffect(dsp.effect.TERROR)
end
function onMobSkillCheck(target, mob, skill)
-- must have pet
if not mob:hasPet() then
return 1
end
local pet = mob:getPet()
-- pet must be an avatar, and active
if pet:getSystem() ~= 5 or petInactive(pet) then
return 1
end
return 0
end
function onMobWeaponSkill(target, mob, skill)
local typeEffect = dsp.effect.ASTRAL_FLOW
local pet = mob:getPet()
skill:setMsg(dsp.msg.basic.USES)
-- no effect if pet is inactive
if petInactive(pet) then
return typeEffect
end
-- Find proper pet skill
local petFamily = pet:getFamily()
local skillId = 0
if petFamily == 34 or petFamily == 379 then skillId = 919 -- carbuncle searing light
elseif petFamily == 36 or petFamily == 381 then skillId = 839 -- fenrir howling moon
elseif petFamily == 37 or petFamily == 382 then skillId = 916 -- garuda aerial blast
elseif petFamily == 38 or petFamily == 383 then skillId = 913 -- ifrit inferno
elseif petFamily == 40 or petFamily == 384 then skillId = 915 -- leviathan tidal wave
elseif petFamily == 43 or petFamily == 386 then skillId = 918 -- ramuh judgment bolt
elseif petFamily == 44 or petFamily == 387 then skillId = 917 -- shiva diamond dust
elseif petFamily == 45 or petFamily == 388 then skillId = 914 -- titan earthen fury
else
printf("[astral_flow_pet] received unexpected pet family %i. Defaulted skill to Searing Light.", petFamily)
skillId = 919 -- searing light
end
pet:useMobAbility(skillId)
return typeEffect
end
| gpl-3.0 |
nicwolff/asterisk-agi-mp3 | utils/build-extensions-conf.lua | 1 | 2040 | #!/usr/bin/env lua
--[[
This utility can be used to generate an extensions.conf file to match an
existing extensions.lua file. As an argument it takes the patch of the
extensions.lua file to read from, otherwise it uses
/etc/asterisk/extensions.lua.
This script can also be used to automatically include extensions.lua in
extensions.conf via a #exec as well.
#exec /usr/bin/build-extensions-conf.lua -c
--]]
usage = [[
Usage:
]] .. arg[0] .. [[ [options] [extensions.lua path]
This utility can generate an extensions.conf file with all of the contexts in
your extensions.lua file defined as including the Lua switch. This is useful
if you want to use your extensions.lua file exclusively. By using this utility
you dont't have to create each extension in extensions.conf manually.
The resulting extensions.conf file is printed to standard output.
--contexts-only, -c Don't print the [global] or [general] sections. This
is useful for including the generated file into an
existing extensions.conf via #include or #exec.
--help, -h Print this message.
]]
extensions_file = "/etc/asterisk/extensions.lua"
options = {}
for k, v in ipairs(arg) do
if v:sub(1, 1) == "-" then
if v == "-h" or v == "--help" then
print("match")
options["help"] = true
elseif v == "-c" or v == "--contexts-only" then
options["contexts-only"] = true
end
else
options["extensions-file"] = v
end
end
if options["help"] then
io.stderr:write(usage)
os.exit(0)
end
if options["extensions-file"] then
extensions_file = options["extensions-file"]
end
result, error_message = pcall(dofile, extensions_file)
if not result then
io.stderr:write(error_message .. "\n")
os.exit(1)
end
if not extensions then
io.stderr:write("Error: extensions table not found in '" .. extensions_file .. "'\n")
os.exit(1)
end
if not options["contexts-only"] then
io.stdout:write("[general]\n\n[globals]\n\n")
end
for context, extens in pairs(extensions) do
io.stdout:write("[" .. tostring(context) .. "]\nswitch => Lua\n\n")
end
| gpl-2.0 |
gabrielegiannini/torch-rnn-repo | LSTM.lua | 13 | 8765 | require 'torch'
require 'nn'
local layer, parent = torch.class('nn.LSTM', 'nn.Module')
--[[
If we add up the sizes of all the tensors for output, gradInput, weights,
gradWeights, and temporary buffers, we get that a SequenceLSTM stores this many
scalar values:
NTD + 6NTH + 8NH + 8H^2 + 8DH + 9H
For N = 100, D = 512, T = 100, H = 1024 and with 4 bytes per number, this comes
out to 305MB. Note that this class doesn't own input or gradOutput, so you'll
see a bit higher memory usage in practice.
--]]
function layer:__init(input_dim, hidden_dim)
parent.__init(self)
local D, H = input_dim, hidden_dim
self.input_dim, self.hidden_dim = D, H
self.weight = torch.Tensor(D + H, 4 * H)
self.gradWeight = torch.Tensor(D + H, 4 * H):zero()
self.bias = torch.Tensor(4 * H)
self.gradBias = torch.Tensor(4 * H):zero()
self:reset()
self.cell = torch.Tensor() -- This will be (N, T, H)
self.gates = torch.Tensor() -- This will be (N, T, 4H)
self.buffer1 = torch.Tensor() -- This will be (N, H)
self.buffer2 = torch.Tensor() -- This will be (N, H)
self.buffer3 = torch.Tensor() -- This will be (1, 4H)
self.grad_a_buffer = torch.Tensor() -- This will be (N, 4H)
self.h0 = torch.Tensor()
self.c0 = torch.Tensor()
self.remember_states = false
self.grad_c0 = torch.Tensor()
self.grad_h0 = torch.Tensor()
self.grad_x = torch.Tensor()
self.gradInput = {self.grad_c0, self.grad_h0, self.grad_x}
end
function layer:reset(std)
if not std then
std = 1.0 / math.sqrt(self.hidden_dim + self.input_dim)
end
self.bias:zero()
self.bias[{{self.hidden_dim + 1, 2 * self.hidden_dim}}]:fill(1)
self.weight:normal(0, std)
return self
end
function layer:resetStates()
self.h0 = self.h0.new()
self.c0 = self.c0.new()
end
local function check_dims(x, dims)
assert(x:dim() == #dims)
for i, d in ipairs(dims) do
assert(x:size(i) == d)
end
end
function layer:_unpack_input(input)
local c0, h0, x = nil, nil, nil
if torch.type(input) == 'table' and #input == 3 then
c0, h0, x = unpack(input)
elseif torch.type(input) == 'table' and #input == 2 then
h0, x = unpack(input)
elseif torch.isTensor(input) then
x = input
else
assert(false, 'invalid input')
end
return c0, h0, x
end
function layer:_get_sizes(input, gradOutput)
local c0, h0, x = self:_unpack_input(input)
local N, T = x:size(1), x:size(2)
local H, D = self.hidden_dim, self.input_dim
check_dims(x, {N, T, D})
if h0 then
check_dims(h0, {N, H})
end
if c0 then
check_dims(c0, {N, H})
end
if gradOutput then
check_dims(gradOutput, {N, T, H})
end
return N, T, D, H
end
--[[
Input:
- c0: Initial cell state, (N, H)
- h0: Initial hidden state, (N, H)
- x: Input sequence, (N, T, D)
Output:
- h: Sequence of hidden states, (N, T, H)
--]]
function layer:updateOutput(input)
self.recompute_backward = true
local c0, h0, x = self:_unpack_input(input)
local N, T, D, H = self:_get_sizes(input)
self._return_grad_c0 = (c0 ~= nil)
self._return_grad_h0 = (h0 ~= nil)
if not c0 then
c0 = self.c0
if c0:nElement() == 0 or not self.remember_states then
c0:resize(N, H):zero()
elseif self.remember_states then
local prev_N, prev_T = self.cell:size(1), self.cell:size(2)
assert(prev_N == N, 'batch sizes must be constant to remember states')
c0:copy(self.cell[{{}, prev_T}])
end
end
if not h0 then
h0 = self.h0
if h0:nElement() == 0 or not self.remember_states then
h0:resize(N, H):zero()
elseif self.remember_states then
local prev_N, prev_T = self.output:size(1), self.output:size(2)
assert(prev_N == N, 'batch sizes must be the same to remember states')
h0:copy(self.output[{{}, prev_T}])
end
end
local bias_expand = self.bias:view(1, 4 * H):expand(N, 4 * H)
local Wx = self.weight[{{1, D}}]
local Wh = self.weight[{{D + 1, D + H}}]
local h, c = self.output, self.cell
h:resize(N, T, H):zero()
c:resize(N, T, H):zero()
local prev_h, prev_c = h0, c0
self.gates:resize(N, T, 4 * H):zero()
for t = 1, T do
local cur_x = x[{{}, t}]
local next_h = h[{{}, t}]
local next_c = c[{{}, t}]
local cur_gates = self.gates[{{}, t}]
cur_gates:addmm(bias_expand, cur_x, Wx)
cur_gates:addmm(prev_h, Wh)
cur_gates[{{}, {1, 3 * H}}]:sigmoid()
cur_gates[{{}, {3 * H + 1, 4 * H}}]:tanh()
local i = cur_gates[{{}, {1, H}}]
local f = cur_gates[{{}, {H + 1, 2 * H}}]
local o = cur_gates[{{}, {2 * H + 1, 3 * H}}]
local g = cur_gates[{{}, {3 * H + 1, 4 * H}}]
next_h:cmul(i, g)
next_c:cmul(f, prev_c):add(next_h)
next_h:tanh(next_c):cmul(o)
prev_h, prev_c = next_h, next_c
end
return self.output
end
function layer:backward(input, gradOutput, scale)
self.recompute_backward = false
scale = scale or 1.0
assert(scale == 1.0, 'must have scale=1')
local c0, h0, x = self:_unpack_input(input)
if not c0 then c0 = self.c0 end
if not h0 then h0 = self.h0 end
local grad_c0, grad_h0, grad_x = self.grad_c0, self.grad_h0, self.grad_x
local h, c = self.output, self.cell
local grad_h = gradOutput
local N, T, D, H = self:_get_sizes(input, gradOutput)
local Wx = self.weight[{{1, D}}]
local Wh = self.weight[{{D + 1, D + H}}]
local grad_Wx = self.gradWeight[{{1, D}}]
local grad_Wh = self.gradWeight[{{D + 1, D + H}}]
local grad_b = self.gradBias
grad_h0:resizeAs(h0):zero()
grad_c0:resizeAs(c0):zero()
grad_x:resizeAs(x):zero()
local grad_next_h = self.buffer1:resizeAs(h0):zero()
local grad_next_c = self.buffer2:resizeAs(c0):zero()
for t = T, 1, -1 do
local next_h, next_c = h[{{}, t}], c[{{}, t}]
local prev_h, prev_c = nil, nil
if t == 1 then
prev_h, prev_c = h0, c0
else
prev_h, prev_c = h[{{}, t - 1}], c[{{}, t - 1}]
end
grad_next_h:add(grad_h[{{}, t}])
local i = self.gates[{{}, t, {1, H}}]
local f = self.gates[{{}, t, {H + 1, 2 * H}}]
local o = self.gates[{{}, t, {2 * H + 1, 3 * H}}]
local g = self.gates[{{}, t, {3 * H + 1, 4 * H}}]
local grad_a = self.grad_a_buffer:resize(N, 4 * H):zero()
local grad_ai = grad_a[{{}, {1, H}}]
local grad_af = grad_a[{{}, {H + 1, 2 * H}}]
local grad_ao = grad_a[{{}, {2 * H + 1, 3 * H}}]
local grad_ag = grad_a[{{}, {3 * H + 1, 4 * H}}]
-- We will use grad_ai, grad_af, and grad_ao as temporary buffers
-- to to compute grad_next_c. We will need tanh_next_c (stored in grad_ai)
-- to compute grad_ao; the other values can be overwritten after we compute
-- grad_next_c
local tanh_next_c = grad_ai:tanh(next_c)
local tanh_next_c2 = grad_af:cmul(tanh_next_c, tanh_next_c)
local my_grad_next_c = grad_ao
my_grad_next_c:fill(1):add(-1, tanh_next_c2):cmul(o):cmul(grad_next_h)
grad_next_c:add(my_grad_next_c)
-- We need tanh_next_c (currently in grad_ai) to compute grad_ao; after
-- that we can overwrite it.
grad_ao:fill(1):add(-1, o):cmul(o):cmul(tanh_next_c):cmul(grad_next_h)
-- Use grad_ai as a temporary buffer for computing grad_ag
local g2 = grad_ai:cmul(g, g)
grad_ag:fill(1):add(-1, g2):cmul(i):cmul(grad_next_c)
-- We don't need any temporary storage for these so do them last
grad_ai:fill(1):add(-1, i):cmul(i):cmul(g):cmul(grad_next_c)
grad_af:fill(1):add(-1, f):cmul(f):cmul(prev_c):cmul(grad_next_c)
grad_x[{{}, t}]:mm(grad_a, Wx:t())
grad_Wx:addmm(scale, x[{{}, t}]:t(), grad_a)
grad_Wh:addmm(scale, prev_h:t(), grad_a)
local grad_a_sum = self.buffer3:resize(1, 4 * H):sum(grad_a, 1)
grad_b:add(scale, grad_a_sum)
grad_next_h:mm(grad_a, Wh:t())
grad_next_c:cmul(f)
end
grad_h0:copy(grad_next_h)
grad_c0:copy(grad_next_c)
if self._return_grad_c0 and self._return_grad_h0 then
self.gradInput = {self.grad_c0, self.grad_h0, self.grad_x}
elseif self._return_grad_h0 then
self.gradInput = {self.grad_h0, self.grad_x}
else
self.gradInput = self.grad_x
end
return self.gradInput
end
function layer:clearState()
self.cell:set()
self.gates:set()
self.buffer1:set()
self.buffer2:set()
self.buffer3:set()
self.grad_a_buffer:set()
self.grad_c0:set()
self.grad_h0:set()
self.grad_x:set()
self.output:set()
end
function layer:updateGradInput(input, gradOutput)
if self.recompute_backward then
self:backward(input, gradOutput, 1.0)
end
return self.gradInput
end
function layer:accGradParameters(input, gradOutput, scale)
if self.recompute_backward then
self:backward(input, gradOutput, scale)
end
end
function layer:__tostring__()
local name = torch.type(self)
local din, dout = self.input_dim, self.hidden_dim
return string.format('%s(%d -> %d)', name, din, dout)
end
| mit |
nimaghorbani/dozdi1 | plugins/groupmanager.lua | 136 | 11323 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin!"
end
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.'
end
local function set_description(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = deskripsi
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..deskripsi
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function set_rules(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules
return rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ')
save_data(_config.moderation.data, data)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-- show group settings
local function show_group_settings(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local settings = data[tostring(msg.to.id)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
function run(msg, matches)
--vardump(msg)
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
return create_group(msg)
end
if not is_chat_msg(msg) then
return "This is not a group chat."
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if msg.media and is_chat_msg(msg) and is_momod(msg) then
if msg.media.type == 'photo' and data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then
load_photo(msg.id, set_group_photo, msg)
end
end
end
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'setabout' and matches[2] then
deskripsi = matches[2]
return set_description(msg, data)
end
if matches[1] == 'about' then
return get_description(msg, data)
end
if matches[1] == 'setrules' then
rules = matches[2]
return set_rules(msg, data)
end
if matches[1] == 'rules' then
return get_rules(msg, data)
end
if matches[1] == 'group' and matches[2] == 'lock' then --group lock *
if matches[3] == 'name' then
return lock_group_name(msg, data)
end
if matches[3] == 'member' then
return lock_group_member(msg, data)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == 'unlock' then --group unlock *
if matches[3] == 'name' then
return unlock_group_name(msg, data)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == 'settings' then
return show_group_settings(msg, data)
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
end
end
return {
description = "Plugin to manage group chat.",
usage = {
"!creategroup <group_name> : Create a new group (admin only)",
"!setabout <description> : Set group description",
"!about : Read group description",
"!setrules <rules> : Set group rules",
"!rules : Read group rules",
"!setname <new_name> : Set group name",
"!setphoto : Set group photo",
"!group <lock|unlock> name : Lock/unlock group name",
"!group <lock|unlock> photo : Lock/unlock group photo",
"!group <lock|unlock> member : Lock/unlock group member",
"!group settings : Show group settings"
},
patterns = {
"^!(creategroup) (.*)$",
"^!(setabout) (.*)$",
"^!(about)$",
"^!(setrules) (.*)$",
"^!(rules)$",
"^!(setname) (.*)$",
"^!(setphoto)$",
"^!(group) (lock) (.*)$",
"^!(group) (unlock) (.*)$",
"^!(group) (settings)$",
"^!!tgservice (.+)$",
"%[(photo)%]",
},
run = run,
}
end | gpl-2.0 |
Noltari/openwrt-packages | utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/bmx6.lua | 78 | 1115 | #!/usr/bin/lua
local json = require "cjson"
local function interpret_suffix(rate)
local value = string.sub(rate, 1, -2)
local suffix = string.sub(rate, -1)
if suffix == "K" then return tonumber(value) * 10^3 end
if suffix == "M" then return tonumber(value) * 10^6 end
if suffix == "G" then return tonumber(value) * 10^9 end
return rate
end
local function scrape()
local status = json.decode(get_contents("/var/run/bmx6/json/status")).status
local labels = {
version = status.version,
id = status.name,
address = status.primaryIp
}
metric("bmx6_status", "gauge", labels, 1)
local links = json.decode(get_contents("/var/run/bmx6/json/links")).links
local metric_bmx6_rxRate = metric("bmx6_link_rxRate","gauge")
local metric_bmx6_txRate = metric("bmx6_link_txRate","gauge")
for _, link in pairs(links) do
local labels = {
source = status.name,
target = link.name,
dev = link.viaDev
}
metric_bmx6_rxRate(labels, interpret_suffix(link.rxRate))
metric_bmx6_txRate(labels, interpret_suffix(link.txRate))
end
end
return { scrape = scrape }
| gpl-2.0 |
geminy/aidear | oss/cegui/cegui-0.8.7/cegui/src/ScriptModules/Lua/support/tolua++bin/lua/module.lua | 14 | 1739 | -- tolua: module class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id$
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- Module class
-- Represents module.
-- The following fields are stored:
-- {i} = list of objects in the module.
classModule = {
classtype = 'module'
}
classModule.__index = classModule
setmetatable(classModule,classContainer)
-- register module
function classModule:register (pre)
pre = pre or ''
push(self)
output(pre..'tolua_module(tolua_S,"'..self.name..'",',self:hasvar(),');')
output(pre..'tolua_beginmodule(tolua_S,"'..self.name..'");')
local i=1
while self[i] do
self[i]:register(pre..' ')
i = i+1
end
output(pre..'tolua_endmodule(tolua_S);')
pop()
end
---
-- LuaDoc Patch
-- outputs an empty(without documentation) LuaDoc interface
-- by klapeto (http://cegui.org.uk/forum/viewtopic.php?f=7&t=6784)
function classModule:output_luadoc()
local i=1
while self[i] do
self[i]:output_luadoc()
i = i+1
end
end
-- Print method
function classModule:print (ident,close)
print(ident.."Module{")
print(ident.." name = '"..self.name.."';")
local i=1
while self[i] do
self[i]:print(ident.." ",",")
i = i+1
end
print(ident.."}"..close)
end
-- Internal constructor
function _Module (t)
setmetatable(t,classModule)
append(t)
return t
end
-- Constructor
-- Expects two string representing the module name and body.
function Module (n,b)
local t = _Module(_Container{name=n})
push(t)
t:parse(strsub(b,2,strlen(b)-1)) -- eliminate braces
pop()
return t
end
| gpl-3.0 |
dacrybabysuck/darkstar | scripts/zones/Bhaflau_Thickets/IDs.lua | 12 | 2723 | -----------------------------------
-- Area: Bhaflau_Thickets
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.BHAFLAU_THICKETS] =
{
text =
{
NOTHING_HAPPENS = 119, -- Nothing happens...
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
FISHING_MESSAGE_OFFSET = 7049, -- You can't fish here.
DIG_THROW_AWAY = 7062, -- You dig up <item>, but your inventory is full. You regretfully throw the <item> away.
FIND_NOTHING = 7064, -- You dig and you dig, but find nothing.
RESPONSE = 7329, -- There is no response...
HARVESTING_IS_POSSIBLE_HERE = 7561, -- Harvesting is possible here if you have <item>.
CANNOT_ENTER = 7584, -- You cannot enter at this time. Please wait a while before trying again.
AREA_FULL = 7585, -- This area is fully occupied. You were unable to enter.
MEMBER_NO_REQS = 7589, -- Not all of your party members meet the requirements for this objective. Unable to enter area.
MEMBER_TOO_FAR = 7593, -- One or more party members are too far away from the entrance. Unable to enter area.
HOMEPOINT_SET = 7692, -- Home point set!
},
mob =
{
MAHISHASURA_PH =
{
[16990296] = 16990306, -- 215.000 -18.000 372.000
},
EMERGENT_ELM_PH =
{
[16990374] = 16990376, -- 86.000 -35.000 621.000
},
NIS_PUK_PH =
{
[16990383] = 16990403, -- -135 -18 -648
[16990384] = 16990403, -- -104 -18 -636
[16990385] = 16990403, -- -123 -16 -638
[16990391] = 16990403, -- -106 -16 -613
[16990392] = 16990403, -- -109 -15 -600
[16990393] = 16990403, -- -128 -15 -602
[16990394] = 16990403, -- -132 -16 -612
[16990398] = 16990403, -- -119 -15 -651
},
HARVESTMAN = 16990252,
LIVIDROOT_AMOOSHAH = 16990473,
DEA = 16990474,
},
npc =
{
HARVESTING =
{
16990607,
16990608,
16990609,
16990610,
16990611,
16990612,
},
},
}
return zones[dsp.zone.BHAFLAU_THICKETS] | gpl-3.0 |
varunparkhe/Algorithm-Implementations | Bellman_Ford_Search/Lua/Yonaba/bellmanford.lua | 26 | 3025 | -- Bellman Ford single source shortest path search algorithm implementation
-- See : https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm
-- Notes : this is a generic implementation of Bellman Ford search algorithm.
-- It is devised to be used on waypoint graphs.
-- The BellmanFord class expects a handler to be initialized. Roughly said, the handler
-- is an interface between your graph and the search algorithm.
-- The passed-in handler should implement those functions.
-- handler.getNode(...) -> returns a Node (instance of node.lua)
-- handler.getAllNodes() -> returns an array list of all nodes in the graph
-- handler.getAllEdges() -> returns an array list of all edges in the graph
-- See utils/graph.lua for reference
-- The generic Node class provided (see utils/node.lua) should also be implemented
-- through the handler. Basically, it should describe how nodes are labelled
-- and tested for equality for a custom search space.
-- The following functions should be implemented:
-- function Node:initialize(...) -> creates a Node with custom attributes
-- function Node:toString() -> returns a unique string representation of
-- the node, for debug purposes
-- Dependencies
local class = require 'utils.class'
-- Clears nodes data between consecutive path requests.
local function resetForNextSearch(bellmanford)
local nodes = bellmanford.handler.getAllNodes()
for _, node in pairs(nodes) do
node.parent = nil
node.distance = math.huge
end
end
-- Builds and returns the path to the goal node
local function backtrace(node)
local path = {}
repeat
table.insert(path, 1, node)
node = node.parent
until not node
return path
end
-- Initializes Bellman Ford search with a custom handler
local BellmanFord = class()
function BellmanFord:initialize(handler)
self.handler = handler
end
-- Processes the graph for shortest paths
-- source : the starting node from which the search will spread.
-- target : the goal node
-- When done, the shortest path from one node to another can easily
-- backtraced by indexing the parent field of a node.
-- Return : if target supplied, returns the shortest path from source
-- to target.
function BellmanFord:process(source, target)
resetForNextSearch(self)
source.distance = 0
local nodes = self.handler.getAllNodes()
local edges = self.handler.getAllEdges()
-- Relaxing all edges |V| - 1 times
for i = 1, #nodes - 1 do
for i, edge in ipairs(edges) do
local u, v, w = edge.from, edge.to, edge.weight
local tempDistance = u.distance + w
if tempDistance < v.distance then
v.distance, v.parent = tempDistance, u
end
end
end
-- Checking for negative cycles
for i, edge in ipairs(edges) do
local u, v, w = edge.from, edge.to, edge.weight
local tempDistance = u.distance + w
assert(tempDistance >= v.distance, 'Negative cycle found!')
end
if target then return backtrace(target) end
end
return BellmanFord
| mit |
fgielow/devenserver | data/actions/scripts/quests/poichest.lua | 2 | 1036 | function onUse(player, item, fromPosition, target, toPosition, isHotkey)
if item.uid == 5306 then
if player:getStorageValue(5310) == -1 then
player:sendTextMessage(MESSAGE_INFO_DESCR, "You have found a Arcane Staff.")
player:addItem(2453, 1)
player:setStorageValue(5310, 1)
else
player:sendTextMessage(MESSAGE_INFO_DESCR, "It is empty.")
end
elseif item.uid == 5307 then
if player:getStorageValue(5310) == -1 then
player:sendTextMessage(MESSAGE_INFO_DESCR, "You have found a Avenger.")
player:addItem(6528, 1)
player:setStorageValue(5310, 1)
else
player:sendTextMessage(MESSAGE_INFO_DESCR, "It is empty.")
end
elseif item.uid == 5308 then
if player:getStorageValue(5310) == -1 then
player:sendTextMessage(MESSAGE_INFO_DESCR, "You have found a Arbalest.")
player:addItem(5803, 1)
player:setStorageValue(5310, 1)
else
player:sendTextMessage(MESSAGE_INFO_DESCR, "It is empty.")
end
end
return true
end
| gpl-2.0 |
avrem/ardupilot | libraries/AP_Scripting/tests/math.lua | 26 | 25303 | -- $Id: math.lua,v 1.77 2016/06/23 15:17:20 roberto Exp roberto $
--[[
*****************************************************************************
* Copyright (C) 1994-2016 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.
*****************************************************************************
]]
-- This code is copied from https://github.com/lua/tests and slightly modified to work within ArduPilot
gcs:send_text(6, "testing numbers and math lib")
local minint = math.mininteger
local maxint = math.maxinteger
local intbits = math.floor(math.log(maxint, 2) + 0.5) + 1
assert((1 << intbits) == 0)
assert(minint == 1 << (intbits - 1))
assert(maxint == minint - 1)
-- number of bits in the mantissa of a floating-point number
local floatbits = 24
do
local p = 2.0^floatbits
while p < p + 1.0 do
p = p * 2.0
floatbits = floatbits + 1
end
end
local function isNaN (x)
return (x ~= x)
end
assert(isNaN(0/0))
assert(not isNaN(1/0))
do
local x = 2.0^floatbits
assert(x > x - 1.0 and x == x + 1.0)
gcs:send_text(6, string.format("%d-bit integers, %d-bit (mantissa) floats",
intbits, floatbits))
end
assert(math.type(0) == "integer" and math.type(0.0) == "float"
and math.type("10") == nil)
local function checkerror (msg, f, ...)
local s, err = pcall(f, ...)
assert(not s and string.find(err, msg))
end
local msgf2i = "number.* has no integer representation"
-- float equality
function eq (a,b,limit)
if not limit then
if floatbits >= 50 then limit = 1E-11
else limit = 1E-5
end
end
-- a == b needed for +inf/-inf
return a == b or math.abs(a-b) <= limit
end
-- equality with types
function eqT (a,b)
return a == b and math.type(a) == math.type(b)
end
-- basic float notation
assert(0e12 == 0 and .0 == 0 and 0. == 0 and .2e2 == 20 and 2.E-1 == 0.2)
do
local a,b,c = "2", " 3e0 ", " 10 "
assert(a+b == 5 and -b == -3 and b+"2" == 5 and "10"-c == 0)
assert(type(a) == 'string' and type(b) == 'string' and type(c) == 'string')
assert(a == "2" and b == " 3e0 " and c == " 10 " and -c == -" 10 ")
assert(c%a == 0 and a^b == 08)
a = 0
assert(a == -a and 0 == -0)
end
do
local x = -1
local mz = 0/x -- minus zero
t = {[0] = 10, 20, 30, 40, 50}
assert(t[mz] == t[0] and t[-0] == t[0])
end
do -- tests for 'modf'
local a,b = math.modf(3.5)
assert(a == 3.0 and b == 0.5)
a,b = math.modf(-2.5)
assert(a == -2.0 and b == -0.5)
a,b = math.modf(-3e23)
assert(a == -3e23 and b == 0.0)
a,b = math.modf(3e35)
assert(a == 3e35 and b == 0.0)
a,b = math.modf(-1/0) -- -inf
assert(a == -1/0 and b == 0.0)
a,b = math.modf(1/0) -- inf
assert(a == 1/0 and b == 0.0)
a,b = math.modf(0/0) -- NaN
assert(isNaN(a) and isNaN(b))
a,b = math.modf(3) -- integer argument
assert(eqT(a, 3) and eqT(b, 0.0))
a,b = math.modf(minint)
assert(eqT(a, minint) and eqT(b, 0.0))
end
assert(math.huge > 10e30)
assert(-math.huge < -10e30)
-- integer arithmetic
assert(minint < minint + 1)
assert(maxint - 1 < maxint)
assert(0 - minint == minint)
assert(minint * minint == 0)
assert(maxint * maxint * maxint == maxint)
-- testing floor division and conversions
for _, i in pairs{-16, -15, -3, -2, -1, 0, 1, 2, 3, 15} do
for _, j in pairs{-16, -15, -3, -2, -1, 1, 2, 3, 15} do
for _, ti in pairs{0, 0.0} do -- try 'i' as integer and as float
for _, tj in pairs{0, 0.0} do -- try 'j' as integer and as float
local x = i + ti
local y = j + tj
assert(i//j == math.floor(i/j))
end
end
end
end
assert(1//0.0 == 1/0)
assert(-1 // 0.0 == -1/0)
assert(eqT(3.5 // 1.5, 2.0))
assert(eqT(3.5 // -1.5, -3.0))
assert(maxint // maxint == 1)
assert(maxint // 1 == maxint)
assert((maxint - 1) // maxint == 0)
assert(maxint // (maxint - 1) == 1)
assert(minint // minint == 1)
assert(minint // minint == 1)
assert((minint + 1) // minint == 0)
assert(minint // (minint + 1) == 1)
assert(minint // 1 == minint)
assert(minint // -1 == -minint)
assert(minint // -2 == 2^(intbits - 2))
assert(maxint // -1 == -maxint)
-- negative exponents
do
assert(2^-3 == 1 / 2^3)
assert(eq((-3)^-3, 1 / (-3)^3))
for i = -3, 3 do -- variables avoid constant folding
for j = -3, 3 do
-- domain errors (0^(-n)) are not portable
if not _port or i ~= 0 or j > 0 then
assert(eq(i^j, 1 / i^(-j)))
end
end
end
end
-- comparison between floats and integers (border cases)
if floatbits < intbits then
assert(2.0^floatbits == (1 << floatbits))
assert(2.0^floatbits - 1.0 == (1 << floatbits) - 1.0)
assert(2.0^floatbits - 1.0 ~= (1 << floatbits))
-- float is rounded, int is not
assert(2.0^floatbits + 1.0 ~= (1 << floatbits) + 1)
else -- floats can express all integers with full accuracy
assert(maxint == maxint + 0.0)
assert(maxint - 1 == maxint - 1.0)
assert(minint + 1 == minint + 1.0)
assert(maxint ~= maxint - 1.0)
end
assert(maxint + 0.0 == 2.0^(intbits - 1) - 1.0)
assert(minint + 0.0 == minint)
assert(minint + 0.0 == -2.0^(intbits - 1))
-- order between floats and integers
assert(1 < 1.1); assert(not (1 < 0.9))
assert(1 <= 1.1); assert(not (1 <= 0.9))
assert(-1 < -0.9); assert(not (-1 < -1.1))
assert(1 <= 1.1); assert(not (-1 <= -1.1))
assert(-1 < -0.9); assert(not (-1 < -1.1))
assert(-1 <= -0.9); assert(not (-1 <= -1.1))
assert(minint <= minint + 0.0)
assert(minint + 0.0 <= minint)
assert(not (minint < minint + 0.0))
assert(not (minint + 0.0 < minint))
assert(maxint < minint * -1.0)
assert(maxint <= minint * -1.0)
do
local fmaxi1 = 2^(intbits - 1)
assert(maxint < fmaxi1)
assert(maxint <= fmaxi1)
assert(not (fmaxi1 <= maxint))
assert(minint <= -2^(intbits - 1))
assert(-2^(intbits - 1) <= minint)
end
if floatbits < intbits then
gcs:send_text(6, "testing order (floats can't represent all int)")
local fmax = 2^floatbits
local ifmax = fmax | 0
assert(fmax < ifmax + 1)
assert(fmax - 1 < ifmax)
assert(-(fmax - 1) > -ifmax)
assert(not (fmax <= ifmax - 1))
assert(-fmax > -(ifmax + 1))
assert(not (-fmax >= -(ifmax - 1)))
assert(fmax/2 - 0.5 < ifmax//2)
assert(-(fmax/2 - 0.5) > -ifmax//2)
assert(maxint < 2^intbits)
assert(minint > -2^intbits)
assert(maxint <= 2^intbits)
assert(minint >= -2^intbits)
else
gcs:send_text(6, "testing order (floats can represent all ints)")
assert(maxint < maxint + 1.0)
assert(maxint < maxint + 0.5)
assert(maxint - 1.0 < maxint)
assert(maxint - 0.5 < maxint)
assert(not (maxint + 0.0 < maxint))
assert(maxint + 0.0 <= maxint)
assert(not (maxint < maxint + 0.0))
assert(maxint + 0.0 <= maxint)
assert(maxint <= maxint + 0.0)
assert(not (maxint + 1.0 <= maxint))
assert(not (maxint + 0.5 <= maxint))
assert(not (maxint <= maxint - 1.0))
assert(not (maxint <= maxint - 0.5))
assert(minint < minint + 1.0)
assert(minint < minint + 0.5)
assert(minint <= minint + 0.5)
assert(minint - 1.0 < minint)
assert(minint - 1.0 <= minint)
assert(not (minint + 0.0 < minint))
assert(not (minint + 0.5 < minint))
assert(not (minint < minint + 0.0))
assert(minint + 0.0 <= minint)
assert(minint <= minint + 0.0)
assert(not (minint + 1.0 <= minint))
assert(not (minint + 0.5 <= minint))
assert(not (minint <= minint - 1.0))
end
do
local NaN = 0/0
assert(not (NaN < 0))
assert(not (NaN > minint))
assert(not (NaN <= -9))
assert(not (NaN <= maxint))
assert(not (NaN < maxint))
assert(not (minint <= NaN))
assert(not (minint < NaN))
end
-- avoiding errors at compile time
--local function checkcompt (msg, code)
-- checkerror(msg, assert(load(code)))
--end
--checkcompt("divide by zero", "return 2 // 0")
--checkcompt(msgf2i, "return 2.3 >> 0")
--checkcompt(msgf2i, ("return 2.0^%d & 1"):format(intbits - 1))
--checkcompt("field 'huge'", "return math.huge << 1")
--checkcompt(msgf2i, ("return 1 | 2.0^%d"):format(intbits - 1))
--checkcompt(msgf2i, "return 2.3 ~ '0.0'")
-- testing overflow errors when converting from float to integer (runtime)
local function f2i (x) return x | x end
checkerror(msgf2i, f2i, math.huge) -- +inf
checkerror(msgf2i, f2i, -math.huge) -- -inf
checkerror(msgf2i, f2i, 0/0) -- NaN
if floatbits < intbits then
-- conversion tests when float cannot represent all integers
assert(maxint + 1.0 == maxint + 0.0)
assert(minint - 1.0 == minint + 0.0)
checkerror(msgf2i, f2i, maxint + 0.0)
assert(f2i(2.0^(intbits - 2)) == 1 << (intbits - 2))
assert(f2i(-2.0^(intbits - 2)) == -(1 << (intbits - 2)))
assert((2.0^(floatbits - 1) + 1.0) // 1 == (1 << (floatbits - 1)) + 1)
-- maximum integer representable as a float
local mf = maxint - (1 << (floatbits - intbits)) + 1
assert(f2i(mf + 0.0) == mf) -- OK up to here
mf = mf + 1
assert(f2i(mf + 0.0) ~= mf) -- no more representable
else
-- conversion tests when float can represent all integers
assert(maxint + 1.0 > maxint)
assert(minint - 1.0 < minint)
assert(f2i(maxint + 0.0) == maxint)
checkerror("no integer rep", f2i, maxint + 1.0)
checkerror("no integer rep", f2i, minint - 1.0)
end
-- 'minint' should be representable as a float no matter the precision
assert(f2i(minint + 0.0) == minint)
-- testing numeric strings
assert("2" + 1 == 3)
assert("2 " + 1 == 3)
assert(" -2 " + 1 == -1)
assert(" -0xa " + 1 == -9)
-- Literal integer Overflows (new behavior in 5.3.3)
do
-- no overflows
assert(eqT(tonumber(tostring(maxint)), maxint))
assert(eqT(tonumber(tostring(minint)), minint))
-- add 1 to last digit as a string (it cannot be 9...)
local function incd (n)
local s = string.format("%d", n)
s = string.gsub(s, "%d$", function (d)
assert(d ~= '9')
return string.char(string.byte(d) + 1)
end)
return s
end
-- 'tonumber' with overflow by 1
assert(eqT(tonumber(incd(maxint)), maxint + 1.0))
assert(eqT(tonumber(incd(minint)), minint - 1.0))
-- large numbers
assert(eqT(tonumber("1"..string.rep("0", 30)), 1e30))
assert(eqT(tonumber("-1"..string.rep("0", 30)), -1e30))
-- hexa format still wraps around
assert(eqT(tonumber("0x1"..string.rep("0", 30)), 0))
-- lexer in the limits
--assert(minint == load("return " .. minint)())
--assert(eqT(maxint, load("return " .. maxint)()))
assert(eqT(10000000000000000000000.0, 10000000000000000000000))
assert(eqT(-10000000000000000000000.0, -10000000000000000000000))
end
-- testing 'tonumber'
-- 'tonumber' with numbers
assert(tonumber(3.4) == 3.4)
assert(eqT(tonumber(3), 3))
assert(eqT(tonumber(maxint), maxint) and eqT(tonumber(minint), minint))
assert(tonumber(1/0) == 1/0)
-- 'tonumber' with strings
assert(tonumber("0") == 0)
assert(tonumber("") == nil)
assert(tonumber(" ") == nil)
assert(tonumber("-") == nil)
assert(tonumber(" -0x ") == nil)
assert(tonumber{} == nil)
assert(tonumber'+0.01' == 1/100 and tonumber'+.01' == 0.01 and
tonumber'.01' == 0.01 and tonumber'-1.' == -1 and
tonumber'+1.' == 1)
assert(tonumber'+ 0.01' == nil and tonumber'+.e1' == nil and
tonumber'1e' == nil and tonumber'1.0e+' == nil and
tonumber'.' == nil)
assert(tonumber('-012') == -010-2)
assert(tonumber('-1.2e2') == - - -120)
assert(tonumber("0xffffffffffff") == (1 << (4*12)) - 1)
assert(tonumber("0x"..string.rep("f", (intbits//4))) == -1)
assert(tonumber("-0x"..string.rep("f", (intbits//4))) == 1)
-- testing 'tonumber' with base
assert(tonumber(' 001010 ', 2) == 10)
assert(tonumber(' 001010 ', 10) == 001010)
assert(tonumber(' -1010 ', 2) == -10)
assert(tonumber('10', 36) == 36)
assert(tonumber(' -10 ', 36) == -36)
assert(tonumber(' +1Z ', 36) == 36 + 35)
assert(tonumber(' -1z ', 36) == -36 + -35)
assert(tonumber('-fFfa', 16) == -(10+(16*(15+(16*(15+(16*15)))))))
assert(tonumber(string.rep('1', (intbits - 2)), 2) + 1 == 2^(intbits - 2))
assert(tonumber('ffffFFFF', 16)+1 == (1 << 32))
assert(tonumber('0ffffFFFF', 16)+1 == (1 << 32))
assert(tonumber('-0ffffffFFFF', 16) - 1 == -(1 << 40))
for i = 2,36 do
local i2 = i * i
local i10 = i2 * i2 * i2 * i2 * i2 -- i^10
assert(tonumber('\t10000000000\t', i) == i10)
end
if not _soft then
-- tests with very long numerals
assert(tonumber("0x"..string.rep("f", 13)..".0") == 2.0^(4*13) - 1)
assert(tonumber("0x"..string.rep("f", 150)..".0") == 2.0^(4*150) - 1)
assert(tonumber("0x"..string.rep("f", 300)..".0") == 2.0^(4*300) - 1)
assert(tonumber("0x"..string.rep("f", 500)..".0") == 2.0^(4*500) - 1)
assert(tonumber('0x3.' .. string.rep('0', 1000)) == 3)
assert(tonumber('0x' .. string.rep('0', 1000) .. 'a') == 10)
assert(tonumber('0x0.' .. string.rep('0', 13).."1") == 2.0^(-4*14))
assert(tonumber('0x0.' .. string.rep('0', 150).."1") == 2.0^(-4*151))
assert(tonumber('0x0.' .. string.rep('0', 300).."1") == 2.0^(-4*301))
assert(tonumber('0x0.' .. string.rep('0', 500).."1") == 2.0^(-4*501))
assert(tonumber('0xe03' .. string.rep('0', 1000) .. 'p-4000') == 3587.0)
assert(tonumber('0x.' .. string.rep('0', 1000) .. '74p4004') == 0x7.4)
end
-- testing 'tonumber' for invalid formats
--[[
local function f (...)
if select('#', ...) == 1 then
return (...)
else
return "***"
end
end
assert(f(tonumber('fFfa', 15)) == nil)
assert(f(tonumber('099', 8)) == nil)
assert(f(tonumber('1\0', 2)) == nil)
assert(f(tonumber('', 8)) == nil)
assert(f(tonumber(' ', 9)) == nil)
assert(f(tonumber(' ', 9)) == nil)
assert(f(tonumber('0xf', 10)) == nil)
assert(f(tonumber('inf')) == nil)
assert(f(tonumber(' INF ')) == nil)
assert(f(tonumber('Nan')) == nil)
assert(f(tonumber('nan')) == nil)
assert(f(tonumber(' ')) == nil)
assert(f(tonumber('')) == nil)
assert(f(tonumber('1 a')) == nil)
assert(f(tonumber('1 a', 2)) == nil)
assert(f(tonumber('1\0')) == nil)
assert(f(tonumber('1 \0')) == nil)
assert(f(tonumber('1\0 ')) == nil)
assert(f(tonumber('e1')) == nil)
assert(f(tonumber('e 1')) == nil)
assert(f(tonumber(' 3.4.5 ')) == nil)
]]
-- testing 'tonumber' for invalid hexadecimal formats
assert(tonumber('0x') == nil)
assert(tonumber('x') == nil)
assert(tonumber('x3') == nil)
assert(tonumber('0x3.3.3') == nil) -- two decimal points
assert(tonumber('00x2') == nil)
assert(tonumber('0x 2') == nil)
assert(tonumber('0 x2') == nil)
assert(tonumber('23x') == nil)
assert(tonumber('- 0xaa') == nil)
assert(tonumber('-0xaaP ') == nil) -- no exponent
assert(tonumber('0x0.51p') == nil)
assert(tonumber('0x5p+-2') == nil)
-- testing hexadecimal numerals
assert(0x10 == 16 and 0xfff == 2^12 - 1 and 0XFB == 251)
assert(0x0p12 == 0 and 0x.0p-3 == 0)
assert(0xFFFFFFFF == (1 << 32) - 1)
assert(tonumber('+0x2') == 2)
assert(tonumber('-0xaA') == -170)
assert(tonumber('-0xffFFFfff') == -(1 << 32) + 1)
-- possible confusion with decimal exponent
assert(0E+1 == 0 and 0xE+1 == 15 and 0xe-1 == 13)
-- floating hexas
assert(tonumber(' 0x2.5 ') == 0x25/16)
assert(tonumber(' -0x2.5 ') == -0x25/16)
assert(tonumber(' +0x0.51p+8 ') == 0x51)
assert(0x.FfffFFFF == 1 - '0x.00000001')
assert('0xA.a' + 0 == 10 + 10/16)
assert(0xa.aP4 == 0XAA)
assert(0x4P-2 == 1)
assert(0x1.1 == '0x1.' + '+0x.1')
assert(0Xabcdef.0 == 0x.ABCDEFp+24)
assert(1.1 == 1.+.1)
assert(100.0 == 1E2 and .01 == 1e-2)
assert(1111111111 - 1111111110 == 1000.00e-03)
assert(1.1 == '1.'+'.1')
assert(tonumber'1111111111' - tonumber'1111111110' ==
tonumber" +0.001e+3 \n\t")
assert(0.1e-30 > 0.9E-31 and 0.9E30 < 0.1e31)
assert(0.123456 > 0.123455)
assert(tonumber('+1.23E18') == 1.23*10.0^18)
-- testing order operators
assert(not(1<1) and (1<2) and not(2<1))
assert(not('a'<'a') and ('a'<'b') and not('b'<'a'))
assert((1<=1) and (1<=2) and not(2<=1))
assert(('a'<='a') and ('a'<='b') and not('b'<='a'))
assert(not(1>1) and not(1>2) and (2>1))
assert(not('a'>'a') and not('a'>'b') and ('b'>'a'))
assert((1>=1) and not(1>=2) and (2>=1))
assert(('a'>='a') and not('a'>='b') and ('b'>='a'))
assert(1.3 < 1.4 and 1.3 <= 1.4 and not (1.3 < 1.3) and 1.3 <= 1.3)
-- testing mod operator
assert(eqT(-4 % 3, 2))
assert(eqT(4 % -3, -2))
assert(eqT(-4.0 % 3, 2.0))
assert(eqT(4 % -3.0, -2.0))
assert(math.pi - math.pi % 1 == 3)
assert(math.pi - math.pi % 0.001 == 3.141)
assert(eqT(minint % minint, 0))
assert(eqT(maxint % maxint, 0))
assert((minint + 1) % minint == minint + 1)
assert((maxint - 1) % maxint == maxint - 1)
assert(minint % maxint == maxint - 1)
assert(minint % -1 == 0)
assert(minint % -2 == 0)
assert(maxint % -2 == -1)
-- testing unsigned comparisons
assert(math.ult(3, 4))
assert(not math.ult(4, 4))
assert(math.ult(-2, -1))
assert(math.ult(2, -1))
assert(not math.ult(-2, -2))
assert(math.ult(maxint, minint))
assert(not math.ult(minint, maxint))
assert(eq(math.sin(-9.8)^2 + math.cos(-9.8)^2, 1))
assert(eq(math.tan(math.pi/4), 1))
assert(eq(math.sin(math.pi/2), 1) and eq(math.cos(math.pi/2), 0))
assert(eq(math.atan(1), math.pi/4) and eq(math.acos(0), math.pi/2) and
eq(math.asin(1), math.pi/2))
assert(eq(math.deg(math.pi/2), 90) and eq(math.rad(90), math.pi/2))
assert(math.abs(-10.43) == 10.43)
assert(eqT(math.abs(minint), minint))
assert(eqT(math.abs(maxint), maxint))
assert(eqT(math.abs(-maxint), maxint))
assert(eq(math.atan(1,0), math.pi/2))
assert(math.fmod(10,3) == 1)
assert(eq(math.sqrt(10)^2, 10))
assert(eq(math.log(2, 10), math.log(2)/math.log(10)))
assert(eq(math.log(2, 2), 1))
assert(eq(math.log(9, 3), 2))
assert(eq(math.exp(0), 1))
assert(eq(math.sin(10), math.sin(10%(2*math.pi))))
assert(tonumber(' 1.3e-2 ') == 1.3e-2)
assert(tonumber(' -1.00000000000001 ') == -1.00000000000001)
-- testing constant limits
-- 2^23 = 8388608
assert(8388609 + -8388609 == 0)
assert(8388608 + -8388608 == 0)
assert(8388607 + -8388607 == 0)
do -- testing floor & ceil
assert(eqT(math.floor(3.4), 3))
assert(eqT(math.ceil(3.4), 4))
assert(eqT(math.floor(-3.4), -4))
assert(eqT(math.ceil(-3.4), -3))
assert(eqT(math.floor(maxint), maxint))
assert(eqT(math.ceil(maxint), maxint))
assert(eqT(math.floor(minint), minint))
assert(eqT(math.floor(minint + 0.0), minint))
assert(eqT(math.ceil(minint), minint))
assert(eqT(math.ceil(minint + 0.0), minint))
assert(math.floor(1e50) == 1e50)
assert(math.ceil(1e50) == 1e50)
assert(math.floor(-1e50) == -1e50)
assert(math.ceil(-1e50) == -1e50)
for _, p in pairs{31,32,63,64} do
assert(math.floor(2^p) == 2^p)
assert(math.floor(2^p + 0.5) == 2^p)
assert(math.ceil(2^p) == 2^p)
assert(math.ceil(2^p - 0.5) == 2^p)
end
checkerror("number expected", math.floor, {})
checkerror("number expected", math.ceil, print)
assert(eqT(math.tointeger(minint), minint))
assert(eqT(math.tointeger(minint .. ""), minint))
assert(eqT(math.tointeger(maxint), maxint))
assert(eqT(math.tointeger(maxint .. ""), maxint))
assert(eqT(math.tointeger(minint + 0.0), minint))
assert(math.tointeger(0.0 - minint) == nil)
assert(math.tointeger(math.pi) == nil)
assert(math.tointeger(-math.pi) == nil)
assert(math.floor(math.huge) == math.huge)
assert(math.ceil(math.huge) == math.huge)
assert(math.tointeger(math.huge) == nil)
assert(math.floor(-math.huge) == -math.huge)
assert(math.ceil(-math.huge) == -math.huge)
assert(math.tointeger(-math.huge) == nil)
assert(math.tointeger("34.0") == 34)
assert(math.tointeger("34.3") == nil)
assert(math.tointeger({}) == nil)
assert(math.tointeger(0/0) == nil) -- NaN
end
-- testing fmod for integers
for i = -6, 6 do
for j = -6, 6 do
if j ~= 0 then
local mi = math.fmod(i, j)
local mf = math.fmod(i + 0.0, j)
assert(mi == mf)
assert(math.type(mi) == 'integer' and math.type(mf) == 'float')
if (i >= 0 and j >= 0) or (i <= 0 and j <= 0) or mi == 0 then
assert(eqT(mi, i % j))
end
end
end
end
assert(eqT(math.fmod(minint, minint), 0))
assert(eqT(math.fmod(maxint, maxint), 0))
assert(eqT(math.fmod(minint + 1, minint), minint + 1))
assert(eqT(math.fmod(maxint - 1, maxint), maxint - 1))
checkerror("zero", math.fmod, 3, 0)
do -- testing max/min
checkerror("value expected", math.max)
checkerror("value expected", math.min)
assert(eqT(math.max(3), 3))
assert(eqT(math.max(3, 5, 9, 1), 9))
assert(math.max(maxint, 10e60) == 10e60)
assert(eqT(math.max(minint, minint + 1), minint + 1))
assert(eqT(math.min(3), 3))
assert(eqT(math.min(3, 5, 9, 1), 1))
assert(math.min(3.2, 5.9, -9.2, 1.1) == -9.2)
assert(math.min(1.9, 1.7, 1.72) == 1.7)
assert(math.min(-10e60, minint) == -10e60)
assert(eqT(math.min(maxint, maxint - 1), maxint - 1))
assert(eqT(math.min(maxint - 2, maxint, maxint - 1), maxint - 2))
end
-- testing implicit convertions
local a,b = '10', '20'
assert(a*b == 200 and a+b == 30 and a-b == -10 and a/b == 0.5 and -b == -20)
assert(a == '10' and b == '20')
do
gcs:send_text(6, "testing -0 and NaN")
local mz, z = -0.0, 0.0
assert(mz == z)
assert(1/mz < 0 and 0 < 1/z)
local a = {[mz] = 1}
assert(a[z] == 1 and a[mz] == 1)
a[z] = 2
assert(a[z] == 2 and a[mz] == 2)
local inf = math.huge * 2 + 1
mz, z = -1/inf, 1/inf
assert(mz == z)
assert(1/mz < 0 and 0 < 1/z)
local NaN = inf - inf
assert(NaN ~= NaN)
assert(not (NaN < NaN))
assert(not (NaN <= NaN))
assert(not (NaN > NaN))
assert(not (NaN >= NaN))
assert(not (0 < NaN) and not (NaN < 0))
local NaN1 = 0/0
assert(NaN ~= NaN1 and not (NaN <= NaN1) and not (NaN1 <= NaN))
local a = {}
assert(not pcall(rawset, a, NaN, 1))
assert(a[NaN] == nil)
a[1] = 1
assert(not pcall(rawset, a, NaN, 1))
assert(a[NaN] == nil)
-- strings with same binary representation as 0.0 (might create problems
-- for constant manipulation in the pre-compiler)
local a1, a2, a3, a4, a5 = 0, 0, "\0\0\0\0\0\0\0\0", 0, "\0\0\0\0\0\0\0\0"
assert(a1 == a2 and a2 == a4 and a1 ~= a3)
assert(a3 == a5)
end
gcs:send_text(6, "testing 'math.random'")
math.randomseed(0)
do -- test random for floats
local max = -math.huge
local min = math.huge
for i = 0, 20000 do
local t = math.random()
assert(0 <= t and t < 1)
max = math.max(max, t)
min = math.min(min, t)
if eq(max, 1, 0.001) and eq(min, 0, 0.001) then
goto ok
end
end
-- loop ended without satisfing condition
assert(false)
::ok::
end
do
local function aux (p, lim) -- test random for small intervals
local x1, x2
if #p == 1 then x1 = 1; x2 = p[1]
else x1 = p[1]; x2 = p[2]
end
local mark = {}; local count = 0 -- to check that all values appeared
for i = 0, lim or 2000 do
local t = math.random(table.unpack(p))
assert(x1 <= t and t <= x2)
if not mark[t] then -- new value
mark[t] = true
count = count + 1
end
if count == x2 - x1 + 1 then -- all values appeared; OK
goto ok
end
end
-- loop ended without satisfing condition
assert(false)
::ok::
end
aux({-10,0})
aux({6})
aux({-10, 10})
aux({minint, minint})
aux({maxint, maxint})
aux({minint, minint + 9})
aux({maxint - 3, maxint})
end
do
local function aux(p1, p2) -- test random for large intervals
local max = minint
local min = maxint
local n = 200
local mark = {}; local count = 0 -- to count how many different values
for _ = 1, n do
local t = math.random(p1, p2)
max = math.max(max, t)
min = math.min(min, t)
if not mark[t] then -- new value
mark[t] = true
count = count + 1
end
end
-- at least 80% of values are different
assert(count >= n * 0.8)
-- min and max not too far from formal min and max
local diff = (p2 - p1) // 8
assert(min < p1 + diff and max > p2 - diff)
end
aux(0, maxint)
aux(1, maxint)
aux(minint, -1)
aux(minint // 2, maxint // 2)
end
for i=1,100 do
assert(math.random(maxint) > 0)
assert(math.random(minint, -1) < 0)
end
assert(not pcall(math.random, 1, 2, 3)) -- too many arguments
-- empty interval
assert(not pcall(math.random, minint + 1, minint))
assert(not pcall(math.random, maxint, maxint - 1))
assert(not pcall(math.random, maxint, minint))
-- interval too large
assert(not pcall(math.random, minint, 0))
assert(not pcall(math.random, -1, maxint))
assert(not pcall(math.random, minint // 2, maxint // 2 + 1))
function update()
gcs:send_text(6, 'Math tests passed')
return update, 1000
end
return update()
| gpl-3.0 |
dacrybabysuck/darkstar | scripts/globals/items/dish_of_spaghetti_vongole_rosso_+1.lua | 11 | 1382 | -----------------------------------------
-- ID: 5198
-- Item: Dish of Spaghetti Vongole Rosso +1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health % 20
-- Health Cap 95
-- Vitality 2
-- Mind -1
-- Defense % 25
-- Defense Cap 35
-- Store TP 6
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,3600,5198)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.FOOD_HPP, 20)
target:addMod(dsp.mod.FOOD_HP_CAP, 95)
target:addMod(dsp.mod.VIT, 2)
target:addMod(dsp.mod.MND, -1)
target:addMod(dsp.mod.FOOD_DEFP, 25)
target:addMod(dsp.mod.FOOD_DEF_CAP, 35)
target:addMod(dsp.mod.STORETP, 6)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_HPP, 20)
target:delMod(dsp.mod.FOOD_HP_CAP, 95)
target:delMod(dsp.mod.VIT, 2)
target:delMod(dsp.mod.MND, -1)
target:delMod(dsp.mod.FOOD_DEFP, 25)
target:delMod(dsp.mod.FOOD_DEF_CAP, 35)
target:delMod(dsp.mod.STORETP, 6)
end
| gpl-3.0 |
kikito/Algorithm-Implementations | Counting_Sort/Lua/Yonaba/countsort_test.lua | 27 | 1206 | -- Tests for countsort.lua
local countsort = require 'countsort'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
-- Checks if the given array is sorted
local function is_sorted(array)
local m = array[1]
for i = 2,#array do
if i < m then return false end
end
return true
end
run('Array should not be empty', function()
assert(not pcall(countsort, {}))
end)
run('Array can be sorted', function()
assert(is_sorted(countsort({0,1,2,3,4,5,6})))
assert(is_sorted(countsort({6,5,4,3,2,1,0})))
end)
run('Array should not contain negative values', function()
assert(not pcall(countsort, {0,-1,5,3,2}))
end)
run('Array should not contain non-integer values', function()
assert(not pcall(countsort, {0.5,5.5,2,3,2}))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
turingbot/B1 | plugins/tools.lua | 1 | 55564 |
local SUDO = 151499613 -- put Your ID here! <===
function exi_files(cpath)
local files = {}
local pth = cpath
for k, v in pairs(scandir(pth)) do
table.insert(files, v)
end
return files
end
local function file_exi(name, cpath)
for k,v in pairs(exi_files(cpath)) do
if name == v then
return true
end
end
return false
end
local function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
return result
end
local function index_function(user_id)
for k,v in pairs(_config.admins) do
if user_id == v[1] then
print(k)
return k
end
end
-- If not found
return false
end
local function getindex(t,id)
for i,v in pairs(t) do
if v == id then
return i
end
end
return nil
end
local function already_sudo(user_id)
for k,v in pairs(_config.sudo_users) do
if user_id == v then
return k
end
end
-- If not found
return false
end
local function reload_plugins( )
plugins = {}
load_plugins()
end
local function exi_file()
local files = {}
local pth = tcpath..'/data/document'
for k, v in pairs(scandir(pth)) do
if (v:match('.lua$')) then
table.insert(files, v)
end
end
return files
end
local function pl_exi(name)
for k,v in pairs(exi_file()) do
if name == v then
return true
end
end
return false
end
local function sudolist(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local sudo_users = _config.sudo_users
if not lang then
text = "*List of sudo users :*\n"
else
text = "_لیست سودو های ربات :_\n"
end
for i=1,#sudo_users do
text = text..i.." - "..sudo_users[i].."\n"
end
return text
end
local function adminlist(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local sudo_users = _config.sudo_users
if not lang then
text = '*List of bot admins :*\n'
else
text = "_لیست ادمین های ربات :_\n"
end
local compare = text
local i = 1
for v,user in pairs(_config.admins) do
text = text..i..'- '..(user[2] or '')..' ➣ ('..user[1]..')\n'
i = i +1
end
if compare == text then
if not lang then
text = '_No_ *admins* _available_'
else
text = '_ادمینی برای ربات تعیین نشده_'
end
end
return text
end
local function chat_list(msg)
i = 1
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use #join (ID) to join*\n\n'
for k,v in pairsByKeys(data[tostring(groups)]) do
local group_id = v
if data[tostring(group_id)] then
settings = data[tostring(group_id)]['settings']
end
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n:gsub("", "")
chat_name = name:gsub("", "")
group_name_id = name .. '\n(ID: ' ..group_id.. ')\n\n'
if name:match("[\216-\219][\128-\191]") then
group_info = i..' - \n'..group_name_id
else
group_info = i..' - '..group_name_id
end
i = i + 1
end
end
message = message..group_info
end
return message
end
local function botrem(msg)
local data = load_data(_config.moderation.data)
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
if redis:get('ExpireDate:'..msg.to.id) then
redis:del('ExpireDate:'..msg.to.id)
end
tdcli.changeChatMemberStatus(msg.to.id, our_id, 'Left', dl_cb, nil)
end
local function warning(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local expiretime = redis:ttl('ExpireDate:'..msg.to.id)
if expiretime == -1 then
return
else
local d = math.floor(expiretime / 86400) + 1
if tonumber(d) == 1 and not is_sudo(msg) and is_mod(msg) then
if lang then
tdcli.sendMessage(msg.to.id, 0, 1, 'از شارژ گروه 1 روز باقی مانده، برای شارژ مجدد با سودو ربات و یا آیدی @g0db0y تماس بگیرید وگرنه با اتمام زمان شارژ، گروه از لیست ربات حذف وربات گروه را ترک خواهد کرد.', 1, 'md')
else
tdcli.sendMessage(msg.to.id, 0, 1, 'Group 1 day remaining charge, to recharge the robot contact with the sudo or contact with @g0db0y ID. With the completion of charging time, the group removed from the robot list and the robot will leave the group.', 1, 'md')
end
end
end
end
local function action_by_reply(arg, data)
local cmd = arg.cmd
if not tonumber(data.sender_user_id_) then return false end
if data.sender_user_id_ then
if cmd == "adminprom" then
local function adminprom_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if is_admin1(tonumber(data.id_)) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md")
end
end
table.insert(_config.admins, {tonumber(data.id_), user_name})
save_config()
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, adminprom_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "admindem" then
local function admindem_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local nameid = index_function(tonumber(data.id_))
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not is_admin1(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md")
end
end
table.remove(_config.admins, nameid)
save_config()
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, admindem_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "visudo" then
local function visudo_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if already_sudo(tonumber(data.id_)) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md")
end
end
table.insert(_config.sudo_users, tonumber(data.id_))
save_config()
reload_plugins(true)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, visudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "desudo" then
local function desudo_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not already_sudo(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md")
end
end
table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_)))
save_config()
reload_plugins(true)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, desudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
else
if lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function action_by_username(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local cmd = arg.cmd
if not arg.username then return false end
if data.id_ then
if data.type_.user_.username_ then
user_name = '@'..check_markdown(data.type_.user_.username_)
else
user_name = check_markdown(data.title_)
end
if cmd == "adminprom" then
if is_admin1(tonumber(data.id_)) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md")
end
end
table.insert(_config.admins, {tonumber(data.id_), user_name})
save_config()
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md")
end
end
if cmd == "admindem" then
local nameid = index_function(tonumber(data.id_))
if not is_admin1(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md")
end
end
table.remove(_config.admins, nameid)
save_config()
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md")
end
end
if cmd == "visudo" then
if already_sudo(tonumber(data.id_)) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md")
end
end
table.insert(_config.sudo_users, tonumber(data.id_))
save_config()
reload_plugins(true)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md")
end
end
if cmd == "desudo" then
if not already_sudo(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md")
end
end
table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_)))
save_config()
reload_plugins(true)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md")
end
end
else
if lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function action_by_id(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local cmd = arg.cmd
if not tonumber(arg.user_id) then return false end
if data.id_ then
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if cmd == "adminprom" then
if is_admin1(tonumber(data.id_)) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md")
end
end
table.insert(_config.admins, {tonumber(data.id_), user_name})
save_config()
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md")
end
end
if cmd == "admindem" then
local nameid = index_function(tonumber(data.id_))
if not is_admin1(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md")
end
end
table.remove(_config.admins, nameid)
save_config()
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md")
end
end
if cmd == "visudo" then
if already_sudo(tonumber(data.id_)) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md")
end
end
table.insert(_config.sudo_users, tonumber(data.id_))
save_config()
reload_plugins(true)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md")
end
end
if cmd == "desudo" then
if not already_sudo(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md")
end
end
table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_)))
save_config()
reload_plugins(true)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md")
end
end
else
if lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function pre_process(msg)
if msg.to.type ~= 'pv' then
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
local gpst = data[tostring(msg.to.id)]
local chex = redis:get('CheckExpire::'..msg.to.id)
local exd = redis:get('ExpireDate:'..msg.to.id)
if gpst and not chex and msg.from.id ~= SUDO and not is_sudo(msg) then
redis:set('CheckExpire::'..msg.to.id,true)
redis:set('ExpireDate:'..msg.to.id,true)
redis:setex('ExpireDate:'..msg.to.id, 86400, true)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, 'گروه به مدت 1 روز شارژ شد. لطفا با سودو و یا آیدی @g0db0y برای شارژ بیشتر تماس بگیرید. در غیر اینصورت گروه شما از لیست ربات حذف و ربات گروه را ترک خواهد کرد.', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, 'Group charged 1 day. to recharge the robot contact with the sudo or contact with @g0db0y ID. With the completion of charging time, the group removed from the robot list and the robot will leave the group.', 1, 'md')
end
end
if chex and not exd and msg.from.id ~= SUDO and not is_sudo(msg) then
local text1 = 'شارژ این گروه به اتمام رسید \n\nID: <code>'..msg.to.id..'</code>\n\nدر صورتی که میخواهید ربات این گروه را ترک کند از دستور زیر استفاده کنید\n\n/leave '..msg.to.id..'\nبرای جوین دادن توی این گروه میتونی از دستور زیر استفاده کنی:\n/jointo '..msg.to.id..'\n_________________\nدر صورتی که میخواهید گروه رو دوباره شارژ کنید میتوانید از کد های زیر استفاده کنید...\n\n<b>برای شارژ 1 ماهه:</b>\n/plan 1 '..msg.to.id..'\n\n<b>برای شارژ 3 ماهه:</b>\n/plan 2 '..msg.to.id..'\n\n<b>برای شارژ نامحدود:</b>\n/plan 3 '..msg.to.id
local text2 = 'شارژ این گروه به پایان رسید. به دلیل عدم شارژ مجدد، گروه از لیست ربات حذف و ربات از گروه خارج میشود، برای خرید مجدد یا آیدی @g0db0y تماس بگیرید.'
local text3 = '_Charging finished._\n\n*Group ID:*\n\n*ID:* `'..msg.to.id..'`\n\n*If you want the robot to leave this group use the following command:*\n\n`/Leave '..msg.to.id..'`\n\n*For Join to this group, you can use the following command:*\n\n`/Jointo '..msg.to.id..'`\n\n_________________\n\n_If you want to recharge the group can use the following code:_\n\n*To charge 1 month:*\n\n`/Plan 1 '..msg.to.id..'`\n\n*To charge 3 months:*\n\n`/Plan 2 '..msg.to.id..'`\n\n*For unlimited charge:*\n\n`/Plan 3 '..msg.to.id..'`'
local text4 = '_Charging finished. Due to lack of recharge remove the group from the robot list and the robot leave the group._'
if lang then
tdcli.sendMessage(SUDO, 0, 1, text1, 1, 'html')
tdcli.sendMessage(msg.to.id, 0, 1, text2, 1, 'md')
else
tdcli.sendMessage(SUDO, 0, 1, text3, 1, 'md')
tdcli.sendMessage(msg.to.id, 0, 1, text4, 1, 'md')
end
botrem(msg)
else
warning(msg)
end
end
end
local function run(msg, matches)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if tonumber(msg.from.id) == SUDO then
if matches[1] == "clear cache" then
run_bash("rm -rf ~/.telegram-cli/data/sticker/*")
run_bash("rm -rf ~/.telegram-cli/data/photo/*")
run_bash("rm -rf ~/.telegram-cli/data/animation/*")
run_bash("rm -rf ~/.telegram-cli/data/video/*")
run_bash("rm -rf ~/.telegram-cli/data/audio/*")
run_bash("rm -rf ~/.telegram-cli/data/voice/*")
run_bash("rm -rf ~/.telegram-cli/data/temp/*")
run_bash("rm -rf ~/.telegram-cli/data/thumb/*")
run_bash("rm -rf ~/.telegram-cli/data/document/*")
run_bash("rm -rf ~/.telegram-cli/data/profile_photo/*")
run_bash("rm -rf ~/.telegram-cli/data/encrypted/*")
return "*All Cache Has Been Cleared*"
end
if matches[1] == "visudo" then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="visudo"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="visudo"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="visudo"})
end
end
if matches[1] == "desudo" then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="desudo"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="desudo"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="desudo"})
end
end
end
if is_sudo(msg) then
if matches[1]:lower() == 'add' and not redis:get('ExpireDate:'..msg.to.id) then
redis:set('ExpireDate:'..msg.to.id,true)
redis:setex('ExpireDate:'..msg.to.id, 180, true)
if not redis:get('CheckExpire::'..msg.to.id) then
redis:set('CheckExpire::'..msg.to.id,true)
end
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_گروه به مدت 3 دقیقه برای اجرای تنظیمات شارژ میباشد._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Group charged 3 minutes for settings._', 1, 'md')
end
end
if matches[1] == 'rem' and redis:get('ExpireDate:'..msg.to.id) then
redis:del('ExpireDate:'..msg.to.id)
end
if matches[1]:lower() == 'gid' then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '`'..msg.to.id..'`', 1,'md')
end
if matches[1] == 'leave' and matches[2] then
if lang then
tdcli.sendMessage(matches[2], 0, 1, 'ربات با دستور سودو از گروه خارج شد.\nبرای اطلاعات بیشتر با سودو تماس بگیرید.', 1, 'md')
tdcli.changeChatMemberStatus(matches[2], our_id, 'Left', dl_cb, nil)
tdcli.sendMessage(SUDO, msg.id_, 1, 'ربات با موفقیت از گروه '..matches[2]..' خارج شد.', 1,'md')
else
tdcli.sendMessage(matches[2], 0, 1, '_Robot left the group._\n*For more information contact The SUDO.*', 1, 'md')
tdcli.changeChatMemberStatus(matches[2], our_id, 'Left', dl_cb, nil)
tdcli.sendMessage(SUDO, msg.id_, 1, '*Robot left from under group successfully:*\n\n`'..matches[2]..'`', 1,'md')
end
end
if matches[1]:lower() == 'charge' and matches[2] and matches[3] then
if string.match(matches[2], '^-%d+$') then
if tonumber(matches[3]) > 0 and tonumber(matches[3]) < 1001 then
local extime = (tonumber(matches[3]) * 86400)
redis:setex('ExpireDate:'..matches[2], extime, true)
if not redis:get('CheckExpire::'..msg.to.id) then
redis:set('CheckExpire::'..msg.to.id,true)
end
if lang then
tdcli.sendMessage(SUDO, 0, 1, 'ربات در گروه '..matches[3]..' به مدت '..matches[2]..' روز تمدید گردید.', 1, 'md')
tdcli.sendMessage(matches[2], 0, 1, 'ربات توسط ادمین به مدت `'..matches[3]..'` روز شارژ شد\nبرای مشاهده زمان شارژ گروه دستور /check استفاده کنید...',1 , 'md')
else
tdcli.sendMessage(SUDO, 0, 1, '*Recharged successfully in the group:* `'..matches[2]..'`\n_Expire Date:_ `'..matches[3]..'` *Day(s)*', 1, 'md')
tdcli.sendMessage(matches[2], 0, 1, '*Robot recharged* `'..matches[3]..'` *day(s)*\n*For checking expire date, send* `/check`',1 , 'md')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_تعداد روزها باید عددی از 1 تا 1000 باشد._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Expire days must be between 1 - 1000_', 1, 'md')
end
end
end
end
if matches[1]:lower() == 'plan' and matches[2] == '1' and matches[3] then
if string.match(matches[3], '^-%d+$') then
local timeplan1 = 2592000
redis:setex('ExpireDate:'..matches[3], timeplan1, true)
if not redis:get('CheckExpire::'..msg.to.id) then
redis:set('CheckExpire::'..msg.to.id,true)
end
if lang then
tdcli.sendMessage(SUDO, msg.id_, 1, 'پلن 1 با موفقیت برای گروه '..matches[3]..' فعال شد\nاین گروه تا 30 روز دیگر اعتبار دارد! ( 1 ماه )', 1, 'md')
tdcli.sendMessage(matches[3], 0, 1, '_ربات با موفقیت فعال شد و تا 30 روز دیگر اعتبار دارد!_', 1, 'md')
else
tdcli.sendMessage(SUDO, msg.id_, 1, '*Plan 1 Successfully Activated!\nThis group recharged with plan 1 for 30 days (1 Month)*', 1, 'md')
tdcli.sendMessage(matches[3], 0, 1, '*Successfully recharged*\n*Expire Date:* `30` *Days (1 Month)*', 1, 'md')
end
end
end
if matches[1]:lower() == 'plan' and matches[2] == '2' and matches[3] then
if string.match(matches[3], '^-%d+$') then
local timeplan2 = 7776000
redis:setex('ExpireDate:'..matches[3],timeplan2,true)
if not redis:get('CheckExpire::'..msg.to.id) then
redis:set('CheckExpire::'..msg.to.id,true)
end
if lang then
tdcli.sendMessage(SUDO, 0, 1, 'پلن 2 با موفقیت برای گروه '..matches[3]..' فعال شد\nاین گروه تا 90 روز دیگر اعتبار دارد! ( 3 ماه )', 1, 'md')
tdcli.sendMessage(matches[3], 0, 1, 'ربات با موفقیت فعال شد و تا 90 روز دیگر اعتبار دارد! ( 3 ماه )', 1, 'md')
else
tdcli.sendMessage(SUDO, msg.id_, 1, '*Plan 2 Successfully Activated!\nThis group recharged with plan 2 for 90 days (3 Month)*', 1, 'md')
tdcli.sendMessage(matches[3], 0, 1, '*Successfully recharged*\n*Expire Date:* `90` *Days (3 Months)*', 1, 'md')
end
end
end
if matches[1]:lower() == 'plan' and matches[2] == '3' and matches[3] then
if string.match(matches[3], '^-%d+$') then
redis:set('ExpireDate:'..matches[3],true)
if not redis:get('CheckExpire::'..msg.to.id) then
redis:set('CheckExpire::'..msg.to.id,true)
end
if lang then
tdcli.sendMessage(SUDO, msg.id_, 1, 'پلن 3 با موفقیت برای گروه '..matches[3]..' فعال شد\nاین گروه به صورت نامحدود شارژ شد!', 1, 'md')
tdcli.sendMessage(matches[3], 0, 1, 'ربات بدون محدودیت فعال شد ! ( نامحدود )', 1, 'md')
else
tdcli.sendMessage(SUDO, msg.id_, 1, '*Plan 3 Successfully Activated!\nThis group recharged with plan 3 for unlimited*', 1, 'md')
tdcli.sendMessage(matches[3], 0, 1, '*Successfully recharged*\n*Expire Date:* `Unlimited`', 1, 'md')
end
end
end
if matches[1]:lower() == 'jointo' and matches[2] then
if string.match(matches[2], '^-%d+$') then
if lang then
tdcli.sendMessage(SUDO, msg.id_, 1, 'با موفقیت تورو به گروه '..matches[2]..' اضافه کردم.', 1, 'md')
tdcli.addChatMember(matches[2], SUDO, 0, dl_cb, nil)
tdcli.sendMessage(matches[2], 0, 1, '_سودو به گروه اضافه شد._', 1, 'md')
else
tdcli.sendMessage(SUDO, msg.id_, 1, '*I added you to this group:*\n\n`'..matches[2]..'`', 1, 'md')
tdcli.addChatMember(matches[2], SUDO, 0, dl_cb, nil)
tdcli.sendMessage(matches[2], 0, 1, 'Admin Joined!', 1, 'md')
end
end
end
end
if matches[1]:lower() == 'savefile' and matches[2] and is_sudo(msg) then
if msg.reply_id then
local folder = matches[2]
function get_filemsg(arg, data)
function get_fileinfo(arg,data)
if data.content_.ID == 'MessageDocument' or data.content_.ID == 'MessagePhoto' or data.content_.ID == 'MessageSticker' or data.content_.ID == 'MessageAudio' or data.content_.ID == 'MessageVoice' or data.content_.ID == 'MessageVideo' or data.content_.ID == 'MessageAnimation' then
if data.content_.ID == 'MessageDocument' then
local doc_id = data.content_.document_.document_.id_
local filename = data.content_.document_.file_name_
local pathf = tcpath..'/data/document/'..filename
local cpath = tcpath..'/data/document'
if file_exi(filename, cpath) then
local pfile = folder
os.rename(pathf, pfile)
file_dl(doc_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>فایل</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>File</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
if data.content_.ID == 'MessagePhoto' then
local photo_id = data.content_.photo_.sizes_[2].photo_.id_
local file = data.content_.photo_.id_
local pathf = tcpath..'/data/photo/'..file..'_(1).jpg'
local cpath = tcpath..'/data/photo'
if file_exi(file..'_(1).jpg', cpath) then
local pfile = folder
os.rename(pathf, pfile)
file_dl(photo_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>عکس</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Photo</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
if data.content_.ID == 'MessageSticker' then
local stpath = data.content_.sticker_.sticker_.path_
local sticker_id = data.content_.sticker_.sticker_.id_
local secp = tostring(tcpath)..'/data/sticker/'
local ffile = string.gsub(stpath, '-', '')
local fsecp = string.gsub(secp, '-', '')
local name = string.gsub(ffile, fsecp, '')
if file_exi(name, secp) then
local pfile = folder
os.rename(stpath, pfile)
file_dl(sticker_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>استیکر</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Sticker</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
if data.content_.ID == 'MessageAudio' then
local audio_id = data.content_.audio_.audio_.id_
local audio_name = data.content_.audio_.file_name_
local pathf = tcpath..'/data/audio/'..audio_name
local cpath = tcpath..'/data/audio'
if file_exi(audio_name, cpath) then
local pfile = folder
os.rename(pathf, pfile)
file_dl(audio_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>صدای</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Audio</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
if data.content_.ID == 'MessageVoice' then
local voice_id = data.content_.voice_.voice_.id_
local file = data.content_.voice_.voice_.path_
local secp = tostring(tcpath)..'/data/voice/'
local ffile = string.gsub(file, '-', '')
local fsecp = string.gsub(secp, '-', '')
local name = string.gsub(ffile, fsecp, '')
if file_exi(name, secp) then
local pfile = folder
os.rename(file, pfile)
file_dl(voice_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>صوت</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Voice</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
if data.content_.ID == 'MessageVideo' then
local video_id = data.content_.video_.video_.id_
local file = data.content_.video_.video_.path_
local secp = tostring(tcpath)..'/data/video/'
local ffile = string.gsub(file, '-', '')
local fsecp = string.gsub(secp, '-', '')
local name = string.gsub(ffile, fsecp, '')
if file_exi(name, secp) then
local pfile = folder
os.rename(file, pfile)
file_dl(video_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>ویديو</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Video</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
if data.content_.ID == 'MessageAnimation' then
local anim_id = data.content_.animation_.animation_.id_
local anim_name = data.content_.animation_.file_name_
local pathf = tcpath..'/data/animation/'..anim_name
local cpath = tcpath..'/data/animation'
if file_exi(anim_name, cpath) then
local pfile = folder
os.rename(pathf, pfile)
file_dl(anim_id)
if lang then
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>تصویر متحرک</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Gif</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
end
end
else
return
end
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, get_fileinfo, nil)
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, get_filemsg, nil)
end
end
if msg.to.type == 'channel' or msg.to.type == 'chat' then
if matches[1] == 'charge' and matches[2] and not matches[3] and is_sudo(msg) then
if tonumber(matches[2]) > 0 and tonumber(matches[2]) < 1001 then
local extime = (tonumber(matches[2]) * 86400)
redis:setex('ExpireDate:'..msg.to.id, extime, true)
if not redis:get('CheckExpire::'..msg.to.id) then
redis:set('CheckExpire::'..msg.to.id)
end
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, 'ربات با موفقیت تنظیم شد\nمدت فعال بودن ربات در گروه به '..matches[2]..' روز دیگر تنظیم شد...', 1, 'md')
tdcli.sendMessage(SUDO, 0, 1, 'ربات در گروه '..matches[2]..' به مدت `'..msg.to.id..'` روز تمدید گردید.', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, 'ربات با موفقیت تنظیم شد\nمدت فعال بودن ربات در گروه به '..matches[2]..' روز دیگر تنظیم شد...', 1, 'md')
tdcli.sendMessage(SUDO, 0, 1, 'ربات در گروه '..matches[2]..' به مدت `'..msg.to.id..'` روز تمدید گردید.', 1, 'md')
end
else
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_تعداد روزها باید عددی از 1 تا 1000 باشد._', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Expire days must be between 1 - 1000_', 1, 'md')
end
end
end
if matches[1]:lower() == 'check' and is_mod(msg) and not matches[2] then
local expi = redis:ttl('ExpireDate:'..msg.to.id)
if expi == -1 then
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_گروه به صورت نامحدود شارژ میباشد!_', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Unlimited Charging!_', 1, 'md')
end
else
local day = math.floor(expi / 86400) + 1
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, day..' روز تا اتما شارژ گروه باقی مانده است.', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '`'..day..'` *Day(s) remaining until Expire.*', 1, 'md')
end
end
end
if matches[1] == 'check' and is_mod(msg) and matches[2] then
if string.match(matches[2], '^-%d+$') then
local expi = redis:ttl('ExpireDate:'..matches[2])
if expi == -1 then
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_گروه به صورت نامحدود شارژ میباشد!_', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Unlimited Charging!_', 1, 'md')
end
else
local day = math.floor(expi / 86400 ) + 1
if lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, day..' روز تا اتمام شارژ گروه باقی مانده است.', 1, 'md')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '`'..day..'` *Day(s) remaining until Expire.*', 1, 'md')
end
end
end
end
end
if matches[1] == "adminprom" and is_sudo(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="adminprom"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="adminprom"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="adminprom"})
end
end
if matches[1] == "admindem" and is_sudo(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.to.id,cmd="admindem"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="admindem"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="admindem"})
end
end
if matches[1] == 'creategroup' and is_admin(msg) then
local text = matches[2]
tdcli.createNewGroupChat({[0] = msg.from.id}, text, dl_cb, nil)
if not lang then
return '_Group Has Been Created!_'
else
return '_گروه ساخته شد!_'
end
end
if matches[1] == 'createsuper' and is_admin(msg) then
local text = matches[2]
tdcli.createNewChannelChat(text, 1, '', dl_cb, nil)
if not lang then
return '_SuperGroup Has Been Created!_'
else
return '_سوپر گروه ساخته شد!_'
end
end
if matches[1] == 'tosuper' and is_admin(msg) then
local id = msg.to.id
tdcli.migrateGroupChatToChannelChat(id, dl_cb, nil)
if not lang then
return '_Group Has Been Changed To SuperGroup!_'
else
return '_گروه به سوپر گروه تبدیل شد!_'
end
end
if matches[1] == 'import' and is_admin(msg) then
tdcli.importChatInviteLink(matches[2])
if not lang then
return '*Done!*'
else
return '*انجام شد!*'
end
end
if matches[1] == 'setbotname' and is_sudo(msg) then
tdcli.changeName(matches[2])
if not lang then
return '_Bot Name Changed To:_ *'..matches[2]..'*'
else
return '_اسم ربات تغییر کرد به:_ \n*'..matches[2]..'*'
end
end
if matches[1] == 'setbotusername' and is_sudo(msg) then
tdcli.changeUsername(matches[2])
if not lang then
return '_Bot Username Changed To:_ @'..matches[2]
else
return '_یوزرنیم ربات تغییر کرد به:_ \n@'..matches[2]..''
end
end
if matches[1] == 'delbotusername' and is_sudo(msg) then
tdcli.changeUsername('')
if not lang then
return '*Done!*'
else
return '*انجام شد!*'
end
end
if matches[1] == 'markread' and is_sudo(msg) then
if matches[2] == 'on' then
redis:set('markread','on')
if not lang then
return '_Markread >_ *ON*'
else
return '_تیک دوم >_ *روشن*'
end
end
if matches[2] == 'off' then
redis:set('markread','off')
if not lang then
return '_Markread >_ *OFF*'
else
return '_تیک دوم >_ *خاموش*'
end
end
end
if matches[1] == 'bc' and is_admin(msg) then
local text = matches[2]
tdcli.sendMessage(matches[3], 0, 0, text, 0) end
if matches[1] == 'broadcast' and is_sudo(msg) then
local data = load_data(_config.moderation.data)
local bc = matches[2]
for k,v in pairs(data) do
tdcli.sendMessage(k, 0, 0, bc, 0)
end
end
if is_sudo(msg) then
if matches[1]:lower() == "sendfile" and matches[2] and
matches[3] then
local send_file =
"./"..matches[2].."/"..matches[3]
tdcli.sendDocument(msg.chat_id_, msg.id_,0,
1, nil, send_file, '@BeyondTeam', dl_cb, nil)
end
if matches[1]:lower() == "sendplug" and matches[2] then
local plug = "./plugins/"..matches[2]..".lua"
tdcli.sendDocument(msg.chat_id_, msg.id_,0,
1, nil, plug, '@BeyondTeam', dl_cb, nil)
end
end
if matches[1]:lower() == 'save' and matches[2] and is_sudo(msg) then
if tonumber(msg.reply_to_message_id_) ~= 0 then
function get_filemsg(arg, data)
function get_fileinfo(arg,data)
if data.content_.ID == 'MessageDocument' then
fileid = data.content_.document_.document_.id_
filename = data.content_.document_.file_name_
if (filename:lower():match('.lua$')) then
local pathf = tcpath..'/data/document/'..filename
if pl_exi(filename) then
local pfile = 'plugins/'..matches[2]..'.lua'
os.rename(pathf, pfile)
tdcli.downloadFile(fileid , dl_cb, nil)
tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Plugin</b> <code>'..matches[2]..'</code> <b>Has Been Saved.</b>', 1, 'html')
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md')
end
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file is not Plugin File._', 1, 'md')
end
else
return
end
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, get_fileinfo, nil)
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, get_filemsg, nil)
end
end
if matches[1] == 'sudolist' and is_sudo(msg) then
return sudolist(msg)
end
if matches[1] == 'chats' and is_admin(msg) then
return chat_list(msg)
end
if matches[1]:lower() == 'join' and is_admin(msg) and matches[2] then
tdcli.sendMessage(msg.to.id, msg.id, 1, 'I Invite you in '..matches[2]..'', 1, 'html')
tdcli.sendMessage(matches[2], 0, 1, "Admin Joined!🌚", 1, 'html')
tdcli.addChatMember(matches[2], msg.from.id, 0, dl_cb, nil)
end
if matches[1] == 'rem' and matches[2] and is_admin(msg) then
local data = load_data(_config.moderation.data)
-- Group configuration removal
data[tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
tdcli.sendMessage(matches[2], 0, 1, "Group has been removed by admin command", 1, 'html')
return '_Group_ *'..matches[2]..'* _removed_'
end
if matches[1] == 'beyond' then
return tdcli.sendMessage(msg.to.id, msg.id, 1, _config.info_text, 1, 'html')
end
if matches[1] == 'adminlist' and is_admin(msg) then
return adminlist(msg)
end
if matches[1] == 'leave' and is_admin(msg) then
tdcli.changeChatMemberStatus(msg.to.id, our_id, 'Left', dl_cb, nil)
end
if matches[1] == 'autoleave' and is_admin(msg) then
local hash = 'auto_leave_bot'
--Enable Auto Leave
if matches[2] == 'enable' then
redis:del(hash)
return 'Auto leave has been enabled'
--Disable Auto Leave
elseif matches[2] == 'disable' then
redis:set(hash, true)
return 'Auto leave has been disabled'
--Auto Leave Status
elseif matches[2] == 'status' then
if not redis:get(hash) then
return 'Auto leave is enable'
else
return 'Auto leave is disable'
end
end
end
if matches[1] == "helptools" and is_mod(msg) then
if not lang then
text = [[
_Sudoer And Admins Bot Help :_
*!visudo* `[username|id|reply]`
_Add Sudo_
*!desudo* `[username|id|reply]`
_Demote Sudo_
*!sudolist *
_Sudo(s) list_
*!adminprom* `[username|id|reply]`
_Add admin for bot_
*!admindem* `[username|id|reply]`
_Demote bot admin_
*!adminlist *
_Admin(s) list_
*!leave *
_Leave current group_
*!autoleave* `[disable/enable]`
_Automatically leaves group_
*!creategroup* `[text]`
_Create normal group_
*!createsuper* `[text]`
_Create supergroup_
*!tosuper *
_Convert to supergroup_
*!chats*
_List of added groups_
*!join* `[id]`
_Adds you to the group_
*!rem* `[id]`
_Remove a group from Database_
*!import* `[link]`
_Bot joins via link_
*!setbotname* `[text]`
_Change bot's name_
*!setbotusername* `[text]`
_Change bot's username_
*!delbotusername *
_Delete bot's username_
*!markread* `[off/on]`
_Second mark_
*!broadcast* `[text]`
_Send message to all added groups_
*!bc* `[text] [gpid]`
_Send message to a specific group_
*!sendfile* `[folder] [file]`
_Send file from folder_
*!sendplug* `[plug]`
_Send plugin_
*!save* `[plugin name] [reply]`
_Save plugin by reply_
*!savefile* `[address/filename] [reply]`
_Save File by reply to specific folder_
*!clear cache*
_Clear All Cache Of .telegram-cli/data_
*!check*
_Stated Expiration Date_
*!check* `[GroupID]`
_Stated Expiration Date Of Specific Group_
*!charge* `[GroupID]` `[Number Of Days]`
_Set Expire Time For Specific Group_
*!charge* `[Number Of Days]`
_Set Expire Time For Group_
*!jointo* `[GroupID]`
_Invite You To Specific Group_
*!leave* `[GroupID]`
_Leave Bot From Specific Group_
_You can use_ *[!/#]* _at the beginning of commands._
`This help is only for sudoers/bot admins.`
*This means only the sudoers and its bot admins can use mentioned commands.*
*Good luck .*]]
tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'md')
else
text = [[
_راهنمای ادمین و سودو های ربات بیوند:_
*!visudo* `[username|id|reply]`
_اضافه کردن سودو_
*!desudo* `[username|id|reply]`
_حذف کردن سودو_
*!sudolist*
_لیست سودوهای ربات_
*!adminprom* `[username|id|reply]`
_اضافه کردن ادمین به ربات_
*!admindem* `[username|id|reply]`
_حذف فرد از ادمینی ربات_
*!adminlist*
_لیست ادمین ها_
*!leave*
_خارج شدن ربات از گروه_
*!autoleave* `[disable/enable]`
_خروج خودکار_
*!creategroup* `[text]`
_ساخت گروه ریلم_
*!createsuper* `[text]`
_ساخت سوپر گروه_
*!tosuper*
_تبدیل به سوپر گروه_
*!chats*
_لیست گروه های مدیریتی ربات_
*!join* `[id]`
_جوین شدن توسط ربات_
*!rem* `[id]`
_حذف گروه ازطریق پنل مدیریتی_
*!import* `[link]`
_جوین شدن ربات توسط لینک_
*!setbotname* `[text]`
_تغییر اسم ربات_
*!setbotusername* `[text]`
_تغییر یوزرنیم ربات_
*!delbotusername*
_پاک کردن یوزرنیم ربات_
*!markread* `[off/on]`
_تیک دوم_
*!broadcast* `[text]`
_فرستادن پیام به تمام گروه های مدیریتی ربات_
*!bc* `[text]` `[gpid]`
_ارسال پیام مورد نظر به گروه خاص_
*!sendfile* `[cd]` `[file]`
_ارسال فایل موردنظر از پوشه خاص_
*!sendplug* `[plug]`
_ارسال پلاگ مورد نظر_
*!save* `[plugin name] [reply]`
_ذخیره کردن پلاگین_
*!savefile* `[address/filename] [reply]`
_ذخیره کردن فایل در پوشه مورد نظر_
*!clear cache*
_پاک کردن کش مسیر .telegram-cli/data_
*!check*
_اعلام تاریخ انقضای گروه_
*!check* `[GroupID]`
_اعلام تاریخ انقضای گروه مورد نظر_
*!charge* `[GroupID]` `[Number Of Days]`
_تنظیم تاریخ انقضای گروه مورد نظر_
*!charge* `[Number Of Days]`
_تنظیم تاریخ انقضای گروه_
*!jointo* `[GroupID]`
_دعوت شدن شما توسط ربات به گروه مورد نظر_
*!leave* `[GroupID]`
_خارج شدن ربات از گروه مورد نظر_
*شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید*
_این راهنما فقط برای سودو ها/ادمین های ربات میباشد!_
`این به این معناست که فقط سودو ها/ادمین های ربات میتوانند از دستورات بالا استفاده کنند!`
*موفق باشید .*]]
tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'md')
end
end
end
return {
patterns = {
"^[!/#](helptools)$",
"^[!/#](visudo)$",
"^[!/#](desudo)$",
"^[!/#](sudolist)$",
"^[!/#](visudo) (.*)$",
"^[!/#](desudo) (.*)$",
"^[!/#](adminprom)$",
"^[!/#](admindem)$",
"^[!/#](adminlist)$",
"^[!/#](adminprom) (.*)$",
"^[!/#](admindem) (.*)$",
"^[!/#](leave)$",
"^[!/#](autoleave) (.*)$",
"^[!/#](beyond)$",
"^[!/#](creategroup) (.*)$",
"^[!/#](createsuper) (.*)$",
"^[!/#](tosuper)$",
"^[!/#](chats)$",
"^[!/#](clear cache)$",
"^[!/#](join) (.*)$",
"^[!/#](rem) (.*)$",
"^[!/#](import) (.*)$",
"^[!/#](setbotname) (.*)$",
"^[!/#](setbotusername) (.*)$",
"^[!/#](delbotusername) (.*)$",
"^[!/#](markread) (.*)$",
"^[!/#](bc) +(.*) (.*)$",
"^[!/#](broadcast) (.*)$",
"^[!/#](sendfile) (.*) (.*)$",
"^[!/#](save) (.*)$",
"^[!/#](sendplug) (.*)$",
"^[!/#](savefile) (.*)$",
"^[!/#]([Aa]dd)$",
"^[!/#]([Gg]id)$",
"^[!/#]([Cc]heck)$",
"^[!/#]([Cc]heck) (.*)$",
"^[!/#]([Cc]harge) (.*) (%d+)$",
"^[!/#]([Cc]harge) (%d+)$",
"^[!/#]([Jj]ointo) (.*)$",
"^[!/#]([Ll]eave) (.*)$",
"^[!/#]([Pp]lan) ([123]) (.*)$",
"^[!/#]([Rr]em)$",
},
run = run, pre_process = pre_process
}
| gpl-3.0 |
pSyChOoOo/TeleSeed | .luarocks/share/lua/5.2/luarocks/loader.lua | 20 | 8685 |
--- A module which installs a Lua package loader that is LuaRocks-aware.
-- This loader uses dependency information from the LuaRocks tree to load
-- correct versions of modules. It does this by constructing a "context"
-- table in the environment, which records which versions of packages were
-- used to load previous modules, so that the loader chooses versions
-- that are declared to be compatible with the ones loaded earlier.
local loaders = package.loaders or package.searchers
local package, require, ipairs, pairs, table, type, next, tostring, error =
package, require, ipairs, pairs, table, type, next, tostring, error
local unpack = unpack or table.unpack
--module("luarocks.loader")
local loader = {}
package.loaded["luarocks.loader"] = loader
local cfg = require("luarocks.cfg")
cfg.init_package_paths()
local path = require("luarocks.path")
local manif_core = require("luarocks.manif_core")
local deps = require("luarocks.deps")
loader.context = {}
-- Contains a table when rocks trees are loaded,
-- or 'false' to indicate rocks trees failed to load.
-- 'nil' indicates rocks trees were not attempted to be loaded yet.
loader.rocks_trees = nil
local function load_rocks_trees()
local any_ok = false
local trees = {}
for _, tree in ipairs(cfg.rocks_trees) do
local manifest, err = manif_core.load_local_manifest(path.rocks_dir(tree))
if manifest then
any_ok = true
table.insert(trees, {tree=tree, manifest=manifest})
end
end
if not any_ok then
loader.rocks_trees = false
return false
end
loader.rocks_trees = trees
return true
end
--- Process the dependencies of a package to determine its dependency
-- chain for loading modules.
-- @param name string: The name of an installed rock.
-- @param version string: The version of the rock, in string format
function loader.add_context(name, version)
-- assert(type(name) == "string")
-- assert(type(version) == "string")
if loader.context[name] then
return
end
loader.context[name] = version
if not loader.rocks_trees and not load_rocks_trees() then
return nil
end
for _, tree in ipairs(loader.rocks_trees) do
local manifest = tree.manifest
local pkgdeps
if manifest.dependencies and manifest.dependencies[name] then
pkgdeps = manifest.dependencies[name][version]
end
if not pkgdeps then
return nil
end
for _, dep in ipairs(pkgdeps) do
local pkg, constraints = dep.name, dep.constraints
for _, tree in ipairs(loader.rocks_trees) do
local entries = tree.manifest.repository[pkg]
if entries then
for version, pkgs in pairs(entries) do
if (not constraints) or deps.match_constraints(deps.parse_version(version), constraints) then
loader.add_context(pkg, version)
end
end
end
end
end
end
end
--- Internal sorting function.
-- @param a table: A provider table.
-- @param b table: Another provider table.
-- @return boolean: True if the version of a is greater than that of b.
local function sort_versions(a,b)
return a.version > b.version
end
--- Request module to be loaded through other loaders,
-- once the proper name of the module has been determined.
-- For example, in case the module "socket.core" has been requested
-- to the LuaRocks loader and it determined based on context that
-- the version 2.0.2 needs to be loaded and it is not the current
-- version, the module requested for the other loaders will be
-- "socket.core_2_0_2".
-- @param module The module name requested by the user, such as "socket.core"
-- @param name The rock name, such as "luasocket"
-- @param version The rock version, such as "2.0.2-1"
-- @param module_name The actual module name, such as "socket.core" or "socket.core_2_0_2".
-- @return table or (nil, string): The module table as returned by some other loader,
-- or nil followed by an error message if no other loader managed to load the module.
local function call_other_loaders(module, name, version, module_name)
for i, a_loader in ipairs(loaders) do
if a_loader ~= loader.luarocks_loader then
local results = { a_loader(module_name) }
if type(results[1]) == "function" then
return unpack(results)
end
end
end
return "Failed loading module "..module.." in LuaRocks rock "..name.." "..version
end
--- Search for a module in the rocks trees
-- @param module string: module name (eg. "socket.core")
-- @param filter_module_name function(string, string, string, string, number):
-- a function that takes the module name (eg "socket.core"), the rock name
-- (eg "luasocket"), the version (eg "2.0.2-1"), the path of the rocks tree
-- (eg "/usr/local"), and the numeric index of the matching entry, so the
-- filter function can know if the matching module was the first entry or not.
-- @return string, string, string, (string or table):
-- * name of the rock containing the module (eg. "luasocket")
-- * version of the rock (eg. "2.0.2-1")
-- * name of the module (eg. "socket.core", or "socket.core_2_0_2" if file is stored versioned).
-- * tree of the module (string or table in `rocks_trees` format)
local function select_module(module, filter_module_name)
--assert(type(module) == "string")
--assert(type(filter_module_name) == "function")
if not loader.rocks_trees and not load_rocks_trees() then
return nil
end
local providers = {}
for _, tree in ipairs(loader.rocks_trees) do
local entries = tree.manifest.modules[module]
if entries then
for i, entry in ipairs(entries) do
local name, version = entry:match("^([^/]*)/(.*)$")
local module_name = tree.manifest.repository[name][version][1].modules[module]
if type(module_name) ~= "string" then
error("Invalid data in manifest file for module "..tostring(module).." (invalid data for "..tostring(name).." "..tostring(version)..")")
end
module_name = filter_module_name(module_name, name, version, tree.tree, i)
if loader.context[name] == version then
return name, version, module_name
end
version = deps.parse_version(version)
table.insert(providers, {name = name, version = version, module_name = module_name, tree = tree})
end
end
end
if next(providers) then
table.sort(providers, sort_versions)
local first = providers[1]
return first.name, first.version.string, first.module_name, first.tree
end
end
--- Search for a module
-- @param module string: module name (eg. "socket.core")
-- @return string, string, string, (string or table):
-- * name of the rock containing the module (eg. "luasocket")
-- * version of the rock (eg. "2.0.2-1")
-- * name of the module (eg. "socket.core", or "socket.core_2_0_2" if file is stored versioned).
-- * tree of the module (string or table in `rocks_trees` format)
local function pick_module(module)
return
select_module(module, function(module_name, name, version, tree, i)
if i > 1 then
module_name = path.versioned_name(module_name, "", name, version)
end
module_name = path.path_to_module(module_name)
return module_name
end)
end
--- Return the pathname of the file that would be loaded for a module.
-- @param module string: module name (eg. "socket.core")
-- @return string: filename of the module (eg. "/usr/local/lib/lua/5.1/socket/core.so")
function loader.which(module)
local name, version, module_name = select_module(module, path.which_i)
return module_name
end
--- Package loader for LuaRocks support.
-- A module is searched in installed rocks that match the
-- current LuaRocks context. If module is not part of the
-- context, or if a context has not yet been set, the module
-- in the package with the highest version is used.
-- @param module string: The module name, like in plain require().
-- @return table: The module table (typically), like in plain
-- require(). See <a href="http://www.lua.org/manual/5.1/manual.html#pdf-require">require()</a>
-- in the Lua reference manual for details.
function loader.luarocks_loader(module)
local name, version, module_name = pick_module(module)
if not name then
return "No LuaRocks module found for "..module
else
loader.add_context(name, version)
return call_other_loaders(module, name, version, module_name)
end
end
table.insert(loaders, 1, loader.luarocks_loader)
return loader
| gpl-2.0 |
dacrybabysuck/darkstar | scripts/zones/Windurst_Waters/Zone.lua | 9 | 2599 | -----------------------------------
--
-- Zone: Windurst_Waters (238)
--
-----------------------------------
local ID = require("scripts/zones/Windurst_Waters/IDs");
require("scripts/globals/events/harvest_festivals");
require("scripts/globals/conquest");
require("scripts/globals/missions");
require("scripts/globals/settings");
require("scripts/globals/zone");
-----------------------------------
function onInitialize(zone)
-- Check if we are on Windurst Mission 1-3
zone:registerRegion(1, 23,-12,-208, 31,-8,-197);
applyHalloweenNpcCostumes(zone:getID())
end;
function onZoneIn(player,prevZone)
local cs = -1;
-- FIRST LOGIN (START CS)
if (player:getPlaytime(false) == 0) then
if (OPENING_CUTSCENE_ENABLE == 1) then
cs = 531;
end
player:setPos(-40,-5,80,64);
player:setHomePoint();
end
-- MOG HOUSE EXIT
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
position = math.random(1,5) + 157;
player:setPos(position,-5,-62,192);
if (player:getMainJob() ~= player:getCharVar("PlayerMainJob")) then
cs = 30004;
end
player:setCharVar("PlayerMainJob",0);
end
if (player:getCurrentMission(COP) == dsp.mission.id.cop.THE_ROAD_FORKS and player:getCharVar("MEMORIES_OF_A_MAIDEN_Status") == 1) then -- COP MEMORIES_OF_A_MAIDEN--3-3B: Windurst Route
player:setCharVar("MEMORIES_OF_A_MAIDEN_Status",2);
cs = 871;
end
return cs;
end;
function onConquestUpdate(zone, updatetype)
dsp.conq.onConquestUpdate(zone, updatetype)
end;
function onRegionEnter(player,region)
switch (region:GetRegionID()): caseof
{
[1] = function (x) -- Windurst Mission 1-3, final cutscene with Leepe-Hoppe
-- If we're on Windurst Mission 1-3
if (player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.THE_PRICE_OF_PEACE and player:getCharVar("MissionStatus") == 2) then
player:startEvent(146);
end
end,
}
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 531) then
player:messageSpecial(ID.text.ITEM_OBTAINED, 536);
elseif (csid == 30004 and option == 0) then
player:setHomePoint();
player:messageSpecial(ID.text.HOMEPOINT_SET);
elseif (csid == 146) then -- Returned from Giddeus, Windurst 1-3
player:setCharVar("MissionStatus", 3);
player:setCharVar("ghoo_talk", 0);
player:setCharVar("laa_talk", 0);
end
end;
| gpl-3.0 |
dacrybabysuck/darkstar | scripts/zones/Halvung/mobs/Wheel_Wamoura.lua | 9 | 1248 | -----------------------------------
-- Area: Halvung
-- Mob: Wheel Wamoura
-- TODO: Damage resistances in streched and curled stances. Halting movement during stance change.
-----------------------------------
require("scripts/globals/status");
-----------------------------------
function onMobSpawn(mob)
mob:setLocalVar("formTime", os.time() + math.random(43,47));
end;
function onMobRoam(mob)
local roamTime = mob:getLocalVar("formTime");
if (mob:AnimationSub() == 0 and os.time() > roamTime) then
mob:AnimationSub(1);
mob:setLocalVar("formTime", os.time() + math.random(43,47));
elseif (mob:AnimationSub() == 1 and os.time() > roamTime) then
mob:AnimationSub(0);
mob:setLocalVar("formTime", os.time() + math.random(43,47));
end
end;
function onMobFight(mob,target)
local fightTime = mob:getLocalVar("formTime");
if (mob:AnimationSub() == 0 and os.time() > fightTime) then
mob:AnimationSub(1);
mob:setLocalVar("formTime", os.time() + math.random(43,47));
elseif (mob:AnimationSub() == 1 and os.time() > fightTime) then
mob:AnimationSub(0);
mob:setLocalVar("formTime", os.time() + math.random(43,47));
end
end;
function onMobDeath(mob)
end;
| gpl-3.0 |
dacrybabysuck/darkstar | scripts/zones/Arrapago_Reef/npcs/Cutter.lua | 9 | 3104 | -----------------------------------
-- Area: Arrapago Reef
-- NPC: Cutter
-- The ship for The Black Coffin Battle (TOAU-15)
-- !pos -462 -2 -394 54
-----------------------------------
local ID = require("scripts/zones/Arrapago_Reef/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
if player:getCurrentMission(TOAU) == dsp.mission.id.toau.THE_BLACK_COFFIN and player:hasKeyItem(dsp.ki.EPHRAMADIAN_GOLD_COIN) then
player:setLocalVar("theblackcoffinfight",1)
player:startEvent(221, 53, -6, 0, 99, 6, 0)
elseif player:hasKeyItem(dsp.ki.LIFE_FLOAT) and player:getCharVar("AgainstAllOdds") == 2 then
player:setLocalVar("againstalloddsfight",1)
player:startEvent(221, 54, -9, 0, 99, 6, 0)
else
player:messageSpecial(ID.text.YOU_NO_REQS)
end
end
function onEventUpdate(player,csid,option,target)
local party = player:getParty()
if player:getLocalVar("theblackcoffinfight") == 1 then
if party ~= nil then
for i,v in ipairs(party) do
if not v:hasKeyItem(dsp.ki.EPHRAMADIAN_GOLD_COIN) then
player:messageText(target,ID.text.MEMBER_NO_REQS, false)
player:instanceEntry(target,1)
return
elseif v:getZoneID() == player:getZoneID() and v:checkDistance(player) > 50 then
player:messageText(target,ID.text.MEMBER_TOO_FAR, false)
player:instanceEntry(target,1)
return
end
end
end
player:createInstance(53,60);
player:setLocalVar("theblackcoffinfight",0)
elseif player:getLocalVar("againstalloddsfight") == 1 then
if (party ~= nil) then
for i,v in ipairs(party) do
if v:getZoneID() == player:getZoneID() and v:checkDistance(player) > 50 then
player:messageText(target,ID.text.MEMBER_TOO_FAR, false)
player:instanceEntry(target,1)
return
end
end
end
player:createInstance(54,60)
player:setLocalVar("againstalloddsfight",0)
end
end
function onEventFinish(player,csid,option)
if (csid == 221 and option == 4) or csid == 90 then
player:setPos(0,0,0,0,60)
end
end
function onInstanceCreated(player,target,instance)
if (instance) then
player:setInstance(instance)
player:instanceEntry(target,4)
local party = player:getParty()
if (party ~= nil) then
for i,v in ipairs(party) do
if v:getID() ~= player:getID() and v:getZoneID() == player:getZoneID() then
v:setInstance(instance)
v:startEvent(90) -- wrong csid, yet better than nothing
end
end
end
else
player:messageText(target,ID.text.CANNOT_ENTER, false);
player:instanceEntry(target,3);
end
end | gpl-3.0 |
nimaghorbani/dozdi1 | bot/utils.lua | 356 | 14963 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has superuser privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has admins privileges
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has moderator privileges
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
-- Berfungsi utk mengecek user jika plugin moderated = true
if plugin.moderated and not is_momod(msg) then --Cek apakah user adalah momod
if plugin.moderated and not is_admin(msg) then -- Cek apakah user adalah admin
if plugin.moderated and not is_sudo(msg) then -- Cek apakah user adalah sudoers
return false
end
end
end
-- Berfungsi mengecek user jika plugin privileged = true
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end | gpl-2.0 |
andeandr100/Crumbled-World | Lua/Game/mapInfo.lua | 1 | 6267 | require("Game/campaignData.lua")
require("Menu/MainMenu/mapInformation.lua")
--this = SceneNode()
MapInfo = {}
function MapInfo.new()
local self = {}
local FIRSTTIMEVICTORYBONUS = 2
local FIRSTTIMEGAMEMODEVICTORYBONUS = 1
local BASEBONUS = 1
local billboard = false
local increasedDifficultyMax = 0.0
local increasedDifficultyMin = 0.0
function self.setLevel(level,notSave)
--1 = 0.70
--2 = 0.75
--3 = 0.80
--4 = 0.85
--5 = 0.90
local actualLevel = level
print("setLevel("..level..")\n")
-- if type(level)=="string" then
-- local difficult = {Easy=1,Normal=2,Hard=3,Extreme=4,Insane=5}--"Impossible #"
-- print("difficult = "..tostring(difficult).."\n")
-- if difficult[level] then
-- level = tonumber(difficult[level])
-- else
-- print("Imposible\n")
-- level = 5+tonumber(string.match(level, " (.*)"))
-- end
-- end
actualLevel = level
--balance difficulty to map
--increasedDifficultyMin
local addPerLevel = (increasedDifficultyMax-increasedDifficultyMin)/4.0
level = (level+increasedDifficultyMin)+(addPerLevel*(level-1))
--
print("setLevel == "..actualLevel..") == "..level.."\n")
billboard:setDouble("level",actualLevel)
billboard:setDouble("difficulty",0.75+((level-1)*0.055)) --start difficulty
billboard:setDouble("difficultIncreaser",1.0160+(level*0.00275)) --how fast the difficulty should accelerate
billboard:setInt("SpawnWindow",math.floor(2+(actualLevel*0.55))) --how many different npc group can be spawned
--
if billboard:exist("isCart")==false then
billboard:setBool("isCart",false)
end
end
function self.getReward()
local cData = CampaignData.new()
local reward = BASEBONUS+math.max(1,math.floor( (self.getLevel()*self.getWaveCount()+0.01)/25 ))
if cData.hasMapBeenBeaten(self.getMapNumber())==false then
reward = reward + FIRSTTIMEVICTORYBONUS
end
if cData.hasMapModeBeenBeaten( self.getMapNumber(), self.getGameMode() )==false then
reward = reward + FIRSTTIMEGAMEMODEVICTORYBONUS
end
return reward
end
function self.setIsCartMap(isCart)
print("setIsCartMap("..tostring(isCart)..")\n")
billboard:setBool("isCart",isCart)
end
function self.setChangedDifficultyMax(amount)
amount = amount or 0
increasedDifficultyMax = amount
self.setLevel(billboard:getDouble("level"))
end
function self.setChangedDifficultyMin(amount)
amount = amount or 0
increasedDifficultyMin = amount
self.setLevel(billboard:getDouble("level"))
end
function self.setIsCampaign(mode)
billboard:setBool("isCampaign",mode)
end
function self.setGameMode(mode)
billboard:setString("GameMode",mode)
end
function self.setTowerSettings(tab)
billboard:setTable("TowerSettings",tab)
end
function self.setMapFileName(mapFileName)
if mapFileName then
billboard:setString("mapFileName",mapFileName)
end
end
function self.setMapName(mapName)
if mapName then
billboard:setString("mapName",mapName)
end
end
function self.setMapNumber(num)
billboard:setInt("mapNumber",tonumber(num))
end
function self.setWaveCount(num)
billboard:setInt("waveCount",tonumber(num))
end
function self.setPlayerCount(num)
billboard:setInt("PlayerCount",tonumber(num))
end
function self.setSead(num)
billboard:setInt("sead",tonumber(num))
end
--
function self.getIncreasedDifficultyMax()
return increasedDifficultyMax
end
function self.getLevel()
return billboard:getDouble("level")
end
function self.getDifficulty()
return billboard:getDouble("difficulty")
end
function self.getDifficultyIncreaser()
return billboard:getDouble("difficultIncreaser")
end
function self.getSpawnWindow()
return billboard:getDouble("SpawnWindow")
end
function self.getGameMode()
return billboard:getString("GameMode")
end
function self.getTowerSettings()
return billboard:getTable("TowerSettings")
end
function self.getMapFileName()
return billboard:getString("mapFileName")
end
function self.getMapName()
return billboard:getString("mapName")
end
function self.getMapNumber()
return math.max(1,billboard:getInt("mapNumber"))
end
function self.isCampaign()
return billboard:getBool("isCampaign")
end
function self.changeToNextMap()
local ret = false
if self.isCampaign() then
local cData = CampaignData.new()
if self.getMapNumber()<cData.getMapCount() then
local mapNum = self.getMapNumber() + 1
local fileTab = cData.getMaps()[mapNum]
local mapFile = fileTab.file
self.setMapNumber(mapNum)
self.setSead(fileTab.sead)
self.setMapFileName(mapFile:getPath())
self.setMapName(mapFile:getName())
if mapFile:isFile() then
local mapInfo = MapInformation.getMapInfoFromFileName(mapFile:getName(), mapFile:getPath())
if mapInfo then
self.setIsCartMap(mapInfo.gameMode=="Cart")
self.setChangedDifficultyMax(mapInfo.difficultyIncreaseMax)
self.setChangedDifficultyMin(mapInfo.difficultyIncreaseMin)
self.setWaveCount(mapInfo.waveCount)
--
ret = true
end
end
end
end
return ret
end
function self.isCartMap()
return billboard:getBool("isCart")
end
function self.getStartWave()
return self.getGameMode()=="training" and self.getWaveCount()-5 or 0
end
function self.getWaveCount()
return billboard:getInt("waveCount")
end
function self.getPlayerCount()
return math.max(1, billboard:getInt("PlayerCount"))
end
function self.getSead()
if billboard:exist("sead") then
return billboard:getInt("sead")
end
return math.randomInt(0,2147483647)
end
--
function self.changeDifficultyIncreaser(byPer)
if byPer<0.0 then
local val = billboard:getDouble("difficultIncreaser")-1.0
billboard:setDouble("difficultIncreaser", 1.0 + ((-byPer)*val) )
else
local val = billboard:getDouble("difficultIncreaser")-1.0
billboard:setDouble("difficultIncreaser", billboard:getDouble("difficultIncreaser") + ((byPer)*val) )
end
end
--
local function init()
billboard = Core.getGlobalBillboard("MapInfo")
if billboard:exist("difficulty")==false then
self.setLevel(2.0)
end
if billboard:exist("GameMode")==false then
billboard:setString("GameMode","Normal")
end
if billboard:exist("TowerSettings")==false then
billboard:setTable("TowerSettings",{})
end
end
init()
--
return self
end | mit |
eagle14/kia12 | plugins/vote.lua | 615 | 2128 | do
local _file_votes = './data/votes.lua'
function read_file_votes ()
local f = io.open(_file_votes, "r+")
if f == nil then
print ('Created voting file '.._file_votes)
serialize_to_file({}, _file_votes)
else
print ('Values loaded: '.._file_votes)
f:close()
end
return loadfile (_file_votes)()
end
function clear_votes (chat)
local _votes = read_file_votes ()
_votes [chat] = {}
serialize_to_file(_votes, _file_votes)
end
function votes_result (chat)
local _votes = read_file_votes ()
local results = {}
local result_string = ""
if _votes [chat] == nil then
_votes[chat] = {}
end
for user,vote in pairs (_votes[chat]) do
if (results [vote] == nil) then
results [vote] = user
else
results [vote] = results [vote] .. ", " .. user
end
end
for vote,users in pairs (results) do
result_string = result_string .. vote .. " : " .. users .. "\n"
end
return result_string
end
function save_vote(chat, user, vote)
local _votes = read_file_votes ()
if _votes[chat] == nil then
_votes[chat] = {}
end
_votes[chat][user] = vote
serialize_to_file(_votes, _file_votes)
end
function run(msg, matches)
if (matches[1] == "ing") then
if (matches [2] == "reset") then
clear_votes (tostring(msg.to.id))
return "Voting statistics reset.."
elseif (matches [2] == "stats") then
local votes_result = votes_result (tostring(msg.to.id))
if (votes_result == "") then
votes_result = "[No votes registered]\n"
end
return "Voting statistics :\n" .. votes_result
end
else
save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2])))
return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2]))
end
end
return {
description = "Plugin for voting in groups.",
usage = {
"!voting reset: Reset all the votes.",
"!vote [number]: Cast the vote.",
"!voting stats: Shows the statistics of voting."
},
patterns = {
"^!vot(ing) (reset)",
"^!vot(ing) (stats)",
"^!vot(e) ([0-9]+)$"
},
run = run
}
end | gpl-2.0 |
fiskio/dp | test/test.lua | 2 | 57387 | local mytester
local dptest = {}
function dptest.uid()
local uid1 = dp.uniqueID()
mytester:asserteq(type(uid1), 'string', 'type(uid1) == string')
local uid2 = dp.uniqueID()
local uid3 = dp.uniqueID('mynamespace')
mytester:assertne(uid1, uid2, 'uid1 ~= uid2')
mytester:assertne(uid2, uid3, 'uid2 ~= uid3')
end
function dptest.dataview()
local data = torch.rand(3,4)
local sizes = {3, 4}
local v = dp.DataView()
-- forward
v:forward('bf', data)
local f = v:forward('bf', 'torch.DoubleTensor')
mytester:asserteq(f:dim(),2)
mytester:assertTensorEq(f,data, 0.00001)
local f2 = v:forward('bf', 'torch.FloatTensor')
mytester:assertTensorEq(f:float(),f2, 0.00001)
-- backward
local g = f:clone()
g[1][1] = 0
local g2 = f2:clone()
g2[1][2] = 0
v:backward('bf', g)
v:backward('bf', g2)
local b = v:backward('bf', 'torch.DoubleTensor')
mytester:asserteq(b:dim(),2)
local r = g2:clone():double()
r:add(g)
mytester:assertTensorEq(b,r, 0.00001)
-- indexing
local indices = torch.LongTensor{2,3}
local v2 = v:index(indices)
mytester:assertTensorEq(v2:forward('bf', 'torch.DoubleTensor'), data:index(1, indices), 0.000001)
local v3 = dp.DataView()
v3:forward('bf', torch.zeros(8,4))
local v3 = v:index(v3, indices)
mytester:assertTensorEq(v2:forward('bf', 'torch.DoubleTensor'), v3:forward('bf', 'torch.DoubleTensor'), 0.0000001)
mytester:assertTensorEq(v3._input, v2:forward('bf', 'torch.DoubleTensor'), 0.0000001)
local v4 = v:index(nil, indices)
mytester:assertTensorEq(v4:forward('bf', 'torch.DoubleTensor'), v2:forward('bf', 'torch.DoubleTensor'), 0.0000001)
-- sub
local v5 = v:sub(2,3)
mytester:assertTensorEq(v2:forward('bf', 'torch.DoubleTensor'), v5:forward('bf', 'torch.DoubleTensor'), 0.000001)
local v6 = v:sub(nil, 2,3)
mytester:assertTensorEq(v2:forward('bf', 'torch.DoubleTensor'), v6:forward('bf', 'torch.DoubleTensor'), 0.000001)
v:sub(v6, 1, 2)
mytester:assertTensorEq(v6:forward('bf', 'torch.DoubleTensor'), data:sub(1,2), 0.000001)
end
function dptest.imageview()
local size = {8,32,32,3}
local feature_size = {8,32*32*3}
local data = torch.rand(unpack(size))
local v = dp.ImageView()
v:forward('bhwc', data)
-- convert to image (shouldn't change anything)
local i = v:forward('bhwc', 'torch.DoubleTensor')
mytester:assertTensorEq(i, data, 0.0001)
mytester:assertTableEq(i:size():totable(), size, 0.0001)
-- convert to feature (should colapse last dims)
local f = v:forward('bf', 'torch.DoubleTensor')
mytester:assertTableEq(f:size():totable(), feature_size, 0.0001)
mytester:assertTensorEq(f, data, 0.00001)
-- convert to image (shouldn't change anything)
local i2 = v:forward('bhwc', 'torch.DoubleTensor')
mytester:assertTensorEq(i2, data, 0.0001)
mytester:assertTableEq(i2:size():totable(), size, 0.0001)
-- convert to image bchw
local i3 = v:forward('bchw', 'torch.DoubleTensor')
mytester:assertTensorEq(i3, data:transpose(2,4):transpose(3,4), 0.0001)
mytester:assertTableEq(i3:size():totable(), {8,3,32,32}, 0.0001)
-- create from bchw
local v2 = dp.ImageView()
v2:forward('bchw', i3)
local i4 = v:forward('bhwc', 'torch.DoubleTensor')
mytester:assertTensorEq(i4, data, 0.0001)
mytester:assertTableEq(i4:size():totable(), size, 0.0001)
-- convert to bchw()
local i5 = v:forward('bchw', 'torch.DoubleTensor')
mytester:assertTensorEq(i5, data:transpose(2,4):transpose(3,4), 0.0001)
mytester:assertTableEq(i5:size():totable(), {8,3,32,32}, 0.0001)
-- indexing
local indices = torch.LongTensor{2,3}
local v3 = v:index(indices)
mytester:assertTensorEq(v3:forward('bf', 'torch.DoubleTensor'), data:reshape(unpack(feature_size)):index(1, indices), 0.000001)
local v4 = dp.ImageView()
v4:forward('bhwc', torch.zeros(2,32,32,3))
v:index(v4, indices)
mytester:assertTensorEq(v4:forward('bf', 'torch.DoubleTensor'), v3:forward('bf', 'torch.DoubleTensor'), 0.0000001)
mytester:assertTensorEq(v4._input, v3:forward('bhwc', 'torch.DoubleTensor'), 0.0000001)
local v5 = v:index(nil, indices)
mytester:assertTensorEq(v5:forward('bhwc', 'torch.DoubleTensor'), v._input:index(1, indices), 0.0000001)
end
function dptest.sequenceview()
local size = {8,10,50}
local feature_size = {8,10*50}
local data = torch.rand(unpack(size))
local v = dp.SequenceView()
v:forward('bwc', data)
-- convert to sequence (shouldn't change anything)
local s = v:forward('bwc', 'torch.DoubleTensor')
mytester:assertTensorEq(s, data, 0.0001)
mytester:assertTableEq(s:size():totable(), size, 0.0001)
-- convert to feature (should colapse last dims)
local f = v:forward('bf', 'torch.DoubleTensor')
mytester:assertTableEq(f:size():totable(), feature_size, 0.0001)
mytester:assertTensorEq(f, data, 0.00001)
-- convert to sequence (should expand last dim)
local s2 = v:forward('bwc', 'torch.DoubleTensor')
mytester:assertTensorEq(s2, data, 0.0001)
mytester:assertTableEq(s2:size():totable(), size, 0.0001)
-- indexing
local indices = torch.LongTensor{2,3}
local v2 = v:index(indices)
mytester:assertTensorEq(v2:forward('bf', 'torch.DoubleTensor'), data:reshape(unpack(feature_size)):index(1, indices), 0.000001)
local v3 = dp.SequenceView()
v3:forward('bwc', torch.zeros(8,10,50))
local v4 = v:index(v3, indices)
mytester:assertTensorEq(v4:forward('bf', 'torch.DoubleTensor'), v2:forward('bf', 'torch.DoubleTensor'), 0.0000001)
mytester:assertTensorEq(v2._input, v4:forward('bwc', 'torch.DoubleTensor'), 0.0000001)
local v5 = v:index(nil, indices)
mytester:assertTensorEq(v4:forward('bf', 'torch.DoubleTensor'), v5:forward('bf', 'torch.DoubleTensor'), 0.0000001)
end
function dptest.classview()
local size = {48,4}
local data = torch.rand(unpack(size))
local v = dp.ClassView()
v:forward('bt', data)
-- multiclass
local c = v:forward('bt', 'torch.DoubleTensor')
mytester:assertTableEq(c:size():totable(), size, 0.0001)
mytester:assertTensorEq(c, data, 0.00001)
local c2 = v:forward('b', 'torch.DoubleTensor')
mytester:asserteq(c2:dim(),1)
mytester:assertTableEq(c2:size(1), size[1], 0.0001)
mytester:assertTensorEq(c2, data:select(2,1), 0.00001)
-- indexing
local indices = torch.LongTensor{2,3}
local v2 = v:index(indices)
mytester:assertTensorEq(v2:forward('bt', 'torch.DoubleTensor'), data:index(1, indices), 0.000001)
local v3 = dp.ClassView()
v3:forward('bt', torch.zeros(8,4))
local v4 = v:index(v3, indices)
mytester:assertTensorEq(v4:forward('bt', 'torch.DoubleTensor'), v2:forward('bt', 'torch.DoubleTensor'), 0.0000001)
mytester:assertTensorEq(v3._input, v4:forward('bt', 'torch.DoubleTensor'), 0.0000001)
local v5 = v:index(nil, indices)
mytester:assertTensorEq(v5:forward('bt', 'torch.DoubleTensor'), v2:forward('bt', 'torch.DoubleTensor'), 0.0000001)
mytester:assertTableEq(v:classes(), v5:classes())
end
function dptest.listview()
-- image tensor
local image_size = {8,32,32,3}
local feature_size = {8,32*32*3}
local image_data = torch.rand(unpack(image_size))
local image_v = dp.ImageView()
-- data tensor
local data = torch.rand(8,4)
local data_v = dp.DataView()
-- composite tensor
local list_v = dp.ListView({image_v,data_v})
list_v:forward({'bhwc', 'bf'}, {image_data, data})
local t = list_v:forward('bf', 'torch.FloatTensor')
mytester:assertTableEq(t[1]:size():totable(), feature_size, 0.0001)
local list_v = dp.ListView({dp.ImageView(), dp.ImageView()})
list_v:forward('bhwc', {image_data, image_data:clone():add(1)})
local t = list_v:forward('bchw')
mytester:assertTensorEq(t[1], image_data:transpose(4,2):transpose(3,4), 0.00001)
local list = dp.ListView{dp.ImageView('bchw',torch.randn(1,2,3,4)), dp.ImageView('bchw',torch.randn(1,2,3,4))}
local t = list:forwardGet('bhwc')
mytester:assertTableEq(t[1]:size():totable(), {1,3,4,2}, 0.00001)
list:forwardPut('bhwc',{torch.randn(1,3,4,2),torch.randn(1,3,4,2)})
local t = list:forwardGet('bchw')
mytester:assertTableEq(t[1]:size():totable(), {1,2,3,4}, 0.00001)
-- indexing
local data1, data2 = torch.randn(5,2,3,4), torch.randn(5,2,3,4)
local v = dp.ListView{dp.ImageView('bchw',data1), dp.ImageView('bchw',data2)}
local indices = torch.LongTensor{2,3}
local v2 = v:index(indices)
local tbl = v2:forward('bchw', 'torch.DoubleTensor')
local tbl2 = {data1, data2}
mytester:assert(#tbl == 2)
for i, d in ipairs(tbl) do
mytester:assertTensorEq(d, tbl2[i]:index(1, indices), 0.000001)
end
local v3 = dp.ListView{dp.ImageView('bchw',torch.randn(1,2,3,4)), dp.ImageView('bchw',torch.randn(1,2,3,4))}
local v4 = v:index(v3, indices)
local tbl = v4:forward('bchw', 'torch.DoubleTensor')
mytester:assert(#tbl == 2)
for i, d in ipairs(tbl) do
mytester:assertTensorEq(d, tbl2[i]:index(1, indices), 0.000001)
end
-- sub
local v5 = v:sub(2,3)
local tbl = v5:forward('bchw', 'torch.DoubleTensor')
mytester:assert(#tbl == 2)
for i, d in ipairs(tbl) do
mytester:assertTensorEq(d, tbl2[i]:index(1, indices), 0.000001)
end
local v6 = v:sub(nil, 2,3)
local tbl = v6:forward('bchw', 'torch.DoubleTensor')
mytester:assert(#tbl == 2)
for i, d in ipairs(tbl) do
mytester:assertTensorEq(d, tbl2[i]:index(1, indices), 0.000001)
end
end
function dptest.carry()
local data = torch.rand(3,4)
local sizes = {3, 4}
local v = dp.DataView('bf', data)
local c = dp.Carry()
c:putView('data', v)
-- indexing
local indices = torch.LongTensor{2,3}
local c2 = c:index(indices)
local v2 = c2:getView('data')
mytester:assertTensorEq(v2:forward('bf', 'torch.DoubleTensor'), data:index(1, indices), 0.000001)
local c3 = dp.Carry()
c3:putView('data', dp.DataView('bf', torch.zeros(8,4)))
c:index(c3, indices)
local v3 = c3:getView('data')
mytester:assertTensorEq(v2:forward('bf', 'torch.DoubleTensor'), v3:forward('bf', 'torch.DoubleTensor'), 0.0000001)
mytester:assertTensorEq(v3._input, v2:forward('bf', 'torch.DoubleTensor'), 0.0000001)
local c4 = c:index(nil, indices)
local v4 = c4:getView('data')
mytester:assertTensorEq(v4:forward('bf', 'torch.DoubleTensor'), v2:forward('bf', 'torch.DoubleTensor'), 0.0000001)
-- sub
local c5 = c:sub(2,3)
local v5 = c5:getView('data')
mytester:assertTensorEq(v2:forward('bf', 'torch.DoubleTensor'), v5:forward('bf', 'torch.DoubleTensor'), 0.000001)
local c6 = c:sub(nil, 2,3)
local v6 = c6:getView('data')
mytester:assertTensorEq(v2:forward('bf', 'torch.DoubleTensor'), v6:forward('bf', 'torch.DoubleTensor'), 0.000001)
c:sub(c6, 1, 2)
mytester:assertTensorEq(v6:forward('bf', 'torch.DoubleTensor'), data:sub(1,2), 0.000001)
end
function dptest.dataset()
-- class tensor
local class_data = torch.randperm(8)
local classes = {1,2,3,4,5,6,7,8,9,10}
local class_v = dp.ClassView()
class_v:forward('b', class_data)
class_v:setClasses(classes)
-- image tensor
local image_data = torch.rand(8,32,32,3)
local image_v = dp.ImageView()
image_v:forward('bhwc', image_data)
-- dataset
local ds = dp.DataSet{which_set='train', inputs=image_v, targets=class_v}
local batch = ds:index(torch.LongTensor{1,2,3})
local batch2 = ds:sub(1, 3)
mytester:assertTensorEq(batch:inputs():forward('bhwc'), batch2:inputs():forward('bhwc'), 0.00001)
ds:index(batch2, torch.LongTensor{2,3,4})
local batch4 = ds:sub(2, 4)
mytester:assertTensorEq(batch4:inputs():forward('bhwc'), batch2:inputs():forward('bhwc'), 0.00001)
mytester:assertTensorEq(batch4:targets():forward('bt'), batch2:targets():forward('bt'), 0.00001)
mytester:assertTensorEq(batch4:targets():forward('bt'), ds:targets():forward('bt'):narrow(1,2,3), 0.00001)
local batch3 = ds:sub(nil, 2, 4)
mytester:assertTensorEq(batch3:inputs():forward('bhwc'), batch2:inputs():forward('bhwc'), 0.00001)
mytester:assertTensorEq(batch3:targets():forward('bt'), batch2:targets():forward('bt'), 0.00001)
ds:sub(batch3, 1, 3)
mytester:assertTensorEq(batch3:inputs():forward('bhwc'), batch:inputs():forward('bhwc'), 0.00001)
mytester:assertTensorEq(batch3:targets():forward('bt'), batch:targets():forward('bt'), 0.00001)
end
function dptest.sentenceset()
local tensor = torch.IntTensor(80, 2):zero()
for i=1,8 do
-- one sentence
local sentence = tensor:narrow(1, ((i-1)*10)+1, 10)
-- fill it with a sequence of words
sentence:select(2,2):copy(torch.randperm(17):sub(1,10))
-- fill it with start sentence delimiters
sentence:select(2,1):fill(((i-1)*10)+1)
end
tensor[tensor:size(1)][2] = 2 -- must finish with end_id
-- 18 words in vocabulary ("<S>" isn't found in tensor since its redundant to "</S>")
local words = {"</S>", "<UNK>", "the", "it", "is", "to", "view", "huh", "hi", "ho", "oh", "I", "you", "we", "see", "do", "have", "<S>"}
-- dataset
local ds = dp.SentenceSet{which_set='train', data=tensor, words=words, context_size=3, start_id=1, end_id=2}
local batch = ds:index(torch.LongTensor{1,2,3})
mytester:assertTableEq(batch:inputs():forward('bt'):size():totable(), {3, 3})
local batch2 = ds:sub(1, 3)
mytester:assertTensorEq(batch:inputs():forward('bt'), batch2:inputs():forward('bt'), 0.00001)
ds:index(batch2, torch.LongTensor{2,3,4})
local batch4 = ds:sub(2, 4)
mytester:assertTensorEq(batch4:inputs():forward('bt'), batch2:inputs():forward('bt'), 0.00001)
mytester:assertTensorEq(batch4:targets():forward('b'), batch2:targets():forward('b'), 0.00001)
mytester:assertTensorEq(batch4:targets():forward('b'), tensor:select(2,2):narrow(1,2,3), 0.00001)
local batch3 = ds:sub(nil, 2, 4)
mytester:assertTensorEq(batch3:inputs():forward('bt'), batch2:inputs():forward('bt'), 0.00001)
mytester:assertTensorEq(batch3:targets():forward('b'), batch2:targets():forward('b'), 0.00001)
ds:sub(batch3, 1, 3)
mytester:assertTensorEq(batch3:inputs():forward('bt'), batch:inputs():forward('bt'), 0.00001)
mytester:assertTensorEq(batch3:targets():forward('b'), batch:targets():forward('b'), 0.00001)
end
function dptest.gcn()
--[[ zero_vector ]]--
-- Global Contrast Normalization
-- Test that passing in the zero vector does not result in
-- a divide by 0 error
local dv = dp.DataView()
dv:forward('bf', torch.zeros(1,1))
local dataset = dp.DataSet{which_set='train', inputs=dv}
--std_bias = 0.0 is the only value for which there
--should be a risk of failure occurring
local preprocess = dp.GCN{sqrt_bias=0.0, use_std=true, progress=false}
dataset:preprocess{input_preprocess=preprocess}
local result = dataset:inputs():input():sum()
mytester:assert(not _.isNaN(result))
mytester:assert(_.isFinite(result))
--[[ unit_norm ]]--
-- Global Contrast Normalization
-- Test that using std_bias = 0.0 and use_norm = True
-- results in vectors having unit norm
local dv = dp.DataView('bf', torch.rand(3,9))
local dataset = dp.DataSet{which_set='train', inputs=dv}
local preprocess = dp.GCN{std_bias=0.0, use_std=false, progress=false}
dataset:preprocess{input_preprocess=preprocess}
local result = dataset:inputs():input()
local norms = torch.pow(result, 2):sum(2):sqrt()
local max_norm_error = torch.abs(norms:add(-1)):max()
mytester:assert(max_norm_error < 3e-5)
end
function dptest.zca()
-- Confirm that ZCA.inv_P_ is the correct inverse of ZCA._P.
local dv = dp.DataView('bf', torch.randn(15,10))
local dataset = dp.DataSet{which_set='train', inputs=dv}
local preprocess = dp.ZCA{compute_undo=true,progress=false}
dataset:preprocess{input_preprocess=preprocess}
local function is_identity(matrix)
local identity = torch.eye(matrix:size(1))
local abs_diff = torch.abs(identity:add(-matrix))
return (torch.lt(abs_diff,.00001):int():min() ~= 0)
end
local data = dataset:inputs():input()
mytester:assert(table.eq(preprocess._P:size():totable(),{data:size(2),data:size(2)}))
mytester:assert(not is_identity(preprocess._P))
mytester:assert(is_identity(preprocess._P*preprocess._inv_P))
end
function dptest.lecunlcn()
-- Test on a random image to confirm that it loads without error
-- and it doesn't result in any NaN or Inf values
local input_tensor = torch.randn(16, 3, 32, 32)
local input = dp.ImageView('bchw', input_tensor:clone())
local pp = dp.LeCunLCN{batch_size=5,progress=false}
pp:apply(input)
mytester:assert(_.isFinite(input:forward('default'):sum()), "LeCunLCN isn't finite")
-- Test on zero-value image if cause any division by zero
input:forward('bchw', input_tensor:clone():zero())
pp:apply(input)
local output1 = input:forward('default')
mytester:assert(_.isFinite(output1:sum()), "LeCunLCN isn't finite (div by zero)")
-- Test if it works fine with different number of channel as argument
pp = dp.LeCunLCN{batch_size=5,channels={1, 2},progress=false}
input:forward('bchw', input_tensor:clone())
pp:apply(input)
mytester:assert(_.isFinite(input:forward('default'):sum()), "LeCunLCN isn't finite (less channels)")
-- Divide by standard deviation
local pp = dp.LeCunLCN{batch_size=5,progress=false,divide_by_std=true}
input:forward('bchw', input_tensor:clone())
pp:apply(input)
local output2 = input:forward('default')
mytester:assert(_.isFinite(output2:sum()), "LeCunLCN isn't finite")
mytester:assertTensorNe(output1, output2, 0.000001, "LeCunLCN is not dividing by std")
-- Test on zero-value image if cause any division by zero
input:forward('bchw', input_tensor:clone():zero())
pp:apply(input)
mytester:assert(_.isFinite(input:forward('default'):sum()), "LeCunLCN isn't finite (div by zero)")
-- Save a test image
input_tensor = mytester.lenna:clone()
input_tensor = input_tensor:view(1,3,512,512)
input:forward("bchw", input_tensor)
pp = dp.LeCunLCN{batch_size=1,progress=false}
pp:apply(input)
image.savePNG(paths.concat(dp.UNIT_DIR, 'lecunlcn.png'), input:forward('default')[1])
end
function dptest.neural()
local tensor = torch.randn(5,10)
local grad_tensor = torch.randn(5, 2)
-- dp
local layer = dp.Neural{input_size=10, output_size=2, transfer=nn.Tanh()}
local input = dp.DataView()
input:forward('bf', tensor)
local output, carry = layer:forward(input, dp.Carry{nSample=5})
output:backward('bf', grad_tensor)
input = layer:backward(output, carry)
-- nn
local mlp = nn.Sequential()
local m = nn.Linear(10,2)
m:share(layer._linear, 'weight', 'bias')
mlp:add(m)
mlp:add(nn.Tanh())
local mlp_act = mlp:forward(tensor)
local mlp_grad = mlp:backward(tensor, grad_tensor)
-- compare nn and dp
mytester:assertTensorEq(mlp_act, output:forward('bf'), 0.00001)
mytester:assertTensorEq(mlp_grad, input:backward('bf'), 0.00001)
-- update
local act_ten = output:forward('bf'):clone()
local grad_ten = input:backward('bf'):clone()
layer:updateParameters(0.1)
layer:doneBatch()
-- forward backward
output, carry2 = layer:forward(input, dp.Carry{nSample=5})
output:backward('bf', grad_tensor)
input, carry2 = layer:backward(output, carry2)
mytester:assertTensorNe(act_ten, output:forward('bf'), 0.00001)
mytester:assertTensorNe(grad_ten, input:backward('bf'), 0.00001)
-- accUpdate
local layer2 = dp.Neural{input_size=10, output_size=2, transfer=nn.Tanh(), acc_update=true}
layer2._linear.weight = layer._linear.weight:clone()
layer2._linear.bias = layer._linear.bias:clone()
layer2:zeroGradParameters()
layer:zeroGradParameters()
local input2 = dp.DataView()
input2:forward('bf', tensor)
input:forward('bf', tensor)
local output2, carry2 = layer2:forward(input2, dp.Carry{nSample=5})
local output, carry = layer:forward(input, dp.Carry{nSample=5})
output2:backward('bf', grad_tensor)
output:backward('bf', grad_tensor)
input2 = layer2:backward(output2, carry)
input = layer:backward(output, carry)
mytester:assertTensorEq(output2:forward('bf'), output:forward('bf'), 0.00001)
mytester:assertTensorEq(input2:backward('bf'), input:backward('bf'), 0.00001)
mytester:assertTensorEq(layer2._linear.weight, layer._linear.weight, 0.00001)
mytester:assertTensorEq(layer2._linear.bias, layer._linear.bias, 0.00001)
layer2:updateParameters(0.1)
layer:updateParameters(0.1)
mytester:assertTensorEq(layer2._linear.weight, layer._linear.weight, 0.00001)
mytester:assertTensorEq(layer2._linear.bias, layer._linear.bias, 0.00001)
end
function dptest.sequential()
local tensor = torch.randn(5,10)
local grad_tensor = torch.randn(5, 2)
-- dp
local input = dp.DataView()
input:forward('bf', tensor)
local model = dp.Sequential{
models = {
dp.Neural{input_size=10, output_size=4, transfer=nn.Tanh()},
dp.Neural{input_size=4, output_size=2, transfer=nn.LogSoftMax()}
}
}
local output, carry = model:forward(input, dp.Carry{nSample=5})
output:backward('bf', grad_tensor)
input, carry = model:backward(output, carry)
mytester:assert(carry:getObj('nSample') == 5, "Carry lost an attribute")
-- nn
local mlp = nn.Sequential()
mlp:add(nn.Linear(10,4))
mlp:get(1):share(model:get(1)._linear, 'weight', 'bias')
mlp:add(nn.Tanh())
mlp:add(nn.Linear(4,2))
mlp:get(3):share(model:get(2)._linear, 'weight', 'bias')
mlp:add(nn.LogSoftMax())
local mlp_act = mlp:forward(tensor)
local mlp_grad = mlp:backward(tensor, grad_tensor)
-- compare nn and dp
mytester:assertTensorEq(mlp_act, output:forward('bf'), 0.00001)
mytester:assertTensorEq(mlp_grad, input:backward('bf'), 0.00001)
end
function dptest.container()
-- test container:parameters()
local dict = dp.Dictionary{dict_size=100,output_size=10}
dict.forwarded = true
dict._lookup.inputs = {[1]=1,[3]=1,[5]=1}
local model = dp.Sequential{
models = {
dict,
dp.Neural{input_size=10, output_size=2, transfer=nn.LogSoftMax()}
}
}
local params, gradParams, scales = model:parameters()
local nParam = table.length(params)
local nGradParam = table.length(gradParams)
mytester:assert(nParam == nGradParam, "missing gradParams")
mytester:assert(nParam == 3+2, "missing parameters")
mytester:assert(torch.type(params[1]) == 'torch.DoubleTensor', "missing param 1")
mytester:assert(torch.type(params[3]) == 'torch.DoubleTensor', "missing param 3")
mytester:assert(torch.type(params[5]) == 'torch.DoubleTensor', "missing param 5")
mytester:assert(torch.type(params[101]) == 'torch.DoubleTensor', "missing param 101")
mytester:assert(torch.type(params[102]) == 'torch.DoubleTensor', "missing param 102")
end
function dptest.softmaxtree()
local input_tensor = torch.randn(5,10)
local target_tensor = torch.IntTensor{20,24,27,10,12}
local grad_tensor = torch.randn(5)
local root_id = 29
local hierarchy={
[29]=torch.IntTensor{30,1,2}, [1]=torch.IntTensor{3,4,5},
[2]=torch.IntTensor{6,7,8}, [3]=torch.IntTensor{9,10,11},
[4]=torch.IntTensor{12,13,14}, [5]=torch.IntTensor{15,16,17},
[6]=torch.IntTensor{18,19,20}, [7]=torch.IntTensor{21,22,23},
[8]=torch.IntTensor{24,25,26,27,28}
}
-- dp
local input = dp.DataView()
input:forward('bf', input_tensor)
local target = dp.ClassView()
target:forward('b', target_tensor)
local model = dp.SoftmaxTree{input_size=10, hierarchy=hierarchy, root_id=root_id}
-- nn
local mlp = nn.SoftMaxTree(10, hierarchy, root_id)
mlp.weight = model._module.weight:clone()
mlp.bias = model._module.bias:clone()
-- forward backward
--- dp
local output, carry = model:forward(input, dp.Carry{nSample=5, targets=target})
local gradWeight = model._module.gradWeight:clone()
output:backward('b', grad_tensor)
input, carry = model:backward(output, carry)
mytester:assertTableEq(output:forward('bf'):size():totable(), {5,1}, 0.000001, "Wrong act size")
mytester:assertTableEq(input:backward('bf'):size():totable(), {5,10}, 0.000001, "Wrong grad size")
local gradWeight2 = model._module.gradWeight
mytester:assertTensorNe(gradWeight, gradWeight2, 0.00001)
--- nn
local mlp_act = mlp:forward{input_tensor, target_tensor}
local mlp_grad = mlp:backward({input_tensor, target_tensor}, grad_tensor)[1]
-- compare nn and dp
mytester:assertTensorEq(mlp_act, output:forward('bf'), 0.00001)
mytester:assertTensorEq(mlp_grad, input:backward('bf'), 0.00001)
-- share
local model2 = model:sharedClone()
-- update
local weight = model._module.weight:clone()
local act_ten = output:forward('bf'):clone()
local grad_ten = input:backward('bf'):clone()
model:updateParameters(0.1)
local weight2 = model._module.weight
mytester:assertTensorNe(weight, weight2, 0.00001)
model:doneBatch()
-- forward backward
local output2, carry2 = model2:forward(input:clone(), dp.Carry{nSample=5, targets=target})
output2:backward('b', grad_tensor)
local input2, carry2 = model2:backward(output2, carry2)
mytester:assertTensorNe(act_ten, output2:forward('bf'), 0.00001)
mytester:assertTensorNe(grad_ten, input2:backward('bf'), 0.00001)
local output, carry = model:forward(input2:clone(), dp.Carry{nSample=5, targets=target})
output:backward('b', grad_tensor)
local input, carry = model:backward(output, carry)
mytester:assertTensorEq(output:forward('bf'), output2:forward('bf'), 0.00001)
mytester:assertTensorEq(input:backward('bf'), input2:backward('bf'), 0.00001)
-- accUpdate
local layer = model
local layer2 = dp.SoftmaxTree{input_size=10, hierarchy=hierarchy, root_id=root_id, acc_update=true}
layer2._smt.weight = layer._smt.weight:clone()
layer2._smt.bias = layer._smt.bias:clone()
layer2:zeroGradParameters()
layer:zeroGradParameters()
local input2 = dp.DataView()
input2:forward('bf', input_tensor)
input:forward('bf', input_tensor)
local output2, carry2 = layer2:forward(input2, dp.Carry{nSample=5, targets=target})
local output, carry = layer:forward(input, dp.Carry{nSample=5, targets=target})
output2:backward('b', grad_tensor)
output:backward('b', grad_tensor)
input = layer:backward(output, carry)
input2 = layer2:backward(output2, carry2)
mytester:assertTensorEq(output2:forward('bf'), output:forward('bf'), 0.00001)
mytester:assertTensorEq(input2:backward('bf'), input:backward('bf'), 0.00001)
mytester:assertTensorEq(layer2._smt.weight, layer._smt.weight, 0.00001)
mytester:assertTensorEq(layer2._smt.bias, layer._smt.bias, 0.00001)
layer2:updateParameters(0.1)
layer:updateParameters(0.1)
mytester:assertTensorEq(layer2._smt.weight, layer._smt.weight, 0.00001)
mytester:assertTensorEq(layer2._smt.bias, layer._smt.bias, 0.00001)
end
function dptest.softmaxforest()
local input_tensor = torch.randn(5,10)
local target_tensor = torch.IntTensor{20,24,27,10,12}
local grad_tensor = torch.randn(5)
local root_id = 29
local hierarchy={
[29]=torch.IntTensor{30,1,2}, [1]=torch.IntTensor{3,4,5},
[2]=torch.IntTensor{6,7,8}, [3]=torch.IntTensor{9,10,11},
[4]=torch.IntTensor{12,13,14}, [5]=torch.IntTensor{15,16,17},
[6]=torch.IntTensor{18,19,20}, [7]=torch.IntTensor{21,22,23},
[8]=torch.IntTensor{24,25,26,27,28}
}
-- dp
local input = dp.DataView()
input:forward('bf', input_tensor)
local target = dp.ClassView()
target:forward('b', target_tensor)
local model = dp.SoftmaxForest{
input_size=10, hierarchy={hierarchy,hierarchy,hierarchy},
root_id={root_id,root_id,root_id}
}
for i=1,3 do
local params2, gradParams2 = model._experts:get(i):parameters()
for k,v in pairs(gradParams2) do
mytester:assert(math.abs(v:sum()) < 0.0001)
end
end
local output, carry = model:forward(input, dp.Carry{nSample=5, targets=target})
local params, gradParams = model:parameters()
local gradParams = table.recurse({}, gradParams, function(t,k,v)
t[k] = v:clone()
end)
output:backward('b', grad_tensor)
input, carry = model:backward(output, carry)
mytester:assertTableEq(output:forward('bf'):size():totable(), {5,1}, 0.000001, "Wrong act size")
mytester:assertTableEq(input:backward('bf'):size():totable(), {5,10}, 0.000001, "Wrong grad size")
local params2, gradParams2 = model:parameters()
table.recurse(gradParams, gradParams2, function(t,k,v)
mytester:assertTensorNe(t[k], v, 0.0000001)
end)
-- nn
-- experts
local experts = nn.ConcatTable()
experts:add(nn.SoftMaxTree(10, hierarchy, root_id))
experts:add(nn.SoftMaxTree(10, hierarchy, root_id))
experts:add(nn.SoftMaxTree(10, hierarchy, root_id))
experts:get(1).weight = model._smts[1].weight:clone()
experts:get(2).weight = model._smts[2].weight:clone()
experts:get(3).weight = model._smts[3].weight:clone()
experts:get(1).bias = model._smts[1].bias:clone()
experts:get(2).bias = model._smts[2].bias:clone()
experts:get(3).bias = model._smts[3].bias:clone()
-- gater
local gater = nn.Sequential()
gater:add(nn.SelectTable(1)) -- ignore targets
gater:add(nn.Linear(10,3))
gater:add(nn.SoftMax())
gater:get(2).weight = model._gater:get(2).weight:clone()
gater:get(2).bias = model._gater:get(2).bias:clone()
-- mixture
local trunk = nn.ConcatTable()
trunk:add(gater)
trunk:add(experts)
local mixture = nn.MixtureTable()
local mlp = nn.Sequential()
mlp:add(trunk)
mlp:add(mixture)
mlp:zeroGradParameters()
for i=1,3 do
local params2, gradParams2 = experts:get(i):parameters()
for k,v in pairs(gradParams2) do
mytester:assert(math.abs(v:sum()) < 0.0001)
end
end
local mlp_act = mlp:forward{input_tensor, target_tensor}
local mlp_grad = mlp:backward({input_tensor, target_tensor}, grad_tensor)[1]
-- compare nn and dp
mytester:assertTensorEq(mlp_act, output:forward('bf'), 0.00001)
mytester:assertTensorEq(mlp_grad, input:backward('bf'), 0.00001)
-- update
mlp:updateParameters(0.1)
model:updateParameters(0.1)
for i=1,experts:size() do
local expert = experts:get(i)
local params, gradParams = expert:parameters()
local params2, gradParams2 = model._experts:get(i):parameters()
table.recurse(params, params2, function(t,k,v)
mytester:assertTensorEq(t[k], v, 0.00001)
end)
end
local params, gradParams = gater:parameters()
local params2, gradParams2 = model._gater:parameters()
table.recurse(params, params2, function(t,k,v)
mytester:assertTensorEq(t[k], v, 0.00001)
end)
end
function dptest.mixtureofexperts()
local input_tensor = torch.randn(5,10)
local grad_tensor = torch.randn(5,6)
-- dp
local input = dp.DataView()
input:forward('bf', input_tensor)
local model = dp.MixtureOfExperts{
input_size=10, n_expert=3, expert_size={7},
gater_size={8}, output_size=6
}
-- forward backward
--- dp
local output, carry = model:forward(input, dp.Carry{nSample=5})
local params, gradParams = model:parameters()
local gradParams = table.recurse({}, gradParams, function(t,k,v)
t[k] = v:clone()
end)
output:backward('bf', grad_tensor)
input, carry = model:backward(output, carry)
mytester:assertTableEq(output:forward('bf'):size():totable(), {5,6}, 0.000001, "Wrong act size")
mytester:assertTableEq(input:backward('bf'):size():totable(), {5,10}, 0.000001, "Wrong grad size")
local params2, gradParams2 = model:parameters()
table.recurse(gradParams, gradParams2, function(t,k,v)
mytester:assertTensorNe(t[k], v, 0.00001)
end)
end
function dptest.convolution1D()
local size = {8,10,50}
local output_size = {8,4,100}
local data = torch.rand(unpack(size))
local grad_tensor = torch.randn(unpack(output_size))
-- dp
local input = dp.SequenceView('bwc', data)
local layer = dp.Convolution1D{
input_size=50, output_size=100, kernel_size=2,
kernel_stride=1, pool_size=2, pool_stride=2,
transfer=nn.Tanh()
}
local output, carry = layer:forward(input, dp.Carry{nSample=8})
mytester:assertTableEq(output:forward('bwc'):size():totable(), output_size, 0.00001)
output:backward('bwc', grad_tensor)
input = layer:backward(output, carry)
mytester:assertTableEq(input:backward('bwc'):size():totable(), size, 0.00001)
-- nn
local mlp = nn.Sequential()
local m = nn.TemporalConvolution(50,100,2,1)
m:share(layer._conv, 'weight', 'bias')
mlp:add(m)
mlp:add(nn.Tanh())
mlp:add(nn.TemporalMaxPooling(2,2))
local mlp_act = mlp:forward(data)
local mlp_grad = mlp:backward(data, grad_tensor)
-- compare nn and dp
mytester:assertTensorEq(mlp_act, output:forward('bwc'), 0.00001)
mytester:assertTableEq(mlp_grad:size():totable(), input:backward('bwc'):size():totable(), 0.00001)
mytester:assertTensorEq(mlp_grad, input:backward('bwc'), 0.00001)
-- update
local act_ten = output:forward('bwc'):clone()
local grad_ten = input:backward('bwc'):clone()
layer:updateParameters(0.1)
layer:doneBatch()
-- forward backward
output, carry2 = layer:forward(input, dp.Carry{nSample=8})
output:backward('bwc', grad_tensor)
input, carry2 = layer:backward(output, carry2)
mytester:assertTensorNe(act_ten, output:forward('bwc'), 0.00001)
mytester:assertTensorNe(grad_ten, input:backward('bwc'), 0.00001)
end
function dptest.convolution2D()
local size = {8,32,32,3}
local output_size = {8,20,15,15}
local data = torch.rand(unpack(size))
local grad_tensor = torch.randn(unpack(output_size))
-- dp
local input = dp.ImageView('bhwc', data)
local layer = dp.Convolution2D{
input_size=3, output_size=20, kernel_size={3,3},
kernel_stride={1,1}, pool_size={2,2}, pool_stride={2,2},
transfer=nn.Tanh()
}
local output, carry = layer:forward(input, dp.Carry{nSample=8})
mytester:assertTableEq(output:forward('bchw'):size():totable(), output_size, 0.00001)
output:backward('bchw', grad_tensor)
input = layer:backward(output, carry)
mytester:assertTableEq(input:backward('bhwc'):size():totable(), size, 0.00001)
-- nn
local mlp = nn.Sequential()
local m = nn.SpatialConvolutionMM(3,20,3,3,1,1)
m:share(layer._conv, 'weight', 'bias')
mlp:add(m)
mlp:add(nn.Tanh())
mlp:add(nn.SpatialMaxPooling(2,2,2,2))
local mlp_act = mlp:forward(input:forward('bchw'))
local mlp_grad = mlp:backward(input:forward('bchw'), grad_tensor)
-- compare nn and dp
mlp_grad = dp.ImageView('bchw', mlp_grad):forward('bhwc')
mytester:assertTensorEq(mlp_act, output:forward('bchw'), 0.00001)
mytester:assertTableEq(mlp_grad:size():totable(), input:backward('bhwc'):size():totable(), 0.00001)
mytester:assertTensorEq(mlp_grad, input:backward('bhwc'), 0.00001)
-- update
local act_ten = output:forward('bhwc'):clone()
local grad_ten = input:backward('bhwc'):clone()
layer:updateParameters(0.1)
layer:doneBatch()
-- forward backward
output, carry2 = layer:forward(input, dp.Carry{nSample=8})
output:backward('bchw', grad_tensor)
input, carry2 = layer:backward(output, carry2)
mytester:assertTensorNe(act_ten, output:forward('bhwc'), 0.00001)
mytester:assertTensorNe(grad_ten, input:backward('bhwc'), 0.00001)
end
function dptest.inception()
local size = {8,32,32,3} --bhwc
local output_size = {8,16+24+8+12,32,32} --bchw
local data = torch.rand(unpack(size))
local grad_tensor = torch.randn(unpack(output_size))
-- dp
local input = dp.ImageView('bhwc', data)
local layer = dp.Inception{
input_size=3, output_size={16,24}, reduce_size={14,16,8,12}, kernel_size={5,3},
pool_size=3, pool_stride=1, transfer=nn.ReLU(), sparse_init=true
}
for i, param in ipairs(layer:parameters()) do
mytester:assert(_.isFinite(param:sum()), 'inception init error')
end
local output, carry = layer:forward(input, dp.Carry{nSample=8})
mytester:assertTableEq(output:forward('bchw'):size():totable(), output_size, 0.00001)
mytester:assert(_.isFinite(output:forward('bchw'):sum()))
output:backward('bchw', grad_tensor)
input = layer:backward(output, carry)
mytester:assertTableEq(input:backward('bhwc'):size():totable(), size, 0.00001)
mytester:assert(_.isFinite(input:backward('bhwc'):sum()))
layer:updateParameters(0.1)
for i, param in ipairs(layer:parameters()) do
mytester:assert(_.isFinite(param:sum()), 'inception update error')
end
layer:maxNorm(1)
for i, param in ipairs(layer:parameters()) do
mytester:assert(_.isFinite(param:sum()), 'inception maxNorm error')
end
end
function dptest.dictionary()
local size = {8,10}
local output_size = {8,10,50}
local data = torch.randperm(80):resize(unpack(size))
local grad_tensor = torch.randn(unpack(output_size))
-- dp
local input = dp.ClassView('bt', data)
local layer = dp.Dictionary{dict_size=100, output_size=50}
local output, carry = layer:forward(input, dp.Carry{nSample=8})
mytester:assertTableEq(output:forward('bwc'):size():totable(), output_size, 0.00001)
output:backward('bwc', grad_tensor)
input = layer:backward(output, carry)
-- should be able to get input gradients
local function f()
input:backward('bt')
end
mytester:assert(not pcall(f))
-- nn
local mlp = nn.LookupTable(100,50)
mlp:share(layer._module, 'weight')
local mlp_act = mlp:forward(input:forward('bt'))
-- compare nn and dp
mytester:assertTensorEq(mlp_act, output:forward('bwc'), 0.00001)
-- update
local act_ten = output:forward('bwc'):clone()
layer:updateParameters(0.1)
layer:doneBatch()
-- forward backward
output, carry2 = layer:forward(input, dp.Carry{nSample=8})
output:backward('bwc', grad_tensor)
input, carry2 = layer:backward(output, carry2)
mytester:assertTensorNe(act_ten, output:forward('bwc'), 0.00001)
end
function dptest.narrowdictionary()
local size = {8,5}
local output_size = {8,120}
local data = torch.randperm(80):resize(unpack(size))
local grad_tensor = torch.randn(unpack(output_size))
-- dp
local input = dp.ClassView('bt', data)
local layer = dp.NarrowDictionary{dict_size=100, output_size=32, delta_size=4}
local output, carry = layer:forward(input, dp.Carry{nSample=8})
mytester:assertTableEq(output:forward('bf'):size():totable(), output_size, 0.00001)
output:backward('bf', grad_tensor)
input = layer:backward(output, carry)
-- should be able to get input gradients
local function f()
input:backward('bt')
end
mytester:assert(not pcall(f))
-- nn
local mlp = nn.NarrowLookupTable(4,100,32,true)
mlp:share(layer._module, 'weight')
local mlp_act = mlp:forward(input:forward('bt'))
-- compare nn and dp
mytester:assertTensorEq(mlp_act, output:forward('bf'), 0.00001)
-- update
local act_ten = output:forward('bf'):clone()
layer:updateParameters(0.1)
-- forward backward
output, carry2 = layer:forward(input, dp.Carry{nSample=8})
output:backward('bf', grad_tensor)
input, carry2 = layer:backward(output, carry2)
mytester:assertTensorNe(act_ten, output:forward('bf'), 0.00001)
end
function dptest.recurrentdictionary()
local batchSize = 8
local dictSize = batchSize * 30
local hiddenSize = 10
local data = torch.randperm(dictSize):view(batchSize, -1)
local gradData = torch.randn(dictSize, batchSize, hiddenSize)
-- dp
local input = dp.ClassView()
local layer = dp.RecurrentDictionary{dict_size=dictSize, output_size=hiddenSize}
layer:zeroGradParameters()
-- nn
local rnn = nn.Recurrent(hiddenSize, nn.LookupTable(dictSize, hiddenSize), nn.Linear(hiddenSize, hiddenSize))
rnn.feedbackModule.weight = layer._feedback.weight:clone()
rnn.feedbackModule.bias = layer._feedback.bias:clone()
rnn.inputModule.weight = layer._lookup.weight:clone()
rnn.startModule.bias = layer._recurrent.startModule.bias:clone()
rnn:zeroGradParameters()
-- compare
for step=1,10 do
-- forward
local inputTensor = data:select(2,step)
input:forward('b', inputTensor)
local output, carry = layer:forward(input, dp.Carry{nSample=batchSize})
local outputTensor = rnn:forward(inputTensor)
mytester:assertTensorEq(outputTensor, output:forward('bf'), 0.000001)
-- backward
local gradOutputTensor = gradData[step]
output:backward('bf', gradOutputTensor)
layer:backward(output, carry)
rnn:backward(inputTensor, gradOutputTensor)
end
-- updateParameters (and BPTT)
layer:updateParameters(0.1)
rnn:updateParameters(0.1)
local params = layer:parameters()
local params2 = rnn:parameters()
mytester:assert(table.length(params) ~= #params2, "missing specific case for lookuptable")
layer.forwarded = false
local params = layer:parameters()
mytester:assert(#params == #params2, #params.." should equal "..#params2)
for i, param in ipairs(params) do
mytester:assertTensorEq(param, params2[i], 0.000001, "error in update "..i)
end
end
function dptest.nll()
local input_tensor = torch.randn(5,10)
local target_tensor = torch.randperm(10):sub(1,5)
-- dp
local input = dp.DataView('bf', input_tensor)
local target = dp.ClassView('b', target_tensor)
local loss = dp.NLL{size_average=false} -- else loss isn't avg
-- test conversion
loss:float()
local err, carry = loss:forward(input, target, dp.Carry{nSample=5})
input = loss:backward(input, target, carry)
-- nn
local criterion = nn.ClassNLLCriterion():float()
local c_err = criterion:forward(input_tensor:float(), target_tensor:float())
local c_grad = criterion:backward(input_tensor:float(), target_tensor:float())
-- compare nn and dp
mytester:asserteq(c_err, err, 0.000001)
mytester:assertTensorEq(c_grad, input:backward('bf'):float(), 0.00001)
end
function dptest.kldivergence()
local input_tensor = torch.randn(5,10)
local target_tensor = torch.randn(5,10)
-- dp
local input = dp.DataView('bf', input_tensor)
local target = dp.DataView('bf', target_tensor)
local loss = dp.KLDivergence{size_average=false} -- else loss isn't avg
-- test conversion
loss:float()
local err, carry = loss:forward(input, target, dp.Carry{nSample=5})
input = loss:backward(input, target, carry)
-- nn
local criterion = nn.DistKLDivCriterion():float()
local c_err = criterion:forward(input_tensor:float(), target_tensor:float())
local c_grad = criterion:backward(input_tensor:float(), target_tensor:float())
-- compare nn and dp
mytester:asserteq(c_err, err, 0.000001)
mytester:assertTensorEq(c_grad, input:backward('bf'):float(), 0.00001)
end
function dptest.treenll()
local input_tensor = torch.randn(5,10):add(100) -- add for log nans
local target_tensor = torch.ones(5) --all targets are 1
-- dp
local input = dp.DataView('bf', input_tensor:narrow(2,1,1))
local target = dp.ClassView('b', target_tensor)
local loss = dp.TreeNLL{size_average=false} -- else loss isn't avg
-- the targets are actually ignored (SoftmaxTree uses them before TreeNLL)
local err, carry = loss:forward(input, target, dp.Carry{nSample=5})
input = loss:backward(input, target, carry)
-- nn
local criterion = nn.ClassNLLCriterion()
local c_err = criterion:forward(input_tensor, target_tensor)
local c_grad = criterion:backward(input_tensor, target_tensor)
-- compare nn and dp
mytester:asserteq(c_err, err, 0.00001)
mytester:assertTensorEq(c_grad:narrow(2,1,1), input:backward('bf'), 0.00001)
end
function dptest.criterion()
local input_tensor = torch.randn(5,10)
local target_tensor = torch.randperm(10):sub(1,5)
-- dp
local input = dp.DataView('bf', input_tensor)
local target = dp.ClassView('b', target_tensor)
local loss = dp.Criterion{
criterion=nn.ClassNLLCriterion(), size_average=false
} -- else loss isn't avg
-- test conversion
loss:float()
local err, carry = loss:forward(input, target, dp.Carry{nSample=5})
input = loss:backward(input, target, carry)
-- nn
local criterion = nn.ClassNLLCriterion():float()
local c_err = criterion:forward(input_tensor:float(), target_tensor:float())
local c_grad = criterion:backward(input_tensor:float(), target_tensor:float())
-- compare nn and dp
mytester:asserteq(c_err, err, 0.000001)
mytester:assertTensorEq(c_grad, input:backward('bf'):float(), 0.00001)
end
function dptest.tomodule()
local datasource = dp.Mnist()
local batch = datasource:trainSet():sub(1,32)
local model = dp.Sequential{
models = {
dp.Neural{input_size=datasource:featureSize(), output_size=100, transfer=nn.Tanh()},
dp.Neural{input_size=100, output_size=#(datasource:classes()),transfer=nn.LogSoftMax()}
}
}
local mlp = model:toModule(batch)
local outputView = model:forward(batch:inputs(), batch:carry())
local output = mlp:forward(batch:inputs():forward('default'))
mytester:assertTensorEq(outputView:forward('default'), output, 0.00001)
end
function dptest.sentencesampler()
local nIndice = 1000
local batchSize = 10
-- create dummy sentence dataset
local data = torch.IntTensor(nIndice, 2):zero()
data:select(2,2):copy(torch.range(1,nIndice))
local start_id, end_id = nIndice+1, nIndice+2
local startIdx = 1
local nSentence = 1
local count = 0
local maxSize = 20
for i=1,nIndice do
data[i][1] = startIdx
if i < nIndice - 5 and count > 3 and (math.random() < 0.1 or maxSize == count) then
data[i][2] = end_id
startIdx = i+1
nSentence = nSentence + 1
count = 0
end
count = count + 1
end
data[nIndice][2] = end_id
local epochSize = nIndice / 10
local dataset = dp.SentenceSet{data=data,which_set='train',start_id=start_id,end_id=end_id}
local nWord = 0
for sentenceSize,s in pairs(dataset:groupBySize()) do
nWord = nWord + (s.count*sentenceSize)
end
mytester:assert(nWord == nIndice, "error in groupBySize "..nWord..' vs '..nIndice)
local sampler = dp.SentenceSampler{batch_size=batchSize,epoch_size=epochSize,evaluate=false}
local batchSampler = sampler:sampleEpoch(dataset)
local sampled = {}
local nSampled = 0
local batch
while true do
batch = batchSampler(batch)
if not batch then
break
end
mytester:assert(batch.isBatch)
local inputs = batch:inputs():input()
local targets = batch:targets():input()
mytester:assert(inputs:dim() == 1)
mytester:assert(targets:dim() == 1)
mytester:assert(inputs:size(1) == targets:size(1))
for i=1,inputs:size(1) do
local wordIdx = inputs[i]
if wordIdx ~= start_id and wordIdx ~= end_id then
local exists = sampled[wordIdx]
mytester:assert(not exists, 'word sampled twice '..wordIdx)
sampled[wordIdx] = true
end
end
nSampled = nSampled + inputs:size(1)
end
mytester:assert(nSampled < epochSize + maxSize * batchSize, "iterator not stoping")
local epochSize = nIndice
local dataset = dp.SentenceSet{data=data,which_set='train',start_id=start_id,end_id=end_id}
local sampler = dp.SentenceSampler{batch_size=batchSize,epoch_size=-1,evaluate=false}
local batchSampler = sampler:sampleEpoch(dataset)
local sampled = {}
local nSampled = 0
local sampledTwice = 0
while nSampled < epochSize do
batch = batchSampler(batch)
mytester:assert(batch.isBatch)
local inputs = batch:inputs():input()
local targets = batch:targets():input()
mytester:assert(inputs:dim() == 1)
mytester:assert(targets:dim() == 1)
mytester:assert(inputs:size(1) == targets:size(1))
for i=1,inputs:size(1) do
local wordIdx = inputs[i]
if wordIdx ~= start_id and wordIdx ~= end_id then
if sampled[wordIdx] then
sampledTwice = sampledTwice + 1
end
sampled[wordIdx] = true
end
end
nSampled = nSampled + inputs:size(1)
end
mytester:assert(sampledTwice == 0, sampledTwice..' words sampled twice ')
mytester:assert(not batchSampler(batch), "iterator not stoping")
mytester:assert(table.length(sampled) == nIndice-nSentence, "not all words were sampled")
local sampled = {}
local nSampled = 0
local sampledTwice = 0
while nSampled < epochSize do
batch = batchSampler(batch)
mytester:assert(batch.isBatch)
local inputs = batch:inputs():input()
local targets = batch:targets():input()
mytester:assert(inputs:dim() == 1)
mytester:assert(targets:dim() == 1)
mytester:assert(inputs:size(1) == targets:size(1))
for i=1,inputs:size(1) do
local wordIdx = inputs[i]
if wordIdx ~= start_id and wordIdx ~= end_id then
if sampled[wordIdx] then
sampledTwice = sampledTwice + 1
end
sampled[wordIdx] = true
end
end
nSampled = nSampled + inputs:size(1)
end
mytester:assert(sampledTwice == 0, sampledTwice..' words sampled twice ')
mytester:assert(not batchSampler(batch), "iterator not stoping")
mytester:assert(table.length(sampled) == nIndice-nSentence, "not all words were sampled")
end
function dptest.errorminima()
local report={validator={loss={avgError=11}},epoch=1}
local mediator = dp.Mediator()
local m = dp.ErrorMinima{start_epoch=5}
m:setup{mediator=mediator}
local mt = {}
local recv_count = 0
local minima, minima_epoch
mediator:subscribe('errorMinima', mt, 'errorMinima')
-- test start_epoch
function mt:errorMinima(found_minima, m)
if found_minima then
minima, minima_epoch = m:minima()
recv_count = recv_count + 1
end
end
for epoch=1,10 do
report.epoch = epoch
m:doneEpoch(report)
end
mytester:assert(recv_count == 1, "ErrorMinima recv_count error")
mytester:assert(minima == 11, "ErrorMinima minima error")
mytester:assert(minima_epoch == 5, "ErrorMinima start_epoch error")
-- test that minimas is found
local recv_count = 0
local losses = {10,8,8,9,7}
local cme = {11,12,15}
local cm = {10,8,7}
function mt:errorMinima(found_minima, m)
if found_minima then
minima, minima_epoch = m:minima()
recv_count = recv_count + 1
mytester:assert(losses[cme[recv_count]-10] == cm[recv_count], "ErrorMinima wrong minima")
end
end
for epoch=11,15 do
report.epoch = epoch
report.validator.loss.avgError = losses[epoch-10]
m:doneEpoch(report)
end
mytester:assert(recv_count == 3, "ErrorMinima recv_count error")
mytester:assert(minima == 7, "ErrorMinima minima error")
mytester:assert(minima_epoch == 15, "ErrorMinima epoch error")
end
function dptest.adaptivelearningrate()
local lr = 20
local mediator = dp.Mediator()
local m = dp.AdaptiveLearningRate{max_wait=1,decay_factor=0.1}
local visitor = dp.Learn{learning_rate=lr, verbose=false, observer=m}
visitor:setup{mediator=mediator, id=dp.ObjectID('learn')}
for epoch=1,10 do
if epoch % 3 == 0 then
mediator:publish('errorMinima', true)
else
mediator:publish('errorMinima', false)
end
end
lr = lr*(0.1^3)
mytester:assert(visitor:learningRate() == lr, "AdaptiveLearningRate learningRate error 1")
mediator:publish('errorMinima', true)
mytester:assert(visitor:learningRate() == lr, "AdaptiveLearningRate learningRate error 2")
for epoch=1,10 do
mediator:publish('errorMinima', false)
end
mytester:assert(math.abs(visitor:learningRate() - lr*(0.1^5)) < 0.00001, "AdaptiveLearningRate learningRate error 3")
end
function dptest.learn()
local batchSize = 8
local inputSize = 10
local outputSize = 5
local lr, learn_scale = 0.1, 0.5
local mediator = dp.Mediator()
local input_tensor = torch.randn(batchSize, inputSize)
local gradOutput_tensor = torch.randn(batchSize, outputSize)
local input = dp.DataView('bf', input_tensor)
local visitor = dp.Learn{learning_rate=lr, verbose=false}
visitor:setup{mediator=mediator, id=dp.ObjectID('learn')}
local neural = dp.Neural{
input_size=inputSize,output_size=outputSize,
transfer=nn.Identity(),mvstate={learn_scale=0.5}
}
local linear = neural._linear:clone()
linear:zeroGradParameters()
local output = neural:forward(input, dp.Carry{nSample=batchSize})
output:backward('bf', gradOutput_tensor)
neural:backward(output, dp.Carry{nSample=batchSize})
neural:accept(visitor)
local output_tensor = linear:forward(input_tensor)
local gradInput_tensor = linear:backward(input_tensor, gradOutput_tensor)
linear:updateParameters(lr*learn_scale)
local params = neural:parameters()
local params2 = linear:parameters()
for i, param in ipairs(params) do
mytester:assertTensorEq(param, params2[i], 0.000001, "learn error")
end
end
function dptest.recurrentvisitorchain()
local batchSize = 8
local inputSize = 10
local outputSize = 5
local lr = 0.1
local updateInterval = 3
local input_tensor = torch.randn(batchSize, inputSize)
local gradOutput_tensor = torch.randn(batchSize, outputSize)
local input = dp.DataView('bf', input_tensor)
local visitor = dp.RecurrentVisitorChain{
visit_interval = updateInterval, force_forget = false,
visitors = {dp.Learn{learning_rate = lr, verbose=false}}
}
local mediator = dp.Mediator()
visitor:setup{mediator=mediator, id=dp.ObjectID('recurrent')}
local neural = dp.Neural{input_size=inputSize,output_size=outputSize,transfer=nn.Identity()}
local linear = neural._linear:clone()
linear:zeroGradParameters()
for i = 1,10 do
local output = neural:forward(input, dp.Carry{nSample=batchSize})
output:backward('bf', gradOutput_tensor)
neural:backward(output, dp.Carry{nSample=batchSize})
neural:accept(visitor)
local output_tensor = linear:forward(input_tensor)
local gradInput_tensor = linear:backward(input_tensor, gradOutput_tensor)
if i % 3 == 0 then
linear:updateParameters(lr)
linear:zeroGradParameters()
end
end
local params = neural:parameters()
local params2 = linear:parameters()
for i, param in ipairs(params) do
mytester:assertTensorEq(param, params2[i], 0.000001, "recurrent visitor chain error")
end
end
function dptest.savetofile()
local mediator = dp.Mediator()
local stf = dp.SaveToFile{in_memory=true,verbose=false}
local subject = {
tensor=torch.randn(3,4), stf=stf,
id=function()return{toPath=function()return'test462346';end};end
}
stf:setup(subject, mediator)
local path = paths.concat(stf._save_dir, stf._filename)
if paths.filep(path) then
os.execute('rm '..path)
end
stf:save(subject)
mediator:publish("doneExperiment")
mytester:assert(paths.filep(path), "file doesn't exist")
local saved_subject = torch.load(path)
mytester:assert(not saved_subject.stf._save_cache, "cache was saved")
mytester:assertTensorEq(subject.tensor, saved_subject.tensor, 0.000001, "tensor not saved")
stf = saved_subject.stf
mediator = saved_subject.stf._mediator
subject = saved_subject
subject.tensor = torch.randn(3,4)
stf:save(subject)
mediator:publish("doneExperiment")
local saved_subject = torch.load(path)
mytester:assertTensorEq(subject.tensor, saved_subject.tensor, 0.000001, "tensor not re saved")
end
function dptest.topcrop()
local fb = dp.TopCrop{n_top={1,3}, n_crop=3,center=1,verbose=false}
fb._id = dp.ObjectID('topcrop')
local carry = dp.Carry{nSample=18}
local preds = {{1,0,0,0,0,0},{1,0,0,0,0,0},{1,0,0,0,0,0}, -- 1,1
{0,1,0,0,0,0},{0,1,0,0,0,0},{0,1,0,0,0,0}, -- 1,1
{0,1,0,0,0,0},{0,0,1,0,0,0},{0,0,1,0,0,0}, -- 1,1
{1,0,0,2,0,0},{1,0,0,2,0,0},{1,0,0,2,0,0}, -- 0,1
{0,-1,0,0,2,0},{0,0,0,0,2,0},{0,-1,0,0,2,0}, -- 0,0
{0,0,-1,0,0,1},{0,0,-1,0,0,1},{0,0,-1,0,0,1}} -- 0,0
preds = torch.FloatTensor(preds)
local targets = torch.IntTensor{1,1,1,2,2,2,3,3,3,1,1,1,2,2,2,3,3,3}
local inputs = torch.randn(18,1,5,5)
local outputView = dp.DataView('bf', preds)
local targetView = dp.ClassView('b', targets)
local inputView = dp.ImageView('bchw', inputs)
local batch = dp.Batch{inputs=inputView, targets=targetView, carry=carry}
fb:add(batch, outputView, carry, {epoch=1})
fb:add(batch, outputView, carry, {epoch=1})
fb:doneEpoch({epoch=1})
local report = fb:report()
mytester:assert(report.topcrop.all[1] == 50, "topcrop all 1 error")
mytester:assert(math.round(report.topcrop.all[3]) == 67, "topcrop all 3 error")
mytester:assert(math.round(report.topcrop.center[1]) == 33, "topcrop center 1 error")
mytester:assert(math.round(report.topcrop.center[3]) == 67, "topcrop center 3 error")
end
function dp.test(tests)
math.randomseed(os.time())
mytester = torch.Tester()
mytester.lenna = image.lena()
mytester:add(dptest)
mytester:run(tests)
return mytester
end
| bsd-3-clause |
dacrybabysuck/darkstar | scripts/zones/Ghelsba_Outpost/npcs/Armoury_Crate.lua | 9 | 8338 | -----------------------------------
-- Area: Ghelsba_Outpost
-- NPC: Armoury Crate
-- Ghelsba_Outpost Armoury_Crate
-------------------------------------
require("scripts/globals/bcnm")
require("scripts/globals/battlefield")
-----------------------------------
local loot =
{
-- BCNM Wings of Fury
[34] =
{
{
{itemid = 891, droprate = 1000}, -- Bat Fang
},
{
{itemid = 4900, droprate = 306}, -- Thunder Spirit Pact
{itemid = 4744, droprate = 319}, -- Scroll Of Invisible
{itemid = 4745, droprate = 125}, -- Scroll Of Sneak
{itemid = 4746, droprate = 222}, -- Scroll Of Deodorize
},
{
{itemid = 17786, droprate = 153},-- Ganko
{itemid = 18170, droprate = 139},-- Platoon Edge
{itemid = 16687, droprate = 83}, -- Platoon Axe
{itemid = 17571, droprate = 97}, -- Platoon Pole
{itemid = 17993, droprate = 125},-- Platoon Dagger
{itemid = 749, droprate = 444}, -- Mythril Beastcoin
{itemid = 773, droprate = 56}, -- Translucent Rock
},
{
{itemid = 17820, droprate = 111},-- Gunromaru
{itemid = 17993, droprate = 139},-- Platoon Dagger
{itemid = 18170, droprate = 139},-- Platoon Edge
{itemid = 18085, droprate = 42}, -- Platoon Lance
{itemid = 16959, droprate = 181},-- Platoon Sword
{itemid = 774, droprate = 97}, -- Purple Rock
{itemid = 769, droprate = 69}, -- Red Rock
{itemid = 776, droprate = 14}, -- White Rock
{itemid = 775, droprate = 28}, -- Black Rock
{itemid = 772, droprate = 28}, -- Green Rock
{itemid = 771, droprate = 14}, -- Yellow Rock
{itemid = 770, droprate = 69}, -- Blue Rock
},
{
{itemid = 0, droprate = 389}, -- nothing
{itemid = 13548, droprate = 167}, -- astral_ring
{itemid = 922, droprate = 444}, -- bat_wing
},
},
-- BCNM Petrifying Pair
[35] =
{
{
{itemid = 852, droprate = 1000}, -- Lizard Skin
},
{
{itemid = 0, droprate = 900}, -- nothing
{itemid = 13014, droprate = 100}, -- leaping_boots
},
{
{itemid = 15282, droprate = 50}, -- Katana Obi
{itemid = 15275, droprate = 75}, -- Rapier Belt
{itemid = 15278, droprate = 175}, -- Scythe Belt
{itemid = 694, droprate = 175}, -- Chestnut Log
{itemid = 690, droprate = 350}, -- Elm Log
{itemid = 652, droprate = 100}, -- Steel Ingot
},
{
{itemid = 0, droprate = 925}, -- nothing (50%)
{itemid = 15282, droprate = 50}, -- Katana Obi
{itemid = 15275, droprate = 75}, -- Rapier Belt
{itemid = 15278, droprate = 175}, -- Scythe Belt
{itemid = 694, droprate = 175}, -- Chestnut Log
{itemid = 690, droprate = 350}, -- Elm Log
{itemid = 652, droprate = 100}, -- Steel Ingot
},
{
{itemid = 15285, droprate = 105},-- Avatar Belt
{itemid = 15279, droprate = 105},-- Pick Belt
{itemid = 651, droprate = 131}, -- Iron Ingot
{itemid = 643, droprate = 131}, -- Chunk Of Iron Ore
{itemid = 644, droprate = 79}, -- Chunk Of Mythril Ore
{itemid = 736, droprate = 79}, -- Chunk Of Silver Ore
{itemid = 795, droprate = 131}, -- Lapis Lazuli
},
{
{itemid = 17867, droprate = 552},-- Jug Of Cold Carrion Broth
{itemid = 4877, droprate = 263}, -- Scroll Of Absorb-agi
{itemid = 4878, droprate = 210}, -- Scroll Of Absorb-int
{itemid = 4876, droprate = 289}, -- Scroll Of Absorb-vit
{itemid = 4868, droprate = 105}, -- Scroll Of Dispel
{itemid = 4751, droprate = 79}, -- Scroll Of Erase
{itemid = 5070, droprate = 421}, -- Scroll Of Magic Finale
{itemid = 4947, droprate = 79}, -- Scroll Of Utsusemi Ni
},
{
{itemid = 0, droprate = 736}, -- nothing (25%)
{itemid = 15271, droprate = 200}, -- Axe Belt
{itemid = 15272, droprate = 125}, -- Cestus Belt
{itemid = 809, droprate = 10}, -- Clear Topaz
{itemid = 15276, droprate = 75}, -- Dagger Belt
{itemid = 645, droprate = 100}, -- Darksteel Ore
{itemid = 15281, droprate = 25}, -- Gun Belt
{itemid = 4132, droprate = 175}, -- Hi-ether
{itemid = 15284, droprate = 200}, -- Lance Belt
{itemid = 796, droprate = 75}, -- Light Opal
{itemid = 15273, droprate = 175}, -- Mace Belt
{itemid = 653, droprate = 200}, -- Mythril Ingot
{itemid = 799, droprate = 25}, -- Onyx
{itemid = 15283, droprate = 250}, -- Sarashi
{itemid = 15277, droprate = 100}, -- Shield Belt
{itemid = 15280, droprate = 100}, -- Song Belt
{itemid = 15274, droprate = 150}, -- Staff Belt
{itemid = 744, droprate = 100}, -- Silver Ingot
{itemid = 806, droprate = 125}, -- Tourmaline
},
{
{itemid = 0, droprate = 2210}, -- nothing (50%)
{itemid = 15271, droprate = 200}, -- Axe Belt
{itemid = 15272, droprate = 125}, -- Cestus Belt
{itemid = 809, droprate = 10}, -- Clear Topaz
{itemid = 15276, droprate = 75}, -- Dagger Belt
{itemid = 645, droprate = 100}, -- Darksteel Ore
{itemid = 15281, droprate = 25}, -- Gun Belt
{itemid = 4132, droprate = 175}, -- Hi-ether
{itemid = 15284, droprate = 200}, -- Lance Belt
{itemid = 796, droprate = 75}, -- Light Opal
{itemid = 15273, droprate = 175}, -- Mace Belt
{itemid = 653, droprate = 200}, -- Mythril Ingot
{itemid = 799, droprate = 25}, -- Onyx
{itemid = 15283, droprate = 250}, -- Sarashi
{itemid = 15277, droprate = 100}, -- Shield Belt
{itemid = 15280, droprate = 100}, -- Song Belt
{itemid = 15274, droprate = 150}, -- Staff Belt
{itemid = 744, droprate = 100}, -- Silver Ingot
{itemid = 806, droprate = 125}, -- Tourmaline
},
},
-- BCNM Toadal Recall
[36] =
{
{
{itemid = 4386, droprate = 1000}, -- king_truffle
},
{
{itemid = 17880, droprate = 1000}, -- jug_of_seedbed_soil
},
{
{itemid = 0, droprate = 200}, -- nothing
{itemid = 12403, droprate = 200}, -- magicians_shield
{itemid = 12389, droprate = 200}, -- mercenarys_targe
{itemid = 12399, droprate = 200}, -- beaters_aspis
{itemid = 12394, droprate = 200}, -- pilferers_aspis
},
{
{itemid = 0, droprate = 250}, -- nothing
{itemid = 13667, droprate = 250}, -- trimmers_mantle
{itemid = 13671, droprate = 250}, -- genin_mantle
{itemid = 13663, droprate = 250}, -- warlocks_mantle
},
{
{itemid = 0, droprate = 625}, -- nothing
{itemid = 4947, droprate = 125}, -- scroll_of_utsusemi_ni
{itemid = 4714, droprate = 125}, -- scroll_of_phalanx
{itemid = 4751, droprate = 125}, -- scroll_of_erase
},
{
{itemid = 0, droprate = 250}, -- nothing
{itemid = 1601, droprate = 250}, -- mannequin_head
{itemid = 1602, droprate = 250}, -- mannequin_body
{itemid = 1603, droprate = 250}, -- mannequin_hands
},
},
}
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local battlefield = player:getBattlefield()
if battlefield then
dsp.battlefield.HandleLootRolls(battlefield, loot[battlefield:getID()], nil, npc)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
dacrybabysuck/darkstar | scripts/globals/abilities/super_jump.lua | 12 | 1039 | -----------------------------------
-- Ability: Super Jump
-- Performs a super jump.
-- Obtained: Dragoon Level 50
-- Recast Time: 3:00
-- Duration: Instant
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/pets")
require("scripts/globals/msg")
-----------------------------------
function onAbilityCheck(player,target,ability)
return 0,0
end
function onUseAbility(player,target,ability)
-- Reduce 99% of total accumulated enmity
if (target:isMob()) then
target:lowerEnmity(player, 99)
end
ability:setMsg(dsp.msg.basic.NONE)
-- Prevent the player from performing actions while in the air
player:queue(0, function(player)
player:stun(5000)
end)
-- If the Dragoon's wyvern is out and alive, tell it to use Super Climb
local wyvern = player:getPet()
if (wyvern ~= nil and player:getPetID() == dsp.pet.id.WYVERN and wyvern:getHP() > 0) then
wyvern:useJobAbility(636, wyvern)
end
end
| gpl-3.0 |
hussian1997/hk-_bot | plugins/ar-badword.lua | 8 | 3422 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY(@AHMED_ALOBIDE) ▀▄ ▄▀
▀▄ ▄▀ BY(@hussian_9) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ (ملف منع الكلمات) ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
local function addword(msg, name)
local hash = 'chat:'..msg.to.id..':badword'
redis:hset(hash, name, 'newword')
return "تَمِ ✔️ أضأفهَ كلمَهَ جَدِيدَهَ الئ قاَئمَهَ المنعَ ❌👍\n>"..name
end
local function get_variables_hash(msg)
return 'chat:'..msg.to.id..':badword'
end
local function list_variablesbad(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = '❌✋🏻 قأئِمَهَ الَمـنعِ الكَلمأَتَ المحـظوَرهَ ❌👍 :\n\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
else
return
end
end
function clear_commandbad(msg, var_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:del(hash, var_name)
return 'تَمِ ✔️تَنظِيَفَ قأئمَةْ الـمنَعْ 👍👿'
end
local function list_variables2(msg, value)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(value, names[i]) and not is_momod(msg) then
if msg.to.type == 'channel' then
delete_msg(msg.id,ok_cb,false)
else
kick_user(msg.from.id, msg.to.id)
end
return
end
--text = text..names[i]..'\n'
end
end
end
local function get_valuebad(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
function clear_commandsbad(msg, cmd_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:hdel(hash, cmd_name)
return ''..cmd_name..' تَمِ ✔️ألغأههأَ مَنِ قأئِمَه المَنعِ👍'
end
local function run(msg, matches)
if matches[2] == 'منع' then
if not is_momod(msg) then
return 'only for moderators'
end
local name = string.sub(matches[3], 1, 50)
local text = addword(msg, name)
return text
end
if matches[2] == 'قائمه المنع' then
return list_variablesbad(msg)
elseif matches[2] == 'تنظيف قائمه المنع' then
if not is_momod(msg) then return '_|_' end
local asd = '1'
return clear_commandbad(msg, asd)
elseif matches[2] == 'الغاء منع' or matches[2] == 'rw' then
if not is_momod(msg) then return '_|_' end
return clear_commandsbad(msg, matches[3])
else
local name = user_print_name(msg.from)
return list_variables2(msg, matches[1])
end
end
return {
patterns = {
"^()(rw) (.*)$",
"^()(منع) (.*)$",
"^()(الغاء منع) (.*)$",
"^()(قائمه المنع)$",
"^()(تنظيف قائمه المنع)$",
"^(.+)$",
},
run = run
}
| gpl-2.0 |
dacrybabysuck/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Animated_Dagger.lua | 9 | 1177 | -----------------------------------
-- Area: Dynamis - Xarcabard
-- Mob: Animated Dagger
-----------------------------------
require("scripts/globals/status");
local ID = require("scripts/zones/Dynamis-Xarcabard/IDs");
-----------------------------------
function onMobEngaged(mob,target)
if (mob:AnimationSub() == 3) then
SetDropRate(103,1572,1000);
else
SetDropRate(103,1572,0);
end
target:showText(mob,ID.text.ANIMATED_DAGGER_DIALOG);
SpawnMob(17330306):updateEnmity(target);
SpawnMob(17330307):updateEnmity(target);
SpawnMob(17330308):updateEnmity(target);
SpawnMob(17330316):updateEnmity(target);
SpawnMob(17330317):updateEnmity(target);
SpawnMob(17330318):updateEnmity(target);
end;
function onMobFight(mob,target)
-- TODO: add battle dialog
end;
function onMobDisengage(mob)
mob:showText(mob,ID.text.ANIMATED_DAGGER_DIALOG+2);
end;
function onMobDeath(mob, player, isKiller)
player:showText(mob,ID.text.ANIMATED_DAGGER_DIALOG+1);
DespawnMob(17330306);
DespawnMob(17330307);
DespawnMob(17330308);
DespawnMob(17330316);
DespawnMob(17330317);
DespawnMob(17330318);
end; | gpl-3.0 |
Teaonly/beginlearning | july/dl_tutorial/simple_lstm/model_utils.lua | 11 | 5151 |
-- adapted from https://github.com/wojciechz/learning_to_execute
-- utilities for combining/flattening parameters in a model
-- the code in this script is more general than it needs to be, which is
-- why it is kind of a large
require 'torch'
local model_utils = {}
function model_utils.combine_all_parameters(...)
--[[ like module:getParameters, but operates on many modules ]]--
-- get parameters
local networks = {...}
local parameters = {}
local gradParameters = {}
for i = 1, #networks do
local net_params, net_grads = networks[i]:parameters()
if net_params then
for _, p in pairs(net_params) do
parameters[#parameters + 1] = p
end
for _, g in pairs(net_grads) do
gradParameters[#gradParameters + 1] = g
end
end
end
local function storageInSet(set, storage)
local storageAndOffset = set[torch.pointer(storage)]
if storageAndOffset == nil then
return nil
end
local _, offset = unpack(storageAndOffset)
return offset
end
-- this function flattens arbitrary lists of parameters,
-- even complex shared ones
local function flatten(parameters)
if not parameters or #parameters == 0 then
return torch.Tensor()
end
local Tensor = parameters[1].new
local storages = {}
local nParameters = 0
for k = 1,#parameters do
local storage = parameters[k]:storage()
if not storageInSet(storages, storage) then
storages[torch.pointer(storage)] = {storage, nParameters}
nParameters = nParameters + storage:size()
end
end
local flatParameters = Tensor(nParameters):fill(1)
local flatStorage = flatParameters:storage()
for k = 1,#parameters do
local storageOffset = storageInSet(storages, parameters[k]:storage())
parameters[k]:set(flatStorage,
storageOffset + parameters[k]:storageOffset(),
parameters[k]:size(),
parameters[k]:stride())
parameters[k]:zero()
end
local maskParameters= flatParameters:float():clone()
local cumSumOfHoles = flatParameters:float():cumsum(1)
local nUsedParameters = nParameters - cumSumOfHoles[#cumSumOfHoles]
local flatUsedParameters = Tensor(nUsedParameters)
local flatUsedStorage = flatUsedParameters:storage()
for k = 1,#parameters do
local offset = cumSumOfHoles[parameters[k]:storageOffset()]
parameters[k]:set(flatUsedStorage,
parameters[k]:storageOffset() - offset,
parameters[k]:size(),
parameters[k]:stride())
end
for _, storageAndOffset in pairs(storages) do
local k, v = unpack(storageAndOffset)
flatParameters[{{v+1,v+k:size()}}]:copy(Tensor():set(k))
end
if cumSumOfHoles:sum() == 0 then
flatUsedParameters:copy(flatParameters)
else
local counter = 0
for k = 1,flatParameters:nElement() do
if maskParameters[k] == 0 then
counter = counter + 1
flatUsedParameters[counter] = flatParameters[counter+cumSumOfHoles[k]]
end
end
assert (counter == nUsedParameters)
end
return flatUsedParameters
end
-- flatten parameters and gradients
local flatParameters = flatten(parameters)
local flatGradParameters = flatten(gradParameters)
-- return new flat vector that contains all discrete parameters
return flatParameters, flatGradParameters
end
function model_utils.clone_many_times(net, T)
local clones = {}
local params, gradParams
if net.parameters then
params, gradParams = net:parameters()
if params == nil then
params = {}
end
end
local paramsNoGrad
if net.parametersNoGrad then
paramsNoGrad = net:parametersNoGrad()
end
local mem = torch.MemoryFile("w"):binary()
mem:writeObject(net)
for t = 1, T do
-- We need to use a new reader for each clone.
-- We don't want to use the pointers to already read objects.
local reader = torch.MemoryFile(mem:storage(), "r"):binary()
local clone = reader:readObject()
reader:close()
if net.parameters then
local cloneParams, cloneGradParams = clone:parameters()
local cloneParamsNoGrad
for i = 1, #params do
cloneParams[i]:set(params[i])
cloneGradParams[i]:set(gradParams[i])
end
if paramsNoGrad then
cloneParamsNoGrad = clone:parametersNoGrad()
for i =1,#paramsNoGrad do
cloneParamsNoGrad[i]:set(paramsNoGrad[i])
end
end
end
clones[t] = clone
collectgarbage()
end
mem:close()
return clones
end
return model_utils
| mit |
dacrybabysuck/darkstar | scripts/globals/mobskills/claw_storm.lua | 11 | 1066 | ---------------------------------------------
-- Claw Storm
--
-- Description: Slashes a single target in a threefold attack. Additional effect: Poison
-- Type: Physical
-- Utsusemi/Blink absorb: 1 shadow
-- Range: Melee
-- Notes:
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 3
local accmod = 1
local dmgmod = 1.1
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.SLASHING,info.hitslanded)
target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.SLASHING)
local typeEffect = dsp.effect.POISON
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, mob:getMainLvl()/2.5, 3, 30)
return dmg
end | gpl-3.0 |
mc-server/Essentials | functions.lua | 2 | 1414 | function GetPlayerLookPos(Player)
local World = Player:GetWorld()
local Start = Player:GetEyePosition()
local End = Start + Player:GetLookVector() * 150
local HitCoords = nil
local Callbacks =
{
OnNextBlock = function(BlockPos, BlockType)
if BlockType ~= E_BLOCK_AIR then
HitCoords = BlockPos
return true
end
end
}
cLineBlockTracer:Trace(World, Callbacks, Start, End)
return HitCoords
end
function IsEnchantable()
if HeldItemType >= 256 and HeldItemType <= 259 then
return true
elseif HeldItemType >= 267 and HeldItemType <= 279 then
return true
elseif HeldItemType >= 283 and HeldItemType <= 286 then
return true
elseif HeldItemType >= 290 and HeldItemType <= 294 then
return true
elseif HeldItemType >= 298 and HeldItemType <= 317 then
return true
elseif HeldItemType >= 290 and HeldItemType <= 294 then
return true
elseif HeldItemType == 346 or HeldItemType == 359 or HeldItemType == 261 then
return true
end
end
function GetAverageNum(Table)
local Sum = 0
for i,Num in ipairs(Table) do
Sum = Sum + Num
end
return (Sum / #Table)
end
function CheckPlayer(Player)
if UsersINI:GetValue(Player:GetUUID(), "Jailed") == "true" then
Jailed[Player:GetUUID()] = true
else
Jailed[Player:GetUUID()] = false
end
if UsersINI:GetValue(Player:GetUUID(), "Muted") == "true" then
Muted[Player:GetUUID()] = true
else
Muted[Player:GetUUID()] = false
end
end
| apache-2.0 |
dacrybabysuck/darkstar | scripts/globals/items/bowl_of_salt_ramen.lua | 11 | 1642 | -----------------------------------------
-- ID: 6462
-- Item: bowl_of_salt_ramen
-- Food Effect: 30Min, All Races
-----------------------------------------
-- DEX +5
-- VIT +5
-- AGI +5
-- Accuracy +5% (cap 90)
-- Ranged Accuracy +5% (cap 90)
-- Evasion +5% (cap 90)
-- Resist Slow +10
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,6462)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.DEX, 5)
target:addMod(dsp.mod.VIT, 5)
target:addMod(dsp.mod.AGI, 5)
target:addMod(dsp.mod.FOOD_ACCP, 5)
target:addMod(dsp.mod.FOOD_ACC_CAP, 90)
target:addMod(dsp.mod.FOOD_RACCP, 5)
target:addMod(dsp.mod.FOOD_RACC_CAP, 90)
-- target:addMod(dsp.mod.FOOD_EVAP, 5)
-- target:addMod(dsp.mod.FOOD_EVA_CAP, 90)
target:addMod(dsp.mod.SLOWRES, 10)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.DEX, 5)
target:delMod(dsp.mod.VIT, 5)
target:delMod(dsp.mod.AGI, 5)
target:delMod(dsp.mod.FOOD_ACCP, 5)
target:delMod(dsp.mod.FOOD_ACC_CAP, 90)
target:delMod(dsp.mod.FOOD_RACCP, 5)
target:delMod(dsp.mod.FOOD_RACC_CAP, 90)
-- target:delMod(dsp.mod.FOOD_EVAP, 5)
-- target:delMod(dsp.mod.FOOD_EVA_CAP, 90)
target:delMod(dsp.mod.SLOWRES, 10)
end
| gpl-3.0 |
keviner2004/shoot-em-up | ui/Score.lua | 1 | 1046 | local ScaleText = require("ui.ScaleText")
local Score = {}
Score.new = function()
local score = ScaleText.new({
text = "0", x = 0, y = 0, font = "kenvector_future_thin", fontSize = 30
})
score.value = 0
function score:gotScoreAnim()
if self.animing then
return
end
self.animing = true
transition.to( self, {time = 100, xScale = 1.5, yScale = 1.5, onComplete =
function()
transition.to( self, {time = 100, xScale = 1, yScale = 1, onComplete =
function()
--print("text anim done!!")
self.animing = false
end})
end})
end
function score:addScore(v)
self.value = self.value + v
self.text = self.value
end
function score:setScore(v)
self.value = v
self.text = self.value
self:gotScoreAnim()
end
function score:getScore()
return self.value
end
return score
end
return Score
| mit |
fakechris/Atlas | tests/unit/lua/proxy-commands.lua | 4 | 3011 | --[[ $%BEGINLICENSE%$
Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the
License.
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 St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
---
-- test the proxy.commands module
--
--
-- file under test
local cmds = require("proxy.commands")
local tests = require("proxy.test")
TestScript = tests.ProxyBaseTest:new()
tests.ProxyBaseTest:setDefaultScope()
function TestScript:testParseCOM_QUERY()
local cmd = cmds.parse(string.char(proxy.COM_QUERY) .. "SELECT 1")
assertNotEquals(cmd, nil)
assertEquals(cmd.type, proxy.COM_QUERY)
assertEquals(cmd.query, "SELECT 1")
end
function TestScript:testParseCOM_STMT_PREPARE()
local cmd = cmds.parse(string.char(proxy.COM_STMT_PREPARE) .. "SELECT 1")
assertNotEquals(cmd, nil)
assertEquals(cmd.type, proxy.COM_STMT_PREPARE)
assertEquals(cmd.query, "SELECT 1")
end
function TestScript:testParseCOM_INIT_DB()
local cmd = cmds.parse(string.char(proxy.COM_INIT_DB) .. "schema")
assertNotEquals(cmd, nil)
assertEquals(cmd.type, proxy.COM_INIT_DB)
assertEquals(cmd.schema, "schema")
end
function TestScript:testParseCOM_FIELD_LIST()
local cmd = cmds.parse(string.char(proxy.COM_FIELD_LIST) .. "table")
assertNotEquals(cmd, nil)
assertEquals(cmd.type, proxy.COM_FIELD_LIST)
assertEquals(cmd.table, "table")
end
function TestScript:testParseCOM_QUIT()
local cmd = cmds.parse(string.char(proxy.COM_QUIT))
assertNotEquals(cmd, nil)
assertEquals(cmd.type, proxy.COM_QUIT)
end
function TestScript:testParseCOM_SHUTDOWN()
local cmd = cmds.parse(string.char(proxy.COM_SHUTDOWN))
assertNotEquals(cmd, nil)
assertEquals(cmd.type, proxy.COM_SHUTDOWN)
end
function TestScript:testParseCOM_PING()
local cmd = cmds.parse(string.char(proxy.COM_PING))
assertNotEquals(cmd, nil)
assertEquals(cmd.type, proxy.COM_PING)
end
function TestScript:testParseCOM_CREATE_DB()
local cmd = cmds.parse(string.char(proxy.COM_CREATE_DB) .. "schema")
assertNotEquals(cmd, nil)
assertEquals(cmd.type, proxy.COM_CREATE_DB)
assertEquals(cmd.schema, "schema")
end
function TestScript:testParseCOM_DROP_DB()
local cmd = cmds.parse(string.char(proxy.COM_DROP_DB) .. "schema")
assertNotEquals(cmd, nil)
assertEquals(cmd.type, proxy.COM_DROP_DB)
assertEquals(cmd.schema, "schema")
end
---
-- the test suite runner
local suite = tests.Suite:new({ result = tests.Result:new()})
suite:run()
suite.result:print()
return suite:exit_code()
| gpl-2.0 |
dacrybabysuck/darkstar | scripts/globals/weaponskills/blade_jin.lua | 10 | 1462 | -----------------------------------
-- Blade Jin
-- Katana weapon skill
-- Skill Level: 200
-- Delivers a three-hit attack. Chance of params.critical varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Breeze Gorget & Thunder Gorget.
-- Aligned with the Breeze Belt & Thunder Belt.
-- Element: Wind
-- Modifiers: STR:30% DEX:30%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 3
params.ftp100 = 1 params.ftp200 = 1 params.ftp300 = 1
params.str_wsc = 0.3 params.dex_wsc = 0.3 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.crit100 = 0.1 params.crit200 = 0.3 params.crit300 = 0.5
params.canCrit = true
params.acc100 = 0.0 params.acc200= 0.0 params.acc300= 0.0
params.atk100 = 1; params.atk200 = 1; params.atk300 = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1.375 params.ftp200 = 1.375 params.ftp300 = 1.375
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
dacrybabysuck/darkstar | scripts/zones/Western_Altepa_Desert/npcs/_3h6.lua | 11 | 1262 | -----------------------------------
-- Area: Western Altepa Desert
-- NPC: _3h6 (Topaz Column)
-- Notes: Mechanism for Altepa Gate
-- !pos -260 10 -344 125
-----------------------------------
local ID = require("scripts/zones/Western_Altepa_Desert/IDs")
require("scripts/globals/status")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
if npc:getAnimation() ~= dsp.anim.OPEN_DOOR then
npc:setAnimation(dsp.anim.OPEN_DOOR)
GetNPCByID(npc:getID() - 4):setAnimation(dsp.anim.OPEN_DOOR)
else
player:messageSpecial(ID.text.DOES_NOT_RESPOND)
end
if
GetNPCByID(ID.npc.ALTEPA_GATE + 5):getAnimation() == dsp.anim.OPEN_DOOR and
GetNPCByID(ID.npc.ALTEPA_GATE + 6):getAnimation() == dsp.anim.OPEN_DOOR and
GetNPCByID(ID.npc.ALTEPA_GATE + 7):getAnimation() == dsp.anim.OPEN_DOOR and
GetNPCByID(ID.npc.ALTEPA_GATE + 8):getAnimation() == dsp.anim.OPEN_DOOR
then
local openTime = math.random(15, 30) * 60
for i = ID.npc.ALTEPA_GATE, ID.npc.ALTEPA_GATE + 8 do
GetNPCByID(i):openDoor(openTime)
end
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end | gpl-3.0 |
dacrybabysuck/darkstar | scripts/zones/Southern_San_dOria/npcs/Varchet.lua | 8 | 2244 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Varchet
-- !pos 116.484 -1 91.554 230
-----------------------------------
local ID = require("scripts/zones/Southern_San_dOria/IDs")
require("scripts/globals/npc_util")
require("scripts/globals/quests")
-----------------------------------
local GAME_WON = 0
local GAME_LOST = 2
local GAME_TIE = 3
function onTrade(player, npc, trade)
if npcUtil.tradeHas(trade, {{"gil", 5}}) then
player:confirmTrade()
local vdie1 = math.random(1, 6)
local vdie2 = math.random(1, 6)
local vtotal = vdie1 + vdie2
local pdie1 = math.random(1, 6)
local pdie2 = math.random(1, 6)
local ptotal = pdie1 + pdie2
local result = GAME_LOST
if ptotal > vtotal then
result = GAME_WON
elseif ptotal == vtotal then
result = GAME_TIE
end
player:setLocalVar('VarchetGame', result)
player:startEvent(519, vdie1, vdie2, vtotal, pdie1, pdie2, ptotal, result)
else
player:startEvent(608)
end
end
function onTrigger(player, npc)
if player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.EXIT_THE_GAMBLER) == QUEST_ACCEPTED then
player:startEvent(638)
else
player:startEvent(525)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 519 then
local result = player:getLocalVar('VarchetGame')
if result == GAME_WON then
local gilPayout = 10
player:addGil(gilPayout)
player:messageSpecial(ID.text.GIL_OBTAINED, gilPayout)
if player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.EXIT_THE_GAMBLER) == QUEST_ACCEPTED then
player:setCharVar("exitTheGamblerStat", 1)
player:showText(player:getEventTarget(), ID.text.VARCHET_KEEP_PROMISE)
end
elseif result == GAME_TIE then
local gilPayout = 5
player:addGil(gilPayout)
player:messageSpecial(ID.text.GIL_OBTAINED, gilPayout)
else
player:messageSpecial(ID.text.VARCHET_BET_LOST)
end
player:setLocalVar('VarchetGame', 0)
end
end
| gpl-3.0 |
dacrybabysuck/darkstar | scripts/zones/Batallia_Downs_[S]/npcs/Thorben.lua | 9 | 2375 | -----------------------------------
-- Area: Batallia Downs (S)
-- NPC: Thorben
-- Type: Quest NPC
-- !pos 175.346,8.038,-419.244 84
-----------------------------------
require("scripts/globals/keyitems")
require("scripts/globals/settings")
require("scripts/globals/quests")
require("scripts/globals/npc_util")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local lostInTranslocation = player:getQuestStatus(CRYSTAL_WAR, dsp.quest.id.crystalWar.LOST_IN_TRANSLOCATION)
local leftMapPiece = player:hasKeyItem(dsp.ki.LEFT_MAP_PIECE)
local middleMapPiece = player:hasKeyItem(dsp.ki.MIDDLE_MAP_PIECE)
local rightMapPiece = player:hasKeyItem(dsp.ki.RIGHT_MAP_PIECE)
local anyMapPiece = leftMapPiece or middleMapPiece or rightMapPiece
if lostInTranslocation == QUEST_COMPLETED then
player:startEvent(108)
elseif lostInTranslocation == QUEST_ACCEPTED and leftMapPiece and middleMapPiece and rightMapPiece then
player:startEvent(107)
elseif player:getCharVar("lostInTranslocationCS") == 1 then
player:startEvent(106)
elseif lostInTranslocation == QUEST_ACCEPTED and anyMapPiece then
player:startEvent(105)
elseif lostInTranslocation == QUEST_ACCEPTED and not anyMapPiece then
player:startEvent(104)
else
player:startEvent(103)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 107 then
if player:hasKeyItem(dsp.ki.MAP_OF_GRAUBERG) then
npcUtil.completeQuest(player, CRYSTAL_WAR, dsp.quest.id.crystalWar.LOST_IN_TRANSLOCATION, {
gil = 2000,
xp = 2000,
var = "lostInTranslocationCS"
})
else
npcUtil.completeQuest(player, CRYSTAL_WAR, dsp.quest.id.crystalWar.LOST_IN_TRANSLOCATION, {
keyItem = dsp.ki.MAP_OF_GRAUBERG,
var = "lostInTranslocationCS"
})
end
player:delKeyItem(dsp.ki.LEFT_MAP_PIECE)
player:delKeyItem(dsp.ki.MIDDLE_MAP_PIECE)
player:delKeyItem(dsp.ki.RIGHT_MAP_PIECE)
elseif csid == 105 then
player:setCharVar("lostInTranslocationCS", 1)
elseif csid == 103 then
player:addQuest(CRYSTAL_WAR, dsp.quest.id.crystalWar.LOST_IN_TRANSLOCATION)
end
end | gpl-3.0 |
ArIaNDeVeLoPeR/IDsearcher | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
eagle14/kia12 | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
sdgdsffdsfff/WizRouter | init.lua | 1 | 1710 | -- LOG
cjson = require "cjson"
function debuglog(...)
local log_table = {}
for i = 1, select("#", ...) do
log_table[i] = select(i, ...)
end
ngx.log(ngx.ERR, "[WIZROUTER-DEBUG] ", cjson.encode(log_table))
end
function ngxlog(...)
ngx.log(ngx.ERR, "[WIZROUTER] ", ...)
end
-- LOG END
-- UTILS
function split(str, sep)
local fields = {}
str:gsub("[^"..sep.."]+", function(c) fields[#fields+1] = c end)
return fields
end
http = require "resty.http"
-- UTILS END
-- REDIS
local redis = require "resty.redis_iresty"
local red = redis:new()
function get_value_from_redis_and_cache_it(key)
local res, err = red:get(key)
if res then
ngx.shared.redis_cache:safe_set(key, res)
return res
else
ngxlog("Can't get " .. key .. " from redis: ", err)
local value = ngx.shared.redis_cache:get(key)
if value then
return value
else
ngxlog("Can't get " .. key .. " from cache: ", err)
end
end
end
function get_smembers_from_redis_and_cache_it(key)
local res, err = red:smembers(key)
if res then
local str = ""
for key, value in ipairs(res) do
if key == 1 then
str = value
else
str = str .. "|||||" .. value
end
end
ngx.shared.redis_cache:safe_set(key, str, 600)
return res
else
ngxlog("Can't get " .. key .. " from redis: ", err)
local str = ngx.shared.redis_cache:get(key)
if str then
return split(str, "|||||")
else
ngxlog("Can't get " .. key .. " from cache: ", err)
end
end
end
-- REDIS END
| apache-2.0 |
Kelwing/pvpgn | lua/include/table.lua | 7 | 6168 | --[[
Copyright (C) 2014 HarpyWar (harpywar@gmail.com)
This file is a part of the PvPGN Project http://pvpgn.pro
Licensed under the same terms as Lua itself.
]]--
-- Clear table
function table.clear(_table)
for k in pairs(_table) do
_table[k] = nil
end
end
-- Get table size
function table.count(T)
if not T or not next(t) then return 0 end
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
-- Get table slice from offset to length
function table.slice(values, offset, length)
local res = {}
local n = #values
-- default values for range
offset = offset or 0
if offset < 0 or offset > n then
return {}
end
length = length or n-offset
if length < 1 then
length = 1
elseif length > n-offset then
length = n-offset
end
for i = offset,offset+length-1 do
res[i-offset] = values[i]
end
return res
end
-- (Debug) Print contents of `tbl`, with indentation.
-- `indent` sets the initial level of indentation.
function table.dump(t, ident)
local output = ""
if not indent then indent = 0 end
-- if table has 0 index then display this key at start
if not (t[0] == nil) then
for k=0, #t do
local formatting = "\n" .. string.rep(" ", indent) .. k .. ": "
local v = t[k]
if type(v) == "table" then
v = "[" .. table.print(v, indent+1) .. "]"
elseif type(v) == 'boolean' then
v = tostring(v)
end
output = output .. formatting .. v
end
else
for k,v in pairs(t) do
local formatting = "\n" .. k .. ": "
local v = t[k]
if type(v) == "table" then
v = "[" .. table.print(v, indent+1) .. "]"
elseif type(v) == 'boolean' then
v = tostring(v)
end
output = output .. formatting .. v
end
end
return output
end
-- Find table key by value
function get_key_for_value( t, value )
for k,v in pairs(t) do
if v==value then return k end
end
return nil
end
--[[
Save Table to File
Load Table from File
v 1.0
Lua 5.2 compatible
Only Saves Tables, Numbers and Strings
Insides Table References are saved
Does not save Userdata, Metatables, Functions and indices of these
----------------------------------------------------
table.save( table , filename )
on failure: returns an error msg
----------------------------------------------------
table.load( filename or stringtable )
Loads a table that has been saved via the table.save function
on success: returns a previously saved table
on failure: returns as second argument an error msg
----------------------------------------------------
Licensed under the same terms as Lua itself.
]]--
do
-- declare local variables
--// exportstring( string )
--// returns a "Lua" portable version of the string
local function exportstring( s )
return string.format("%q", s)
end
--// The Save Function
function table.save( tbl,filename )
local charS,charE = " ","\n"
local file,err = io.open( filename, "wb" )
if err then return err end
-- initiate variables for save procedure
local tables,lookup = { tbl },{ [tbl] = 1 }
file:write( "return {"..charE )
for idx,t in ipairs( tables ) do
file:write( "-- Table: {"..idx.."}"..charE )
file:write( "{"..charE )
local thandled = {}
for i,v in ipairs( t ) do
thandled[i] = true
local stype = type( v )
-- only handle value
if stype == "table" then
if not lookup[v] then
table.insert( tables, v )
lookup[v] = #tables
end
file:write( charS.."{"..lookup[v].."},"..charE )
elseif stype == "string" then
file:write( charS..exportstring( v )..","..charE )
elseif stype == "number" then
file:write( charS..tostring( v )..","..charE )
end
end
for i,v in pairs( t ) do
-- escape handled values
if (not thandled[i]) then
local str = ""
local stype = type( i )
-- handle index
if stype == "table" then
if not lookup[i] then
table.insert( tables,i )
lookup[i] = #tables
end
str = charS.."[{"..lookup[i].."}]="
elseif stype == "string" then
str = charS.."["..exportstring( i ).."]="
elseif stype == "number" then
str = charS.."["..tostring( i ).."]="
end
if str ~= "" then
stype = type( v )
-- handle value
if stype == "table" then
if not lookup[v] then
table.insert( tables,v )
lookup[v] = #tables
end
file:write( str.."{"..lookup[v].."},"..charE )
elseif stype == "string" then
file:write( str..exportstring( v )..","..charE )
elseif stype == "number" then
file:write( str..tostring( v )..","..charE )
end
end
end
end
file:write( "},"..charE )
end
file:write( "}" )
file:close()
end
--// The Load Function
function table.load( sfile )
local ftables,err = loadfile( sfile )
if err or not ftables() then return _,err end
local tables = ftables()
for idx = 1,#tables do
local tolinki = {}
for i,v in pairs( tables[idx] ) do
if type( v ) == "table" then
tables[idx][i] = tables[v[1]]
end
if type( i ) == "table" and tables[i[1]] then
table.insert( tolinki,{ i,tables[i[1]] } )
end
end
-- link indices
for _,v in ipairs( tolinki ) do
tables[idx][v[2]],tables[idx][v[1]] = tables[idx][v[1]],nil
end
end
return tables[1]
end
-- close do
end
-- ChillCode | gpl-2.0 |
dacrybabysuck/darkstar | scripts/globals/items/elshena.lua | 11 | 1034 | -----------------------------------------
-- ID: 5886
-- Item: elshena
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP +7% (cap 120)
-- Increases rate of combat skill gains by 40%
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,5886)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.FOOD_HPP, 7)
target:addMod(dsp.mod.FOOD_HP_CAP, 120)
target:addMod(dsp.mod.COMBAT_SKILLUP_RATE, 40)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_HPP, 7)
target:delMod(dsp.mod.FOOD_HP_CAP, 120)
target:delMod(dsp.mod.COMBAT_SKILLUP_RATE, 40)
end
| gpl-3.0 |
dacrybabysuck/darkstar | scripts/commands/npchere.lua | 14 | 1615 | ---------------------------------------------------------------------------------------------------
-- func: npchere <npcId>
-- desc: Spawns an NPC and then moves it to the current position, if in same zone.
-- Errors will despawn the NPC unless "noDepop" was specified (any value works).
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "is"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!npchere {npcID} {noDepop}");
end;
function onTrigger(player, npcId, noDepop)
require("scripts/globals/status");
-- validate npc
local targ;
if (npcId == nil) then
targ = player:getCursorTarget();
if (targ == nil or not targ:isNPC()) then
error(player, "You must either provide an npcID or target an NPC.");
return;
end
else
targ = GetNPCByID(npcId);
if (targ == nil) then
error(player, "Invalid npcID.");
return;
end
end
if (player:getZoneID() == targ:getZoneID()) then
targ:setPos( player:getXPos(), player:getYPos(), player:getZPos(), player:getRotPos(), player:getZoneID() );
targ:setStatus(dsp.status.NORMAL);
else
if (noDepop == nil or noDepop == 0) then
targ:setStatus(dsp.status.DISAPPEAR);
player:PrintToPlayer("Despawned the NPC because of an error.");
end
player:PrintToPlayer("NPC could not be moved to current pos - you are probably in the wrong zone.");
end
end; | gpl-3.0 |
dacrybabysuck/darkstar | scripts/zones/Dangruf_Wadi/IDs.lua | 9 | 3577 | -----------------------------------
-- Area: Dangruf Wadi (191)
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.DANGRUF_WADI] =
{
text =
{
CONQUEST_BASE = 0, -- Tallying conquest results...
ITEM_CANNOT_BE_OBTAINED = 6541, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6547, -- Obtained: <item>.
GIL_OBTAINED = 6548, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6550, -- Obtained key item: <keyitem>.
GEOMAGNETRON_ATTUNED = 7169, -- Your <keyitem> has been attuned to a geomagnetic fount in the corresponding locale.
FISHING_MESSAGE_OFFSET = 7208, -- You can't fish here.
DEVICE_NOT_WORKING = 7322, -- The device is not working.
SYS_OVERLOAD = 7331, -- Warning! Sys...verload! Enterin...fety mode. ID eras...d.
YOU_LOST_THE = 7336, -- You lost the <item>.
CRYSTALLINE_DUST = 7340, -- The area is littered with a white crystalline dust.
PLANT_EXTRACT = 7341, -- A plant extract is smeared around the area.
BROKEN_EGGS = 7342, -- A number of broken eggs lie scattered about.
YOU_PLACE_ITEM = 7343, -- You place <item> down.
YOU_BEAT_GOBLIN = 7345, -- You beat the Goblin!
GOBLIN_BEAT_YOU = 7346, -- The Goblin beat you...
YOU_GAVE_UP = 7347, -- You gave up...
BEAT_SALTVIX = 7352, -- You hear a voice... (...Hmph! All happy 'cause [he/she] beat Saltvix...Won't stand chance 'gainst Grasswix of North...)
DONT_WASTE_TIME = 7362, -- You hear a voice... (Grasswix don't waste time with losers...)
BEAT_GRASSWIX = 7363, -- You hear a voice... (...can't believe it! How could Grasswix lose! Eggblix of Cavern...he no lose!)
JUST_WONT_DO = 7373, -- You hear a voice... (...just won't do...nope...nope...)
BEAT_EGGBLIX = 7374, -- (...Lucky, ya are! Don't forget to say hi to our sister at Drachenfall!)
CHEST_UNLOCKED = 7434, -- You unlock the chest!
SMALL_HOLE = 7488, -- There is a small hole here.
PLAYER_OBTAINS_ITEM = 8365, -- <name> obtains <item>!
UNABLE_TO_OBTAIN_ITEM = 8366, -- You were unable to obtain the item.
PLAYER_OBTAINS_TEMP_ITEM = 8367, -- <name> obtains the temporary item: <item>!
ALREADY_POSSESS_TEMP = 8368, -- You already possess that temporary item.
NO_COMBINATION = 8373, -- You were unable to enter a combination.
REGIME_REGISTERED = 10451, -- New training regime registered!
COMMON_SENSE_SURVIVAL = 11522, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
},
mob =
{
TEPORINGO_PH =
{
[17559583] = 17559584,
},
GEYSER_LIZARD = 17559558,
CHOCOBOLEECH = 17559869,
APPARATUS_ELEMENTAL = 17559870,
},
npc =
{
CASKET_BASE = 17559877,
GEYSER_OFFSET = 17559899,
AN_EMPTY_VESSEL_QM = 17559911,
TREASURE_CHEST = 17559924,
},
}
return zones[dsp.zone.DANGRUF_WADI] | gpl-3.0 |
dacrybabysuck/darkstar | scripts/globals/mobskills/dreadstorm.lua | 11 | 1174 | ---------------------------------------------
-- Dreadstorm
--
-- Description: Deals magical damage in an area of effect. Additional effect: Terror
-- Type: Magical
-- Wipes Shadows
-- Range: 13' radial
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:getFamily() == 316) then
local mobSkin = mob:getModelId()
if (mobSkin == 1805) then
return 0
else
return 1
end
end
return 1
end
function onMobWeaponSkill(target, mob, skill)
local typeEffect = dsp.effect.TERROR
local duration = 10
skill:setMsg(MobGazeMove(mob, target, typeEffect, 1, 0, duration))
local dmgmod = 2.5
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg() * 4,dsp.magic.ele.DARK,dmgmod,TP_MAB_BONUS,1)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.DARK,MOBPARAM_WIPE_SHADOWS)
target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.DARK)
return dmg
end
| gpl-3.0 |
andeandr100/Crumbled-World | Lua/Enviromental/islandMeshExporter.lua | 1 | 10555 | --this = Island()
IslandMeshExporter = {}
function IslandMeshExporter.new()
local self = {}
local navLines
local meshTable
local listOfAllCombinedMeshes
local hidenNodes = {}
local meshes
local importentMeshes--a list of meshes thats always need to be renderd
local minPos
local maxPos
local density = 1.0
local combinedMeshes
local debugNodes
local debugNodeNames = { "debug_circle_5m", "debug_circle_7_5m", "debug_crossbow_attack_area", "debug_tower_platform_1x1", "debug_tower_platform_2x2", "debug_tower_platform_3x3", "debug_tower_platform_4x4" }
local aFileNode
local destroyFiles = {}
--clear scene tree from exported data
function self.destroy()
if aFileNode then
for i=1, #destroyFiles do
aFileNode:removeFile(destroyFiles[i])
end
end
end
function self.getMeshTable()
return listOfAllCombinedMeshes
end
local function getNodeBeforeIsland(sceneNode)
if sceneNode and sceneNode:getParent() and sceneNode:getParent():getNodeType() == NodeId.island then
return sceneNode
end
return sceneNode and getNodeBeforeIsland(sceneNode:getParent()) or nil
end
function self.hideExportedMeshes()
--hide all meshes
print("hideExportedMeshes\n")
for i=1, #listOfAllCombinedMeshes do
listOfAllCombinedMeshes[i]:setCanBeSaved(false)
end
for i=1, #debugNodes do
debugNodes[i]:setCanBeSaved(false)
end
for i=1, #listOfAllCombinedMeshes do
local node = getNodeBeforeIsland(listOfAllCombinedMeshes[i])
if node then
local meshList = node:findAllNodeByTypeTowardsLeaf(NodeId.mesh)
local allHiden = true
for n=1, #meshList do
if meshList[n]:getCanBeSaved() then
allHiden = false
end
end
if allHiden then
node:setCanBeSaved(false)
hidenNodes[#hidenNodes + 1] = node
end
end
end
end
function self.showHidenNodes()
print("showHidenNodes\n")
for i=1, #listOfAllCombinedMeshes do
listOfAllCombinedMeshes[i]:setCanBeSaved(true)
end
for i=1, #debugNodes do
debugNodes[i]:setCanBeSaved(true)
end
for i=1, #hidenNodes do
hidenNodes[i]:setCanBeSaved(true)
end
hidenNodes = {}
end
local optimizationIgnoreFileNameTable = {
"props/watermelon.mym",
"props/end_crystal.mym",
"props/minecart_npc.mym",
"nature/worldedge/edge_floater1.mym",
"nature/worldedge/edge_floater2.mym",
"nature/worldedge/edge_floater3.mym",
"nature/worldedge/edge_floater4.mym",
"nature/worldedge/edge_floater5.mym",
"Constructions/buildings/mine.mym"
}
local function isOnNavMeshHullEdge(position)
for i=1, #navLines do
if Collision.lineSegmentPointLength2( navLines[i], position) < 1 then
return true
end
end
return false
end
local function isInOptimizationIgnoreModelTable(fileName)
for key,name in pairs(optimizationIgnoreFileNameTable) do
if name==fileName then
return true
end
end
return false
end
local function findAllMeshes(node, inMeshTable)
--node = Model()
if node:getNodeType() == NodeId.model or node:getNodeType() == NodeId.islandMesh or (node:getNodeType() ~= NodeId.island and #node:getAllScript() > 0 ) then
--nodes to ignore
if (node:getNodeType() ~= NodeId.island and #node:getAllScript() > 0 ) then
return false
end
if node:getNodeType() == NodeId.islandMesh or isInOptimizationIgnoreModelTable(node:getFileName()) then
return false
end
for i=1, #debugNodeNames do
if debugNodeNames[i] == node:getSceneName() then
debugNodes[#debugNodes+1] = node
return false
end
end
if string.find(node:getFileName(),"tree") then
return false
end
end
local nodeLocalMatrix = this:getGlobalMatrix():inverseM() * node:getGlobalMatrix()
local dontTochMesh = false
if node:getNodeType() == NodeId.mesh then
if isOnNavMeshHullEdge(nodeLocalMatrix:getPosition()) or string.find(node:getModelName(),"buildingParts") or string.find(node:getModelName(),"railroad") or string.find(node:getModelName(),"buildings") or string.find(node:getModelName(),"world_edge") then
importentMeshes[#importentMeshes+1] = {mesh=node,localMatrix=nodeLocalMatrix}
else
inMeshTable[#inMeshTable+1] = {mesh=node,localMatrix=nodeLocalMatrix}
inMeshTable = inMeshTable[#inMeshTable]
end
if string.find(node:getModelName(),"minecart_npc") then
print("ModelName: "..node:getModelName().."\n")
abort()
end
listOfAllCombinedMeshes[#listOfAllCombinedMeshes + 1] = node
end
if not (node:getNodeType() == NodeId.model and isInOptimizationIgnoreModelTable(node:getFileName())) then--we only optimize children of none ignored parents
if node:getNodeType() == NodeId.model and node:getFileName() == "props/minecart_npc.mym" then
abort()
end
for i=0, node:getChildSize() do
--copy node to the final mesh table and save the local island matrix
local childNode = node:getChildNode(i)
if childNode and childNode:getCanBeSaved() then
findAllMeshes( childNode, inMeshTable )
end
end
end
return true
end
--calculate bound volume
local function calculateBounds(inMeshTable)
if inMeshTable.mesh then
local position = inMeshTable.localMatrix:getPosition()
minPos:minimize( position )
maxPos:maximize( position )
end
for i=1, #inMeshTable do
calculateBounds(inMeshTable[i])
end
end
local function addAllToMeshList(inMeshTable)
if inMeshTable.mesh then
meshes[#meshes+1] = {mesh = inMeshTable.mesh, localMatrix = inMeshTable.localMatrix}
end
for i=1, #inMeshTable do
addAllToMeshList(inMeshTable[i])
end
end
local function addToRenderList(inMeshTable, dropCount, dropfrekvence)
dropCount = dropCount + dropfrekvence
for i=1, #inMeshTable do
dropCount = addToRenderList(inMeshTable[i], dropCount, dropfrekvence)
end
if dropCount >= 1 then
dropCount = dropCount - 1
else
meshes[#meshes+1] = {mesh = inMeshTable.mesh, localMatrix = inMeshTable.localMatrix}
end
return dropCount
end
local function getMeshesToCombine()
meshes = {}
local dropfrekvence = 1.0 - density
print("dropfrekvence "..dropfrekvence.."\n")
if dropfrekvence < 0.01 then
addAllToMeshList(meshTable)
else
local drop = 0
for i=1, #meshTable do
drop = addToRenderList(meshTable[i], drop, dropfrekvence)
end
end
for i=1, #importentMeshes do
meshes[#meshes+1] = importentMeshes[i]
end
end
local function combineMeshes()
local parent = nil
local meshOldLocalMatrix = Matrix()
for x = minPos.x, maxPos.x+5, 15 do
for z = minPos.z, maxPos.z+5, 15 do
local areaMeshes = {}
for i=1, #meshes do
local position = meshes[i].localMatrix:getPosition()
if position.x > x and position.x <= x+15 and position.z > z and position.z <= z+15 then
--prepare mesh to be added to a nodemesh
meshOldLocalMatrix = meshes[i].mesh:getLocalMatrix()
parent = meshes[i].mesh:getParent()
meshes[i].mesh:setLocalMatrix(meshes[i].localMatrix)
parent:removeChild(meshes[i].mesh)
--Try to add mesh and if so remove all triangles facing down and have a dot value greater then 0.75
local added = false
for n=1, #areaMeshes do
if not added and areaMeshes[n]:addMesh(meshes[i].mesh, Vec3(0,-1,0), 0.75) then
added = true
end
end
if not added then
areaMeshes[#areaMeshes+1] = NodeMesh()
areaMeshes[#areaMeshes]:setLocalPosition(Vec3(x+5,0,z+5))
if not areaMeshes[#areaMeshes]:addMesh(meshes[i].mesh, Vec3(0,-1,0), 0.75) then
print("Mesh was not added to a combined mesh\n")
end
end
--restore the mesh information
meshes[i].mesh:setLocalMatrix(meshOldLocalMatrix)
parent:addChild(meshes[i].mesh)
end
end
for n=1, #areaMeshes do
if areaMeshes[n]:getNumVertex() > 0 then
combinedMeshes[#combinedMeshes+1] = areaMeshes[n]
end
end
end
end
end
local function convertNavVertexToLocalIslandPos(navVertex)
if navVertex.island == this then
return navVertex.position
else
return this:getGlobalMatrix():inverseM() * navVertex.island:getGlobalMatrix() * navVertex.position
end
end
local function buildNavMeshEdgeLine()
local navMesh = this:findNodeByType(NodeId.navMesh)
navLines = {}
if navMesh then
local navMeshHull = navMesh:getHull()
for i=1, #navMeshHull do
local oldVertex = navMeshHull[i][#navMeshHull[i]]
for n=1, #navMeshHull[i] do
if navMeshHull[i][n].island and oldVertex.island and ( oldVertex.island == this or navMeshHull[i][n].island == this ) then
navLines[#navLines+1] = Line3D(convertNavVertexToLocalIslandPos(oldVertex), convertNavVertexToLocalIslandPos(navMeshHull[i][n]))
oldVertex = navMeshHull[i][n]
end
end
end
end
end
function self.export(fileNode)
buildNavMeshEdgeLine()
listOfAllCombinedMeshes = {}
importentMeshes = {}
meshTable = {}
debugNodes = {}
--find all meshes
findAllMeshes(this, meshTable)
minPos = Vec3()
maxPos = Vec3()
--calculate bound volume
calculateBounds(meshTable)
calculateBounds(importentMeshes)
--increase size
minPos = minPos - Vec3(1)
maxPos = maxPos + Vec3(1)
aFileNode = fileNode
local fileId = 1
local modelInfo = {}
for newDensity = 1.0, -0.1, -0.2 do
density = newDensity
--calculate which meshes will be used
getMeshesToCombine()
combinedMeshes = {}
combineMeshes()
local models = {}
for i=1, #combinedMeshes do
print("Save model "..fileId.."\n")
local nodeMesh = combinedMeshes[i]
--nodeMesh = NodeMesh()
local modelName = "Island"..this:getIslandId().."Model"..fileId
local modelFile = nodeMesh:saveToFile(modelName)
fileNode:addFile(modelName, modelFile)
destroyFiles[#destroyFiles + 1] = modelName
models[#models+1] = {modelName = modelName, localPosition = nodeMesh:getLocalPosition()}
fileId = fileId + 1
end
modelInfo[#modelInfo + 1] = {value=density}
modelInfo[#modelInfo].models = models
end
return modelInfo
end
local function init()
end
init()
return self
end | mit |
martinfelis/ggj15 | utils/parsexml.lua | 1 | 1432 | --[[
-- taken from http://lua-users.org/wiki/LuaXml
--]]
local function parseargs(s)
local arg = {}
string.gsub(s, "([%-%w]+)=([\"'])(.-)%2", function (w, _, a)
arg[w] = a
end)
return arg
end
local function parse_xml(s)
local stack = {}
local top = {}
table.insert(stack, top)
local ni,c,label,xarg, empty
local i, j = 1, 1
while true do
ni,j,c,label,xarg, empty = string.find(s, "<(%/?)([%w:]+)(.-)(%/?)>", i)
if not ni then break end
local text = string.sub(s, i, ni-1)
if not string.find(text, "^%s*$") then
table.insert(top, text)
end
if empty == "/" then -- empty element tag
table.insert(top, {label=label, xarg=parseargs(xarg), empty=1})
elseif c == "" then -- start tag
top = {label=label, xarg=parseargs(xarg)}
table.insert(stack, top) -- new level
else -- end tag
local toclose = table.remove(stack) -- remove top
top = stack[#stack]
if #stack < 1 then
error("nothing to close with "..label)
end
if toclose.label ~= label then
error("trying to close "..toclose.label.." with "..label)
end
table.insert(top, toclose)
end
i = j+1
end
local text = string.sub(s, i)
if not string.find(text, "^%s*$") then
table.insert(stack[#stack], text)
end
if #stack > 1 then
error("unclosed "..stack[#stack].label)
end
return stack[1]
end
return parse_xml
| apache-2.0 |
LuaDist2/lua-jet | src/jet/daemon/radix.lua | 3 | 6129 | -- Implements a radix tree for the jet-daemon
local pairs = pairs
local next = next
local tinsert = table.insert
local tremove = table.remove
local new = function()
local j = {}
-- the table that holds the radix_tree
j.radix_tree = {}
-- elments that can be filled by several functions
-- and be returned as set of possible hits
j.radix_elements = {}
-- internal tree instance or table of tree instances
-- used to hold parts of the tree that may be interesting afterwards
j.return_tree = {}
-- this FSM is used for string comparison
-- can evaluate if the radix tree contains or ends with a specific string
local lookup_fsm = function (wordpart,next_state,next_letter)
if wordpart:sub(next_state,next_state) ~= next_letter then
if wordpart:sub(1,1) ~= next_letter then
return false,0
else
return false,1
end
end
if #wordpart == next_state then
return true,next_state
else
return false,next_state
end
end
-- evaluate if the radix tree starts with a specific string
-- returns pointer to subtree
local root_lookup
root_lookup = function(tree_instance,part)
if #part == 0 then
j.return_tree = tree_instance
else
local s = part:sub(1,1)
if tree_instance and tree_instance[s] ~= true then
root_lookup(tree_instance[s], part:sub(2))
end
end
end
-- evaluate if the radix tree contains or ends with a specific string
-- returns list of pointers to subtrees
local leaf_lookup
leaf_lookup = function(tree_instance,word,state)
local next_state = state + 1
if tree_instance then
for k,v in pairs(tree_instance) do
if v ~= true then
local hit,next_state = lookup_fsm(word,next_state,k)
if hit == true then
tinsert(j.return_tree,v)
else
leaf_lookup(v,word,next_state)
end
end
end
end
end
-- takes a single tree or a list of trees
-- traverses the trees and adds all elements to j.radix_elements
local radix_traverse
radix_traverse = function(tree_instance)
for k,v in pairs(tree_instance) do
if v == true then
j.radix_elements[k] = true
elseif v ~= true then
radix_traverse(v)
end
end
end
-- adds a new element to the tree
local add_to_tree = function(word)
local t = j.radix_tree
for i=1,#word do
local char = word:sub(i,i)
local tmpt = t[char]
if tmpt == nil then
tmpt = {}
t[char] = tmpt
end
t = tmpt
end
t[word] = true
end
-- removes an element from the tree
local remove_from_tree = function(word)
local t = j.radix_tree
local tables = {}
for i=1,#word do
local char = word:sub(i,i)
local tmpt = t[char]
tables[i] = tmpt
t = tmpt
end
t[word] = nil
local i = #word
while next(t) == nil and i > 1 do
local char = word:sub(i, i)
t = tables[i-1]
t[char] = nil
i = i - 1
end
end
-- performs the respective actions for the parts of a fetcher
-- that can be handled by a radix tree
-- fills j.radix_elements with all hits that were found
local match_parts = function(tree_instance,parts)
j.radix_elements = {}
if parts['equals'] then
j.return_tree = {}
root_lookup(tree_instance,parts['equals'])
if j.return_tree[parts['equals']] == true then
j.radix_elements[parts['equals']] = true
end
else
local temp_tree = tree_instance
if parts['startsWith'] then
j.return_tree = {}
root_lookup(temp_tree,parts['startsWith'])
temp_tree = j.return_tree
end
if parts['contains'] then
j.return_tree = {}
leaf_lookup(temp_tree,parts['contains'],0)
temp_tree = j.return_tree
end
if parts['endsWith'] then
j.return_tree = {}
leaf_lookup(temp_tree,parts['endsWith'],0)
for k,t in pairs(j.return_tree) do
for _,v in pairs(t) do
if v ~= true then
j.return_tree[k] = nil
break
end
end
end
temp_tree = j.return_tree
end
if temp_tree then
radix_traverse(temp_tree)
end
end
end
-- evaluates if the fetch operation can be handled
-- completely or partially by the radix tree
-- returns elements from the j.radix_tree if it can be handled
-- and nil otherwise
local get_possible_matches = function(peer,params,fetch_id,is_case_insensitive)
local involves_path_match = params.path
local involves_value_match = params.value or params.valueField
local level = 'impossible'
local radix_expressions = {}
if involves_path_match and not is_case_insensitive then
for name,value in pairs(params.path) do
if name == 'equals' or name == 'startsWith' or name == 'endsWith' or name == 'contains' then
if radix_expressions[name] then
level = 'impossible'
break
end
radix_expressions[name] = value
if level == 'partial_pending' or involves_value_match then
level = 'partial'
elseif level ~= 'partial' then
level = 'all'
end
else
if level == 'easy' or level == 'partial' then
level = 'partial'
else
level = 'partial_pending'
end
end
end
if level == 'partial_pending' then
level = 'impossible'
end
end
if level ~= 'impossible' then
match_parts(j.radix_tree,radix_expressions)
return j.radix_elements
else
return nil
end
end
j.add = function(word)
add_to_tree(word)
end
j.remove = function(word)
remove_from_tree(word)
end
j.get_possible_matches = get_possible_matches
-- for unit testing
j.match_parts = function(parts,xxx)
match_parts(j.radix_tree,parts,xxx)
end
j.found_elements = function()
return j.radix_elements
end
return j
end
return {
new = new
}
| mit |
tung/doomrl | bin/lua/items/eitems.lua | 2 | 28603 | function DoomRL.loadexoticitems()
-- Item sets --
register_itemset "gothic"
{
name = "Gothic Arms",
trigger = 2,
OnEquip = function (self,being)
being.flags[ BF_SESSILE ] = true
being.armor = being.armor + 4
being:msg( "Suddenly you feel immobilized. You feel like a fortress!" )
end,
OnRemove = function (self,being)
being.flags[ BF_SESSILE ] = false
being.armor = being.armor - 4
being:msg( "You feel more agile and less protected." )
end,
}
register_itemset "phaseshift"
{
name = "Phaseshift Suit",
trigger = 2,
OnEquip = function (self,being)
being.flags[ BF_ENVIROSAFE ] = true
being:msg( "You start to float!" )
end,
OnRemove = function (self,being)
being.flags[ BF_ENVIROSAFE ] = false
being:msg( "You touch the ground." )
end,
}
register_item "ublaster"
{
name = "blaster",
color = LIGHTMAGENTA,
sprite = SPRITE_PISTOL,
psprite = SPRITE_PLAYER_PISTOL,
level = 8,
weight = 2,
group = "weapon-pistol",
desc = "This is the standard issue rechargeable energy side-arm. Cool!",
flags = { IF_EXOTIC, IF_PISTOL, IF_RECHARGE },
type = ITEMTYPE_RANGED,
ammo_id = "cell",
ammomax = 10,
rechargeamount= 1,
rechargedelay = 3,
damage = "2d4",
damagetype = DAMAGE_PLASMA,
acc = 3,
fire = 9,
reload = 10,
altfire = ALT_AIMED,
missile = "mblaster",
}
register_item "ucpistol"
{
name = "combat pistol",
color = LIGHTMAGENTA,
sprite = SPRITE_PISTOL,
psprite = SPRITE_PLAYER_PISTOL,
level = 4,
weight = 6,
group = "weapon-pistol",
desc = "This is the kind of handgun given to your superiors. Doesn't look like they're using it right now...",
flags = { IF_EXOTIC, IF_PISTOL },
type = ITEMTYPE_RANGED,
ammo_id = "ammo",
ammomax = 15,
damage = "3d3",
damagetype = DAMAGE_BULLET,
acc = 5,
fire = 10,
reload = 18,
altfire = ALT_AIMED,
altreload = RELOAD_DUAL,
missile = "mgun",
}
register_item "uashotgun"
{
name = "assault shotgun",
sound_id = "ashotgun",
color = LIGHTMAGENTA,
sprite = SPRITE_CSHOTGUN,
psprite = SPRITE_PLAYER_CSHOTGUN,
level = 6,
weight = 6,
group = "weapon-shotgun",
desc = "Big, bad and ugly.",
flags = { IF_EXOTIC, IF_SHOTGUN, IF_SINGLERELOAD },
type = ITEMTYPE_RANGED,
ammo_id = "shell",
ammomax = 6,
damage = "7d3",
damagetype = DAMAGE_SHARPNEL,
fire = 10,
reload = 10,
altreload = RELOAD_FULL,
missile = "sfocused",
}
register_item "upshotgun"
{
name = "plasma shotgun",
sound_id = "ashotgun",
color = LIGHTMAGENTA,
sprite = SPRITE_SHOTGUN,
psprite = SPRITE_PLAYER_SHOTGUN,
level = 12,
weight = 4,
group = "weapon-shotgun",
desc = "Plasma shotgun -- the best of two worlds.",
firstmsg = "Splash and they're dead!",
flags = { IF_EXOTIC, IF_SHOTGUN },
type = ITEMTYPE_RANGED,
ammo_id = "cell",
ammomax = 30,
shotcost = 3,
damage = "7d3",
damagetype = DAMAGE_PLASMA,
fire = 10,
reload = 20,
-- TODO Confirm if plasma shotgun does not use alt-reload
--altreload = RELOAD_FULL,
missile = "splasma",
}
register_item "udshotgun"
{
name = "super shotgun",
sound_id = "dshotgun",
color = LIGHTMAGENTA,
sprite = SPRITE_DSHOTGUN,
psprite = SPRITE_PLAYER_DSHOTGUN,
level = 10,
weight = 5,
group = "weapon-shotgun",
desc = "After the first hellish invasion, weapon engineers designed the super shotgun as the world's first firearm designed to kill demons. And boy does it do a good job.",
firstmsg = "This little baby brings back memories!",
flags = { IF_EXOTIC, IF_SHOTGUN, IF_DUALSHOTGUN },
type = ITEMTYPE_RANGED,
ammo_id = "shell",
ammomax = 2,
damage = "8d4",
damagetype = DAMAGE_SHARPNEL,
fire = 10,
reload = 15,
shots = 2,
missile = "snormal",
}
register_item "ulaser"
{
name = "laser rifle",
sound_id = "plasma",
color = LIGHTMAGENTA,
sprite = SPRITE_PLASMA,
psprite = SPRITE_PLAYER_PLASMA,
level = 12,
weight = 5,
group = "weapon-plasma",
desc = "With no recoil and pinpoint accuracy, it takes a world-class moron to miss while using a laser rifle.",
firstmsg = "The sniper chain weapon!",
flags = { IF_EXOTIC },
type = ITEMTYPE_RANGED,
ammo_id = "cell",
ammomax = 40,
damage = "1d7",
damagetype = DAMAGE_PLASMA,
acc = 8,
fire = 10,
reload = 15,
shots = 5,
altfire = ALT_CHAIN,
missile = {
sound_id = "plasma",
color = MULTIYELLOW,
sprite = SPRITE_CSHOT,
coscolor = { 1.0, 1.0, 0.0, 1.0 },
delay = 10,
miss_base = 10,
miss_dist = 3,
},
}
register_item "utristar"
{
name = "tristar blaster",
sound_id = "plasma",
color = LIGHTMAGENTA,
sprite = SPRITE_DSHOTGUN,
psprite = SPRITE_PLAYER_DSHOTGUN,
level = 12,
weight = 4,
group = "weapon-plasma",
desc = "Now this is a weird weapon.",
firstmsg = "Quite bulky!",
flags = { IF_EXOTIC, IF_SPREAD },
type = ITEMTYPE_RANGED,
ammo_id = "cell",
ammomax = 45,
damage = "4d5",
damagetype = DAMAGE_PLASMA,
acc = 5,
fire = 10,
radius = 2,
reload = 15,
shots = 3,
shotcost = 5,
missile = {
sound_id = "plasma",
ascii = "*",
color = LIGHTBLUE,
sprite = SPRITE_PLASMASHOT,
delay = 20,
miss_base = 1,
miss_dist = 3,
expl_delay = 40,
expl_color = LIGHTBLUE,
},
}
register_item "uminigun"
{
name = "minigun",
color = LIGHTMAGENTA,
sprite = SPRITE_CHAINGUN,
psprite = SPRITE_PLAYER_CHAINGUN,
level = 10,
weight = 6,
group = "weapon-chain",
desc = "Spits enough lead into the air to be considered an environmental hazard.",
flags = { IF_EXOTIC },
type = ITEMTYPE_RANGED,
ammo_id = "ammo",
ammomax = 200,
damage = "1d6",
damagetype = DAMAGE_BULLET,
acc = 1,
fire = 12,
reload = 35,
shots = 8,
altfire = ALT_CHAIN,
missile = "mchaingun",
}
register_item "umbazooka"
{
name = "missile launcher",
color = LIGHTMAGENTA,
sprite = SPRITE_BAZOOKA,
psprite = SPRITE_PLAYER_BAZOOKA,
level = 10,
weight = 6,
group = "weapon-rocket",
desc = "The definitive upgrade to the rocket launcher.",
flags = { IF_EXOTIC, IF_ROCKET, IF_SINGLERELOAD },
type = ITEMTYPE_RANGED,
ammo_id = "rocket",
ammomax = 4,
damage = "6d6",
damagetype = DAMAGE_FIRE,
acc = 10,
fire = 8,
radius = 3,
reload = 12,
altreload = RELOAD_FULL,
missile = "mrocket",
}
register_item "unplasma"
{
name = "nuclear plasma rifle",
color = LIGHTMAGENTA,
sprite = SPRITE_PLASMA,
psprite = SPRITE_PLAYER_PLASMA,
level = 15,
weight = 4,
group = "weapon-plasma",
desc = "A self-charging plasma rifle -- too bad it can't be manually reloaded.",
flags = { IF_EXOTIC, IF_RECHARGE },
type = ITEMTYPE_RANGED,
ammo_id = "cell",
ammomax = 24,
rechargeamount= 4,
rechargedelay = 4,
damage = "1d7",
damagetype = DAMAGE_PLASMA,
acc = 2,
fire = 10,
reload = 20,
shots = 6,
altfire = ALT_CHAIN,
altreload = RELOAD_SCRIPT,
altreloadname = "overcharge",
missile = "mplasma",
OnAltReload = function(self, being)
local floor_cell = cells[ level.map[ being.position ] ]
if floor_cell.flags[CF_STAIRS] then
ui.msg("Better not do this on the stairs...");
return false
end
if not self:can_overcharge("This will overload the nuclear reactor...") then return false end
if floor_cell.flags[CF_HAZARD] then
ui.msg("Somehow, in an instant, you feel like an idiot...");
being:nuke(1)
else
ui.msg("Warning! Explosion in 10 seconds!")
being:nuke(100)
end
player:add_history("He overloaded a nuclear plasma rifle on level @1!")
being.eq.weapon = nil
being.scount = being.scount - 1000
return true
end,
}
register_item "unbfg9000"
{
name = "nuclear BFG 9000",
color = LIGHTMAGENTA,
sprite = SPRITE_BFG9000,
psprite = SPRITE_PLAYER_BFG9000,
level = 22,
weight = 2,
group = "weapon-bfg",
desc = "A self-charging BFG9000! How much more lucky can you get?",
flags = { IF_EXOTIC, IF_RECHARGE },
type = ITEMTYPE_RANGED,
ammo_id = "cell",
ammomax = 40,
rechargeamount= 1,
rechargedelay = 0,
damage = "8d6",
damagetype = DAMAGE_SPLASMA,
acc = 5,
fire = 15,
radius = 8,
reload = 20,
shotcost = 40,
altreload = RELOAD_SCRIPT,
altreloadname = "overcharge",
overcharge = "mbfgover",
missile = "mbfg",
OnAltReload = function(self, being)
local floor_cell = cells[ level.map[ being.position ] ]
if floor_cell.flags[CF_STAIRS] then
ui.msg("Better not do this on the stairs...");
return false
end
if not self:can_overcharge("This will overload the nuclear reactor...") then return false end
if floor_cell.flags[CF_HAZARD] then
ui.msg("Somehow, in an instant, you feel like an idiot...");
being:nuke(1)
else
ui.msg("Warning! Explosion in 10 seconds!")
being:nuke(100)
end
player:add_history("He overloaded a nuclear BFG 9000 on level @1!")
being.eq.weapon = nil
being.scount = being.scount - 1000
return true
end,
}
register_item "utrans"
{
name = "combat translocator",
color = LIGHTMAGENTA,
sprite = SPRITE_PLASMA,
psprite = SPRITE_PLAYER_PLASMA,
level = 14,
weight = 3,
group = "weapon-plasma",
desc = "Now this is a piece of weird technology, wonder how it works?",
firstmsg = "Well this is a weird device!",
flags = { IF_EXOTIC, IF_NONMODABLE },
type = ITEMTYPE_RANGED,
ammo_id = "cell",
ammomax = 60,
damage = "0d0",
damagetype = DAMAGE_PLASMA,
acc = 4,
fire = 15,
reload = 20,
shotcost = 10,
missile = "mplasma",
OnHitBeing = function(self,being,target)
target:play_sound("soldier.phase")
being:msg("Suddenly "..target:get_name(true,false).." blinks away!")
level:explosion( target.position, 2, 50, 0, 0, LIGHTBLUE )
target:phase()
return false
end,
}
register_item "unapalm"
{
name = "napalm launcher",
color = LIGHTMAGENTA,
sprite = SPRITE_BAZOOKA,
psprite = SPRITE_PLAYER_BAZOOKA,
level = 10,
weight = 6,
group = "weapon-rocket",
desc = "This will surely make a mess!",
flags = { IF_EXOTIC, IF_ROCKET, IF_SINGLERELOAD },
type = ITEMTYPE_RANGED,
ammo_id = "rocket",
ammomax = 1,
damage = "7d7",
damagetype = DAMAGE_FIRE,
acc = 10,
fire = 8,
radius = 2,
reload = 12,
missile = {
sound_id = "bazooka",
color = BROWN,
sprite = SPRITE_ROCKETSHOT,
delay = 10,
miss_base = 30,
miss_dist = 5,
expl_delay = 80,
expl_color = RED,
content = "lava",
},
}
register_item "uoarmor"
{
name = "onyx armor",
color = LIGHTMAGENTA,
sprite = SPRITE_ARMOR,
coscolor = { 0.1,0.1,0.1,1.0 },
level = 7,
weight = 4,
desc = "This thing looks absurdly resistant.",
flags = { IF_EXOTIC, IF_NODURABILITY },
type = ITEMTYPE_ARMOR,
armor = 2,
movemod = -25,
}
register_item "uparmor"
{
name = "phaseshift armor",
color = LIGHTMAGENTA,
sprite = SPRITE_ARMOR,
coscolor = { 0.2,1.0,0.2,1.0 },
level = 10,
weight = 6,
set = "phaseshift",
desc = "Shiny and high-tech, feels like it almost floats by itself.",
flags = { IF_EXOTIC },
resist = { bullet = 30, melee = 30, shrapnel = 30 },
type = ITEMTYPE_ARMOR,
armor = 2,
movemod = 25,
knockmod = 50,
}
register_item "upboots"
{
name = "phaseshift boots",
color = LIGHTMAGENTA,
sprite = SPRITE_BOOTS,
coscolor = { 0.2,1.0,0.2,1.0 },
level = 8,
weight = 6,
set = "phaseshift",
desc = "Shiny and high-tech, feels like they almost float by themselves.",
flags = { IF_EXOTIC, IF_PLURALNAME },
type = ITEMTYPE_BOOTS,
armor = 4,
movemod = 15,
knockmod = 20,
}
register_item "ugarmor"
{
name = "gothic armor",
color = LIGHTMAGENTA,
sprite = SPRITE_ARMOR,
coscolor = { 0.7,0.0,0.0,1.0 },
level = 15,
weight = 6,
set = "gothic",
desc = "It's surprising that one can actually still move in this monolithic thing.",
flags = { IF_EXOTIC },
resist = { bullet = 50, melee = 50, shrapnel = 50 },
type = ITEMTYPE_ARMOR,
armor = 6,
durability = 200,
movemod = -70,
knockmod = -90,
}
register_item "ugboots"
{
name = "gothic boots",
color = LIGHTMAGENTA,
sprite = SPRITE_BOOTS,
coscolor = { 0.7,0.0,0.0,1.0 },
level = 10,
weight = 6,
set = "gothic",
desc = "It's surprising that one can actually still move in these monolithic boots.",
flags = { IF_EXOTIC, IF_PLURALNAME },
type = ITEMTYPE_BOOTS,
armor = 10,
durability = 200,
movemod = -15,
knockmod = -70,
}
register_item "umedarmor"
{
name = "medical armor",
color = LIGHTMAGENTA,
sprite = SPRITE_ARMOR,
coscolor = { 1.0,0.2,0.2,1.0 },
level = 5,
weight = 6,
desc = "Handy stuff on the battlefield, why don't they give it to regular marines?",
flags = { IF_EXOTIC },
resist = { bullet = 20, melee = 20, shrapnel = 20},
type = ITEMTYPE_ARMOR,
armor = 2,
movemod = -15,
OnEquipTick = function(self, being)
if self.durability > 20 then
if being.hp < being.hpmax / 4 then
being.hp = being.hp + 1
self.durability = self.durability - 1
end
end
end,
}
register_item "uduelarmor"
{
name = "duelist armor",
color = LIGHTMAGENTA,
sprite = SPRITE_ARMOR,
coscolor = { 0.4,0.4,0.4,1.0 },
level = 5,
weight = 6,
desc = "A little archaic, but a surprisingly well-kept armor.",
flags = { IF_EXOTIC },
resist = { bullet = 50, melee = 50, shrapnel = 50},
type = ITEMTYPE_ARMOR,
armor = 2,
movemod = 15,
knockmod = -15,
}
register_item "ubulletarmor"
{
name = "bullet-proof vest",
color = LIGHTMAGENTA,
sprite = SPRITE_ARMOR,
coscolor = { 0.6,0.6,0.6,1.0 },
level = 2,
weight = 4,
desc = "Maybe too specialized for most tastes.",
flags = { IF_EXOTIC },
resist = { bullet = 80 },
type = ITEMTYPE_ARMOR,
armor = 1,
}
register_item "uballisticarmor"
{
name = "ballistic vest",
color = LIGHTMAGENTA,
sprite = SPRITE_ARMOR,
coscolor = { 0.2,0.6,0.2,1.0 },
level = 2,
weight = 5,
desc = "Might serve one well in the beginning.",
flags = { IF_EXOTIC },
resist = { bullet = 50, melee = 50, shrapnel = 50 },
type = ITEMTYPE_ARMOR,
armor = 1,
}
register_item "ueshieldarmor"
{
name = "energy-shielded vest",
color = LIGHTMAGENTA,
sprite = SPRITE_ARMOR,
coscolor = { 1.0,0.6,0.0,1.0 },
level = 5,
weight = 3,
desc = "If it just wouldn't be so fragile...",
flags = { IF_EXOTIC },
resist = { fire = 50, acid = 50, plasma = 50 },
type = ITEMTYPE_ARMOR,
armor = 1,
}
register_item "uplasmashield"
{
name = "plasma shield",
color = LIGHTMAGENTA,
sprite = SPRITE_ARMOR,
coscolor = { 1.0,0.0,1.0,1.0 },
level = 10,
weight = 3,
desc = "Under some circumstances, this is the best thing... too bad it can't be repaired.",
flags = { IF_EXOTIC, IF_NOREPAIR, IF_NONMODABLE, IF_NODEGRADE },
resist = { plasma = 95 },
type = ITEMTYPE_ARMOR,
armor = 0,
}
register_item "uenergyshield"
{
name = "energy shield",
color = LIGHTMAGENTA,
sprite = SPRITE_ARMOR,
coscolor = { 1.0,0.8,0.0,1.0 },
level = 8,
weight = 3,
desc = "Under some circumstances, this is the best thing... too bad it can't be repaired.",
flags = { IF_EXOTIC, IF_NOREPAIR, IF_NONMODABLE, IF_NODEGRADE },
resist = { fire = 80, acid = 80, plasma = 80 },
type = ITEMTYPE_ARMOR,
armor = 0,
}
register_item "ubalshield"
{
name = "ballistic shield",
color = LIGHTMAGENTA,
sprite = SPRITE_ARMOR,
coscolor = { 0.8,0.8,0.3,1.0 },
level = 6,
weight = 3,
desc = "Under some circumstances, this is the best thing... too bad it can't be repaired.",
flags = { IF_EXOTIC, IF_NOREPAIR, IF_NONMODABLE, IF_NODEGRADE },
resist = { bullet = 95, melee = 95, shrapnel = 95 },
type = ITEMTYPE_ARMOR,
armor = 0,
}
register_item "uacidboots"
{
name = "acid-proof boots",
color = LIGHTMAGENTA,
sprite = SPRITE_BOOTS,
coscolor = { 0.2,1.0,0.0,1.0 },
level = 8,
weight = 5,
desc = "The best thing to carry for an acid-bath.",
flags = { IF_EXOTIC, IF_PLURALNAME },
resist = { acid = 100 },
type = ITEMTYPE_BOOTS,
armor = 0,
}
-- Exotic Mods
register_item "umod_firestorm"
{
name = "firestorm weapon pack",
ascii = "\"",
color = RED,
sprite = SPRITE_MOD,
coscolor = { 1.0,0.0,1.0,1.0 },
level = 10,
weight = 4,
desc = "A modification for rapid or explosive weapons -- increases shots by 2 for rapid, and blast radius by 2 for explosive weapons.",
flags = { IF_EXOTIC },
type = ITEMTYPE_PACK,
mod_letter = "F",
OnUseCheck = function(self,being)
if not being:is_player() then return false end
local item = being.eq.weapon
if not item then
ui.msg( "Nothing to modify!" )
return false
end
if item:check_mod_array( 'F', being.techbonus ) then
self:add_property( "assembled" )
return true
end
if not item:can_mod( 'F' ) then
ui.msg( "This weapon can't be modded any more!" )
return false
end
if item.itype ~= ITEMTYPE_RANGED then
ui.msg( "This weapon can't be modified!" )
return false
end
return true
end,
OnUse = function(self,being)
if self:has_property( "assembled" ) then return true end
local item = being.eq.weapon
if item.shots >= 3 then
item.shots = item.shots + 2
elseif item.blastradius >= 3 then
item.blastradius = item.blastradius + 2
else
ui.msg( "Only a rapid-fire or explosive weapon can be modded!" )
return false
end
ui.msg( "You upgrade your weapon!" )
item:add_mod( 'F' )
return true
end,
}
register_item "umod_sniper"
{
name = "sniper weapon pack",
ascii = "\"",
color = MAGENTA,
sprite = SPRITE_MOD,
coscolor = { 1.0,0.0,1.0,1.0 },
level = 10,
weight = 4,
desc = "A high-tech modification for ranged weapons -- implements an advanced auto-hit mechanism.",
flags = { IF_EXOTIC },
type = ITEMTYPE_PACK,
mod_letter = "S",
OnUseCheck = function(self,being)
if not being:is_player() then return false end
local item = being.eq.weapon
if not item then
ui.msg( "Nothing to modify!" )
return false
end
if item:check_mod_array( 'S', being.techbonus ) then
self:add_property( "assembled" )
return true
end
--[[
if item.flags[ IF_SHOTGUN ] or item.itype ~= ITEMTYPE_RANGED then
ui.msg( "This weapon can't be modified!" )
return false
end
--]]
if not item:can_mod( 'S' ) then
ui.msg( "This weapon can't be modded any more!" )
return false
end
return true
end,
OnUse = function(self,being)
if self:has_property( "assembled" ) then return true end
local item = being.eq.weapon
if item.flags[IF_FARHIT] == true then
item.flags[IF_UNSEENHIT] = true
else
item.flags[IF_FARHIT] = true
end
-- A little easter egg for applying S-mod on shotgun/melee
if item.flags[ IF_SHOTGUN ] or item.itype ~= ITEMTYPE_RANGED then
ui.msg( "You suddenly feel a little silly." )
else
ui.msg( "You upgrade your weapon!" )
end
item:add_mod( 'S' )
return true
end,
}
register_item "umod_nano"
{
name = "nano pack",
ascii = "\"",
color = GREEN,
sprite = SPRITE_MOD,
coscolor = { 0.5,0.5,1.0,1.0 },
level = 10,
weight = 4,
desc = "Nanotechnology -- modified weapon reconstructs shot ammo, modified armor/boots reconstruct itself",
flags = { IF_EXOTIC },
type = ITEMTYPE_PACK,
mod_letter = "N",
OnUseCheck = function(self,being)
if not being:is_player() then return false end
local item, result = being:pick_mod_item('N', being.techbonus )
if not result then return false end
if item and item.itype == ITEMTYPE_MELEE then
ui.msg( "Nanotechnology doesn't work on melee weapons!" )
return false
elseif item and item.itype == ITEMTYPE_RANGED and (item.rechargedelay == 0 and item.rechargeamount >= item.ammomax) then
ui.msg( "This weapon can't be modified anymore with this mod!" )
return false
end
if item ~= nil then self:add_property( "chosen_item", item ) end
return true
end,
OnUse = function(self,being)
if not self:has_property( "chosen_item" ) then return true end
local item = self.chosen_item
ui.msg( "You upgrade your gear!" )
item:add_mod( 'N' )
if item.flags[ IF_RECHARGE ] then
if item.rechargedelay == 0 then
item.rechargeamount = item.rechargeamount + 1
else
item.rechargedelay = math.max(0, item.rechargedelay - 5)
end
else
item.flags[ IF_RECHARGE ] = true
item.rechargedelay = 5
if item.itype == ITEMTYPE_ARMOR or item.itype == ITEMTYPE_BOOTS then
item.rechargeamount = 2
elseif item.itype == ITEMTYPE_RANGED then
item.rechargeamount = 1
end
end
return true
end,
}
register_item "umod_onyx"
{
name = "onyx armor pack",
ascii = "\"",
color = LIGHTGRAY,
sprite = SPRITE_MOD,
coscolor = { 0.0,0.0,0.0,1.0 },
level = 10,
weight = 4,
desc = "A modification for boots and armors -- makes them indestructible.",
flags = { IF_EXOTIC },
type = ITEMTYPE_PACK,
mod_letter = "O",
OnUseCheck = function(self,being)
if not being:is_player() then return false end
local item, result = being:pick_mod_item('O', being.techbonus )
if not result then return false end
if item and not ( item.itype == ITEMTYPE_ARMOR or item.itype == ITEMTYPE_BOOTS ) then
ui.msg( "Only boots or armor can be modded with this mod!" )
return false
end
if item ~= nil then self:add_property( "chosen_item", item ) end
return true
end,
OnUse = function(self,being)
if not self:has_property( "chosen_item" ) then return true end
local item = self.chosen_item
ui.msg( "You upgrade your gear!" )
item.durability = 100
item.flags[ IF_NODURABILITY ] = true
item:add_mod( 'O' )
return true
end,
}
register_item "uswpack"
{
name = "shockwave pack",
ascii = "+",
color = LIGHTMAGENTA,
sprite = SPRITE_PHASE,
coscolor = { 0.7,0.0,0.0,1.0 },
level = 5,
weight = 10,
desc = "Woah, what a useful device. Just wait for them to surround you...",
flags = { IF_EXOTIC },
type = ITEMTYPE_PACK,
OnUse = function(self,being)
ui.blink(LIGHTRED,50)
level:explosion( being.position , 6, 50, 10, 10, RED, "barrel.explode", DAMAGE_FIRE, self, { EFSELFSAFE } )
return true
end,
}
register_item "ubskull"
{
name = "blood skull",
ascii = "+",
color = LIGHTMAGENTA,
sprite = SPRITE_SKULL,
coscolor = { 1.0,0.0,0.0,1.0 },
level = 5,
weight = 8,
desc = "This skull gives you the shivers... like it would lust for blood.",
flags = { IF_EXOTIC },
type = ITEMTYPE_PACK,
OnUse = function(self,being)
ui.blink(LIGHTRED,50)
local p = being.position
for c in area.around( p, 8 ):clamped( area.FULL ):coords() do
if coord.distance( c, p ) <= 8 and level:is_corpse( c ) then
level.map[ c ] = "bloodpool"
being:play_sound( "gib" )
being.hp = math.min( being.hp + 5, being.hpmax * 2 )
being.tired = false
end
end
return true
end,
}
register_item "ufskull"
{
name = "fire skull",
ascii = "+",
color = LIGHTMAGENTA,
sprite = SPRITE_SKULL,
coscolor = { 1.0,1.0,0.0,1.0 },
level = 7,
weight = 8,
desc = "This skull gives you the shivers... you feel instability.",
flags = { IF_EXOTIC },
type = ITEMTYPE_PACK,
OnUse = function(self,being)
ui.blink(YELLOW,50)
local p = being.position
for c in area.around( p, 8 ):clamped( area.FULL ):coords() do
if coord.distance( c, p ) <= 8 and level:is_corpse( c ) then
level.map[ c ] = "bloodpool"
being:play_sound( "gib" )
level:explosion( c , 3, 50, 7, 7, RED, "barrel.explode", DAMAGE_FIRE, self, { EFSELFSAFE } )
end
end
return true
end,
}
register_item "uhskull"
{
name = "hatred skull",
ascii = "+",
color = LIGHTMAGENTA,
sprite = SPRITE_SKULL,
coscolor = { 1.0,0.7,0.0,1.0 },
level = 9,
weight = 8,
desc = "This skull gives you the shivers... as if it were filled with hatred.",
flags = { IF_EXOTIC },
type = ITEMTYPE_PACK,
OnUse = function(self,being)
ui.blink(LIGHTRED,50)
local p = being.position
local count = 0
for c in area.around( p, 8 ):clamped( area.FULL ):coords() do
if coord.distance( c, p ) <= 8 and level:is_corpse( c ) then
level.map[ c ] = "bloodpool"
being:play_sound( "gib" )
count = count + 1
end
end
if count > 0 then
being:set_affect( "berserk", count * 5 )
being.tired = false
end
return true
end,
}
-- "Normal" exotics
register_item "chainsaw"
{
name = "chainsaw",
color = LIGHTMAGENTA,
sprite = SPRITE_CHAINSAW,
psprite = SPRITE_PLAYER_CHAINSAW,
level = 12,
weight = 3,
group = "weapon-melee",
desc = "Chainsaw -- cuts through flesh like a hot knife through butter.",
flags = { IF_EXOTIC },
type = ITEMTYPE_MELEE,
damage = "4d6",
damagetype = DAMAGE_MELEE,
OnFirstPickup = function(self,being)
if not being:is_player() then return end
ui.blink(LIGHTRED,100)
-- XXX Should this be given on first pick-up ALWAYS or only when in chain court?
being:set_affect( "berserk",40*diff[DIFFICULTY].powerfactor)
if not being.flags[ BF_NOHEAL ] and being.hp < being.hpmax then
being.hp = being.hpmax
end
being.tired = false
being:quick_weapon("chainsaw")
ui.msg("BLOOD! BLOOD FOR ARMOK, GOD OF BLOOD!")
end
}
register_item "bfg9000"
{
name = "BFG 9000",
color = LIGHTMAGENTA,
sprite = SPRITE_BFG9000,
psprite = SPRITE_PLAYER_BFG9000,
level = 20,
weight = 2,
group = "weapon-bfg",
desc = "The Big Fucking Gun. Hell wouldn't be fun without it.",
flags = { IF_EXOTIC },
type = ITEMTYPE_RANGED,
ammo_id = "cell",
ammomax = 100,
damage = "10d6",
damagetype = DAMAGE_SPLASMA,
acc = 5,
fire = 10,
radius = 8,
reload = 20,
shotcost = 40,
altreload = RELOAD_SCRIPT,
altreloadname = "overcharge",
overcharge = "mbfgover",
missile = "mbfg",
OnFirstPickup = function(self,being)
if not being:is_player() then return end
being:quick_weapon("bfg9000")
ui.blink(LIGHTBLUE,100)
ui.blink(WHITE,100)
ui.blink(LIGHTBLUE,100)
ui.msg("HELL, NOW YOU'LL GET LOOSE!")
end,
OnAltReload = function(self)
if not self:can_overcharge("This will destroy the weapon after the next shot...") then return false end
self.missile = missiles[ "mbfgover" ].nid
self.blastradius = self.blastradius * 2
self.damage_dice = self.damage_dice + 2
self.shotcost = self.ammomax
self.ammomax = self.shotcost
self.ammo = self.shotcost
return true
end,
}
end
| gpl-2.0 |
pSyChOoOo/TeleSeed | plugins/banhammer.lua | 1085 | 11557 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
Whit3Tig3R/FuCk3R | plugins/banhammer.lua | 1085 | 11557 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
andeandr100/Crumbled-World | Lua/MapEditor/Tools/islandPaintTool.lua | 1 | 6742 | require("MapEditor/Tools/Tool.lua")
require("MapEditor/menuStyle.lua")
require("MapEditor/Tools/circleModel.lua")
require("MapEditor/textureSelectionMenu.lua")
function destroy()
if textureSelectionMenu then
textureSelectionMenu.destroy()
end
end
function replaceTexture(textureName)
if paintConfig["Texture"..changeTextureId] == textureName then
--Texture was not changed
return
end
--Texture has been changed
paintConfig["Texture"..changeTextureId] = textureName
local texture = Core.getTexture(textureName)
textureButton[changeTextureId]:setTexture( texture )
toolConfig:get("islandPaintbrushTool"):setTable(paintConfig)
toolConfig:save()
--Replace all textures on all islands
local islands = this:getRootNode():findAllNodeByTypeTowardsLeaf(NodeId.island)
for i=1, #islands do
islands[i]:setIslandTexture(changeTextureId, texture)
end
end
--this = SceneNode()
function changeTexture(button)
textureId = tonumber(button:getTag():toString())
end
function showTextureSelectMenu(button)
changeTextureId = tonumber(button:getTag():toString())
textureSelectionMenu.setVisible(true)
end
function addButtonTexture(buttonPanel, textureName, tag)
local texture = Core.getTexture(textureName)
local panelWidthFor4 = toolAndSettingMenuSize - 0.005 * 3 - 0.005
local buttonWidth = panelWidthFor4 * 0.25
local button = buttonPanel:add(Button(PanelSize(Vec2(buttonWidth,1), Vec2(1)), ButtonStyle.SQUARE, texture, Vec2(), Vec2(1)))
button:setInnerColor(Vec4(0),Vec4(0), Vec4(0))
button:setInnerHoverColor(Vec4(0,0,0,0),Vec4(1,1,1,0.25), Vec4(1,1,1,0.25))
button:setInnerDownColor(Vec4(0,0,0,0.3),Vec4(0.2,0.2,0.2,0.7), Vec4(0.1,0.1,0.1,0.6))
button:setTag(tag)
button:addEventCallbackExecute(changeTexture);
return button
end
function changeSettings(textField)
if paintConfig[textField:getTag():toString()] then
paintConfig[textField:getTag():toString()] = textField:getFloat()
end
if textField:getTag():toString() == "range" then
CircleModel.create(paintConfig.range)
end
toolConfig:get("islandPaintbrushTool"):setTable(paintConfig)
toolConfig:save()
end
function createMenu(panel)
panel:add(Label(PanelSize(Vec2(-0.66, MenuStyle.rowHeight)),"Range", Vec3(1)))
textFieldRange = panel:add(TextField(PanelSize(Vec2(-1, MenuStyle.rowHeight)), tostring(paintConfig.range)))
textFieldRange:setWhiteList(".0123456789")
textFieldRange:addEventCallbackExecute(changeSettings)
textFieldRange:setTag("range")
panel:add(Label(PanelSize(Vec2(-0.66, MenuStyle.rowHeight)),"Power", Vec3(1)))
textFieldPower = panel:add(TextField(PanelSize(Vec2(-1, MenuStyle.rowHeight)), tostring(paintConfig.power)))
textFieldPower:setWhiteList(".0123456789")
textFieldPower:addEventCallbackExecute(changeSettings)
textFieldPower:setTag("power")
local buttonPanel = panel:add(Panel(PanelSize(Vec2(-1,-1),Vec2(4,1))))
buttonPanel:setLayout(GridLayout(1,4,Alignment.TOP_RIGHT))
textureButton = {}
textureButton[1] = addButtonTexture(buttonPanel, paintConfig["Texture1"], "0")
textureButton[2] = addButtonTexture(buttonPanel, paintConfig["Texture2"], "1")
textureButton[3] = addButtonTexture(buttonPanel, paintConfig["Texture3"], "2")
local buttonChangeTexturePanel = panel:add(Panel(PanelSize(Vec2(1,1),Vec2(4,0.3),PanelSizeType.ParentPercent)))
buttonChangeTexturePanel:setLayout(GridLayout(1,4))
for i=1, 3 do
local button = buttonChangeTexturePanel:add(Button(PanelSize(Vec2(-1)), "Change"))
button:addEventCallbackExecute(showTextureSelectMenu)
button:setTag(tostring(i))
end
--Needed for an panel ERROR
local buttonPanel = panel:add(Panel(PanelSize(Vec2(-1,-1),Vec2(8,1))))
end
function setDefaultValue(name, value)
if not paintConfig[name] then
paintConfig[name] = value
end
end
function create()
textureId = 1
Tool.create()
Tool.enableChangeOfSelectedScene = false
textureSelectionMenu = TextureSelectionMenu.new(replaceTexture)
--Get billboard for the map editor
local mapEditor = Core.getBillboard("MapEditor")
--Get the Tool panel
local toolPanel = mapEditor:getPanel("ToolPanel")
--Get the setting panel
local settingsPanel = mapEditor:getPanel("SettingPanel")
camera = this:getRootNode():findNodeByType(NodeId.camera)
--Load config
toolConfig = Config("ToolsSettings")
--Get the ligt tool config settings
paintConfig = toolConfig:get("islandPaintbrushTool"):getTable()
setDefaultValue("range", 2)
setDefaultValue("power", 2.5)
setDefaultValue("Texture1", "gt_grass_d.dds")
setDefaultValue("Texture2", "gt_dirtgrass_d.dds")
setDefaultValue("Texture3", "gt_dirt_d.dds")
CircleModel.init()
CircleModel.create( paintConfig.range )
CircleModel.mesh:setVisible(false)
if settingsPanel then
titlePanel, bodyPanel = MenuStyle.createTitleAndBody(settingsPanel, "Paint tool")
--body = Panel()
titlePanel:setVisible(false)
createMenu(bodyPanel)
end
editorListener = Listener("Editor")
editorListener:registerEvent("newMap", newMap)
editorListener:registerEvent("loadedMap", loadedMap)
return true
end
function newMap()
end
function loadedMap()
local island = this:getRootNode():findNodeByTypeTowardsLeafe(NodeId.island)
--island = Island()
if island then
for i=1, 3 do
local texture = island:getIslandTexture(i)
changeTextureId = i
replaceTexture(texture:getName():toString())
end
end
end
function Loaded(inTable)
deActivated()
end
--Called when the tool has been activated
function activated()
titlePanel:setVisible(true)
CircleModel.mesh:setVisible(true)
end
--Called when tool is being deactivated
function deActivated()
titlePanel:setVisible(false)
CircleModel.mesh:setVisible(false)
end
--As long as the tool is active update is caled
function update()
textureSelectionMenu.update()
--Do collision check
local island, collisionPos, collisionNormal = Tool.getCollision(false, false)
--island = Island()
if island then
CircleModel.setPosition(collisionPos, Vec3(0,1,0))
CircleModel.mesh:setVisible(true)
else
CircleModel.mesh:setVisible(false)
end
if island and Core.getInput():getMouseHeld(MouseKey.left) then
if textureId == 0 then
island:setPaintBrushColor(Vec3(1,0,0))
elseif textureId == 1 then
island:setPaintBrushColor(Vec3(0,1,0))
elseif textureId == 2 then
island:setPaintBrushColor(Vec3(0,0,1))
end
island:paint(collisionPos, paintConfig.range, Core.getDeltaTime() * paintConfig.power)
elseif island then
end
--Update basic tool
Tool.update()
return true
end | mit |
martinfelis/ggj15 | Quickie/init.lua | 17 | 1815 | --[[
Copyright (c) 2012 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local BASE = (...) .. '.'
assert(not BASE:match('%.init%.$'), "Invalid require path `"..(...).."' (drop the `.init').")
return {
core = require(BASE .. 'core'),
group = require(BASE .. 'group'),
mouse = require(BASE .. 'mouse'),
keyboard = require(BASE .. 'keyboard'),
Button = require(BASE .. 'button'),
Slider = require(BASE .. 'slider'),
Slider2D = require(BASE .. 'slider2d'),
Label = require(BASE .. 'label'),
Input = require(BASE .. 'input'),
Checkbox = require(BASE .. 'checkbox')
}
| apache-2.0 |
fakechris/Atlas | examples/tutorial-resultset.lua | 40 | 3110 | --[[ $%BEGINLICENSE%$
Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the
License.
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 St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
--[[
--]]
-- init the query-counter if it isn't done yet
if not proxy.global.query_counter then
proxy.global.query_counter = 0
end
local query_counter = 0
---
-- read_query() can return a resultset
--
-- You can use read_query() to return a result-set.
--
-- @param packet the mysql-packet sent by the client
--
-- @return
-- * nothing to pass on the packet as is,
-- * proxy.PROXY_SEND_QUERY to send the queries from the proxy.queries queue
-- * proxy.PROXY_SEND_RESULT to send your own result-set
--
function read_query( packet )
-- a new query came in in this connection
proxy.global.query_counter = proxy.global.query_counter + 1
query_counter = query_counter + 1
if string.byte(packet) == proxy.COM_QUERY then
--[[
we use a simple string-match to split commands are word-boundaries
mysql> show querycounter
is split into
command = "show"
option = "querycounter"
spaces are ignored, the case has to be as is.
mysql> show myerror
returns a error-packet
--]]
-- try to match the string up to the first non-alphanum
local f_s, f_e, command = string.find(packet, "^%s*(%w+)", 2)
local option
if f_e then
-- if that match, take the next sub-string as option
f_s, f_e, option = string.find(packet, "^%s+(%w+)", f_e + 1)
end
-- we got our commands, execute it
if string.lower(command) == "show" and string.lower(option) == "querycounter" then
---
-- proxy.PROXY_SEND_RESULT requires
--
-- proxy.response.type to be either
-- * proxy.MYSQLD_PACKET_OK or
-- * proxy.MYSQLD_PACKET_ERR
--
-- for proxy.MYSQLD_PACKET_OK you need a resultset
-- * fields
-- * rows
--
-- for proxy.MYSQLD_PACKET_ERR
-- * errmsg
proxy.response.type = proxy.MYSQLD_PACKET_OK
proxy.response.resultset = {
fields = {
{ type = proxy.MYSQL_TYPE_LONG, name = "global_query_counter", },
{ type = proxy.MYSQL_TYPE_LONG, name = "query_counter", },
},
rows = {
{ proxy.global.query_counter, query_counter }
}
}
-- we have our result, send it back
return proxy.PROXY_SEND_RESULT
elseif string.lower(command) == "show" and string.lower(option) == "myerror" then
proxy.response.type = proxy.MYSQLD_PACKET_ERR
proxy.response.errmsg = "my first error"
return proxy.PROXY_SEND_RESULT
end
end
end
| gpl-2.0 |
dkogan/notion.xfttest | etc/cfg_notioncore.lua | 1 | 14636 | --
-- Notion core configuration file
--
--
-- Bindings. This includes global bindings and bindings common to
-- screens and all types of frames only. See modules' configuration
-- files for other bindings.
--
-- WScreen context bindings
--
-- The bindings in this context are available all the time.
--
-- The variable META should contain a string of the form 'Mod4+'
-- where Mod4 maybe replaced with the modifier you want to use for most
-- of the bindings. Similarly ALTMETA may be redefined to add a
-- modifier to some of the F-key bindings.
defbindings("WScreen", {
bdoc("Switch to n:th object (workspace, full screen client window) "..
"within current screen."),
kpress(META.."1", "WScreen.switch_nth(_, 0)"),
kpress(META.."2", "WScreen.switch_nth(_, 1)"),
kpress(META.."3", "WScreen.switch_nth(_, 2)"),
kpress(META.."4", "WScreen.switch_nth(_, 3)"),
kpress(META.."5", "WScreen.switch_nth(_, 4)"),
kpress(META.."6", "WScreen.switch_nth(_, 5)"),
kpress(META.."7", "WScreen.switch_nth(_, 6)"),
kpress(META.."8", "WScreen.switch_nth(_, 7)"),
kpress(META.."9", "WScreen.switch_nth(_, 8)"),
kpress(META.."0", "WScreen.switch_nth(_, 9)"),
bdoc("Switch to next/previous object within current screen."),
kpress(META.."comma", "WScreen.switch_prev(_)"),
kpress(META.."period", "WScreen.switch_next(_)"),
submap(META.."K", {
bdoc("Go to first region demanding attention or previously active one."),
kpress("K", "mod_menu.grabmenu(_, _sub, 'focuslist')"),
-- Alternative without (cyclable) menu
--kpress("K", "ioncore.goto_activity() or ioncore.goto_previous()"),
--bdoc("Go to previous active object."),
--kpress("K", "ioncore.goto_previous()"),
--bdoc("Go to first object on activity/urgency list."),
--kpress("I", "ioncore.goto_activity()"),
bdoc("Clear all tags."),
kpress("T", "ioncore.tagged_clear()"),
}),
bdoc("Go to n:th screen on multihead setup."),
kpress(META.."Shift+1", "ioncore.goto_nth_screen(0)"),
kpress(META.."Q", "ioncore.goto_nth_screen(0)"),
kpress(META.."Shift+2", "ioncore.goto_nth_screen(1)"),
kpress(META.."W", "ioncore.goto_nth_screen(1)"),
kpress(META.."Shift+3", "ioncore.goto_nth_screen(2)"),
kpress(META.."E", "ioncore.goto_nth_screen(2)"),
bdoc("Go to next/previous screen on multihead setup."),
kpress(META.."Shift+comma", "ioncore.goto_prev_screen()"),
kpress(META.."I", "ioncore.goto_prev_screen()"),
kpress(META.."O", "ioncore.goto_next_screen()"),
kpress(META.."grave", "ioncore.goto_next_screen()"),
bdoc("Create a new workspace of chosen default type."),
kpress(META.."F9", "ioncore.create_ws(_)"),
bdoc("Display the main menu."),
kpress(ALTMETA.."F12", "mod_query.query_menu(_, _sub, 'mainmenu', 'Main menu:')"),
--kpress(ALTMETA.."F12", "mod_menu.menu(_, _sub, 'mainmenu', {big=true})"),
mpress("Button3", "mod_menu.pmenu(_, _sub, 'mainmenu')"),
bdoc("Display the window list menu."),
mpress("Button2", "mod_menu.pmenu(_, _sub, 'windowlist')"),
bdoc("Forward-circulate focus."),
-- '_chld' used here stands to for an actual child window that may not
-- be managed by the screen itself, unlike '_sub', that is likely to be
-- the managing group of that window. The right/left directions are
-- used instead of next/prev, because they work better in conjunction
-- with tilings.
kpress(META.."Tab", "ioncore.goto_next(_chld, 'right')",
"_chld:non-nil"),
submap(META.."K", {
bdoc("Backward-circulate focus."),
kpress("AnyModifier+Tab", "ioncore.goto_next(_chld, 'left')",
"_chld:non-nil"),
bdoc("Raise focused object, if possible."),
kpress("AnyModifier+R", "WRegion.rqorder(_chld, 'front')",
"_chld:non-nil"),
}),
})
-- Client window bindings
--
-- These bindings affect client windows directly.
defbindings("WClientWin", {
submap(META.."K", {
bdoc("Nudge the client window. This might help with some "..
"programs' resizing problems."),
kpress_wait(META.."L", "WClientWin.nudge(_)"),
bdoc("Kill client owning the client window."),
kpress("C", "WClientWin.kill(_)"),
bdoc("Send next key press to the client window. "..
"Some programs may not allow this by default."),
kpress("Q", "WClientWin.quote_next(_)"),
}),
})
-- Client window group bindings
defbindings("WGroupCW", {
bdoc("Toggle client window group full-screen mode"),
kpress_wait(META.."Return", "WGroup.set_fullscreen(_, 'toggle')"),
})
-- WMPlex context bindings
--
-- These bindings work in frames and on screens. The innermost of such
-- contexts/objects always gets to handle the key press.
defbindings("WMPlex", {
bdoc("Close current object."),
kpress_wait(META.."C", "WRegion.rqclose_propagate(_, _sub)"),
})
-- Frames for transient windows ignore this bindmap
defbindings("WMPlex.toplevel", {
bdoc("Toggle tag of current object."),
kpress(META.."T", "WRegion.set_tagged(_sub, 'toggle')", "_sub:non-nil"),
bdoc("Lock screen"),
kpress(META.."L", "notioncore.exec_on(_, notioncore.lookup_script('notion-lock'))"),
bdoc("Query for manual page to be displayed."),
kpress(ALTMETA.."F1", "mod_query.query_man(_, ':man')"),
bdoc("Show the Notion manual page."),
kpress(META.."F1", "ioncore.exec_on(_, ':man notion')"),
bdoc("Run a terminal emulator."),
kpress(ALTMETA.."F2", "mod_query.exec_on_merr(_, XTERM or 'xterm')"),
bdoc("Query for command line to execute."),
kpress(ALTMETA.."F3", "mod_query.query_exec(_)"),
bdoc("Query for Lua code to execute."),
kpress(META.."F3", "mod_query.query_lua(_)"),
bdoc("Query for host to connect to with SSH."),
kpress(ALTMETA.."F4", "mod_query.query_ssh(_, ':ssh')"),
bdoc("Query for file to edit."),
kpress(ALTMETA.."F5",
"mod_query.query_editfile(_, 'run-mailcap --action=edit')"),
bdoc("Query for file to view."),
kpress(ALTMETA.."F6",
"mod_query.query_runfile(_, 'run-mailcap --action=view')"),
bdoc("Query for workspace to go to or create a new one."),
kpress(ALTMETA.."F9", "mod_query.query_workspace(_)"),
bdoc("Query for a client window to go to."),
kpress(META.."G", "mod_query.query_gotoclient(_)"),
bdoc("Display context menu."),
--kpress(META.."M", "mod_menu.menu(_, _sub, 'ctxmenu')"),
kpress(META.."M", "mod_query.query_menu(_, _sub, 'ctxmenu', 'Context menu:')"),
submap(META.."K", {
bdoc("Detach (float) or reattach an object to its previous location."),
-- By using _chld instead of _sub, we can detach/reattach queries
-- attached to a group. The detach code checks if the parameter
-- (_chld) is a group 'bottom' and detaches the whole group in that
-- case.
kpress("D", "ioncore.detach(_chld, 'toggle')", "_chld:non-nil"),
}),
})
-- WFrame context bindings
--
-- These bindings are common to all types of frames. Some additional
-- frame bindings are found in some modules' configuration files.
defbindings("WFrame", {
submap(META.."K", {
bdoc("Maximize the frame horizontally/vertically."),
kpress("H", "WFrame.maximize_horiz(_)"),
kpress("V", "WFrame.maximize_vert(_)"),
}),
bdoc("Display context menu."),
mpress("Button3", "mod_menu.pmenu(_, _sub, 'ctxmenu')"),
bdoc("Begin move/resize mode."),
kpress(META.."R", "WFrame.begin_kbresize(_)"),
bdoc("Switch the frame to display the object indicated by the tab."),
mclick("Button1@tab", "WFrame.p_switch_tab(_)"),
mclick("Button2@tab", "WFrame.p_switch_tab(_)"),
bdoc("Resize the frame."),
mdrag("Button1@border", "WFrame.p_resize(_)"),
mdrag(META.."Button3", "WFrame.p_resize(_)"),
bdoc("Move the frame."),
mdrag(META.."Button1", "WFrame.p_move(_)"),
bdoc("Move objects between frames by dragging and dropping the tab."),
mdrag("Button1@tab", "WFrame.p_tabdrag(_)"),
mdrag("Button2@tab", "WFrame.p_tabdrag(_)"),
bdoc("Switch to next/previous object within the frame."),
mclick(META.."Button4", "WFrame.switch_next(_)"),
mclick(META.."Button5", "WFrame.switch_prev(_)"),
})
-- Frames for transient windows ignore this bindmap
defbindings("WFrame.toplevel", {
bdoc("Query for a client window to attach."),
kpress(META.."A", "mod_query.query_attachclient(_)"),
submap(META.."K", {
-- Display tab numbers when modifiers are released
submap_wait("ioncore.tabnum.show(_)"),
bdoc("Switch to n:th object within the frame."),
kpress("1", "WFrame.switch_nth(_, 0)"),
kpress("2", "WFrame.switch_nth(_, 1)"),
kpress("3", "WFrame.switch_nth(_, 2)"),
kpress("4", "WFrame.switch_nth(_, 3)"),
kpress("5", "WFrame.switch_nth(_, 4)"),
kpress("6", "WFrame.switch_nth(_, 5)"),
kpress("7", "WFrame.switch_nth(_, 6)"),
kpress("8", "WFrame.switch_nth(_, 7)"),
kpress("9", "WFrame.switch_nth(_, 8)"),
kpress("0", "WFrame.switch_nth(_, 9)"),
bdoc("Switch to next/previous object within the frame."),
kpress("N", "WFrame.switch_next(_)"),
kpress("P", "WFrame.switch_prev(_)"),
bdoc("Move current object within the frame left/right."),
kpress("comma", "WFrame.dec_index(_, _sub)", "_sub:non-nil"),
kpress("period", "WFrame.inc_index(_, _sub)", "_sub:non-nil"),
bdoc("Maximize the frame horizontally/vertically."),
kpress("H", "WFrame.maximize_horiz(_)"),
kpress("V", "WFrame.maximize_vert(_)"),
bdoc("Attach tagged objects to this frame."),
kpress("A", "ioncore.tagged_attach(_)"),
}),
})
-- Bindings for floating frames.
defbindings("WFrame.floating", {
bdoc("Toggle shade mode"),
mdblclick("Button1@tab", "WFrame.set_shaded(_, 'toggle')"),
bdoc("Raise the frame."),
mpress("Button1@tab", "WRegion.rqorder(_, 'front')"),
mpress("Button1@border", "WRegion.rqorder(_, 'front')"),
mclick(META.."Button1", "WRegion.rqorder(_, 'front')"),
bdoc("Lower the frame."),
mclick(META.."Button3", "WRegion.rqorder(_, 'back')"),
bdoc("Move the frame."),
mdrag("Button1@tab", "WFrame.p_move(_)"),
})
-- WMoveresMode context bindings
--
-- These bindings are available keyboard move/resize mode. The mode
-- is activated on frames with the command begin_kbresize (bound to
-- META.."R" above by default).
defbindings("WMoveresMode", {
bdoc("Cancel the resize mode."),
kpress("AnyModifier+Escape","WMoveresMode.cancel(_)"),
bdoc("End the resize mode."),
kpress("AnyModifier+Return","WMoveresMode.finish(_)"),
bdoc("Grow in specified direction."),
kpress("Left", "WMoveresMode.resize(_, 1, 0, 0, 0)"),
kpress("Right", "WMoveresMode.resize(_, 0, 1, 0, 0)"),
kpress("Up", "WMoveresMode.resize(_, 0, 0, 1, 0)"),
kpress("Down", "WMoveresMode.resize(_, 0, 0, 0, 1)"),
kpress("F", "WMoveresMode.resize(_, 1, 0, 0, 0)"),
kpress("B", "WMoveresMode.resize(_, 0, 1, 0, 0)"),
kpress("P", "WMoveresMode.resize(_, 0, 0, 1, 0)"),
kpress("N", "WMoveresMode.resize(_, 0, 0, 0, 1)"),
bdoc("Shrink in specified direction."),
kpress("Shift+Left", "WMoveresMode.resize(_,-1, 0, 0, 0)"),
kpress("Shift+Right", "WMoveresMode.resize(_, 0,-1, 0, 0)"),
kpress("Shift+Up", "WMoveresMode.resize(_, 0, 0,-1, 0)"),
kpress("Shift+Down", "WMoveresMode.resize(_, 0, 0, 0,-1)"),
kpress("Shift+F", "WMoveresMode.resize(_,-1, 0, 0, 0)"),
kpress("Shift+B", "WMoveresMode.resize(_, 0,-1, 0, 0)"),
kpress("Shift+P", "WMoveresMode.resize(_, 0, 0,-1, 0)"),
kpress("Shift+N", "WMoveresMode.resize(_, 0, 0, 0,-1)"),
bdoc("Move in specified direction."),
kpress(META.."Left", "WMoveresMode.move(_,-1, 0)"),
kpress(META.."Right", "WMoveresMode.move(_, 1, 0)"),
kpress(META.."Up", "WMoveresMode.move(_, 0,-1)"),
kpress(META.."Down", "WMoveresMode.move(_, 0, 1)"),
kpress(META.."F", "WMoveresMode.move(_,-1, 0)"),
kpress(META.."B", "WMoveresMode.move(_, 1, 0)"),
kpress(META.."P", "WMoveresMode.move(_, 0,-1)"),
kpress(META.."N", "WMoveresMode.move(_, 0, 1)"),
})
--
-- Menu definitions
--
-- Main menu
defmenu("mainmenu", {
menuentry("Run...", "mod_query.query_exec(_)"),
menuentry("Terminal", "mod_query.exec_on_merr(_, XTERM or 'xterm')"),
menuentry("Lock screen",
"notioncore.exec_on(_, notioncore.lookup_script('notion-lock'))"),
menuentry("Help", "mod_query.query_man(_)"),
menuentry("About Notion", "mod_query.show_about_ion(_)"),
submenu("Styles", "stylemenu"),
submenu("Session", "sessionmenu"),
})
-- Session control menu
defmenu("sessionmenu", {
menuentry("Save", "ioncore.snapshot()"),
menuentry("Restart", "ioncore.restart()"),
menuentry("Restart TWM", "ioncore.restart_other('twm')"),
menuentry("Exit", "ioncore.shutdown()"),
})
-- Context menu (frame actions etc.)
defctxmenu("WFrame", "Frame", {
-- Note: this propagates the close to any subwindows; it does not
-- destroy the frame itself, unless empty. An entry to destroy tiled
-- frames is configured in cfg_tiling.lua.
menuentry("Close", "WRegion.rqclose_propagate(_, _sub)"),
-- Low-priority entries
menuentry("Attach tagged", "ioncore.tagged_attach(_)", { priority = 0 }),
menuentry("Clear tags", "ioncore.tagged_clear()", { priority = 0 }),
menuentry("Window info", "mod_query.show_tree(_, _sub)", { priority = 0 }),
})
-- Context menu for groups (workspaces, client windows)
defctxmenu("WGroup", "Group", {
menuentry("Toggle tag", "WRegion.set_tagged(_, 'toggle')"),
menuentry("De/reattach", "ioncore.detach(_, 'toggle')"),
})
-- Context menu for workspaces
defctxmenu("WGroupWS", "Workspace", {
menuentry("Close", "WRegion.rqclose(_)"),
menuentry("Rename", "mod_query.query_renameworkspace(nil, _)"),
menuentry("Attach tagged", "ioncore.tagged_attach(_)"),
})
-- Context menu for client windows
defctxmenu("WClientWin", "Client window", {
menuentry("Kill", "WClientWin.kill(_)"),
})
| lgpl-2.1 |
birdbrainswagtrain/grid-sdk | src/shaders/gaussianblur.lua | 1 | 3228 | --========= Copyright © 2013-2015, Planimeter, All rights reserved. ==========--
--
-- Purpose: Gaussian Blur pixel shader
--
--============================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2015 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
]]--
require( "shaders.shader" )
class "gaussianblur" ( "shader" )
-- unroll convolution loop
local function build_shader(sigma)
local support = math.max(1, math.floor(3*sigma + .5))
local one_by_sigma_sq = sigma > 0 and 1 / (sigma * sigma) or 1
local norm = 0
local code = {[[
extern vec2 direction;
vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _)
{ vec4 c = vec4(0.0f);
]]}
local blur_line = "c += vec4(%f) * Texel(texture, tc + vec2(%f) * direction);"
for i = -support,support do
local coeff = math.exp(-.5 * i*i * one_by_sigma_sq)
norm = norm + coeff
code[#code+1] = blur_line:format(coeff, i)
end
code[#code+1] = ("return c * vec4(%f) * color;}"):format(norm > 0 and 1/norm or 1)
return graphics.newShader(table.concat(code))
end
function gaussianblur:gaussianblur()
self.canvas_h = graphics.newFullscreenFramebuffer()
self.canvas_v = graphics.newFullscreenFramebuffer()
self.shader = build_shader(1)
self.shader:send("direction",{1.0,0.0})
end
function gaussianblur:draw(func)
local s = graphics.getShader()
-- draw scene
self.canvas_h:clear()
self.canvas_h:renderTo(func)
graphics.setShader(self.shader)
local b = graphics.getBlendMode()
graphics.setBlendMode('premultiplied')
-- first pass (horizontal blur)
self.shader:send('direction', {1 / graphics.getViewportWidth(), 0})
self.canvas_v:clear()
self.canvas_v:renderTo(function() graphics.draw(self.canvas_h:getDrawable(), 0,0) end)
-- second pass (vertical blur)
self.shader:send('direction', {0, 1 / graphics.getViewportHeight()})
graphics.draw(self.canvas_v:getDrawable(), 0,0)
-- restore blendmode, shader and canvas
graphics.setBlendMode(b)
graphics.setShader(s)
end
function gaussianblur:set(key, value)
if key == "sigma" then
self.shader = build_shader(tonumber(value))
else
error("Unknown property: " .. tostring(key))
end
return self
end
shader.register( gaussianblur, "gaussianblur" )
| mit |
fgielow/devenserver | data/npc/scripts/tapete mark.lua | 2 | 2383 | local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local travelNode = keywordHandler:addKeyword({'infernium'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'You want fly to Infernium for 130 gold coins?'})
travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = false, level = 2, cost = 130, destination = {x=237, y=259, z=8} })
travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'I wouldn\'t go there either.'})
local travelNode = keywordHandler:addKeyword({'dorion'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'You want fly to Dorion for 115 gold coins?'})
travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = false, level = 2, cost = 115, destination = {x=39, y=86, z=6} })
travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'I wouldn\'t go there either.'})
local travelNode = keywordHandler:addKeyword({'saari'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'You want fly to saari for 100 gold coins?'})
travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = false, level = 2, cost = 100, destination = {x=259, y=112, z=5} })
travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'I wouldn\'t go there either.'})
local travelNode = keywordHandler:addKeyword({'mirand theraan'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'You want fly to mirand theraan for 90 gold coins?'})
travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = false, level = 2, cost = 90, destination = {x=297, y=177, z=6} })
travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'I wouldn\'t go there either.'})
npcHandler:addModule(FocusModule:new()) | gpl-2.0 |
dacrybabysuck/darkstar | scripts/globals/items/plate_of_ic_pilav_+1.lua | 11 | 1691 | -----------------------------------------
-- ID: 5585
-- Item: plate_of_ic_pilav_+1
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Health % 14
-- Health Cap 70
-- Strength 5
-- Vitality -2
-- Intelligence -2
-- Health Regen While Healing 1
-- Attack % 22
-- Attack Cap 70
-- Ranged ATT % 22
-- Ranged ATT Cap 70
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,14400,5585)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.FOOD_HPP, 14)
target:addMod(dsp.mod.FOOD_HP_CAP, 70)
target:addMod(dsp.mod.STR, 5)
target:addMod(dsp.mod.VIT, -2)
target:addMod(dsp.mod.INT, -2)
target:addMod(dsp.mod.HPHEAL, 1)
target:addMod(dsp.mod.FOOD_ATTP, 22)
target:addMod(dsp.mod.FOOD_ATT_CAP, 70)
target:addMod(dsp.mod.FOOD_RATTP, 22)
target:addMod(dsp.mod.FOOD_RATT_CAP, 70)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_HPP, 14)
target:delMod(dsp.mod.FOOD_HP_CAP, 70)
target:delMod(dsp.mod.STR, 5)
target:delMod(dsp.mod.VIT, -2)
target:delMod(dsp.mod.INT, -2)
target:delMod(dsp.mod.HPHEAL, 1)
target:delMod(dsp.mod.FOOD_ATTP, 22)
target:delMod(dsp.mod.FOOD_ATT_CAP, 70)
target:delMod(dsp.mod.FOOD_RATTP, 22)
target:delMod(dsp.mod.FOOD_RATT_CAP, 70)
end
| gpl-3.0 |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/skia/resources/slides_content2.lua | 73 | 3377 | Skia Update
Skia : Access
- https://skia.org
- https://skia.googlesource.com/skia
Skia : Overview
- portable graphics engine
- 2D transformations + perspective
- primitives: text, geometry, images
- effects: shaders, filters, antialiasing, blending
Skia : Porting
- C++ and some SIMD assembly
- Fonts : CoreText, FreeType, GDI, DirectWrite
- Threads : wrappers for native apis
- Memory : wrappers for [new, malloc, discardable]
Skia : Backends
- Surface
-- raster : ARGB, RGB16, A8 in software
-- gpu : transcribe to OpenGL
- Document
-- transcribe to PDF or XPS
- Record and Playback
-- Picture
-- Pipe
Skia : Clients
- Blink : under the GraphicsContext hood
- Chrome : ui/gfx and compositor
- Android : framework
- third parties : e.g. Mozilla
Skia In Blink
Skia In Blink : Fonts
- SkTypeface and SkFontMgr : platform agnostic
- Runtime switch between GDI and DirectWrite
- SkTextBlob to encapsulate runs of text
- Push LCD decision-making out of Blink
Skia In Blink : Record-Time-Rasterization
- What? : direct rendering during “Paint” pass
-- Image scaling, filters
-- SVG patterns, masks
- Problematic in modern Blink
-- CTM not always known/knowable
-- Rendering backend not always known (gpu or cpu)
-- Rasterization takes (too much) time
Skia In Blink : RTR response
- SkImageFilter w/ CPU and GPU implementations
- Bitmap scaling : bilerp, mipmaps, fancy
- SkPicture for caching SVG
- SkPicture + saveLayer() for masks
-- PathOps for resolving complex paths
- SkPictureShader for device-independent patterns
Skia In Blink : Recording
- GraphicsContext (now) backed by SkPicture
-- draw commands are recorded for later playback
-- all parameters must be copied or (safely) ref'd
-- may record more than is currently visible
- Resulting picture may be replayed multiple times
-- from different thread(s)
Skia In Blink : Recording response
- New implementation
- Optimized for recording speed
-- shallow copies whenever possible
-- rearchitect all Skia effects to be immutable
- Reentrant-safe for playback in multiple threads
-- also affected effect subclasses
Skia In Blink : Playback
- Separate pass for optimizations (optional)
-- peep-holes rewrites
-- compute bounding-box hierarchy for faster tiling
-- can be done outside of Blink thread
- GPU optimizations
-- layer "hoisting"
-- distance fields : fonts and concave paths
Skia In Blink : multi-picture-draw
- mpd(canvas[], picture[], matrix[], paint[])
- Requires independent canvas objects
-- all other parameters can be shared
-- draw order is unspecified
- Examples
-- 1 picture drawing to multiple tiles (canvases)
-- multiple pictures each drawing to its own layer
Skia In Blink : MPD optimizations*
- GPU
-- "layer hoisting" to reduce rendertarget switching
-- layer atlasing (also applies to imagefilters)
-- pre-uploading of textures
-- atlas yuv (from jpeg) to convert on gpu
- CPU
-- parallel execution using thread pool
-- pre-decoding of images based on visibility
Skia : Roadmap
Skia : Roadmap - performance
- GPU
-- extended OpenGL features (e.g. geometry shaders)
-- reordering for increased batching
-- support for new low-level OpenGL APIs
- CPU
-- SIMD applied to floats
-- smarter culling in pictures
Skia : Roadmap - API
- Cross process support
- Direct support for sRGB
- Robust file format
- Support PDF viewing
- Stable C ABI
-- bindings for JS, Go, Python, Lua
Demo
| gpl-3.0 |
dacrybabysuck/darkstar | scripts/zones/Southern_San_dOria/npcs/Femitte.lua | 9 | 2758 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Femitte
-- Involved in Quest: Lure of the Wildcat (San d'Oria), Distant Loyalties
-- !pos -17 2 10 230
-------------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
local ID = require("scripts/zones/Southern_San_dOria/IDs");
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer
player:messageSpecial(ID.text.FLYER_REFUSED);
end
end
end;
function onTrigger(player,npc)
local DistantLoyaltiesProgress = player:getCharVar("DistantLoyaltiesProgress");
local DistantLoyalties = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.DISTANT_LOYALTIES);
local WildcatSandy = player:getCharVar("WildcatSandy");
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.LURE_OF_THE_WILDCAT) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,3) == false) then
player:startEvent(807);
elseif (player:getFameLevel(SANDORIA) >= 4 and DistantLoyalties == 0) then
player:startEvent(663);
elseif (DistantLoyalties == 1 and DistantLoyaltiesProgress == 1) then
player:startEvent(664);
elseif (DistantLoyalties == 1 and DistantLoyaltiesProgress == 4 and player:hasKeyItem(dsp.ki.MYTHRIL_HEARTS)) then
player:startEvent(665);
else
player:startEvent(661);
end;
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 807) then
player:setMaskBit(player:getCharVar("WildcatSandy"),"WildcatSandy",3,true);
elseif (csid == 663 and option == 0) then
player:addKeyItem(dsp.ki.GOLDSMITHING_ORDER);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.GOLDSMITHING_ORDER);
player:addQuest(SANDORIA,dsp.quest.id.sandoria.DISTANT_LOYALTIES);
player:setCharVar("DistantLoyaltiesProgress",1);
elseif (csid == 665) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,13585);
else
player:delKeyItem(dsp.ki.MYTHRIL_HEARTS);
player:addItem(13585,1);
player:messageSpecial(ID.text.ITEM_OBTAINED,13585);
player:setCharVar("DistantLoyaltiesProgress",0);
player:completeQuest(SANDORIA,dsp.quest.id.sandoria.DISTANT_LOYALTIES);
end;
end;
end;
--------Other CS
--32692
--0
--661 Standard dialog
--663
--664
--665
--725
--747
--748
--807 Lure of the Wildcat
--945 CS with small mythra dancer | gpl-3.0 |
dacrybabysuck/darkstar | scripts/zones/Northern_San_dOria/npcs/Abioleget.lua | 9 | 2118 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Abioleget
-- Type: Quest Giver (Her Memories: The Faux Pas and The Vicasque's Sermon) / Merchant
-- !pos 128.771 0.000 118.538 231
--
-----------------------------------
local ID = require("scripts/zones/Northern_San_dOria/IDs");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
if (sermonQuest == QUEST_ACCEPTED) then
gil = trade:getGil();
count = trade:getItemCount();
if (gil == 70 and count == 1) then
player:tradeComplete();
player:startEvent(591);
end
end
end;
function onTrigger(player,npc)
sermonQuest = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THE_VICASQUE_S_SERMON);
if (sermonQuest == QUEST_AVAILABLE) then
player:startEvent(589);
elseif (sermonQuest == QUEST_ACCEPTED) then
if (player:getCharVar("sermonQuestVar") == 1) then
player:tradeComplete();
player:startEvent(600);
else
player:showText(npc,11103,618,70);
end
else
player:showText(npc,ID.text.ABIOLEGET_DIALOG);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 600) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,13465);
else
player:addItem(13465);
player:messageSpecial(ID.text.ITEM_OBTAINED, 13465);
player:addFame(SANDORIA,30);
player:addTitle(dsp.title.THE_BENEVOLENT_ONE);
player:setCharVar("sermonQuestVar",0);
player:completeQuest(SANDORIA,dsp.quest.id.sandoria.THE_VICASQUE_S_SERMON );
end
elseif (csid == 589) then
player:addQuest(SANDORIA,dsp.quest.id.sandoria.THE_VICASQUE_S_SERMON );
elseif (csid == 591) then
player:addItem(618);
player:messageSpecial(ID.text.ITEM_OBTAINED, 618);
end
end;
| gpl-3.0 |
pSyChOoOo/TeleSeed | .luarocks/share/lua/5.2/feedparser/XMLElement.lua | 569 | 4025 | -- Copyright 2009 Leo Ponomarev. Distributed under the BSD Licence.
-- updated for module-free world of lua 5.3 on April 2 2015
-- Not documented at all, but not interesting enough to warrant documentation anyway.
local setmetatable, pairs, ipairs, type, getmetatable, tostring, error = setmetatable, pairs, ipairs, type, getmetatable, tostring, error
local table, string = table, string
local XMLElement={}
local mt
XMLElement.new = function(lom)
return setmetatable({lom=lom or {}}, mt)
end
local function filter(filtery_thing, lom)
filtery_thing=filtery_thing or '*'
for i, thing in ipairs(type(filtery_thing)=='table' and filtery_thing or {filtery_thing}) do
if thing == "text()" then
if type(lom)=='string' then return true end
elseif thing == '*' then
if type(lom)=='table' then return true end
else
if type(lom)=='table' and string.lower(lom.tag)==string.lower(thing) then return true end
end
end
return nil
end
mt ={ __index = {
getAttr = function(self, attribute)
if type(attribute) ~= "string" then return nil, "attribute name must be a string." end
return self.lom.attr[attribute]
end,
setAttr = function(self, attribute, value)
if type(attribute) ~= "string" then return nil, "attribute name must be a string." end
if value == nil then return self:removeAttr(attribute) end
self.lom.attr[attribute]=tostring(value)
return self
end,
removeAttr = function(self, attribute)
local lom = self.lom
if type(attribute) ~= "string" then return nil, "attribute name must be a string." end
if not lom.attr[attribute] then return self end
for i,v in ipairs(lom.attr) do
if v == attribute then
table.remove(lom.attr, i)
break
end
end
lom.attr[attribute]=nil
end,
removeAllAttributes = function(self)
local attr = self.lom.attr
for i, v in pairs(self.lom.attr) do
attr[i]=nil
end
return self
end,
getAttributes = function(self)
local attr = {}
for i, v in ipairs(self.lom.attr) do
table.insert(attr,v)
end
return attr
end,
getXML = function(self)
local function getXML(lom)
local attr, inner = {}, {}
for i, attribute in ipairs(lom.attr) do
table.insert(attr, string.format('%s=%q', attribute, lom.attr[attribute]))
end
for i, v in ipairs(lom) do
local t = type(v)
if t == "string" then table.insert(inner, v)
elseif t == "table" then
table.insert(inner, getXML(v))
else
error("oh shit")
end
end
local tagcontents = table.concat(inner)
local attrstring = #attr>0 and (" " .. table.concat(attr, " ")) or ""
if #tagcontents>0 then
return string.format("<%s%s>%s</%s>", lom.tag, attrstring, tagcontents, lom.tag)
else
return string.format("<%s%s />", lom.tag, attrstring)
end
end
return getXML(self.lom)
end,
getText = function(self)
local function getText(lom)
local inner = {}
for i, v in ipairs(lom) do
local t = type(v)
if t == "string" then table.insert(inner, v)
elseif t == "table" then
table.insert(inner, getText(v))
end
end
return table.concat(inner)
end
return getText(self.lom)
end,
getChildren = function(self, filter_thing)
local res = {}
for i, node in ipairs(self.lom) do
if filter(filter_thing, node) then
table.insert(res, type(node)=='table' and XMLElement.new(node) or node)
end
end
return res
end,
getDescendants = function(self, filter_thing)
local res = {}
local function descendants(lom)
for i, child in ipairs(lom) do
if filter(filter_thing, child) then
table.insert(res, type(child)=='table' and XMLElement.new(child) or child)
if type(child)=='table' then descendants(child) end
end
end
end
descendants(self.lom)
return res
end,
getChild = function(self, filter_thing)
for i, node in ipairs(self.lom) do
if filter(filter_thing, node) then
return type(node)=='table' and XMLElement.new(node) or node
end
end
end,
getTag = function(self)
return self.lom.tag
end
}}
return XMLElement | gpl-2.0 |
dacrybabysuck/darkstar | scripts/commands/adddynatime.lua | 9 | 1519 | ---------------------------------------------------------------------------------------------------
-- func: adddynatime
-- desc: Adds an amount of time to the given target. If no target then to the current player.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "is"
}
function error(player, msg)
player:PrintToPlayer(msg)
player:PrintToPlayer("!adddynatime <minutes> {player}")
end
function onTrigger(player, minutes, target)
-- validate target
local targ
if target == nil then
targ = player
else
targ = GetPlayerByName(target)
if targ == nil then
error(player, string.format("Player named '%s' not found!", target))
return
end
end
-- target must be in dynamis
local effect = targ:getStatusEffect(dsp.effect.DYNAMIS)
if not effect then
error(player, string.format("%s is not in Dynamis.", targ:getName()))
return
end
-- validate amount
if minutes == nil or minutes < 1 then
error(player, "Invalid number of minutes.")
return
end
-- add time
local zoneId = targ:getZoneID()
local ID = zones[zoneId]
local old_duration = effect:getDuration()
effect:setDuration((old_duration + (minutes * 60)) * 1000)
targ:setLocalVar("dynamis_lasttimeupdate", effect:getTimeRemaining() / 1000)
targ:messageSpecial(ID.text.DYNAMIS_TIME_EXTEND, minutes)
end | gpl-3.0 |
dacrybabysuck/darkstar | scripts/zones/King_Ranperres_Tomb/npcs/_5a0.lua | 9 | 2089 | -----------------------------------
-- Area: King Ranperre's Tomb
-- DOOR: _5a0 (Heavy Stone Door)
-- !pos -39.000 4.823 20.000 190
-----------------------------------
local ID = require("scripts/zones/King_Ranperres_Tomb/IDs")
require("scripts/globals/missions")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local currentMission = player:getCurrentMission(SANDORIA)
local MissionStatus = player:getCharVar("MissionStatus")
if
currentMission == dsp.mission.id.sandoria.RANPERRE_S_FINAL_REST and
MissionStatus == 1 and
not GetMobByID(ID.mob.CORRUPTED_YORGOS):isSpawned() and
not GetMobByID(ID.mob.CORRUPTED_SOFFEIL):isSpawned() and
not GetMobByID(ID.mob.CORRUPTED_ULBRIG):isSpawned()
then
if player:getCharVar("Mission6-2MobKilled") == 1 then
player:setCharVar("Mission6-2MobKilled", 0)
player:setCharVar("MissionStatus", 2)
else
SpawnMob(ID.mob.CORRUPTED_YORGOS)
SpawnMob(ID.mob.CORRUPTED_SOFFEIL)
SpawnMob(ID.mob.CORRUPTED_ULBRIG)
end
elseif currentMission == dsp.mission.id.sandoria.RANPERRE_S_FINAL_REST and MissionStatus == 2 then
player:startEvent(6)
elseif currentMission == dsp.mission.id.sandoria.RANPERRE_S_FINAL_REST and MissionStatus == 3 then
player:startEvent(7)
elseif currentMission == dsp.mission.id.sandoria.RANPERRE_S_FINAL_REST and MissionStatus == 8 then
player:startEvent(5)
elseif currentMission == dsp.mission.id.sandoria.THE_HEIR_TO_THE_LIGHT and MissionStatus == 6 then
player:startEvent(14)
else
player:messageSpecial(ID.text.HEAVY_DOOR)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 5 then
player:setCharVar("MissionStatus", 9)
elseif csid == 14 then
player:setCharVar("MissionStatus", 7)
-- at this point 3 optional cs are available and open until watched (add 3 var to char?)
end
end
| gpl-3.0 |
baishancloud/lua-acid | lib/acid/redis_proxy_cli.lua | 1 | 8036 | --example, how to use
-- local opts = {
-- nwr = {3, 2, 2},
-- ak_sk = {'accesskey', 'secret_key'},
-- timeouts = {1, 1, 1},
-- }
-- local cli = redis_proxy_cli:new({{ip, port}}, opts)
--
-- "retry(another N times) is optional"
-- cli:get(key, retry)
-- E.g. cli:get('key1')
-- E.g. cli:get('key1', 1)
--
-- "expire(msec) and retry(another N times) are optional"
-- cli:set(key, val, expire, retry)
-- E.g. cli:set('key1', 'val1')
-- E.g. cli:set('key1', 'val1', 1000)
-- E.g. cli:set('key1', 'val1', nil, 2)
-- E.g. cli:set('key1', 'val1', 1000, 2)
--
-- "retry(another N times) is optional"
-- cli:hget(hashname, hashkey, retry)
-- E.g. cli:hget('hashname1', 'hashkey1')
-- E.g. cli:hget('hashname1', 'hashkey1', 2)
--
-- "expire(msec) and retry(another N times) are optional"
-- cli:hset(hashname, hashkey, val, expire, retry)
-- E.g. cli:hset('hashname1', 'hashkey1', 'val')
-- E.g. cli:hset('hashname1', 'hashkey1', 'val', 1000)
-- E.g. cli:hset('hashname1', 'hashkey1', 'val', nil, 2)
-- E.g. cli:hset('hashname1', 'hashkey1', 'val', 1000, 2)
local http_cli = require("acid.httpclient")
local aws_signer = require('resty.awsauth.aws_signer')
local tableutil = require('acid.tableutil')
local strutil = require('acid.strutil')
local json = require('acid.json')
local _M = { _VERSION = '1.0' }
local mt = { __index = _M }
local to_str = strutil.to_str
-- cmd: {"redis operation", "http method", "args count", "optional args names"}
local cmds = {
get = {"get", "GET", 2, {}},
set = {"set", "PUT", 4, {"expire"}},
hget = {"hget", "GET", 3, {}},
hset = {"hset", "PUT", 5, {"expire"}},
hkeys = {"keys", "GET", 2, {}},
hvals = {"hvals", "GET", 2, {}},
hgetall = {"hgetall", "GET", 2, {}},
delete = {"del", "DELETE", 2, {}},
hdel = {"hdel", "DELETE", 3, {}},
}
local function _sign_req(rp_cli, req)
if rp_cli.access_key == nil or rp_cli.secret_key == nil then
return nil, nil, nil
end
local signer, err, errmsg = aws_signer.new(rp_cli.access_key,
rp_cli.secret_key,
{default_expires = 600})
if err ~= nil then
return nil, err, errmsg
end
local opts = {
query_auth = true,
sign_payload = (req['body'] ~= nil),
}
return signer:add_auth_v4(req, opts)
end
local function _make_req_uri(rp_cli, params, opts, qs_values)
local path = tableutil.extends({rp_cli.ver}, params)
local qs_list = {
string.format('n=%s', rp_cli.n),
string.format('w=%s', rp_cli.w),
string.format('r=%s', rp_cli.r),
}
for i = 1, #opts do
if opts[i] ~= nil and qs_values[i] ~= nil then
table.insert(qs_list, string.format('%s=%s', opts[i], qs_values[i]))
end
end
return string.format(
'%s?%s',
table.concat(path, '/'),
table.concat(qs_list, '&')
)
end
local function _req(rp_cli, ip, port, request)
local req = tableutil.dup(request, true)
req['headers'] = req['headers'] or {}
if req['headers']['Host'] == nil then
req['headers']['Host'] = string.format('%s:%s', ip, port)
end
if req['body'] ~= nil then
req['headers']['Content-Length'] = #req['body']
end
local _, err, errmsg = _sign_req(rp_cli, req)
if err ~= nil then
return nil, err, errmsg
end
local cli = http_cli:new(ip, port, rp_cli.timeouts)
local req_opts = {
method = req['verb'],
headers = req['headers'],
body = req['body'],
}
local _, err, errmsg = cli:request(req['uri'], req_opts)
if err ~= nil then
return nil, err, errmsg
end
local res, err, errmsg = cli:read_body(100*1024*1024)
if err ~= nil then
return nil, err, errmsg
end
if cli.status == 404 then
return nil, 'KeyNotFoundError', to_str('Uri:', req['uri'])
elseif cli.status ~= 200 then
return nil, 'ServerResponseError', to_str('Res:', res, ' Uri:', req['uri'])
end
return res, nil, nil
end
local function can_proxy(proxy_hosts, verb, err)
if #proxy_hosts == 0 then
return false
end
if verb == 'PUT' and err == nil then
return true
end
if verb == 'GET' and err ~= nil then
return true
end
return false
end
local function _send_req(rp_cli, request)
local rst, err, errmsg
for _, h in ipairs(rp_cli.hosts) do
local ip, port = h[1], h[2]
rst, err, errmsg = _req(rp_cli, ip, port, request)
if err == nil then
break
end
end
if not can_proxy(rp_cli.proxy_hosts, request.verb, err) then
return rst, err, errmsg
end
for _, hosts in ipairs(rp_cli.proxy_hosts) do
ngx.log(ngx.INFO, to_str("send req to proxy hosts:", hosts))
for _, h in ipairs(hosts) do
local ip, port = h[1], h[2]
rst, err, errmsg = _req(rp_cli, ip, port, request)
if err == nil then
break
end
end
if not can_proxy(rp_cli.proxy_hosts, request.verb, err) then
break
end
end
ngx.log(ngx.INFO, to_str("finish send req to proxy hosts error:", err, ",", errmsg))
return rst, err, errmsg
end
local function _parse_args(cmd, args, args_cnt, http_mtd, opts)
local path = {string.upper(cmd)}
-- (args count) - (#opts) - "retry"
local path_args_cnt = args_cnt - #opts - 1
if http_mtd == "PUT" then
-- remove body
path_args_cnt = path_args_cnt - 1
end
for _ = 1, path_args_cnt do
table.insert(path, args[1])
table.remove(args, 1)
end
local body
if http_mtd == "PUT" then
body = args[1]
table.remove(args, 1)
end
local retry
if #args > #opts then
retry = args[#args]
table.remove(args, #args)
end
return path, args, body, retry
end
local function _do_cmd(rp_cli, cmd, ...)
ngx.log(ngx.INFO, to_str("start do cmd:", cmd))
local cmd_info = cmds[cmd]
if cmd_info == nil then
local support_keys = tableutil.keys(cmds)
return nil, 'NotSupportCmd', to_str(cmd, ' not in ', support_keys)
end
local args = {...}
local http_mtd, args_cnt, opts = cmd_info[2], cmd_info[3], cmd_info[4]
local path, qs_values, body, retry = _parse_args(cmd_info[1], args, args_cnt, http_mtd, opts)
local req = {
verb = http_mtd,
uri = _make_req_uri(rp_cli, path, opts, qs_values),
}
local res, err, errmsg
if body ~= nil then
req['body'], err = json.enc(body)
if err ~= nil then
return nil, err, to_str("json encode error:", body)
end
end
retry = retry or 0
for _ = 1, retry + 1 do
res, err, errmsg = _send_req(rp_cli, req)
if err == nil then
break
end
end
if err ~= nil then
return nil, err, errmsg
end
if http_mtd == 'GET' then
res, err = json.dec(res)
if err ~= nil then
return nil, err, to_str("json decode error:", res)
end
return res, nil, nil
end
return nil, nil, nil
end
function _M.new(_, hosts, opts)
opts = opts or {}
local nwr = opts.nwr or {3, 2, 2}
local ak_sk = opts.ak_sk or {}
local n, w, r = nwr[1], nwr[2], nwr[3]
local access_key, secret_key = ak_sk[1], ak_sk[2]
return setmetatable({
ver = '/redisproxy/v1',
hosts = hosts,
proxy_hosts = opts.proxy_hosts or {},
n = n,
w = w,
r = r,
access_key = access_key,
secret_key = secret_key,
timeouts = opts.timeouts,
}, mt)
end
for cmd, _ in pairs(cmds) do
_M[cmd] = function (self, ...)
return _do_cmd(self, cmd, ...)
end
end
return _M
| mit |
dacrybabysuck/darkstar | scripts/zones/Riverne-Site_B01/IDs.lua | 8 | 2071 | -----------------------------------
-- Area: Riverne-Site_B01
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.RIVERNE_SITE_B01] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here.
CONQUEST_BASE = 7049, -- Tallying conquest results...
SD_VERY_SMALL = 7585, -- The spatial displacement is very small. If you only had some item that could make it bigger...
SD_HAS_GROWN = 7586, -- The spatial displacement has grown.
SPACE_SEEMS_DISTORTED = 7587, -- The space around you seems oddly distorted and disrupted.
MONUMENT = 7593, -- Something has been engraved on this stone, but the message is too difficult to make out.
GROUND_GIVING_HEAT = 7595, -- The ground here is giving off heat.
BAHAMUT_TAUNT = 7663, -- Children of Vana'diel, what do you think to accomplish by fighting for your lives? You know your efforts are futile, yet still you resist...
HOMEPOINT_SET = 7699, -- Home point set!
},
mob =
{
IMDUGUD_PH =
{
[16896101] = 16896107, -- 650.770 20.052 676.513
[16896102] = 16896107, -- 643.308 20.049 652.354
[16896103] = 16896107, -- 669.574 19.215 623.129
[16896104] = 16896107, -- 691.504 21.296 583.884
[16896105] = 16896107, -- 687.199 21.161 582.560
[16896106] = 16896107, -- 666.737 20.012 652.352
},
UNSTABLE_CLUSTER = 16896155,
},
npc =
{
DISPLACEMENT_OFFSET = 16896183,
},
}
return zones[dsp.zone.RIVERNE_SITE_B01] | gpl-3.0 |
25A0/Quadtastic | Quadtastic/Keybindings.lua | 1 | 2314 | -- Each entry is a table with the trigger key in the first element, and a
-- list of modifiers in the second element.
-- Modifiers that have a left and right equivalent can be specified as
-- e.g. "*shift" when it doesn't matter which of the two modifiers was pressed
-- Quick reference for modifiers: (from https://love2d.org/wiki/KeyConstant)
-- numlock Num-lock key Clear on Mac leopards.
-- capslock Caps-lock key Caps-on is a key press. Caps-off is a key release.
-- scrolllock Scroll-lock key
-- rshift Right shift key
-- lshift Left shift key
-- rctrl Right control key
-- lctrl Left control key
-- ralt Right alt key
-- lalt Left alt key
-- rgui Right gui key Command key in OS X, Windows key in Windows.
-- lgui Left gui key Command key in OS X, Windows key in Windows.
-- mode Mode key
-- expected values: "OS X", "Windows", "Linux", "Android", or "iOS"
local os = love.system.getOS()
local mac = os == "OS X"
local win = os == "Windows"
local linux = os == "Linux"
local keybindings = {
-- selection
select_all = {"a", {mac and "*gui" or "*ctrl"}},
delete = {"backspace"},
rename = {mac and "return" or "f2"},
group = {"g", {mac and "*gui" or "*ctrl"}},
ungroup = {"g", {mac and "*gui" or "*ctrl", "*shift"}},
-- undo, redo
undo = {"z", {mac and "*gui" or "*ctrl"}},
redo = {"z", {mac and "*gui" or "*ctrl", "*shift"}},
-- open, save, quit, etc
open = {"o", {mac and "*gui" or "*ctrl"}},
save = {"s", {mac and "*gui" or "*ctrl"}},
save_as = {"s", {mac and "*gui" or "*ctrl", "*shift"}},
export = {"e", {mac and "*gui" or "*ctrl"}},
quit = mac and {"q", {"*gui"}} or
linux and {"q", {"*ctrl"}} or
win and {"f4", {"*alt"}} or nil,
new = {"n", {mac and "*gui" or "*ctrl"}},
}
local subs = {
["*ctrl"] = "ctrl",
["*gui"] = "cmd",
["*shift"] = "shift",
["*alt"] = "alt",
["return"] = "enter",
}
function keybindings.to_string(keybinding)
-- This lets us do keybindings.to_string("undo")
if type(keybinding) == "string" then
keybinding = keybindings[keybinding]
end
local s = {}
-- Iterate through modifiers
if keybinding[2] then
for _,v in ipairs(keybinding[2]) do
table.insert(s, subs[v] or v)
end
end
table.insert(s, subs[keybinding[1]] or keybinding[1])
return table.concat(s, "+")
end
return keybindings
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.