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
wingo/snabb
lib/ljsyscall/include/luaunit/luaunit.lua
24
19044
--[[ luaunit.lua Description: A unit testing framework Homepage: http://phil.freehackers.org/luaunit/ Initial author: Ryu, Gwang (http://www.gpgstudy.com/gpgiki/LuaUnit) Lot of improvements by Philippe Fremy <phil@freehackers.org> More improvements by Ryan P. <rjpcomputing@gmail.com> Version: 2.0 License: X11 License, see LICENSE.txt - Justin Cormack added slightly hacky method for marking tests as skipped, not really suitable for upstream yet. Changes between 2.0 and 1.3: - This is a major update that has some breaking changes to make it much more easy to use and code in many different styles - Made the module only touch the global table for the asserts. You now use the module much more like Lua 5.2 when you require it. You need to store the LuaUnit table after you require it to allow you access to the LuaUnit methods and variables. (ex. local LuaUnit = require( "luaunit" )) - Made changes to the style of which LuaUnit forced users to code there test classes. It now is more layed back and give the ability to code in a few styles. - Made "testable" classes able to start with 'test' or 'Test' for their name. - Made "testable" methods able to start with 'test' or 'Test' for their name. - Made testClass:setUp() methods able to be named with 'setUp' or 'Setup' or 'setup'. - Made testClass:tearDown() methods able to be named with 'tearDown' or 'TearDown' or 'teardown'. - Made LuaUnit.wrapFunctions() function able to be called with 'wrapFunctions' or 'WrapFunctions' or 'wrap_functions'. - Made LuaUnit:run() method able to be called with 'run' or 'Run'. - Added the ability to tell if tables are equal using assertEquals. This uses a deep compare, not just the equality that they are the same memory address. - Added LuaUnit.is<Type> and LuaUnit.is_<type> helper functions. (e.g. assert( LuaUnit.isString( getString() ) ) - Added assert<Type> and assert_<type> - Added assertNot<Type> and assert_not_<type> - Added _VERSION variable to hold the LuaUnit version - Added LuaUnit:setVerbosity(lvl) method to the LuaUnit table to allow you to control the verbosity now. If lvl is greater than 1 it will give verbose output. This can be called from alias of LuaUnit.SetVerbosity() and LuaUnit:set_verbosity(). - Moved wrapFunctions to the LuaUnit module table (e.g. local LuaUnit = require( "luaunit" ); LuaUnit.wrapFunctions( ... ) ) - Fixed the verbosity to actually format in a way that is closer to other unit testing frameworks I have used. NOTE: This is not the only way, I just thought the old output was way to verbose and duplicated the errors. - Made the errors only show in the "test report" section (at the end of the run) Changes between 1.3 and 1.2a: - port to lua 5.1 - use orderedPairs() to iterate over a table in the right order - change the order of expected, actual in assertEquals() and the default value of USE_EXPECTED_ACTUAL_IN_ASSERT_EQUALS. This can be adjusted with USE_EXPECTED_ACTUAL_IN_ASSERT_EQUALS. Changes between 1.2a and 1.2: - fix: test classes were not run in the right order Changes between 1.2 and 1.1: - tests are now run in alphabetical order - fix a bug that would prevent all tests from being run Changes between 1.1 and 1.0: - internal variables are not global anymore - you can choose between assertEquals( actual, expected) or assertEquals( expected, actual ) - you can assert for an error: assertError( f, a, b ) will assert that calling the function f(a,b) generates an error - display the calling stack when an error is spotted - a dedicated class collects and displays the result, to provide easy customisation - two verbosity level, like in python unittest ]]-- -- SETUP ----------------------------------------------------------------------- -- local argv = arg local typenames = { "Nil", "Boolean", "Number", "String", "Table", "Function", "Thread", "Userdata" } --[[ Some people like assertEquals( actual, expected ) and some people prefer assertEquals( expected, actual ). ]]-- USE_EXPECTED_ACTUAL_IN_ASSERT_EQUALS = USE_EXPECTED_ACTUAL_IN_ASSERT_EQUALS or true -- HELPER FUNCTIONS ------------------------------------------------------------ -- local function tablePrint(tt, indent, done) done = done or {} indent = indent or 0 if type(tt) == "table" then local sb = {} for key, value in pairs(tt) do table.insert(sb, string.rep(" ", indent)) -- indent it if type(value) == "table" and not done[value] then done[value] = true table.insert(sb, "[\""..key.."\"] = {\n"); table.insert(sb, tablePrint(value, indent + 2, done)) table.insert(sb, string.rep(" ", indent)) -- indent it table.insert(sb, "}\n"); elseif "number" == type(key) then table.insert(sb, string.format("\"%s\"\n", tostring(value))) else table.insert(sb, string.format( "%s = \"%s\"\n", tostring(key), tostring(value))) end end return table.concat(sb) else return tt .. "\n" end end local function toString( tbl ) if "nil" == type( tbl ) then return tostring(nil) elseif "table" == type( tbl ) then return tablePrint(tbl) elseif "string" == type( tbl ) then return tbl else return tostring(tbl) end end local function deepCompare(t1, t2, ignore_mt) local ty1 = type(t1) local ty2 = type(t2) if ty1 ~= ty2 then return false end -- non-table types can be directly compared if ty1 ~= 'table' and ty2 ~= 'table' then return t1 == t2 end -- as well as tables which have the metamethod __eq local mt = getmetatable(t1) if not ignore_mt and mt and mt.__eq then return t1 == t2 end for k1,v1 in pairs(t1) do local v2 = t2[k1] if v2 == nil or not deepCompare(v1,v2) then return false end end for k2,v2 in pairs(t2) do local v1 = t1[k2] if v1 == nil or not deepCompare(v1,v2) then return false end end return true end -- Order of testing local function __genOrderedIndex( t ) local orderedIndex = {} for key,_ in pairs(t) do table.insert( orderedIndex, key ) end table.sort( orderedIndex ) return orderedIndex end local function orderedNext(t, state) -- Equivalent of the next() function of table iteration, but returns the -- keys in the alphabetic order. We use a temporary ordered key table that -- is stored in the table being iterated. --print("orderedNext: state = "..tostring(state) ) if state == nil then -- the first time, generate the index t.__orderedIndex = __genOrderedIndex( t ) local key = t.__orderedIndex[1] return key, t[key] end -- fetch the next value local key = nil for i = 1,#t.__orderedIndex do if t.__orderedIndex[i] == state then key = t.__orderedIndex[i+1] end end if key then return key, t[key] end -- no more value to return, cleanup t.__orderedIndex = nil return end local function orderedPairs(t) -- Equivalent of the pairs() function on tables. Allows to iterate -- in order return orderedNext, t, nil end -- ASSERT FUNCTIONS ------------------------------------------------------------ -- function assertError(f, ...) -- assert that calling f with the arguments will raise an error -- example: assertError( f, 1, 2 ) => f(1,2) should generate an error local has_error, error_msg = not pcall( f, ... ) if has_error then return end error( "No error generated", 2 ) end assert_error = assertError function assertEquals(actual, expected) -- assert that two values are equal and calls error else if not USE_EXPECTED_ACTUAL_IN_ASSERT_EQUALS then expected, actual = actual, expected end if "table" == type(actual) then if not deepCompare(actual, expected, true) then error("table expected: \n"..toString(expected)..", actual: \n"..toString(actual)) end else if actual ~= expected then local function wrapValue( v ) if type(v) == 'string' then return "'"..v.."'" end return tostring(v) end local errorMsg --if type(expected) == 'string' then -- errorMsg = "\nexpected: "..wrapValue(expected).."\n".. -- "actual : "..wrapValue(actual).."\n" --else errorMsg = "expected: "..wrapValue(expected)..", actual: "..wrapValue(actual) --end --print(errorMsg) error(errorMsg, 2) end end end assert_equals = assertEquals -- assert_<type> functions for _, typename in ipairs(typenames) do local tName = typename:lower() local assert_typename = "assert"..typename _G[assert_typename] = function(actual, msg) local actualtype = type(actual) if actualtype ~= tName then local errorMsg = tName.." expected but was a "..actualtype if msg then errorMsg = msg.."\n"..errorMsg end error(errorMsg, 2) end return actual end -- Alias to lower underscore naming _G["assert_"..tName] = _G[assert_typename] end -- assert_not_<type> functions for _, typename in ipairs(typenames) do local tName = typename:lower() local assert_not_typename = "assertNot"..typename _G[assert_not_typename] = function(actual, msg) if type(actual) == tName then local errorMsg = tName.." not expected but was one" if msg then errorMsg = msg.."\n"..errorMsg end error(errorMsg, 2) end end -- Alias to lower underscore naming _G["assert_not_"..tName] = _G[assert_not_typename] end -- UNITRESULT CLASS ------------------------------------------------------------ -- local UnitResult = { -- class failureCount = 0, skipCount = 0, testCount = 0, errorList = {}, currentClassName = "", currentTestName = "", testHasFailure = false, testSkipped = false, verbosity = 1 } function UnitResult:displayClassName() --if self.verbosity == 0 then print("") end print(self.currentClassName) end function UnitResult:displayTestName() if self.verbosity == 0 then io.stdout:write(".") else io.stdout:write((" [%s] "):format(self.currentTestName)) end end function UnitResult:displayFailure(errorMsg) if self.verbosity == 0 then io.stdout:write("F") else --print(errorMsg) print("", "Failed") end end function UnitResult:displaySuccess() if self.verbosity == 0 then io.stdout:write(".") else print("", "Ok") end end function UnitResult:displaySkip() if self.verbosity == 0 then io.stdout:write(".") else print("", "Skipped") end end function UnitResult:displayOneFailedTest(failure) local testName, errorMsg = unpack(failure) print(">>> "..testName.." failed") print(errorMsg) end function UnitResult:displayFailedTests() if #self.errorList == 0 then return end print("Failed tests:") print("-------------") for i,v in ipairs(self.errorList) do self.displayOneFailedTest(i, v) end end function UnitResult:displayFinalResult() if self.verbosity == 0 then print("") end print("=========================================================") self:displayFailedTests() local failurePercent, successCount local totalTested = self.testCount - self.skipCount if totalTested == 0 then failurePercent = 0 else failurePercent = 100 * self.failureCount / totalTested end local successCount = totalTested - self.failureCount print( string.format("Success : %d%% - %d / %d (total of %d tests, %d skipped)", 100-math.ceil(failurePercent), successCount, totalTested, self.testCount, self.skipCount ) ) return self.failureCount end function UnitResult:startClass(className) self.currentClassName = className self:displayClassName() -- indent status messages if self.verbosity == 0 then io.stdout:write("\t") end end function UnitResult:startTest(testName) self.currentTestName = testName self:displayTestName() self.testCount = self.testCount + 1 self.testHasFailure = false self.testSkipped = false end function UnitResult:addFailure( errorMsg ) self.failureCount = self.failureCount + 1 self.testHasFailure = true table.insert( self.errorList, { self.currentTestName, errorMsg } ) self:displayFailure( errorMsg ) end function UnitResult:addSkip() self.testSkipped = true self.skipCount = self.skipCount + 1 end function UnitResult:endTest() if not self.testHasFailure then if self.testSkipped then self:displaySkip() else self:displaySuccess() end end end -- class UnitResult end -- LUAUNIT CLASS --------------------------------------------------------------- -- local LuaUnit = { result = UnitResult, _VERSION = "2.0" } -- Sets the verbosity level -- @param lvl {number} If greater than 0 there will be verbose output. Defaults to 0 function LuaUnit:setVerbosity(lvl) self.result.verbosity = lvl or 0 assert("number" == type(self.result.verbosity), ("bad argument #1 to 'setVerbosity' (number expected, got %s)"):format(type(self.result.verbosity))) end -- Other alias's LuaUnit.set_verbosity = LuaUnit.setVerbosity LuaUnit.SetVerbosity = LuaUnit.setVerbosity -- Split text into a list consisting of the strings in text, -- separated by strings matching delimiter (which may be a pattern). -- example: strsplit(",%s*", "Anna, Bob, Charlie,Dolores") function LuaUnit.strsplit(delimiter, text) local list = {} local pos = 1 if string.find("", delimiter, 1) then -- this would result in endless loops error("delimiter matches empty string!") end while 1 do local first, last = string.find(text, delimiter, pos) if first then -- found? table.insert(list, string.sub(text, pos, first-1)) pos = last+1 else table.insert(list, string.sub(text, pos)) break end end return list end -- Type check functions for _, typename in ipairs(typenames) do local tName = typename:lower() LuaUnit["is"..typename] = function(x) return type(x) == tName end -- Alias to lower underscore naming LuaUnit["is_"..tName] = LuaUnit["is"..typename] end -- Use me to wrap a set of functions into a Runnable test class: -- TestToto = wrapFunctions( f1, f2, f3, f3, f5 ) -- Now, TestToto will be picked up by LuaUnit:run() function LuaUnit.wrapFunctions(...) local testClass, testFunction testClass = {} local function storeAsMethod(idx, testName) testFunction = _G[testName] testClass[testName] = testFunction end for i, v in ipairs {...} do storeAsMethod(i, v) end return testClass end -- Other alias's LuaUnit.wrap_functions = LuaUnit.wrapFunctions LuaUnit.WrapFunctions = LuaUnit.wrapFunctions function LuaUnit.strip_luaunit_stack(stack_trace) local stack_list = LuaUnit.strsplit( "\n", stack_trace ) local strip_end = nil for i = #stack_list,1,-1 do -- a bit rude but it works ! if string.find(stack_list[i],"[C]: in function `xpcall'",0,true) then strip_end = i - 2 end end if strip_end then table.setn( stack_list, strip_end ) end local stack_trace = table.concat( stack_list, "\n" ) return stack_trace end function LuaUnit:runTestMethod(aName, aClassInstance, aMethod) local ok, errorMsg -- example: runTestMethod( 'TestToto:test1', TestToto, TestToto.testToto(self) ) LuaUnit.result:startTest(aName) -- run setUp first(if any) if self.isFunction( aClassInstance.setUp) then aClassInstance:setUp() elseif self.isFunction( aClassInstance.Setup) then aClassInstance:Setup() elseif self.isFunction( aClassInstance.setup) then aClassInstance:setup() end -- run testMethod() local tracemsg local function trace(err) tracemsg = debug.traceback() return err end local ok, errorMsg, ret = xpcall( aMethod, trace ) if not ok then errorMsg = self.strip_luaunit_stack(errorMsg) if type(errorMsg) == "string" and errorMsg:sub(-9):lower() == ": skipped" then LuaUnit.result:addSkip() else LuaUnit.result:addFailure( errorMsg ..'\n'.. tracemsg) end end -- lastly, run tearDown(if any) if self.isFunction(aClassInstance.tearDown) then aClassInstance:tearDown() elseif self.isFunction(aClassInstance.TearDown) then aClassInstance:TearDown() elseif self.isFunction(aClassInstance.teardown) then aClassInstance:teardown() end self.result:endTest() end function LuaUnit:runTestMethodName(methodName, classInstance) -- example: runTestMethodName( 'TestToto:testToto', TestToto ) local methodInstance = loadstring(methodName .. '()') LuaUnit:runTestMethod(methodName, classInstance, methodInstance) end function LuaUnit:runTestClassByName(aClassName) --assert("table" == type(aClassName), ("bad argument #1 to 'runTestClassByName' (string expected, got %s). Make sure you are not trying to just pass functions not part of a class."):format(type(aClassName))) -- example: runTestMethodName( 'TestToto' ) local hasMethod, methodName, classInstance hasMethod = string.find(aClassName, ':' ) if hasMethod then methodName = string.sub(aClassName, hasMethod+1) aClassName = string.sub(aClassName,1,hasMethod-1) end classInstance = _G[aClassName] if "table" ~= type(classInstance) then error("No such class: "..aClassName) end LuaUnit.result:startClass( aClassName ) if hasMethod then if not classInstance[ methodName ] then error( "No such method: "..methodName ) end LuaUnit:runTestMethodName( aClassName..':'.. methodName, classInstance ) else -- run all test methods of the class for methodName, method in orderedPairs(classInstance) do --for methodName, method in classInstance do if LuaUnit.isFunction(method) and (string.sub(methodName, 1, 4) == "test" or string.sub(methodName, 1, 4) == "Test") then LuaUnit:runTestMethodName( aClassName..':'.. methodName, classInstance ) end end end end function LuaUnit:run(...) -- Run some specific test classes. -- If no arguments are passed, run the class names specified on the -- command line. If no class name is specified on the command line -- run all classes whose name starts with 'Test' -- -- If arguments are passed, they must be strings of the class names -- that you want to run local args = {...} if #args > 0 then for i, v in ipairs(args) do LuaUnit.runTestClassByName(i, v) end else if argv and #argv > 1 then -- Run files passed on the command line for i, v in ipairs(argv) do LuaUnit.runTestClassByName(i, v) end else -- create the list before. If you do not do it now, you -- get undefined result because you modify _G while iterating -- over it. local testClassList = {} for key, val in pairs(_G) do if type(key) == "string" and "table" == type(val) then if string.sub(key, 1, 4) == "Test" or string.sub(key, 1, 4) == "test" then table.insert( testClassList, key ) end end end for i, val in orderedPairs(testClassList) do LuaUnit:runTestClassByName(val) end end end return LuaUnit.result:displayFinalResult() end -- Other alias LuaUnit.Run = LuaUnit.run -- end class LuaUnit return LuaUnit
apache-2.0
bmscoordinators/FFXI-Server
scripts/globals/items/love_chocolate.lua
12
1133
----------------------------------------- -- ID: 5230 -- Item: love_chocolate -- Food Effect: 180Min, All Races ----------------------------------------- -- Magic Regen While Healing 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5230); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 4); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Windurst_Woods/Zone.lua
26
2352
----------------------------------- -- -- Zone: Windurst_Woods (241) -- ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/events/harvest_festivals"); require("scripts/globals/zone"); require("scripts/globals/settings"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) applyHalloweenNpcCostumes(zone:getID()) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; -- FIRST LOGIN (START CS) if (player:getPlaytime(false) == 0) then if (OPENING_CUTSCENE_ENABLE == 1) then cs = 0x016F; end player:setPos(0,0,-50,0); player:setHomePoint(); end -- MOG HOUSE EXIT if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then position = math.random(1,5) + 37; player:setPos(-138,-10,position,0); if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then cs = 0x7534; end player:setVar("PlayerMainJob",0); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x016F) then player:messageSpecial(ITEM_OBTAINED,0x218); elseif (csid == 0x7534 and option == 0) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); end end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Eastern_Adoulin/npcs/HomePoint#2.lua
27
1255
----------------------------------- -- Area: Eastern_Adoulin -- NPC: HomePoint#2 -- @pos ----------------------------------- package.loaded["scripts/zones/Eastern_Adoulin/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Eastern_Adoulin/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fd, 110); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fd) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
ashkanpj/firec
plugins/inrealm.lua
850
25085
-- 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 is_sudo(msg) or is_realm(msg) and is_admin(msg) then 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 end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['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, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['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, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['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, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['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, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['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 local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) 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' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(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) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
saeid0034/New
plugins/inrealm.lua
850
25085
-- 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 is_sudo(msg) or is_realm(msg) and is_admin(msg) then 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 end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['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, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['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, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['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, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['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, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['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 local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) 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' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(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) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
bmscoordinators/FFXI-Server
scripts/zones/Northern_San_dOria/npcs/Jufaue.lua
14
1065
----------------------------------- -- Area: Northern San d'Oria -- NPC: Jufaue -- Type: Past Event Watcher -- @zone 231 -- @pos 13.221 -1.199 -19.231 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02cb); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/globals/items/nosteau_herring.lua
12
1330
----------------------------------------- -- ID: 4482 -- Item: nosteau_herring -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4482); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -4); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Southern_San_dOria/npcs/Rouva.lua
14
1754
----------------------------------- -- Area: Southern San d'Oria -- NPC: Rouva -- Involved in Quest: Lure of the Wildcat (San d'Oria) -- @pos -17 2 10 230 ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatSandy = player:getVar("WildcatSandy"); if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,2) == false) then player:startEvent(0x0328); else player:startEvent(0x0298); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0328) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",2,true); end end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Castle_Oztroja/npcs/_475.lua
14
1143
----------------------------------- -- Area: Castle Oztroja -- NPC: _475 (Brass Door) -- Involved in Mission: Magicite -- @pos -99 24 -105 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Castle_Oztroja/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 9) then player:messageSpecial(ITS_LOCKED); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Windurst_Woods/npcs/Sariale.lua
5
1975
----------------------------------- -- Area: Windurst Woods -- NPC: Sariale -- Type: Chocobo Renter ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/chocobo"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local level = player:getMainLvl(); local gil = player:getGil(); if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 15) then local price = getChocoboPrice(player); player:setLocalVar("chocoboPriceOffer",price); if (level >= 20) then level = 0; end player:startEvent(0x2713,price,gil); else player:startEvent(0x2716); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local price = player:getLocalVar("chocoboPriceOffer"); if (csid == 0x2713 and option == 0) then if (player:delGil(price)) then updateChocoboPrice(player, price); if (player:getMainLvl() >= 20) then local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60) player:addStatusEffectEx(EFFECT_MOUNTED,EFFECT_MOUNTED,0,0,duration,true); else player:addStatusEffectEx(EFFECT_MOUNTED,EFFECT_MOUNTED,0,0,900,true); end player:setPos(-122,-4,-520,0,0x74); end end end;
gpl-3.0
jsenellart/OpenNMT
tools/release_model.lua
3
2834
require('onmt.init') local path = require('pl.path') local cmd = onmt.utils.ExtendedCmdLine.new('release_model.lua') local options = { { '-model', '', [[Path to the trained model to release.]], { valid = onmt.utils.ExtendedCmdLine.fileExists } }, { '-output_model', '', [[Path the released model. If not set, the `release` suffix will be automatically added to the model filename.]] }, { '-force', false, [[Force output model creation even if the target file exists.]] } } cmd:setCmdLineOptions(options, 'Model') onmt.utils.Cuda.declareOpts(cmd) onmt.utils.Logger.declareOpts(cmd) local opt = cmd:parse(arg) local function isModel(object) return torch.type(object) == 'table' and object.modules end local function releaseModule(object, tensorCache) tensorCache = tensorCache or {} if object.release then object:release() end object:float(tensorCache) object:clearState() object:apply(function (m) nn.utils.clear(m, 'gradWeight', 'gradBias') for k, v in pairs(m) do if type(v) == 'function' then m[k] = nil end end end) end local function releaseModel(model, tensorCache) tensorCache = tensorCache or {} for _, object in pairs(model.modules) do if isModel(object) then releaseModel(object, tensorCache) else releaseModule(object, tensorCache) end end end local function main() assert(path.exists(opt.model), 'model \'' .. opt.model .. '\' does not exist.') _G.logger = onmt.utils.Logger.new(opt.log_file, opt.disable_logs, opt.log_level) if opt.output_model:len() == 0 then if opt.model:sub(-3) == '.t7' then opt.output_model = opt.model:sub(1, -4) -- copy input model without '.t7' extension else opt.output_model = opt.model end opt.output_model = opt.output_model .. '_release.t7' end if not opt.force then assert(not path.exists(opt.output_model), 'output model already exists; use -force to overwrite.') end onmt.utils.Cuda.init(opt) _G.logger:info('Loading model \'' .. opt.model .. '\'...') local checkpoint local _, err = pcall(function () checkpoint = torch.load(opt.model) end) if err then error('unable to load the model (' .. err .. '). If you are releasing a GPU model, it needs to be loaded on the GPU first (set -gpuid > 0)') end _G.logger:info('... done.') _G.logger:info('Converting model...') checkpoint.info = nil for _, object in pairs(checkpoint.models) do if isModel(object) then releaseModel(object) else releaseModule(object) end end _G.logger:info('... done.') _G.logger:info('Releasing model \'' .. opt.output_model .. '\'...') torch.save(opt.output_model, checkpoint) _G.logger:info('... done.') _G.logger:shutDown() end main()
mit
MRAHS/SBSS_Plus
plugins/Add_Bot.lua
29
1484
--[[ Bot can join into a group by replying a message contain an invite link or by typing !join [invite link]. URL.parse cannot parsing complicated message. So, this plugin only works for single [invite link] in a post. [invite link] may be preceeded but must not followed by another characters. --]] do local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) i = 0 for k,segment in pairs(parsed_path) do i = i + 1 if segment == 'joinchat' then invite_link = string.gsub(parsed_path[i+1], '[ %c].+$', '') break end end return invite_link end local function action_by_reply(extra, success, result) local hash = parsed_url(result.text) join = import_chat_link(hash, ok_cb, false) end function run(msg, matches) if is_sudo(msg) then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) elseif matches[1] then local hash = parsed_url(matches[1]) join = import_chat_link(hash, ok_cb, false) end end end return { description = 'Invite the bot into a group chat via its invite link.', usage = { '!AddBot : Join a group by replying a message containing invite link.', '!AddBot [invite_link] : Join into a group by providing their [invite_link].' }, patterns = { '^!AddBot$', '^!AddBot (.*)$' }, run = run } end
gpl-2.0
bmscoordinators/FFXI-Server
scripts/zones/Castle_Zvahl_Keep/npcs/Treasure_Chest.lua
17
3763
----------------------------------- -- Area: Castle Zvahl Keep -- NPC: Treasure Chest -- @zone 162 ----------------------------------- package.loaded["scripts/zones/Castle_Zvahl_Keep/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Castle_Zvahl_Keep/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1048,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1048,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); -- IMPORTANT ITEM: keyitem ----------- if (player:getQuestStatus(BASTOK,A_TEST_OF_TRUE_LOVE) == QUEST_ACCEPTED and player:hasKeyItem(UN_MOMENT) == false) then questItemNeeded = 1; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- 0 or 1 -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then player:setVar("ATestOfTrueLoveProgress",player:getVar("ATestOfTrueLoveProgress")+1); player:addKeyItem(UN_MOMENT); player:messageSpecial(KEYITEM_OBTAINED,UN_MOMENT); -- Un moment for A Test Of True Love quest else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1048); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/globals/items/death_scythe.lua
42
1065
----------------------------------------- -- ID: 16777 -- Item: Death Scythe -- Additional Effect: Drains HP ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance) then return 0,0,0; else local power = 10; local params = {}; params.bonusmab = 0; params.includemab = false; power = addBonusesAbility(player, ELE_DARK, target, power, params); power = power * applyResistanceAddEffect(player,target,ELE_DARK,0); power = adjustForTarget(target,power,ELE_DARK); power = finalMagicNonSpellAdjustments(player,target,ELE_DARK,power ); if (power < 0) then power = 0; else player:addHP(power) end return SUBEFFECT_HP_DRAIN, MSGBASIC_ADD_EFFECT_HP_DRAIN, power; end end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/globals/weaponskills/knights_of_round.lua
19
1904
----------------------------------- -- Knights Of Round -- Sword Weapon Skill -- Skill Level: N/A -- Caliburn/Excalibur: Additional Effect: Regen. -- Regen 10HP/Tick, duration varies with TP. -- Available only when equipped with the Relic Weapons Caliburn (Dynamis use only) or Excalibur. -- Also available without aftermath as a latent effect on Corbenic Sword. -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: None -- Modifiers: STR:40% ; MND:40% -- 100%TP 200%TP 300%TP -- 3.00 3.00 3.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 = 1; params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3; params.str_wsc = 0.4; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.4; 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.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 5; params.ftp200 = 5; params.ftp300 = 5; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); -- TODO: Whoever codes those level 85 weapons with the latent that grants this WS needs to code a check to not give the aftermath effect. if (damage > 0) then local amDuration = 20 * math.floor(tp/1000); player:addStatusEffect(EFFECT_AFTERMATH, 10, 0, amDuration, 0, 3); end return tpHits, extraHits, criticalHit, damage; end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Abyssea-Vunkerl/npcs/qm5.lua
14
1357
----------------------------------- -- Zone: Abyssea-Vunkerl -- NPC: qm5 (???) -- Spawns Kadraeth the Hatespawn -- @pos ? ? ? 217 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3102,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(17666491) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17666491):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3102); -- Inform player what items they need. end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/globals/weaponskills/blade_ku.lua
26
1711
----------------------------------- -- Blade Ku -- Katana weapon skill -- Skill level: N/A -- Description: Delivers a five-hit attack. params.accuracy varies with TP. -- In order to obtain Blade: Ku, the quest Bugi Soden must be completed. -- Will stack with Sneak Attack. -- Aligned with the Shadow Gorget, Soil Gorget & Light Gorget. -- Aligned with the Shadow Belt, Soil Belt & Light Belt. -- Skillchain Properties: Gravitation/Transfixion -- Modifiers: STR:10% ; DEX:10% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 -- -- params.acc -- 100%TP 200%TP 300%TP -- ?? ?? ?? ----------------------------------- 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 = 5; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.1; params.dex_wsc = 0.1; 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.8; params.acc200= 0.9; params.acc300= 1.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 1.25; params.ftp200 = 1.25; params.ftp300 = 1.25; params.str_wsc = 0.3; params.dex_wsc = 0.3; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Tavnazian_Safehold/npcs/Maturiri.lua
14
1064
---------------------------------- -- Area: Tavnazian Safehold -- NPC: Maturiri -- Type: Item Deliverer -- @zone 26 -- @pos -77.366 -20 -71.128 -- ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
NoahNMorton/MinecraftLuaPrograms
Computercraft/Botaniaendoflameautomation (x6hJNtW2).lua
2
1518
--Botania Endoflame redstone dropper automation --Copyright 2015 Gangsir --Provide args on launch for fuel type. either coal,coalblock,coalcoke,coalcokeblock. local fueltype = {...} --get args local dir = fueltype[2] --direction to output redstone on function isCoal() while true do rs.setOutput(dir,true) sleep(1) rs.setOutput(dir,false) sleep(80) end end function isCoalBlock() while true do rs.setOutput(dir,true) sleep(1) rs.setOutput(dir,false) sleep(720) end end function isCoalCoke() while true do rs.setOutput(dir,true) sleep(1) rs.setOutput(dir,false) sleep(320) end end function isCoalCokeBlock() while true do rs.setOutput(dir,true) sleep(1) rs.setOutput(dir,false) sleep(2880) end end if fueltype[1] == nil then print("Usage: Provide fuel type. coal,coalblock,coalcoke,coalcokeblock. Also provide direction to output redstone.") return nil end if fueltype[1] == "coal" then print("Fuel type is coal, dropping every 80 seconds.") isCoal() end if fueltype[1] == "coalblock" then print("Fuel type is coal blocks, dropping every 12 mins.") isCoalBlock() end if fueltype[1] == "coalcoke" then print("Fuel type is coal blocks, dropping every 5 mins 20 secs.") isCoalCoke() end if fueltype[1] == "coalcokeblock" then print("Fuel type is coal coke blocks, dropping every 48 mins.") isCoalCokeBlock() end
mit
bmscoordinators/FFXI-Server
scripts/globals/items/plate_of_yahata-style_carp_sushi.lua
12
1423
----------------------------------------- -- ID: 5186 -- Item: plate_of_yahata-style_carp_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- Dexterity 2 -- Accuracy % 11 (cap 56) -- HP Recovered While Healing 2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5186); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_FOOD_ACCP, 11); target:addMod(MOD_FOOD_ACC_CAP, 56); target:addMod(MOD_HPHEAL, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_FOOD_ACCP, 11); target:delMod(MOD_FOOD_ACC_CAP, 56); target:delMod(MOD_HPHEAL, 2); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Northern_San_dOria/npcs/Gulmama.lua
13
5620
----------------------------------- -- Area: Northern San d'Oria -- NPC: Gulmama -- Starts and Finishes Quest: Trial by Ice -- Involved in Quest: Class Reunion -- @pos -186 0 107 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TrialByIce = player:getQuestStatus(SANDORIA,TRIAL_BY_ICE); local WhisperOfFrost = player:hasKeyItem(WHISPER_OF_FROST); local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day local ClassReunion = player:getQuestStatus(WINDURST,CLASS_REUNION); local ClassReunionProgress = player:getVar("ClassReunionProgress"); ------------------------------------------------------------ -- Class Reunion if (ClassReunion == 1 and ClassReunionProgress == 4) then player:startEvent(0x02c9,0,1171,0,0,0,0,0,0); -- he gives you an ice pendulum and wants you to go to Cloister of Frost elseif (ClassReunion == 1 and ClassReunionProgress == 5 and player:hasItem(1171) == false) then player:startEvent(0x02c8,0,1171,0,0,0,0,0,0); -- lost the ice pendulum need another one ------------------------------------------------------------ elseif ((TrialByIce == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 6) or (TrialByIce == QUEST_COMPLETED and realday ~= player:getVar("TrialByIce_date"))) then player:startEvent(0x02c2,0,TUNING_FORK_OF_ICE); -- Start and restart quest "Trial by ice" elseif (TrialByIce == QUEST_ACCEPTED and player:hasKeyItem(TUNING_FORK_OF_ICE) == false and WhisperOfFrost == false) then player:startEvent(0x02ce,0,TUNING_FORK_OF_ICE); -- Defeat against Shiva : Need new Fork elseif (TrialByIce == QUEST_ACCEPTED and WhisperOfFrost == false) then player:startEvent(0x02c3,0,TUNING_FORK_OF_ICE,4); elseif (TrialByIce == QUEST_ACCEPTED and WhisperOfFrost) then local numitem = 0; if (player:hasItem(17492)) then numitem = numitem + 1; end -- Shiva's Claws if (player:hasItem(13242)) then numitem = numitem + 2; end -- Ice Belt if (player:hasItem(13561)) then numitem = numitem + 4; end -- Ice Ring if (player:hasItem(1207)) then numitem = numitem + 8; end -- Rust 'B' Gone if (player:hasSpell(302)) then numitem = numitem + 32; end -- Ability to summon Shiva player:startEvent(0x02c5,0,TUNING_FORK_OF_ICE,4,0,numitem); else player:startEvent(0x02c6); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x02c2 and option == 1) then if (player:getQuestStatus(SANDORIA,TRIAL_BY_ICE) == QUEST_COMPLETED) then player:delQuest(SANDORIA,TRIAL_BY_ICE); end player:addQuest(SANDORIA,TRIAL_BY_ICE); player:setVar("TrialByIce_date", 0); player:addKeyItem(TUNING_FORK_OF_ICE); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_ICE); elseif (csid == 0x02ce) then player:addKeyItem(TUNING_FORK_OF_ICE); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_ICE); elseif (csid == 0x02c5) then local item = 0; if (option == 1) then item = 17492; -- Shiva's Claws elseif (option == 2) then item = 13242; -- Ice Belt elseif (option == 3) then item = 13561; -- Ice Ring elseif (option == 4) then item = 1207; -- Rust 'B' Gone end if (player:getFreeSlotsCount() == 0 and (option ~= 5 or option ~= 6)) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item); else if (option == 5) then player:addGil(GIL_RATE*10000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*10000); -- Gil elseif (option == 6) then player:addSpell(302); -- Avatar player:messageSpecial(SHIVA_UNLOCKED,0,0,4); else player:addItem(item); player:messageSpecial(ITEM_OBTAINED,item); -- Item end player:addTitle(HEIR_OF_THE_GREAT_ICE); player:delKeyItem(WHISPER_OF_FROST); --Whisper of Frost, as a trade for the above rewards player:setVar("TrialByIce_date", os.date("%j")); -- %M for next minute, %j for next day player:addFame(SANDORIA,30); player:completeQuest(SANDORIA,TRIAL_BY_ICE); end elseif (csid == 0x02c9 or csid == 0x02c8) then if (player:getFreeSlotsCount() ~= 0) then player:addItem(1171); player:messageSpecial(ITEM_OBTAINED,1171); player:setVar("ClassReunionProgress",5); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1171); end; end; end;
gpl-3.0
albanD/adaptive-neural-compilation
adaptation/layers/machine.lua
1
11185
require 'nn' local ops = require 'nc.ops' local layers = require 'nc.layers' local distUtils = require 'nc.distUtils' local RamMachine, parent = torch.class('nc.RamMachine', 'nn.Module', layers) function RamMachine:__init(nb_registers, memory_size) parent.__init(self) -- Initialise parameters self.memory_size = memory_size self.nb_registers = nb_registers -- Initialise instruction set self.instruction_set = {} local current_pos = 1 -- Load the instruction set self.stop_op_index = current_pos table.insert(self.instruction_set, ops.Stop_op(memory_size)); current_pos = current_pos + 1 table.insert(self.instruction_set, ops.Zero_op(memory_size)); current_pos = current_pos + 1 table.insert(self.instruction_set, ops.Inc_op(memory_size)); current_pos = current_pos + 1 table.insert(self.instruction_set, ops.Add_op(memory_size)); current_pos = current_pos + 1 table.insert(self.instruction_set, ops.Sub_op(memory_size)); current_pos = current_pos + 1 table.insert(self.instruction_set, ops.Dec_op(memory_size)); current_pos = current_pos + 1 table.insert(self.instruction_set, ops.Min_op(memory_size)); current_pos = current_pos + 1 table.insert(self.instruction_set, ops.Max_op(memory_size)); current_pos = current_pos + 1 table.insert(self.instruction_set, ops.Read_op(memory_size)); current_pos = current_pos + 1 self.write_op_index = current_pos table.insert(self.instruction_set, ops.Write_op(memory_size)); current_pos = current_pos + 1 self.jump_op_index = current_pos table.insert(self.instruction_set, ops.Jez_op(memory_size)); current_pos = current_pos + 1 self.arg1 = torch.zeros(self.memory_size) self.arg2 = torch.zeros(self.memory_size) self.out_vector = torch.zeros(self.memory_size) self.out_instr = torch.Tensor(ops.nb_existing_ops, self.memory_size) end function RamMachine:updateOutput(input) -- Input is -- { {[R] [R] [R] [I]} , {[M x M] [R x M] [2]} } -- Arg1-distribution, Arg2-distribution, out-distribution, Instruction distribution -- Memory-distribution, Register distribution, StopTensor -- Output is -- { [M x M] [R x M] [2] } -- Memory-distribution, Register distribution, StopTensor local operation_parameters = input[1] local memory_tape = input[2][1]:clone() local registers = input[2][2]:clone() local stop_tensor = input[2][3]:clone() local instruction_register = registers[1] local standard_registers = registers:narrow(1, 2, registers:size(1)-1) torch.mv(self.arg1, standard_registers:t(), operation_parameters[1]) torch.mv(self.arg2, standard_registers:t(), operation_parameters[2]) -- Compute the output of the operations for index, op in ipairs(self.instruction_set) do self.out_instr[index]:copy(op:updateOutput({{self.arg1, self.arg2}, memory_tape})) end -- Modify the memory tape according to the write instruction -- At the moment, this is the only one that has any effect on the memory tape. local write_coefficient = operation_parameters[4][self.write_op_index] self.instruction_set[self.write_op_index]:update_memory(write_coefficient, self.arg1, self.arg2, memory_tape) -- Weight the output of each instruction according to the probability it is used. self.out_vector = torch.mv(self.out_instr:t(), operation_parameters[4]) -- Reshape the vectors so that they can be multiplied correctly with each other. self.out_vector = self.out_vector:view(1,-1) local out_mat = torch.expand(self.out_vector, self.nb_registers-1, self.memory_size) local operation_parameters_3 = operation_parameters[3]:view(-1,1) local register_write_coefficient = torch.expandAs(operation_parameters_3, out_mat) -- Multiply them together so that we have the version of the registers local written_registers_unrolled = torch.cmul(out_mat, register_write_coefficient) -- For each of the output, we had a probability of writing to it. We also have the -- inverse probability of not writing to it (discretely, this corresponds to writing to another register -- and therefore leaving this one intact) local keep_write_coefficient = register_write_coefficient*(-1) + 1 local kept_registers = torch.cmul(standard_registers, keep_write_coefficient) -- Update the standard registers standard_registers:copy(kept_registers + written_registers_unrolled) -- Update the instruction registers local jump_coefficient = operation_parameters[4][self.jump_op_index]*self.arg1[1] -- Standard increment local nojumped_instruction = distUtils.addDist(instruction_register, distUtils.toDist(1, self.memory_size)) -- Increment if the conditional jump was selected. We pick up the second argument as new RI. local jumped_instruction = self.arg2 -- Do the mixing of the instructions positions. instruction_register:copy(jumped_instruction*jump_coefficient + nojumped_instruction*(1-jump_coefficient)) -- Update the stopping criterion local stop_coefficient = operation_parameters[4][self.stop_op_index] stop_tensor[1] = stop_tensor[1] + stop_coefficient * stop_tensor[2] stop_tensor[2] = (1-stop_coefficient) * stop_tensor[2] self.output = {memory_tape, registers, stop_tensor} return self.output end function RamMachine:updateGradInput(input, gradOutput) -- Input is -- { {[R] [R] [R] [I]} , {[M x M] [R x M] t_stop} } and { [M x M] [R x M] t_stop } -- Arg1-distribution, Arg2-distribution, out-distribution, Instruction distribution -- Output is -- { {[R] [R] [R] [I]} , {[M x M] [R x M] t_stop} } -- Memory-distribution, Register distribution if not (type(self.gradInput) == "table") then self.gradInput = { { torch.zeros(self.nb_registers-1), torch.zeros(self.nb_registers-1), torch.zeros(self.nb_registers-1), torch.zeros(ops.nb_existing_ops) }, { torch.zeros(self.memory_size, self.memory_size), torch.zeros(self.nb_registers, self.memory_size), torch.zeros(2) } } self.arg1GradInput = torch.zeros(self.memory_size) self.arg2GradInput = torch.zeros(self.memory_size) self.outGradInput = torch.zeros(self.memory_size) else self.gradInput[1][1]:zero() self.gradInput[1][2]:zero() self.gradInput[1][3]:zero() self.gradInput[1][4]:zero() self.gradInput[2][1]:zero() self.gradInput[2][2]:zero() self.gradInput[2][3]:zero() self.arg1GradInput:zero() self.arg2GradInput:zero() self.outGradInput:zero() end local operation_parameters = input[1] local memory_tape = input[2][1] local registers = input[2][2] local stop_tensor = input[2][3]:clone() local instruction_register = registers[1] local standard_registers = registers:narrow(1, 2, registers:size(1)-1) -------- -- Update the stopping criterion -- Not what we want to do but remove dependancy self.gradInput[1][4][self.stop_op_index] = self.gradInput[1][4][self.stop_op_index] + gradOutput[3][1] * stop_tensor[2] self.gradInput[1][4][self.stop_op_index] = self.gradInput[1][4][self.stop_op_index] - gradOutput[3][2] * stop_tensor[2] self.gradInput[2][3][1] = self.gradInput[2][3][1] + gradOutput[3][1] + operation_parameters[4][self.stop_op_index] * gradOutput[3][2] self.gradInput[2][3][2] = self.gradInput[2][3][2] - gradOutput[3][2] * operation_parameters[4][self.stop_op_index] -------- -- Update the instruction registers local instruction_register_grad_output = gradOutput[2][1] local IR_plus_one = distUtils.addDist(instruction_register, distUtils.toDist(1, self.memory_size)) -- arg1 self.arg1GradInput[1] = self.arg1GradInput[1] + torch.cmul( instruction_register_grad_output, self.arg2 * operation_parameters[4][self.jump_op_index] - IR_plus_one * operation_parameters[4][self.jump_op_index] ):sum() -- arg2 self.arg2GradInput:add(instruction_register_grad_output * self.arg1[1] * operation_parameters[4][self.jump_op_index]) -- jmp instr self.gradInput[1][4][self.jump_op_index] = self.gradInput[1][4][self.jump_op_index] + torch.cmul( instruction_register_grad_output, self.arg2 * self.arg1[1] - IR_plus_one * self.arg1[1] ):sum() -- IR local IR_coeff = (1-self.arg1[1]*operation_parameters[4][self.jump_op_index]) local shifted_irgo = torch.zeros(self.memory_size) shifted_irgo[self.memory_size] = instruction_register_grad_output[1] shifted_irgo:narrow(1,1,self.memory_size-1):copy(instruction_register_grad_output:narrow(1,2,self.memory_size-1)) self.gradInput[2][2]:narrow(1,1,1):add(shifted_irgo * IR_coeff) -------- -- Update the standard registers local std_register_grad_output = gradOutput[2]:narrow(1,2,self.nb_registers-1) local operation_parameters_3 = operation_parameters[3]:view(-1,1) local register_write_coefficient = torch.expand(operation_parameters_3, self.nb_registers-1, self.memory_size) local out_mat = torch.expand(self.out_vector, self.nb_registers-1, self.memory_size) -- std reg self.gradInput[2][2]:narrow(1,2,self.nb_registers-1):add(torch.cmul( std_register_grad_output, register_write_coefficient*(-1) + 1 )) -- param3 self.gradInput[1][3]:add(torch.cmul( std_register_grad_output, out_mat-standard_registers ):sum(2)) -- outMat self.outGradInput:add(torch.cmul( std_register_grad_output, register_write_coefficient ):sum(1)) -------- -- Grad of the memory local write_coefficient = operation_parameters[4][self.write_op_index] self.instruction_set[self.write_op_index]:grad_update_memory( write_coefficient, self.arg1, self.arg2, memory_tape, gradOutput[1], self.gradInput[1][4], self.write_op_index, self.arg1GradInput, self.arg2GradInput, self.gradInput[2][1]) -------- -- Grad of the operations local gi local go for index, op in ipairs(self.instruction_set) do -- grad on instr weight self.gradInput[1][4][index] = self.gradInput[1][4][index] + torch.cmul( self.outGradInput, self.out_instr[index] ):sum() go = self.outGradInput * operation_parameters[4][index] gi = op:updateGradInput({{self.arg1, self.arg2}, memory_tape}, go) -- Grad on arg1 self.arg1GradInput:add(gi[1][1]) -- Grad on arg2 self.arg2GradInput:add(gi[1][2]) -- Grad on mem self.gradInput[2][1]:add(gi[2]) end -------- -- Grad on arg1 -- param1 self.gradInput[1][1]:addmv(0, 1, standard_registers, self.arg1GradInput) -- reg self.gradInput[2][2]:narrow(1,2,self.nb_registers-1):addr(operation_parameters[1], self.arg1GradInput) -------- -- Grad on arg2 -- param2 self.gradInput[1][2]:addmv(0, 1, standard_registers, self.arg2GradInput) -- reg self.gradInput[2][2]:narrow(1,2,self.nb_registers-1):addr(operation_parameters[2], self.arg2GradInput) return self.gradInput end function RamMachine:__tostring__() return "nc.RamMachine :)" end
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Rabao/npcs/Scamplix.lua
17
1532
----------------------------------- -- Area: Rabao -- NPC: Scamplix -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Rabao/TextIDs"] = nil; require("scripts/zones/Rabao/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,SCAMPLIX_SHOP_DIALOG); stock = {0x119D,10, -- Distilled Waterr 0x1118,108, -- Meat Jerky 0x116A,270, -- Goblin Bread 0x0719,720, -- Cactus Arm 0x1020,4348, -- Ether 0x113C,292, -- Thundermelon 0x118B,180, -- Watermelon 0x1010,819, -- Potion 0x1034,284, -- Antidote 0x1043,1080, -- Blinding Potion 0x3410,4050, -- Mythril Earring 0x006B,180, -- Water Jug 0x0b34,9000} -- Rabao Waystone showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
DavidKnight247/solarus
sample_quest/data/menus/solarus_logo.lua
3
5042
-- Animated Solarus logo by Maxs. -- Usage: -- local logo = require("menus/solarus_logo") -- sol.menu.start(logo) local solarus_logo_menu = {} -- Main surface of the menu. local surface = sol.surface.create(201, 48) -- Solarus title sprite. local title = sol.sprite.create("menus/solarus_logo") title:set_animation("title") -- Solarus subtitle sprite. local subtitle = sol.sprite.create("menus/solarus_logo") subtitle:set_animation("subtitle") -- Sun sprite. local sun = sol.sprite.create("menus/solarus_logo") sun:set_animation("sun") -- Sword sprite. local sword = sol.sprite.create("menus/solarus_logo") sword:set_animation("sword") -- Black square below the sun. local black_square = sol.surface.create(48, 15) black_square:fill_color{0, 0, 0} -- Step of the animation. local animation_step = 0 -- Time handling. local timer = nil ------------------------------------------------------------------------------- -- Rebuilds the whole surface of the menu. local function rebuild_surface() surface:clear() -- Draw the title (after step 1). if animation_step >= 1 then title:draw(surface) end -- Draw the sun. sun:draw(surface, 0, 33) -- Draw the black square to partially hide the sun. black_square:draw(surface, 24, 33) -- Draw the sword. sword:draw(surface, 48, -48) -- Draw the subtitle (after step 2). if animation_step >= 2 then subtitle:draw(surface) end end ------------------------------------------------------------------------------- -- Starting the menu. function solarus_logo_menu:on_started() -- Initialize or reinitialize the animation. animation_step = 0 timer = nil surface:set_opacity(255) sun:set_direction(0) sun:set_xy(0, 0) sword:set_xy(0, 0) -- Start the animation. solarus_logo_menu:start_animation() -- Update the surface. rebuild_surface() end -- Animation step 1. function solarus_logo_menu:step1() animation_step = 1 -- Change the sun color. sun:set_direction(1) -- Stop movements and replace elements. sun:stop_movement() sun:set_xy(0, -33) sword:stop_movement() sword:set_xy(-48, 48) -- Update the surface. rebuild_surface() end -- Animation step 2. function solarus_logo_menu:step2() animation_step = 2 -- Update the surface. rebuild_surface() -- Start the final timer. sol.timer.start(solarus_logo_menu, 500, function() surface:fade_out() sol.timer.start(solarus_logo_menu, 700, function() sol.menu.stop(solarus_logo_menu) end) end) end -- Run the logo animation. function solarus_logo_menu:start_animation() -- Move the sun. local sun_movement = sol.movement.create("target") sun_movement:set_speed(64) sun_movement:set_target(0, -33) -- Update the surface whenever the sun moves. function sun_movement:on_position_changed() rebuild_surface() end -- Move the sword. local sword_movement = sol.movement.create("target") sword_movement:set_speed(96) sword_movement:set_target(-48, 48) -- Update the surface whenever the sword moves. function sword_movement:on_position_changed() rebuild_surface() end -- Start the movements. sun_movement:start(sun, function() sword_movement:start(sword, function() if not sol.menu.is_started(solarus_logo_menu) then -- The menu may have been stopped, but the movement continued. return end -- If the animation step is not greater than 0 -- (if no key was pressed). if animation_step <= 0 then -- Start step 1. solarus_logo_menu:step1() -- Create the timer for step 2. timer = sol.timer.start(solarus_logo_menu, 250, function() -- If the animation step is not greater than 1 -- (if no key was pressed). if animation_step <= 1 then -- Start step 2. solarus_logo_menu:step2() end end) end end) end) end -- Draws this menu on the quest screen. function solarus_logo_menu:on_draw(screen) -- Get the screen size. local width, height = screen:get_size() -- Center the surface in the screen. surface:draw(screen, width / 2 - 100, height / 2 - 24) end -- Called when a keyboard key is pressed. function solarus_logo_menu:on_key_pressed(key) if key == "escape" then -- Escape: quit Solarus. sol.main.exit() else -- If the timer exists (after step 1). if timer ~= nil then -- Stop the timer. timer:stop() timer = nil -- If the animation step is not greater than 1 -- (if the timer has not expired in the meantime). if animation_step <= 1 then -- Start step 2. solarus_logo_menu:step2() end -- If the animation step is not greater than 0. elseif animation_step <= 0 then -- Start step 1. solarus_logo_menu:step1() -- Start step 2. solarus_logo_menu:step2() end -- Return true to indicate that the keyboard event was handled. return true end end -- Return the menu to the caller. return solarus_logo_menu
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Selbina/npcs/Chutarmire.lua
17
1765
----------------------------------- -- Area: Selbina -- NPC: Chutarmire -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CHUTARMIRE_SHOP_DIALOG); stock = {0x12A0,5751, -- Scroll of Stone II 0x12AA,8100, -- Scroll of Water II 0x129B,11970, -- Scroll of Aero II 0x1291,16560, -- Scroll of Fire II 0x1296,21870, -- Scroll of Blizzard II 0x12A5,27900, -- Scroll of Thunder II 0x12BD,1165, -- Scroll of Stonega 0x12C7,2097, -- Scroll of Waterga 0x12B8,4147, -- Scroll of Aeroga 0x12AE,7025, -- Scroll of Firaga 0x12B3,10710, -- Scroll of Blizzaga 0x12C2,15120, -- Scroll of Thundaga 0x12DD,22680, -- Scroll of Poison II 0x12E7,12600, -- Scroll of Bio II 0x12E1,4644, -- Scroll of Poisonga 0x12FB,8100} -- Scroll of Shock Spikes showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Temple_of_Uggalepih/npcs/_mf8.lua
14
1429
----------------------------------- -- Area: Temple of Uggalepih -- NPC: _mf8 (Granite Door) -- Notes: Opens with Prelate Key -- @pos -11 -8 -99 159 ----------------------------------- package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Temple_of_Uggalepih/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1137,1) and trade:getItemCount() == 1) then -- Trade Prelate Key player:tradeComplete(); player:messageSpecial(YOUR_KEY_BREAKS,0000,1137); npc:openDoor(6.5); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getXPos() <= -8) then player:messageSpecial(THE_DOOR_IS_LOCKED,1137); else npc:openDoor(11); -- retail timed end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
chanko08/Ludum-Dare-34
lib/hump/vector.lua
20
5319
--[[ Copyright (c) 2010-2013 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 assert = assert local sqrt, cos, sin, atan2 = math.sqrt, math.cos, math.sin, math.atan2 local vector = {} vector.__index = vector local function new(x,y) return setmetatable({x = x or 0, y = y or 0}, vector) end local zero = new(0,0) local function isvector(v) return type(v) == 'table' and type(v.x) == 'number' and type(v.y) == 'number' end function vector:clone() return new(self.x, self.y) end function vector:unpack() return self.x, self.y end function vector:__tostring() return "("..tonumber(self.x)..","..tonumber(self.y)..")" end function vector.__unm(a) return new(-a.x, -a.y) end function vector.__add(a,b) assert(isvector(a) and isvector(b), "Add: wrong argument types (<vector> expected)") return new(a.x+b.x, a.y+b.y) end function vector.__sub(a,b) assert(isvector(a) and isvector(b), "Sub: wrong argument types (<vector> expected)") return new(a.x-b.x, a.y-b.y) end function vector.__mul(a,b) if type(a) == "number" then return new(a*b.x, a*b.y) elseif type(b) == "number" then return new(b*a.x, b*a.y) else assert(isvector(a) and isvector(b), "Mul: wrong argument types (<vector> or <number> expected)") return a.x*b.x + a.y*b.y end end function vector.__div(a,b) assert(isvector(a) and type(b) == "number", "wrong argument types (expected <vector> / <number>)") return new(a.x / b, a.y / b) end function vector.__eq(a,b) return a.x == b.x and a.y == b.y end function vector.__lt(a,b) return a.x < b.x or (a.x == b.x and a.y < b.y) end function vector.__le(a,b) return a.x <= b.x and a.y <= b.y end function vector.permul(a,b) assert(isvector(a) and isvector(b), "permul: wrong argument types (<vector> expected)") return new(a.x*b.x, a.y*b.y) end function vector:len2() return self.x * self.x + self.y * self.y end function vector:len() return sqrt(self.x * self.x + self.y * self.y) end function vector.dist(a, b) assert(isvector(a) and isvector(b), "dist: wrong argument types (<vector> expected)") local dx = a.x - b.x local dy = a.y - b.y return sqrt(dx * dx + dy * dy) end function vector.dist2(a, b) assert(isvector(a) and isvector(b), "dist: wrong argument types (<vector> expected)") local dx = a.x - b.x local dy = a.y - b.y return (dx * dx + dy * dy) end function vector:normalizeInplace() local l = self:len() if l > 0 then self.x, self.y = self.x / l, self.y / l end return self end function vector:normalized() return self:clone():normalizeInplace() end function vector:rotateInplace(phi) local c, s = cos(phi), sin(phi) self.x, self.y = c * self.x - s * self.y, s * self.x + c * self.y return self end function vector:rotated(phi) local c, s = cos(phi), sin(phi) return new(c * self.x - s * self.y, s * self.x + c * self.y) end function vector:perpendicular() return new(-self.y, self.x) end function vector:projectOn(v) assert(isvector(v), "invalid argument: cannot project vector on " .. type(v)) -- (self * v) * v / v:len2() local s = (self.x * v.x + self.y * v.y) / (v.x * v.x + v.y * v.y) return new(s * v.x, s * v.y) end function vector:mirrorOn(v) assert(isvector(v), "invalid argument: cannot mirror vector on " .. type(v)) -- 2 * self:projectOn(v) - self local s = 2 * (self.x * v.x + self.y * v.y) / (v.x * v.x + v.y * v.y) return new(s * v.x - self.x, s * v.y - self.y) end function vector:cross(v) assert(isvector(v), "cross: wrong argument types (<vector> expected)") return self.x * v.y - self.y * v.x end -- ref.: http://blog.signalsondisplay.com/?p=336 function vector:trimInplace(maxLen) local s = maxLen * maxLen / self:len2() s = (s > 1 and 1) or math.sqrt(s) self.x, self.y = self.x * s, self.y * s return self end function vector:angleTo(other) if other then return atan2(self.y, self.x) - atan2(other.y, other.x) end return atan2(self.y, self.x) end function vector:trimmed(maxLen) return self:clone():trimInplace(maxLen) end -- the module return setmetatable({new = new, isvector = isvector, zero = zero}, {__call = function(_, ...) return new(...) end})
mit
deepak78/luci
modules/admin-full/luasrc/model/cbi/admin_system/fstab/swap.lua
84
1922
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" local util = require "nixio.util" local devices = {} util.consume((fs.glob("/dev/sd*")), devices) util.consume((fs.glob("/dev/hd*")), devices) util.consume((fs.glob("/dev/scd*")), devices) util.consume((fs.glob("/dev/mmc*")), devices) local size = {} for i, dev in ipairs(devices) do local s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev:sub(6)))) size[dev] = s and math.floor(s / 2048) end m = Map("fstab", translate("Mount Points - Swap Entry")) m.redirect = luci.dispatcher.build_url("admin/system/fstab") if not arg[1] or m.uci:get("fstab", arg[1]) ~= "swap" then luci.http.redirect(m.redirect) return end mount = m:section(NamedSection, arg[1], "swap", translate("Swap Entry")) mount.anonymous = true mount.addremove = false mount:tab("general", translate("General Settings")) mount:tab("advanced", translate("Advanced Settings")) mount:taboption("general", Flag, "enabled", translate("Enable this swap")).rmempty = false o = mount:taboption("general", Value, "device", translate("Device"), translate("The device file of the memory or partition (<abbr title=\"for example\">e.g.</abbr> <code>/dev/sda1</code>)")) for i, d in ipairs(devices) do o:value(d, size[d] and "%s (%s MB)" % {d, size[d]}) end o = mount:taboption("advanced", Value, "uuid", translate("UUID"), translate("If specified, mount the device by its UUID instead of a fixed device node")) o = mount:taboption("advanced", Value, "label", translate("Label"), translate("If specified, mount the device by the partition label instead of a fixed device node")) return m
apache-2.0
bmscoordinators/FFXI-Server
scripts/zones/Yhoator_Jungle/npcs/qm2.lua
14
1953
----------------------------------- -- Area: Yhoator Jungle -- NPC: ??? Used for Norg quest "Stop Your Whining" -- @pos -94.073 -0.999 22.295 124 ----------------------------------- package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Yhoator_Jungle/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local StopWhining = player:getQuestStatus(OUTLANDS,STOP_YOUR_WHINING); if (StopWhining == QUEST_ACCEPTED and player:hasKeyItem(BARREL_OF_OPOOPO_BREW) == false and player:hasKeyItem(EMPTY_BARREL)) then player:messageSpecial(TREE_CHECK); player:addKeyItem(BARREL_OF_OPOOPO_BREW); --Filled Barrel player:messageSpecial(KEYITEM_OBTAINED,BARREL_OF_OPOOPO_BREW); player:delKeyItem(EMPTY_BARREL); --Empty Barrel elseif (StopWhining == QUEST_ACCEPTED and player:hasKeyItem(BARREL_OF_OPOOPO_BREW) == true) then player:messageSpecial(TREE_FULL); --Already have full barrel else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0001) then player:addKeyItem(SEA_SERPENT_STATUE); player:messageSpecial(KEYITEM_OBTAINED,SEA_SERPENT_STATUE); end end;
gpl-3.0
trigrass2/gopher-lua
_lua5.1-tests/nextvar.lua
20
8553
print('testing tables, next, and for') local a = {} -- make sure table has lots of space in hash part for i=1,100 do a[i.."+"] = true end for i=1,100 do a[i.."+"] = nil end -- fill hash part with numeric indices testing size operator for i=1,100 do a[i] = true assert(#a == i) end if T then -- testing table sizes local l2 = math.log(2) local function log2 (x) return math.log(x)/l2 end local function mp2 (n) -- minimum power of 2 >= n local mp = 2^math.ceil(log2(n)) assert(n == 0 or (mp/2 < n and n <= mp)) return mp end local function fb (n) local r, nn = T.int2fb(n) assert(r < 256) return nn end -- test fb function local a = 1 local lim = 2^30 while a < lim do local n = fb(a) assert(a <= n and n <= a*1.125) a = math.ceil(a*1.3) end local function check (t, na, nh) local a, h = T.querytab(t) if a ~= na or h ~= nh then print(na, nh, a, h) assert(nil) end end -- testing constructor sizes local lim = 40 local s = 'return {' for i=1,lim do s = s..i..',' local s = s for k=0,lim do local t = loadstring(s..'}')() assert(#t == i) check(t, fb(i), mp2(k)) s = string.format('%sa%d=%d,', s, k, k) end end -- tests with unknown number of elements local a = {} for i=1,lim do a[i] = i end -- build auxiliary table for k=0,lim do local a = {unpack(a,1,k)} assert(#a == k) check(a, k, 0) a = {1,2,3,unpack(a,1,k)} check(a, k+3, 0) assert(#a == k + 3) end print'+' -- testing tables dynamically built local lim = 130 local a = {}; a[2] = 1; check(a, 0, 1) a = {}; a[0] = 1; check(a, 0, 1); a[2] = 1; check(a, 0, 2) a = {}; a[0] = 1; a[1] = 1; check(a, 1, 1) a = {} for i = 1,lim do a[i] = 1 assert(#a == i) check(a, mp2(i), 0) end a = {} for i = 1,lim do a['a'..i] = 1 assert(#a == 0) check(a, 0, mp2(i)) end a = {} for i=1,16 do a[i] = i end check(a, 16, 0) for i=1,11 do a[i] = nil end for i=30,40 do a[i] = nil end -- force a rehash (?) check(a, 0, 8) a[10] = 1 for i=30,40 do a[i] = nil end -- force a rehash (?) check(a, 0, 8) for i=1,14 do a[i] = nil end for i=30,50 do a[i] = nil end -- force a rehash (?) check(a, 0, 4) -- reverse filling for i=1,lim do local a = {} for i=i,1,-1 do a[i] = i end -- fill in reverse check(a, mp2(i), 0) end -- size tests for vararg lim = 35 function foo (n, ...) local arg = {...} check(arg, n, 0) assert(select('#', ...) == n) arg[n+1] = true check(arg, mp2(n+1), 0) arg.x = true check(arg, mp2(n+1), 1) end local a = {} for i=1,lim do a[i] = true; foo(i, unpack(a)) end end -- test size operation on empty tables assert(#{} == 0) assert(#{nil} == 0) assert(#{nil, nil} == 0) assert(#{nil, nil, nil} == 0) assert(#{nil, nil, nil, nil} == 0) print'+' local nofind = {} a,b,c = 1,2,3 a,b,c = nil local function find (name) local n,v while 1 do n,v = next(_G, n) if not n then return nofind end assert(v ~= nil) if n == name then return v end end end local function find1 (name) for n,v in pairs(_G) do if n==name then return v end end return nil -- not found end do -- create 10000 new global variables for i=1,10000 do _G[i] = i end end a = {x=90, y=8, z=23} assert(table.foreach(a, function(i,v) if i=='x' then return v end end) == 90) assert(table.foreach(a, function(i,v) if i=='a' then return v end end) == nil) table.foreach({}, error) table.foreachi({x=10, y=20}, error) local a = {n = 1} table.foreachi({n=3}, function (i, v) assert(a.n == i and not v) a.n=a.n+1 end) a = {10,20,30,nil,50} table.foreachi(a, function (i,v) assert(a[i] == v) end) assert(table.foreachi({'a', 'b', 'c'}, function (i,v) if i==2 then return v end end) == 'b') assert(print==find("print") and print == find1("print")) assert(_G["print"]==find("print")) assert(assert==find1("assert")) assert(nofind==find("return")) assert(not find1("return")) _G["ret" .. "urn"] = nil assert(nofind==find("return")) _G["xxx"] = 1 assert(xxx==find("xxx")) print('+') a = {} for i=0,10000 do if math.mod(i,10) ~= 0 then a['x'..i] = i end end n = {n=0} for i,v in pairs(a) do n.n = n.n+1 assert(i and v and a[i] == v) end assert(n.n == 9000) a = nil -- remove those 10000 new global variables for i=1,10000 do _G[i] = nil end do -- clear global table local a = {} local preserve = {io = 1, string = 1, debug = 1, os = 1, coroutine = 1, table = 1, math = 1} for n,v in pairs(_G) do a[n]=v end for n,v in pairs(a) do if not preserve[n] and type(v) ~= "function" and not string.find(n, "^[%u_]") then _G[n] = nil end collectgarbage() end end local function foo () local getfenv, setfenv, assert, next = getfenv, setfenv, assert, next local n = {gl1=3} setfenv(foo, n) assert(getfenv(foo) == getfenv(1)) assert(getfenv(foo) == n) assert(print == nil and gl1 == 3) gl1 = nil gl = 1 assert(n.gl == 1 and next(n, 'gl') == nil) end foo() print'+' local function checknext (a) local b = {} table.foreach(a, function (k,v) b[k] = v end) for k,v in pairs(b) do assert(a[k] == v) end for k,v in pairs(a) do assert(b[k] == v) end b = {} do local k,v = next(a); while k do b[k] = v; k,v = next(a,k) end end for k,v in pairs(b) do assert(a[k] == v) end for k,v in pairs(a) do assert(b[k] == v) end end checknext{1,x=1,y=2,z=3} checknext{1,2,x=1,y=2,z=3} checknext{1,2,3,x=1,y=2,z=3} checknext{1,2,3,4,x=1,y=2,z=3} checknext{1,2,3,4,5,x=1,y=2,z=3} assert(table.getn{} == 0) assert(table.getn{[-1] = 2} == 0) assert(table.getn{1,2,3,nil,nil} == 3) for i=0,40 do local a = {} for j=1,i do a[j]=j end assert(table.getn(a) == i) end assert(table.maxn{} == 0) assert(table.maxn{["1000"] = true} == 0) assert(table.maxn{["1000"] = true, [24.5] = 3} == 24.5) assert(table.maxn{[1000] = true} == 1000) assert(table.maxn{[10] = true, [100*math.pi] = print} == 100*math.pi) -- int overflow a = {} for i=0,50 do a[math.pow(2,i)] = true end assert(a[table.getn(a)]) print("+") -- erasing values local t = {[{1}] = 1, [{2}] = 2, [string.rep("x ", 4)] = 3, [100.3] = 4, [4] = 5} local n = 0 for k, v in pairs( t ) do n = n+1 assert(t[k] == v) t[k] = nil collectgarbage() assert(t[k] == nil) end assert(n == 5) local function test (a) table.insert(a, 10); table.insert(a, 2, 20); table.insert(a, 1, -1); table.insert(a, 40); table.insert(a, table.getn(a)+1, 50) table.insert(a, 2, -2) assert(table.remove(a,1) == -1) assert(table.remove(a,1) == -2) assert(table.remove(a,1) == 10) assert(table.remove(a,1) == 20) assert(table.remove(a,1) == 40) assert(table.remove(a,1) == 50) assert(table.remove(a,1) == nil) end a = {n=0, [-7] = "ban"} test(a) assert(a.n == 0 and a[-7] == "ban") a = {[-7] = "ban"}; test(a) assert(a.n == nil and table.getn(a) == 0 and a[-7] == "ban") table.insert(a, 1, 10); table.insert(a, 1, 20); table.insert(a, 1, -1) assert(table.remove(a) == 10) assert(table.remove(a) == 20) assert(table.remove(a) == -1) a = {'c', 'd'} table.insert(a, 3, 'a') table.insert(a, 'b') assert(table.remove(a, 1) == 'c') assert(table.remove(a, 1) == 'd') assert(table.remove(a, 1) == 'a') assert(table.remove(a, 1) == 'b') assert(table.getn(a) == 0 and a.n == nil) print("+") a = {} for i=1,1000 do a[i] = i; a[i-1] = nil end assert(next(a,nil) == 1000 and next(a,1000) == nil) assert(next({}) == nil) assert(next({}, nil) == nil) for a,b in pairs{} do error"not here" end for i=1,0 do error'not here' end for i=0,1,-1 do error'not here' end a = nil; for i=1,1 do assert(not a); a=1 end; assert(a) a = nil; for i=1,1,-1 do assert(not a); a=1 end; assert(a) a = 0; for i=0, 1, 0.1 do a=a+1 end; assert(a==11) -- precision problems --a = 0; for i=1, 0, -0.01 do a=a+1 end; assert(a==101) a = 0; for i=0, 0.999999999, 0.1 do a=a+1 end; assert(a==10) a = 0; for i=1, 1, 1 do a=a+1 end; assert(a==1) a = 0; for i=1e10, 1e10, -1 do a=a+1 end; assert(a==1) a = 0; for i=1, 0.99999, 1 do a=a+1 end; assert(a==0) a = 0; for i=99999, 1e5, -1 do a=a+1 end; assert(a==0) a = 0; for i=1, 0.99999, -1 do a=a+1 end; assert(a==1) -- conversion a = 0; for i="10","1","-2" do a=a+1 end; assert(a==5) collectgarbage() -- testing generic 'for' local function f (n, p) local t = {}; for i=1,p do t[i] = i*10 end return function (_,n) if n > 0 then n = n-1 return n, unpack(t) end end, nil, n end local x = 0 for n,a,b,c,d in f(5,3) do x = x+1 assert(a == 10 and b == 20 and c == 30 and d == nil) end assert(x == 5) print"OK"
mit
bmscoordinators/FFXI-Server
scripts/zones/Oldton_Movalpolos/npcs/Tarnotik.lua
14
1772
----------------------------------- -- Area: Oldton Movalpolos -- NPC: Tarnotik -- Type: Standard NPC -- @pos 160.896 10.999 -55.659 11 ----------------------------------- package.loaded["scripts/zones/Oldton_Movalpolos/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Oldton_Movalpolos/TextIDs"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getCurrentMission(COP) >= THREE_PATHS) then if (trade:getItemCount() == 1 and trade:hasItemQty(1725,1)) then player:tradeComplete(); player:startEvent(0x0020); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Louverance_s_Path") == 7 ) then player:startEvent(0x0022); else if (math.random()<0.5) then -- this isnt retail at all. player:startEvent(0x001e); else player:startEvent(0x001f); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0020) then player:setPos(-116,-119,-620,253,13); elseif (csid == 0x0022) then player:setVar("COP_Louverance_s_Path",8); end end;
gpl-3.0
jochem-brouwer/VO2_Model
Plotter.lua
1
1789
local gp = require 'lgnuplot' -- Plotter; for a new output file -- You can add more data files to a Plotter instance by passing true as new_dbin to Plotter:SetData local Plotter = {}; function Plotter:New() return setmetatable({gp = gp{}, DBins = {}}, {__index=self});-- __newindex = self.Set}); end local valid = { xlabel = true; ylabel = true; } function Plotter:Set(index, value) self.gp[index]=value; end function Plotter:SetData(dname, data, new_dbin) if not self.DBins then self.DBins = {}; end local using if new_dbin or #self.DBins == 0 then table.insert(self.DBins, {}); using = self.DBins[#self.DBins] else using = self.DBins[#self.DBins] end; if dname == "xdata" then if not using[1] then using[1] = {} end ; using[1][1] = data; elseif dname == "ydata" then if not using[1] then using[1] = {} end ; using[1][2] = data; else using[dname] = data; end end function Plotter:Plot(fname) self.gp.width = self.gp.width or 640; self.gp.height = self.gp.height or 480; self.gp.xlabel = self.gp.xlabel or "X axis"; self.gp.ylabel = self.gp.ylabel or "Y axis"; self.gp.key = self.gp.key or "top left"; self.gp.terminal = self.gp.terminal or "png" -- build data. local d = {} for _, data in pairs(self.DBins or {}) do if not data.using then data.using = {1,2} end -- if not data.with then data.with = "linespoints" end -- if not data.title then data.title = "Title" end print(data) for ind, val in pairs(data) do print(ind, val) if type(val) == "table" then for i,v in pairs(val) do print("\t", i,v) end end end if not data.__gptype then table.insert(d, gp.array(data)); else table.insert(d, gp[data.__gptype](data)); end end self.gp.data = d; self.gp:plot(fname) end return Plotter
mit
bmscoordinators/FFXI-Server
scripts/zones/Nashmau/npcs/Pyopyoroon.lua
28
2129
----------------------------------- -- Area: Nashmau -- NPC: Pyopyoroon -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getCurrentMission(TOAU) == ROYAL_PUPPETEER and player:getVar("AhtUrganStatus") == 1 and trade:hasItemQty(2307,1)) then player:startEvent(279); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(TOAU) == ROYAL_PUPPETEER and player:getVar("AhtUrganStatus") == 0) then player:startEvent(277); elseif (player:getCurrentMission(TOAU) == ROYAL_PUPPETEER and player:getVar("AhtUrganStatus") == 1) then player:startEvent(278); elseif (player:getCurrentMission(TOAU) == LOST_KINGDOM) then player:startEvent(280); else player:startEvent(275); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 277) then player:setVar("AhtUrganStatus",1); elseif (csid == 279 and player:getVar("AhtUrganStatus") == 1) then player:setVar("AhtUrganStatus",0); player:tradeComplete(); player:addKeyItem(VIAL_OF_SPECTRAL_SCENT); player:messageSpecial(KEYITEM_OBTAINED,VIAL_OF_SPECTRAL_SCENT); player:completeMission(TOAU,ROYAL_PUPPETEER); player:addMission(TOAU,LOST_KINGDOM); end end;
gpl-3.0
PraveerSINGH/nn
L1Penalty.lua
16
1128
local L1Penalty, parent = torch.class('nn.L1Penalty','nn.Module') --This module acts as an L1 latent state regularizer, adding the --[gradOutput] to the gradient of the L1 loss. The [input] is copied to --the [output]. function L1Penalty:__init(l1weight, sizeAverage, provideOutput) parent.__init(self) self.l1weight = l1weight self.sizeAverage = sizeAverage or false if provideOutput == nil then self.provideOutput = true else self.provideOutput = provideOutput end end function L1Penalty:updateOutput(input) local m = self.l1weight if self.sizeAverage == true then m = m/input:nElement() end local loss = m*input:norm(1) self.loss = loss self.output = input return self.output end function L1Penalty:updateGradInput(input, gradOutput) local m = self.l1weight if self.sizeAverage == true then m = m/input:nElement() end self.gradInput:resizeAs(input):copy(input):sign():mul(m) if self.provideOutput == true then self.gradInput:add(gradOutput) end return self.gradInput end
bsd-3-clause
deepak78/luci
libs/web/luasrc/http.lua
5
8064
--[[ LuCI - HTTP-Interaction Description: HTTP-Header manipulator and form variable preprocessor FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local ltn12 = require "luci.ltn12" local protocol = require "luci.http.protocol" local util = require "luci.util" local string = require "string" local coroutine = require "coroutine" local table = require "table" local ipairs, pairs, next, type, tostring, error = ipairs, pairs, next, type, tostring, error --- LuCI Web Framework high-level HTTP functions. module "luci.http" context = util.threadlocal() Request = util.class() function Request.__init__(self, env, sourcein, sinkerr) self.input = sourcein self.error = sinkerr -- File handler self.filehandler = function() end -- HTTP-Message table self.message = { env = env, headers = {}, params = protocol.urldecode_params(env.QUERY_STRING or ""), } self.parsed_input = false end function Request.formvalue(self, name, noparse) if not noparse and not self.parsed_input then self:_parse_input() end if name then return self.message.params[name] else return self.message.params end end function Request.formvaluetable(self, prefix) local vals = {} prefix = prefix and prefix .. "." or "." if not self.parsed_input then self:_parse_input() end local void = self.message.params[nil] for k, v in pairs(self.message.params) do if k:find(prefix, 1, true) == 1 then vals[k:sub(#prefix + 1)] = tostring(v) end end return vals end function Request.content(self) if not self.parsed_input then self:_parse_input() end return self.message.content, self.message.content_length end function Request.getcookie(self, name) local c = string.gsub(";" .. (self:getenv("HTTP_COOKIE") or "") .. ";", "%s*;%s*", ";") local p = ";" .. name .. "=(.-);" local i, j, value = c:find(p) return value and urldecode(value) end function Request.getenv(self, name) if name then return self.message.env[name] else return self.message.env end end function Request.setfilehandler(self, callback) self.filehandler = callback end function Request._parse_input(self) protocol.parse_message_body( self.input, self.message, self.filehandler ) self.parsed_input = true end --- Close the HTTP-Connection. function close() if not context.eoh then context.eoh = true coroutine.yield(3) end if not context.closed then context.closed = true coroutine.yield(5) end end --- Return the request content if the request was of unknown type. -- @return HTTP request body -- @return HTTP request body length function content() return context.request:content() end --- Get a certain HTTP input value or a table of all input values. -- @param name Name of the GET or POST variable to fetch -- @param noparse Don't parse POST data before getting the value -- @return HTTP input value or table of all input value function formvalue(name, noparse) return context.request:formvalue(name, noparse) end --- Get a table of all HTTP input values with a certain prefix. -- @param prefix Prefix -- @return Table of all HTTP input values with given prefix function formvaluetable(prefix) return context.request:formvaluetable(prefix) end --- Get the value of a certain HTTP-Cookie. -- @param name Cookie Name -- @return String containing cookie data function getcookie(name) return context.request:getcookie(name) end --- Get the value of a certain HTTP environment variable -- or the environment table itself. -- @param name Environment variable -- @return HTTP environment value or environment table function getenv(name) return context.request:getenv(name) end --- Set a handler function for incoming user file uploads. -- @param callback Handler function function setfilehandler(callback) return context.request:setfilehandler(callback) end --- Send a HTTP-Header. -- @param key Header key -- @param value Header value function header(key, value) if not context.headers then context.headers = {} end context.headers[key:lower()] = value coroutine.yield(2, key, value) end --- Set the mime type of following content data. -- @param mime Mimetype of following content function prepare_content(mime) if not context.headers or not context.headers["content-type"] then if mime == "application/xhtml+xml" then if not getenv("HTTP_ACCEPT") or not getenv("HTTP_ACCEPT"):find("application/xhtml+xml", nil, true) then mime = "text/html; charset=UTF-8" end header("Vary", "Accept") end header("Content-Type", mime) end end --- Get the RAW HTTP input source -- @return HTTP LTN12 source function source() return context.request.input end --- Set the HTTP status code and status message. -- @param code Status code -- @param message Status message function status(code, message) code = code or 200 message = message or "OK" context.status = code coroutine.yield(1, code, message) end --- Send a chunk of content data to the client. -- This function is as a valid LTN12 sink. -- If the content chunk is nil this function will automatically invoke close. -- @param content Content chunk -- @param src_err Error object from source (optional) -- @see close function write(content, src_err) if not content then if src_err then error(src_err) else close() end return true elseif #content == 0 then return true else if not context.eoh then if not context.status then status() end if not context.headers or not context.headers["content-type"] then header("Content-Type", "text/html; charset=utf-8") end if not context.headers["cache-control"] then header("Cache-Control", "no-cache") header("Expires", "0") end context.eoh = true coroutine.yield(3) end coroutine.yield(4, content) return true end end --- Splice data from a filedescriptor to the client. -- @param fp File descriptor -- @param size Bytes to splice (optional) function splice(fd, size) coroutine.yield(6, fd, size) end --- Redirects the client to a new URL and closes the connection. -- @param url Target URL function redirect(url) status(302, "Found") header("Location", url) close() end --- Create a querystring out of a table of key - value pairs. -- @param table Query string source table -- @return Encoded HTTP query string function build_querystring(q) local s = { "?" } for k, v in pairs(q) do if #s > 1 then s[#s+1] = "&" end s[#s+1] = urldecode(k) s[#s+1] = "=" s[#s+1] = urldecode(v) end return table.concat(s, "") end --- Return the URL-decoded equivalent of a string. -- @param str URL-encoded string -- @param no_plus Don't decode + to " " -- @return URL-decoded string -- @see urlencode urldecode = protocol.urldecode --- Return the URL-encoded equivalent of a string. -- @param str Source string -- @return URL-encoded string -- @see urldecode urlencode = protocol.urlencode --- Send the given data as JSON encoded string. -- @param data Data to send function write_json(x) if x == nil then write("null") elseif type(x) == "table" then local k, v if type(next(x)) == "number" then write("[ ") for k, v in ipairs(x) do write_json(v) if next(x, k) then write(", ") end end write(" ]") else write("{ ") for k, v in pairs(x) do write("%q: " % k) write_json(v) if next(x, k) then write(", ") end end write(" }") end elseif type(x) == "number" or type(x) == "boolean" then write(tostring(x)) elseif type(x) == "string" then write("%q" % tostring(x)) end end
apache-2.0
bmscoordinators/FFXI-Server
scripts/zones/Boneyard_Gully/npcs/_081.lua
22
1453
----------------------------------- -- Area: Boneyard_Gully -- NPC: _081 (Dark Miasma) ----------------------------------- package.loaded["scripts/zones/Boneyard_Gully/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Boneyard_Gully/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; else return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/globals/spells/bluemagic/sandspray.lua
26
1404
----------------------------------------- -- Spell: Sandspray -- Blinds enemies within a fan-shaped area originating from the caster -- Spell cost: 43 MP -- Monster Type: Beastmen -- Spell Type: Magical (Dark) -- Blue Magic Points: 2 -- Stat Bonus: VIT+1 -- Level: 66 -- Casting Time: 3 seconds -- Recast Time: 90 seconds -- Magic Bursts on: Compression, Gravitation, and Darkness -- Combos: Clear Mind ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_BLINDNESS; local dINT = caster:getStat(MOD_MND) - target:getStat(MOD_MND); local resist = applyResistanceEffect(caster,spell,target,dINT,BLUE_SKILL,0,typeEffect); local duration = 120 * resist; local power = 25; if (resist > 0.5) then -- Do it! if (target:addStatusEffect(typeEffect,power,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end; return typeEffect; end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Mhaura/npcs/Nereus.lua
29
3092
----------------------------------- -- Area: Mhaura -- NPC: Nereus -- Starts and ends repeteable quest A_POTTER_S_PREFERENCE ----------------------------------- -- player:startEvent(0x006e); standar dialog -- player:startEvent(0x0073); -- i have enough for now, come later -- player:startEvent(0x0072); -- get me x as soon as you can -- player:startEvent(0x006f); -- start quest A Potter's Preference -- player:startEvent(0x0071); -- quest done! -- player:startEvent(0x0070); -- repeat quest ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if ((player:getQuestStatus(OTHER_AREAS,A_POTTER_S_PREFERENCE) == QUEST_ACCEPTED) or (player:getVar("QuestAPotterPrefeRepeat_var")==1)) then local gusgenclay = trade:hasItemQty(569,1); if (gusgenclay == true) then player:startEvent(0x0071); -- quest done! end; end; end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(OTHER_AREAS,A_POTTER_S_PREFERENCE)==QUEST_AVAILABLE and player:getFameLevel(WINDURST)>5) then player:startEvent(0x006f,569); -- start quest A Potter's Preference elseif (player:getQuestStatus(OTHER_AREAS,A_POTTER_S_PREFERENCE)==QUEST_ACCEPTED) then player:startEvent(0x0072,569); -- get me dish_of_gusgen_clay as soon as you can elseif (player:getQuestStatus(OTHER_AREAS,A_POTTER_S_PREFERENCE)==QUEST_COMPLETED) then if (player:getVar("QuestAPotterPrefeCompDay_var")+7<VanadielDayOfTheYear() or player:getVar("QuestAPotterPrefeCompYear_var")<VanadielYear()) then -- seven days after copletition, allow to do the quest again player:startEvent(0x0070); -- repeat quest else player:startEvent(0x0073); -- i have enough for now, come later end; else player:startEvent(0x006e); --standar dialog end; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if ((csid == 0x006f and option == 1)) then --accept quest player:addQuest(OTHER_AREAS,A_POTTER_S_PREFERENCE); elseif (csid == 0x0071) then --quest completed player:tradeComplete(); player:addFame(WINDURST,120); player:addGil(GIL_RATE*2160); player:messageSpecial(GIL_OBTAINED,GIL_RATE*2160); player:setVar("QuestAPotterPrefeRepeat_var",0); player:setVar("QuestAPotterPrefeCompDay_var",VanadielDayOfTheYear()); player:setVar("QuestAPotterPrefeCompYear_var",VanadielYear()); player:completeQuest(OTHER_AREAS,A_POTTER_S_PREFERENCE); elseif (csid == 0x0070) then --repeat quest player:setVar("QuestAPotterPrefeRepeat_var",1); end; end;
gpl-3.0
diamondo25/Vana
scripts/npcs/friend00.lua
2
3241
--[[ Copyright (C) 2008-2016 Vana Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. --]] -- Mr. Goldstein (Buddy List Admin) dofile("scripts/utils/npcHelper.lua"); price = 250000; addText("I hope I can make as much as yesterday ...well, hello! "); addText("Don't you want to extend your buddy list? "); addText("You look like someone who'd have a whole lot of friends... well, what do you think? "); addText("With some money I can make it happen for you. "); addText("Remember, though, it only applies to one character at a time, so it won't affect any of your other characters on your account. "); addText("Do you want to do it?"); answer = askYesNo(); if answer == answer_no then addText("I see... you don't have as many friends as I thought you would. "); addText("Hahaha, just kidding! "); addText("Anyway if you feel like changing your mind, please feel free to come back and we'll talk business. "); addText("If you make a lot of friends, then you know ... hehe ..."); sendNext(); else addText("Alright, good call! "); addText("It's not that expensive actually. "); addText(blue("250,000 mesos and I'll add 5 more slots to your buddy list") .. ". "); addText("And no, I won't be selling them individually. "); addText("Once you buy it, it's going to be permanently on your buddy list. "); addText("So if you're one of those that needs more space there, then you might as well do it. "); addText("What do you think? "); addText("Will you spend 250,000 mesos for it?"); answer = askYesNo(); if answer == answer_no then addText("I see... I don't think you don't have as many friends as I thought you would. "); addText("If not, you just don't have 250,000 mesos with you right this minute? "); addText("Anyway, if you ever change your mind, come back and we'll talk business. "); addText("That is, of course, once you have get some financial relief ... hehe ..."); sendNext(); else if getMesos() < price or getBuddySlots() == 50 then addText("Hey... are you sure you have " .. blue("250,000 mesos") .. "?? "); addText("If so then check and see if you have extended your buddy list to the max. "); addText("Even if you pay up, the most you can have on your buddy list is " .. blue("50") .. "."); sendNext(); else giveMesos(-price); addBuddySlots(5); addText("Alright! "); addText("Your buddy list will have 5 extra slots by now. "); addText("Check and see for it yourself. "); addText("And if you still need more room on your buddy list, you know who to find. "); addText("Of course, it isn't going to be for free ... well, so long ..."); sendOk(); end end end
gpl-2.0
bmscoordinators/FFXI-Server
scripts/zones/Tavnazian_Safehold/npcs/Justinius.lua
14
2018
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Justinius -- Involved in mission : COP2-3 -- @pos 76 -34 68 26 ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == DISTANT_BELIEFS and player:getVar("PromathiaStatus") == 3) then player:startEvent(0x0071); elseif (player:getCurrentMission(COP) == SHELTERING_DOUBT and player:getVar("PromathiaStatus") == 2) then player:startEvent(0x006D); elseif (player:getCurrentMission(COP) == THE_SAVAGE and player:getVar("PromathiaStatus") == 2) then player:startEvent(0x006E); else player:startEvent(0x007B); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0071) then player:setVar("PromathiaStatus",0); player:completeMission(COP,DISTANT_BELIEFS); player:addMission(COP,AN_ETERNAL_MELODY); elseif (csid == 0x006D) then player:setVar("PromathiaStatus",3); elseif (csid == 0x006E) then player:setVar("PromathiaStatus",0); player:completeMission(COP,THE_SAVAGE); player:addMission(COP,THE_SECRETS_OF_WORSHIP); player:addTitle(NAGMOLADAS_UNDERLING); end end;
gpl-3.0
kharkoni18/teleseed
plugins/all.lua
264
4202
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'chat stats! \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) if not data[tostring(target)] then return 'Group is not added.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group \n \n" local settings = show_group_settings(target) text = text.."Group settings \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\n"..modlist local link = get_link(target) text = text.."\n\n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] and msg.to.id ~= our_id then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end return end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
bmscoordinators/FFXI-Server
scripts/zones/Castle_Zvahl_Baileys/npcs/Treasure_Chest.lua
12
3770
----------------------------------- -- Area: Castle Zvahl Baileys -- NPC: Treasure Chest -- @zone 161 ----------------------------------- package.loaded["scripts/zones/Castle_Zvahl_Baileys/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Castle_Zvahl_Baileys/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1038,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1038,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); -- IMPORTANT ITEM: keyitem ----------- if (player:getQuestStatus(BASTOK,A_TEST_OF_TRUE_LOVE) == QUEST_ACCEPTED and player:hasKeyItem(UN_MOMENT) == false) then questItemNeeded = 1; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- 0 or 1 -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then player:setVar("ATestOfTrueLoveProgress",player:getVar("ATestOfTrueLoveProgress")+1); player:addKeyItem(UN_MOMENT); player:messageSpecial(KEYITEM_OBTAINED,UN_MOMENT); -- Un moment for A Test Of True Love quest else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1038); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
aliwvw/Smart_guy
plugin/sticker.lua
3
1898
--[[ _ _ _ _ ___ ___ _ __ _| |__ ___ ___| | ___ __ ___ _ __ (_) __ _ / |/ _ \ / _ \| | __ / _` | '_ \ / _ \/ __| |/ / '__/ _ \| '_ \ | |/ _` | | | | | | | | | |/ / | (_| | |_) | (_) \__ \ <| | | (_) | |_) | | | (_| | | | |_| | |_| | < \__,_|_.__/ \___/|___/_|\_\_| \___/| .__/ |_|\__, |____|_|\___/ \___/|_|\_\ |_| |_|_____| —]] local function tosticker(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'sticker'..msg.from.id..'.webp' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) send_document(get_receiver(msg), file, ok_cb, false) redis:del("photo:sticker") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function run(msg,matches) local receiver = get_receiver(msg) local group = msg.to.id if msg.reply_id then if msg.to.type == 'photo' and redis:get("photo:sticker") then if redis:set("photo:sticker", "waiting") then end end if matches[1] == "ملصق" then redis:get("photo:sticker") load_photo(msg.reply_id, tosticker, msg) end end end return { patterns = { "^(ملصق)$", "%[(photo)%]", }, run = run, } --[[ _ _ _ _ ___ ___ _ __ _| |__ ___ ___| | ___ __ ___ _ __ (_) __ _ / |/ _ \ / _ \| | __ / _` | '_ \ / _ \/ __| |/ / '__/ _ \| '_ \ | |/ _` | | | | | | | | | |/ / | (_| | |_) | (_) \__ \ <| | | (_) | |_) | | | (_| | | | |_| | |_| | < \__,_|_.__/ \___/|___/_|\_\_| \___/| .__/ |_|\__, |____|_|\___/ \___/|_|\_\ |_| |_|_____| —]]
gpl-2.0
bmscoordinators/FFXI-Server
scripts/zones/The_Shrine_of_RuAvitau/mobs/Kirin.lua
19
3656
----------------------------------- -- Area: The Shrine of Ru'Avitau -- MOB: Kirin ----------------------------------- package.loaded[ "scripts/zones/The_Shrine_of_RuAvitau/TextIDs" ] = nil; ----------------------------------- require( "scripts/zones/The_Shrine_of_RuAvitau/TextIDs" ); require( "scripts/globals/titles" ); require( "scripts/globals/ability" ); require( "scripts/globals/pets" ); require( "scripts/globals/status" ); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize( mob ) end ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setMod(MOD_WINDRES, -64); mob:setLocalVar("numAdds", 1); end ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight( mob, target ) if (mob:getHPP() < math.random(50,60) and mob:getLocalVar("astralFlow") == 0) then mob:useMobAbility(734); -- Spawn Avatar mob:spawnPet(); mob:setLocalVar("astralFlow", 1); end local numAdds = mob:getLocalVar("numAdds"); if (mob:getBattleTime() / 180 == numAdds) then -- Ensure we have not spawned all pets yet.. local genbu = mob:getLocalVar("genbu"); local seiryu = mob:getLocalVar("seiryu"); local byakko = mob:getLocalVar("byakko"); local suzaku = mob:getLocalVar("suzaku"); if (genbu == 1 and seiryu == 1 and byakko == 1 and suzaku == 1) then return; end -- Pick a pet to spawn at random.. local ChosenPet = nil; local newVar = nil; repeat local rand = math.random( 0, 3 ); ChosenPet = 17506671 + rand; switch (ChosenPet): caseof { [17506671] = function (x) if ( genbu == 1) then ChosenPet = 0; else newVar = "genbu"; end end, -- Genbu [17506672] = function (x) if (seiryu == 1) then ChosenPet = 0; else newVar = "seiryu"; end end, -- Seiryu [17506673] = function (x) if (byakko == 1) then ChosenPet = 0; else newVar = "byakko"; end end, -- Byakko [17506674] = function (x) if (suzaku == 1) then ChosenPet = 0; else newVar = "suzaku"; end end, -- Suzaku } until (ChosenPet ~= 0 and ChosenPet ~= nil) -- Spawn the pet.. local pet = SpawnMob( ChosenPet ); pet:updateEnmity( target ); pet:setPos( mob:getXPos(), mob:getYPos(), mob:getZPos() ); -- Update Kirins extra vars.. mob:setLocalVar(newVar, 1); mob:setLocalVar("numAdds", numAdds + 1); end -- Ensure all spawned pets are doing stuff.. for pets = 17506671, 17506674 do if (GetMobAction( pets ) == 16) then -- Send pet after current target.. GetMobByID( pets ):updateEnmity( target ); end end end ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) -- Award title and cleanup.. player:addTitle( KIRIN_CAPTIVATOR ); player:showText( mob, KIRIN_OFFSET + 1 ); -- Despawn pets.. DespawnMob( 17506671 ); DespawnMob( 17506672 ); DespawnMob( 17506673 ); DespawnMob( 17506674 ); end ----------------------------------- -- OnMobDespawn ----------------------------------- function onMobDespawn( mob ) -- Despawn pets.. DespawnMob( 17506671 ); DespawnMob( 17506672 ); DespawnMob( 17506673 ); DespawnMob( 17506674 ); GetNPCByID( 17506693 ):updateNPCHideTime(FORCE_SPAWN_QM_RESET_TIME); end
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Kazham/npcs/Mumupp.lua
15
4341
----------------------------------- -- Area: Kazham -- NPC: Mumupp -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); require("scripts/globals/pathfind"); local path = { 94.732452, -15.000000, -114.034622, 94.210846, -15.000000, -114.989388, 93.508865, -15.000000, -116.274101, 94.584877, -15.000000, -116.522118, 95.646988, -15.000000, -116.468452, 94.613518, -15.000000, -116.616562, 93.791100, -15.000000, -115.858505, 94.841835, -15.000000, -116.108437, 93.823380, -15.000000, -116.712860, 94.986847, -15.000000, -116.571831, 94.165512, -15.000000, -115.965698, 95.005806, -15.000000, -116.519707, 93.935555, -15.000000, -116.706291, 94.943497, -15.000000, -116.578346, 93.996826, -15.000000, -115.932816, 95.060165, -15.000000, -116.180840, 94.081062, -15.000000, -115.923836, 95.246490, -15.000000, -116.215691, 94.234077, -15.000000, -115.960793 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- -- item IDs -- 483 Broken Mithran Fishing Rod -- 22 Workbench -- 1008 Ten of Coins -- 1157 Sands of Silence -- 1158 Wandering Bulb -- 904 Giant Fish Bones -- 4599 Blackened Toad -- 905 Wyvern Skull -- 1147 Ancient Salt -- 4600 Lucky Egg function onTrade(player,npc,trade) local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, THE_OPO_OPO_AND_I); local progress = player:getVar("OPO_OPO_PROGRESS"); local failed = player:getVar("OPO_OPO_FAILED"); local goodtrade = trade:hasItemQty(1008,1); local badtrade = (trade:hasItemQty(483,1) or trade:hasItemQty(22,1) or trade:hasItemQty(1157,1) or trade:hasItemQty(1158,1) or trade:hasItemQty(904,1) or trade:hasItemQty(4599,1) or trade:hasItemQty(905,1) or trade:hasItemQty(1147,1) or trade:hasItemQty(4600,1)); if (OpoOpoAndIStatus == QUEST_ACCEPTED) then if progress == 2 or failed == 3 then if goodtrade then player:startEvent(0x00DD); elseif badtrade then player:startEvent(0x00E7); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, THE_OPO_OPO_AND_I); local progress = player:getVar("OPO_OPO_PROGRESS"); local failed = player:getVar("OPO_OPO_FAILED"); local retry = player:getVar("OPO_OPO_RETRY"); if (OpoOpoAndIStatus == QUEST_ACCEPTED) then if retry >= 1 then -- has failed on future npc so disregard previous successful trade player:startEvent(0x00C7); npc:wait(-1); elseif (progress == 2 or failed == 3) then player:startEvent(0x00D1); -- asking for ten of coins elseif (progress >= 3 or failed >= 4) then player:startEvent(0x00F4); -- happy with ten of coins end else player:startEvent(0x00C7); npc:wait(-1); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00DD) then -- correct trade, onto next opo if player:getVar("OPO_OPO_PROGRESS") == 2 then player:tradeComplete(); player:setVar("OPO_OPO_PROGRESS",3); player:setVar("OPO_OPO_FAILED",0); else player:setVar("OPO_OPO_FAILED",4); end elseif (csid == 0x00E7) then -- wrong trade, restart at first opo player:setVar("OPO_OPO_FAILED",1); player:setVar("OPO_OPO_RETRY",3); else npc:wait(0); end end;
gpl-3.0
ncoop/vgr
lua/Battlemaster.lua
1
22076
print("Experimental Lua script for Battle Master (Genesis)") print("Written by Dammit, last updated 1/13/2011") print("http://www.gamefaqs.com/genesis/586050-battle-master/faqs/29225") print() print("Lua hotkey 1: toggle memviewer") print("Lua hotkey 2: cycle memviewer profiles") print("Lua hotkey 3: cycle parley/travel/default") print("Lua hotkey 4: report stage enemies & items") print() local mode = { skip_lag = true, autofire = 10, parley_travel = false, no_hostility = true, full_hp = false, infinite_GP = false, --stage_select = 32, skip_crown = false, draw_HUD = true, draw_memviewer = false, debug_damage = false, jewel_read = false, } -------------------------------------------------------------------------------- local active, current_stage, current_enemies, melee_id, missile_id, items_base local address = { xcam = 0xff0216, ycam = 0xff0218, items_base = 0xff9e7a, input_masked = 0xffba13, input = 0xffba14, items_ptr = 0xffba24, race_class = 0xffba48, fight_mode = 0xffba4f, max_hp = 0xffba51, enemies = 0xffba62, quota = 0xffba64, damage_mod = 0xffba7c, curr_stage = 0xffba83, dest_stage = 0xffba84, crown_pieces = 0xffba9e, active = 0xffbaac, password = 0xffc5f4, inventory = 0xffc65e, groups2 = 0xffcc5a, groups = 0xffcfa4, char_base = 0xffd764, attk_base = 0xffe200, race_table = 0x01184C, melee_table = 0x013746, missile_table= 0x0136aa, } local char_offset = { x_pos = 0x00, --word y_pos = 0x02, --word group = 0x0a, --word race = 0x0c, layer = 0x0d, hp = 0x0e, morale = 0x0f, wounded = 0x11, --bitwise missile = 0x13, facing = 0x16, number = 0x18, space = 0x1c, } local attk_offset = { x_pos = 0x0, --word y_pos = 0x2, --word weap_id = 0x4, --word attacker= 0x6, --word, offset from char_base facing = 0x8, status = 0x9, --bitwise layer = 0xa, missile = 0xb, skill = 0xc, damage = 0xd, space = 0xe, } local group_offset = { group_no = 0x00, --word leader_area = 0x04, --word GP = 0x06, --word leader_x1 = 0x08, --word leader_y1 = 0x0a, --word leader_x2 = 0x0c, --word leader_y2 = 0x0e, --word leader_x3 = 0x10, --word leader_y3 = 0x12, --word weapon = 0x2c, --word missile = 0x2e, --word armor = 0x30, --word race = 0x33, eq_morale = 0x34, skill = 0x35, members = 0x36, formation = 0x37, hostility = 0x38, --bitwise, bit 0 leader_face = 0x39, melee = 0x3d, space = 0x40, } local group2_offset = { max_hp = 0x10, space = 0x16, } local item_offset = { type = 0x0, --word x_pos = 0x2, --word y_pos = 0x4, --word cost = 0x6, --word name = 0x8, --word number = 0xa, layer = 0xb, plus = 0xc, hidden = 0xd, --bitwise, bit 7 space = 0xe, } local nchars = 0x60 -------------------------------------------------------------------------------- local HUD_transparency = 0xc0 HUD_transparency = AND(0xff, HUD_transparency) local function damage_mod(group, weapon_id, rom_table) local mod = memory.readword(address.groups + group + group_offset.armor) mod = memory.readword(items_base + mod + 0x2) mod = (AND(mod, 0x0fff) + weapon_id) * 2 mod = memory.readwordsigned(rom_table + mod) return mod end local function HUD(go) if not active or not go then return end local quota = AND(0xff, memory.readword(address.quota)) gui.text(0x0f8, 0xd2, "enemies: " .. current_enemies .. " (" .. quota .. ")", 0xff0000ff) gui.text(0x102, 0xda, "stage #" .. current_stage, 0x00ffffff) local cam = { x = memory.readword(address.xcam), y = memory.readword(address.ycam), layer = memory.readbyte(address.char_base + char_offset.layer), } for n = 0, nchars-1 do --characters local char_base = address.char_base + char_offset.space * n local x = memory.readword(char_base + char_offset.x_pos) - cam.x local y = memory.readword(char_base + char_offset.y_pos) - cam.y local same_layer = memory.readbyte(char_base + char_offset.layer) == cam.layer local group = memory.readwordsigned(char_base + char_offset.group) local race = memory.readbyte(char_base + char_offset.race) local hp = memory.readbyte(char_base + char_offset.hp) local morale = memory.readbyte(char_base + char_offset.morale) local skill = memory.readbyte(address.groups + group + group_offset.skill) local armor = memory.readwordsigned(address.groups + group + group_offset.armor) armor = AND(0xf, memory.readword(address.items_base + armor)) local weapon = memory.readwordsigned(address.groups + group + group_offset.weapon) weapon = AND(0xf, memory.readword(address.items_base + weapon)) local missile = memory.readwordsigned(address.groups + group + group_offset.missile) missile = missile < 0 and "-" or AND(0xf, memory.readword(address.items_base + missile)) local color = char_base == address.char_base and 0x00ff0000 + HUD_transparency --player char or group == 0 and 0xffff0000 + HUD_transparency --troops or 0xff00ff00 + HUD_transparency --enemies if x > -0x08 and x < 0xb8 and y > 0 and y < 0xd0 and same_layer and group >= 0 then gui.text(x+0x0a, y-0x12, string.format("%d(%d)",hp,skill), color) --gui.text(x+0x0a, y-0x12, string.format("%d(%03x)",hp,group), color) --gui.text(x+0x0a, y-0x12, string.format("%04X,%02x,%d", AND(0xffff, char_base), group, race), color) if group > 0 then local melee_mod = damage_mod(group, melee_id, address.melee_table) local missile_mod = damage_mod(group, missile_id, address.missile_table) gui.text(x+0x0a, y-0x08, string.format("%d/%d [%s%s%s]",melee_mod,missile_mod,armor,weapon,missile), 0xff000000 + HUD_transparency) end end end for n = 0, nchars-1 do --attacks local attk_base = address.attk_base + attk_offset.space * n local x = memory.readwordsigned(attk_base + attk_offset.x_pos) - cam.x local y = memory.readwordsigned(attk_base + attk_offset.y_pos) - cam.y local same_layer = memory.readbyte(attk_base + attk_offset.layer) == cam.layer local damage = memory.readbytesigned(attk_base + attk_offset.damage) if x > 0 and x < 0xc0 and y > 0 and y < 0xd0 and same_layer then gui.text(x + 0xc, y, damage, 0xff000000 + HUD_transparency) end end end -------------------------------------------------------------------------------- memprofile = { {address.attk_base, attk_offset.space, "attacks"}, {address.items_base, item_offset.space, "stage items/triggers"}, {address.inventory, item_offset.space, "inventory"}, {address.char_base, char_offset.space/2, "chars"}, {address.groups, group_offset.space/4, "group properties 1"}, {address.groups2, group2_offset.space, "group properties 2"}, --{address.melee_table, 0x10, "melee damage mod table"}, --{address.missile_table, 0x10, "missile damage mod table"}, --{address.race_table, 0x10, "racial properties"}, --{address.password, 0xd, "password"}, } local memarray, start_addr, rowsize, class local rows = 10 local memprofileindex = 1 local function setmemprofile(go) if not go then return end local n = memprofileindex memprofileindex = n < #memprofile and n + 1 or 1 start_addr, rowsize, class = memprofile[n][1], memprofile[n][2], memprofile[n][3] memarray = {} for a = start_addr, start_addr + rowsize*rows - 1 do table.insert(memarray, { x = 0x10 + (a-start_addr)%rowsize * 0x10, y = 0x10 + math.floor((a-start_addr)/rowsize) * 0x10, addr = a, }) end end setmemprofile(true) input.registerhotkey(1, function() mode.draw_memviewer = not mode.draw_memviewer end) input.registerhotkey(2, function() setmemprofile(mode.draw_memviewer) end) local function memviewer(draw) if not draw then return end gui.text(0, 0, string.format("%06x", start_addr) .. ": " .. class, 0x00ff00ff) for n = 0, rowsize-1 do gui.text(0x10 + n*0x10, 0x8, string.format("%02X", n), 0xffff00ff) end for n = 0, rows-1 do gui.text(0x0, 0x10 + n*0x10, string.format("%02X", n*rowsize), 0xffff00ff) end for _,v in ipairs(memarray) do --gui.text(v.x, v.y, string.format("%3d", memory.readbyte(v.addr))) gui.text(v.x, v.y, string.format("%02x", memory.readbyte(v.addr))) end end -------------------------------------------------------------------------------- local race_list = { [ 0] = {"Human"}, [ 1] = {"Elf"}, [ 2] = {"Dwarf"}, [ 3] = {"Orc"}, [ 4] = {"Scorpion"}, [ 5] = {"Spider"}, [ 6] = {"Dragonfly"}, [ 7] = {"Chomper"}, [ 8] = {"Snake"}, [ 9] = {"Ghost"}, [10] = {"Bat"}, [11] = {"Fireball"}, [12] = {"Giant eye"}, [13] = {"Will-o-wisp"}, [14] = {"Chomper"}, [15] = {"Fireball"}, [20] = {"Ogre"}, [21] = {"Troll"}, [22] = {"Armored giant"}, [23] = {"Dragon"}, [24] = {"Ogre"}, [26] = {"Giant beetle"}, [27] = {"Giant spider"}, [29] = {"Dragonfly"}, } for k,v in pairs(race_list) do if v[1]:sub(-1) == "f" then v[2] = v[1]:sub(1,-2) .. "ves" elseif v[1]:sub(-1) == "y" then v[2] = v[1]:sub(1,-2) .. "ies" else v[2] = v[1] .. "s" end v[1] = v[1]:lower() .. string.rep(" ", 14-string.len(v[1])) v[2] = v[2]:lower() .. string.rep(" ", 14-string.len(v[2])) end local formation_list = { [0] = "column", [1] = "wedge ", [2] = "line ", [3] = "single", [4] = "open ", [5] = "huddle", } local table_end = "+" .. string.rep("-", 26) .. "+" .. string.rep("-", 16) .. "+" .. string.rep("-", 33) .. "+" input.registerhotkey(4, function() print() print("stage " .. (current_stage or memory.readbyte(address.curr_stage))) local total = 0 print(table_end) for n = 1, 0x1e do --required for every group local offset = n*group_offset.space local addr = address.groups + offset local group_no = memory.readwordsigned(addr + group_offset.group_no) local race = memory.readbytesigned(addr + group_offset.race) if race >= 0 and group_no >= 0 then local group_size = memory.readbyte(addr + group_offset.members) race = race_list[race] and (group_size > 1 and race_list[race][2] or race_list[race][1]) or "race #" .. race .. "\t" total = total + group_size local formation = AND(0xf, memory.readbyte(addr + group_offset.formation)) formation = formation_list[formation] local max_hp = memory.readbyte(address.groups2 + (group_no-1)*group2_offset.space + group2_offset.max_hp) local skill = memory.readbyte(addr + group_offset.skill) local item_base = address.items_base + memory.readword(addr + group_offset.armor) local item_type = AND(0xf, memory.readword(item_base)) local item_plus = memory.readbyte(item_base + item_offset.plus) local armor = "[A" .. item_type .. "]" .. (item_plus > 9 and "" or " ") .. "(+" .. item_plus .. ")" item_base = address.items_base + memory.readword(addr + group_offset.weapon) item_type = AND(0xf, memory.readword(item_base)) item_plus = memory.readbyte(item_base + item_offset.plus) local weapon = "[W" .. item_type .. "]" .. (item_plus > 9 and "" or " ") .. "(+" .. item_plus .. ")" local missile = " " item_base = memory.readwordsigned(addr + group_offset.missile) if item_base > 0 then item_base = address.items_base + item_base item_type = AND(0xf, memory.readword(item_base)) item_plus = memory.readbyte(item_base + item_offset.plus) missile = "[M" .. item_type .. "]" .. (item_plus > 9 and "" or " ") .. "(+" .. item_plus .. ")" end --print(string.format("#%02d\t0x%03x",group_no,offset)) print(string.format("| %2d %s %s | %3d hp %3d sk | %s %s %s |", group_size,race,formation,max_hp,skill,armor,weapon,missile)) end end print(table_end) print(total .. " enemies") total = 0 local n_items = memory.readbyte(memory.readdword(address.items_ptr) + 1) for n = 0, n_items-1 do local offset = n*item_offset.space local addr = address.items_base + offset local item_type = memory.readword(addr) local hidden = memory.readbyte(addr + item_offset.hidden) local cost = memory.readwordsigned(addr + item_offset.cost) local name = memory.readwordsigned(addr + item_offset.name) local x_pos = memory.readwordsigned(addr + item_offset.x_pos) local y_pos = memory.readwordsigned(addr + item_offset.y_pos) local layer = memory.readbyte(addr + item_offset.layer) if item_type < 0x1000 then local icon if item_type < 25 then icon = "coins" elseif item_type < 50 then icon = "pouch" elseif item_type < 100 then icon = "sack" else icon = "chest" end print(string.format("#%02d $%04x\t%d GP %s\t($%04x,$%04x,$%02x)\t$%02x",n,offset,item_type,icon,x_pos,y_pos,layer,hidden)) total = total + item_type elseif AND(item_type, 0xf000) ~= 0x4000 and AND(item_type, 0xf000) ~= 0x5000 and AND(item_type, 0xf000) ~= 0x7000 and AND(item_type, 0xf000) ~= 0x9000 then if AND(hidden, 0xf0) == 0x80 then print(string.format("#%02d $%04x\thidden item: $%04x ($%04x,$%04x,$%02x) $%02x",n,offset,item_type,x_pos,y_pos,layer,hidden)) --memory.writebyte(addr + 0xd, hidden - 0x40) end if cost <= 0 and name > 0 then print(string.format("#%02d $%04x\tunbuyable: $%04x ($%04x,$%04x,$%02x) $%02x",n,offset,item_type,x_pos,y_pos,layer,hidden)) memory.writeword(addr + item_offset.cost, 1) end end end print("total " .. total .. " GP, " .. n_items .. " items/triggers") end) -------------------------------------------------------------------------------- if mode.debug_damage then local dmg = {} memory.registerexec(0x5f7c, function() --defender's armor type was just loaded dmg.attk_base = AND(0xffffff, memory.getregister("a0")) dmg.attacker = AND(0xffffff, memory.getregister("a2")) dmg.a_group = memory.readword(dmg.attacker + char_offset.group) dmg.weapon = memory.readword(dmg.attk_base + attk_offset.weap_id) dmg.a_plus = memory.readbyte(dmg.attk_base + attk_offset.damage) dmg.a_skill = memory.readbyte(dmg.attk_base + attk_offset.skill) dmg.a_race = memory.readbyte(address.groups + dmg.a_group + group_offset.race) dmg.a_lead = memory.readbyte(address.groups + dmg.a_group + group_offset.formation) --if a_group ~= 0 then return end dmg.armor_base = AND(0xffffff, memory.getregister("a3")) dmg.defender = AND(0xffffff, memory.getregister("a6")) dmg.d_group = memory.readword(dmg.defender + char_offset.group) dmg.armor = memory.readword(dmg.armor_base) dmg.d_plus = memory.readbyte(dmg.armor_base + item_offset.plus) dmg.d_skill = memory.readbyte(address.groups + dmg.d_group + group_offset.skill) dmg.d_race = memory.readbyte(address.groups + dmg.d_group + group_offset.race) dmg.d_lead = memory.readbyte(address.groups + dmg.d_group + group_offset.formation) end) memory.registerexec(0x608a, function() --damage is about to be deducted if not dmg.attk_base then return end dmg.wounded = memory.readbyte(dmg.defender + char_offset.wounded) print() --print(string.format("armor_base: $%x\twounded: %02x", dmg.armor_base,dmg.wounded)) print(string.format("attacker:\t$%x\t($%03x)\tlead: %02x\tskill: %d\tweapon:\t$%x %+d", dmg.attacker,dmg.a_group,dmg.a_lead,dmg.a_skill,dmg.weapon,dmg.a_plus)) print(string.format("defendr:\t$%x\t($%03x)\tlead: %02x\tskill: %d\tarmor:\t$%x %+d", dmg.defender,dmg.d_group,dmg.d_lead,dmg.d_skill,dmg.armor,dmg.d_plus)) dmg.modifier = memory.readwordsigned(address.damage_mod) dmg.final = AND(0xffff, memory.getregister("d7")) print(string.format("atkbase:\t$%x\tdmg: (%d%+d)*x + 1 = %d --> %d", dmg.attk_base,dmg.a_plus,dmg.modifier,dmg.a_plus+dmg.modifier+1,dmg.final)) dmg = {} end) --[[ local attacker_formation,defender_formation,attacker_base,defender_base memory.registerexec(0x5ff2, function() --about to compare formations attacker_base = memory.getregister("a1") defender_base = memory.getregister("a5") attacker_formation = memory.readbyte(attacker_base + group_offset.formation) defender_formation = memory.readbyte(defender_base + group_offset.formation) local attacker_upper = AND(0xf0, attacker_formation) local defender_upper = AND(0xf0, defender_formation) end) memory.registerexec(0x6010, function() --about to load formation modifier local modifier = memory.readword(0x013822 + memory.getregister("d6")) print(string.format("attacker formation: %02x\tdefender formation: %02x\tmodifier: %d",attacker_formation,defender_formation,modifier)) end)]] end -------------------------------------------------------------------------------- --jewel_read requires rings/jewels to be added to inventory in this order if mode.jewel_read then local jewel_read = { "R0 shield ring", "R1 normellon", "R2 sulandir", "R3 lit ring", "R4 nendil", "R5 gondrim", "J0 ruby star", "J1 diamond star", "J2 holy necklace", "J3 faith", "J4 emerald star", "J5 mal's gem", "J6 magicbane", "R6", "R7", "R8", "J7", } for k,v in ipairs(jewel_read) do memory.registerread(0xffc688 + 0xe*(k-1) + 0xc, function() if active then print(v) end end) end end --[[memory.registerexec(0x77DE, function() --force successful password check? local targetval = memory.readbyte(memory.getregister("a0")) memory.setregister("d1", targetval) end) local pc = 0x76c2 memory.registerexec(pc, function() --password check local d4 = memory.getregister("d4") print(string.format("pc $%04X\td4 $%08X",pc,d4)) end)]] --[[local addr = 0xFFBA44 --rng memory.register(addr,4,function(addr, size) if memory.readdword(addr) ~= 0x1f then memory.writedword(addr, 0x1f) end end)]] -------------------------------------------------------------------------------- local function autofire(period) if type(period) ~= "number" or period < 1 or not active or gens.framecount()%period*2 < period then return end if joypad.get()["A"] then joypad.set({A = false}) end if joypad.get()["B"] then joypad.set({B = false}) end end input.registerhotkey(3, function() if not mode.parley_travel then mode.parley_travel = 1 gens.message("fight mode: forced parley") elseif mode.parley_travel == 1 then mode.parley_travel = 2 gens.message("fight mode: forced travel") else mode.parley_travel = false gens.message("fight mode: normal") end end) local function parley_travel(val) if not val then return end memory.writebyte(address.fight_mode, val) end if mode.no_hostility then print("no hostility: on") for n = 0, 0x1e do --required for every group local addr = address.groups + group_offset.hostility + n*0x40 memory.register(addr, 1, function(addr, size) local val = memory.readbyte(addr) if AND(val,0x01) == 1 then memory.writebyte(addr, AND(val,0xfe)) end end) end end local function full_hp(go) if not go then return end local full = memory.readbyte(address.max_hp) for n = 0, nchars-1 do local char_base = address.char_base + char_offset.space * n if memory.readwordsigned(char_base + char_offset.group) == 0 then memory.writebyte(char_base + char_offset.hp, full) end end end if mode.infinite_GP then print("infinite gp: on") end local function infinite_GP(go) if not go then return end memory.writeword(address.groups + group_offset.GP, 20000) end local stages = { {crown = 0x0, 1,2,3,4,5,6,7,8,9,10,11,12,13}, {crown = 0x0, 14,15,24,26,27,30}, {crown = 0x0, 16,17,18,19,20,21,22,23}, {crown = 0x0, 25,29,32,37,41,35}, {crown = 0x0, 33,28,31,34,38,44,39}, {crown = 0x3, 42,36,40,43,46}, {crown = 0xf, 45,47,48,49,50,51}, } if mode.stage_select then print("stage select: " .. (type(mode.stage_select) == "number" and mode.stage_select or "progressive")) end local function stage_select(stage) if not stage then return elseif type(stage) == "number" then --memory.writebyte(address.curr_stage, stage) memory.writebyte(address.dest_stage, stage) else mode.skip_crown = true memory.writebyte(address.dest_stage, current_stage + 1) end end local function skip_crown(go) if not go then return end local dest = memory.readbyte(address.dest_stage) for chapter,set in ipairs(stages) do for _,stage in ipairs(set) do if dest == stage then memory.writebyte(address.crown_pieces, set.crown) return end end end end -------------------------------------------------------------------------------- gui.register(function() HUD(mode.draw_HUD) memviewer(mode.draw_memviewer) end) local last_enemies,just_loaded_state = 100,true savestate.registerload(function() just_loaded_state = true end) gens.registerbefore(function() active = memory.readbyte(address.active) == 0xff melee_id = memory.readbyte(address.inventory + attk_offset.space*1 + 1) * 11 missile_id = memory.readbyte(address.inventory + attk_offset.space*2 + 1) * 11 items_base = memory.readdword(address.items_ptr) current_stage = memory.readbyte(address.curr_stage) current_enemies = memory.readword(address.enemies) if active and not just_loaded_state and current_enemies > last_enemies then print("stage " .. current_stage .. ": enemy count increased by " .. current_enemies - last_enemies) end last_enemies,just_loaded_state = current_enemies,false autofire(mode.autofire) full_hp(mode.full_hp) infinite_GP(mode.infinite_GP) parley_travel(mode.parley_travel) skip_crown(mode.skip_crown) stage_select(mode.stage_select) end) if mode.skip_lag then print("skip lag: on") while true do gens.frameadvance() if gens.lagged() then gens.emulateframeinvisible() end end end
apache-2.0
AmirMohammadLocker/BOT
bot/bot.lua
1
11423
-- #Beyond Reborn Robot -- #@BeyondTeam tdcli = dofile('./tg/tdcli.lua') serpent = (loadfile "./libs/serpent.lua")() feedparser = (loadfile "./libs/feedparser.lua")() require('./bot/utils') require('./libs/lua-redis') URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() local lgi = require ('lgi') local notify = lgi.require('Notify') notify.init ("Telegram updates") chats = {} plugins = {} helper_username = 'BOTFieryBoT' -- Input Helper Username Here Without @ function do_notify (user, msg) local n = notify.Notification.new(user, msg) n:show () end function dl_cb (arg, data) -- vardump(data) end function vardump(value) print(serpent.block(value, {comment=false})) end function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end function whoami() local usr = io.popen("whoami"):read('*a') usr = string.gsub(usr, '^%s+', '') usr = string.gsub(usr, '%s+$', '') usr = string.gsub(usr, '[\n\r]+', ' ') if usr:match("^root$") then tcpath = '/root/.telegram-cli' elseif not usr:match("^root$") then tcpath = '/home/'..usr..'/.telegram-cli' end print('>> Download Path = '..tcpath) end function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end function create_config( ) io.write('\n\27[1;33m>> Input your Telegram ID for set Sudo : \27[0;39;49m') local sudo_id = tonumber(io.read()) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "banhammer", "groupmanager", "msg-checks", "plugins", "tools", "fun", }, sudo_users = {446738577, 374734484, sudo_id}, admins = {}, disabled_channels = {}, moderation = {data = './data/moderation.json'}, info_text = [[ Ad̈m̈ïn̈s̈: @SudoLocker Cḧän̈n̈ël̈: @LockerTeam ]], } serialize_to_file(config, './data/config.lua') print ('saved config into config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: ./data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("SUDO USER: " .. user) end return config end whoami() _config = load_config() function load_plugins() local config = loadfile ("./data/config.lua")() for k, v in pairs(config.enabled_plugins) do print("Loaded Plugin ", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugins '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end print('\n'..#config.enabled_plugins..' Plugins Are Active\n\nStarting BDReborn Robot...\n') end load_plugins() function msg_valid(msg) if tonumber(msg.date_) < (tonumber(os.time()) - 60) then print('\27[36m>>-- OLD MESSAGE --<<\27[39m') return false end if is_silent_user(msg.sender_user_id_, msg.chat_id_) then del_msg(msg.chat_id_, msg.id_) return false end if is_banned(msg.sender_user_id_, msg.chat_id_) then del_msg(msg.chat_id_, tonumber(msg.id_)) kick_user(msg.sender_user_id_, msg.chat_id_) return false end if is_gbanned(msg.sender_user_id_) then del_msg(msg.chat_id_, tonumber(msg.id_)) kick_user(msg.sender_user_id_, msg.chat_id_) return false end return true end 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 end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = '_Plugin_ *'..check_markdown(disabled_plugin)..'* _is disabled on this chat_' print(warning) tdcli.sendMessage(receiver, "", 0, warning, 0, "md") return true end end end return false end function match_plugin(plugin, plugin_name, msg) if plugin.pre_process then --If plugin is for privileged users only local result = plugin.pre_process(msg) if result then print("pre process: ", plugin_name) -- tdcli.sendMessage(msg.chat_id_, "", 0, result, 0, "md") end end for k, pattern in pairs(plugin.patterns) do matches = match_pattern(pattern, msg.content_.text_ or msg.content_.caption_) if matches then if is_plugin_disabled_on_chat(plugin_name, msg.chat_id_) then return nil end print("Message matches: ", pattern..' | Plugin: '..plugin_name) if plugin.run then if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then tdcli.sendMessage(msg.chat_id_, msg.id_, 0, result, 0, "md") end end end return end end end function file_cb(msg) if msg.content_.ID == "MessagePhoto" then photo_id = '' local function get_cb(arg, data) if data.content_.photo_.sizes_[2] then photo_id = data.content_.photo_.sizes_[2].photo_.id_ else photo_id = data.content_.photo_.sizes_[1].photo_.id_ end tdcli.downloadFile(photo_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageVideo" then video_id = '' local function get_cb(arg, data) video_id = data.content_.video_.video_.id_ tdcli.downloadFile(video_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageAnimation" then anim_id, anim_name = '', '' local function get_cb(arg, data) anim_id = data.content_.animation_.animation_.id_ anim_name = data.content_.animation_.file_name_ tdcli.downloadFile(anim_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageVoice" then voice_id = '' local function get_cb(arg, data) voice_id = data.content_.voice_.voice_.id_ tdcli.downloadFile(voice_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageAudio" then audio_id, audio_name, audio_title = '', '', '' local function get_cb(arg, data) audio_id = data.content_.audio_.audio_.id_ audio_name = data.content_.audio_.file_name_ audio_title = data.content_.audio_.title_ tdcli.downloadFile(audio_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageSticker" then sticker_id = '' local function get_cb(arg, data) sticker_id = data.content_.sticker_.sticker_.id_ tdcli.downloadFile(sticker_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) elseif msg.content_.ID == "MessageDocument" then document_id, document_name = '', '' local function get_cb(arg, data) document_id = data.content_.document_.document_.id_ document_name = data.content_.document_.file_name_ tdcli.downloadFile(document_id, dl_cb, nil) end tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.id_ }, get_cb, nil) end end function tdcli_update_callback (data) if data.message_ then if msg_caption ~= get_text_msg() then msg_caption = get_text_msg() end end if (data.ID == "UpdateNewMessage") then local msg = data.message_ local d = data.disable_notification_ local chat = chats[msg.chat_id_] local hash = 'msgs:'..msg.sender_user_id_..':'..msg.chat_id_ redis:incr(hash) if redis:get('markread') == 'on' then tdcli.viewMessages(msg.chat_id_, {[0] = msg.id_}, dl_cb, nil) end if ((not d) and chat) then if msg.content_.ID == "MessageText" then do_notify (chat.title_, msg.content_.text_) else do_notify (chat.title_, msg.content_.ID) end end if msg_valid(msg) then var_cb(msg, msg) file_cb(msg) if msg.content_.ID == "MessageText" then msg.text = msg.content_.text_ msg.edited = false msg.pinned = false elseif msg.content_.ID == "MessagePinMessage" then msg.pinned = true elseif msg.content_.ID == "MessagePhoto" then msg.photo_ = true elseif msg.content_.ID == "MessageVideo" then msg.video_ = true elseif msg.content_.ID == "MessageAnimation" then msg.animation_ = true elseif msg.content_.ID == "MessageVoice" then msg.voice_ = true elseif msg.content_.ID == "MessageAudio" then msg.audio_ = true elseif msg.content_.ID == "MessageForwardedFromUser" then msg.forward_info_ = true elseif msg.content_.ID == "MessageSticker" then msg.sticker_ = true elseif msg.content_.ID == "MessageContact" then msg.contact_ = true elseif msg.content_.ID == "MessageDocument" then msg.document_ = true elseif msg.content_.ID == "MessageLocation" then msg.location_ = true elseif msg.content_.ID == "MessageGame" then msg.game_ = true elseif msg.content_.ID == "MessageChatAddMembers" then for i=0,#msg.content_.members_ do msg.adduser = msg.content_.members_[i].id_ end elseif msg.content_.ID == "MessageChatJoinByLink" then msg.joinuser = msg.sender_user_id_ elseif msg.content_.ID == "MessageChatDeleteMember" then msg.deluser = true end end elseif data.ID == "UpdateMessageContent" then cmsg = data local function edited_cb(arg, data) msg = data msg.media = {} if cmsg.new_content_.text_ then msg.text = cmsg.new_content_.text_ end if cmsg.new_content_.caption_ then msg.media.caption = cmsg.new_content_.caption_ end msg.edited = true if msg_valid(msg) then var_cb(msg, msg) end end tdcli_function ({ ID = "GetMessage", chat_id_ = data.chat_id_, message_id_ = data.message_id_ }, edited_cb, nil) elseif data.ID == "UpdateFile" then file_id = data.file_.id_ elseif (data.ID == "UpdateChat") then chat = data.chat_ chats[chat.id_] = chat elseif (data.ID == "UpdateOption" and data.name_ == "my_id") then tdcli_function ({ID="GetChats", offset_order_="9223372036854775807", offset_chat_id_=0, limit_=20}, dl_cb, nil) end end
gpl-3.0
RockySeven3161/NewBot
bot/utils.lua
239
13499
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")() 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 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 -- 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) 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
jvehent/MozDef
examples/heka-lua-bro/bro_ftp.lua
10
3588
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. -- Copyright (c) 2014 Mozilla Corporation -- -- Contributors: -- Anthony Verez averez@mozilla.com -- Jeff Bryner jbryner@mozilla.com -- Michal Purzynski mpurzynski@mozilla.com local l=require "lpeg" local string=require "string" l.locale(l) --add locale entries in the lpeg table local space = l.space^0 --define a space constant local sep = l.P"\t" local elem = l.C((1-sep)^0) grammar = l.Ct(elem * (sep * elem)^0) -- split on tabs, return as table function toString(value) if value == "-" then return nil end return value end function nilToString(value) if value == nil then return "" end return value end function toNumber(value) if value == "-" then return nil end return tonumber(value) end function truncate(value) -- truncate the URI if too long (heka limited to 63KiB messages) if toString(value) then if string.len(value) > 10000 then return toString(string.sub(value, 1, 10000)) .. "[truncated]" else return value end end end function lastField(value) -- remove last "\n" if there's one if value ~= nil and string.len(value) > 1 and string.sub(value, -2) == "\n" then return string.sub(value, 1, -2) end return value end function process_message() local log = read_message("Payload") --set a default msg that heka's --message matcher can ignore via a message matcher: -- message_matcher = "( Type!='heka.all-report' && Type != 'IGNORE' )" local msg = { Type = "IGNORE", Fields={} } local matches = grammar:match(log) if not matches then --return 0 to not propogate errors to heka's log. --return a message with IGNORE type to not match heka's message matcher inject_message(msg) return 0 end if string.sub(log,1,1)=='#' then --it's a comment line inject_message(msg) return 0 end msg['Type'] = 'broftp' msg['Logger'] = 'nsm' msg.Fields['ts'] = toString(matches[1]) msg.Fields['uid'] = toString(matches[2]) msg.Fields['sourceipaddress'] = toString(matches[3]) msg.Fields['sourceport'] = toNumber(matches[4]) msg.Fields['destinationipaddress'] = toString(matches[5]) msg.Fields['destinationport'] = toNumber(matches[6]) msg.Fields['user'] = toString(matches[7]) msg.Fields['password'] = toString(matches[8]) msg.Fields['command'] = toString(matches[9]) msg.Fields['arg'] = toString(matches[10]) msg.Fields['mime_type'] = toString(matches[11]) msg.Fields['file_size_int'] = toNumber(matches[12]) msg.Fields['reply_code_int'] = toNumber(matches[13]) msg.Fields['reply_msg'] = toString(matches[14]) msg.Fields['data_channel.passive'] = toString(matches[15]) msg.Fields['data_channel.orig_h'] = toString(matches[16]) msg.Fields['data_channel.resp_h'] = toString(matches[17]) msg.Fields['data_channel.resp_p_int'] = toNumber(matches[18]) msg.Fields['fuid'] = lastField(matches[19]) -- remove last "\n" msg.Fields['summary'] = "FTP: " .. nilToString(msg.Fields['sourceipaddress']) .. " -> " .. nilToString(msg.Fields['destinationipaddress']) .. ":" .. nilToString(msg.Fields['destinationport']) .. " " .. nilToString(msg.Fields['command']) .. " as " .. nilToString(msg.Fields['user']) inject_message(msg) return 0 end
mpl-2.0
cypherkey/AvorionMission
lib/rewards.lua
1
1409
package.path = package.path .. ";data/scripts/lib/?.lua" require ("randomext") require ("stringutility") TurretGenerator = require ("turretgenerator") UpgradeGenerator = require ("upgradegenerator") local Rewards = {} local messages1 = { "Thank you."%_t, "Thank you so much."%_t, "We thank you."%_t, "Thank you for helping us."%_t, } local messages2 = { "You have our endless gratitude."%_t, "We transferred a reward to your account."%_t, "We have a reward for you."%_t, "Please take this as a sign of our gratitude."%_t, } function standard(player, faction, msg, money, reputation, turret, system) msg = msg or messages1[random():getInt(1, #messages1)] .. " " .. messages2[random():getInt(1, #messages2)] -- give payment to players who participated player:sendChatMessage(faction.name, 0, msg) player:receive(money) Galaxy():changeFactionRelations(player, faction, reputation) local x, y = Sector():getCoordinates() local object if system and random():getFloat() < 0.5 then UpgradeGenerator.initialize(random():createSeed()) object = UpgradeGenerator.generateSystem(Rarity(RarityType.Uncommon)) elseif turret then object = InventoryTurret(TurretGenerator.generate(Sector():getCoordinates())) end if object then player:getInventory():add(object) end end Rewards.standard = standard return Rewards
gpl-3.0
diamondo25/Vana
scripts/instances/papulatus.lua
2
1391
--[[ Copyright (C) 2008-2016 Vana Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. --]] function beginInstance() addInstanceMap(220080001); players = getAllMapPlayerIds(220080001); for i = 1, #players do addInstancePlayer(players[i]); end end function playerDisconnect(playerId, isPartyLeader) cleanUpPapulatus(); end function changeMap(playerId, newMap, oldMap, isPartyLeader) if not isInstanceMap(newMap) then -- Player probably died, want to make sure this doesn't keep the room full removeInstancePlayer(playerId); cleanUpPapulatus(); end end function cleanUpPapulatus() if getInstancePlayerCount() == 0 then setReactorState(220080000, 2208001, 0); setReactorState(220080000, 2208003, 0); setReactorState(220080001, 2201004, 0); markForDelete(); end end
gpl-2.0
shahabsaf1/Teleseed-sami
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) 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 pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
aliomega/aliomega
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) 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 pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
Whit3Tig3R/spammn1
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) 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 pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
5620g/38196040
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) 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 pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
bmscoordinators/FFXI-Server
scripts/zones/Port_Jeuno/npcs/Veujaie.lua
14
1041
---------------------------------- -- Area: Port Jeuno -- NPC: Veujaie -- Type: Item Deliverer -- @zone 246 -- @pos -20.349 7.999 -2.888 -- ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/globals/weaponskills/black_halo.lua
25
1568
----------------------------------- -- Black Halo -- Club weapon skill -- Skill level: 230 -- In order to obtain Black Halo, the quest Orastery Woes must be completed. -- Delivers a two-hit attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Shadow Gorget, Thunder Gorget & Breeze Gorget. -- Aligned with the Shadow Belt, Thunder Belt & Breeze Belt. -- Element: None -- Modifiers: STR:30% ; MND:50% -- 100%TP 200%TP 300%TP -- 1.50 2.50 3.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 = 2; params.ftp100 = 1.5; params.ftp200 = 2.5; params.ftp300 = 3; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.5; 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.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 3.0; params.ftp200 = 7.25; params.ftp300 = 9.75; params.mnd_wsc = 0.7; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
bmscoordinators/FFXI-Server
scripts/globals/spells/valor_minuet_iv.lua
27
1567
----------------------------------------- -- Spell: Valor Minuet IV -- Grants Attack bonus to all allies. ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 31; if (sLvl+iLvl > 300) then power = power + math.floor((sLvl+iLvl-300) / 6); end if (power >= 56) then power = 56; end local iBoost = caster:getMod(MOD_MINUET_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); if (iBoost > 0) then power = power + 1 + (iBoost-1)*4; end power = power + caster:getMerit(MERIT_MINUET_EFFECT); if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_MINUET,power,0,duration,caster:getID(), 0, 4)) then spell:setMsg(75); end return EFFECT_MINUET; end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/globals/spells/light_carol.lua
27
1535
----------------------------------------- -- Spell: Light Carol -- Increases light resistance for party members within the area of effect. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 20; if (sLvl+iLvl > 200) then power = power + math.floor((sLvl+iLvl-200) / 10); end if (power >= 40) then power = 40; end local iBoost = caster:getMod(MOD_CAROL_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost*5; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_CAROL,power,0,duration,caster:getID(), ELE_LIGHT, 1)) then spell:setMsg(75); end return EFFECT_CAROL; end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Kazham-Jeuno_Airship/npcs/Joosef.lua
30
2300
----------------------------------- -- Area: Kazham-Jeuno Airship -- NPC: Joosef -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham-Jeuno_Airship/TextIDs"] = nil; require("scripts/zones/Kazham-Jeuno_Airship/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 1 do vHour = vHour - 6; end local message = WILL_REACH_KAZHAM; if (vHour == -5) then if (vMin >= 48) then vHour = 3; message = WILL_REACH_JEUNO; else vHour = 0; end elseif (vHour == -4) then vHour = 2; message = WILL_REACH_JEUNO; elseif (vHour == -3) then vHour = 1; message = WILL_REACH_JEUNO; elseif (vHour == -2) then if (vMin <= 49) then vHour = 0; message = WILL_REACH_JEUNO; else vHour = 3; end elseif (vHour == -1) then vHour = 2; elseif (vHour == 0) then vHour = 1; end local vMinutes = 0; if (message == WILL_REACH_JEUNO) then vMinutes = (vHour * 60) + 49 - vMin; else -- WILL_REACH_KAZHAM vMinutes = (vHour * 60) + 48 - vMin; end if (vMinutes <= 30) then if ( message == WILL_REACH_KAZHAM) then message = IN_KAZHAM_MOMENTARILY; else -- WILL_REACH_JEUNO message = IN_JEUNO_MOMENTARILY; end elseif (vMinutes < 60) then vHour = 0; end player:messageSpecial( message, math.floor((2.4 * vMinutes) / 60), math.floor( vMinutes / 60 + 0.5)); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Windurst_Woods/npcs/Abby_Jalunshi.lua
14
1055
----------------------------------- -- Area: Windurst Woods -- NPC: Abby Jalunshi -- Type: Moghouse Renter -- @zone 241 -- @pos -101.895 -5 36.172 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x031e); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Guilty3096/guiltyyy
plugins/owners.lua
94
12617
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run } --Copyright and edit; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
colesbury/nn
MixtureTable.lua
15
5720
local MixtureTable, parent = torch.class('nn.MixtureTable', 'nn.Module') function MixtureTable:__init(dim) parent.__init(self) self.dim = dim self.size = torch.LongStorage() self.batchSize = 0 self.size2 = torch.LongStorage() self.backwardSetup = false self.gradInput = {} end function MixtureTable:updateOutput(input) local gaterInput, expertInputs = table.unpack(input) -- buffers self._gaterView = self._gaterView or input[1].new() self._expert = self._expert or input[1].new() self._expertView = self._expertView or input[1].new() self.dimG = 2 local batchSize = gaterInput:size(1) if gaterInput:dim() < 2 then self.dimG = 1 self.dim = self.dim or 1 batchSize = 1 end self.dim = self.dim or 2 if self.table or torch.type(expertInputs) == 'table' then -- expertInputs is a Table : self.table = true if gaterInput:size(self.dimG) ~= #expertInputs then error"Should be one gater output per expert" end local expertInput = expertInputs[1] if self.batchSize ~= batchSize then self.size:resize(expertInput:dim()+1):fill(1) if self.dimG > 1 then self.size[1] = gaterInput:size(1) end self.size[self.dim] = gaterInput:size(self.dimG) self.output:resizeAs(expertInput) self.backwardSetup = false self.batchSize = batchSize end self._gaterView:view(gaterInput, self.size) self.output:zero() -- multiply accumulate gater outputs by their commensurate expert for i,expertInput in ipairs(expertInputs) do local gate = self._gaterView:select(self.dim,i):expandAs(expertInput) self.output:addcmul(expertInput, gate) end else -- expertInputs is a Tensor : if self.batchSize ~= batchSize then self.size:resize(expertInputs:dim()):fill(1) if self.dimG > 1 then self.size[1] = gaterInput:size(1) end self.size[self.dim] = gaterInput:size(self.dimG) self.output:resizeAs(expertInputs:select(self.dim, 1)) self.batchSize = batchSize self.backwardSetup = false end self._gaterView:view(gaterInput, self.size) self._expert:cmul(self._gaterView:expandAs(expertInputs), expertInputs) self.output:sum(self._expert, self.dim) self.output:resizeAs(expertInputs:select(self.dim, 1)) end return self.output end function MixtureTable:updateGradInput(input, gradOutput) local gaterInput, expertInputs = table.unpack(input) nn.utils.recursiveResizeAs(self.gradInput, input) local gaterGradInput, expertGradInputs = table.unpack(self.gradInput) -- buffers self._sum = self._sum or input[1].new() self._expertView2 = self._expertView2 or input[1].new() self._expert2 = self._expert2 or input[1].new() if self.table then if not self.backwardSetup then for i,expertInput in ipairs(expertInputs) do local expertGradInput = expertGradInputs[i] or expertInput:clone() expertGradInput:resizeAs(expertInput) expertGradInputs[i] = expertGradInput end gaterGradInput:resizeAs(gaterInput) self.backwardSetup = true end -- like CMulTable, but with broadcasting for i,expertGradInput in ipairs(expertGradInputs) do -- gater updateGradInput self._expert:cmul(gradOutput, expertInputs[i]) if self.dimG == 1 then self._expertView:view(self._expert, -1) else self._expertView:view(self._expert, gradOutput:size(1), -1) end self._sum:sum(self._expertView, self.dimG) if self.dimG == 1 then gaterGradInput[i] = self._sum:select(self.dimG,1) else gaterGradInput:select(self.dimG,i):copy(self._sum:select(self.dimG,1)) end -- expert updateGradInput local gate = self._gaterView:select(self.dim,i):expandAs(expertGradInput) expertGradInput:cmul(gate, gradOutput) end else if not self.backwardSetup then self.size2:resize(expertInputs:dim()) self.size2:copy(expertInputs:size()) self.size2[self.dim] = 1 gaterGradInput:resizeAs(gaterInput) self.backwardSetup = true end -- gater updateGradInput self._expertView:view(gradOutput, self.size2) local gradOutput = self._expertView:expandAs(expertInputs) self._expert:cmul(gradOutput, expertInputs) local expert = self._expert:transpose(self.dim, self.dimG) if not expert:isContiguous() then self._expert2:resizeAs(expert) self._expert2:copy(expert) expert = self._expert2 end if self.dimG == 1 then self._expertView2:view(expert, gaterInput:size(1), -1) else self._expertView2:view(expert, gaterInput:size(1), gaterInput:size(2), -1) end gaterGradInput:sum(self._expertView2, self.dimG+1) gaterGradInput:resizeAs(gaterInput) -- expert updateGradInput expertGradInputs:cmul(self._gaterView:expandAs(expertInputs), gradOutput) end return self.gradInput end function MixtureTable:type(type, tensorCache) self._gaterView = nil self._expert = nil self._expertView = nil self._sum = nil self._expert2 = nil self._expertView2 = nil return parent.type(self, type, tensorCache) end function MixtureTable:clearState() nn.utils.clear(self, { '_gaterView', '_expert', '_expertView', '_sum', '_expert2', '_expertView2', }) return parent.clearState(self) end
bsd-3-clause
bmscoordinators/FFXI-Server
scripts/zones/Qufim_Island/npcs/Sasa_IM.lua
14
3330
----------------------------------- -- Area: Qufim Island -- NPC: Sasa, I.M. -- Type: Outpost Conquest Guards -- @pos -245.366 -20.344 299.502 126 ------------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Qufim_Island/TextIDs"); local guardnation = NATION_BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = QUFIMISLAND; local csid = 0x7ff9; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
mohammad25253/teamking
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
bmscoordinators/FFXI-Server
scripts/zones/East_Sarutabaruta/Zone.lua
4
5409
----------------------------------- -- -- Zone: East_Sarutabaruta (116) -- ----------------------------------- package.loaded[ "scripts/zones/East_Sarutabaruta/TextIDs"] = nil; package.loaded["scripts/globals/chocobo_digging"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/icanheararainbow"); require("scripts/zones/East_Sarutabaruta/TextIDs"); require("scripts/globals/zone"); require("scripts/globals/chocobo_digging"); ----------------------------------- -- Chocobo Digging vars ----------------------------------- local itemMap = { -- itemid, abundance, requirement { 689, 132, DIGREQ_NONE }, { 938, 79, DIGREQ_NONE }, { 17296, 132, DIGREQ_NONE }, { 847, 100, DIGREQ_NONE }, { 846, 53, DIGREQ_NONE }, { 833, 100, DIGREQ_NONE }, { 841, 53, DIGREQ_NONE }, { 834, 26, DIGREQ_NONE }, { 772, 50, DIGREQ_NONE }, { 701, 50, DIGREQ_NONE }, { 702, 3, DIGREQ_NONE }, { 4096, 100, DIGREQ_NONE }, -- all crystals { 4545, 200, DIGREQ_BURROW }, { 636, 50, DIGREQ_BURROW }, { 5235, 10, DIGREQ_BURROW }, { 617, 50, DIGREQ_BORE }, { 4570, 10, DIGREQ_MODIFIER }, { 4487, 11, DIGREQ_MODIFIER }, { 4409, 12, DIGREQ_MODIFIER }, { 1188, 10, DIGREQ_MODIFIER }, { 4532, 12, DIGREQ_MODIFIER }, { 572, 100, DIGREQ_NIGHT }, }; local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED }; ----------------------------------- -- onChocoboDig ----------------------------------- function onChocoboDig(player, precheck) return chocoboDig(player, itemMap, precheck, messageArray); end; ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) SetRespawnTime(17252725, 3600, 4200); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(305.377,-36.092,660.435,71); end -- Check if we are on Windurst Mission 1-2 if (player:getCurrentMission(WINDURST) == THE_HEART_OF_THE_MATTER and player:getVar( "MissionStatus") == 5 and prevZone == 194) then cs = 0x0030; elseif (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow cs = 0x0032; elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then cs = 0x0034; -- go north no parameters (0 = north NE 1 E 2 SE 3 S 4 SW 5 W6 NW 7 @ as the 6th parameter) elseif (player:getCurrentMission(ASA) == BURGEONING_DREAD and prevZone == 241 and player:hasStatusEffect(EFFECT_MOUNTED) == false ) then cs = 0x0047; end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter( player, region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0032) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow elseif (csid == 0x0034) then if (player:getPreviousZone() == 241 or player:getPreviousZone() == 115) then if (player:getZPos() < 570) then player:updateEvent(0,0,0,0,0,1); else player:updateEvent(0,0,0,0,0,2); end elseif (player:getPreviousZone() == 194) then if (player:getZPos() > 570) then player:updateEvent(0,0,0,0,0,2); end end elseif (csid == 0x0047) then player:setVar("ASA_Status",option); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0030) then player:setVar( "MissionStatus",6); -- Remove the glowing orb key items player:delKeyItem(FIRST_GLOWING_MANA_ORB); player:delKeyItem(SECOND_GLOWING_MANA_ORB); player:delKeyItem(THIRD_GLOWING_MANA_ORB); player:delKeyItem(FOURTH_GLOWING_MANA_ORB); player:delKeyItem(FIFTH_GLOWING_MANA_ORB); player:delKeyItem(SIXTH_GLOWING_MANA_ORB); elseif (csid == 0x0032) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow elseif (csid == 0x0047) then player:completeMission(ASA,BURGEONING_DREAD); player:addMission(ASA,THAT_WHICH_CURDLES_BLOOD); end end;
gpl-3.0
Guilty3096/guiltyyy
plugins/anti_chat.lua
62
1069
antichat = {}-- An empty table for solving multiple kicking problem do local function run(msg, matches) if is_momod(msg) then -- Ignore mods,owner,admins return end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)]['settings']['lock_chat'] then if data[tostring(msg.to.id)]['settings']['lock_chat'] == 'yes' then if antichat[msg.from.id] == true then return end send_large_msg("chat#id".. msg.to.id , "chat is not allowed here") local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked (chat was locked) ") chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false) antichat[msg.from.id] = true return end end return end local function cron() antichat = {} -- Clear antichat table end return { patterns = { "([\216-\219][\128-\191])" }, run = run, cron = cron } end --Copyright; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
TannerRogalsky/GGJ2017
states/game/game_lighting_test.lua
1
2259
local LightingTest = Game:addState('LightingTest') local physicsDebugDraw = require('physics_debug_draw') local buildLightOverlay = require('light.build_light_overlay') LIGHT_FALLOFF_DISTANCE = 250 function LightingTest:enteredState() self.origin = {x = g.getWidth() / 2, y = g.getHeight() / 2} self.world = love.physics.newWorld(0, 0) local body = love.physics.newBody(self.world, 0, 0, 'static') local world_shape = love.physics.newPolygonShape(150 + 200, 100 + 200, 200 + 200, 100 + 200, 175 + 200, 150 + 200) local world_fixture = love.physics.newFixture(body, world_shape) self.map = {body = body} self.light_bbox = love.physics.newBody(self.world, 0, 0, 'static') local light_bbox_shape = love.physics.newChainShape(true, -LIGHT_FALLOFF_DISTANCE, -LIGHT_FALLOFF_DISTANCE, -LIGHT_FALLOFF_DISTANCE, LIGHT_FALLOFF_DISTANCE, LIGHT_FALLOFF_DISTANCE, LIGHT_FALLOFF_DISTANCE, LIGHT_FALLOFF_DISTANCE, -LIGHT_FALLOFF_DISTANCE) self.light_bbox_fix = love.physics.newFixture(self.light_bbox, light_bbox_shape) self.light_bbox_fix:setSensor(true) self.light_overlay = g.newCanvas(g.getWidth(), g.getHeight(), 'normal') self.player_light_falloff_shader = g.newShader('shaders/player_light_falloff.glsl') self.player_light_falloff_shader:send('falloff_distance', LIGHT_FALLOFF_DISTANCE) g.setBackgroundColor(100, 100, 100) end local t = 0 function LightingTest:update(dt) t = t + dt self.light_bbox:setPosition(self.origin.x, self.origin.y) self.light_bbox:setAngle(t / 2) end function LightingTest:draw() self.origin.x, self.origin.y = love.mouse.getPosition() -- g.setColor(255, 255, 255, 100) -- buildLightOverlay(self.origin.x, self.origin.y) do g.push('all') g.setCanvas(self.light_overlay) g.clear(0, 0, 0, 255 * 0.6) if love.keyboard.isDown('space') then g.setWireframe(true) else g.setShader(self.player_light_falloff_shader) end g.setBlendMode('multiply') g.setColor(255, 255, 255, 255 * 0.25) buildLightOverlay(self.origin.x, self.origin.y, self.light_filter) g.pop() g.draw(self.light_overlay) end physicsDebugDraw(self.world) g.print(love.timer.getFPS()) end function LightingTest:exitedState() end return LightingTest
mit
bmscoordinators/FFXI-Server
scripts/zones/Metalworks/npcs/Vicious_Eye.lua
27
1187
----------------------------------- -- Area: Metalworks -- NPC: Vicious Eye -- Type: Guild Merchant (Blacksmithing Guild) -- @pos -106.132 0.999 -28.757 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(533,8,23,2)) then player:showText(npc, VICIOUS_EYE_SHOP_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Spire_of_Holla/npcs/_0h0.lua
22
1508
----------------------------------- -- Area: Spire of Holla -- NPC: Web of Recollection ----------------------------------- package.loaded["scripts/zones/Spire_of_Holla/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Spire_of_Holla/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; else player:messageSpecial(FAINT_SCRAPING); return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
XtBot/xt
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
bmscoordinators/FFXI-Server
scripts/globals/spells/burn.lua
9
1852
----------------------------------------- -- Spell: Burn -- Deals fire damage that lowers an enemy's intelligence and gradually reduces its HP. ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) if (target:getStatusEffect(EFFECT_DROWN) ~= nil) then spell:setMsg(75); -- no effect else local dINT = caster:getStat(MOD_INT)-target:getStat(MOD_INT); local resist = applyResistance(caster,spell,target,dINT,36,0); if (resist <= 0.125) then spell:setMsg(85); else if (target:getStatusEffect(EFFECT_FROST) ~= nil) then target:delStatusEffect(EFFECT_FROST); end; local sINT = caster:getStat(MOD_INT); local DOT = getElementalDebuffDOT(sINT); local effect = target:getStatusEffect(EFFECT_BURN); local noeffect = false; if (effect ~= nil) then if (effect:getPower() >= DOT) then noeffect = true; end; end; if (noeffect) then spell:setMsg(75); -- no effect else if (effect ~= nil) then target:delStatusEffect(EFFECT_BURN); end; spell:setMsg(237); local duration = math.floor(ELEMENTAL_DEBUFF_DURATION * resist); target:addStatusEffect(EFFECT_BURN,DOT, 3, ELEMENTAL_DEBUFF_DURATION,FLAG_ERASABLE); end; end; end; return EFFECT_BURN; end;
gpl-3.0
mohammadrezatitan/maikel
plugins/kickme.lua
1
1223
--Start By @Tele_Sudo local function run(msg, matches) if matches[1] == 'kickme' or matches[1] == 'ترک گروه' then local hash = 'kick:'..msg.chat_id_..':'..msg.sender_user_id_ redis:set(hash, "waite") return 'کاربر عزیز شما در خواست اخراج از گروه را دارید اگر اطمینان دارید *yes* را ارسال کینید✅' end msg.text = msg.content_.text_ if msg.text then local hash = 'kick:'..msg.chat_id_..':'..msg.sender_user_id_ if msg.text:match("^yes$") and redis:get(hash) == "waite" then redis:set(hash, "ok") elseif msg.text:match("^no$") and redis:get(hash) == "waite" then tdcli.sendMessage(msg.chat_id_, 0, 1, 'کاربر عزیز شما مرض دارید', 1, 'md') redis:del(hash, true) end end local hash = 'kick:'..msg.chat_id_..':'..msg.sender_user_id_ if redis:get(hash) then if redis:get(hash) == "ok" then kick_user(msg.sender_user_id_,msg.chat_id_) return 'انجام شد✅' end end end return { patterns = { "[!/#]([Kk][Ii][Cc][Kk][Mm][Ee])", "kickme", "^yes$", "^no$", "^ترک گروه$" }, run = run, } --End By @Tele_Sudo --Channel @LuaError
gpl-3.0
diamondo25/Vana
scripts/instances/miniDungeonRabbit.lua
2
1320
--[[ Copyright (C) 2008-2016 Vana Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. --]] dofile("scripts/utils/miniDungeonHelper.lua"); function beginInstance() initMiniDungeonMaps(221023401, 25, 221023400, 220000000); end function timerEnd(name, fromTimer) miniDungeonTimerEnd(name, fromTimer); end function playerDisconnect(playerId, isPartyLeader) miniDungeonPlayerDisconnect(playerId, isPartyLeader); end function partyDisband(partyId) miniDungeonPartyDisband(partyId); end function partyRemoveMember(partyId, playerId) miniDunegonPartyRemoveMember(partyId, playerId); end function changeMap(playerId, newMap, oldMap, isPartyLeader) miniDungeonChangeMap(playerId, newMap, oldMap, isPartyLeader); end
gpl-2.0
diamondo25/Vana
scripts/npcs/taxi3.lua
2
2312
--[[ Copyright (C) 2008-2016 Vana Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. --]] -- Regular Cab (Kerning cab) dofile("scripts/utils/npcHelper.lua"); function generateChoice(mapId, price) return makeChoiceData(mapRef(mapId) .. "(" .. price .. " mesos) ", {mapId, price}); end function getPrice(basePrice) if getJob() == 0 then return basePrice / 10; end return basePrice; end choices = { generateChoice(104000000, getPrice(1000)), generateChoice(102000000, getPrice(800)), generateChoice(101000000, getPrice(1200)), generateChoice(100000000, getPrice(1000)), }; addText("Hi! I drive the " .. npcRef(1052016) .. ". "); addText("If you want to go from town to town safely and fast, then ride our cab. "); addText("We'll gladly take you to your destination with an affordable price."); sendNext(); if getJob() == 0 then addText("We have a special 90% discount for beginners. "); end addText("Choose your destination, for fees will change from place to place.\r\n"); addText(blue(choiceRef(choices))); choice = askChoice(); data = selectChoice(choices, choice); mapId, price = data[1], data[2]; addText("You don't have anything else to do here, huh? "); addText("Do you really want to go to " .. blue(mapRef(mapId)) .. "? "); addText("It'll cost you " .. blue(price .. " mesos") .. "."); answer = askYesNo(); if answer == answer_yes then if giveMesos(-price) then setMap(mapId); else addText("You don't have enough mesos. "); addText("Sorry to say this, but without them, you won't be able to ride this cab."); sendOk(); end else addText("There's a lot to see in this town, too. "); addText("Come back and find me when you need to go to a different town."); sendOk(); end
gpl-2.0
bmscoordinators/FFXI-Server
scripts/zones/Gustav_Tunnel/mobs/Goblin_Mercenary.lua
2
1175
---------------------------------- -- Area: Gustav Tunnel -- MOB: Goblin Mercenary -- Note: Place holder Wyvernpoacher Drachlox ----------------------------------- require("scripts/globals/groundsofvalor"); require("scripts/zones/Gustav_Tunnel/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) checkGoVregime(player,mob,764,3); checkGoVregime(player,mob,765,3); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); if (Wyvernpoacher_Drachlox_PH[mobID] ~= nil) then local ToD = GetServerVariable("[POP]Wyvernpoacher_Drachlox"); if (ToD <= os.time() and GetMobAction(Wyvernpoacher_Drachlox) == 0) then if (math.random(1,20) == 5) then UpdateNMSpawnPoint(Wyvernpoacher_Drachlox); GetMobByID(Wyvernpoacher_Drachlox):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Wyvernpoacher_Drachlox", mobID); DeterMob(mobID, true); end end end end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Port_Bastok/npcs/Dehlner.lua
17
1208
----------------------------------- -- Area: Port Bastok -- NPC: Dehlner -- Standard Info NPC -- Invlolved in Quest: A Foreman's Best Friend ----------------------------------- require("scripts/globals/quests"); package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) ForemansBestFriend = player:getQuestStatus(BASTOK,A_FOREMAN_S_BEST_FRIEND); if (ForemansBestFriend == QUEST_ACCEPTED) then player:startEvent(0x006f); else player:startEvent(0x002e); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
rajive/mongrel2
examples/bbs/ui.lua
96
2026
local coroutine = coroutine module 'ui' local SCREENS = { ['welcome'] = [[ __ __ ____ ____ ____ ____ | \/ |___ \| __ )| __ ) ___| | |\/| | __) | _ \| _ \___ \ | | | |/ __/| |_) | |_) |__) | |_| |_|_____|____/|____/____/ Welcome to the Mongrel2 BBS. ]], ['name'] = "What's your name?", ['welcome_newbie'] = 'Awesome! Welcome to our little BBS. Have fun.\n', ['password'] = "What's your password?", ['motd'] = [[ MOTD: There's not much going on here currently, and we're mostly just trying out this whole Lua with Mongrel2 thing. If you like it then help out by leaving a message and trying to break it. -- Zed Enter to continue.]], ['menu'] = [[ ---(((MAIN MENU))--- 1. Leave a message. 2. Read messages left. 3. Send to someone else. 4. Read messages to you. Q. Quit the BBS. ]], ['bye'] = "Alright, see ya later.", ['leave_msg'] = "Enter your message, up to 20 lines, then enter . by itself to end it:\n", ['read_msg'] = "These are left by different users:\n", ['menu_error'] = "That's not a valid menu option.", ['posted'] = "Message posted.", ['new_user'] = "Looks like you're new here. Type your password again and make it match.", ['bad_pass'] = "Right, I can't let you in unless you get the user and password right. Bye.", ['repeat_pass'] = "Password doesn't matched what you typed already, try again.", ['error'] = "We had an error, try again later.", } function display(conn, request, data) conn:reply_json(request, {type = 'screen', msg = data}) end function ask(conn, request, data, pchar) conn:reply_json(request, {type = 'prompt', msg = data, pchar = pchar}) return coroutine.yield() end function screen(conn, request, name) display(conn, request, SCREENS[name]) end function prompt(conn, request, name) return ask(conn, request, SCREENS[name], '> ') end function exit(conn, request, name) conn:reply_json(request, {type = 'exit', msg = SCREENS[name]}) end
bsd-3-clause
bmscoordinators/FFXI-Server
scripts/zones/Eastern_Altepa_Desert/TextIDs.lua
7
1060
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6385; -- Obtained: <item>. GIL_OBTAINED = 6386; -- Obtained <number> gil. KEYITEM_OBTAINED = 6388; -- Obtained key item: <keyitem>. BEASTMEN_BANNER = 7127; -- There is a beastmen's banner. FISHING_MESSAGE_OFFSET = 7547; -- You can't fish here. ALREADY_OBTAINED_TELE = 7656; -- You already possess the gate crystal for this telepoint. -- Conquest CONQUEST = 7214; -- You've earned conquest points! -- Quest Dialog SENSE_OF_FOREBODING = 6400; -- You are suddenly overcome with a sense of foreboding... NOTHING_OUT_OF_ORDINARY = 7662; -- There is nothing out of the ordinary here. -- conquest Base CONQUEST_BASE = 7046; -- Tallying conquest results... --chocobo digging DIG_THROW_AWAY = 7560; -- You dig up$, but your inventory is full. You regretfully throw the # away. FIND_NOTHING = 7562; -- You dig and you dig, but find nothing.
gpl-3.0
bmscoordinators/FFXI-Server
scripts/globals/weaponskills/dulling_arrow.lua
15
1369
----------------------------------- -- Dulling Arrow -- Archery weapon skill -- Skill level: 80 -- Lowers enemy's INT. Chance of params.critical varies with TP. -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: None -- Modifiers: STR:16% ; AGI:25% -- 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 = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.16; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.25; 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.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.2; params.agi_wsc = 0.5; end local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
colesbury/nn
MM.lua
17
2812
--[[ Module to perform matrix multiplication on two minibatch inputs, producing a minibatch. ]] local MM, parent = torch.class('nn.MM', 'nn.Module') --[[ The constructor takes two optional arguments, specifying whether or not transpose any of the input matrices before perfoming the multiplication. ]] function MM:__init(transA, transB) parent.__init(self) self.transA = transA or false self.transB = transB or false self.gradInput = {torch.Tensor(), torch.Tensor()} end function MM:updateOutput(input) assert(#input == 2, 'input must be a pair of minibatch matrices') local a, b = table.unpack(input) assert(a:nDimension() == 2 or a:nDimension() == 3, 'input tensors must be 2D or 3D') if a:nDimension() == 2 then assert(b:nDimension() == 2, 'second input tensor must be 2D') if self.transA then a = a:t() end if self.transB then b = b:t() end assert(a:size(2) == b:size(1), 'matrix sizes do not match') self.output:resize(a:size(1), b:size(2)) self.output:mm(a, b) else assert(b:nDimension() == 3, 'second input tensor must be 3D') assert(a:size(1) == b:size(1), 'inputs must contain the same number of minibatches') if self.transA then a = a:transpose(2, 3) end if self.transB then b = b:transpose(2, 3) end assert(a:size(3) == b:size(2), 'matrix sizes do not match') self.output:resize(a:size(1), a:size(2), b:size(3)) self.output:bmm(a, b) end return self.output end function MM:updateGradInput(input, gradOutput) self.gradInput[1] = self.gradInput[1] or input[1].new() self.gradInput[2] = self.gradInput[2] or input[2].new() assert(#input == 2, 'input must be a pair of tensors') local a, b = table.unpack(input) self.gradInput[1]:resizeAs(a) self.gradInput[2]:resizeAs(b) assert(gradOutput:nDimension() == 2 or gradOutput:nDimension() == 3, 'arguments must be a 2D or 3D Tensor') local h_dim, w_dim, f if gradOutput:nDimension() == 2 then assert(a:nDimension() == 2, 'first input tensor must be 2D') assert(b:nDimension() == 2, 'second input tensor must be 2D') h_dim, w_dim = 1, 2 f = "mm" else assert(a:nDimension() == 3, 'first input tensor must be 3D') assert(b:nDimension() == 3, 'second input tensor must be 3D') h_dim, w_dim = 2, 3 f = "bmm" end if self.transA == self.transB then a = a:transpose(h_dim, w_dim) b = b:transpose(h_dim, w_dim) end if self.transA then self.gradInput[1][f](self.gradInput[1], b, gradOutput:transpose(h_dim, w_dim)) else self.gradInput[1][f](self.gradInput[1], gradOutput, b) end if self.transB then self.gradInput[2][f](self.gradInput[2], gradOutput:transpose(h_dim, w_dim), a) else self.gradInput[2][f](self.gradInput[2], a, gradOutput) end return self.gradInput end
bsd-3-clause
TannerRogalsky/GGJ2017
lib/vector.lua
3
5350
--[[ Copyright (c) 2010-2013 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 assert = assert local sqrt, cos, sin, atan2 = math.sqrt, math.cos, math.sin, math.atan2 local vector = {} vector.__index = vector local function new(x,y) return setmetatable({x = x or 0, y = y or 0}, vector) end local zero = new(0,0) local function isvector(v) return getmetatable(v) == vector end function vector:clone() return new(self.x, self.y) end function vector:unpack() return self.x, self.y end function vector:__tostring() return "("..tonumber(self.x)..","..tonumber(self.y)..")" end function vector.__unm(a) return new(-a.x, -a.y) end function vector.__add(a,b) assert(isvector(a) and isvector(b), "Add: wrong argument types (<vector> expected)") return new(a.x+b.x, a.y+b.y) end function vector.__sub(a,b) assert(isvector(a) and isvector(b), "Sub: wrong argument types (<vector> expected)") return new(a.x-b.x, a.y-b.y) end function vector.__mul(a,b) if type(a) == "number" then return new(a*b.x, a*b.y) elseif type(b) == "number" then return new(b*a.x, b*a.y) else assert(isvector(a) and isvector(b), "Mul: wrong argument types (<vector> or <number> expected)") return a.x*b.x + a.y*b.y end end function vector.__div(a,b) assert(isvector(a) and type(b) == "number", "wrong argument types (expected <vector> / <number>)") return new(a.x / b, a.y / b) end function vector.__eq(a,b) return a.x == b.x and a.y == b.y end function vector.__lt(a,b) return a.x < b.x or (a.x == b.x and a.y < b.y) end function vector.__le(a,b) return a.x <= b.x and a.y <= b.y end function vector.permul(a,b) assert(isvector(a) and isvector(b), "permul: wrong argument types (<vector> expected)") return new(a.x*b.x, a.y*b.y) end function vector:len2() return self.x * self.x + self.y * self.y end function vector:len() return sqrt(self.x * self.x + self.y * self.y) end function vector.dist(a, b) assert(isvector(a) and isvector(b), "dist: wrong argument types (<vector> expected)") local dx = a.x - b.x local dy = a.y - b.y return sqrt(dx * dx + dy * dy) end function vector.dist2(a, b) assert(isvector(a) and isvector(b), "dist: wrong argument types (<vector> expected)") local dx = a.x - b.x local dy = a.y - b.y return (dx * dx + dy * dy) end function vector:normalize_inplace() local l = self:len() if l > 0 then self.x, self.y = self.x / l, self.y / l end return self end function vector:normalized() return self:clone():normalize_inplace() end function vector:rotate_inplace(phi) local c, s = cos(phi), sin(phi) self.x, self.y = c * self.x - s * self.y, s * self.x + c * self.y return self end function vector:rotated(phi) local c, s = cos(phi), sin(phi) return new(c * self.x - s * self.y, s * self.x + c * self.y) end function vector:perpendicular() return new(-self.y, self.x) end function vector:projectOn(v) assert(isvector(v), "invalid argument: cannot project vector on " .. type(v)) -- (self * v) * v / v:len2() local s = (self.x * v.x + self.y * v.y) / (v.x * v.x + v.y * v.y) return new(s * v.x, s * v.y) end function vector:mirrorOn(v) assert(isvector(v), "invalid argument: cannot mirror vector on " .. type(v)) -- 2 * self:projectOn(v) - self local s = 2 * (self.x * v.x + self.y * v.y) / (v.x * v.x + v.y * v.y) return new(s * v.x - self.x, s * v.y - self.y) end function vector:cross(v) assert(isvector(v), "cross: wrong argument types (<vector> expected)") return self.x * v.y - self.y * v.x end -- ref.: http://blog.signalsondisplay.com/?p=336 function vector:trim_inplace(maxLen) local s = maxLen * maxLen / self:len2() s = (s > 1 and 1) or math.sqrt(s) self.x, self.y = self.x * s, self.y * s return self end function vector:angleTo(other) if other then return atan2(self.y, self.x) - atan2(other.y, other.x) end return atan2(self.y, self.x) end function vector:trimmed(maxLen) return self:clone():trim_inplace(maxLen) end -- the module return setmetatable({new = new, isvector = isvector, zero = zero}, {__call = function(_, ...) return new(...) end})
mit
bmscoordinators/FFXI-Server
scripts/globals/items/bowl_of_pebble_soup.lua
12
1137
----------------------------------------- -- ID: 4455 -- Item: Bowl of Pebble Soup -- Food Effect: 3 Hr, All Races ----------------------------------------- -- HP Recovered while healing 2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4455); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HPHEAL, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HPHEAL, 2); end;
gpl-3.0
cypherkey/AvorionMission
lib/defaultscripts.lua
1
1130
function AddDefaultShipScripts(ship) ship:addScriptOnce("data/scripts/entity/startbuilding.lua") ship:addScriptOnce("data/scripts/entity/entercraft.lua") ship:addScriptOnce("data/scripts/entity/exitcraft.lua") ship:addScriptOnce("data/scripts/entity/craftorders.lua") ship:addScriptOnce("data/scripts/entity/transfercrewgoods.lua") ship:addScriptOnce("data/scripts/entity/collaboration.lua") end function AddDefaultStationScripts(station) station:addScriptOnce("data/scripts/entity/startbuilding.lua") station:addScriptOnce("data/scripts/entity/entercraft.lua") station:addScriptOnce("data/scripts/entity/exitcraft.lua") station:addScriptOnce("data/scripts/entity/crewboard.lua") station:addScriptOnce("data/scripts/entity/backup.lua") station:addScriptOnce("data/scripts/entity/bulletinboard.lua") station:addScriptOnce("data/scripts/entity/story/bulletins.lua") station:addScriptOnce("data/scripts/entity/craftorders.lua") station:addScriptOnce("data/scripts/entity/transfercrewgoods.lua") station:addScriptOnce("data/scripts/entity/collaboration.lua") end
gpl-3.0
deepak78/luci
applications/luci-multiwan/luasrc/model/cbi/multiwan/multiwanmini.lua
7
2330
require("luci.tools.webadmin") m = Map("multiwan", translate("Multi-WAN"), translate("Multi-WAN allows for the use of multiple uplinks for load balancing and failover.")) s = m:section(NamedSection, "config", "multiwan", "") e = s:option(Flag, "enabled", translate("Enable")) e.rmempty = false function e.write(self, section, value) local cmd = (value == "1") and "enable" or "disable" if value ~= "1" then os.execute("/etc/init.d/multiwan stop") end os.execute("/etc/init.d/multiwan " .. cmd) end function e.cfgvalue(self, section) return (os.execute("/etc/init.d/multiwan enabled") == 0) and "1" or "0" end s = m:section(TypedSection, "mwanfw", translate("Multi-WAN Traffic Rules"), translate("Configure rules for directing outbound traffic through specified WAN Uplinks.")) s.template = "cbi/tblsection" s.anonymous = true s.addremove = true src = s:option(Value, "src", translate("Source Address")) src.rmempty = true src:value("", translate("all")) luci.tools.webadmin.cbi_add_knownips(src) dst = s:option(Value, "dst", translate("Destination Address")) dst.rmempty = true dst:value("", translate("all")) luci.tools.webadmin.cbi_add_knownips(dst) proto = s:option(Value, "proto", translate("Protocol")) proto:value("", translate("all")) proto:value("tcp", "TCP") proto:value("udp", "UDP") proto:value("icmp", "ICMP") proto.rmempty = true ports = s:option(Value, "ports", translate("Ports")) ports.rmempty = true ports:value("", translate("all", translate("all"))) wanrule = s:option(ListValue, "wanrule", translate("WAN Uplink")) luci.tools.webadmin.cbi_add_networks(wanrule) wanrule:value("fastbalancer", translate("Load Balancer(Performance)")) wanrule:value("balancer", translate("Load Balancer(Compatibility)")) wanrule.default = "fastbalancer" wanrule.optional = false wanrule.rmempty = false s = m:section(NamedSection, "config", "", "") s.addremove = false default_route = s:option(ListValue, "default_route", translate("Default Route")) luci.tools.webadmin.cbi_add_networks(default_route) default_route:value("fastbalancer", translate("Load Balancer(Performance)")) default_route:value("balancer", translate("Load Balancer(Compatibility)")) default_route.default = "balancer" default_route.optional = false default_route.rmempty = false return m
apache-2.0
bmscoordinators/FFXI-Server
scripts/globals/items/dried_date_+1.lua
12
1350
----------------------------------------- -- ID: 5574 -- Item: dried_date_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 12 -- Magic 22 -- Agility -1 -- Intelligence 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5574); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 12); target:addMod(MOD_MP, 22); target:addMod(MOD_AGI, -1); target:addMod(MOD_INT, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 12); target:delMod(MOD_MP, 22); target:delMod(MOD_AGI, -1); target:delMod(MOD_INT, 4); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/globals/items/crab_stewpot.lua
12
1753
----------------------------------------- -- ID: 5544 -- Item: Crab Stewpot -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10% Cap 50 -- MP +10 -- HP Recoverd while healing 5 -- MP Recovered while healing 1 -- Defense +20% Cap 50 -- Evasion +5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5544); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_FOOD_HP_CAP, 50); target:addMod(MOD_MP, 10); target:addMod(MOD_HPHEAL, 5); target:addMod(MOD_MPHEAL, 1); target:addMod(MOD_FOOD_DEFP, 20); target:addMod(MOD_FOOD_DEF_CAP, 50); target:addMod(MOD_EVA, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_FOOD_HP_CAP, 50); target:delMod(MOD_MP, 10); target:delMod(MOD_HPHEAL, 5); target:delMod(MOD_MPHEAL, 1); target:delMod(MOD_FOOD_DEFP, 20); target:delMod(MOD_FOOD_DEF_CAP, 50); target:delMod(MOD_EVA, 5); end;
gpl-3.0
bmscoordinators/FFXI-Server
scripts/zones/Diorama_Abdhaljs-Ghelsba/Zone.lua
17
1127
----------------------------------- -- -- Zone: Diorama_Abdhaljs-Ghelsba -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Diorama_Abdhaljs-Ghelsba/TextIDs"] = nil; require("scripts/zones/Diorama_Abdhaljs-Ghelsba/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Percona-QA/toku-qa
tokudb/software/sysbench/backup-test/lua/tokudb_oltp_valid.lua
4
2125
pathtest = string.match(test, "(.*/)") or "" dofile(pathtest .. "common.lua") function thread_init(thread_id) set_vars() if (db_driver == "mysql" and mysql_table_engine == "myisam") then begin_query = "LOCK TABLES sbtest WRITE" commit_query = "UNLOCK TABLES" else begin_query = "BEGIN" commit_query = "COMMIT" end end function event(thread_id) local rs local i local table_name local range_start local c_val local pad_val local query table_name = "sbtest".. sb_rand_uniform(1, oltp_tables_count) db_query(begin_query) -- do some point queries to keep busy for i=1, oltp_point_selects do rs = db_query("SELECT c FROM ".. table_name .." WHERE id=" .. sb_rand(1, oltp_table_size)) end -- do some sum queries to keep busy for i=1, oltp_sum_ranges do range_start = sb_rand(1, oltp_table_size) rs = db_query("SELECT SUM(K) FROM ".. table_name .." WHERE id BETWEEN " .. range_start .. " AND " .. range_start .. "+" .. oltp_range_size - 1) end if not oltp_read_only then -- just do a single update, we DO NOT want any deadlocks -- sbvalid allows us to keep track of what the running totals are by table c_val = sb_rand_str("###########-###########-###########-###########-###########-###########-###########-###########-###########-###########") inc_c1 = sb_rand_uniform(1, 32) inc_id = sb_rand(1, oltp_table_size) query1 = "UPDATE " .. table_name .. " SET k=k+1, c='" .. c_val .. "', c1=c1+ " .. inc_c1 .. " where id=" .. inc_id query2 = "insert into sbvalid (table_name,table_id,c1) values ('" .. table_name .. "'," .. inc_id .. "," .. inc_c1 .. ")" -- print(query1) rs=db_query(query1) if rs then -- based on the code, I'm not sure that you'd ever end up in here print(query1) end rs=db_query(query2) if rs then -- based on the code, I'm not sure that you'd ever end up in here print(query2) end end -- oltp_read_only db_query(commit_query) end
gpl-2.0
Percona-QA/toku-qa
tokudb/software/sysbench/sysbench-0.5/sysbench/tests/db/tokudb_oltp_valid.lua
4
2125
pathtest = string.match(test, "(.*/)") or "" dofile(pathtest .. "common.lua") function thread_init(thread_id) set_vars() if (db_driver == "mysql" and mysql_table_engine == "myisam") then begin_query = "LOCK TABLES sbtest WRITE" commit_query = "UNLOCK TABLES" else begin_query = "BEGIN" commit_query = "COMMIT" end end function event(thread_id) local rs local i local table_name local range_start local c_val local pad_val local query table_name = "sbtest".. sb_rand_uniform(1, oltp_tables_count) db_query(begin_query) -- do some point queries to keep busy for i=1, oltp_point_selects do rs = db_query("SELECT c FROM ".. table_name .." WHERE id=" .. sb_rand(1, oltp_table_size)) end -- do some sum queries to keep busy for i=1, oltp_sum_ranges do range_start = sb_rand(1, oltp_table_size) rs = db_query("SELECT SUM(K) FROM ".. table_name .." WHERE id BETWEEN " .. range_start .. " AND " .. range_start .. "+" .. oltp_range_size - 1) end if not oltp_read_only then -- just do a single update, we DO NOT want any deadlocks -- sbvalid allows us to keep track of what the running totals are by table c_val = sb_rand_str("###########-###########-###########-###########-###########-###########-###########-###########-###########-###########") inc_c1 = sb_rand_uniform(1, 32) inc_id = sb_rand(1, oltp_table_size) query1 = "UPDATE " .. table_name .. " SET k=k+1, c='" .. c_val .. "', c1=c1+ " .. inc_c1 .. " where id=" .. inc_id query2 = "insert into sbvalid (table_name,table_id,c1) values ('" .. table_name .. "'," .. inc_id .. "," .. inc_c1 .. ")" -- print(query1) rs=db_query(query1) if rs then -- based on the code, I'm not sure that you'd ever end up in here print(query1) end rs=db_query(query2) if rs then -- based on the code, I'm not sure that you'd ever end up in here print(query2) end end -- oltp_read_only db_query(commit_query) end
gpl-2.0
bmscoordinators/FFXI-Server
scripts/zones/Lufaise_Meadows/npcs/Teldo-Moroldo_WW.lua
14
3342
----------------------------------- -- Area: Lufaise Meadows -- NPC: Teldo-Moroldo, W.W. -- Outpost Conquest Guards -- @pos -542.418 -7.124 -53.521 24 ----------------------------------- package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Lufaise_Meadows/TextIDs"); local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = TAVNAZIANARCH; local csid = 0x7ff7; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
wingo/snabb
src/apps/lwaftr/test_phm_lookup.lua
2
1318
local ffi = require('ffi') local bit = require('bit') local phm = require("apps.lwaftr.podhashmap") local stream = require("apps.lwaftr.stream") local function test(rhh, count, active) print('lookup1 speed test (hits, uniform distribution)') print(count..' lookups, '..(active or count)..' active keys') local start = ffi.C.get_time_ns() local result for i = 1, count do if active then i = (i % active) + 1 end result = rhh:val_at(rhh:lookup(i))[0] end local stop = ffi.C.get_time_ns() local ns = tonumber(stop-start)/count print(ns..' ns/lookup (final result: '..result..')') end local function run(params) if #params < 1 or #params > 2 then error('usage: test_phm_lookup.lua FILENAME [ACTIVE]') end local filename, active = unpack(params) if active then active = assert(tonumber(active), 'active should be a number') assert(active == math.floor(active) and active > 0, 'active should be a positive integer') end local key_t, value_t = ffi.typeof('uint32_t'), ffi.typeof('int32_t[6]') print('loading saved file '..filename) local input = stream.open_input_byte_stream(filename) local rhh = phm.load(input, key_t, value_t, phm.hash_i32) test(rhh, rhh.occupancy, active) print("done") end run(main.parameters)
apache-2.0
mohammadrezatitan/maikel
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-3.0
blackops97/KING_TELE
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
zyhkz/waifu2x
lib/reconstruct.lua
2
10061
require 'image' local iproc = require 'iproc' local srcnn = require 'srcnn' local function reconstruct_nn(model, x, inner_scale, offset, block_size, batch_size) batch_size = batch_size or 1 if x:dim() == 2 then x = x:reshape(1, x:size(1), x:size(2)) end local ch = x:size(1) local new_x = torch.Tensor(x:size(1), x:size(2) * inner_scale, x:size(3) * inner_scale):zero() local input_block_size = block_size local output_block_size = block_size * inner_scale local output_size = output_block_size - offset * 2 local output_size_in_input = input_block_size - math.ceil(offset / inner_scale) * 2 local input_indexes = {} local output_indexes = {} for i = 1, x:size(2), output_size_in_input do for j = 1, x:size(3), output_size_in_input do if i + input_block_size - 1 <= x:size(2) and j + input_block_size - 1 <= x:size(3) then local index = {{}, {i, i + input_block_size - 1}, {j, j + input_block_size - 1}} local ii = (i - 1) * inner_scale + 1 local jj = (j - 1) * inner_scale + 1 local output_index = {{}, { ii , ii + output_size - 1 }, { jj, jj + output_size - 1}} table.insert(input_indexes, index) table.insert(output_indexes, output_index) end end end local input = torch.Tensor(batch_size, ch, input_block_size, input_block_size) local input_cuda = torch.CudaTensor(batch_size, ch, input_block_size, input_block_size) for i = 1, #input_indexes, batch_size do local c = 0 local output for j = 0, batch_size - 1 do if i + j > #input_indexes then break end input[j+1]:copy(x[input_indexes[i + j]]) c = c + 1 end input_cuda:copy(input) if c == batch_size then output = model:forward(input_cuda) else output = model:forward(input_cuda:narrow(1, 1, c)) end --output = output:view(batch_size, ch, output_size, output_size) for j = 0, c - 1 do new_x[output_indexes[i + j]]:copy(output[j+1]) end end return new_x end local reconstruct = {} function reconstruct.is_rgb(model) if srcnn.channels(model) == 3 then -- 3ch RGB return true else -- 1ch Y return false end end function reconstruct.offset_size(model) return srcnn.offset_size(model) end function reconstruct.has_resize(model) return srcnn.scale_factor(model) > 1 end function reconstruct.inner_scale(model) return srcnn.scale_factor(model) end local function padding_params(x, model, block_size) local p = {} local offset = reconstruct.offset_size(model) p.x_w = x:size(3) p.x_h = x:size(2) p.inner_scale = reconstruct.inner_scale(model) local input_offset = math.ceil(offset / p.inner_scale) local input_block_size = block_size local process_size = input_block_size - input_offset * 2 local h_blocks = math.floor(p.x_h / process_size) + ((p.x_h % process_size == 0 and 0) or 1) local w_blocks = math.floor(p.x_w / process_size) + ((p.x_w % process_size == 0 and 0) or 1) local h = (h_blocks * process_size) + input_offset * 2 local w = (w_blocks * process_size) + input_offset * 2 p.pad_h1 = input_offset p.pad_w1 = input_offset p.pad_h2 = (h - input_offset) - p.x_h p.pad_w2 = (w - input_offset) - p.x_w return p end function reconstruct.image_y(model, x, offset, block_size, batch_size) block_size = block_size or 128 local p = padding_params(x, model, block_size) x = iproc.padding(x, p.pad_w1, p.pad_w2, p.pad_h1, p.pad_h2) x = x:cuda() x = image.rgb2yuv(x) local y = reconstruct_nn(model, x[1], p.inner_scale, offset, block_size, batch_size) x = iproc.crop(x, p.pad_w1, p.pad_h1, p.pad_w1 + p.x_w, p.pad_h1 + p.x_h) y = iproc.crop(y, 0, 0, p.x_w, p.x_h):clamp(0, 1) x[1]:copy(y) local output = image.yuv2rgb(x):clamp(0, 1):float() x = nil y = nil collectgarbage() return output end function reconstruct.scale_y(model, scale, x, offset, block_size, batch_size) block_size = block_size or 128 local x_lanczos if reconstruct.has_resize(model) then x_lanczos = iproc.scale(x, x:size(3) * scale, x:size(2) * scale, "Lanczos") else x_lanczos = iproc.scale(x, x:size(3) * scale, x:size(2) * scale, "Lanczos") x = iproc.scale(x, x:size(3) * scale, x:size(2) * scale, "Box") end local p = padding_params(x, model, block_size) if p.x_w * p.x_h > 2048*2048 then collectgarbage() end x = iproc.padding(x, p.pad_w1, p.pad_w2, p.pad_h1, p.pad_h2) x = x:cuda() x = image.rgb2yuv(x) x_lanczos = image.rgb2yuv(x_lanczos) local y = reconstruct_nn(model, x[1], p.inner_scale, offset, block_size, batch_size) y = iproc.crop(y, 0, 0, p.x_w * p.inner_scale, p.x_h * p.inner_scale):clamp(0, 1) x_lanczos[1]:copy(y) local output = image.yuv2rgb(x_lanczos:cuda()):clamp(0, 1):float() x = nil x_lanczos = nil y = nil collectgarbage() return output end function reconstruct.image_rgb(model, x, offset, block_size, batch_size) block_size = block_size or 128 local p = padding_params(x, model, block_size) x = iproc.padding(x, p.pad_w1, p.pad_w2, p.pad_h1, p.pad_h2) if p.x_w * p.x_h > 2048*2048 then collectgarbage() end local y = reconstruct_nn(model, x, p.inner_scale, offset, block_size, batch_size) local output = iproc.crop(y, 0, 0, p.x_w, p.x_h):clamp(0, 1) x = nil y = nil collectgarbage() return output end function reconstruct.scale_rgb(model, scale, x, offset, block_size, batch_size) block_size = block_size or 128 if not reconstruct.has_resize(model) then x = iproc.scale(x, x:size(3) * scale, x:size(2) * scale, "Box") end local p = padding_params(x, model, block_size) x = iproc.padding(x, p.pad_w1, p.pad_w2, p.pad_h1, p.pad_h2) if p.x_w * p.x_h > 2048*2048 then collectgarbage() end local y y = reconstruct_nn(model, x, p.inner_scale, offset, block_size, batch_size) local output = iproc.crop(y, 0, 0, p.x_w * p.inner_scale, p.x_h * p.inner_scale):clamp(0, 1) x = nil y = nil collectgarbage() return output end function reconstruct.image(model, x, block_size) local i2rgb = false if x:size(1) == 1 then local new_x = torch.Tensor(3, x:size(2), x:size(3)) new_x[1]:copy(x) new_x[2]:copy(x) new_x[3]:copy(x) x = new_x i2rgb = true end if reconstruct.is_rgb(model) then x = reconstruct.image_rgb(model, x, reconstruct.offset_size(model), block_size) else x = reconstruct.image_y(model, x, reconstruct.offset_size(model), block_size) end if i2rgb then x = image.rgb2y(x) end return x end function reconstruct.scale(model, scale, x, block_size) local i2rgb = false if x:size(1) == 1 then local new_x = torch.Tensor(3, x:size(2), x:size(3)) new_x[1]:copy(x) new_x[2]:copy(x) new_x[3]:copy(x) x = new_x i2rgb = true end if reconstruct.is_rgb(model) then x = reconstruct.scale_rgb(model, scale, x, reconstruct.offset_size(model), block_size) else x = reconstruct.scale_y(model, scale, x, reconstruct.offset_size(model), block_size) end if i2rgb then x = image.rgb2y(x) end return x end local function tr_f(a) return a:transpose(2, 3):contiguous() end local function itr_f(a) return a:transpose(2, 3):contiguous() end local augmented_patterns = { { forward = function (a) return a end, backward = function (a) return a end }, { forward = function (a) return image.hflip(a) end, backward = function (a) return image.hflip(a) end }, { forward = function (a) return image.vflip(a) end, backward = function (a) return image.vflip(a) end }, { forward = function (a) return image.hflip(image.vflip(a)) end, backward = function (a) return image.vflip(image.hflip(a)) end }, { forward = function (a) return tr_f(a) end, backward = function (a) return itr_f(a) end }, { forward = function (a) return image.hflip(tr_f(a)) end, backward = function (a) return itr_f(image.hflip(a)) end }, { forward = function (a) return image.vflip(tr_f(a)) end, backward = function (a) return itr_f(image.vflip(a)) end }, { forward = function (a) return image.hflip(image.vflip(tr_f(a))) end, backward = function (a) return itr_f(image.vflip(image.hflip(a))) end } } local function get_augmented_patterns(n) if n == 1 then -- no tta return {augmented_patterns[1]} elseif n == 2 then return {augmented_patterns[1], augmented_patterns[5]} elseif n == 4 then return {augmented_patterns[1], augmented_patterns[5], augmented_patterns[2], augmented_patterns[7]} elseif n == 8 then return augmented_patterns else error("unsupported TTA level: " .. n) end end local function tta(f, n, model, x, block_size) local average = nil local offset = reconstruct.offset_size(model) local augments = get_augmented_patterns(n) for i = 1, #augments do local out = augments[i].backward(f(model, augments[i].forward(x), offset, block_size)) if not average then average = out else average:add(out) end end return average:div(#augments) end function reconstruct.image_tta(model, n, x, block_size) if reconstruct.is_rgb(model) then return tta(reconstruct.image_rgb, n, model, x, block_size) else return tta(reconstruct.image_y, n, model, x, block_size) end end function reconstruct.scale_tta(model, n, scale, x, block_size) if reconstruct.is_rgb(model) then local f = function (model, x, offset, block_size) return reconstruct.scale_rgb(model, scale, x, offset, block_size) end return tta(f, n, model, x, block_size) else local f = function (model, x, offset, block_size) return reconstruct.scale_y(model, scale, x, offset, block_size) end return tta(f, n, model, x, block_size) end end return reconstruct
mit
scummvm/scummvm
devtools/create_ultima/files/ultima6/scripts/se/lang/en/game.lua
19
3136
return { PASS="Pass!\n", YOU_SEE="you see %s", NOTHING="nothing!\n", SEARCHING_HERE_YOU_FIND="Searching here, you find %s", SEARCHING_HERE_YOU_FIND_NOTHING="Searching here, you find nothing.\n", SEARCH_NEXT_OBJ=", %s", SEARCH_LAST_OBJ=" and %s", OUT_OF_RANGE="Out of Range!\n", BLAH="Blah", CARRY_TOO_MUCH="You are carrying too much already.\n", GOT_CORN="You got some corn from the plant.\n", USE_CLAY="You shaped a small, soft pot from the clay.\n", USE_FISHING_POLE_NO_WATER="You need to stand next to deep water.\n", USE_FISHING_POLE_FAIL="You didn't get a fish.\n", USE_FISHING_POLE_SUCCESS="You caught a fish!\n", USE_DIGGING_STICK_NO_WATER="There is nothing to dig!\n", USE_DIGGING_STICK="You get some clay.\n", USE_YUCCA_PLANT="You got some flax from the yucca plant.\n", USE_TREE="You pulled a branch from the tree.\n", IMG1_TXT1_END="Members of all the tribes come for the feast... the largest and most important feast ever held in the Valley of Eodon.", IMG1_TXT2_END="Kurak sits beside Yolaru, Pindiro beside Barako, Haakur beside Sakkhra, and peace is sworn between the tribes.", IMG1_TXT3_END="You know this peace isn't for you. Soon enough, you will hear the call to action again. But tonight, there is time for music and dance, friendship and love.", IMG2_TXT1_END="At dawn, your past catches up with you... and your future beckons. A vision of Lord British appears before you.", IMG2_TXT2_END="\"You have done well,\" he says. \"But now I must take you where you are needed. For the sake of the friends you leave behind, I am sorry. Prepare yourself.\"", IMG3_TXT1_END="You say farewell to Aiela. \"Aiela does not know your world. Take her there,\" she pleads. \"Teach her of your world.", IMG3_TXT2_END="You shake your head. \"My world would strangle you. You must stay. My heart remains with you. But my duty is elsewhere... with him.\"", IMG3_TXT3_END="Tears roll down her cheeks. \"Abandon duty, and you will not be warrior Aiela loves. Choose duty, and you must leave. Either way, Aiela loses all... Farewell.\"", IMG4_TXT1_END="You say farewell to Tristia. \"I must go with Lord British,\" you say. \"My duty lies with him, though it breaks my heart.\"", IMG4_TXT2_END="Tristia laughs sweetly. \"Tristia does not mind,\" she says. \"Tristia has found another loves: handsome Botorok. Botorok is so much better than you. Go with your chief. Go.\"", IMG5_TXT1_END="You are joined by Spector's former assistant, Fritz, who came out of hiding to fight the Myrmidex, and bears their scars.", IMG5_TXT2_END="The moongate appears, summoned by the shade of Lord British. Jimmy, Spector and Fritz gather their belongs...", IMG5_TXT3_END="But Rafkin does not. \"I'm staying, my friend,\" he says, \"Someone must. I will stay here... and hope other scientists come. Farewell.\"", IMG5_TXT4_END="Saddened, you follow your friends and allies into the moongate, leaving the Valley of Eodon. Perhaps someday you will return to those you have left behind.", IMG2_TXT3_END="CONGRATULATIONS. You have completed THE SAVAGE EMPIRE in XXTIMESTRXX. Communicate your success to Lord British at Origin!", }
gpl-3.0
bmscoordinators/FFXI-Server
scripts/globals/spells/bluemagic/cannonball.lua
33
1721
----------------------------------------- -- Spell: Cannonball -- Damage varies with TP -- Spell cost: 66 MP -- Monster Type: Vermin -- Spell Type: Physical (Blunt) -- Blue Magic Points: 3 -- Stat Bonus: STR+1, DEX+1 -- Level: 70 -- Casting Time: 0.5 seconds -- Recast Time: 28.5 seconds -- Skillchain Element(s): Fusion (can open/close Light with Fragmentation WSs and spells) -- Combos: None ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_DAMAGE; params.dmgtype = DMGTYPE_H2H; params.scattr = SC_FUSION; params.numhits = 1; params.multiplier = 1.75; params.tp150 = 2.125; params.tp300 = 2.75; params.azuretp = 2.875; params.duppercap = 75; params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.offcratiomod = caster:getStat(MOD_DEF); damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
nsimplex/wicker
utils/table/tree/dfs.lua
6
3406
--[[ Copyright (C) 2013 simplex 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, see <http://www.gnu.org/licenses/>. ]]-- local Tree = pkgrequire 'core' local Lambda = wickerrequire 'paradigms.functional' local Logic = wickerrequire 'lib.logic' local Pred = wickerrequire 'lib.predicates' -- It actually works for arbitrary table graphs. -- The return list consists of a metadata table -- followed by the node value. function Iterator(r, revisit_fn) local function new_empty_data() local ret = {} ret.branch = {} ret.visited = setmetatable({}, {__mode = 'k'}) ret.is_initial = true -- Convenience functions. ret.branchTop = Lambda.StackGetter( ret.branch ) ret.branchPop = Lambda.StackPopper( ret.branch ) ret.branchPush = Lambda.StackPusher( ret.branch ) ret.branchTopOrEmpty = function() return ret.branchTop() or {} end ret.t = function(t) local top = ret.branchTop() if top then if t ~= nil then assert( Tree.IsTree(t) ) top.t = t end return top.t end end ret.parent_k = function() return ret.branchTopOrEmpty().parent_k end ret.k = function(k) local top = ret.branchTop() if top then if k ~= nil then top.k = k end return top.k end end ret.v = function(v) local top = ret.branchTop() if top and top.k ~= nil then if v ~= nil then top.t[top.k] = v end return top.t[top.k] end end ret.subroot = ret.t ret.branchGetAt = function(i) if i < 0 then i = #ret.branch + i + 1 end return ret.branch[i] end return ret end local function initialize_data(data, s) assert( data.is_initial ) data.is_initial = nil table.insert(data.branch, {t = s.root, parent_k = nil, k = nil}) return data end if Tree.IsSingletonIfTree(r) then return Lambda.iterator.SingletonList(new_empty_data(), r) end local s = {root = r} assert( Tree.IsTree(s.root) ) local function f(s, data) if not data then data = new_empty_data() return data, s.root elseif data.is_initial then data = initialize_data(data, s) end local t, k = data.t(), data.k() assert( Tree.IsTree(t) ) k = next(t, k) while k == nil do data.branchPop() if not data.branchTop() then return nil end t = data.t() k = next(t, data.k()) end data.k(k) --local branch_keys = Lambda.CompactlyMap(function(n) return tostring(n.k) end, ipairs(data.branch)) --print( 'Current branch: ' .. table.concat( branch_keys, ', ') ) local v = data.v() if Tree.IsTree(v) then if data.visited[v] and not (revisit_fn and revisit_fn(v, data)) then -- Tail call. return f(s, data) end data.visited[v] = true if not Tree.IsSingleton(v) then data.branchPush( {t = v, parent_k = k} ) end end return data, v end return f, s, nil end return Lambda.GenerateConceptsFromIteration( Iterator, _M )
gpl-2.0
cheney247689848/Cloud-edge
Assets/ToLua/Lua/UnityEngine/Touch.lua
6
1991
-------------------------------------------------------------------------------- -- Copyright (c) 2015 - 2016 , 蒙占志(topameng) topameng@gmail.com -- All rights reserved. -- Use, modification and distribution are subject to the "MIT License" -------------------------------------------------------------------------------- local zero = Vector2.zero local rawget = rawget local setmetatable = setmetatable TouchPhase = { Began = 0, Moved = 1, Stationary = 2, Ended = 3, Canceled = 4, } TouchBits = { DeltaPosition = 1, Position = 2, RawPosition = 4, ALL = 7, } local TouchPhase = TouchPhase local TouchBits = TouchBits local Touch = {} local get = tolua.initget(Touch) Touch.__index = function(t,k) local var = rawget(Touch, k) if var == nil then var = rawget(get, k) if var ~= nil then return var(t) end end return var end --c# 创建 function Touch.New(fingerId, position, rawPosition, deltaPosition, deltaTime, tapCount, phase) return setmetatable({fingerId = fingerId or 0, position = position or zero, rawPosition = rawPosition or zero, deltaPosition = deltaPosition or zero, deltaTime = deltaTime or 0, tapCount = tapCount or 0, phase = phase or 0}, Touch) end function Touch:Init(fingerId, position, rawPosition, deltaPosition, deltaTime, tapCount, phase) self.fingerId = fingerId self.position = position self.rawPosition = rawPosition self.deltaPosition = deltaPosition self.deltaTime = deltaTime self.tapCount = tapCount self.phase = phase end function Touch:Destroy() self.position = nil self.rawPosition = nil self.deltaPosition = nil end function Touch.GetMask(...) local arg = {...} local value = 0 for i = 1, #arg do local n = TouchBits[arg[i]] or 0 if n ~= 0 then value = value + n end end if value == 0 then value = TouchBits["all"] end return value end UnityEngine.TouchPhase = TouchPhase UnityEngine.Touch = Touch setmetatable(Touch, Touch) return Touch
mit