content
stringlengths
5
1.05M
local dataTypes = {} local function serializedValue(type, value) return { _serialized_type = type, value = value, } end local function parseValueForDeserialization(value) if typeof(value) ~= "table" then return end if not value._serialized_type then return end return value.value end dataTypes = { ["Color3"] = { serialize = function(value: Color3) return serializedValue("Color3", {value:ToHSV()}) end, deserialize = function(value) value = parseValueForDeserialization(value) return Color3.fromHSV(unpack(value)) end, }, ["BrickColor"] = { serialize = function(value: BrickColor) return serializedValue("BrickColor", tostring(value)) end, deserialize = function(value) value = parseValueForDeserialization(value) return BrickColor.new(value) end, }, ["Vector3"] = { serialize = function(value: Vector3) return serializedValue("Vector3", {value.X, value.Y, value.Z}) end, deserialize = function(value) value = parseValueForDeserialization(value) return Vector3.new(value.X, value.Y, value.Z) end, }, ["Vector2"] = { serialize = function(value: Vector2) return serializedValue("Vector2", {value.X, value.Y}) end, deserialize = function(value) value = parseValueForDeserialization(value) return Vector2.new(value.X, value.Y) end, }, ["CFrame"] = { serialize = function(value: CFrame) return serializedValue("CFrame", { pos = dataTypes.Vector3.serialize(value.Position), rX = dataTypes.Vector3.serialize(value.RightVector), rY = dataTypes.Vector3.serialize(value.UpVector), rZ = dataTypes.Vector3.serialize(-value.LookVector), }) end, deserialize = function(value) value = parseValueForDeserialization(value) return CFrame.fromMatrix( dataTypes.Vector3.deserialize(value.pos), dataTypes.Vector3.deserialize(value.rX), dataTypes.Vector3.deserialize(value.rY), dataTypes.Vector3.deserialize(value.rZ) ) end, }, ["EnumItem"] = { serialize = function(value: Enum) local s = string.split(tostring(value), ".") return serializedValue("EnumItem", {s[2], s[3]}) end, deserialize = function(value) value = parseValueForDeserialization(value) return Enum[value[1]][value[2]] end, } } return dataTypes
description=[[ Discovers hosts and routing information from devices running RIPv2 on the LAN. It does so by sending a RIPv2 Request command and collects the responses from all devices responding to the request. ]] --- -- @usage -- nmap --script broadcast-rip-discover -- -- @output -- Pre-scan script results: -- | broadcast-rip-discover: -- | Discovered RIPv2 devices -- | 10.0.200.107 -- | ip netmask nexthop metric -- | 10.46.100.0 255.255.255.0 0.0.0.0 1 -- | 10.46.110.0 255.255.255.0 0.0.0.0 1 -- | 10.46.120.0 255.255.255.0 0.0.0.0 1 -- | 10.46.123.0 255.255.255.0 10.0.200.123 1 -- | 10.46.124.0 255.255.255.0 10.0.200.124 1 -- | 10.46.125.0 255.255.255.0 10.0.200.125 1 -- | 10.0.200.101 -- | ip netmask nexthop metric -- |_ 0.0.0.0 0.0.0.0 10.0.200.1 1 -- -- @args broadcast-rip-discover.timeout sets the timeout in seconds to wait for -- a response. -- -- Version 0.1 -- Created 29/10/2011 - v0.1 - created by Patrik Karlsson <patrik@cqure.net> -- author = "Patrik Karlsson" license = "Same as Nmap--See http://nmap.org/book/man-legal.html" categories = {"broadcast", "safe"} require 'bin' require 'ipOps' require 'tab' prerule = function() return not( nmap.address_family() == "inet6") end RIPv2 = { Command = { Request = 1, Response = 2, }, AddressFamily = { IP = 2, }, -- The Request class contains functions to build a RIPv2 Request Request = { -- Creates a new Request instance -- -- @param command number containing the RIPv2 Command to use -- @return o instance of request new = function(self, command) local o = { version = 2, command = command, domain = 0, family = 0, tag = 0, address = 0, subnet = 0, nexthop = 0, metric = 16 } setmetatable(o, self) self.__index = self return o end, -- Converts the whole request to a string __tostring = function(self) assert(self.command, "No command was supplied") assert(self.metric, "No metric was supplied") assert(self.address, "No address was supplied") local RESERVED = 0 -- RIPv2 stuff, should be 0 for RIPv1 local tag, subnet, nexthop = 0, 0, 0 local data = bin.pack(">CCSSSIIII", self.command, self.version, self.domain, self.family, self.tag, self.address, self.subnet, self.nexthop, self.metric) return data end, }, -- The Response class contains code needed to parse a RIPv2 response Response = { -- Creates a new Response instance based on raw socket data -- -- @param data string containing the raw socket response -- @return o Response instance new = function(self, data) local o = { data = data } if ( not(data) or #data < 3 ) then return end local pos pos, o.command, o.version = bin.unpack(">CCS", data) if ( o.command ~= RIPv2 and o.version ~= 2 ) then return end local routes = tab.new(2) tab.addrow(routes, "ip", "netmask", "nexthop", "metric") while( #data - pos >= 20 ) do local family, address, metric, _ pos, family, _, address, netmask, nexthop, metric = bin.unpack(">SS<III>I", data, pos) if ( family == RIPv2.AddressFamily.IP ) then local ip = ipOps.fromdword(address) netmask = ipOps.fromdword(netmask) nexthop = ipOps.fromdword(nexthop) tab.addrow(routes, ip, netmask, nexthop, metric) end end if ( #routes > 1 ) then o.routes = routes end setmetatable(o, self) self.__index = self return o end, } } action = function() local timeout = stdnse.get_script_args('broadcast-rip-discover.timeout') timeout = (timeout and tonumber(timeout) * 1000) or 5000 local socket = nmap.new_socket("udp") socket:set_timeout(timeout) local rip = RIPv2.Request:new(RIPv2.Command.Request) local status, err = socket:sendto("224.0.0.9", { number = 520, protocol = "udp" }, tostring(rip)) local result = {} repeat local data status, data = socket:receive() if ( status ) then local status, _, _, rhost, _ = socket:get_info() local response = RIPv2.Response:new(data) table.insert(result, rhost) if ( response and response.routes and #response.routes > 0 ) then --response.routes.name = "Routes" table.insert(result, { tab.dump(response.routes) } ) end end until( not(status) ) if ( #result > 0 ) then result.name = "Discovered RIPv2 devices" end return stdnse.format_output(true, result) end
-- Assumes pwd is same as this script's directory function modifyPlist( options ) local baseName = options.dstFile; local appBundleFile = options.dstDir .. "/" .. baseName .. ".app" print( "modifying plist: " .. appBundleFile .. " using name: " .. baseName ) os.execute( "defaults write "..appBundleFile.."/Contents/Info CFBundleExecutable "..options.bundlename ) os.execute( "defaults write "..appBundleFile.."/Contents/Info CFBundleIdentifier "..options.appid ) os.execute( "defaults write "..appBundleFile.."/Contents/Info CFBundleName ".. "\"Corona Simulator\"" ) -- os.execute( "defaults write "..appBundleFile.."/Contents/Info CFBundleIconFile "..options.bundlename..".icns" ) end function packageApp( options ) local baseName = options.dstFile; local appBundleFile = options.dstDir .. "/" .. baseName .. ".app" os.execute( "ditto -X " .. options.binDir .. "/template.app " .. appBundleFile ) os.execute( "mv " .. appBundleFile .. "/Contents/MacOS/template " .. appBundleFile .. "/Contents/MacOS/" .. baseName ) modifyPlist( options ) --[[ if ( options.iconFile ) then local srcDir = options.srcAssets local dstDir = options.dstDir os.execute( "sips -z 48 48 s -s format tiff " .. srcDir .. "/Icon.png --out " .. dstDir .. "/Icon.tiff" ) os.execute( "tiff2icns -noLarge " .. dstDir .. "/Icon.tiff" ) os.execute( "rm -f " .. dstDir .. "/Icon.tiff" ) end --]] local runScript = "bash " if ( options.verbose ) then -- runScript = runScript .. "-x " end local dstDir = appBundleFile .. "/Contents/Resources" local binDir = options.binDir -- Replace ditto with CopyResources.sh and BuildSources.sh calls os.execute( runScript .. binDir .. "/CopyResources.sh release "..options.srcAssets.." "..dstDir .. " --preserve" ) os.execute( runScript .. binDir .. "/BuildSources.sh release "..options.srcAssets.." "..dstDir ) os.execute( "/usr/bin/codesign -f -s rttplayer " .. appBundleFile ) os.execute( "chmod 755 " .. appBundleFile ) end function usage( arg0 ) print( "USAGE" ) print( "\t" .. arg0 .. " -a bin_dir -d appid.bundleid [options] src_dir dst_dir " ) print( "" ) print( "DESCRIPTION" ) print( "\tThe parameter 'src_dir' is the path to the assets used by the app." ) print( "\tAt a minimum, it must include a file called 'main.lua'" ) print( "\tThe parameter 'dst_dir' is the folder where the built app will be." ) print( "\tfile assigned to the developer." ) print( "" ) print( "OPTIONS" ) print( "\t-q quiet mode (suppresses output)" ) print( "\t-i file.png png file to be used as application icon" ) print( "" ) print( "EXAMPLES" ) print( "\t" .. arg0 .. " -a ../bin/mac -d com.mycompany.nameofapp path/to/assets/dir" ) error( "" ) end function parseOptions( argv ) local result = { verbose = true } -- NOTE: argv is 0-based!!! local argc = #argv -- skip argv[0] local i = 1 if ( argc < 2 ) then usage( argv[0] ) end while i <= argc do local arg = argv[i] local key = nil local switchString = string.sub( arg, 1, 2 ) if ( switchString == "-a" ) then assert( (i + 1) <= argc ) i = i + 1 local value = argv[i] result.binDir = argv[i] elseif ( switchString == "-d" ) then assert( (i + 1) <= argc ) i = i + 1 local value = argv[i] result.appid = value result.bundleid = string.match( value, "[^%.]+%.(.*)" ) local name = string.match( result.bundleid, "^.*%.([^%.]+)$" ) if ( nil == name ) then name = result.bundleid end result.bundlename = name result.bundledisplayname = name result.bundleexecutable = name result.dstFile = name elseif ( switchString == "-q" ) then result.verbose = false elseif ( switchString == "-i" ) then assert( (i + 1) <= argc ) i = i + 1 local value = argv[i] result.iconFile = value; assert( string.match( value, "^.*%.([^%.]+)$" ) == "png" ) elseif ( nil == result.srcAssets ) then result.srcAssets = argv[i] elseif ( nil == result.dstDir ) then result.dstDir = argv[i] else usage( argv[0] ) end i = i + 1 end if ( result.verbose ) then print( "Using displayname: " .. result.bundledisplayname ) print( "Using bundlename " .. result.bundlename ) print( "Using bundleid: " .. result.bundleid ) print( "Using appid: " .. result.appid ) print( "Using icon file: " .. tostring( result.iconFile ) ) print( "Using source assets dir: " .. result.srcAssets ) print( "Using dst dir: " .. result.dstDir ) print( "Using bin dir: " .. result.binDir ) end return result end local options = parseOptions( arg ) packageApp( options )
function onCreate() for i = 0, getProperty('unspawnNotes.length')-1 do if getPropertyFromGroup('unspawnNotes', i, 'noteType') == 'Carmen Note' then setPropertyFromGroup('unspawnNotes', i, 'texture', 'Carmen Note'); --Change the note texture if getPropertyFromGroup('unspawnNotes', i, 'mustPress') then setPropertyFromGroup('unspawnNotes', i, 'ignoreNote', false); --Miss has no penalties end end end end -- Called after the note miss calculations -- Player missed a note by letting it go offscreen function noteMiss(id, noteData, noteType, isSustainNote) if noteType == 'Carmen Note' then -- put something here if you want setProperty('health',-500) end end
-- note mlh: commented out during migration to endpoint... Load calls will need to support callback if this code is to be reinstated -- local sessions = {} -- local getSteamIdConnectedTimeInSeconds = function(steamId) -- local player = TGNS.GetPlayerMatchingSteamId(steamId) -- local client = TGNS.GetClient(player) -- local result = TGNSConnectedTimesTracker.GetClientConnectedTimeInSeconds(client) -- return result -- end -- local sessionBoundOnDataLoaded = function(data, onDataLoaded) -- if data.sessionId == nil or data.steamId == nil or data.sessionId ~= getSteamIdConnectedTimeInSeconds(data.steamId) then -- data = {} -- end -- return onDataLoaded(data) -- end -- TGNSSessionDataRepository = {} -- TGNSSessionDataRepository.Create = function(dataTypeName, onDataLoaded) -- local dr = TGNSDataRepository.Create(dataTypeName, function(data) sessionBoundOnDataLoaded(data, onDataLoaded) end, function(recordId) return string.format("%s-session", recordId) end) -- local result = {} -- result.Save = function(self, data) -- dr.Save(data, data.steamId) -- sessions[data.steamId] = data -- end -- result.Load = function(self, steamId) -- local data = sessions[steamId] or dr.Load(steamId) -- data.steamId = data.steamId or steamId -- data.sessionId = data.sessionId or getSteamIdConnectedTimeInSeconds(steamId) -- return data -- end -- return result -- end
return {'vtje','vtjes'}
function getAny(param, func, size) local retVal = func(resiot_baslice(param.bytes, param.position, param.position + size)) param.position = param.position + size return retVal end function setValue(appeui, deveui, name, value) worked, err = resiot_setnodevalue(appeui, deveui, name, value) if (not worked) then resiot_debug(string.format("Set Value Error %s \n", err)) else resiot_debug(string.format("Tag %s set to %s \n", name, value)) end end function getInt32(param) return getAny(param, resiot_ba2sintBE32, 4) end function getUInt32(param) return getAny(param, resiot_ba2intBE32, 4) end function getFloat(param) return getAny(param, resiot_ba2float32BE, 4) end function getChar(param) return getAny(param, resiot_ba2str, 1) end function parsePayload(appeui,deveui,payload) lat = "Latitude" lon = "Longitude" moist = "Moisture" light = "Light" temp = "Temperature" hum = "Humidity" rgb = "RGB" acc_x = "ACC_x" values = resiot_hexdecode(payload) p = {bytes=bytes, position=0} setValue(appeui,deveui, lat, getFloat(p)) setValue(appeui, deveui, lon, getFloat(p)) setValue(appeui, deveui, light, getFloat(p)) setValue(appeui, deveui, moist, getFloat(p)) setValue(appeui, deveui, temp , getInt32(p)) setValue(appeui, deveui, hum , getUInt32(p)) color_char = getChar(p) setValue(appeui, deveui, moist, getFloat(p)) if colotChar == "R" then setValue(appeui, deveui, "Color", "Red") elseif colotChar == "G" then setValue(appeui, deveui, "Color", "Green") elseif colotChar == "B" then setValue(appeui, deveui, "Color", "Blue") elseif colotChar == "C" then setValue(appeui, deveui, "Color", "Clear") end end Origin = resiot_startfrom() --Scene process starts here --Manual script execution for testing if Origin == "Manual" then payload = "ceaa21420f0b6d400000000000000000f2440000cb9b000066259561" --Set your test payload here in hexadecimal appeui = "f31c2e8bc671281d5116f08ff0b7928f" --Set your Application EUI here deveui = "7139323559379194" --Set your own Device EUI here -- Normal execution, get payload received from device else appeui = resiot_comm_getparam("appeui") deveui = resiot_comm_getparam("deveui") payload, err = resiot_getlastpayload(appeui, deveui) end --Do your stuff parsePayload(appeui,deveui,payload)
logs = { EXP_MAX = 1e10, EXP_MIN = 1e-10, LOG_ZERO = -1e10, LOG_INF = 1e10 } logs.EXP_LIMIT = math.log(logs.EXP_MAX) function logs.safe_log(x) if x == 0 then return logs.LOG_ZERO elseif x > 0 then return math.log(x) else error("passing a negtive number to the log function.") end end function logs.safe_exp(x) if x == logs.LOG_ZERO then return 0 end if x >= logs.EXP_LIMIT then return logs.EXP_MAX end return math.exp(x) end function logs.log_add(x, y) if math.abs(x - y) > 10 then return math.max(x, y) end if x < y then return y + math.log(1.0 + logs.safe_exp(x - y)) else return x + math.log(1.0 + logs.safe_exp(y - x)) end end function logs.log_sub(x, y) if y == logs.LOG_ZERO then return x end if y >= x then return logs.LOG_ZERO end return x + math.log(1.0 - logs.safe_exp(y - x)) end function logs.log_mul(x, y) if y == logs.LOG_ZERO or x == logs.LOG_ZERO then return logs.LOG_ZERO end return x + y end function logs.log_div(x, y) if x == logs.LOG_ZERO then return logs.LOG_ZERO end if y == logs.LOG_ZERO then return logs.LOG_INF end return x - y end function logs.log_sum(...) local arg = table.pack(...) if arg["n"] == 1 then return arg[1] end local max = math.max(unpack(arg)) local result = 0.0 for i, v in ipairs(arg) do result = result + logs.safe_exp(v - max) end result = max + logs.safe_log(result) return result end
local outColor = color("#00326B") local lang = "us"; if THEME:GetCurLanguage() == "ja" then lang = "jp"; end; local t = Def.ActorFrame{ LoadActor(lang.."_bg")..{ InitCommand=cmd(Center;); }; } return t;
----------------------------------- -- Area: Temenos E T -- Mob: Light Elemental ----------------------------------- local ID = require("scripts/zones/Temenos/IDs") function onMobEngaged(mob, target) local mobID = mob:getID() if mobID == ID.mob.TEMENOS_C_MOB[2]+1 then GetMobByID(ID.mob.TEMENOS_C_MOB[2]+2):updateEnmity(target) GetMobByID(ID.mob.TEMENOS_C_MOB[2]):updateEnmity(target) elseif mobID == ID.mob.TEMENOS_C_MOB[2]+2 then GetMobByID(ID.mob.TEMENOS_C_MOB[2]+1):updateEnmity(target) GetMobByID(ID.mob.TEMENOS_C_MOB[2]):updateEnmity(target) end end function onMobDeath(mob, player, isKiller, noKiller) if isKiller or noKiller then switch (mob:getID()): caseof { [ID.mob.TEMENOS_C_MOB[2]+1] = function() if GetMobByID(ID.mob.TEMENOS_C_MOB[2]):isDead() and GetMobByID(ID.mob.TEMENOS_C_MOB[2]+2):isDead() then GetNPCByID(ID.npc.TEMENOS_C_CRATE[2]):setStatus(tpz.status.NORMAL) end end, [ID.mob.TEMENOS_C_MOB[2]+2] = function() if GetMobByID(ID.mob.TEMENOS_C_MOB[2]):isDead() and GetMobByID(ID.mob.TEMENOS_C_MOB[2]+1):isDead() then GetNPCByID(ID.npc.TEMENOS_C_CRATE[2]):setStatus(tpz.status.NORMAL) end end, } end end
-- -- Public domain -- local socket = require("socket") local ssl = require("ssl") local util = require("util") local params = { mode = "server", protocol = "tlsv1", key = "../certs/serverAkey.pem", certificate = "../certs/serverA.pem", cafile = "../certs/rootA.pem", verify = {"peer", "fail_if_no_peer_cert"}, options = {"all", "no_sslv2"}, } local ctx = assert(ssl.newcontext(params)) local server = socket.tcp() server:setoption('reuseaddr', true) assert( server:bind("127.0.0.1", 8888) ) server:listen() local conn = server:accept() conn = assert( ssl.wrap(conn, ctx) ) assert( conn:dohandshake() ) util.show( conn:getpeercertificate() ) print("----------------------------------------------------------------------") for k, cert in ipairs( conn:getpeerchain() ) do util.show(cert) end local f = io.open(params.certificate) local str = f:read("*a") f:close() util.show( ssl.loadcertificate(str) ) print("----------------------------------------------------------------------") local cert = conn:getpeercertificate() print( cert ) print( cert:digest() ) print( cert:digest("sha1") ) print( cert:digest("sha256") ) print( cert:digest("sha512") ) conn:close() server:close()
--[[ Copyright 2017 wrxck <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]] local unicode = {} local mattata = require('mattata') local json = require('dkjson') function unicode:init() unicode.commands = mattata.commands( self.info.username ):command('unicode').table unicode.help = [[/unicode <text> - Returns the given text as a JSON-encoded table of Unicode (UTF-32) values.]] end function unicode:on_message(message) local input = mattata.input(message.text) if not input then return mattata.send_reply( message, unicode.help ) end input = tostring(input) local res = {} local seq = 0 local val = nil for i = 1, #input do local char = input:byte(i) if seq == 0 then table.insert( res, val ) seq = char < 0x80 and 1 or char < 0xE0 and 2 or char < 0xF0 and 3 or char < 0xF8 and 4 or error('invalid UTF-8 character sequence') val = bit32.band( char, 2 ^ (8 - seq) - 1 ) else val = bit32.bor( bit32.lshift( val, 6 ), bit32.band( char, 0x3F ) ) end seq = seq - 1 end table.insert( res, val ) return mattata.send_message( message.chat.id, '<pre>' .. json.encode(res) .. '</pre>', 'html' ) end return unicode
local Y = require("yalg.yalg") local SaveRestore = require("src.SaveRestore") local Highscores = require("src.Highscores") local L = require("src.Local") local S = require("src.menu.options.styles") ------------------ -- DELETE SAVES -- ------------------ local DelSaves = Y.Switcher( Y.HDiv( Y.Button(L["no"], S.OffBTN, "noDelSavesBtn"), Y.Label(L["sure"], S.NL), Y.Button(L["yes"], S.OnBTN, "delSavesBtn"), {}, "delSavesHDiv" ), Y.Button(L["delSaves"], S.NB, "delSavesMenuBtn"), {}, "delSavesSwitcher" ) -- menu button function DelSaves.widgets.delSavesMenuBtn.style:click() self:getWidget("delSavesSwitcher").selected = "delSavesHDiv" end -- no button function DelSaves.widgets.noDelSavesBtn.style:click() self:getWidget("delSavesSwitcher").selected = "delSavesMenuBtn" end -- yes button function DelSaves.widgets.delSavesBtn.style:click() SaveRestore.remove("normal") SaveRestore.remove("timed") self:getWidget("delSavesSwitcher").selected = "delSavesMenuBtn" end ----------------------- -- Delete highscores -- ----------------------- local DelHS = Y.Switcher( Y.HDiv( Y.Button(L["no"], S.OffBTN, "noDelHSBtn"), Y.Label(L["sure"], S.NL), Y.Button(L["yes"], S.OnBTN, "delHSBtn"), {}, "delHSHDiv" ), Y.Button(L["delHS"], S.NB, "delHSMenuBtn"), {}, "delHSSwitcher" ) -- menu button function DelHS.widgets.delHSMenuBtn.style:click() self:getWidget("delHSSwitcher").selected = "delHSHDiv" end -- no button function DelHS.widgets.noDelHSBtn.style:click() self:getWidget("delHSSwitcher").selected = "delHSMenuBtn" end -- yes button function DelHS.widgets.delHSBtn.style:click() Highscores.delete() self:getWidget("highscores"):loadHighscores() self:getWidget("delHSSwitcher").selected = "delHSMenuBtn" end ------------------ -- OPTIONS PAGE -- ------------------ local Page = Y.VDiv( Y.Label(L["gamedata"], S.LS), DelSaves, DelHS, {slots = 6}, "optionsPage3" ) return Page
object_tangible_loot_creature_loot_generic_generic_heart = object_tangible_loot_creature_loot_generic_shared_generic_heart:new { } ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_generic_generic_heart, "object/tangible/loot/creature_loot/generic/generic_heart.iff")
local PlayerJob = {} local isLoggedIn = false local isInMenu = false local sleep RegisterNetEvent('QBCore:Client:OnPlayerLoaded') AddEventHandler('QBCore:Client:OnPlayerLoaded', function() isLoggedIn = true PlayerJob = QBCore.Functions.GetPlayerData().job end) RegisterNetEvent('QBCore:Client:OnPlayerUnload') AddEventHandler('QBCore:Client:OnPlayerUnload', function() isLoggedIn = false end) RegisterNetEvent('QBCore:Client:OnJobUpdate') AddEventHandler('QBCore:Client:OnJobUpdate', function(JobInfo) PlayerJob = JobInfo end) -- MENU local menu = MenuV:CreateMenu(false, 'Boss Menu', 'topright', 155, 0, 0, 'size-125', 'none', 'menuv', 'main') local menu2 = MenuV:CreateMenu(false, 'Society money', 'topright', 155, 0, 0, 'size-125', 'none', 'menuv', 'society') local menu3 = MenuV:CreateMenu(false, 'Employee Management', 'topright', 155, 0, 0, 'size-125', 'none', 'menuv', 'employees') local menu4 = MenuV:CreateMenu(false, 'Recruit Menu', 'topright', 155, 0, 0, 'size-125', 'none', 'menuv', 'recruit') RegisterNetEvent('qb-bossmenu:client:openMenu') AddEventHandler('qb-bossmenu:client:openMenu', function() for k, v in pairs(Config.Jobs) do if k == PlayerJob.name and PlayerJob.isboss then MenuV:OpenMenu(menu) end end end) local menu_button = menu:AddButton({ icon = '📋', label = 'Employees', value = menu3, description = 'Manage Employees' }) local menu_button1 = menu:AddButton({ icon = '🤝', label = 'Recruit', value = menu4, description = 'Hire New Players' }) local menu_button2 = menu:AddButton({ icon = '📦', label = 'Storage', value = nil, description = 'Personal Storage' }) local menu_button3 = menu:AddButton({ icon = '👕', label = 'Outfits', value = nil, description = 'View Outfits' }) local menu_button4 = menu:AddButton({ icon = '💰', label = 'Society Money', value = menu2, description = 'View/Manage Society Money' }) local menu_button5 = menu2:AddButton({ icon = '💲', label = '', value = nil, description = 'Current Society Amount' }) local menu_button6 = menu2:AddButton({ icon = '🤑', label = 'Withdraw', value = menu2, description = 'Withdraw Money From Society' }) local menu_button7 = menu2:AddButton({ icon = '🏦', label = 'Deposit', value = menu2, description = 'Deposit Money Into Society' }) -- Storage menu_button2:On("select", function() MenuV:CloseMenu(menu) TriggerServerEvent("inventory:server:OpenInventory", "stash", "boss_" .. PlayerJob.name, { maxweight = 4000000, slots = 500, }) TriggerEvent("inventory:client:SetCurrentStash", "boss_" .. PlayerJob.name) end) -- Outfit menu_button3:On("select", function() MenuV:CloseMenu(menu) TriggerEvent('qb-clothing:client:openOutfitMenu') end) -- Society menu_button4:On('select', function() UpdateSociety() end) -- Withdraw menu_button6:On("select", function() local result = LocalInput('Withdrawal Amount', 255, '') if result ~= nil then TriggerServerEvent("qb-bossmenu:server:withdrawMoney", tonumber(result)) UpdateSociety() end end) -- Deposit menu_button7:On("select", function() local result = LocalInput('Deposit Amount', 255, '') if result ~= nil then TriggerServerEvent("qb-bossmenu:server:depositMoney", tonumber(result)) UpdateSociety() end end) -- Employees menu_button:On("select", function() menu3:ClearItems() QBCore.Functions.TriggerCallback('qb-bossmenu:server:GetEmployees', function(cb) for k,v in pairs(cb) do local menu_button8 = menu3:AddButton({ label = v.grade.name.. ' ' ..v.name, value = v, description = 'Employee', select = function(btn) local select = btn.Value ManageEmployees(select) end }) end end, PlayerJob.name) end) -- Recruit menu_button1:On("select", function() menu4:ClearItems() local playerPed = PlayerPedId() for k,v in pairs(QBCore.Functions.GetPlayersFromCoords(GetEntityCoords(playerPed), 10.0)) do if v and v ~= PlayerId() then local menu_button10 = menu4:AddButton({ label = GetPlayerName(v), value = v, description = 'Available Recruit', select = function(btn) local select = btn.Value TriggerServerEvent('qb-bossmenu:server:giveJob', GetPlayerServerId(v)) end }) end end end) -- MAIN THREAD CreateThread(function() while true do sleep = 1000 if PlayerJob.name ~= nil then local pos = GetEntityCoords(PlayerPedId()) for k, v in pairs(Config.Jobs) do if k == PlayerJob.name and PlayerJob.isboss then if #(pos - v) < 1.0 then inRange = true DrawText3D(v, "~g~E~w~ - Boss Menu") if IsControlJustReleased(0, 38) then MenuV:OpenMenu(menu) end else MenuV:CloseMenu(menu) sleep = 7 end end end end Wait(sleep) end end) -- FUNCTIONS function UpdateSociety() QBCore.Functions.TriggerCallback('qb-bossmenu:server:GetAccount', function(cb) menu_button5.Label = 'Society Amount: $' ..comma_value(cb) end, PlayerJob.name) end function ManageEmployees(employee) local manageroptions = MenuV:CreateMenu(false, employee.name .. ' Options', 'topright', 155, 0, 0, 'size-125', 'none', 'menuv') manageroptions:ClearItems() MenuV:OpenMenu(manageroptions) buttons = { [1] = { icon = '↕️', label = "Promote/Demote", value = "promote", description = "Promote " .. employee.name }, [3] = { icon = '🔥', label = "Fire", value = "Fire", description = "Fire " .. employee.name } } for k, v in pairs(buttons) do local menu_button9 = manageroptions:AddButton({ icon = v.icon, label = v.label, value = v.value, description = v.description, select = function(btn) local values = btn.Value if values == 'promote' then local result = LocalInput('New Grade Level', 255, '') if result ~= nil then TriggerServerEvent('qb-bossmenu:server:updateGrade', employee.source, tonumber(result)) end else TriggerServerEvent('qb-bossmenu:server:fireEmployee', employee.source) end end }) end end -- UTIL function DrawText3D(v, text) SetTextScale(0.35, 0.35) SetTextFont(4) SetTextProportional(1) SetTextColour(255, 255, 255, 215) SetTextEntry("STRING") SetTextCentre(true) AddTextComponentString(text) SetDrawOrigin(v, 0) DrawText(0.0, 0.0) local factor = (string.len(text)) / 370 DrawRect(0.0, 0.0+0.0125, 0.017+ factor, 0.03, 0, 0, 0, 0) ClearDrawOrigin() end function LocalInput(text, number, windows) AddTextEntry("FMMC_MPM_NA", text) DisplayOnscreenKeyboard(1, "FMMC_MPM_NA", "", windows or "", "", "", "", number or 30) while (UpdateOnscreenKeyboard() == 0) do DisableAllControlActions(0) Wait(0) end if (GetOnscreenKeyboardResult()) then local result = GetOnscreenKeyboardResult() return result end end function comma_value(amount) local formatted = amount while true do formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2') if (k==0) then break end end return formatted end
local asserts = require 'testing.asserts' local test_runner = require 'testing.test_runner' local mnist = require 'datasets.mnist' local tests = {} function tests.mnistTrain() local ds = mnist{} asserts.EQ(60000, ds:getSize()) local image1 = ds:getImage(1) asserts.tablesEQ({28, 28, 3}, image1:shape()) local imageLast = ds:getImage(ds:getSize()) asserts.tablesEQ({28, 28, 3}, imageLast:shape()) asserts.NE(image1, imageLast) local label1 = ds:getLabel(1) local labelLast = ds:getLabel(ds:getSize()) asserts.NE(label1, labelLast) end function tests.mnistTest() local ds = mnist{test = true} asserts.EQ(10000, ds:getSize()) local image1 = ds:getImage(1) asserts.tablesEQ({28, 28, 3}, image1:shape()) local imageLast = ds:getImage(ds:getSize()) asserts.tablesEQ({28, 28, 3}, imageLast:shape()) asserts.NE(image1, imageLast) local label1 = ds:getLabel(1) local labelLast = ds:getLabel(ds:getSize()) asserts.NE(label1, labelLast) end return test_runner.run(tests)
do local cur_volume = 1 function Characters:Tick() if Flux.menu_music then if !system.HasFocus() then Flux.menu_music:SetVolume(0) else Flux.menu_music:SetVolume(cur_volume) end if !IsValid(Flux.intro_panel) then if cur_volume > 0.05 then cur_volume = Lerp(0.1, cur_volume, 0) Flux.menu_music:SetVolume(cur_volume) else cur_volume = 1 Flux.menu_music:Stop() Flux.menu_music = nil end end end end end function Characters:PlayerInitialized() if !PLAYER:is_character_loaded() and !IsValid(Flux.intro_panel) then Flux.intro_panel = vgui.Create('fl_intro') if IsValid(Flux.intro_panel) then Flux.intro_panel:MakePopup() end end end function Characters:GetLoadingScreenMessage() if !IsValid(PLAYER) or !istable(PLAYER.characters) then return t'ui.hud.loading.characters', 75 end end function Characters:ShouldMapsceneRender() if IsValid(Flux.intro_panel) then return true end end function Characters:OnIntroPanelRemoved() if !PLAYER:get_character() then Flux.intro_panel = Theme.create_panel('main_menu') if IsValid(Flux.intro_panel) then Flux.intro_panel:MakePopup() else timer.Create('fl_create_main_panel', 0.1, 0, function() Flux.intro_panel = Theme.create_panel('main_menu') if IsValid(Flux.intro_panel) then Flux.intro_panel:MakePopup() timer.Remove('fl_create_main_panel') end end) end end end function Characters:OnThemeLoaded(current_theme) current_theme:add_panel('main_menu', function(id, parent, ...) return vgui.Create('fl_main_menu', parent) end) current_theme:add_panel('char_create', function(id, parent, ...) return vgui.Create('fl_char_create', parent) end) current_theme:add_panel('char_create.load', function(id, parent, ...) return vgui.Create('fl_char_load', parent) end) current_theme:add_panel('ui.char_create.general', function(id, parent, ...) return vgui.Create('fl_char_create_general', parent) end) if IsValid(Flux.intro_panel) then Flux.intro_panel:Remove() Flux.intro_panel = Theme.create_panel('main_menu') Flux.intro_panel:MakePopup() end end function Characters:AddTabMenuItems(menu) menu:add_menu_item('mainmenu', { title = t'ui.tab_menu.main_menu', icon = 'fa-bars', override = function(menu_panel, button) menu_panel:safe_remove() Flux.intro_panel = Theme.create_panel('main_menu') end }, 1) end function Characters:PostCharacterLoaded(char_id) if IsValid(Flux.intro_panel) then Flux.intro_panel:safe_remove() end end function Characters:ShouldDrawLoadingScreen() if !Flux.intro_panel then return true end end function Characters:ShouldHUDPaint() if !PLAYER:is_character_loaded() then return false end end function Characters:ShouldScoreboardHide() return PLAYER:is_character_loaded() end function Characters:ShouldScoreboardShow() return PLAYER:is_character_loaded() end function Characters:RebuildScoreboardPlayerCard(card, player) local x, y = card.name_label:GetPos() local text = player:steam_name() local font = Theme.get_font('text_normal') local text_height = util.text_height(text, font) card.steam_name = vgui.Create('DLabel', card) card.steam_name:SetText(text) card.steam_name:SetFont(font) card.steam_name:SetTextColor(Theme.get_color('text')) card.steam_name:SizeToContents() if hook.run('IsCharacterCardVisible', card, player) != false then card.avatar_panel:SetPos(card:GetWide() - card.avatar_panel:GetWide() - math.scale(48), math.scale(4)) card.steam_name:SetText(card.steam_name:GetText()) card.steam_name:SizeToContents() card.steam_name:SetPos(card.avatar_panel.x - card.steam_name:GetWide() - math.scale(4), card:GetTall() * 0.5 - text_height * 0.5) if IsValid(card.desc_label) then card.desc_label:safe_remove() card.spawn_icon:safe_remove() end card.spawn_icon = vgui.Create('SpawnIcon', card) card.spawn_icon:SetPos(math.scale_size(4, 4)) card.spawn_icon:SetSize(math.scale_size(32, 32)) card.spawn_icon:SetModel(player:GetModel()) card.spawn_icon:SetEnabled(false) local phys_desc = player:get_phys_desc() if utf8.len(phys_desc) > 128 then phys_desc = phys_desc:utf8sub(1, 128)..'...' end card.desc_label = vgui.Create('DLabel', card) card.desc_label:SetText(phys_desc) card.desc_label:SetFont(Theme.get_font('text_smallest')) card.desc_label:SetTextColor(Theme.get_color('text'):darken(50)) card.desc_label:SizeToContents() card.desc_label:SetPos(card.name_label.x, card.name_label.y + card.name_label:GetTall()) else card.steam_name:SetPos(math.scale(48), card:GetTall() * 0.5 - text_height * 0.6) card.name_label:SetVisible(false) end end function Characters:AddCharacterCreationMenuStages(panel) panel:add_stage('ui.char_create.general') end function Characters:GetDrawPlayerInfo(player, x, y, distance, lines) lines['desc'] = { text = player:get_phys_desc(), font = Theme.get_font('tooltip_small'), color = Color('white'), priority = 200 } end function Characters:AddMainMenuItems(panel, sidebar) local scrw, scrh = ScrW(), ScrH() if PLAYER:is_character_loaded() then panel:add_button(t'ui.main_menu.continue', function(btn) panel:Remove() end) end panel:add_button(t'ui.char_create.title', function(btn) btn:set_enabled(false) panel.menu = Theme.create_panel('char_create', panel) panel.menu:SetPos(ScrW(), 0) panel.menu:MoveTo(0, 0, Theme.get_option('menu_anim_duration'), 0.25, 0.5) panel.sidebar:MoveTo(-panel.sidebar:GetWide(), Theme.get_option('menu_sidebar_y'), Theme.get_option('menu_anim_duration'), 0.25, 0.5) end) if PLAYER:get_all_characters() and #PLAYER:get_all_characters() > 0 then panel:add_button(t'ui.char_create.load', function(btn) btn:set_enabled(false) panel.menu = Theme.create_panel('char_create.load', panel) panel.menu:SetPos(-panel.menu:GetWide(), 0) panel.menu:MoveTo(0, 0, Theme.get_option('menu_anim_duration'), 0.25, 0.5) panel.sidebar:MoveTo(ScrW(), Theme.get_option('menu_sidebar_y'), Theme.get_option('menu_anim_duration'), 0.25, 0.5) end) end panel:add_button(t'ui.main_menu.disconnect', function(btn) Derma_Query(t'ui.main_menu.disconnect_msg', t'ui.main_menu.disconnect', t'ui.yes', function() RunConsoleCommand('disconnect') end, t'ui.no') end) end function Characters:PanelCharacterSet(panel, char_data) panel.model.Entity:SetSkin(char_data.skin or 1) end
object_mobile_outbreak_undead_civilian_43 = object_mobile_shared_outbreak_undead_civilian_43:new { } ObjectTemplates:addTemplate(object_mobile_outbreak_undead_civilian_43, "object/mobile/outbreak_undead_civilian_43.iff")
object_tangible_quest_wave_event_shared_aaa_wave_event_test_object = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/quest/wave_event/shared_aaa_wave_event_test_object.iff" } ObjectTemplates:addClientTemplate(object_tangible_quest_wave_event_shared_aaa_wave_event_test_object, "object/tangible/quest/wave_event/shared_aaa_wave_event_test_object.iff") ------------------------------------------------------------------------------------------------------------------------------------
local techHandler = LazarusMod:GetModule('techhandler') techHandler:ChangeTechData(kTechId.BabblerEgg, { [kTechDataDisplayName] = "BABBLER_EGG", [kTechDataTooltipInfo] = "BABBLER_EGG_TOOLTIP", })
if SERVER and game.SinglePlayer() then util.AddNetworkString("arccw_sp_reloadlangs") end ArcCW.LangTable = ArcCW.LangTable or {} -- Converts raw string to a lang phrase. not case sensitive. ArcCW.StringToLang = { -- Class ["pistol"] = "class.pistol", ["revolver"] = "class.revolver", ["machine pistol"] = "class.machinepistol", ["submachine gun"] = "class.smg", -- Preferred ["sub-machine gun"] = "class.smg", ["smg"] = "class.smg", ["personal defense weapon"] = "class.pdw", -- Preferred ["pdw"] = "class.pdw", ["shotgun"] = "class.shotgun", ["assault carbine"] = "class.assaultcarbine", ["carbine"] = "class.carbine", ["assault rifle"] = "class.assaultrifle", ["rifle"] = "class.rifle", ["battle rifle"] = "class.battlerifle", ["designated marksman rifle"] = "class.dmr", ["dmr"] = "class.dmr", -- Preferred ["sniper rifle"] = "class.sniperrifle", -- Preferred ["sniper"] = "class.sniperrifle", ["antimateriel rifle"] = "class.antimaterielrifle", -- Preferred ["antimaterial rifle"] = "class.antimaterielrifle", ["anti-material rifle"] = "class.antimaterielrifle", ["rocket launcher"] = "class.rocketlauncher", ["hand grenade"] = "class.grenade", -- Preferred ["grenade"] = "class.grenade", ["melee weapon"] = "class.melee", -- Preferred -- Attachment Slot ["optic"] = "attslot.optic", ["backup optic"] = "attslot.bkoptic", ["muzzle"] = "attslot.muzzle", ["barrel"] = "attslot.barrel", ["choke"] = "attslot.choke", ["underbarrel"] = "attslot.underbarrel", ["tactical"] = "attslot.tactical", ["grip"] = "attslot.grip", ["stock"] = "attslot.stock", ["fire group"] = "attslot.fcg", ["ammo type"] = "attslot.ammo", ["perk"] = "attslot.perk", ["charm"] = "attslot.charm", ["skin"] = "attslot.skin", ["magazine"] = "attslot.magazine", ["slide"] = "attslot.slide", ["iron sights"] = "attslot.optic.default", ["ironsights"] = "attslot.optic.default", ["standard barrel"] = "attslot.barrel.default", ["standard choke"] = "attslot.choke.default", ["standard muzzle"] = "attslot.muzzle.default", ["standard grip"] = "attslot.grip.default", ["standard stock"] = "attslot.stock.default", ["no stock"] = "attslot.stock.none", ["standard fcg"] = "attslot.fcg.default", } -- Helper function for getting the overwrite or default language function ArcCW.GetLanguage() local l = GetConVar("arccw_language") and string.lower(GetConVar("arccw_language"):GetString()) if !l or l == "" then l = string.lower(GetConVar("gmod_language"):GetString()) end return l end -- Adds a string to the StringToLang table. function ArcCW.AddStringToLang(str, phrase) if phrase == nil or phrase == "" or str == nil or str == "" then return nil end ArcCW.StringToLang[string.lower(str)] = phrase end -- Retrieves a lang phrase from a string. If the string is a phrase itself, it will be returned. function ArcCW.GetPhraseFromString(str) if str == nil or str == "" then return nil end if ArcCW.StringToLang[string.lower(str)] then return ArcCW.StringToLang[string.lower(str)] end if ArcCW.LangTable["en"][string.lower(str)] then return string.lower(str) end return nil end -- Gets a translated string from a phrase. Will attempt to fallback to English. -- Returns nil if no such phrase exists. function ArcCW.GetTranslation(phrase, format) if phrase == nil or phrase == "" then return nil end local lang = ArcCW.GetLanguage() if !lang or lang == "" or !ArcCW.LangTable[lang] or !ArcCW.LangTable[lang][phrase] then lang = "en" end if ArcCW.LangTable[lang] and ArcCW.LangTable[lang][phrase] then local str = ArcCW.LangTable[lang][phrase] for i, v in pairs(format or {}) do -- print(i, v) str = string.Replace(str, "{" .. i .. "}", v) end return str end return nil end -- Attempts to translate a string (could be either a raw string or a phrase). -- If fail, return the string itself. function ArcCW.TryTranslation(str, format) if !str then return nil end local phrase = ArcCW.GetPhraseFromString(str) if !phrase then return str end return ArcCW.GetTranslation(phrase, format) or str end -- Adds a translated string for a specific language's phrase. lang defaults to English. function ArcCW.AddTranslation(phrase, str, lang) if phrase == nil or phrase == "" or str == nil or str == "" then return nil end lang = lang and string.lower(lang) or "en" ArcCW.LangTable[lang] = ArcCW.LangTable[lang] or {} ArcCW.LangTable[lang][string.lower(phrase)] = str end -- Translates an ammo string. If enabled, we will use our custom names (pulse -> rifle, smg -> carbine); -- Otherwise returns the in-game translation for it. function ArcCW.TranslateAmmo(ammo) if isnumber(ammo) then ammo = game.GetAmmoName(ammo) end if !ammo or !isstring(ammo) then return nil end ammo = string.lower(ammo) local lang = ArcCW.GetLanguage() local str = "ammo." .. ammo if SERVER or GetConVar("arccw_ammonames"):GetBool() then if ArcCW.LangTable[lang] and ArcCW.LangTable[lang][str] then return ArcCW.LangTable[lang][str] elseif ArcCW.LangTable["en"][str] then return ArcCW.LangTable["en"][str] end end return SERVER and (ammo .. " ammo") or language.GetPhrase(ammo .. "_ammo") end if CLIENT then function ArcCW.LoadClientLanguage(files) local lang = ArcCW.GetLanguage() files = files or file.Find("arccw/client/cl_languages/*", "LUA") --[[] -- First make sure there is actually a file in such language; otherwise default to english local has = false for _, v in pairs(files) do local exp = string.Explode("_", string.lower(string.Replace(v, ".lua", ""))) if exp[#exp] == lang then has = true break end end if !has then lang = "en" end ]] local lang_tbl = {} local lang_tbl_en = {} for _, v in pairs(files) do local exp = string.Explode("_", string.lower(string.Replace(v, ".lua", ""))) if lang != "en" and exp[#exp] == lang then include("arccw/client/cl_languages/" .. v) for phrase, str in pairs(L) do lang_tbl[phrase] = str end print("Loaded ArcCW cl_language file " .. v .. " with " .. table.Count(L) .. " strings.") L = nil elseif exp[#exp] == "en" then -- Always load english as backup include("arccw/client/cl_languages/" .. v) for phrase, str in pairs(L) do lang_tbl_en[phrase] = str end end end table.Merge(lang_tbl_en, lang_tbl) for phrase, str in pairs(lang_tbl_en) do language.Add(phrase, str) end end elseif SERVER then for _, v in pairs(file.Find("arccw/client/cl_languages/*", "LUA")) do AddCSLuaFile("arccw/client/cl_languages/" .. v) end end function ArcCW.LoadLanguages() ArcCW.LangTable = {} for _, v in pairs(file.Find("arccw/shared/languages/*", "LUA")) do include("arccw/shared/languages/" .. v) AddCSLuaFile("arccw/shared/languages/" .. v) local exp = string.Explode("_", string.lower(string.Replace(v, ".lua", ""))) local lang = exp[#exp] if !lang then print("Failed to load ArcCW language file " .. v .. ", did not get language name (naming convention incorrect?)") continue elseif !L then print("Failed to load ArcCW language file " .. v .. ", did not get language table") continue end for phrase, str in pairs(L) do ArcCW.AddTranslation(phrase, str, lang) end -- Load StringToLang stuff incase it is needed if STL then for str, phrase in pairs(STL) do ArcCW.AddStringToLang(str, phrase) end end print("Loaded ArcCW language file " .. v .. " with " .. table.Count(L) .. " strings.") L = nil STL = nil end if CLIENT then ArcCW.LoadClientLanguage() end hook.Run("ArcCW_LocalizationLoaded") end ArcCW.LoadLanguages() hook.Add("PreGamemodeLoaded", "ArcCW_Lang", function() if CLIENT and GetConVar("arccw_ammonames"):GetBool() then local ourlang = ArcCW.GetLanguage() for _, name in pairs(game.GetAmmoTypes()) do if ArcCW.LangTable[ourlang] and ArcCW.LangTable[ourlang]["ammo." .. string.lower(name)] then language.Add(name .. "_ammo", ArcCW.LangTable[ourlang]["ammo." .. string.lower(name)]) elseif ArcCW.LangTable["en"]["ammo." .. string.lower(name)] then language.Add(name .. "_ammo", ArcCW.LangTable["en"]["ammo." .. string.lower(name)]) end end end end) concommand.Add("arccw_reloadlangs", function(ply) ArcCW.LoadLanguages() if SERVER and game.SinglePlayer() then net.Start("arccw_sp_reloadlangs") net.Broadcast() end end, nil, "Reloads all language files.") if game.SinglePlayer() then net.Receive("arccw_sp_reloadlangs", function() ArcCW.LoadLanguages() end) end
-- Run exactly once, at the beginning of a program require('lfs') require('cutorch') require('nn') require('cunn') require('cudnn') require('xlua') require('optim') require('image') require('nngraph') require('strict')
function main() ret = nil num = m.getvar("tx.test"); if num == nil then m.log(9, "Don't know what to say about this so called number."); return ret end num = tonumber(num) if num > 1 then m.log(9, "Number is bigger than one."); ret = "Whee :)" else m.log(9, "Really?"); end return ret end
object_draft_schematic_space_reactor_collection_reward_reactor_02_mk2 = object_draft_schematic_space_reactor_shared_collection_reward_reactor_02_mk2:new { } ObjectTemplates:addTemplate(object_draft_schematic_space_reactor_collection_reward_reactor_02_mk2, "object/draft_schematic/space/reactor/collection_reward_reactor_02_mk2.iff")
local tArgs = { ... } if #tArgs > 2 then local programName = arg[0] or fs.getName(shell.getRunningProgram()) print("Usage: " .. programName .. " <alias> <program>") return end local sAlias = tArgs[1] local sProgram = tArgs[2] if sAlias and sProgram then -- Set alias shell.setAlias(sAlias, sProgram) elseif sAlias then -- Clear alias shell.clearAlias(sAlias) else -- List aliases local tAliases = shell.aliases() local tList = {} for sAlias, sCommand in pairs(tAliases) do table.insert(tList, sAlias .. ":" .. sCommand) end table.sort(tList) textutils.pagedTabulate(tList) end
--[[ The Context object implements a write-once key-value store. It also allows for a new Context object to inherit the entries from an existing one. ]] local Context = {} function Context.new(parent) local meta = {} local index = {} meta.__index = index if parent then for key, value in pairs(getmetatable(parent).__index) do index[key] = value end end function meta.__newindex(_obj, key, value) assert(index[key] == nil, string.format("Cannot reassign %s in context", tostring(key))) index[key] = value end return setmetatable({}, meta) end return Context
wifi_mode = 1 wifi_ssid = "YOUR_WIFI_SSID_HERE" wifi_pass = "YOUR_WIFI_PASSWORD_HERE" mqtt_ip = "YOUR_THINGSBOARD_HOST_OR_IP_HERE" mqtt_port = 1883 access_token = "DHT11_DEMO_TOKEN"
--This is a comment :eyes: local module = {} function module.init(Modules) -- This function is called after all modules have been required -- Modules is a table of all of the modules, indexed by name only -- ex. module at GUI.ItemPreview.Frame.Preview is Modules.Preview -- TWO MODULES CANNOT HAVE THE SAME NAME! -- All sounds physically located at GUI.Menu.Menu.Sounds local Sounds = Modules.Menu.sounds script.Parent.Top.Close.MouseButton1Click:Connect(function() Sounds.Click:Play() -- Focus.close() takes care of everything. Gui objects -- should be an imagelabel with a shadow called "Depth" -- in order to properly tween in and out. Modules.Focus.close() -- Focus.change(GuiObject) displays the GuiObject while -- closing any object that is currently open. Handles -- xbox controls as well by automatically selecting a button. end) local BigNumber = -12300000000000000000000000000000000000 -- Oh noes, a big number! How do we display this on a GUI? local MoneyLib = Modules.MoneyLib local NiceString -- For money: NiceString = MoneyLib.HandleMoney(BigNumber) --> -($12.3Ud) -- For everything else: NiceString = MoneyLib.DealWithPoints(BigNumber) --> 12.3Ud -- Other useful information: -- PlayerTycoon - Always set to the Tycoon that the Player OWNS local PlayerTycoon = game.Players.LocalPlayer.PlayerTycoon.Value -- ActiveTycoon - Set to the tycoon the player is currently EDITING -- (nil if not at a base they have permissions to edit) local ActiveTycoon = game.Players.LocalPlayer.ActiveTycoon.Value -- NearTycoon - Set to the tycoon the player is at, regardless of -- whether or not they have access to it. (nil if not at a tycoon) local NearTycoon = game.Players.LocalPlayer.NearTycoon.Value -- FOR SERVER -> USER INPUT, check GUI.Notifcations.Notify -- Use ReplicatedStorage.Hint, ReplicatedStorage.Currency or -- ReplicatedStorage.CurrencyPopup to send information to client. -- Important info: -- Use BoolValues titled "Xbox" "Mobile" AND/OR "PC" as children to make the -- parent only visible on those input modes. Using multiple tags is the same -- as an OR statement. If "Xbox" and "Mobile" are children, the parent will be -- visible on either input mode. This is automatic, you don't need to script anything. -- In fact, make sure you do not change the visibility of objects that have these tags -- as children because it will conflict. Use container objects if you wish to do this. -- DO NOT TOUCH ANYTHING IN SERVERSCRIPTSTORAGE.PLAYERDATAGUARDIAN -- LEAVE A COMMENT WITH DATE WHENEVER YOU CHANGE SOMETHING IN AN EXISTING SCRIPT -- LEAVE A COMMENT AT THE TOP OF ANY SCRIPT YOU CREATE EXPLAINING PURPOSE -- LEAVE INFORMATION IN GOOGLE DOC WHENEVER YOU MAKE A CHANGE. end return module
local an, ns = ... local _G = getfenv(0) -- Things local wwtc = {} local charClassID, charData, charName, guildName, playedLevel, playedLevelUpdated, playedTotal, playedTotalUpdated, regionName local hookedCollections, loggingOut = false, false, false local bankOpen, crafterOpen, guildBankOpen, reagentBankUpdated = false, false, false, false local maxScannedToys = 0 local oldScannedTransmog = 0 local dirtyBags, dirtyCovenant, dirtyCurrencies, dirtyLockouts, dirtyMounts, dirtyMythicPlus, dirtyPets, dirtyQuests, dirtyReputations, dirtyToys, dirtyTransmog, dirtyVault = {}, false, false, false, false, false, false, false, false, false, false, false, false local dirtyCallings, callingData = false, nil local dirtyGuildBank, guildBankQueried, requestingPlayedTime = false, false, true -- Libs local LibRealmInfo = LibStub('LibRealmInfo17janekjl') -- Default SavedVariables local defaultWWTCSaved = { version = 9158, chars = {}, guilds = {}, heirlooms = {}, toys = {}, } local instanceNameToId = {} -- Trade skill cooldowns local tradeSkills = { [156587] = true, -- Alchemical Catalyst [175880] = true, -- Secrets of Draenor Alchemy [171690] = true, -- Truesteel Ingot [176090] = true, -- Secrets of Draenor Blacksmithing [169092] = true, -- Temporal Crystal [177043] = true, -- Secrets of Draenor Enchanting [169080] = true, -- Gearspring Parts [177054] = true, -- Secrets of Draenor Engineering [169081] = true, -- War Paints [177045] = true, -- Secrets of Draenor Inscription [170700] = true, -- Taladite Crystal [176087] = true, -- Secrets of Draenor Jewelcrafting [171391] = true, -- Burnished Leather [176089] = true, -- Secrets of Draenor Leatherworking [168835] = true, -- Hexweave Cloth [176058] = true, -- Secrets of Draenor Tailoring } local weeklyQuests = { [37638] = "Bronze Invasion", [37639] = "Silver Invasion", [37640] = "Gold Invasion", [38482] = "Platinum Invasion", } local weeklyUghQuests = { ["anima"] = {61981, 61982, 61983, 61984}, ["souls"] = {61331, 61332, 61333, 61334, 62858, 62859, 62860, 62861, 62862, 62863, 62864, 62865, 62866, 62867, 62868, 62869}, ["shapingFate"] = {63949} } -- Check things the Battle.net API is bugged for local checkMounts = { --[458] = true, -- Brown Horse --[229376] = true, -- Archmage's Prismatic Disc (Mage Order Hall) --[229377] = true, -- Gift of the Holy Keepers (Priest Order Hall) --[229417] = true, -- Slayer's Felbroken Shrieker (Demon Hunter Order Hall) --[232412] = true, -- Netherlord's Chaotic Wrathsteed (Warlock Order Hall) --[215545] = true, -- Mastercraft Gravewing (Korthia rare) } local checkPets = { [216] = 33239, -- Argent Gruntling [1350] = 73809, -- Sky Lantern } local checkReputations = { --1492, -- Emperor Shaohao } local checkFriendships = { 2463, -- Marasmius } local paragonReputations = { -- Legion 1828, -- Highmountain Tribe 1859, -- The Nightfallen 1883, -- Dreamweavers 1894, -- The Wardens 1900, -- Court of Farondis 1948, -- Valarjar 2045, -- Armies of Legionfall 2165, -- Army of the Light 2170, -- Argussian Reach -- Battle for Azeroth 2103, -- Zandalari Empire 2156, -- Talanji's Expedition 2157, -- The Honorbound 2158, -- Voldunai 2159, -- 7th Legion 2160, -- Proudmoore Admiralty 2161, -- Order of Embers 2162, -- Storm's Wake 2163, -- Tortollan Seekers 2164, -- Champions of Azeroth 2373, -- The Unshackled 2391, -- Rustbolt Resistance 2400, -- Waveblade Ankoan 2415, -- Rajani 2417, -- Uldum Accord -- Shadowlands 2407, -- The Ascended 2410, -- The Undying Army 2413, -- Court of Harvesters 2432, -- Ve'nari 2465, -- The Wild Hunt 2470, -- Death's Advance 2472, -- The Archivists' Codex } local worldQuestFactions = { -- Both [50562] = 2164, -- Champions of Azeroth [50604] = 2163, -- Tortollan Seekers -- Alliance [50605] = 2157, -- 7th Legion => The Honorbound [50600] = 2158, -- Order of Embers => Voldunai [50599] = 2103, -- Proudmoore Admiralty => Zandalari Empire [50601] = 2156, -- Storm's Wake => Talanji's Expedition -- Horde [50602] = 2156, -- Talanji's Expedition [50606] = 2157, -- The Honorbound [50603] = 2158, -- Voldunai [50598] = 2103, -- Zandalari Empire } local torghastWidgets = { {name = 2927, level = 2936}, -- Coldheart Interstitia {name = 2925, level = 2930}, -- Fracture Chambers {name = 2928, level = 2938}, -- Mort'regar {name = 2926, level = 2932}, -- Skoldus Hall {name = 2924, level = 2934}, -- Soulforges {name = 2929, level = 2940}, -- The Upper Reaches } -- Misc constants local MAP_KULTIRAS = 876 local SLOTS_PER_GUILD_BANK_TAB = 98 -- Hook the time played message so that we don't print it to chat every time do local originalDisplayTimePlayed = _G.ChatFrame_DisplayTimePlayed _G.ChatFrame_DisplayTimePlayed = function(...) if requestingPlayedTime then requestingPlayedTime = false return end return originalDisplayTimePlayed(...) end end -- Need a frame for events local frame, events = CreateFrame("FRAME"), {} -- Fires when the addon has finished loading function events:ADDON_LOADED(name) -- Damn Pet Journal! if name == "Blizzard_Collections" then wwtc:HookCollections() end end -- Fires when the player logs in, surprisingly function events:PLAYER_LOGIN() wwtc:Login() end -- Fires when the player logs out, surprisingly function events:PLAYER_LOGOUT() wwtc:Logout() end -- Fires any time the player sees a loading screen function events:PLAYER_ENTERING_WORLD() -- FIXME: goes in PLAYER_LOGIN when not dev? --wwtc:Initialise() wwtc:UpdateCharacterData() dirtyCovenant = true dirtyCurrencies = true dirtyTransmog = true dirtyVault = true end -- Fires when /played information is available function events:TIME_PLAYED_MSG(total, level) playedLevel, playedLevelUpdated, playedTotal, playedTotalUpdated = level, time(), total, time() -- Unregister since we no longer care frame:UnregisterEvent("TIME_PLAYED_MSG") end -- Fires when the player gains a character level function events:PLAYER_LEVEL_UP() playedLevel, playedLevelUpdated = 0, time() end -- Fires when the player's rest state or amount of rested XP changes function events:UPDATE_EXHAUSTION() wwtc:UpdateExhausted() end -- Fires when guild stats changes function events:PLAYER_GUILD_UPDATE(unitID) if unitID == "player" then wwtc:UpdateGuildData() end end -- Fires when RequestRaidInfo() completes function events:UPDATE_INSTANCE_INFO() dirtyLockouts = true end -- Fires when currency changes function events:CURRENCY_DISPLAY_UPDATE(currencyType) -- Redeemed Soul, Reservoir Anima if currencyType == 1810 or currencyType == 1813 then dirtyCovenant = true end dirtyCurrencies = true end -- Fires when player money changes function events:PLAYER_MONEY() charData.copper = GetMoney() end -- Fires when information about the contents of a trade skill recipe list changes or becomes available --function events:TRADE_SKILL_UPDATE() -- wwtc:ScanTradeSkills() --end -- Fires when a unit casts a spell - used for trade skill updating --function events:UNIT_SPELLCAST_SUCCEEDED(evt, unit, spellName, rank, lineID, spellID) -- -- We only care about the player's trade skills -- if unit == "player" and tradeSkills[spellID] == true then -- C_Timer.NewTimer(0.5, function() wwtc:ScanTradeSkills() end) -- end --end -- Fires when the contents of a bag changes function events:BAG_UPDATE(bagID) dirtyBags[bagID] = true end -- Fires when the bank is opened function events:BANKFRAME_OPENED() -- Force a bag scan of the bank now that it's open bankOpen = true dirtyBags[-1] = true dirtyBags[-3] = true for i = 5, 11 do dirtyBags[i] = true end end -- Fires when the bank is closed function events:BANKFRAME_CLOSED() bankOpen = false end -- Fires when something changes in the reagent bank function events:PLAYERREAGENTBANKSLOTS_CHANGED() dirtyBags[-3] = true reagentBankUpdated = true end -- Fires when the guild bank opens function events:GUILDBANKFRAME_OPENED() guildBankOpen = true guildBankQueried = false wwtc:UpdateGuildBank() end -- Fires when the guild bank closes function events:GUILDBANKFRAME_CLOSED() guildBankOpen = false end -- Fires when something changes in a guild bank tab, including when it is first filled function events:GUILDBANKBAGSLOTS_CHANGED() dirtyGuildBank = true end -- Fires ?? function events:COMPANION_UPDATE() dirtyMounts = true dirtyPets = true end -- Fires when a new companion is learned function events:COMPANION_LEARNED() dirtyMounts = true dirtyPets = true end -- Fires when the mount journal usability list changes (move between inside/outside/water/etc) function events:MOUNT_JOURNAL_USABILITY_CHANGED() dirtyMounts = true end -- Fires when the pet journal list updates function events:PET_JOURNAL_LIST_UPDATE() dirtyPets = true end -- Fires when the contents of the reputation listing change or become available function events:UPDATE_FACTION() dirtyReputations = true end -- Fires when Mythic dungeon ends function events:CHALLENGE_MODE_COMPLETED() C_MythicPlus.RequestMapInfo() end -- Fires when Mythic dungeon map information updates function events:CHALLENGE_MODE_MAPS_UPDATE() dirtyMythicPlus = true dirtyVault = true end -- Vault function events:WEEKLY_REWARDS_HIDE() dirtyVault = true end function events:WEEKLY_REWARDS_SHOW() dirtyVault = true end function events:WEEKLY_REWARDS_UPDATE() dirtyVault = true end -- Quest changes, spammy function events:QUEST_LOG_UPDATE() dirtyQuests = true end -- Finished looting something function events:LOOT_CLOSED() dirtyLockouts = true dirtyQuests = true end -- Popup "you got loot" box function events:SHOW_LOOT_TOAST() dirtyLockouts = true dirtyQuests = true end -- Chromie time function events:CHROMIE_TIME_CLOSE() wwtc:UpdateChromieTime() end function events:CHROMIE_TIME_OPEN() wwtc:UpdateChromieTime() end -- Vague about what this does, but it includes war mode function events:PLAYER_FLAGS_CHANGED(unitId) if unitId == 'player' then wwtc:UpdateWarMode() end end -- Quests function events:COVENANT_CALLINGS_UPDATED(callings) dirtyCallings = true callingData = callings end -- Shadowlands: Covenants function events:COVENANT_CHOSEN() dirtyCovenant = true end function events:COVENANT_SANCTUM_RENOWN_LEVEL_CHANGED() dirtyCovenant = true end function events:COVENANT_SANCTUM_INTERACTION_STARTED() dirtyCovenant = true end function events:COVENANT_SANCTUM_INTERACTION_ENDED() dirtyCovenant = true end function events:SOULBIND_ACTIVATED() dirtyCovenant = true end function events:SOULBIND_FORGE_INTERACTION_STARTED() dirtyCovenant = true end function events:SOULBIND_FORGE_INTERACTION_ENDED() dirtyCovenant = true end -- Toys function events:NEW_TOY_ADDED() dirtyToys = true end function events:TOYS_UPDATED() dirtyToys = true end -- Transmog function events:TRANSMOG_COLLECTION_SOURCE_ADDED() dirtyTransmog = true end function events:TRANSMOG_COLLECTION_SOURCE_REMOVED() dirtyTransmog = true end function events:TRANSMOG_COLLECTION_UPDATED() dirtyTransmog = true end ------------------------------------------------------------------------------- -- Call functions in the events table for events frame:SetScript("OnEvent", function(self, event, ...) events[event](self, ...) end) -- Register every event in the events table for k, v in pairs(events) do frame:RegisterEvent(k) end ------------------------------------------------------------------------------- -- Timer to do spammy things function wwtc:Timer() for bagID, dirty in pairs(dirtyBags) do dirtyBags[bagID] = nil wwtc:ScanBag(bagID) end if dirtyCovenant then dirtyCovenant = false wwtc:ScanCovenants() end if dirtyCurrencies then dirtyCurrencies = false wwtc:ScanCurrencies() end if dirtyGuildBank then dirtyGuildBank = false wwtc:ScanGuildBankTabs() end if dirtyLockouts then dirtyLockouts = false wwtc:ScanLockouts() end if dirtyMounts then dirtyMounts = false wwtc:ScanMounts() end if dirtyMythicPlus then dirtyMythicPlus = false wwtc:ScanMythicPlus() end if dirtyPets then dirtyPets = false wwtc:ScanPets() end if dirtyReputations then dirtyReputations = false wwtc:ScanReputations() end if dirtyToys then dirtyToys = false wwtc:ScanToys(false) end if dirtyTransmog then dirtyTransmog = false wwtc:ScanTransmog() end if dirtyVault then dirtyVault = false wwtc:ScanVault() end if dirtyQuests then dirtyQuests = false C_CovenantCallings.RequestCallings() wwtc:ScanQuests() end if dirtyCallings then dirtyCallings = false wwtc:ScanCallings() end end -- Run the timer once per 2 seconds to do chunky things local _ = C_Timer.NewTicker(2, function() wwtc:Timer() end, nil) ------------------------------------------------------------------------------- function wwtc:Initialise() if WWTCSaved == nil or WWTCSaved.version < defaultWWTCSaved.version then WWTCSaved = defaultWWTCSaved end -- Perform any cleanup wwtc:Cleanup() -- Build a unique ID for this character -- id, name, nameForAPI, rules, locale, nil, region, timezone, connections, englishName, englishNameForAPI local _, realm, _, _, _, _, region, _, _, realmEnglish = LibRealmInfo:GetRealmInfoByUnit("player") regionName = region or GetCurrentRegion() charName = regionName .. "/" .. (realmEnglish or realm) .. "/" .. UnitName("player") charClassID = select(3, UnitClass("player")) -- Set up character data table charData = WWTCSaved.chars[charName] or {} WWTCSaved.chars[charName] = charData charData.chromieTime = 0 charData.copper = 0 charData.isResting = false charData.isWarMode = false charData.keystoneInstance = 0 charData.keystoneLevel = 0 charData.lastSeen = 0 charData.mountSkill = 0 charData.playedLevel = 0 charData.playedTotal = 0 charData.restedXP = 0 charData.achievements = charData.achievements or {} charData.bags = charData.bags or {} charData.callings = charData.callings or {} charData.covenants = charData.covenants or {} charData.currencies = charData.currencies or {} charData.dailyQuests = charData.dailyQuests or {} charData.items = charData.items or {} charData.lockouts = charData.lockouts or {} charData.mounts = charData.mounts or {} charData.mythicDungeons = charData.mythicDungeons or {} charData.mythicPlus = charData.mythicPlus or {} charData.orderHallResearch = charData.orderHallResearch or {} charData.otherQuests = charData.otherQuests or {} charData.paragons = charData.paragons or {} charData.pets = charData.pets or {} charData.reputations = charData.reputations or {} charData.scanTimes = charData.scanTimes or {} charData.torghast = charData.torghast or {} charData.tradeSkills = charData.tradeSkills or {} charData.transmog = charData.transmog or nil charData.vault = charData.vault or {} charData.weeklyQuests = charData.weeklyQuests or {} charData.weeklyUghQuests = charData.weeklyUghQuests or {} -- Deprecated charData.biggerFishToFry = nil charData.hiddenDungeons = nil charData.hiddenKills = nil charData.hiddenWorldQuests = nil charData.balanceUnleashedMonstrosities = nil charData.balanceMythic15 = nil charData.worldQuests = nil charData.dailyResetTime = wwtc:GetDailyResetTime() wwtc:BuildEJData() wwtc:UpdateGuildData() end function wwtc:Login() wwtc:Initialise() -- Try to hook things wwtc:HookCollections() RequestTimePlayed() C_Garrison.RequestLandingPageShipmentInfo() wwtc:ScanMounts() wwtc:ScanToys(true) end function wwtc:Logout() loggingOut = true wwtc:UpdateCharacterData() end function wwtc:Cleanup() -- Remove data for any characters not seen in the last 3 days local old = time() - (3 * 24 * 60 * 60) for cName, cData in pairs(WWTCSaved.chars) do if not cData.lastSeen or cData.lastSeen < old then WWTCSaved.chars[cName] = nil end end end -- Build a mapping of instanceName => instanceId function wwtc:BuildEJData() for tier = 1, EJ_GetNumTiers() do EJ_SelectTier(tier) for i = 1, 2 do local isRaid = i == 1 local index = 1 local instanceId, name = EJ_GetInstanceByIndex(index, isRaid) while instanceId do instanceNameToId[name] = instanceId index = index + 1 instanceId, name = EJ_GetInstanceByIndex(index, isRaid) end end end end -- Update various character data function wwtc:UpdateCharacterData() if charData == nil then return end local now = time() charData.lastSeen = now -- Played time if playedLevel and playedTotal then charData.playedLevel = playedLevel + (now - playedLevelUpdated) charData.playedTotal = playedTotal + (now - playedTotalUpdated) end -- Master Riding if IsSpellKnown(90265) then charData.mountSkill = 5 -- Artisan Riding (DEPRECATED but still gives 280%) elseif IsSpellKnown(34091) then charData.mountSkill = 4 -- Expert Riding elseif IsSpellKnown(34090) then charData.mountSkill = 3 -- Journeyman Riding elseif IsSpellKnown(33391) then charData.mountSkill = 2 -- Apprentice Riding elseif IsSpellKnown(33388) then charData.mountSkill = 1 end if not loggingOut then dirtyQuests = true charData.copper = GetMoney() wwtc:UpdateChromieTime() wwtc:UpdateExhausted() wwtc:UpdateWarMode() wwtc:ScanAchievements() wwtc:ScanTorghast() C_MythicPlus.RequestMapInfo() RequestRaidInfo() end end function wwtc:UpdateGuildData() if charData == nil then return end -- Sometimes this fires before region is checked? Weird if not regionName then return end -- Build a unique ID for this character's guild local gName, gRankName, gRankIndex = GetGuildInfo("player") if gName then guildName = regionName .. "/" .. GetRealmName() .. "/" .. gName WWTCSaved.guilds[guildName] = WWTCSaved.guilds[guildName] or {} WWTCSaved.guilds[guildName].copper = WWTCSaved.guilds[guildName].copper or 0 WWTCSaved.guilds[guildName].items = WWTCSaved.guilds[guildName].items or {} WWTCSaved.guilds[guildName].tabs = WWTCSaved.guilds[guildName].tabs or {} else guildName = nil end end function wwtc:UpdateChromieTime() if charData == nil then return end charData.chromieTime = UnitChromieTimeID("player") end -- Update resting status and rested XP function wwtc:UpdateExhausted() if charData == nil then return end charData.isResting = IsResting() local rested = GetXPExhaustion() if rested and rested > 0 then charData.restedXP = rested else charData.restedXP = 0 end end function wwtc:UpdateWarMode() if charData == nil then return end charData.isWarMode = C_PvP.IsWarModeDesired() end -- Scan a specific bag function wwtc:ScanBag(bagID) if charData == nil then return end -- Short circuit if bank isn't open if (bagID == -1 or (bagID >= 5 and bagID <= 11)) and not bankOpen then return end -- Reagent bank is weird, make sure that the bank is open or it was actually updated if bagID == -3 then if not (bankOpen or reagentBankUpdated) then return end reagentBankUpdated = false end local now = time() if bagID >= 0 and bagID <= 4 then charData.scanTimes["bags"] = now -- Update mythic plus keystone since bags changed charData.keystoneInstance = C_MythicPlus.GetOwnedKeystoneChallengeMapID() charData.keystoneLevel = C_MythicPlus.GetOwnedKeystoneLevel() else charData.scanTimes["bank"] = now end charData.items["b"..bagID] = {} local bag = charData.items["b"..bagID] -- Update bag ID if bagID >= 1 then local bagItemID, _ = GetInventoryItemID('player', ContainerIDToInventoryID(bagID)) charData.bags["b"..bagID] = bagItemID end local numSlots = GetContainerNumSlots(bagID) if numSlots > 0 then for i = 1, numSlots do local _, count, _, _, _, _, link, _ = GetContainerItemInfo(bagID, i) if count ~= nil and link ~= nil then local parsed = wwtc:ParseItemLink(link, count) bag["s"..i] = parsed end end end end function wwtc:UpdateGuildBank() WWTCSaved.guilds[guildName].copper = GetGuildBankMoney() for i = 1, GetNumGuildBankTabs() do local name, icon, isViewable, canDeposit, numWithdrawals, remainingWithdrawals = GetGuildBankTabInfo(i) WWTCSaved.guilds[guildName].tabs["tab "..i] = { name, icon } end end -- Scan guild bank tabs function wwtc:ScanGuildBankTabs() if charData == nil then return end -- Short circuit if guild bank isn't open if not guildBankOpen then return end local now = time() -- Request data for every tab, but only once per guild bank opening or we scan infinitely if guildBankQueried == false then for tabIndex = 1, GetNumGuildBankTabs() do QueryGuildBankTab(tabIndex) end guildBankQueried = true end for tabIndex = 1, GetNumGuildBankTabs() do local tabKey = "t"..tabIndex charData.scanTimes[tabKey] = now WWTCSaved.guilds[guildName].items[tabKey] = {} local tab = WWTCSaved.guilds[guildName].items[tabKey] for slotIndex = 1, SLOTS_PER_GUILD_BANK_TAB do local link = GetGuildBankItemLink(tabIndex, slotIndex) if link ~= nil then local _, itemCount, _, _, _ = GetGuildBankItemInfo(tabIndex, slotIndex) local parsed = wwtc:ParseItemLink(link, itemCount) tab["s"..slotIndex] = parsed end end end end -- Scan covenant local function SortTalents(talentA, talentB) return talentA.tier < talentB.tier end function wwtc:ScanCovenants() if charData == nil then return end local now = time() -- 1=Kyrian 2=Venthyr 3=NightFae 4=Necrolord local covenantId = C_Covenants.GetActiveCovenantID() if covenantId == 0 then return end local covenantData = { id = covenantId, renown = C_CovenantSanctumUI.GetRenownLevel(), anima = 0, souls = 0, conductor = {}, transport = {}, missions = {}, unique = {}, soulbinds = {}, } -- Currencies local animaInfo = C_CurrencyInfo.GetCurrencyInfo(1813) if animaInfo ~= nil then covenantData.anima = animaInfo.quantity end local soulsInfo = C_CurrencyInfo.GetCurrencyInfo(1810) if soulsInfo ~= nil then covenantData.souls = soulsInfo.quantity end -- Features local covenant = ns.covenants[covenantId] for thing, talentTreeId in pairs(covenant.features) do local talentData = C_Garrison.GetTalentTreeInfo(talentTreeId) table.sort(talentData.talents, SortTalents) local thingData = { name = talentData.title, rank = 0, researchEnds = 0, } for _, talent in ipairs(talentData.talents) do if talent.researched == true then thingData.rank = talent.tier + 1 else if talent.isBeingResearched == true then thingData.researchEnds = now + talent.timeRemaining end break end end covenantData[thing] = thingData end -- Soulbinds local soulbindIds = C_Covenants.GetCovenantData(covenantId)['soulbindIDs'] for _, soulbindId in ipairs(soulbindIds) do local soulbindData = C_Soulbinds.GetSoulbindData(soulbindId) local soulbind = { id = soulbindData.ID, unlocked = soulbindData.unlocked, specs = C_Soulbinds.GetSpecsAssignedToSoulbind(soulbindId), tree = {}, } for _, node in ipairs(soulbindData.tree.nodes) do if node.state == 3 then soulbind.tree[node.row + 1] = { node.column + 1, C_Soulbinds.GetConduitSpellID(node.conduitID, node.conduitRank), node.conduitRank, } end end covenantData.soulbinds[#covenantData.soulbinds + 1] = soulbind end local found = false for i = 1, #charData.covenants do if charData.covenants[i].id == covenantId then charData.covenants[i] = covenantData found = true break end end if found == false then charData.covenants[#charData.covenants + 1] = covenantData end end -- Scan achievements function wwtc:ScanAchievements() if charData == nil then return end charData.achievements = {} charData.scanTimes['achievements'] = time() for _, achievementId in ipairs(ns.achievements) do local criteria = {} local earnedByCharacter = select(13, GetAchievementInfo(achievementId)) if not earnedByCharacter then local numCriteria = GetAchievementNumCriteria(achievementId) for i = 1, numCriteria do local _, _, _, quantity = GetAchievementCriteriaInfo(achievementId, i) table.insert(criteria, quantity) end end charData.achievements[#charData.achievements + 1] = { id = achievementId, earned = earnedByCharacter, criteria = criteria, } end end -- Scan currencies function wwtc:ScanCurrencies() if charData == nil then return end charData.currencies = {} charData.scanTimes["currencies"] = time() for _, currencyID in ipairs(ns.currencies) do local currencyInfo = C_CurrencyInfo.GetCurrencyInfo(currencyID) if currencyInfo ~= nil then -- quantity:max:isWeekly:weekQuantity:weekMax:isMovingMax:totalQuantity charData.currencies[currencyID] = table.concat({ currencyInfo.quantity, currencyInfo.maxQuantity, currencyInfo.canEarnPerWeek and 1 or 0, currencyInfo.quantityEarnedThisWeek, currencyInfo.maxWeeklyQuantity, currencyInfo.useTotalEarnedForMaxQty and 1 or 0, currencyInfo.totalEarned, }, ':') end end end -- Scan instance/world boss lockouts function wwtc:ScanLockouts() if charData == nil then return end charData.lockouts = {} local now = time() charData.scanTimes["lockouts"] = now -- Instances for i = 1, GetNumSavedInstances() do local instanceName, _, instanceReset, instanceDifficulty, locked, _, _, _, _, _, maxBosses, defeatedBosses = GetSavedInstanceInfo(i) if instanceReset > 0 then instanceReset = now + instanceReset end -- Get saved boss names local bosses, j = {}, 1 local name, _, dead = GetSavedInstanceEncounterInfo(i, j) while name do bosses[#bosses + 1] = table.concat({ dead and 1 or 0, name, }, ':') j = j + 1 name, _, dead = GetSavedInstanceEncounterInfo(i, j) end charData.lockouts[#charData.lockouts+1] = { id = instanceNameToId[instanceName], name = instanceName, resetTime = instanceReset, bosses = bosses, difficulty = instanceDifficulty, defeatedBosses = defeatedBosses, locked = locked, maxBosses = maxBosses, } end -- World bosses --for i = 1, GetNumSavedWorldBosses() do -- local instanceName, worldBossID, instanceReset = GetSavedWorldBossInfo(i) -- charData.lockouts[#charData.lockouts+1] = { -- name = instanceName, -- resetTime = now + instanceReset, -- difficulty = 0, -- defeatedBosses = 1, -- maxBosses = 1, -- } --end local dailyReset = now + C_DateAndTime.GetSecondsUntilDailyReset() local weeklyReset = now + C_DateAndTime.GetSecondsUntilWeeklyReset() -- Other world bosses for questID, questData in pairs(ns.worldBossQuests) do groupId, groupName, bossName, isDaily = unpack(questData) if C_QuestLog.IsQuestFlaggedCompleted(questID) then local resetTime if isDaily == true then resetTime = dailyReset else resetTime = weeklyReset end charData.lockouts[#charData.lockouts+1] = { id = groupId, name = groupName, resetTime = resetTime, bosses = { "1:"..bossName, }, difficulty = 0, defeatedBosses = 1, locked = true, maxBosses = 1, weeklyQuest = true, } end end end -- Scan quests function wwtc:ScanQuests() if charData == nil then return end charData.dailyQuests = {} charData.otherQuests = {} charData.weeklyQuests = {} charData.weeklyUghQuests = {} charData.scanTimes["quests"] = time() for _, questID in ipairs(ns.otherQuests) do if C_QuestLog.IsQuestFlaggedCompleted(questID) then charData.otherQuests[#charData.otherQuests + 1] = questID end end for _, questID in ipairs(ns.scanQuests) do if C_QuestLog.IsQuestFlaggedCompleted(questID) then charData.dailyQuests[#charData.dailyQuests + 1] = questID end end for questID, _ in ipairs(weeklyQuests) do if C_QuestLog.IsQuestFlaggedCompleted(questID) then charData.weeklyQuests[#charData.weeklyQuests + 1] = questID end end for name, questIds in pairs(weeklyUghQuests) do local ugh = { status = 0 } for _, questId in ipairs(questIds) do -- Quest is completed if C_QuestLog.IsQuestFlaggedCompleted(questId) then ugh.status = 2 break -- Quest is in progress, check progress elseif C_QuestLog.IsOnQuest(questId) then --local index = C_QuestLog.GetLogIndexForQuestID(questId) --local description, _, _ = GetQuestLogLeaderBoard(1, index) local objectives = C_QuestLog.GetQuestObjectives(questId) if objectives ~= nil then local obj = objectives[1] ugh.status = 1 ugh.text = obj.text ugh.type = obj.type if obj.type == 'progressbar' then ugh.have = GetQuestProgressBarPercent(questId) ugh.need = 100 else ugh.have = obj.numFulfilled ugh.need = obj.numRequired end break end end end charData.weeklyUghQuests[name] = ugh end end -- Scan mythic plus dungeons function wwtc:ScanMythicPlus() if charData == nil then return end local now = time() charData.scanTimes["mythicPlus"] = now charData.mythicPlus = { maps = {}, season = C_MythicPlus.GetCurrentSeason(), } local maps = C_ChallengeMode.GetMapTable() for i = 1, #maps do local affixScores, overallScore = C_MythicPlus.GetSeasonBestAffixScoreInfoForMap(maps[i]) charData.mythicPlus.maps[#charData.mythicPlus.maps + 1] = { mapId = maps[i], affixScores = affixScores, overallScore = overallScore, } end end -- Scan transmog function wwtc:ScanTransmog() if charData == nil then return end charData.scanTimes["transmog"] = time() local transmog = {} -- Try the hack that TransmogRoulette uses to fix the category bug -- https://github.com/semlar/TransmogRoulette/blob/181615d0bb7fb19992bbcefae7f5c6970865e52b/TransmogRoulette.xml#L119 --C_Timer.After(1, function() for categoryID = 0, 29 do local appearances = C_TransmogCollection.GetCategoryAppearances(categoryID) for _, appearance in pairs(appearances) do if appearance.isCollected then transmog[appearance.visualID] = true end end end if oldScannedTransmog ~= #transmog then print("WoWthing_Collector: found", #transmog, "transmog appearances") oldScannedTransmog = #transmog end local keys = {} for key in pairs(transmog) do keys[#keys + 1] = key end table.sort(keys) charData.transmog = table.concat(keys, ':') end -- Scan dirtyVault function wwtc:ScanVault() if charData == nil then return end local now = time() charData.scanTimes["vault"] = now charData.vault = {} -- Mythic dungeons charData.mythicDungeons = {} local runs = C_MythicPlus.GetRunHistory(false, true) -- includePreviousWeeks, includeIncompleteRuns for i = 1, #runs do local run = runs[i] charData.mythicDungeons[i] = { map = run.mapChallengeModeID, level = run.level, } end -- Vault completion local activities = C_WeeklyRewards.GetActivities() for i = 1, #activities do -- [1]={ -- threshold=10, -- type=1, -- index=3, -- progress=8, -- level=0, -- rewards={ -- }, -- id=34 -- }, local activity = activities[i] -- We only care about 1 (MythicPlus), 2 (RankedPvP), 3 (Raid) if activity.type >= 1 and activity.type <= 3 then charData.vault[activity.type] = charData.vault[activity.type] or {} charData.vault[activity.type][activity.index] = { level = activity.level, progress = activity.progress, threshold = activity.threshold, } end end end -- Scan callings function wwtc:ScanCallings() if charData == nil then return end local now = time() charData.scanTimes["callings"] = now charData.callings = {} if callingData == nil then return end if not C_CovenantCallings.AreCallingsUnlocked() then return end local dailyReset = now + C_DateAndTime.GetSecondsUntilDailyReset() for i = 1, 3 do charData.callings[i] = { completed = true, expires = dailyReset + ((i - 1) * 24 * 60 * 60), } end -- questID number -- factionID number -- icon number -- numObjectives number -- turninRequirementText string? for _, calling in ipairs(callingData) do local timeLeft = C_TaskQuest.GetQuestTimeLeftMinutes(calling.questID) or 0 local index = 3 if timeLeft < 1440 then index = 1 elseif timeLeft < 2880 then index = 2 end charData.callings[index].completed = C_QuestLog.IsQuestFlaggedCompleted(calling.questID) end return end -- Scan trade skills for cooldowns function wwtc:ScanTradeSkills() if charData == nil then return end -- Don't care about tradeskills that aren't our own if IsTradeSkillGuild() or IsTradeSkillLinked() then return end local now = time() for i = 1, GetNumTradeSkills() do local link = GetTradeSkillRecipeLink(i) if link then local spellID = tonumber(link:match("\|Henchant:(%d+)\|h")) if spellID and tradeSkills[spellID] == true then local cooldown = GetTradeSkillCooldown(i) if cooldown then charData.tradeSkills[spellID] = now + cooldown else charData.tradeSkills[spellID] = nil end end end end end -- Hook various Blizzard_Collections things for scanning function wwtc:HookCollections() if not IsAddOnLoaded("Blizzard_Collections") then UIParentLoadAddOn("Blizzard_Collections") return end if hookedCollections then return end -- Hook heirlooms local hlframe = _G["HeirloomsJournal"] if hlframe then hlframe:HookScript("OnShow", function(self) wwtc:ScanHeirlooms() end) else print("WoWthing_Collector: unable to hook 'HeirloomsJournal' frame!") end -- Hook toys local tbframe = _G["ToyBox"] if tbframe then tbframe:HookScript("OnShow", function(self) wwtc:ScanToys(false) end) else print("WoWthing_Collector: unable to hook 'ToyBox' frame!") end -- Hook transmog local tmogframe = _G["WardrobeCollectionFrame"] if tmogframe then tmogframe:HookScript("OnShow", function(self) dirtyTransmog = true end) else print("WoWthing_Collector: unable to hook 'WardrobeCollectionFrame' frame!") end hookedCollections = true end -- Scan heirlooms function wwtc:ScanHeirlooms() if charData == nil then return end charData.scanTimes['heirlooms'] = time() WWTCSaved.heirlooms = {} for i = 1, C_Heirloom.GetNumDisplayedHeirlooms() do local itemID = C_Heirloom.GetHeirloomItemIDFromDisplayedIndex(i) -- name, itemEquipLoc, isPvP, itemTexture, upgradeLevel, source, searchFiltered, effectiveLevel, minLevel, maxLevel if C_Heirloom.PlayerHasHeirloom(itemID) then local _, _, _, _, upgradeLevel = C_Heirloom.GetHeirloomInfo(itemID) WWTCSaved.heirlooms[itemID] = upgradeLevel end end end -- Scan mounts function wwtc:ScanMounts() if charData == nil then return end charData.scanTimes['mounts'] = time() charData.mounts = {} local mountIDs = C_MountJournal.GetMountIDs() for _, mountID in ipairs(mountIDs) do local _, spellID, _, _, _, _, _, _, _, _, isCollected = C_MountJournal.GetMountInfoByID(mountID) if isCollected and checkMounts[spellID] then charData.mounts[#charData.mounts+1] = spellID end end end -- Scan pets function wwtc:ScanPets() if charData == nil then return end charData.scanTimes['pets'] = time() charData.pets = {} for i = 1, C_PetJournal.GetNumPets() do local petID, speciesID, owned = C_PetJournal.GetPetInfoByIndex(i) if owned and checkPets[speciesID] then local _, customName, level, _, _, _, isFavorite, petName = C_PetJournal.GetPetInfoByPetID(petID) local _, _, _, _, rarity = C_PetJournal.GetPetStats(petID) charData.pets[#charData.pets+1] = { petID = checkPets[speciesID], favourite = isFavorite, guid = petID, level = level, name = customName or petName, quality = rarity, } end end end -- Scan reputations function wwtc:ScanReputations() if charData == nil then return end charData.scanTimes['reputations'] = time() charData.paragons = {} charData.reputations = {} for _, factionID in ipairs(checkReputations) do local _, _, _, _, _, barValue = GetFactionInfoByID(factionID) charData.reputations[factionID] = barValue end for _, friendshipID in ipairs(checkFriendships) do local _, friendRep = GetFriendshipReputation(friendshipID) charData.reputations[friendshipID] = friendRep end for i, factionID in ipairs(paragonReputations) do if C_Reputation.IsFactionParagon(factionID) then local currentValue, threshold, _, hasRewardPending = C_Reputation.GetFactionParagonInfo(factionID) -- value:max:hasReward charData.paragons[factionID] = table.concat({ currentValue, threshold, hasRewardPending and 1 or 0, }, ':') end end end -- Scan Torghast function wwtc:ScanTorghast() if charData == nil then return end local now = time() charData.scanTimes["torghast"] = now charData.torghast = {} -- Into Torghast, intro quest if C_QuestLog.IsQuestFlaggedCompleted(60136) then for _, widget in ipairs(torghastWidgets) do local name = C_UIWidgetManager.GetTextWithStateWidgetVisualizationInfo(widget.name) local level = C_UIWidgetManager.GetTextWithStateWidgetVisualizationInfo(widget.level) if name and level and name.shownState == 1 then charData.torghast[#charData.torghast + 1] = { level = tonumber(strmatch(level.text, '|cFF00FF00.-(%d+).+|r')), name = strmatch(name.text, '|n|cffffffff(.+)|r'), } end end end end -- Scan toys function wwtc:ScanToys(resetToyBox) if charData == nil then return end charData.scanTimes['toys'] = time() local toys = {} for _, toyId in pairs(WWTCSaved.toys) do toys[toyId] = true end -- Reset toy box to show everything if resetToyBox == true then C_ToyBox.SetAllSourceTypeFilters(true) C_ToyBox.SetCollectedShown(true) C_ToyBox.SetUncollectedShown(true) C_ToyBox.SetUnusableShown(true) C_ToyBox.SetFilterString("") end local numToys = C_ToyBox.GetNumToys() for i = 1, numToys do local itemID = C_ToyBox.GetToyFromIndex(i) if itemID > 0 and PlayerHasToy(itemID) then toys[itemID] = true end end WWTCSaved.toys = {} for itemID, _ in pairs(toys) do WWTCSaved.toys[#WWTCSaved.toys + 1] = itemID end if #WWTCSaved.toys > maxScannedToys then maxScannedToys = #WWTCSaved.toys print("WoWthing_Collector: scanned", maxScannedToys, "toys") end end function wwtc:ScanOrderHallResearch() if charData == nil then return end local talentTreeIDs = C_Garrison.GetTalentTreeIDsByClassID(Enum.GarrisonType.Type_7_0, charClassID) if talentTreeIDs and talentTreeIDs[1] then charData.orderHallResearch = {} local talentTree = C_Garrison.GetTalentTreeInfo(talentTreeIDs[1]) for _, talent in ipairs(talentTree.talents) do if talent.selected then local finishes = 0 if talent.isBeingResearched then finishes = talent.researchStartTime + talent.researchDuration end charData.orderHallResearch[talent.tier+1] = { id = talent.id, finishes = finishes, } end end end -- { -- ["isBeingResearched"] = true, -- ["description"] = "Increase the number of Legendary items you can equip by 1.", -- ["perkSpellID"] = 0, -- ["researchCost"] = 5000, -- ["researchDuration"] = 86400, -- ["tier"] = 5, -- ["selected"] = true, -- ["icon"] = 1247265, -- ["researched"] = false, -- ["talentAvailability"] = 8, -- ["id"] = 423, -- ["researchCurrency"] = 1220, -- ["name"] = "Demonic Fate", -- ["researchTimeRemaining"] = 35918, -- ["uiOrder"] = 0, -- ["researchGoldCost"] = 0, -- ["researchStartTime"] = 1524344516, -- }, -- [14] end ------------------------------------------------------------------------------- -- Util functions ------------------------------------------------------------------------------- -- Parse an item link and return useful information function wwtc:ParseItemLink(link, count) local parts = { strsplit(":", link) } local item = { count = count, itemID = tonumber(parts[2]), bonusIDs = {}, gems = {}, } if parts[3] ~= '' then item.enchantID = tonumber(parts[3]) end if parts[4] ~= '' then for i = 4, 7 do if parts[i] then item.gems[#item.gems + 1] = tonumber(parts[i]) end end end if parts[8] ~= '' then item.suffixID = tonumber(parts[8]) end -- 9 = uniqueID -- 10 = linkLevel -- 11 = specializationID -- 12 = modifiersMask if parts[13] ~= '' then item.context = tonumber(parts[13]) end local numBonusIDs = tonumber(parts[14]) if numBonusIDs ~= nil then for i = 15, 14 + numBonusIDs do item.bonusIDs[#item.bonusIDs + 1] = tonumber(parts[i]) end end -- 15 + numBonusIds = numModifiers -- <modifiers> local effectiveILvl, _, _ = GetDetailedItemLevelInfo(link) item.itemLevel = effectiveILvl item.quality = C_Item.GetItemQualityByID(link) -- count:id:context:enchant:ilvl:quality:suffix:bonusIDs:gems return table.concat({ item.count, item.itemID, item.context or 0, item.enchantID or 0, item.itemLevel or 0, item.quality or 0, item.suffixID or 0, table.concat(item.bonusIDs, ','), table.concat(item.gems, ','), }, ':') --return item end -- Returns the daily quest reset time in the local timezone function wwtc:GetDailyResetTime() local resetTime = GetQuestResetTime() if not resetTime or resetTime <= 0 or resetTime > (24 * 60 * 60) + 30 then return nil end return time() + resetTime end function wwtc:GetItemLevel(itemLink) local effectiveLevel, _, _ = GetDetailedItemLevelInfo(itemLink) return effectiveLevel end ------------------------------------------------------------------------------- SLASH_WWTC1 = "/wwtc" SlashCmdList["WWTC"] = function(msg) wwtc:ScanAchievements() end SLASH_RL1 = "/rl" SlashCmdList["RL"] = function(msg) ReloadUI() end
local ck = require('resty.cookie') local cookie_store = ngx.shared[ngx.var.COOKIE_STORE] local cookie_name = "NGXCAS" function first_access() -- CAS_URI and CAS_SERVICEREG are both trusted return ngx.redirect( ngx.var.CAS_URI .. "/login?service=" .. ngx.var.CAS_SERVICEREG, ngx.HTTP_MOVED_TEMPORARILY) end function set_cookie_and_store(max_age, cookie_val, ticket_val) local cookie = ck:new() -- place cookie into cookie store local success, err, forcible = cookie_store:add( cookie_val, true, max_age) if not success then if err == "no memory" then -- the add method will attempt to clear out all LRU entries -- if it doesn't have sufficient memory to do an insertion, -- but if it got here then even that didn't help. ngx.log(ngx.EMERG, "Cookie store is out of memory") return false elseif err == "exists" then -- we don't do anything, since this in itself has a very low -- probability of occurring (the user just has to log in again) return false end end -- if that was okay, then place cookie into the browser cookie:set({ key=cookie_name, value=cookie_val, max_age=max_age, path=ngx.var.uri }) return true end function generate_cookie() local resty_random = require('resty.random') local str = require("resty.string") local strong_random = resty_random.bytes(32, true) while strong_random == nil do strong_random = resty_random.bytes(32, true) end return "CK-" .. str.to_hex(strong_random) end function validate_with_CAS(ticket) -- send a subrequest to CAS/validate w/ the ticket local res = ngx.location.capture(ngx.var.CAS_URI .. "/validate", { args = { ticket = ticket, service = ngx.var.CAS_SERVICEREG } }) -- did the response from CAS have the string "yes" in it? if res.status == ngx.HTTP_OK and res.body ~= nil and string.find(res.body, "yes") then local max_age = (ngx.var.COOKIE_EXPIRY or 3600) local cookie_val = generate_cookie() -- fails on low memory or on duplicate (for now) if not set_cookie_and_store(max_age, cookie_val, ticket) then return first_access() end else return first_access() end end function validate_cookie(cookie) -- does the cookie exist in our store? if cookie_store:get(cookie) == nil then -- the cookie was probably destroyed by us in SLO previously -- so we expire it immediately. Otherwise the client hits -- an infinite loop if the invalid cookie still exists. local cookie = ck:new() cookie:set({ key=cookie_name, value="", max_age=-1 }) return first_access() end end function destroy_cookie(cookie) -- destroys cookie for logout cookie_store:delete(cookie) end return { first_access = first_access; validate_with_CAS = validate_with_CAS; validate_cookie = validate_cookie; destroy_cookie = destroy_cookie; }
local MIN_LEVEL = 44 LevelUpEnemyState = State:new() function LevelUpEnemyState:needToRun(game_context, bot_context) -- must be in battle if not game_context.battle.is_in_battle then return false end local character_has_lvlup = false for character_index = 0,2 do local character = game_context.characters[character_index] character_has_lvlup = character_has_lvlup or character.has_command_lvlup end -- someone must have the level up command if not character_has_lvlup then return false end -- all enemies must either be a card or alive local has_low_level_enemy = false local has_high_level_enemy = false for enemy_index = 0,3 do local enemy = game_context.battle.enemies[enemy_index] --console.writeline('enemy level: ' .. enemy.level) if enemy.exists and enemy.is_card == false and enemy.is_alive == false then return false end if enemy.exists and enemy.is_card == false and enemy.is_alive and enemy.level < MIN_LEVEL then has_low_level_enemy = true end if enemy.exists and enemy.is_card == false and enemy.is_alive and enemy.level >= MIN_LEVEL then has_high_level_enemy = true end end -- level up one, get rid of one, etc if has_high_level_enemy then return false end local all_enemies_are_cards = true for enemy_index = 0,3 do local enemy = game_context.battle.enemies[enemy_index] if enemy.exists and not enemy.is_card then all_enemies_are_cards = false break end end return all_enemies_are_cards == false and has_low_level_enemy end function LevelUpEnemyState:writeText(game_context, bot_context) local y_offset = 30 gui.text(0, y_offset + 0, "level up") for enemy_index = 0,3 do local enemy = game_context.battle.enemies[enemy_index] if enemy.exists then local message = '' .. enemy_index .. ': ' .. enemy.level if enemy.is_card then message = '' .. enemy_index .. ': CARD' elseif not enemy.is_alive then message = '' .. enemy_index .. ': DEAD' end gui.text(0, y_offset + 15 + (enemy_index * 15), message) end end end function LevelUpEnemyState:run(game_context, bot_context, keys) local character_with_lvlup = nil for character_index = 0,2 do if game_context.characters[character_index].has_command_lvlup then character_with_lvlup = character_index break end end if character_with_lvlup == nil then return end -- pass the turn if the active character doesn't have the level up command, but a character who does can act if game_context.battle.active_character ~= character_with_lvlup then if game_context.characters[character_with_lvlup].can_act and bot_context.characters[character_with_lvlup].can_act then pressAndRelease(bot_context, keys, 'Circle') end return end local enemy_to_level = nil for enemy_index = 0,3 do local enemy = game_context.battle.enemies[enemy_index] if enemy.exists and not enemy.is_card and enemy.is_alive and enemy.level < MIN_LEVEL then enemy_to_level = enemy_index break end end if enemy_to_level == nil then return end -- select 'level up' if game_context.battle.is_main_menu_active then -- DF2B == 'level up' if game_context.battle.menu_id == 0xDF2B then pressAndRelease(bot_context, keys, 'Cross') else pressAndRelease(bot_context, keys, 'Down') end -- select enemy elseif game_context.battle.menu_id == 0x3070 or game_context.battle.menu_id == 0x3090 or game_context.battle.menu_id == 0x30B0 then if game_context.battle.target_enemy ~= enemy_to_level then bot_context.card_attack_moves = bot_context.card_attack_moves or 0 if bot_context.card_attack_moves < 50 then pressAndRelease(bot_context, keys, 'Left') else pressAndRelease(bot_context, keys, 'Up') end bot_context.card_attack_moves = bot_context.card_attack_moves + 1 else pressAndRelease(bot_context, keys, 'Cross') bot_context.characters[game_context.battle.active_character].queued = true bot_context.card_attack_moves = nil end end end
function model.getAvailableCameras() local l=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0) local retL={} for i=1,#l,1 do local data=sim.readCustomDataBlock(l[i],simBWF.modelTags.RAGNARCAMERA) if data then retL[#retL+1]={simBWF.getObjectAltName(l[i]),l[i]} end end return retL end function model.getModelRagnarCameraConnection(modelHandle) -- returns true if ragnarCamera is connected to selected visionBox: if modelHandle~=-1 then for i=1,4,1 do if simBWF.getReferencedObjectHandle(model.handle,model.objRefIdx.CAMERA1+i-1)==modelHandle then return model.handle end end end return -1 end function model.disconnectRagnarCameraConnection(modelHandle) print("logging") local refreshDlg=false if modelHandle~=-1 then for i=1,4,1 do if simBWF.getReferencedObjectHandle(model.handle,model.objRefIdx.CAMERA1+i-1)==modelHandle then simBWF.setReferencedObjectHandle(model.handle,model.objRefIdx.CAMERA1+i-1,-1) refreshDlg=true break end end end if refreshDlg then model.dlg.refresh() end end function model.getAvailableVisionWindows() local l=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0) local retL={} for i=1,#l,1 do local data=sim.readCustomDataBlock(l[i],simBWF.modelTags.VISIONWINDOW) if data then retL[#retL+1]={simBWF.getObjectAltName(l[i]),l[i]} end end return retL end function model.getAvailableLocationFrames() local l=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0) local retL={} for i=1,#l,1 do local data=sim.readCustomDataBlock(l[i],simBWF.modelTags.LOCATIONFRAME) if data then retL[#retL+1]={simBWF.getObjectAltName(l[i]),l[i]} end end return retL end function sysCall_init() model.codeVersion=1 model.dlg.init() model.handleJobConsistency(simBWF.isModelACopy_ifYesRemoveCopyTag(model.handle)) model.updatePluginRepresentation() end function sysCall_nonSimulation() model.dlg.showOrHideDlgIfNeeded() model.updatePluginRepresentation() end function sysCall_beforeSimulation() local c=model.readInfo() if sim.boolAnd32(c.bitCoded,1)>0 then sim.setObjectInt32Parameter(model.handles.body,sim.objintparam_visibility_layer,0) model.dlg.removeDlg() end model.simJustStarted=true model.ext.outputBrSetupMessages() model.ext.outputPluginSetupMessages() end function sysCall_sensing() if model.simJustStarted then model.dlg.updateEnabledDisabledItems() end model.simJustStarted=nil model.dlg.showOrHideDlgIfNeeded() model.ext.outputPluginRuntimeMessages() end function sysCall_afterSimulation() sim.setObjectInt32Parameter(model.handles.body,sim.objintparam_visibility_layer,1) model.dlg.showOrHideDlgIfNeeded() model.dlg.updateEnabledDisabledItems() model.updatePluginRepresentation() end function sysCall_beforeInstanceSwitch() model.dlg.removeDlg() model.removeFromPluginRepresentation() end function sysCall_afterInstanceSwitch() model.updatePluginRepresentation() end function sysCall_cleanup() model.dlg.removeDlg() model.removeFromPluginRepresentation() model.dlg.cleanup() end
#!/usr/bin/env tarantool local set = require "set" set.config{ memtx_dir = "files", vinyl_dir = "files", wal_dir = "logs" } set.server{ host = "127.0.0.1", port = 8080, modules = { "example" } }
deathWatchRescueScientistConvoTemplate = ConvoTemplate:new { initialScreen = "", templateType = "Lua", luaClassHandler = "deathWatchRescueScientistConvoHandler", screens = {} } thanks1 = ConvoScreen:new { id = "thanks1", leftDialog = "@conversation/death_watch_rescue_scientist:s_d3b5ac87", -- Ah! I'm so glad you've come! I thought I was done for! Here, take this as a symbol of my appreciation. I need to get out of here! stopConversation = "true", options = { } } deathWatchRescueScientistConvoTemplate:addScreen(thanks1); thanks2 = ConvoScreen:new { id = "thanks2", leftDialog = "@conversation/death_watch_rescue_scientist:s_b4b8c363", -- Whew! Thank you for rescuing me. I appreciate it! I have to get out of here quickly! stopConversation = "true", options = { } } deathWatchRescueScientistConvoTemplate:addScreen(thanks2); thanks3 = ConvoScreen:new { id = "thanks3", leftDialog = "@conversation/death_watch_rescue_scientist:s_8801c9a5", -- Thank you for rescuing me. I am truly in your debt. Forgive me, but I must get out of here quickly. Thank you again. stopConversation = "true", options = { } } deathWatchRescueScientistConvoTemplate:addScreen(thanks3); return_thanks = ConvoScreen:new { id = "return_thanks", leftDialog = "@conversation/death_watch_rescue_scientist:s_bbc873d5", -- Thank you for saving me earlier. Getting out is harder than I thought. I'm devising my plan for escape now. You needn't worry about me anymore. stopConversation = "true", options = { } } deathWatchRescueScientistConvoTemplate:addScreen(return_thanks); addConversationTemplate("deathWatchRescueScientistConvoTemplate", deathWatchRescueScientistConvoTemplate);
local mod = get_mod("rwaon_talents") ------------------------------------------------------------------------------ -- Double Duration Burn Dots DoubleBurnDotLookup = { sienna_adept_ability_trail = "sienna_adept_ability_trail_double", burning_dot = "burning_dot_double", burning_1W_dot = "burning_1W_dot_double", burning_flamethrower_dot = "burning_flamethrower_dot_double", burning_3W_dot = "burning_3W_dot_double", beam_burning_dot = "beam_burning_dot_double", burning_geiser_dot = "burning_geiser_dot_double" } mod:add_buff("burning_dot_double", { duration = 4.5, name = "burning dot", end_flow_event = "smoke", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", apply_buff_func = "start_dot_damage", time_between_dot_damages = 0.1, damage_type = "burninating", damage_profile = "burning_dot", update_func = "apply_dot_damage" }) mod:add_buff("burning_geiser_dot_double", { duration = 7.5, name = "burning dot", end_flow_event = "smoke", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", apply_buff_func = "start_dot_damage", time_between_dot_damages = 1, damage_type = "burninating", damage_profile = "burning_geiser_dot", update_func = "apply_dot_damage" }) mod:add_buff("beam_burning_dot_double", { duration = 4.5, name = "burning dot", end_flow_event = "smoke", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", apply_buff_func = "start_dot_damage", time_between_dot_damages = 1, damage_type = "burninating", damage_profile = "beam_burning_dot", update_func = "apply_dot_damage", }) mod:add_buff("burning_flamethrower_dot_double", { duration = 2.25, name = "burning dot", end_flow_event = "smoke", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", apply_buff_func = "start_dot_damage", max_stacks = 1, refresh_durations = true, time_between_dot_damages = 0.65, damage_type = "burninating", damage_profile = "flamethrower_burning_dot", update_func = "apply_dot_damage", }) mod:add_buff("sienna_adept_ability_trail_double", { apply_buff_func = "start_dot_damage", name = "burning dot", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", end_flow_event = "smoke", time_between_dot_damages = 0.125, damage_type = "burninating", damage_profile = "burning_dot", update_func = "apply_dot_damage" }) mod:add_buff("burning_1W_dot_double", { duration = 3, name = "burning dot", end_flow_event = "smoke", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", apply_buff_func = "start_dot_damage", time_between_dot_damages = 1.5, damage_type = "burninating", damage_profile = "burning_dot", update_func = "apply_dot_damage" }) mod:add_buff("burning_3W_dot_double", { duration = 4.5, name = "burning dot", end_flow_event = "smoke", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", apply_buff_func = "start_dot_damage", time_between_dot_damages = 1.25, damage_type = "burninating", damage_profile = "burning_dot", update_func = "apply_dot_damage" }) -- Armour Burn Dots ArmourBurnDotLookup = { sienna_adept_ability_trail = "sienna_adept_ability_trail_armour", burning_dot = "burning_dot_armour", burning_1W_dot = "burning_1W_dot_armour", burning_flamethrower_dot = "burning_flamethrower_dot_armour", burning_3W_dot = "burning_3W_dot_armour", beam_burning_dot = "beam_burning_dot_armour", burning_geiser_dot = "burning_geiser_dot_armour" } mod:add_buff("burning_dot_armour", { duration = 3, name = "burning dot", end_flow_event = "smoke", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", apply_buff_func = "start_dot_damage", time_between_dot_damages = 0.1, damage_type = "burninating", damage_profile = "burning_dot", update_func = "apply_dot_damage", hit_zone = "head", }) mod:add_buff("burning_geiser_dot_armour", { duration = 5, name = "burning dot", end_flow_event = "smoke", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", apply_buff_func = "start_dot_damage", time_between_dot_damages = 1, damage_type = "burninating", damage_profile = "burning_geiser_dot", update_func = "apply_dot_damage", hit_zone = "head", }) mod:add_buff("beam_burning_dot_armour", { duration = 2.25, name = "burning dot", end_flow_event = "smoke", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", apply_buff_func = "start_dot_damage", time_between_dot_damages = 1, damage_type = "burninating", damage_profile = "beam_burning_dot", update_func = "apply_dot_damage", hit_zone = "head", }) mod:add_buff("burning_flamethrower_dot_armour", { duration = 1.5, name = "burning dot", end_flow_event = "smoke", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", apply_buff_func = "start_dot_damage", max_stacks = 1, refresh_durations = true, time_between_dot_damages = 0.65, damage_type = "burninating", damage_profile = "flamethrower_burning_dot", update_func = "apply_dot_damage", hit_zone = "head", }) mod:add_buff("sienna_adept_ability_trail_armour", { apply_buff_func = "start_dot_damage", name = "burning dot", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", end_flow_event = "smoke", time_between_dot_damages = 0.25, damage_type = "burninating", damage_profile = "burning_dot", update_func = "apply_dot_damage", hit_zone = "head", }) mod:add_buff("burning_1W_dot_armour", { duration = 2, name = "burning dot", end_flow_event = "smoke", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", apply_buff_func = "start_dot_damage", time_between_dot_damages = 1.5, damage_type = "burninating", damage_profile = "burning_dot", update_func = "apply_dot_damage", hit_zone = "head", }) mod:add_buff("burning_3W_dot_armour", { duration = 3, name = "burning dot", end_flow_event = "smoke", start_flow_event = "burn", death_flow_event = "burn_death", remove_buff_func = "remove_dot_damage", apply_buff_func = "start_dot_damage", time_between_dot_damages = 1.25, damage_type = "burninating", damage_profile = "burning_dot", update_func = "apply_dot_damage", hit_zone = "head", }) ------------------------------------------------------------------------------ -- Activating new burn dots if have Boiling Blood local buff_params = {} local function add_dot(dot_template_name, hit_unit, attacker_unit, damage_source, power_level) if ScriptUnit.has_extension(hit_unit, "buff_system") then table.clear(buff_params) buff_params.attacker_unit = attacker_unit buff_params.damage_source = damage_source buff_params.power_level = power_level local buff_extension = ScriptUnit.extension(hit_unit, "buff_system") buff_extension:add_buff(dot_template_name, buff_params) end end mod:hook_origin(Dots, "burning_dot", function (dot_template_name, damage_profile, target_index, power_level, target_unit, attacker_unit, hit_zone_name, damage_source, boost_curve_multiplier, is_critical_strike) if damage_profile then dot_template_name = dot_template_name or target_settings.dot_template_name or damage_profile.dot_template_name end if not dot_template_name then return false end local talent_extension = ScriptUnit.has_extension(attacker_unit, "talent_system") if talent_extension then local breed = AiUtils.unit_breed(target_unit) local infinite_burn_talent = talent_extension:has_talent("sienna_adept_infinite_burn", "bright_wizard") local double_dot_duration_talent = talent_extension:has_talent("rwaon_sienna_scholar_double_dot_duration", "bw_scholar") local armour_dot_duration_talent = talent_extension:has_talent("rwaon_sienna_scholar_armour_dot", "bw_scholar") if infinite_burn_talent and breed then dot_template_name = InfiniteBurnDotLookup[dot_template_name] end if double_dot_duration_talent and breed then dot_template_name = DoubleBurnDotLookup[dot_template_name] end if armour_dot_duration_talent and breed then dot_template_name = ArmourBurnDotLookup[dot_template_name] end end add_dot(dot_template_name, target_unit, attacker_unit, damage_source, power_level) return true end)
--[[ A HashVocabulary object. Initialized from a file with one HashVocabulary token per line. Maps between HashVocabulary tokens and indices. If an UNK token is defined in the HashVocabulary, returns the index to this token if queried for an out-of-HashVocabulary token. --]] local HashVocab = torch.class('datasets.HashVocab') function HashVocab:__init(path, add_unk) assert(add_unk ~= nil, "Must determine whether to add unknown token or not") print("Loading HashVocabulary from path " .. path) self.hashed = true self.size = 0 self._index = {} self._tokens = {} -- Include special start symbol and end symbol local file = io.open(path) if file == nil then error("Error opening file " .. path .. "\n") end -- Gets all tokens from line via hashing and adds local function add_line(line) local hashed_items = self:hash(line) for i = 1, #hashed_items do local hashed_item = hashed_items[i] self:add(hashed_item) end end local num_lines = 0 while true do local line = file:read() num_lines = num_lines + 1 if line == nil then break end add_line(line) end file:close() local unks = {'<unk>', '<UNK>', 'UUUNKKK'} for _, tok in pairs(unks) do self.unk_index = self.unk_index or self._index[tok] if self.unk_index ~= nil then self.unk_token = tok break end end local starts = {'<s>', '<S>'} for _, tok in pairs(starts) do self.start_index = self.start_index or self._index[tok] if self.start_index ~= nil then self.start_token = tok break end end local ends = {'</s>', '</S>'} for _, tok in pairs(ends) do self.end_index = self.end_index or self._index[tok] if self.end_index ~= nil then self.end_token = tok break end end if add_unk then self:add_start_token() self:add_pad_token() self:add_end_token() self:add_unk_token() end print("Loaded all the HashVocabulary from " .. path .. " size is " .. self.size) end -- Hashes word into word vector function HashVocab:hash(w) hashed_items = {} padded_word = "#" .. w .. "#" for i = 1, #padded_word - 2 do table.insert(hashed_items, padded_word:sub(i, i + 2)) end return hashed_items end function HashVocab:contains(w) if not self._index[w] then return false end return true end function HashVocab:add(w) if self._index[w] ~= nil then return self._index[w] end self.size = self.size + 1 self._tokens[self.size] = w self._index[w] = self.size return self.size end -- returns index/hashed vocab representation -- if gpu_mode is null then assume that we want IntTensor function HashVocab:index(word, gpu_mode) assert(word ~= nil, "Must specify word to index") local tensor = torch.DoubleTensor(self.size):zero() local hashed_items = self:hash(word) for i = 1, #hashed_items do local token = hashed_items[i] local index = self._index[token] if index == nil then if self.unk_index == nil then error('Token not in HashVocabulary and no UNK token defined: ' .. w) else index = self.unk_index end end tensor[index] = tensor[index] + 1 end return tensor end function HashVocab:token(i) if i < 1 or i > self.size then error('Index ' .. i .. ' out of bounds') end return self._tokens[i] end function HashVocab:tokens(indeces) local output = {} local len = #indeces for i = 1, len do output[i] = self:token(indeces[i]) end return output end -- Converts tokens including unknowns to IntTensor -- tokens: a table of strings function HashVocab:map(tokens) assert(tokens ~= nil, "Tokens must not be null") local len = #tokens local output = torch.DoubleTensor(len, self.size) for i = 1, len do output[i] = self:index(tokens[i]) end return output end -- Converts tokens excluding unknowns to int indeces function HashVocab:map_no_unk(tokens) assert(tokens ~= nil, "Tokens must not be null") self:map(tokens) end function HashVocab:add_pad_token() if self.unk_token ~= nil then return end self.pad_index = self:add('<pad>') end function HashVocab:add_unk_token() if self.unk_token ~= nil then return end self.unk_index = self:add('<unk>') end function HashVocab:add_start_token() if self.start_token ~= nil then return end self.start_index = self:add('<s>') end function HashVocab:add_end_token() if self.end_token ~= nil then return end self.end_index = self:add('</s>') end
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0216-widget-support.md -- -- Description:Check SDL rejects request with "INVALID_ID" result code if app tries to delete Main window -- -- Precondition: -- 1) SDL and HMI are started and MAIN window created during HMI started -- 2) DeleteWindow is allowed by policies -- 3) App is registered and activated -- Steps: -- 1) App send DeleteWindow request with MAIN WindowID to SDL -- SDL does: -- - send DeleteWindow response with (success = false, resultCode = INVALID_ID") to App -- - not send UI.DeleteWindow(WindowID) request to HMI -- - not send OnSystemCapabilityUpdated notification to App --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local common = require('test_scripts/WidgetSupport/common') --[[ Scenario ]] common.Title("Preconditions") common.Step("Clean environment and Back-up/update PPT", common.precondition) common.Step("Start SDL, init HMI", common.start) common.Step("Register App", common.registerAppWOPTU) common.Step("Activate App", common.activateApp) common.Title("Test") common.Step("Delete MAIN window", common.deleteWindowUnsuccess, { 0, "INVALID_ID" }) common.Title("Postconditions") common.Step("Stop SDL, restore SDL settings and PPT", common.postcondition)
class 'Overseer' function Overseer:__init( ... ) -- The Overseer is a helper class, an entity makes a request to the Overseer to get information -- from a clients game, line of sight is the only request at the moment. -- The Overseer takes that request, finds a player that's in the area relevant to the request -- sends the request off to the player then hands the information back to the entity that -- requested it when its received. self.recent_requests = {} self.task_queue = {} Network:Subscribe( 'PlayerCalculationReceive', self, self.PlayerCalculationReceive ) self.task_id = 0 self.callbacks = {} end function Overseer:Tick() if #self.task_queue == 0 then return end -- task_queue is a backlog of requests, they're automatically killed if not handed to a player -- within 2 seconds of the request being made. local i = 1 while i <= #self.task_queue do local task = self.task_queue[i] if task.timer:GetSeconds() > 2 then -- remove task, request has likely become irrelevant table.remove( self.task_queue, i ) else if task.entity and IsValid( task.entity ) and task.entity.network_object and IsValid(task.entity.network_object) then local found_slave = self:RequestLoSCalculation( task.cell, task.a, task.b, task.entity, task.taskId, true ) if found_slave then -- task was issued successfully table.remove( self.task_queue, i ) else i = i + 1 end else -- entity which made the request no longer valid table.remove( self.task_queue, i ) end end end end function Overseer:RequestLoSCalculation( cell, a, b, entity, taskId, tickTask ) local player_table = {} local found_slave = false if not taskId then taskId = self:GetTaskId() end if entity and IsValid(entity) then for player in entity.network_object:GetStreamedPlayers() do if player and IsValid(Player) then local pId = player:GetId() if not self.recent_requests[pId] then -- this player hasn't been tasked recently self.recent_requests[pId] = Timer() self:RequestPlayerCalculation( player, a, b, entity, taskId ) found_slave = true break else if self.recent_requests[pId]:GetMilliseconds() > 200 then self.recent_requests[pId]:Restart() self:RequestPlayerCalculation( player, a, b, entity, taskId ) found_slave = true break end end end end end -- if the task is coming from the tick event, we don't want to add it to the -- task_queue again. if tickTask then return found_slave, taskId end -- code will only go past this point if the request came directly from an entity if not found_slave then local task = { cell = cell, a = a, b = b, entity = entity, timer = Timer(), taskId = taskId } table.insert( self.task_queue, task ) end return found_slave, taskId end function Overseer:RequestPlayerCalculation( player, a, b, entity, taskId ) local entityId = entity.network_object:GetId() local t = { from = a, to = b, entityId = entityId, taskId = taskId } Network:Send( player, 'RequestPlayerCalculation', t ) t.entity = entity self.callbacks[entityId] = t end function Overseer:PlayerCalculationReceive( t, sender ) local entityId = t.entityId local info = self.callbacks[entityId] if info then local entity = info.entity info.result = t.result -- hand the info back to the entity if entity and IsValid(entity) then entity:LoSRequest( info ) end end -- cleanup self.callbacks[entityId] = nil end function Overseer:GetTaskId( ... ) if self.task_id > 1000 then self.task_id = 0 end self.task_id = self.task_id + 1 return self.task_id end OS = Overseer()
--- Core index module. -- Modules -- local af = require("arrayfire_lib") -- Forward declarations -- -- Exports -- local M = {} -- See also: https://github.com/arrayfire/arrayfire/blob/devel/src/api/cpp/index.cpp -- function M.Add (array_module) -- Import these here since the array module is not yet registered. --[[ /// /// \brief Wrapper for af_index. /// /// This class is a wrapper for the af_index struct in the C interface. It /// allows implicit type conversion from valid indexing types like int, /// \ref af::seq, \ref af_seq, and \ref af::array. /// /// \note This is a helper class and does not necessarily need to be created /// explicitly. It is used in the operator() overloads to simplify the API. /// class AFAPI index { af_index_t impl; public: /// /// \brief Default constructor. Equivalent to \ref af::span /// index(); ~index(); /// /// \brief Implicit int converter /// /// Indexes the af::array at index \p idx /// /// \param[in] idx is the id of the index /// /// \sa indexing /// index(const int idx); /// /// \brief Implicit seq converter /// /// Indexes the af::array using an \ref af::seq object /// /// \param[in] s0 is the set of indices to parse /// /// \sa indexing /// index(const af::seq& s0); /// /// \brief Implicit seq converter /// /// Indexes the af::array using an \ref af_seq object /// /// \param[in] s0 is the set of indices to parse /// /// \sa indexing /// index(const af_seq& s0); /// /// \brief Implicit int converter /// /// Indexes the af::array using an \ref af::array object /// /// \param[in] idx0 is the set of indices to parse /// /// \sa indexing /// index(const af::array& idx0); #if AF_API_VERSION >= 31 /// /// \brief Copy constructor /// /// \param[in] idx0 is index to copy. /// /// \sa indexing /// index(const index& idx0); #endif /// /// \brief Returns true if the \ref af::index represents a af::span object /// /// \returns true if the af::index is an af::span /// bool isspan() const; /// /// \brief Gets the underlying af_index_t object /// /// \returns the af_index_t represented by this object /// const af_index_t& get() const; ]] --[[ array lookup(const array &in, const array &idx, const int dim) { af_array out = 0; AF_THROW(af_lookup(&out, in.get(), idx.get(), getFNSD(dim, in.dims()))); return array(out); } void copy(array &dst, const array &src, const index &idx0, const index &idx1, const index &idx2, const index &idx3) { unsigned nd = dst.numdims(); af_index_t indices[] = {idx0.get(), idx1.get(), idx2.get(), idx3.get()}; af_array lhs = dst.get(); const af_array rhs = src.get(); AF_THROW(af_assign_gen(&lhs, lhs, nd, indices, rhs)); } index::index() { impl.idx.seq = af_span; impl.isSeq = true; impl.isBatch = false; } index::index(const int idx) { impl.idx.seq = af_make_seq(idx, idx, 1); impl.isSeq = true; impl.isBatch = false; } index::index(const af::seq& s0) { impl.idx.seq = s0.s; impl.isSeq = true; impl.isBatch = s0.m_gfor; } index::index(const af_seq& s0) { impl.idx.seq = s0; impl.isSeq = true; impl.isBatch = false; } index::index(const af::array& idx0) { array idx = idx0.isbool() ? where(idx0) : idx0; af_array arr = 0; AF_THROW(af_retain_array(&arr, idx.get())); impl.idx.arr = arr; impl.isSeq = false; impl.isBatch = false; } index::index(const af::index& idx0) { *this = idx0; } index::~index() { if (!impl.isSeq) af_release_array(impl.idx.arr); } index & index::operator=(const index& idx0) { impl = idx0.get(); if(impl.isSeq == false){ // increment reference count to avoid double free // when/if idx0 is destroyed AF_THROW(af_retain_array(&impl.idx.arr, impl.idx.arr)); } return *this; } #if __cplusplus > 199711L index::index(index &&idx0) { impl = idx0.impl; } index& index::operator=(index &&idx0) { impl = idx0.impl; return *this; } #endif static bool operator==(const af_seq& lhs, const af_seq& rhs) { return lhs.begin == rhs.begin && lhs.end == rhs.end && lhs.step == rhs.step; } bool index::isspan() const { return impl.isSeq == true && impl.idx.seq == af_span; } const af_index_t& index::get() const { return impl; } ]] end -- TODO: Add "index" environment type? -- Export the module. return M
object_mobile_halloween_skeleton_1 = object_mobile_shared_halloween_skeleton_1:new { } ObjectTemplates:addTemplate(object_mobile_halloween_skeleton_1, "object/mobile/halloween_skeleton_1.iff")
project "Light Engine" kind "StaticLib" staticruntime "on" cppdialect "C++17" language "C++" targetdir (TargetDir) objdir (ObjectDir) defines "_CRT_SECURE_NO_WARNINGS" files "%{prj.location}/**.**" excludes "%{prj.location}/**.vcxproj**" pchheader "ltpch.h" pchsource "src/Engine/ltpch.cpp" links { "glfw" , "glad" , "ImGui" , "freetype" , "spdlog" , "opengl32.lib" , "irrKlang.lib" , } includedirs { "%{prj.location}/src/Engine/" , "%{prj.location}/src/" , "%{wks.location}/glfw/include" , "%{wks.location}/glad/" , "%{wks.location}/ImGui/" , "%{wks.location}/freetype/" , "%{wks.location}/spdlog/" , "%{wks.location}/Dependencies/glm/" , "%{wks.location}/Dependencies/irrKlang/include" , "%{wks.location}/Dependencies/stb_image" , } libdirs { "%{wks.location}/Dependencies/irrKlang/lib" , } -- Operating System filter "system:not windows" excludes "%{prj.location}/src/Platform/DirectX**" filter "system:windows" links { "d3d11.lib" , "dxguid.lib" , "D3DCompiler.lib" , } -- Configurations filter "configurations:debug" defines "LIGHT_DEBUG" optimize "debug" runtime "debug" symbols "on" filter "configurations:release" defines "LIGHT_RELEASE" optimize "on" runtime "release" filter "configurations:distribution" defines "LIGHT_DIST" optimize "on" runtime "release"
local Dta = select(2, ...) --[[ shopping list structure: list = { <type> = { name = <item name> amount = <required number>, -- only ater ScanInventory(): stock = <total available>, shelf = { <id> = <stack size>, ... } }, ... } ]] -- compile a list of inventory items available for requested items function Dta.losa.ScanInventory(shoppingList, includeBags, includeBank) local slots = {} if includeBags then slots[Utility.Item.Slot.Inventory()] = true -- "si", means all inventory slots end if includeBank then slots[Utility.Item.Slot.Vault()] = true -- "sv", means all vault tabs slots[Utility.Item.Slot.Bank()] = true -- "sb", means all slots of bank's bags, end -- plus the 8 bag slots themselves local inventory = Inspect.Item.List(slots) for _s, id in pairs(inventory) do if id then -- empty slots are set to "false"...usually local item = Inspect.Item.Detail(id) -- sometimes empty slots have IDs but return nil here if item then local cart_item = shoppingList[item.type] if item ~= nil and cart_item ~= nil then if not cart_item.shelf then cart_item.shelf = {} cart_item.stock = 0 end cart_item.stock = cart_item.stock + (item.stack or 1) --'stack' field only available for stackable items cart_item.shelf[id] = item.stack or 1 end end end end end -- compile a list of selected items available for requested items function Dta.losa.ScanSelection(shoppingList) for id, item in pairs(Dta.selectedItems) do local cart_item = shoppingList[item.type] if cart_item ~= nil then if not cart_item.shelf then cart_item.shelf = {} cart_item.stock = 0 end cart_item.stock = cart_item.stock + 1 cart_item.shelf[id] = 1 end end end -- check availability and compile a list of missing items, if any function Dta.losa.checkShoppingList(shoppingList, NrCopies) NrCopies = NrCopies or 1 local missingItems = {} for item, entry in pairs(shoppingList) do if not entry.stock then missingItems[item] = entry.amount * NrCopies else local missing = entry.amount * NrCopies - entry.stock if missing > 0 then missingItems[item] = missing end end end return next(missingItems) and missingItems end -- print missing items to fullfill a shopping list function Dta.losa.printMissingItems(missing, shoppingList, message) Dta.CPrint(message) for id, amount in pairs(missing) do local stock = shoppingList[id].stock or 0 Dta.CPrint(string.format("%s: %d (%d/%d)", shoppingList[id].name, amount, stock, stock+amount)) end end
require 'nn' require 'cltorch' nn.Threshold.baseUpdateOutput = nn.Threshold.updateOutput nn.Threshold.baseUpdateGradInput = nn.Threshold.updateGradInput local function floatToString(val) local valstring = tostring(val) if valstring:find('%.') or valstring:find('e') then valstring = valstring .. 'f' end return valstring end function nn.Threshold.updateOutput(self, input) if torch.type(input) ~= 'torch.ClTensor' then return self:baseUpdateOutput(input) end self.thresholdstring = floatToString(self.threshold) self.valstring = floatToString(self.val) if self.inplace then input:apply_on_gpu("*out = (*out > " .. self.thresholdstring .. ") ? *out : " .. self.valstring) self.output = input else self.output:resize(input:size()) self.output:map_on_gpu(input, "*out = ( *in1 > " .. self.thresholdstring .. ") ? *in1 : " .. self.valstring) end return self.output end function nn.Threshold.updateGradInput(self, input, gradOutput) if torch.type(input) ~= 'torch.ClTensor' then return self:baseUpdateGradInput(input, gradOutput) end local nElement = self.gradInput:nElement() self.gradInput:resizeAs(input) if self.gradInput:nElement() ~= nElement then self.gradInput:zero() end if self.inplace then gradOutput:map2_on_gpu(input, gradOutput, "*out = (*in1 > " .. self.thresholdstring .. ") ? *in2 : 0.0f") self.gradInput = gradOutput else self.gradInput:map2_on_gpu(input, gradOutput, "*out = (*in1 > " .. self.thresholdstring .. ") ? *in2 : 0.0f") end return self.gradInput end
TweakDataHelper = TweakDataHelper or {} local tdh = TweakDataHelper tdh._storage = {} tdh._overwrite_storage = {} tdh._callbacks = {} function tdh:ModifyTweak(data, ...) local dest_tbl = tweak_data or self._storage local path = {...} local key = table.remove(path) for _, k in pairs(path) do dest_tbl[k] = dest_tbl[k] or {} dest_tbl = dest_tbl[k] end if type(dest_tbl[key]) == "table" then table.add_merge(dest_tbl[key], data) else dest_tbl[key] = data end end function tdh:OverwriteTweak(data, ...) table.insert(self._overwrite_storage, {path = {...}, data = data}) if tweak_data then self:ApplyOverwrites(tweak_data) end end function tdh:ModifyTweakFunc(tbl_name, clbk) self._callbacks[tbl_name] = self._callbacks[tbl_name] or {} table.insert(self._callbacks[tbl_name], clbk) end --Takes tweak_main and tweak_data_tbl for cases where this is being called from a tweak init function as it wont have been inserted into the tweak_data main table yet. function tdh:Apply(tweak_main, tweak_data_tbl, tbl_name) tweak_data_tbl = tweak_data_tbl or (tbl_name and tweak_main[tbl_name]) or tweak_main or tweak_data table.add_merge(tweak_data_tbl, (tbl_name and self._storage[tbl_name] or self._storage) or {}) self:ApplyOverwrites(tweak_data_tbl) if tbl_name then self._storage[tbl_name] = nil if self.callback[tbl_name] then for _, func in pairs(self.callbacks[tbl_name]) do func(tweak_data_tbl or tweak_main[tbl_name], tweak_main) end self.callbacks[tbl_name] = nil end else self._storage = {} for k, sub_tbl in pairs(self._callbacks) do for _, func in pairs(sub_tbl) do func(tweak_main[k], tweak_main) end end end end function tdh:ApplyOverwrites(tweak_data_tbl) for _, overwrite in pairs(self._overwrite_storage) do local current = tweak_data_tbl or tweak_data for i, key in pairs(overwrite.path) do current[key] = current[key] or {} if #overwrite.path == i then current[key] = overwrite.data else current = current[key] end end end self._overwrite_storage = nil end
local Roact = require(game:GetService("ReplicatedStorage").Roact) local Settings = require(script.Parent.Parent.Parent.Parent:WaitForChild("Settings")) local BlipController = require(script.Parent.Parent.BlipController) local ToolTip = require(script.Parent.ToolTip) local TagController = require(script.Parent.Parent.Parent.TagController) local BorderSnap = require(script:WaitForChild("BorderSnap")) local Players = game:GetService("Players") local plr = Players.LocalPlayer local cam = game.Workspace.CurrentCamera local blip = Roact.Component:extend("Blip") function blip:init() self:setState({ Position = UDim2.new(0, 0, 0, 0); Rotation = 0; Visible = true; }) end function blip:render() local Object = self.props.Object local Pos = self.state.Position local Rot = self.state.Rotation local Vis = self.state.Visible local TagInfo = TagController:findTag(self.props.TagName) return Roact.createElement("ImageButton", { BackgroundTransparency = TagInfo.transparency or Settings["Gui"]["blipTransparency"]; BorderSizePixel = Settings["Gui"]["blipBorderSizePixel"]; BackgroundColor3 = Settings["Gui"]["blipColor"]; BorderColor3 = Settings["Gui"]["blipBorderColor"]; AnchorPoint = Vector2.new(.5,.5); AutoButtonColor = false; Size = TagInfo.size; ImageColor3 = TagInfo.color; Image = "rbxassetid://"..TagInfo.iconID; Position = Pos; Rotation = Rot; Visible = Vis; [Roact.Event.MouseEnter] = function(rbx) --Show tooltip if not TagInfo.toolTip or TagInfo.toolTip == "" then return end self.toolTip = Roact.mount(Roact.createElement(ToolTip, {Text = TagInfo.toolTip; Blip = rbx;}), plr:WaitForChild("PlayerGui")) end; [Roact.Event.MouseLeave] = function(rbx) --Hide tooltip if not self.toolTip then return end Roact.unmount(self.toolTip) end; }) end function blip:didMount() self.renderLoop = game:GetService("RunService").RenderStepped:connect(function() if BlipController:getDistanceFromPlayer(self.props.Object.Position) <= Settings["Technical"]["maxBlipDistance"] then local Pos = BlipController:getUIPosition(Vector3.new(self.props.Object.Position.X, 0, self.props.Object.Position.Z) / Settings["Divide"]) local Rotation = 0 local TagInfo = TagController:findTag(self.props.TagName) --Getting the position of the blip. if TagInfo.snapToBorder == true then self.state.Visible = true --Pos = Vector2.new(math.clamp(Pos.X, 0, Settings["Gui"]["mapSize"].X.Offset), math.clamp(Pos.Y, 0, Settings["Gui"]["mapSize"].Y.Offset)) Pos = BorderSnap:ClampToBorder(Pos, Vector2.new(Settings["Gui"]["mapSize"].X.Offset, Settings["Gui"]["mapSize"].Y.Offset), Settings["Gui"]["mapCornerRoundness"]) else local n = BorderSnap:ClampToBorder(Pos, Vector2.new(Settings["Gui"]["mapSize"].X.Offset, Settings["Gui"]["mapSize"].Y.Offset), Settings["Gui"]["mapCornerRoundness"]) if n.X ~= Pos.X or n.Y ~= Pos.Y then self.state.Visible = false elseif self.state.Visible == false then self.state.Visible = true end end if TagInfo.rotate == true then --Get the rotation of the object local direction = cam.CFrame.lookVector local heading = math.atan2(direction.x,direction.z) heading = math.deg(heading) Rotation = heading - self.props.Object.Orientation.Y + 180 end self:setState(function(state) return{ Position = UDim2.new(0, Pos.X, 0, Pos.Y); Rotation = Rotation; } end) elseif self.state.Visible == true then self:setState(function(state) return{ Visible = false } end) end end) end function blip:willUnmount() self.renderLoop:Disconnect() if self.toolTip then Roact.unmount(self.toolTip) end end return blip
function EFFECT:Init( effectdata ) self.pos = effectdata:GetOrigin()+Vector(0,0,100) self.Entity:SetPos(self.pos) self.em = ParticleEmitter(self.pos) self.Die = CurTime()+0.1 end function EFFECT:Think() for i=1,3 do local x = math.random(-2,2)*10 local y = math.random(-2,2)*10 local part = self.em:Add("particles/smokey",self.pos+Vector(x,y,0)) part:SetColor(math.random(150,255),20,20,255) part:SetVelocity(Vector(0,0,-1000)) part:SetCollide(true) part:SetDieTime(0.7) part:SetStartAlpha(50) part:SetAirResistance(100) part:SetEndAlpha(0) part:SetLifeTime(0) part:SetStartSize(10) end return self.Die > CurTime() end function EFFECT:Render() end
love.filesystem.load('libs/utils.lua')() utils=new_utils() love.filesystem.load('libs/acid.lua')() acid=new_acid() acid.update=utils.set_timer(acid.update,1/60) love.filesystem.load('libs/object_utils.lua')() o_utils=new_object_utils() love.filesystem.load('libs/cellAM.lua')() cellam1=new_cellAM(80,60) cellam1.new_cells() cell_rule=function(x,y) local sum=0 for i=-1,1 do for j=-1,1 do sum=sum+cellam1.access_cell(x+i,y+j).status end end sum=sum-cellam1.access_cell(x,y).status if sum==3 then return 1 end if sum==2 then return cellam1.access_cell(x,y).status end return 0 end cell_print=function(s,x,y) if s==1 then R,G,B=acid.raibow(x*y/10) love.graphics.setColor(R,G,B) love.graphics.rectangle('fill',(x-1)*10,(y-1)*10,10,10) end end cellam1.next_age=utils.set_timer(cellam1.next_age,0.1) font4banner1=love.graphics.newFont('fonts/famib.ttf',80) font4banner2=love.graphics.newFont('fonts/famib.ttf',30) font4normal=love.graphics.newFont('fonts/famib.ttf',80) banner=o_utils.new_obj() banner.isVisible=true banner.show=function(x,y) love.graphics.setFont(font4banner2) acid.banner("test project ",400,130) love.graphics.setFont(font4banner1) acid.banner("LIFE GAME IN LOVE2D",400,190) end banner2=o_utils.new_obj() banner2.isVisible=true banner2.isTouchable=true str2="START!" str1="STOP!" toggle=true banner2.isHit=o_utils.collision_sq( 400-font4normal:getWidth(str1)/2, 400+font4normal:getWidth(str1)/2, 400-font4normal:getHeight(str1)/2, 400+font4normal:getHeight(str1)/2) function redsky() R,G,B=acid.raibow() Ramp=16;Rbias=239;Gamp=40;Gbias=80;Bamp=16;Bbias=19 return (R*Ramp+Rbias)/255,(G*Gamp+Gbias)/255,(B*Bamp+Bbias)/255 end banner2.show=function(x,y) if banner2.isHit(x,y) then if love.mouse.isDown(1) then acid.pop(400-font4normal:getWidth(str1)/2, 400+font4normal:getWidth(str1)/2, 400-font4normal:getHeight(str1)/2, 400+font4normal:getHeight(str1)/2,1) else acid.pop(400-font4normal:getWidth(str1)/2, 400+font4normal:getWidth(str1)/2, 400-font4normal:getHeight(str1)/2, 400+font4normal:getHeight(str1)/2) end end love.graphics.setFont(font4normal) acid.print(str1,400,400,0,1,1,love.graphics.getFont():getWidth(str1)/2,love.graphics.getFont():getHeight(str1)/2) end function banner2.released(button,x,y) if button==1 then toggle=not toggle tmp=str1 str1=str2 str2=tmp end end lyr=o_utils.new_layer() lyr.insert(banner2) lyr.insert(banner) cellam1.access_cell(3,3).status=1 cellam1.access_cell(2,3).status=1 cellam1.access_cell(1,3).status=1 cellam1.access_cell(3,2).status=1 cellam1.access_cell(2,1).status=1 --updates drawer and updater utils.update_draw(function() cellam1.show(cell_print) lyr.show(utils.getMouseX(),utils.getMouseY()) love.graphics.setBackgroundColor(redsky()) end) utils.update_update(function() if love.mouse.isDown(1) then cellam1.access_cell(math.floor(1+utils.getMouseX()/10),math.floor(1+utils.getMouseY()/10)).status=1 end if love.mouse.isDown(2) then cellam1.access_cell(math.floor(1+utils.getMouseX()/10),math.floor(1+utils.getMouseY()/10)).status=0 end if toggle==true then cellam1.access_cell(-1,-1).status=0 cellam1.next_age(cell_rule) end acid.update() function love.mousereleased(x,y,button,istouch) lyr.released(button,utils.getMouseX(),utils.getMouseY()) end end)
sptbl["delay"] = { files = { module = "delay.c", header = "delay.h", example = "ex_delay.c", }, func = { create = "ut_delay_create", destroy = "ut_delay_destroy", init = "ut_delay_init", compute = "ut_delay_compute", }, params = { mandatory = { { name = "time", type = "UTFLOAT", description = "Delay time, in seconds.", default = 1.0 } }, optional = { { name = "feedback", type = "UTFLOAT", description = "Feedback amount. Should be a value between 0-1.", default = 0.0 } } }, modtype = "module", description = [[Adds a delay to an incoming signal with optional feedback.]], ninputs = 1, noutputs = 1, inputs = { { name = "input", description = "Signal input." }, }, outputs = { { name = "out", description = "Signal output." }, } }
--[[ MyGame.Example.TestSimpleTableWithEnum Automatically generated by the FlatBuffers compiler, do not modify. Or modify. I'm a message, not a cop. flatc version: 2.0.6 Declared by : //monster_test.fbs Rooting type : MyGame.Example.Monster (//monster_test.fbs) --]] local flatbuffers = require('flatbuffers') local TestSimpleTableWithEnum = {} local mt = {} function TestSimpleTableWithEnum.New() local o = {} setmetatable(o, {__index = mt}) return o end function mt:Init(buf, pos) self.view = flatbuffers.view.New(buf, pos) end function mt:Color() local o = self.view:Offset(4) if o ~= 0 then return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o) end return 2 end function TestSimpleTableWithEnum.Start(builder) builder:StartObject(1) end function TestSimpleTableWithEnum.AddColor(builder, color) builder:PrependUint8Slot(0, color, 2) end function TestSimpleTableWithEnum.End(builder) return builder:EndObject() end return TestSimpleTableWithEnum
require('plenary.reload').reload_module('telescope') local tester = require('telescope.pickers._test') describe('scrolling strategies', function() it('should handle cycling for full list', function() tester.run_file [[find_files__scrolling_descending_cycle]] end) end)
object_tangible_loot_mustafar_cube_loot_cube_loot_1k = object_tangible_loot_mustafar_cube_loot_shared_cube_loot_1k:new { } ObjectTemplates:addTemplate(object_tangible_loot_mustafar_cube_loot_cube_loot_1k, "object/tangible/loot/mustafar/cube/loot/cube_loot_1k.iff")
local Elements = { -----------[[ ADMINS ]]----------------- Ranks = { ["Owner"] = {"brandonisabillionare", "Player1"}; -- All commands, full power, stops admin, and other ownery things ["Admin"] = {"FoodForDays345"}; -- Most commands, can kick, ban, crash, and has power in servers ["Member"] = {"Friend", "Other Friend"}; -- Some commands, no kick, ban, crash, shutdown, no real power ["Banned"] = {"Noob", "Butt"}; -- Can't join ["Crashed"] = {"TurdHead", "BiggerNoob"}; -- Get's lagged >:D ["Muted"] = {"Hacker", "Exploiter"}; -- Can join server, but they can't chat(Great for nooby hackers) }; ---------------------------------------- -----------[[ SETTINGS ]]--------------- FUN = true; -- Eveyone likes fun! so why not me true! If your place is a military place and you have no scene of humor you can change it to false LagTime = 5; -- The crash command disconnects the player. then the time set here will count down until lag Prefix = ";"; -- What you say before a command. The ";" in [ ;kill me ] Bet = " "; -- Separates arguments(Cannot be slash or dash or it will become space) EnableAdminMenu = true; -- Set true or false if you want to enable the admin menu Filter = {"GetObjects"}; -- Used for Anti-Exploits. If someone says anything on this list they will be kicked. ServerLocked = false; -- Used to kick non-admins when they join DisableAbuse = false; -- Disables abusive command like kill,fling,loopfling,ect... (FOR MEMBER RANK ONLY) -------------------------------------- -----------[[ VIPS ]]----------------- VIPMemberID = 0; -- Put the gamepass ID for people to have member access, leave 0 if you do not want it VIPAdminID = 0; -- Put the gamepass ID for people to have admin access, leave 0 if you do not want it -------------------------------------- -----------[[ GROUPS ]]--------------- GroupID = 0; -- Links group to admin, leave 0 if you do not want to do so GroupMemberRank = 0; -- the lowest rank that will get admin commands[Member Rank], If you have linked a group to this DO NOT make 0 GroupAdminRank = 0; -- the lowest rank that will get admin commands[Admin Rank], If you have linked a group to this DO NOT make 0 GroupOwnerRank = 0; -- the lowest rank that will get admin commands[Owner Rank], If you have linked a group to this DO NOT make 0 RankBan = 0; -- 1st arguments is what action a rank will be from a group, 2nd is the rank -------------------------------------- -----------[[ BADGES ]]--------------- BadgeID = 0; -- Leave 0 if you don't want people to have admin when they get a badge[Member Rank], otherwise, put in badge ID -------------------------------------- } return Elements
--[[ Copyright 2021 Manticore Games, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Author: Burnzie Keeps a vehicle spawned at a location after a set delay. To use: Drag and drop the script into the scene and set a vehicle template for it to spawn. Feel free to adjust position and rotation of the script --]] local TEMPLATE = script:GetCustomProperty("Vehicle") local DELAY = script:GetCustomProperty("TimeToRespawn") local eventHandler = nil local spawnedVehicle = nil local vehicleHasDied = false local countdown = DELAY function Spawn() spawnedVehicle = World.SpawnAsset(TEMPLATE, {position = script:GetWorldPosition(), rotation = script:GetWorldRotation()}) eventHandler = spawnedVehicle.destroyEvent:Connect(Destroyed) vehicleHasDied = false end function Destroyed() eventHandler:Disconnect() spawnedVehicle = nil vehicleHasDied = true end function Tick(dt) if vehicleHasDied then countdown = countdown - dt if countdown < 0 then countdown = DELAY Spawn() end end end Spawn()
local default_settings = { fileencoding = "utf-8", -- Incremental live completion, default on `master` inccommand = "nosplit", -- Use system clipboard clipboard = vim.opt.clipboard + "unnamedplus", -- Hide the `-- INSERT --` messages showmode = false, -- Highlight searches when done searching hlsearch = true, -- Enable relative line numbers number = true, relativenumber = true, -- Increase width of number columns and always show sign column numberwidth = 4, signcolumn = "yes", -- For faster completion updatetime = 250, timeoutlen = 500, completeopt = { "menu", "menuone", "noinsert" }, -- Tabs vs spaces, make indenting great again smartindent = true, expandtab = true, breakindent = true, shiftwidth = 2, tabstop = 2, -- Show tabs for open files on top of window showtabline = 2, -- Enable using the mouse to click around mouse = "a", -- Highlight current line cursorline = true, -- Case insensitive searching ignorecase = true, smartcase = true, -- Splitting, always below or to the right splitbelow = true, splitright = true, -- Required for switching buffers and so on hidden = true, -- Backups, swaps and history backup = false, swapfile = false, undofile = true, -- How many rows/colums to show around cursor when jumping around scrolloff = 8, sidescrolloff = 8, -- Configure themes termguicolors = true, -- Set folding to use Tree-Sitter foldmethod = "manual", foldexpr = "nvim_treesitter#foldexpr()", } for k, v in pairs(default_settings) do vim.opt[k] = v end vim.opt.shortmess:append("c")
object_tangible_loot_loot_schematic_marauder_s02_leggings_schematic = object_tangible_loot_loot_schematic_shared_marauder_s02_leggings_schematic:new { templateType = LOOTSCHEMATIC, customName = "Marauder Armor Leggings Schematic", objectMenuComponent = "LootSchematicMenuComponent", attributeListComponent = "LootSchematicAttributeListComponent", requiredSkill = "crafting_armorsmith_master", targetDraftSchematic = "object/draft_schematic/clothing/shared_clothing_armor_marauder_s02_leggings.iff", targetUseCount = 1 } ObjectTemplates:addTemplate(object_tangible_loot_loot_schematic_marauder_s02_leggings_schematic, "object/tangible/loot/loot_schematic/marauder_s02_leggings_schematic.iff")
return PlaceObj("ModDef", { "title", "Disable Annoying Sounds", "version", 3, "version_major", 0, "version_minor", 3, "saved", 0, "image", "Preview.png", "id", "ChoGGi_DisableAnnoyingSounds", "steam_id", "1816633344", "pops_any_uuid", "03c6b6ff-1afd-489e-b923-69f171b248eb", "author", "ChoGGi", "lua_revision", 249143, "code", { "Code/Script.lua", }, "has_options", true, "TagOther", true, "description", [[Stops certain sounds from happening. Sensor Tower Beeping, RC Commander Drones Deployed, Mirror Sphere Crackling, Nursery Wailing, Spacebar Music. Got another? You'll need to turn off the mod option and restart if you want to re-enable any disabled sounds.]], })
local lspsignature = require("lsp_signature") local on_attach = require("plugins.lsp_attach").on_attach local present2, lspinstall = pcall(require, "nvim-lsp-installer") if not present2 then return end lspsignature.setup({ bind = true, handler_opts = { border = "rounded", }, floating_window_above_cur_line = false, }) local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true lspinstall.on_server_ready(function(server) local opts = { capabilities = capabilities, on_attach = on_attach, } local lang = server.languages[1] if lang == "lua" then opts = vim.tbl_deep_extend("force", { root_dir = vim.loop.cwd, settings = { Lua = { diagnostics = { globals = { "vim" }, }, workspace = { library = { [vim.fn.expand("$VIMRUNTIME/lua")] = true, [vim.fn.expand("$VIMRUNTIME/lua/vim/lsp")] = true, [vim.fn.stdpath("config") .. "/lua"] = true, }, maxPreload = 100000, preloadFileSize = 10000, }, telemetry = { enable = false, }, }, }, }, opts) elseif server.name == "jsonls" or server.name == "yamlls" then local jsonls_opts = require("jsonls")[server.name] opts = vim.tbl_deep_extend("force", jsonls_opts, opts) elseif server.name == "clangd" then opts = vim.tbl_deep_extend("force", opts, { cmd = { "clangd", "--enable-config" }, }) elseif server.name == "pyright" then opts = vim.tbl_deep_extend("force", { settings = { python = { analysis = { typeCheckingMode = "off", }, }, }, }, opts) end server:setup(opts) end) -- Automatically reload after `:LspInstall <server>` so we don't have to restart neovim lspinstall.post_install_hook = function() -- setup_servers() -- reload installed servers vim.cmd("bufdo e") end -- replace the default lsp diagnostic symbols local function lspSymbol(name, icon) vim.fn.sign_define("DiagnosticSign" .. name, { texthl = "DiagnosticSign" .. name, text = icon, numhl = "" }) end lspSymbol("Error", "") lspSymbol("Warn", "") lspSymbol("Info", "") lspSymbol("Hint", "") vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { virtual_text = { prefix = "", spacing = 0, }, signs = true, underline = true, -- set this to true if you want diagnostics to show in insert mode update_in_insert = false, }) -- suppress error messages from lang servers vim.notify = function(msg, log_level, _opts) if msg:match("exit code") then return end if log_level == vim.log.levels.ERROR then vim.api.nvim_err_writeln(msg) else vim.api.nvim_echo({ { msg } }, true, {}) end end
xml = require("cheat_xml") json = dofile("../json/init.lua") function readAll(file) local f = io.open(file, "rb") local content = f:read("*all") f:close() return content end print(json.stringify(xml.conv_cheat(readAll(arg[1])), {indent = true}))
local pcall = pcall local xpcall = xpcall local traceback = debug.traceback local pairs = pairs local ipairs = ipairs local type = type local setmetatable = setmetatable local ostime = os.time local pathRegexp = require("lor.lib.utils.path_to_regexp") local utils = require("lor.lib.utils.utils") local random = utils.random local debug = require("lor.lib.debug") math.randomseed(ostime()) local Layer = {} function Layer:new(path, options, fn, fn_args_length) local opts = options or {} local instance = {} instance.handle = fn instance.name = "layer-" .. random() instance.params = {} instance.path = path instance.keys = {} instance.length = fn_args_length -- todo:shoule only be 3 or 4 instance.is_end = opts.is_end or false -- is belong to a route?;is the last really to match the path? instance.is_start = opts.is_start or false -- is belong to a route?;is the last really to match the path? local tmp_pattern = pathRegexp.parse_pattern(path, instance.keys, opts) if tmp_pattern == "" or not tmp_pattern then instance.pattern = "/" else instance.pattern = tmp_pattern end if instance.is_end then instance.pattern = instance.pattern .. "$" else instance.pattern = pathRegexp.clear_slash(instance.pattern .. "/") end if instance.is_start then instance.pattern = "^" .. pathRegexp.clear_slash("/" .. instance.pattern) else instance.pattern = instance.pattern end setmetatable(instance, { __index = self, __tostring = function(s) local ok, result = pcall(function() local route_name, is_end = "<nil>", "" if s.route then route_name = s.route.name end if s.is_end then is_end = "true" else is_end = "false" end return "(name:" .. s.name .. "\tpath:" .. s.path .. "\tlength:" .. s.length .. "\t layer.route.name:" .. route_name .. "\tpattern:" .. s.pattern .."\tis_end:" .. is_end .. ")" end) if ok then return result else return "layer.tostring() error" end end }) debug("layer.lua#new:", instance) return instance end function Layer:handle_error(err, req, res, next) debug("layer.lua#handel_error:", self, err) local fn = self.handle -- a property named 'length' to indicate its args length if self.length ~= 4 then debug("not match handle_error") next(err) return end local e local ok = xpcall(function() fn(err, req, res, next) end, function() e = (err or "") .. "\n" .. traceback() end) --print(random() .. " layer.lua - Layer:handle_error", "ok?", ok, "error:", e, "pcall_error:", e, "layer.name:", self.name) if not ok then next(e) end end function Layer:handle_request(req, res, next) debug("layer.lua#handle_request:", self) local fn = self.handle if self.length > 3 then debug("---------->not match handle_request") next() return end --local trackId = random() local e local ok, ee = xpcall(function() -- add `ee` for final handler logic fn(req, res, next) end, function(msg) e = (msg or "") .. "\n" .. traceback() end) --debug(trackId .. " layer.lua - Layer:handle_request-", "ok?", ok, "error:", e, "layer.name:", self.name, "middle_type:", self.length) if not ok then debug("handle_request:call error", ok, e, ee) next(e or ee) end end function Layer:match(path) debug("layer.lua#match before:", "path:", path, "layer:", self) if not path then self.params = nil debug("layer.lua#match 1") return false end if self.is_end then path = pathRegexp.clear_slash(path) else path = pathRegexp.clear_slash(path .. "/") end local match_or_not = pathRegexp.is_match(path, self.pattern) if not match_or_not then debug("layer.lua#match 3") return false end local m = pathRegexp.parse_path(path, self.pattern, self.keys) if m then debug("layer.lua#match 4", path, self.pattern, self.keys, m) end -- store values -- self.path = path -- self.params = mixin(m, self.params) -- this is only this layer's params self.params = m -- fixbug: the params should not be transfered to next Request. debug(function() print("layer.lua# print layer.params") if self.params then for i, v in pairs(self.params) do print(i, v) end end end) return true end return Layer
require "Global.consts" GAME_OVER_SCREEN_PATH = RESOURCES_PATH .. "/GameOverScreen/background.png"
EditorOperator = EditorOperator or class(MissionScriptEditor) function EditorOperator:create_element() self.super.create_element(self) self._element.class = "ElementOperator" self._element.values.operation = "none" self._element.values.elements = {} end function EditorOperator:_build_panel() self:_create_panel() self:BuildElementsManage("elements") self:ComboCtrl("operation", {"none","add","remove"}, {help = "Select an operation for the selected elements"}) self:Text("Choose an operation to perform on the selected elements. An element might not have the selected operation implemented and will then generate error when executed.") end
package.path = package.path .. ';' .. cfg.dir .. '/?.lua' require("fw_common"); open_by_program = "fw_edit"; -- 被 fw 编辑工具打开 is_open_by_ufw = true; output_view_tabs = {} output_bin_tabs = {} enable_moudles = { ["isdtool"] = false, ["audio"] = true, ["charge"] = true, ["status"] = true, ["tone"] = true, ["bluetooth"] = true, ["key_msg"] = {enable = true, num = 10}, }; require("common") -- 把下面这些insert放到模块里面去 insert_item_to_list(output_view_tabs, bluetooth_view); insert_item_to_list(output_view_tabs, tone_view); insert_list_to_list(output_bin_tabs, bt_output_bin_tabs); local output_bin_tabs_view = cfg:vBox { cfg:stTab(output_view_tabs); }; cfg:addFirmwareFile("cfg_tool.bin", "蓝牙配置", 2, -- 文件类型,是个bin文件 output_bin_tabs, -- 组的列表 output_bin_tabs_view );
function onCreate() -- background shit makeLuaSprite('outside', 'stages/Outside', -600, 40); setLuaSpriteScrollFactor('outside', 0.8, 0.8); scaleObject('outside', 0.8, 0.8); makeLuaSprite('inside', 'stages/BACKGROUND', -800, -370); setLuaSpriteScrollFactor('inside', 0.9, 0.9); scaleObject('inside', 0.9, 0.9); addLuaSprite('outside', false); addLuaSprite('inside', false); close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end
local StackFsm = {} function StackFsm:new(o) o = o or {} self.__index = self setmetatable(o, self) local Stack = require("stack") o.stack = Stack:new() return o end function StackFsm:getCurrentState() return self.stack:top() end function StackFsm:pushState(state) local function stateEql(s1, s2) if s1 and s2 then return (s1[1] == s2[1]) and (s1[2] == s2[2]) else return false end end if not stateEql(self:getCurrentState(), state) then self.stack:push(state) else error("push state error: same state") end end function StackFsm:popState() return self.stack:pop() end function StackFsm:update() local current_state = self:getCurrentState() if current_state then -- call table method current_state[1](current_state[2]) end end return StackFsm
if ngx.req.get_uri_args()["jump"] == "1" then ngx.req.set_uri("/lua_rewrite_foo", false); ngx.req.set_uri("/lua_rewrite_bar", false); ngx.req.set_uri_args({ a = 1, b = 2 }); end
slot0 = class("SpringFestivalTownScene2", import("..TemplateMV.BackHillTemplate")) slot0.getUIName = function (slot0) return "SpringFestivalTownUI2" end slot0.edge2area = { default = "map_middle" } slot0.init = function (slot0) slot0.super.init(slot0) slot0.top = slot0:findTF("top") slot0._bg = slot0:findTF("BG") slot0._map = slot0:findTF("map") for slot4 = 0, slot0._map.childCount - 1, 1 do slot0["map_" .. go(slot5).name] = slot0._map:GetChild(slot4) end slot0._shipTpl = slot0._map:Find("ship") slot0._upper = slot0:findTF("upper") for slot4 = 0, slot0._upper.childCount - 1, 1 do slot0["upper_" .. go(slot5).name] = slot0._upper:GetChild(slot4) end slot0.containers = { slot0.map_middle } slot0.graphPath = GraphPath.New(import("GameCfg.BackHillGraphs.SpringFestivalTownGraph2")) slot0._bg:GetComponent(typeof(UnityEngine.Canvas)).sortingOrder = ((slot0._tf:GetComponentInParent(typeof(UnityEngine.Canvas)) and slot1.sortingOrder) or 0) - 2 slot3 = GetComponent(slot0._bg, "ItemList") for slot7 = 1, 1, 1 do if not IsNil(slot3.prefabItem[slot7 - 1]) then setParent(slot9, slot0._bg) pg.ViewUtils.SetSortingOrder(tf(Instantiate(slot8)), slot2 - 1) end end end slot0.didEnter = function (slot0) onButton(slot0, slot0:findTF("top/back"), function () slot0:emit(slot1.ON_BACK) end, SFX_CANCEL) onButton(slot0, slot0:findTF("top/home"), function () slot0:emit(slot1.ON_HOME) end, SFX_PANEL) onButton(slot0, slot0:findTF("top/help"), function () pg.MsgboxMgr.GetInstance():ShowMsgBox({ type = MSGBOX_TYPE_HELP, helps = pg.gametip.help_chunjie2021_feast.tip }) end, SFX_PANEL) slot0:InitStudents(getProxy(ActivityProxy).getActivityById(slot1, ActivityConst.SPRING_FES_MINIGAME_SECOND) and slot1.id, 2, 3) slot0:InitFacilityCross(slot0._map, slot0._upper, "damaoxian", function () pg.m02:sendNotification(GAME.GO_MINI_GAME, 21) end) slot0.InitFacilityCross(slot0, slot0._map, slot0._upper, "chunyouji", function () slot0:emit(NewYearFestivalMediator.GO_SCENE, SCENE.ACTIVITY, { id = getProxy(ActivityProxy):getActivityByType(ActivityConst.ACTIVITY_TYPE_MONOPOLY) and slot0.id }) end) slot0.InitFacilityCross(slot0, slot0._map, slot0._upper, "huituriji", function () slot0:emit(NewYearFestivalMediator.GO_SCENE, SCENE.COLORING) end) slot0.InitFacilityCross(slot0, slot0._map, slot0._upper, "dajiulou", function () slot0:emit(NewYearFestivalMediator.GO_SUBLAYER, Context.New({ mediator = RedPacketMediator, viewComponent = RedPacketLayer })) end) slot0.InitFacilityCross(slot0, slot0._map, slot0._upper, "fuzhuang", function () slot0:emit(NewYearFestivalMediator.GO_SCENE, SCENE.SKINSHOP) end) slot0.InitFacilityCross(slot0, slot0._map, slot0._upper, "jianzao", function () slot0:emit(NewYearFestivalMediator.GO_SCENE, SCENE.GETBOAT, { page = 1, projectName = BuildShipScene.PROJECTS.LIGHT }) end) slot0.UpdateView(slot0) end slot0.UpdateView = function (slot0) slot4 = getProxy(MiniGameProxy) setActive(slot0.upper_huituriji:Find("Tip"), getProxy(ColoringProxy):CheckTodayTip()) setActive(slot0.upper_dajiulou:Find("Tip"), nil) setActive(slot0.upper_chunyouji:Find("Tip"), getProxy(ActivityProxy):getActivityByType(ActivityConst.ACTIVITY_TYPE_MONOPOLY) and not slot2.isEnd(nil) and slot2:readyToAchieve()) setActive(slot0.upper_damaoxian:Find("Tip"), slot3:getActivityByType(ActivityConst.ACTIVITY_TYPE_MINIGAME) and not slot2:isEnd() and slot2:readyToAchieve()) end slot0.willExit = function (slot0) slot0:clearStudents() slot0.super.willExit(slot0) end return slot0
package.path = "../src/?.lua;src/?.lua;" .. package.path pcall(require, "luarocks.require") local redis = require 'redis' local params = { host = '127.0.0.1', port = 6379, } local client = redis.connect(params) client:select(15) -- for testing purposes -- Start processing the monitor messages. Open a terminal and use redis-cli to -- send some commands to the server that will make MONITOR return some entries. local counter = 0 for msg, abort in client:monitor_messages() do counter = counter + 1 local feedback = string.format("[%d] Received %s on database %d", msg.timestamp, msg.command, msg.database) if msg.arguments then feedback = string.format('%s with arguments %s', feedback, msg.arguments) end print(feedback) if counter == 5 then abort() end end print(string.format("Closed the MONITOR context after receiving %d commands.", counter))
data.raw["gui-style"].default["red-background-image-style"] = { type = "button_style", parent = "icon_button", default_graphical_set = { type = "composition", filename = "__split_with_the_team__/graphics/custom_buttons.png", priority = "extra-high-no-scale", corner_size = {3, 3}, position = {0, 0} } } data.raw["gui-style"].default["transparent-background-image-style"] = { type = "button_style", parent = "icon_button", default_graphical_set = { type = "composition", filename = "__split_with_the_team__/graphics/custom_buttons.png", priority = "extra-high-no-scale", corner_size = {3, 3}, position = {8, 0} } }
--[[ Copyright 2015 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local HostInfo = require('./base').HostInfo local misc = require('./misc') local Transform = require('stream').Transform -------------------------------------------------------------------------------------------------------------------- local Reader = Transform:extend() function Reader:initialize() Transform.initialize(self, {objectMode = true}) end function Reader:_transform(line, cb) self:push({hostname = line}) return cb() end -------------------------------------------------------------------------------------------------------------------- --[[ Fetch this servers hostname ]]-- local Info = HostInfo:extend() function Info:initialize(params) HostInfo.initialize(self) end function Info:_run(callback) local command = 'hostname' local outTable, errTable = {}, {} local function finalCb() self:_pushParams(errTable, outTable) return callback() end local child = misc.run('sh', {'-c', command}) local reader = Reader:new() child:pipe(reader) reader:on('error', function(err) misc.safeMerge(errTable, err) end) reader:on('data', function(datum) misc.safeMerge(outTable, datum) end) reader:once('end', finalCb) end function Info:getPlatforms() return {'linux'} end function Info:getType() return 'HOSTNAME' end exports.Info = Info exports.Reader = Reader
local pl = {} ---------------- --- Lua 5.1/5.2/5.3 compatibility. -- Ensures that `table.pack` and `package.searchpath` are available -- for Lua 5.1 and LuaJIT. -- The exported function `load` is Lua 5.2 compatible. -- `compat.setfenv` and `compat.getfenv` are available for Lua 5.2, although -- they are not always guaranteed to work. -- @module pl.compat local compat = {} compat.lua51 = _VERSION == 'Lua 5.1' local isJit = (tostring(assert):match('builtin') ~= nil) if isJit then -- 'goto' is a keyword when 52 compatibility is enabled in LuaJit compat.jit52 = not loadstring("local goto = 1") end compat.dir_separator = _G.package.config:sub(1,1) compat.is_windows = compat.dir_separator == '\\' --- execute a shell command. -- This is a compatibility function that returns the same for Lua 5.1 and Lua 5.2 -- @param cmd a shell command -- @return true if successful -- @return actual return code function compat.execute (cmd) local res1,_,res3 = os.execute(cmd) if compat.lua51 and not compat.jit52 then if compat.is_windows then res1 = res1 > 255 and res1 % 256 or res1 return res1==0,res1 else res1 = res1 > 255 and res1 / 256 or res1 return res1==0,res1 end else if compat.is_windows then res3 = res3 > 255 and res3 % 256 or res3 return res3==0,res3 else return not not res1,res3 end end end ---------------- -- Load Lua code as a text or binary chunk. -- @param ld code string or loader -- @param[opt] source name of chunk for errors -- @param[opt] mode 'b', 't' or 'bt' -- @param[opt] env environment to load the chunk in -- @function compat.load --------------- -- Get environment of a function. -- With Lua 5.2, may return nil for a function with no global references! -- Based on code by [Sergey Rozhenko](http://lua-users.org/lists/lua-l/2010-06/msg00313.html) -- @param f a function or a call stack reference -- @function compat.getfenv --------------- -- Set environment of a function -- @param f a function or a call stack reference -- @param env a table that becomes the new environment of `f` -- @function compat.setfenv if compat.lua51 then -- define Lua 5.2 style load() if not isJit then -- but LuaJIT's load _is_ compatible local lua51_load = load function compat.load(str,src,mode,env) local chunk,err if type(str) == 'string' then if str:byte(1) == 27 and not (mode or 'bt'):find 'b' then return nil,"attempt to load a binary chunk" end chunk,err = loadstring(str,src) else chunk,err = lua51_load(str,src) end if chunk and env then setfenv(chunk,env) end return chunk,err end else compat.load = load end compat.setfenv, compat.getfenv = setfenv, getfenv else compat.load = load -- setfenv/getfenv replacements for Lua 5.2 -- by Sergey Rozhenko -- http://lua-users.org/lists/lua-l/2010-06/msg00313.html -- Roberto Ierusalimschy notes that it is possible for getfenv to return nil -- in the case of a function with no globals: -- http://lua-users.org/lists/lua-l/2010-06/msg00315.html function compat.setfenv(f, t) f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func) local name local up = 0 repeat up = up + 1 name = debug.getupvalue(f, up) until name == '_ENV' or name == nil if name then debug.upvaluejoin(f, up, function() return name end, 1) -- use unique upvalue debug.setupvalue(f, up, t) end if f ~= 0 then return f end end function compat.getfenv(f) local f = f or 0 f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func) local name, val local up = 0 repeat up = up + 1 name, val = debug.getupvalue(f, up) until name == '_ENV' or name == nil return val end end --- Lua 5.2 Functions Available for 5.1 -- @section lua52 --- pack an argument list into a table. -- @param ... any arguments -- @return a table with field n set to the length -- @return the length -- @function table.pack --if not table.pack then function table.pack (...) return {n=select('#',...); ...} end --end ------ -- return the full path where a Lua module name would be matched. -- @param mod module name, possibly dotted -- @param path a path in the same form as package.path or package.cpath -- @see path.package_path -- @function package.searchpath if not package.searchpath then local sep = package.config:sub(1,1) function package.searchpath (mod,path) mod = mod:gsub('%.',sep) for m in path:gmatch('[^;]+') do local nm = m:gsub('?',mod) local f = io.open(nm,'r') if f then f:close(); return nm end end end end --- Generally useful routines. -- See @{01-introduction.md.Generally_useful_functions|the Guide}. -- -- Dependencies: `pl.compat` -- -- @module pl.utils local format = string.format local stdout = io.stdout local append = table.insert local unpack = rawget(_G,'unpack') or rawget(table,'unpack') local utils = { _VERSION = "1.5.2", lua51 = compat.lua51, setfenv = compat.setfenv, getfenv = compat.getfenv, load = compat.load, execute = compat.execute, dir_separator = compat.dir_separator, is_windows = compat.is_windows, unpack = unpack } --- end this program gracefully. -- @param code The exit code or a message to be printed -- @param ... extra arguments for message's format' -- @see utils.fprintf function utils.quit(code,...) if type(code) == 'string' then utils.fprintf(io.stderr,code,...) code = -1 else utils.fprintf(io.stderr,...) end io.stderr:write('\n') os.exit(code) end --- print an arbitrary number of arguments using a format. -- @param fmt The format (see string.format) -- @param ... Extra arguments for format function utils.printf(fmt,...) utils.assert_string(1,fmt) utils.fprintf(stdout,fmt,...) end --- write an arbitrary number of arguments to a file using a format. -- @param f File handle to write to. -- @param fmt The format (see string.format). -- @param ... Extra arguments for format function utils.fprintf(f,fmt,...) utils.assert_string(2,fmt) f:write(format(fmt,...)) end local function import_symbol(T,k,v,libname) local key = rawget(T,k) -- warn about collisions! if key and k ~= '_M' and k ~= '_NAME' and k ~= '_PACKAGE' and k ~= '_VERSION' then utils.fprintf(io.stderr,"warning: '%s.%s' will not override existing symbol\n",libname,k) return end rawset(T,k,v) end local function lookup_lib(T,t) for k,v in pairs(T) do if v == t then return k end end return '?' end local already_imported = {} --- take a table and 'inject' it into the local namespace. -- @param t The Table -- @param T An optional destination table (defaults to callers environment) function utils.import(t,T) T = T or _G t = t or utils if type(t) == 'string' then t = require (t) end local libname = lookup_lib(T,t) if already_imported[t] then return end already_imported[t] = libname for k,v in pairs(t) do import_symbol(T,k,v,libname) end end utils.patterns = { FLOAT = '[%+%-%d]%d*%.?%d*[eE]?[%+%-]?%d*', INTEGER = '[+%-%d]%d*', IDEN = '[%a_][%w_]*', FILE = '[%a%.\\][:%][%w%._%-\\]*' } --- escape any 'magic' characters in a string -- @param s The input string function utils.escape(s) utils.assert_string(1,s) return (s:gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1')) end --- return either of two values, depending on a condition. -- @param cond A condition -- @param value1 Value returned if cond is true -- @param value2 Value returned if cond is false (can be optional) function utils.choose(cond,value1,value2) if cond then return value1 else return value2 end end local raise --- return the contents of a file as a string -- @param filename The file path -- @param is_bin open in binary mode -- @return file contents function utils.readfile(filename,is_bin) local mode = is_bin and 'b' or '' utils.assert_string(1,filename) local f,open_err = io.open(filename,'r'..mode) if not f then return utils.raise (open_err) end local res,read_err = f:read('*a') f:close() if not res then -- Errors in io.open have "filename: " prefix, -- error in file:read don't, add it. return raise (filename..": "..read_err) end return res end --- write a string to a file -- @param filename The file path -- @param str The string -- @param is_bin open in binary mode -- @return true or nil -- @return error message -- @raise error if filename or str aren't strings function utils.writefile(filename,str,is_bin) local mode = is_bin and 'b' or '' utils.assert_string(1,filename) utils.assert_string(2,str) local f,err = io.open(filename,'w'..mode) if not f then return raise(err) end f:write(str) f:close() return true end --- return the contents of a file as a list of lines -- @param filename The file path -- @return file contents as a table -- @raise errror if filename is not a string function utils.readlines(filename) utils.assert_string(1,filename) local f,err = io.open(filename,'r') if not f then return raise(err) end local res = {} for line in f:lines() do append(res,line) end f:close() return res end --- split a string into a list of strings separated by a delimiter. -- @param s The input string -- @param re A Lua string pattern; defaults to '%s+' -- @param plain don't use Lua patterns -- @param n optional maximum number of splits -- @return a list-like table -- @raise error if s is not a string function utils.split(s,re,plain,n) utils.assert_string(1,s) local find,sub,append = string.find, string.sub, table.insert local i1,ls = 1,{} if not re then re = '%s+' end if re == '' then return {s} end while true do local i2,i3 = find(s,re,i1,plain) if not i2 then local last = sub(s,i1) if last ~= '' then append(ls,last) end if #ls == 1 and ls[1] == '' then return {} else return ls end end append(ls,sub(s,i1,i2-1)) if n and #ls == n then ls[#ls] = sub(s,i1) return ls end i1 = i3+1 end end --- split a string into a number of values. -- @param s the string -- @param re the delimiter, default space -- @return n values -- @usage first,next = splitv('jane:doe',':') -- @see split function utils.splitv (s,re) return unpack(utils.split(s,re)) end --- convert an array of values to strings. -- @param t a list-like table -- @param temp buffer to use, otherwise allocate -- @param tostr custom tostring function, called with (value,index). -- Otherwise use `tostring` -- @return the converted buffer function utils.array_tostring (t,temp,tostr) temp, tostr = temp or {}, tostr or tostring for i = 1,#t do temp[i] = tostr(t[i],i) end return temp end local is_windows = utils.is_windows --- Quote an argument of a command. -- Quotes a single argument of a command to be passed -- to `os.execute`, `pl.utils.execute` or `pl.utils.executeex`. -- @string argument the argument. -- @return quoted argument. function utils.quote_arg(argument) if is_windows then if argument == "" or argument:find('[ \f\t\v]') then -- Need to quote the argument. -- Quotes need to be escaped with backslashes; -- additionally, backslashes before a quote, escaped or not, -- need to be doubled. -- See documentation for CommandLineToArgvW Windows function. argument = '"' .. argument:gsub([[(\*)"]], [[%1%1\"]]):gsub([[\+$]], "%0%0") .. '"' end -- os.execute() uses system() C function, which on Windows passes command -- to cmd.exe. Escape its special characters. return (argument:gsub('["^<>!|&%%]', "^%0")) else if argument == "" or argument:find('[^a-zA-Z0-9_@%+=:,./-]') then -- To quote arguments on posix-like systems use single quotes. -- To represent an embedded single quote close quoted string ('), -- add escaped quote (\'), open quoted string again ('). argument = "'" .. argument:gsub("'", [['\'']]) .. "'" end return argument end end --- execute a shell command and return the output. -- This function redirects the output to tempfiles and returns the content of those files. -- @param cmd a shell command -- @param bin boolean, if true, read output as binary file -- @return true if successful -- @return actual return code -- @return stdout output (string) -- @return errout output (string) function utils.executeex(cmd, bin) local mode local outfile = os.tmpname() local errfile = os.tmpname() if is_windows and not outfile:find(':') then outfile = os.getenv('TEMP')..outfile errfile = os.getenv('TEMP')..errfile end cmd = cmd .. " > " .. utils.quote_arg(outfile) .. " 2> " .. utils.quote_arg(errfile) local success, retcode = utils.execute(cmd) local outcontent = utils.readfile(outfile, bin) local errcontent = utils.readfile(errfile, bin) os.remove(outfile) os.remove(errfile) return success, retcode, (outcontent or ""), (errcontent or "") end --- 'memoize' a function (cache returned value for next call). -- This is useful if you have a function which is relatively expensive, -- but you don't know in advance what values will be required, so -- building a table upfront is wasteful/impossible. -- @param func a function of at least one argument -- @return a function with at least one argument, which is used as the key. function utils.memoize(func) local cache = {} return function(k) local res = cache[k] if res == nil then res = func(k) cache[k] = res end return res end end utils.stdmt = { List = {_name='List'}, Map = {_name='Map'}, Set = {_name='Set'}, MultiMap = {_name='MultiMap'} } local _function_factories = {} --- associate a function factory with a type. -- A function factory takes an object of the given type and -- returns a function for evaluating it -- @tab mt metatable -- @func fun a callable that returns a function function utils.add_function_factory (mt,fun) _function_factories[mt] = fun end local function _string_lambda(f) local raise = utils.raise if f:find '^|' or f:find '_' then local args,body = f:match '|([^|]*)|(.+)' if f:find '_' then args = '_' body = f else if not args then return raise 'bad string lambda' end end local fstr = 'return function('..args..') return '..body..' end' local fn,err = utils.load(fstr) if not fn then return raise(err) end fn = fn() return fn else return raise 'not a string lambda' end end --- an anonymous function as a string. This string is either of the form -- '|args| expression' or is a function of one argument, '_' -- @param lf function as a string -- @return a function -- @usage string_lambda '|x|x+1' (2) == 3 -- @usage string_lambda '_+1' (2) == 3 -- @function utils.string_lambda utils.string_lambda = utils.memoize(_string_lambda) local ops --- process a function argument. -- This is used throughout Penlight and defines what is meant by a function: -- Something that is callable, or an operator string as defined by <code>pl.operator</code>, -- such as '>' or '#'. If a function factory has been registered for the type, it will -- be called to get the function. -- @param idx argument index -- @param f a function, operator string, or callable object -- @param msg optional error message -- @return a callable -- @raise if idx is not a number or if f is not callable function utils.function_arg (idx,f,msg) utils.assert_arg(1,idx,'number') local tp = type(f) if tp == 'function' then return f end -- no worries! -- ok, a string can correspond to an operator (like '==') if tp == 'string' then if not ops then ops = require 'pl.operator'.optable end local fn = ops[f] if fn then return fn end local fn, err = utils.string_lambda(f) if not fn then error(err..': '..f) end return fn elseif tp == 'table' or tp == 'userdata' then local mt = getmetatable(f) if not mt then error('not a callable object',2) end local ff = _function_factories[mt] if not ff then if not mt.__call then error('not a callable object',2) end return f else return ff(f) -- we have a function factory for this type! end end if not msg then msg = " must be callable" end if idx > 0 then error("argument "..idx..": "..msg,2) else error(msg,2) end end --- bind the first argument of the function to a value. -- @param fn a function of at least two values (may be an operator string) -- @param p a value -- @return a function such that f(x) is fn(p,x) -- @raise same as @{function_arg} -- @see func.bind1 function utils.bind1 (fn,p) fn = utils.function_arg(1,fn) return function(...) return fn(p,...) end end --- bind the second argument of the function to a value. -- @param fn a function of at least two values (may be an operator string) -- @param p a value -- @return a function such that f(x) is fn(x,p) -- @raise same as @{function_arg} function utils.bind2 (fn,p) fn = utils.function_arg(1,fn) return function(x,...) return fn(x,p,...) end end --- assert that the given argument is in fact of the correct type. -- @param n argument index -- @param val the value -- @param tp the type -- @param verify an optional verification function -- @param msg an optional custom message -- @param lev optional stack position for trace, default 2 -- @raise if the argument n is not the correct type -- @usage assert_arg(1,t,'table') -- @usage assert_arg(n,val,'string',path.isdir,'not a directory') function utils.assert_arg (n,val,tp,verify,msg,lev) if type(val) ~= tp then error(("argument %d expected a '%s', got a '%s'"):format(n,tp,type(val)),lev or 2) end if verify and not verify(val) then error(("argument %d: '%s' %s"):format(n,val,msg),lev or 2) end end --- assert the common case that the argument is a string. -- @param n argument index -- @param val a value that must be a string -- @raise val must be a string function utils.assert_string (n,val) utils.assert_arg(n,val,'string',nil,nil,3) end local err_mode = 'default' --- control the error strategy used by Penlight. -- Controls how <code>utils.raise</code> works; the default is for it -- to return nil and the error string, but if the mode is 'error' then -- it will throw an error. If mode is 'quit' it will immediately terminate -- the program. -- @param mode - either 'default', 'quit' or 'error' -- @see utils.raise function utils.on_error (mode) if ({['default'] = 1, ['quit'] = 2, ['error'] = 3})[mode] then err_mode = mode else -- fail loudly if err_mode == 'default' then err_mode = 'error' end utils.raise("Bad argument expected string; 'default', 'quit', or 'error'. Got '"..tostring(mode).."'") end end --- used by Penlight functions to return errors. Its global behaviour is controlled -- by <code>utils.on_error</code> -- @param err the error string. -- @see utils.on_error function utils.raise (err) if err_mode == 'default' then return nil,err elseif err_mode == 'quit' then utils.quit(err) else error(err,2) end end --- is the object of the specified type?. -- If the type is a string, then use type, otherwise compare with metatable -- @param obj An object to check -- @param tp String of what type it should be function utils.is_type (obj,tp) if type(tp) == 'string' then return type(obj) == tp end local mt = getmetatable(obj) return tp == mt end raise = utils.raise --- load a code string or bytecode chunk. -- @param code Lua code as a string or bytecode -- @param name for source errors -- @param mode kind of chunk, 't' for text, 'b' for bytecode, 'bt' for all (default) -- @param env the environment for the new chunk (default nil) -- @return compiled chunk -- @return error message (chunk is nil) -- @function utils.load --------------- -- Get environment of a function. -- With Lua 5.2, may return nil for a function with no global references! -- Based on code by [Sergey Rozhenko](http://lua-users.org/lists/lua-l/2010-06/msg00313.html) -- @param f a function or a call stack reference -- @function utils.getfenv --------------- -- Set environment of a function -- @param f a function or a call stack reference -- @param env a table that becomes the new environment of `f` -- @function utils.setfenv --- execute a shell command. -- This is a compatibility function that returns the same for Lua 5.1 and Lua 5.2 -- @param cmd a shell command -- @return true if successful -- @return actual return code -- @function utils.execute local file = {} --- return the contents of a file as a string -- @function file.read -- @string filename The file path -- @return file contents file.read = utils.readfile --- write a string to a file -- @function file.write -- @string filename The file path -- @string str The string file.write = utils.writefile local _G = _G local sub = string.sub local getenv = os.getenv local tmpnam = os.tmpname local package = package local append, concat, remove = table.insert, table.concat, table.remove local assert_string,raise = utils.assert_string,utils.raise local attrib local path = {} local lfs = require "lfs" getfenv(1).lfs = nil -- lfs is an 'old-school' module, hence global pollution local attributes = lfs.attributes local currentdir = lfs.currentdir local link_attrib = lfs.symlinkattributes attrib = attributes path.attrib = attrib path.link_attrib = link_attrib --- Lua iterator over the entries of a given directory. -- Behaves like `lfs.dir` path.dir = lfs.dir --- Creates a directory. path.mkdir = lfs.mkdir --- Removes a directory. path.rmdir = lfs.rmdir ---- Get the working directory. path.currentdir = currentdir --- Changes the working directory. path.chdir = lfs.chdir --- is this a directory? -- @string P A file path function path.isdir(P) assert_string(1,P) if P:match("\\$") then P = P:sub(1,-2) end return attrib(P,'mode') == 'directory' end --- is this a file?. -- @string P A file path function path.isfile(P) assert_string(1,P) return attrib(P,'mode') == 'file' end -- is this a symbolic link? -- @string P A file path function path.islink(P) assert_string(1,P) if link_attrib then return link_attrib(P,'mode')=='link' else return false end end --- return size of a file. -- @string P A file path function path.getsize(P) assert_string(1,P) return attrib(P,'size') end --- does a path exist?. -- @string P A file path -- @return the file path if it exists, nil otherwise function path.exists(P) assert_string(1,P) return attrib(P,'mode') ~= nil and P end --- Return the time of last access as the number of seconds since the epoch. -- @string P A file path function path.getatime(P) assert_string(1,P) return attrib(P,'access') end --- Return the time of last modification -- @string P A file path function path.getmtime(P) return attrib(P,'modification') end ---Return the system's ctime. -- @string P A file path function path.getctime(P) assert_string(1,P) return path.attrib(P,'change') end local function at(s,i) return sub(s,i,i) end path.is_windows = utils.is_windows local other_sep -- !constant sep is the directory separator for this platform. if path.is_windows then path.sep = '\\'; other_sep = '/' path.dirsep = ';' else path.sep = '/' path.dirsep = ':' end local sep,dirsep = path.sep,path.dirsep --- are we running Windows? -- @class field -- @name path.is_windows --- path separator for this platform. -- @class field -- @name path.sep --- separator for PATH for this platform -- @class field -- @name path.dirsep --- given a path, return the directory part and a file part. -- if there's no directory part, the first value will be empty -- @string P A file path function path.splitpath(P) assert_string(1,P) local i = #P local ch = at(P,i) while i > 0 and ch ~= sep and ch ~= other_sep do i = i - 1 ch = at(P,i) end if i == 0 then return '',P else return sub(P,1,i-1), sub(P,i+1) end end --- return an absolute path. -- @string P A file path -- @string[opt] pwd optional start path to use (default is current dir) function path.abspath(P,pwd) assert_string(1,P) if pwd then assert_string(2,pwd) end local use_pwd = pwd ~= nil if not use_pwd and not currentdir then return P end P = P:gsub('[\\/]$','') pwd = pwd or currentdir() if not path.isabs(P) then P = path.join(pwd,P) elseif path.is_windows and not use_pwd and at(P,2) ~= ':' and at(P,2) ~= '\\' then P = pwd:sub(1,2)..P -- attach current drive to path like '\\fred.txt' end return path.normpath(P) end --- given a path, return the root part and the extension part. -- if there's no extension part, the second value will be empty -- @string P A file path -- @treturn string root part -- @treturn string extension part (maybe empty) function path.splitext(P) assert_string(1,P) local i = #P local ch = at(P,i) while i > 0 and ch ~= '.' do if ch == sep or ch == other_sep then return P,'' end i = i - 1 ch = at(P,i) end if i == 0 then return P,'' else return sub(P,1,i-1),sub(P,i) end end --- return the directory part of a path -- @string P A file path function path.dirname(P) assert_string(1,P) local p1,p2 = path.splitpath(P) return p1 end --- return the file part of a path -- @string P A file path function path.basename(P) assert_string(1,P) local p1,p2 = path.splitpath(P) return p2 end --- get the extension part of a path. -- @string P A file path function path.extension(P) assert_string(1,P) local p1,p2 = path.splitext(P) return p2 end --- is this an absolute path?. -- @string P A file path function path.isabs(P) assert_string(1,P) if path.is_windows then return at(P,1) == '/' or at(P,1)=='\\' or at(P,2)==':' else return at(P,1) == '/' end end --- return the path resulting from combining the individual paths. -- if the second (or later) path is absolute, we return the last absolute path (joined with any non-absolute paths following). -- empty elements (except the last) will be ignored. -- @string p1 A file path -- @string p2 A file path -- @string ... more file paths function path.join(p1,p2,...) assert_string(1,p1) assert_string(2,p2) if select('#',...) > 0 then local p = path.join(p1,p2) local args = {...} for i = 1,#args do assert_string(i,args[i]) p = path.join(p,args[i]) end return p end if path.isabs(p2) then return p2 end local endc = at(p1,#p1) if endc ~= path.sep and endc ~= other_sep and endc ~= "" then p1 = p1..path.sep end return p1..p2 end --- normalize the case of a pathname. On Unix, this returns the path unchanged; -- for Windows, it converts the path to lowercase, and it also converts forward slashes -- to backward slashes. -- @string P A file path function path.normcase(P) assert_string(1,P) if path.is_windows then return (P:lower():gsub('/','\\')) else return P end end --- normalize a path name. -- A//B, A/./B and A/foo/../B all become A/B. -- @string P a file path function path.normpath(P) assert_string(1,P) -- Split path into anchor and relative path. local anchor = '' if path.is_windows then if P:match '^\\\\' then -- UNC anchor = '\\\\' P = P:sub(3) elseif at(P, 1) == '/' or at(P, 1) == '\\' then anchor = '\\' P = P:sub(2) elseif at(P, 2) == ':' then anchor = P:sub(1, 2) P = P:sub(3) if at(P, 1) == '/' or at(P, 1) == '\\' then anchor = anchor..'\\' P = P:sub(2) end end P = P:gsub('/','\\') else -- According to POSIX, in path start '//' and '/' are distinct, -- but '///+' is equivalent to '/'. if P:match '^//' and at(P, 3) ~= '/' then anchor = '//' P = P:sub(3) elseif at(P, 1) == '/' then anchor = '/' P = P:match '^/*(.*)$' end end local parts = {} for part in P:gmatch('[^'..sep..']+') do if part == '..' then if #parts ~= 0 and parts[#parts] ~= '..' then remove(parts) else append(parts, part) end elseif part ~= '.' then append(parts, part) end end P = anchor..concat(parts, sep) if P == '' then P = '.' end return P end local function ATS (P) if at(P,#P) ~= path.sep then P = P..path.sep end return path.normcase(P) end --- relative path from current directory or optional start point -- @string P a path -- @string[opt] start optional start point (default current directory) function path.relpath (P,start) assert_string(1,P) if start then assert_string(2,start) end local split,normcase,min,append = utils.split, path.normcase, math.min, table.insert P = normcase(path.abspath(P,start)) start = start or currentdir() start = normcase(start) local startl, Pl = split(start,sep), split(P,sep) local n = min(#startl,#Pl) if path.is_windows and n > 0 and at(Pl[1],2) == ':' and Pl[1] ~= startl[1] then return P end local k = n+1 -- default value if this loop doesn't bail out! for i = 1,n do if startl[i] ~= Pl[i] then k = i break end end local rell = {} for i = 1, #startl-k+1 do rell[i] = '..' end if k <= #Pl then for i = k,#Pl do append(rell,Pl[i]) end end return table.concat(rell,sep) end --- Replace a starting '~' with the user's home directory. -- In windows, if HOME isn't set, then USERPROFILE is used in preference to -- HOMEDRIVE HOMEPATH. This is guaranteed to be writeable on all versions of Windows. -- @string P A file path function path.expanduser(P) assert_string(1,P) if at(P,1) == '~' then local home = getenv('HOME') if not home then -- has to be Windows home = getenv 'USERPROFILE' or (getenv 'HOMEDRIVE' .. getenv 'HOMEPATH') end return home..sub(P,2) else return P end end ---Return a suitable full path to a new temporary file name. -- unlike os.tmpnam(), it always gives you a writeable path (uses TEMP environment variable on Windows) function path.tmpname () local res = tmpnam() -- On Windows if Lua is compiled using MSVC14 os.tmpname -- already returns an absolute path within TEMP env variable directory, -- no need to prepend it. if path.is_windows and not res:find(':') then res = getenv('TEMP')..res end return res end --- return the largest common prefix path of two paths. -- @string path1 a file path -- @string path2 a file path function path.common_prefix (path1,path2) assert_string(1,path1) assert_string(2,path2) path1, path2 = path.normcase(path1), path.normcase(path2) -- get them in order! if #path1 > #path2 then path2,path1 = path1,path2 end for i = 1,#path1 do local c1 = at(path1,i) if c1 ~= at(path2,i) then local cp = path1:sub(1,i-1) if at(path1,i-1) ~= sep then cp = path.dirname(cp) end return cp end end if at(path2,#path1+1) ~= sep then path1 = path.dirname(path1) end return path1 --return '' end --- return the full path where a particular Lua module would be found. -- Both package.path and package.cpath is searched, so the result may -- either be a Lua file or a shared library. -- @string mod name of the module -- @return on success: path of module, lua or binary -- @return on error: nil,error string function path.package_path(mod) assert_string(1,mod) local res mod = mod:gsub('%.',sep) res = package.searchpath(mod,package.path) if res then return res,true end res = package.searchpath(mod,package.cpath) if res then return res,false end return raise 'cannot find module on path' end --- Provides a reuseable and convenient framework for creating classes in Lua. -- Two possible notations: -- -- B = class(A) -- class.B(A) -- -- The latter form creates a named class within the current environment. Note -- that this implicitly brings in `pl.utils` as a dependency. -- -- See the Guide for further @{01-introduction.md.Simplifying_Object_Oriented_Programming_in_Lua|discussion} -- @module pl.class local error, getmetatable, io, pairs, rawget, rawset, setmetatable, tostring, type = _G.error, _G.getmetatable, _G.io, _G.pairs, _G.rawget, _G.rawset, _G.setmetatable, _G.tostring, _G.type local compat -- this trickery is necessary to prevent the inheritance of 'super' and -- the resulting recursive call problems. local function call_ctor (c,obj,...) -- nice alias for the base class ctor local base = rawget(c,'_base') if base then local parent_ctor = rawget(base,'_init') while not parent_ctor do base = rawget(base,'_base') if not base then break end parent_ctor = rawget(base,'_init') end if parent_ctor then rawset(obj,'super',function(obj,...) call_ctor(base,obj,...) end) end end local res = c._init(obj,...) rawset(obj,'super',nil) return res end --- initializes an __instance__ upon creation. -- @function class:_init -- @param ... parameters passed to the constructor -- @usage local Cat = class() -- function Cat:_init(name) -- --self:super(name) -- call the ancestor initializer if needed -- self.name = name -- end -- -- local pussycat = Cat("pussycat") -- print(pussycat.name) --> pussycat --- checks whether an __instance__ is derived from some class. -- Works the other way around as `class_of`. It has two ways of using; -- 1) call with a class to check against, 2) call without params. -- @function instance:is_a -- @param some_class class to check against, or `nil` to return the class -- @return `true` if `instance` is derived from `some_class`, or if `some_class == nil` then -- it returns the class table of the instance -- @usage local pussycat = Lion() -- assuming Lion derives from Cat -- if pussycat:is_a(Cat) then -- -- it's true, it is a Lion, but also a Cat -- end -- -- if pussycat:is_a() == Lion then -- -- It's true -- end local function is_a(self,klass) if klass == nil then -- no class provided, so return the class this instance is derived from return getmetatable(self) end local m = getmetatable(self) if not m then return false end --*can't be an object! while m do if m == klass then return true end m = rawget(m,'_base') end return false end --- checks whether an __instance__ is derived from some class. -- Works the other way around as `is_a`. -- @function some_class:class_of -- @param some_instance instance to check against -- @return `true` if `some_instance` is derived from `some_class` -- @usage local pussycat = Lion() -- assuming Lion derives from Cat -- if Cat:class_of(pussycat) then -- -- it's true -- end local function class_of(klass,obj) if type(klass) ~= 'table' or not rawget(klass,'is_a') then return false end return klass.is_a(obj,klass) end --- cast an object to another class. -- It is not clever (or safe!) so use carefully. -- @param some_instance the object to be changed -- @function some_class:cast local function cast (klass, obj) return setmetatable(obj,klass) end local function _class_tostring (obj) local mt = obj._class local name = rawget(mt,'_name') setmetatable(obj,nil) local str = tostring(obj) setmetatable(obj,mt) if name then str = name ..str:gsub('table','') end return str end local function tupdate(td,ts,dont_override) for k,v in pairs(ts) do if not dont_override or td[k] == nil then td[k] = v end end end local function _class(base,c_arg,c) -- the class `c` will be the metatable for all its objects, -- and they will look up their methods in it. local mt = {} -- a metatable for the class to support __call and _handler -- can define class by passing it a plain table of methods local plain = type(base) == 'table' and not getmetatable(base) if plain then c = base base = c._base else c = c or {} end if type(base) == 'table' then -- our new class is a shallow copy of the base class! -- but be careful not to wipe out any methods we have been given at this point! tupdate(c,base,plain) c._base = base -- inherit the 'not found' handler, if present if rawget(c,'_handler') then mt.__index = c._handler end elseif base ~= nil then error("must derive from a table type",3) end c.__index = c setmetatable(c,mt) if not plain then c._init = nil end if base and rawget(base,'_class_init') then base._class_init(c,c_arg) end -- expose a ctor which can be called by <classname>(<args>) mt.__call = function(class_tbl,...) local obj if rawget(c,'_create') then obj = c._create(...) end if not obj then obj = {} end setmetatable(obj,c) if rawget(c,'_init') then -- explicit constructor local res = call_ctor(c,obj,...) if res then -- _if_ a ctor returns a value, it becomes the object... obj = res setmetatable(obj,c) end elseif base and rawget(base,'_init') then -- default constructor -- make sure that any stuff from the base class is initialized! call_ctor(base,obj,...) end if base and rawget(base,'_post_init') then base._post_init(obj) end return obj end -- Call Class.catch to set a handler for methods/properties not found in the class! c.catch = function(self, handler) if type(self) == "function" then -- called using . instead of : handler = self end c._handler = handler mt.__index = handler end c.is_a = is_a c.class_of = class_of c.cast = cast c._class = c if not rawget(c,'__tostring') then c.__tostring = _class_tostring end return c end --- create a new class, derived from a given base class. -- Supporting two class creation syntaxes: -- either `Name = class(base)` or `class.Name(base)`. -- The first form returns the class directly and does not set its `_name`. -- The second form creates a variable `Name` in the current environment set -- to the class, and also sets `_name`. -- @function class -- @param base optional base class -- @param c_arg optional parameter to class constructor -- @param c optional table to be used as class local class class = setmetatable({},{ __call = function(fun,...) return _class(...) end, __index = function(tbl,key) if key == 'class' then io.stderr:write('require("pl.class").class is deprecated. Use require("pl.class")\n') return class end compat = compat or require 'pl.compat' local env = compat.getfenv(2) return function(...) local c = _class(...) c._name = key rawset(env,key,c) return c end end }) class.properties = class() function class.properties._class_init(klass) klass.__index = function(t,key) -- normal class lookup! local v = klass[key] if v then return v end -- is it a getter? v = rawget(klass,'get_'..key) if v then return v(t) end -- is it a field? return rawget(t,'_'..key) end klass.__newindex = function (t,key,value) -- if there's a setter, use that, otherwise directly set table local p = 'set_'..key local setter = klass[p] if setter then setter(t,value) else rawset(t,key,value) end end end ---- Dealing with Detailed Type Information -- Dependencies `pl.utils` -- @module pl.types local types = {} --- is the object either a function or a callable object?. -- @param obj Object to check. function types.is_callable (obj) return type(obj) == 'function' or getmetatable(obj) and getmetatable(obj).__call and true end --- is the object of the specified type?. -- If the type is a string, then use type, otherwise compare with metatable -- @param obj An object to check -- @param tp String of what type it should be -- @function is_type types.is_type = utils.is_type local fileMT = getmetatable(io.stdout) --- a string representation of a type. -- For tables with metatables, we assume that the metatable has a `_name` -- field. Knows about Lua file objects. -- @param obj an object -- @return a string like 'number', 'table' or 'List' function types.type (obj) local t = type(obj) if t == 'table' or t == 'userdata' then local mt = getmetatable(obj) if mt == fileMT then return 'file' elseif mt == nil then return t else return mt._name or "unknown "..t end else return t end end --- is this number an integer? -- @param x a number -- @raise error if x is not a number function types.is_integer (x) return math.ceil(x)==x end --- Check if the object is "empty". -- An object is considered empty if it is nil, a table with out any items (key, -- value pairs or indexes), or a string with no content (""). -- @param o The object to check if it is empty. -- @param ignore_spaces If the object is a string and this is true the string is -- considered empty is it only contains spaces. -- @return true if the object is empty, otherwise false. function types.is_empty(o, ignore_spaces) if o == nil or (type(o) == "table" and not next(o)) or (type(o) == "string" and (o == "" or (ignore_spaces and o:match("^%s+$")))) then return true end return false end local function check_meta (val) if type(val) == 'table' then return true end return getmetatable(val) end --- is an object 'array-like'? -- @param val any value. function types.is_indexable (val) local mt = check_meta(val) if mt == true then return true end return mt and mt.__len and mt.__index and true end --- can an object be iterated over with `pairs`? -- @param val any value. function types.is_iterable (val) local mt = check_meta(val) if mt == true then return true end return mt and mt.__pairs and true end --- can an object accept new key/pair values? -- @param val any value. function types.is_writeable (val) local mt = check_meta(val) if mt == true then return true end return mt and mt.__newindex and true end -- Strings that should evaluate to true. local trues = { yes=true, y=true, ["true"]=true, t=true, ["1"]=true } -- Conditions types should evaluate to true. local true_types = { boolean=function(o, true_strs, check_objs) return o end, string=function(o, true_strs, check_objs) if trues[o:lower()] then return true end -- Check alternative user provided strings. for _,v in ipairs(true_strs or {}) do if type(v) == "string" and o == v:lower() then return true end end return false end, number=function(o, true_strs, check_objs) return o ~= 0 end, table=function(o, true_strs, check_objs) if check_objs and next(o) ~= nil then return true end return false end } --- Convert to a boolean value. -- True values are: -- -- * boolean: true. -- * string: 'yes', 'y', 'true', 't', '1' or additional strings specified by `true_strs`. -- * number: Any non-zero value. -- * table: Is not empty and `check_objs` is true. -- * object: Is not `nil` and `check_objs` is true. -- -- @param o The object to evaluate. -- @param[opt] true_strs optional Additional strings that when matched should evaluate to true. Comparison is case insensitive. -- This should be a List of strings. E.g. "ja" to support German. -- @param[opt] check_objs True if objects should be evaluated. Default is to evaluate objects as true if not nil -- or if it is a table and it is not empty. -- @return true if the input evaluates to true, otherwise false. function types.to_bool(o, true_strs, check_objs) local true_func if true_strs then utils.assert_arg(2, true_strs, "table") end true_func = true_types[type(o)] if true_func then return true_func(o, true_strs, check_objs) elseif check_objs and o ~= nil then return true end return false end --- Extended operations on Lua tables. -- -- See @{02-arrays.md.Useful_Operations_on_Tables|the Guide} -- -- Dependencies: `pl.utils`, `pl.types` -- @module pl.tablex local getmetatable,setmetatable,require = getmetatable,setmetatable,require local tsort,append,remove = table.sort,table.insert,table.remove local min = math.min local pairs,type,unpack,select,tostring = pairs,type,utils.unpack,select,tostring local function_arg = utils.function_arg local assert_arg = utils.assert_arg local tablex = {} -- generally, functions that make copies of tables try to preserve the metatable. -- However, when the source has no obvious type, then we attach appropriate metatables -- like List, Map, etc to the result. local function setmeta (res,tbl,pl_class) local mt = getmetatable(tbl) or pl_class and require('pl.' .. pl_class) return mt and setmetatable(res, mt) or res end local function makelist(l) return setmetatable(l, require('pl.List')) end local function makemap(m) return setmetatable(m, require('pl.Map')) end local function complain (idx,msg) error(('argument %d is not %s'):format(idx,msg),3) end local function assert_arg_indexable (idx,val) if not types.is_indexable(val) then complain(idx,"indexable") end end local function assert_arg_iterable (idx,val) if not types.is_iterable(val) then complain(idx,"iterable") end end local function assert_arg_writeable (idx,val) if not types.is_writeable(val) then complain(idx,"writeable") end end --- copy a table into another, in-place. -- @within Copying -- @tab t1 destination table -- @tab t2 source (actually any iterable object) -- @return first table function tablex.update (t1,t2) assert_arg_writeable(1,t1) assert_arg_iterable(2,t2) for k,v in pairs(t2) do t1[k] = v end return t1 end --- total number of elements in this table. -- Note that this is distinct from `#t`, which is the number -- of values in the array part; this value will always -- be greater or equal. The difference gives the size of -- the hash part, for practical purposes. Works for any -- object with a __pairs metamethod. -- @tab t a table -- @return the size function tablex.size (t) assert_arg_iterable(1,t) local i = 0 for k in pairs(t) do i = i + 1 end return i end --- make a shallow copy of a table -- @within Copying -- @tab t an iterable source -- @return new table function tablex.copy (t) assert_arg_iterable(1,t) local res = {} for k,v in pairs(t) do res[k] = v end return res end --- make a deep copy of a table, recursively copying all the keys and fields. -- This will also set the copied table's metatable to that of the original. -- @within Copying -- @tab t A table -- @return new table function tablex.deepcopy(t) if type(t) ~= 'table' then return t end assert_arg_iterable(1,t) local mt = getmetatable(t) local res = {} for k,v in pairs(t) do if type(v) == 'table' then v = tablex.deepcopy(v) end res[k] = v end setmetatable(res,mt) return res end local abs, deepcompare = math.abs --- compare two values. -- if they are tables, then compare their keys and fields recursively. -- @within Comparing -- @param t1 A value -- @param t2 A value -- @bool[opt] ignore_mt if true, ignore __eq metamethod (default false) -- @number[opt] eps if defined, then used for any number comparisons -- @return true or false function tablex.deepcompare(t1,t2,ignore_mt,eps) 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' then if ty1 == 'number' and eps then return abs(t1-t2) < eps end 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 in pairs(t1) do if t2[k1]==nil then return false end end for k2 in pairs(t2) do if t1[k2]==nil then return false end end for k1,v1 in pairs(t1) do local v2 = t2[k1] if not deepcompare(v1,v2,ignore_mt,eps) then return false end end return true end deepcompare = tablex.deepcompare --- compare two arrays using a predicate. -- @within Comparing -- @array t1 an array -- @array t2 an array -- @func cmp A comparison function function tablex.compare (t1,t2,cmp) assert_arg_indexable(1,t1) assert_arg_indexable(2,t2) if #t1 ~= #t2 then return false end cmp = function_arg(3,cmp) for k = 1,#t1 do if not cmp(t1[k],t2[k]) then return false end end return true end --- compare two list-like tables using an optional predicate, without regard for element order. -- @within Comparing -- @array t1 a list-like table -- @array t2 a list-like table -- @param cmp A comparison function (may be nil) function tablex.compare_no_order (t1,t2,cmp) assert_arg_indexable(1,t1) assert_arg_indexable(2,t2) if cmp then cmp = function_arg(3,cmp) end if #t1 ~= #t2 then return false end local visited = {} for i = 1,#t1 do local val = t1[i] local gotcha for j = 1,#t2 do if not visited[j] then local match if cmp then match = cmp(val,t2[j]) else match = val == t2[j] end if match then gotcha = j break end end end if not gotcha then return false end visited[gotcha] = true end return true end --- return the index of a value in a list. -- Like string.find, there is an optional index to start searching, -- which can be negative. -- @within Finding -- @array t A list-like table -- @param val A value -- @int idx index to start; -1 means last element,etc (default 1) -- @return index of value or nil if not found -- @usage find({10,20,30},20) == 2 -- @usage find({'a','b','a','c'},'a',2) == 3 function tablex.find(t,val,idx) assert_arg_indexable(1,t) idx = idx or 1 if idx < 0 then idx = #t + idx + 1 end for i = idx,#t do if t[i] == val then return i end end return nil end --- return the index of a value in a list, searching from the end. -- Like string.find, there is an optional index to start searching, -- which can be negative. -- @within Finding -- @array t A list-like table -- @param val A value -- @param idx index to start; -1 means last element,etc (default 1) -- @return index of value or nil if not found -- @usage rfind({10,10,10},10) == 3 function tablex.rfind(t,val,idx) assert_arg_indexable(1,t) idx = idx or #t if idx < 0 then idx = #t + idx + 1 end for i = idx,1,-1 do if t[i] == val then return i end end return nil end --- return the index (or key) of a value in a table using a comparison function. -- @within Finding -- @tab t A table -- @func cmp A comparison function -- @param arg an optional second argument to the function -- @return index of value, or nil if not found -- @return value returned by comparison function function tablex.find_if(t,cmp,arg) assert_arg_iterable(1,t) cmp = function_arg(2,cmp) for k,v in pairs(t) do local c = cmp(v,arg) if c then return k,c end end return nil end --- return a list of all values in a table indexed by another list. -- @tab tbl a table -- @array idx an index table (a list of keys) -- @return a list-like table -- @usage index_by({10,20,30,40},{2,4}) == {20,40} -- @usage index_by({one=1,two=2,three=3},{'one','three'}) == {1,3} function tablex.index_by(tbl,idx) assert_arg_indexable(1,tbl) assert_arg_indexable(2,idx) local res = {} for i = 1,#idx do res[i] = tbl[idx[i]] end return setmeta(res,tbl,'List') end --- apply a function to all values of a table. -- This returns a table of the results. -- Any extra arguments are passed to the function. -- @within MappingAndFiltering -- @func fun A function that takes at least one argument -- @tab t A table -- @param ... optional arguments -- @usage map(function(v) return v*v end, {10,20,30,fred=2}) is {100,400,900,fred=4} function tablex.map(fun,t,...) assert_arg_iterable(1,t) fun = function_arg(1,fun) local res = {} for k,v in pairs(t) do res[k] = fun(v,...) end return setmeta(res,t) end --- apply a function to all values of a list. -- This returns a table of the results. -- Any extra arguments are passed to the function. -- @within MappingAndFiltering -- @func fun A function that takes at least one argument -- @array t a table (applies to array part) -- @param ... optional arguments -- @return a list-like table -- @usage imap(function(v) return v*v end, {10,20,30,fred=2}) is {100,400,900} function tablex.imap(fun,t,...) assert_arg_indexable(1,t) fun = function_arg(1,fun) local res = {} for i = 1,#t do res[i] = fun(t[i],...) or false end return setmeta(res,t,'List') end --- apply a named method to values from a table. -- @within MappingAndFiltering -- @string name the method name -- @array t a list-like table -- @param ... any extra arguments to the method function tablex.map_named_method (name,t,...) utils.assert_string(1,name) assert_arg_indexable(2,t) local res = {} for i = 1,#t do local val = t[i] local fun = val[name] res[i] = fun(val,...) end return setmeta(res,t,'List') end --- apply a function to all values of a table, in-place. -- Any extra arguments are passed to the function. -- @func fun A function that takes at least one argument -- @tab t a table -- @param ... extra arguments function tablex.transform (fun,t,...) assert_arg_iterable(1,t) fun = function_arg(1,fun) for k,v in pairs(t) do t[k] = fun(v,...) end end --- generate a table of all numbers in a range. -- This is consistent with a numerical for loop. -- @int start number -- @int finish number -- @int[opt=1] step make this negative for start < finish function tablex.range (start,finish,step) local res step = step or 1 if start == finish then res = {start} elseif (start > finish and step > 0) or (finish > start and step < 0) then res = {} else local k = 1 res = {} for i=start,finish,step do res[k]=i; k=k+1 end end return makelist(res) end --- apply a function to values from two tables. -- @within MappingAndFiltering -- @func fun a function of at least two arguments -- @tab t1 a table -- @tab t2 a table -- @param ... extra arguments -- @return a table -- @usage map2('+',{1,2,3,m=4},{10,20,30,m=40}) is {11,22,23,m=44} function tablex.map2 (fun,t1,t2,...) assert_arg_iterable(1,t1) assert_arg_iterable(2,t2) fun = function_arg(1,fun) local res = {} for k,v in pairs(t1) do res[k] = fun(v,t2[k],...) end return setmeta(res,t1,'List') end --- apply a function to values from two arrays. -- The result will be the length of the shortest array. -- @within MappingAndFiltering -- @func fun a function of at least two arguments -- @array t1 a list-like table -- @array t2 a list-like table -- @param ... extra arguments -- @usage imap2('+',{1,2,3,m=4},{10,20,30,m=40}) is {11,22,23} function tablex.imap2 (fun,t1,t2,...) assert_arg_indexable(2,t1) assert_arg_indexable(3,t2) fun = function_arg(1,fun) local res,n = {},math.min(#t1,#t2) for i = 1,n do res[i] = fun(t1[i],t2[i],...) end return res end --- 'reduce' a list using a binary function. -- @func fun a function of two arguments -- @array t a list-like table -- @array memo optional initial memo value. Defaults to first value in table. -- @return the result of the function -- @usage reduce('+',{1,2,3,4}) == 10 function tablex.reduce (fun,t,memo) assert_arg_indexable(2,t) fun = function_arg(1,fun) local n = #t if n == 0 then return memo end local res = memo and fun(memo, t[1]) or t[1] for i = 2,n do res = fun(res,t[i]) end return res end --- apply a function to all elements of a table. -- The arguments to the function will be the value, -- the key and _finally_ any extra arguments passed to this function. -- Note that the Lua 5.0 function table.foreach passed the _key_ first. -- @within Iterating -- @tab t a table -- @func fun a function with at least one argument -- @param ... extra arguments function tablex.foreach(t,fun,...) assert_arg_iterable(1,t) fun = function_arg(2,fun) for k,v in pairs(t) do fun(v,k,...) end end --- apply a function to all elements of a list-like table in order. -- The arguments to the function will be the value, -- the index and _finally_ any extra arguments passed to this function -- @within Iterating -- @array t a table -- @func fun a function with at least one argument -- @param ... optional arguments function tablex.foreachi(t,fun,...) assert_arg_indexable(1,t) fun = function_arg(2,fun) for i = 1,#t do fun(t[i],i,...) end end --- Apply a function to a number of tables. -- A more general version of map -- The result is a table containing the result of applying that function to the -- ith value of each table. Length of output list is the minimum length of all the lists -- @within MappingAndFiltering -- @func fun a function of n arguments -- @tab ... n tables -- @usage mapn(function(x,y,z) return x+y+z end, {1,2,3},{10,20,30},{100,200,300}) is {111,222,333} -- @usage mapn(math.max, {1,20,300},{10,2,3},{100,200,100}) is {100,200,300} -- @param fun A function that takes as many arguments as there are tables function tablex.mapn(fun,...) fun = function_arg(1,fun) local res = {} local lists = {...} local minn = 1e40 for i = 1,#lists do minn = min(minn,#(lists[i])) end for i = 1,minn do local args,k = {},1 for j = 1,#lists do args[k] = lists[j][i] k = k + 1 end res[#res+1] = fun(unpack(args)) end return res end --- call the function with the key and value pairs from a table. -- The function can return a value and a key (note the order!). If both -- are not nil, then this pair is inserted into the result: if the key already exists, we convert the value for that -- key into a table and append into it. If only value is not nil, then it is appended to the result. -- @within MappingAndFiltering -- @func fun A function which will be passed each key and value as arguments, plus any extra arguments to pairmap. -- @tab t A table -- @param ... optional arguments -- @usage pairmap(function(k,v) return v end,{fred=10,bonzo=20}) is {10,20} _or_ {20,10} -- @usage pairmap(function(k,v) return {k,v},k end,{one=1,two=2}) is {one={'one',1},two={'two',2}} function tablex.pairmap(fun,t,...) assert_arg_iterable(1,t) fun = function_arg(1,fun) local res = {} for k,v in pairs(t) do local rv,rk = fun(k,v,...) if rk then if res[rk] then if type(res[rk]) == 'table' then table.insert(res[rk],rv) else res[rk] = {res[rk], rv} end else res[rk] = rv end else res[#res+1] = rv end end return res end local function keys_op(i,v) return i end --- return all the keys of a table in arbitrary order. -- @within Extraction -- @tab t A table function tablex.keys(t) assert_arg_iterable(1,t) return makelist(tablex.pairmap(keys_op,t)) end local function values_op(i,v) return v end --- return all the values of the table in arbitrary order -- @within Extraction -- @tab t A table function tablex.values(t) assert_arg_iterable(1,t) return makelist(tablex.pairmap(values_op,t)) end local function index_map_op (i,v) return i,v end --- create an index map from a list-like table. The original values become keys, -- and the associated values are the indices into the original list. -- @array t a list-like table -- @return a map-like table function tablex.index_map (t) assert_arg_indexable(1,t) return makemap(tablex.pairmap(index_map_op,t)) end local function set_op(i,v) return true,v end --- create a set from a list-like table. A set is a table where the original values -- become keys, and the associated values are all true. -- @array t a list-like table -- @return a set (a map-like table) function tablex.makeset (t) assert_arg_indexable(1,t) return setmetatable(tablex.pairmap(set_op,t),require('pl.Set')) end --- combine two tables, either as union or intersection. Corresponds to -- set operations for sets () but more general. Not particularly -- useful for list-like tables. -- @within Merging -- @tab t1 a table -- @tab t2 a table -- @bool dup true for a union, false for an intersection. -- @usage merge({alice=23,fred=34},{bob=25,fred=34}) is {fred=34} -- @usage merge({alice=23,fred=34},{bob=25,fred=34},true) is {bob=25,fred=34,alice=23} -- @see tablex.index_map function tablex.merge (t1,t2,dup) assert_arg_iterable(1,t1) assert_arg_iterable(2,t2) local res = {} for k,v in pairs(t1) do if dup or t2[k] then res[k] = v end end if dup then for k,v in pairs(t2) do res[k] = v end end return setmeta(res,t1,'Map') end --- the union of two map-like tables. -- If there are duplicate keys, the second table wins. -- @tab t1 a table -- @tab t2 a table -- @treturn tab -- @see tablex.merge function tablex.union(t1, t2) return tablex.merge(t1, t2, true) end --- the intersection of two map-like tables. -- @tab t1 a table -- @tab t2 a table -- @treturn tab -- @see tablex.merge function tablex.intersection(t1, t2) return tablex.merge(t1, t2, false) end --- a new table which is the difference of two tables. -- With sets (where the values are all true) this is set difference and -- symmetric difference depending on the third parameter. -- @within Merging -- @tab s1 a map-like table or set -- @tab s2 a map-like table or set -- @bool symm symmetric difference (default false) -- @return a map-like table or set function tablex.difference (s1,s2,symm) assert_arg_iterable(1,s1) assert_arg_iterable(2,s2) local res = {} for k,v in pairs(s1) do if s2[k] == nil then res[k] = v end end if symm then for k,v in pairs(s2) do if s1[k] == nil then res[k] = v end end end return setmeta(res,s1,'Map') end --- A table where the key/values are the values and value counts of the table. -- @array t a list-like table -- @func cmp a function that defines equality (otherwise uses ==) -- @return a map-like table -- @see seq.count_map function tablex.count_map (t,cmp) assert_arg_indexable(1,t) local res,mask = {},{} cmp = function_arg(2,cmp or '==') local n = #t for i = 1,#t do local v = t[i] if not mask[v] then mask[v] = true -- check this value against all other values res[v] = 1 -- there's at least one instance for j = i+1,n do local w = t[j] local ok = cmp(v,w) if ok then res[v] = res[v] + 1 mask[w] = true end end end end return makemap(res) end --- filter an array's values using a predicate function -- @within MappingAndFiltering -- @array t a list-like table -- @func pred a boolean function -- @param arg optional argument to be passed as second argument of the predicate function tablex.filter (t,pred,arg) assert_arg_indexable(1,t) pred = function_arg(2,pred) local res,k = {},1 for i = 1,#t do local v = t[i] if pred(v,arg) then res[k] = v k = k + 1 end end return setmeta(res,t,'List') end --- return a table where each element is a table of the ith values of an arbitrary -- number of tables. It is equivalent to a matrix transpose. -- @within Merging -- @usage zip({10,20,30},{100,200,300}) is {{10,100},{20,200},{30,300}} -- @array ... arrays to be zipped function tablex.zip(...) return tablex.mapn(function(...) return {...} end,...) end local _copy function _copy (dest,src,idest,isrc,nsrc,clean_tail) idest = idest or 1 isrc = isrc or 1 local iend if not nsrc then nsrc = #src iend = #src else iend = isrc + min(nsrc-1,#src-isrc) end if dest == src then -- special case if idest > isrc and iend >= idest then -- overlapping ranges src = tablex.sub(src,isrc,nsrc) isrc = 1; iend = #src end end for i = isrc,iend do dest[idest] = src[i] idest = idest + 1 end if clean_tail then tablex.clear(dest,idest) end return dest end --- copy an array into another one, clearing `dest` after `idest+nsrc`, if necessary. -- @within Copying -- @array dest a list-like table -- @array src a list-like table -- @int[opt=1] idest where to start copying values into destination -- @int[opt=1] isrc where to start copying values from source -- @int[opt=#src] nsrc number of elements to copy from source function tablex.icopy (dest,src,idest,isrc,nsrc) assert_arg_indexable(1,dest) assert_arg_indexable(2,src) return _copy(dest,src,idest,isrc,nsrc,true) end --- copy an array into another one. -- @within Copying -- @array dest a list-like table -- @array src a list-like table -- @int[opt=1] idest where to start copying values into destination -- @int[opt=1] isrc where to start copying values from source -- @int[opt=#src] nsrc number of elements to copy from source function tablex.move (dest,src,idest,isrc,nsrc) assert_arg_indexable(1,dest) assert_arg_indexable(2,src) return _copy(dest,src,idest,isrc,nsrc,false) end function tablex._normalize_slice(self,first,last) local sz = #self if not first then first=1 end if first<0 then first=sz+first+1 end -- make the range _inclusive_! if not last then last=sz end if last < 0 then last=sz+1+last end return first,last end --- Extract a range from a table, like 'string.sub'. -- If first or last are negative then they are relative to the end of the list -- eg. sub(t,-2) gives last 2 entries in a list, and -- sub(t,-4,-2) gives from -4th to -2nd -- @within Extraction -- @array t a list-like table -- @int first An index -- @int last An index -- @return a new List function tablex.sub(t,first,last) assert_arg_indexable(1,t) first,last = tablex._normalize_slice(t,first,last) local res={} for i=first,last do append(res,t[i]) end return setmeta(res,t,'List') end --- set an array range to a value. If it's a function we use the result -- of applying it to the indices. -- @array t a list-like table -- @param val a value -- @int[opt=1] i1 start range -- @int[opt=#t] i2 end range function tablex.set (t,val,i1,i2) assert_arg_indexable(1,t) i1,i2 = i1 or 1,i2 or #t if types.is_callable(val) then for i = i1,i2 do t[i] = val(i) end else for i = i1,i2 do t[i] = val end end end --- create a new array of specified size with initial value. -- @int n size -- @param val initial value (can be `nil`, but don't expect `#` to work!) -- @return the table function tablex.new (n,val) local res = {} tablex.set(res,val,1,n) return res end --- clear out the contents of a table. -- @array t a list -- @param istart optional start position function tablex.clear(t,istart) istart = istart or 1 for i = istart,#t do remove(t) end end --- insert values into a table. -- similar to `table.insert` but inserts values from given table `values`, -- not the object itself, into table `t` at position `pos`. -- @within Copying -- @array t the list -- @int[opt] position (default is at end) -- @array values function tablex.insertvalues(t, ...) assert_arg(1,t,'table') local pos, values if select('#', ...) == 1 then pos,values = #t+1, ... else pos,values = ... end if #values > 0 then for i=#t,pos,-1 do t[i+#values] = t[i] end local offset = 1 - pos for i=pos,pos+#values-1 do t[i] = values[i + offset] end end return t end --- remove a range of values from a table. -- End of range may be negative. -- @array t a list-like table -- @int i1 start index -- @int i2 end index -- @return the table function tablex.removevalues (t,i1,i2) assert_arg(1,t,'table') i1,i2 = tablex._normalize_slice(t,i1,i2) for i = i1,i2 do remove(t,i1) end return t end local _find _find = function (t,value,tables) for k,v in pairs(t) do if v == value then return k end end for k,v in pairs(t) do if not tables[v] and type(v) == 'table' then tables[v] = true local res = _find(v,value,tables) if res then res = tostring(res) if type(k) ~= 'string' then return '['..k..']'..res else return k..'.'..res end end end end end --- find a value in a table by recursive search. -- @within Finding -- @tab t the table -- @param value the value -- @array[opt] exclude any tables to avoid searching -- @usage search(_G,math.sin,{package.path}) == 'math.sin' -- @return a fieldspec, e.g. 'a.b' or 'math.sin' function tablex.search (t,value,exclude) assert_arg_iterable(1,t) local tables = {[t]=true} if exclude then for _,v in pairs(exclude) do tables[v] = true end end return _find(t,value,tables) end --- return an iterator to a table sorted by its keys -- @within Iterating -- @tab t the table -- @func f an optional comparison function (f(x,y) is true if x < y) -- @usage for k,v in tablex.sort(t) do print(k,v) end -- @return an iterator to traverse elements sorted by the keys function tablex.sort(t,f) local keys = {} for k in pairs(t) do keys[#keys + 1] = k end tsort(keys,f) local i = 0 return function() i = i + 1 return keys[i], t[keys[i]] end end --- return an iterator to a table sorted by its values -- @within Iterating -- @tab t the table -- @func f an optional comparison function (f(x,y) is true if x < y) -- @usage for k,v in tablex.sortv(t) do print(k,v) end -- @return an iterator to traverse elements sorted by the values function tablex.sortv(t,f) f = function_arg(2, f or '<') local keys = {} for k in pairs(t) do keys[#keys + 1] = k end tsort(keys,function(x, y) return f(t[x], t[y]) end) local i = 0 return function() i = i + 1 return keys[i], t[keys[i]] end end --- modifies a table to be read only. -- This only offers weak protection. Tables can still be modified with -- `table.insert` and `rawset`. -- @tab t the table -- @return the table read only. function tablex.readonly(t) local mt = { __index=t, __newindex=function(t, k, v) error("Attempt to modify read-only table", 2) end, __pairs=function() return pairs(t) end, __ipairs=function() return ipairs(t) end, __len=function() return #t end, __metatable=false } return setmetatable({}, mt) end --- Python-style list class. -- -- **Please Note**: methods that change the list will return the list. -- This is to allow for method chaining, but please note that `ls = ls:sort()` -- does not mean that a new copy of the list is made. In-place (mutable) methods -- are marked as returning 'the list' in this documentation. -- -- See the Guide for further @{02-arrays.md.Python_style_Lists|discussion} -- -- See <a href="http://www.python.org/doc/current/tut/tut.html">http://www.python.org/doc/current/tut/tut.html</a>, section 5.1 -- -- **Note**: The comments before some of the functions are from the Python docs -- and contain Python code. -- -- Written for Lua version Nick Trout 4.0; Redone for Lua 5.1, Steve Donovan. -- -- Dependencies: `pl.utils`, `pl.tablex`, `pl.class` -- @classmod pl.List -- @pragma nostrip local tinsert,tremove,concat,tsort = table.insert,table.remove,table.concat,table.sort local setmetatable, getmetatable,type,tostring,string = setmetatable,getmetatable,type,tostring,string local filter,imap,imap2,reduce,transform,tremovevalues = tablex.filter,tablex.imap,tablex.imap2,tablex.reduce,tablex.transform,tablex.removevalues local tsub = tablex.sub local array_tostring,split,assert_arg,function_arg = utils.array_tostring,utils.split,utils.assert_arg,utils.function_arg local normalize_slice = tablex._normalize_slice -- metatable for our list and map objects has already been defined.. local Multimap = utils.stdmt.MultiMap local List = utils.stdmt.List local iter class(nil,nil,List) -- we want the result to be _covariant_, i.e. t must have type of obj if possible local function makelist (t,obj) local klass = List if obj then klass = getmetatable(obj) end return setmetatable(t,klass) end local function simple_table(t) return type(t) == 'table' and not getmetatable(t) and #t > 0 end function List._create (src) if simple_table(src) then return src end end function List:_init (src) if self == src then return end -- existing table used as self! if src then for v in iter(src) do tinsert(self,v) end end end --- Create a new list. Can optionally pass a table; -- passing another instance of List will cause a copy to be created; -- this will return a plain table with an appropriate metatable. -- we pass anything which isn't a simple table to iterate() to work out -- an appropriate iterator -- @see List.iterate -- @param[opt] t An optional list-like table -- @return a new List -- @usage ls = List(); ls = List {1,2,3,4} -- @function List.new List.new = List --- Make a copy of an existing list. -- The difference from a plain 'copy constructor' is that this returns -- the actual List subtype. function List:clone() local ls = makelist({},self) ls:extend(self) return ls end ---Add an item to the end of the list. -- @param i An item -- @return the list function List:append(i) tinsert(self,i) return self end List.push = tinsert --- Extend the list by appending all the items in the given list. -- equivalent to 'a[len(a):] = L'. -- @tparam List L Another List -- @return the list function List:extend(L) assert_arg(1,L,'table') for i = 1,#L do tinsert(self,L[i]) end return self end --- Insert an item at a given position. i is the index of the -- element before which to insert. -- @int i index of element before whichh to insert -- @param x A data item -- @return the list function List:insert(i, x) assert_arg(1,i,'number') tinsert(self,i,x) return self end --- Insert an item at the begining of the list. -- @param x a data item -- @return the list function List:put (x) return self:insert(1,x) end --- Remove an element given its index. -- (equivalent of Python's del s[i]) -- @int i the index -- @return the list function List:remove (i) assert_arg(1,i,'number') tremove(self,i) return self end --- Remove the first item from the list whose value is given. -- (This is called 'remove' in Python; renamed to avoid confusion -- with table.remove) -- Return nil if there is no such item. -- @param x A data value -- @return the list function List:remove_value(x) for i=1,#self do if self[i]==x then tremove(self,i) return self end end return self end --- Remove the item at the given position in the list, and return it. -- If no index is specified, a:pop() returns the last item in the list. -- The item is also removed from the list. -- @int[opt] i An index -- @return the item function List:pop(i) if not i then i = #self end assert_arg(1,i,'number') return tremove(self,i) end List.get = List.pop --- Return the index in the list of the first item whose value is given. -- Return nil if there is no such item. -- @function List:index -- @param x A data value -- @int[opt=1] idx where to start search -- @return the index, or nil if not found. local tfind = tablex.find List.index = tfind --- does this list contain the value?. -- @param x A data value -- @return true or false function List:contains(x) return tfind(self,x) and true or false end --- Return the number of times value appears in the list. -- @param x A data value -- @return number of times x appears function List:count(x) local cnt=0 for i=1,#self do if self[i]==x then cnt=cnt+1 end end return cnt end --- Sort the items of the list, in place. -- @func[opt='<'] cmp an optional comparison function -- @return the list function List:sort(cmp) if cmp then cmp = function_arg(1,cmp) end tsort(self,cmp) return self end --- return a sorted copy of this list. -- @func[opt='<'] cmp an optional comparison function -- @return a new list function List:sorted(cmp) return List(self):sort(cmp) end --- Reverse the elements of the list, in place. -- @return the list function List:reverse() local t = self local n = #t for i = 1,n/2 do t[i],t[n] = t[n],t[i] n = n - 1 end return self end --- return the minimum and the maximum value of the list. -- @return minimum value -- @return maximum value function List:minmax() local vmin,vmax = 1e70,-1e70 for i = 1,#self do local v = self[i] if v < vmin then vmin = v end if v > vmax then vmax = v end end return vmin,vmax end --- Emulate list slicing. like 'list[first:last]' in Python. -- If first or last are negative then they are relative to the end of the list -- eg. slice(-2) gives last 2 entries in a list, and -- slice(-4,-2) gives from -4th to -2nd -- @param first An index -- @param last An index -- @return a new List function List:slice(first,last) return tsub(self,first,last) end --- empty the list. -- @return the list function List:clear() for i=1,#self do tremove(self) end return self end local eps = 1.0e-10 --- Emulate Python's range(x) function. -- Include it in List table for tidiness -- @int start A number -- @int[opt] finish A number greater than start; if absent, -- then start is 1 and finish is start -- @int[opt=1] incr an increment (may be less than 1) -- @return a List from start .. finish -- @usage List.range(0,3) == List{0,1,2,3} -- @usage List.range(4) = List{1,2,3,4} -- @usage List.range(5,1,-1) == List{5,4,3,2,1} function List.range(start,finish,incr) if not finish then finish = start start = 1 end if incr then assert_arg(3,incr,'number') if math.ceil(incr) ~= incr then finish = finish + eps end else incr = 1 end assert_arg(1,start,'number') assert_arg(2,finish,'number') local t = List() for i=start,finish,incr do tinsert(t,i) end return t end --- list:len() is the same as #list. function List:len() return #self end -- Extended operations -- --- Remove a subrange of elements. -- equivalent to 'del s[i1:i2]' in Python. -- @int i1 start of range -- @int i2 end of range -- @return the list function List:chop(i1,i2) return tremovevalues(self,i1,i2) end --- Insert a sublist into a list -- equivalent to 's[idx:idx] = list' in Python -- @int idx index -- @tparam List list list to insert -- @return the list -- @usage l = List{10,20}; l:splice(2,{21,22}); assert(l == List{10,21,22,20}) function List:splice(idx,list) assert_arg(1,idx,'number') idx = idx - 1 local i = 1 for v in iter(list) do tinsert(self,i+idx,v) i = i + 1 end return self end --- general slice assignment s[i1:i2] = seq. -- @int i1 start index -- @int i2 end index -- @tparam List seq a list -- @return the list function List:slice_assign(i1,i2,seq) assert_arg(1,i1,'number') assert_arg(1,i2,'number') i1,i2 = normalize_slice(self,i1,i2) if i2 >= i1 then self:chop(i1,i2) end self:splice(i1,seq) return self end --- concatenation operator. -- @within metamethods -- @tparam List L another List -- @return a new list consisting of the list with the elements of the new list appended function List:__concat(L) assert_arg(1,L,'table') local ls = self:clone() ls:extend(L) return ls end --- equality operator ==. True iff all elements of two lists are equal. -- @within metamethods -- @tparam List L another List -- @return true or false function List:__eq(L) if #self ~= #L then return false end for i = 1,#self do if self[i] ~= L[i] then return false end end return true end --- join the elements of a list using a delimiter. -- This method uses tostring on all elements. -- @string[opt=''] delim a delimiter string, can be empty. -- @return a string function List:join (delim) delim = delim or '' assert_arg(1,delim,'string') return concat(array_tostring(self),delim) end --- join a list of strings. <br> -- Uses `table.concat` directly. -- @function List:concat -- @string[opt=''] delim a delimiter -- @return a string List.concat = concat local function tostring_q(val) local s = tostring(val) if type(val) == 'string' then s = '"'..s..'"' end return s end --- how our list should be rendered as a string. Uses join(). -- @within metamethods -- @see List:join function List:__tostring() return '{'..self:join(',',tostring_q)..'}' end --- call the function on each element of the list. -- @func fun a function or callable object -- @param ... optional values to pass to function function List:foreach (fun,...) fun = function_arg(1,fun) for i = 1,#self do fun(self[i],...) end end local function lookup_fun (obj,name) local f = obj[name] if not f then error(type(obj).." does not have method "..name,3) end return f end --- call the named method on each element of the list. -- @string name the method name -- @param ... optional values to pass to function function List:foreachm (name,...) for i = 1,#self do local obj = self[i] local f = lookup_fun(obj,name) f(obj,...) end end --- create a list of all elements which match a function. -- @func fun a boolean function -- @param[opt] arg optional argument to be passed as second argument of the predicate -- @return a new filtered list. function List:filter (fun,arg) return makelist(filter(self,fun,arg),self) end --- split a string using a delimiter. -- @string s the string -- @string[opt] delim the delimiter (default spaces) -- @return a List of strings -- @see pl.utils.split function List.split (s,delim) assert_arg(1,s,'string') return makelist(split(s,delim)) end --- apply a function to all elements. -- Any extra arguments will be passed to the function. -- @func fun a function of at least one argument -- @param ... arbitrary extra arguments. -- @return a new list: {f(x) for x in self} -- @usage List{'one','two'}:map(string.upper) == {'ONE','TWO'} -- @see pl.tablex.imap function List:map (fun,...) return makelist(imap(fun,self,...),self) end --- apply a function to all elements, in-place. -- Any extra arguments are passed to the function. -- @func fun A function that takes at least one argument -- @param ... arbitrary extra arguments. -- @return the list. function List:transform (fun,...) transform(fun,self,...) return self end --- apply a function to elements of two lists. -- Any extra arguments will be passed to the function -- @func fun a function of at least two arguments -- @tparam List ls another list -- @param ... arbitrary extra arguments. -- @return a new list: {f(x,y) for x in self, for x in arg1} -- @see pl.tablex.imap2 function List:map2 (fun,ls,...) return makelist(imap2(fun,self,ls,...),self) end --- apply a named method to all elements. -- Any extra arguments will be passed to the method. -- @string name name of method -- @param ... extra arguments -- @return a new list of the results -- @see pl.seq.mapmethod function List:mapm (name,...) local res = {} for i = 1,#self do local val = self[i] local fn = lookup_fun(val,name) res[i] = fn(val,...) end return makelist(res,self) end local function composite_call (method,f) return function(self,...) return self[method](self,f,...) end end function List.default_map_with(T) return function(self,name) local m if T then local f = lookup_fun(T,name) m = composite_call('map',f) else m = composite_call('mapn',name) end getmetatable(self)[name] = m -- and cache.. return m end end List.default_map = List.default_map_with --- 'reduce' a list using a binary function. -- @func fun a function of two arguments -- @return result of the function -- @see pl.tablex.reduce function List:reduce (fun) return reduce(fun,self) end --- partition a list using a classifier function. -- The function may return nil, but this will be converted to the string key '<nil>'. -- @func fun a function of at least one argument -- @param ... will also be passed to the function -- @treturn MultiMap a table where the keys are the returned values, and the values are Lists -- of values where the function returned that key. -- @see pl.MultiMap function List:partition (fun,...) fun = function_arg(1,fun) local res = {} for i = 1,#self do local val = self[i] local klass = fun(val,...) if klass == nil then klass = '<nil>' end if not res[klass] then res[klass] = List() end res[klass]:append(val) end return setmetatable(res,Multimap) end --- return an iterator over all values. function List:iter () return iter(self) end --- Create an iterator over a seqence. -- This captures the Python concept of 'sequence'. -- For tables, iterates over all values with integer indices. -- @param seq a sequence; a string (over characters), a table, a file object (over lines) or an iterator function -- @usage for x in iterate {1,10,22,55} do io.write(x,',') end ==> 1,10,22,55 -- @usage for ch in iterate 'help' do do io.write(ch,' ') end ==> h e l p function List.iterate(seq) if type(seq) == 'string' then local idx = 0 local n = #seq local sub = string.sub return function () idx = idx + 1 if idx > n then return nil else return sub(seq,idx,idx) end end elseif type(seq) == 'table' then local idx = 0 local n = #seq return function() idx = idx + 1 if idx > n then return nil else return seq[idx] end end elseif type(seq) == 'function' then return seq elseif type(seq) == 'userdata' and io.type(seq) == 'file' then return seq:lines() end end iter = List.iterate local is_windows = path.is_windows local ldir = path.dir local mkdir = path.mkdir local rmdir = path.rmdir local sub = string.sub local os,pcall,ipairs,pairs,require,setmetatable = os,pcall,ipairs,pairs,require,setmetatable local remove = os.remove local append = table.insert local wrap = coroutine.wrap local yield = coroutine.yield local assert_arg,assert_string,raise = utils.assert_arg,utils.assert_string,utils.raise local dir = {} local function makelist(l) return setmetatable(l, List) end local function assert_dir (n,val) assert_arg(n,val,'string',path.isdir,'not a directory',4) end local function filemask(mask) mask = utils.escape(path.normcase(mask)) return '^'..mask:gsub('%%%*','.*'):gsub('%%%?','.')..'$' end --- Test whether a file name matches a shell pattern. -- Both parameters are case-normalized if operating system is -- case-insensitive. -- @string filename A file name. -- @string pattern A shell pattern. The only special characters are -- `'*'` and `'?'`: `'*'` matches any sequence of characters and -- `'?'` matches any single character. -- @treturn bool -- @raise dir and mask must be strings function dir.fnmatch(filename,pattern) assert_string(1,filename) assert_string(2,pattern) return path.normcase(filename):find(filemask(pattern)) ~= nil end --- Return a list of all file names within an array which match a pattern. -- @tab filenames An array containing file names. -- @string pattern A shell pattern. -- @treturn List(string) List of matching file names. -- @raise dir and mask must be strings function dir.filter(filenames,pattern) assert_arg(1,filenames,'table') assert_string(2,pattern) local res = {} local mask = filemask(pattern) for i,f in ipairs(filenames) do if path.normcase(f):find(mask) then append(res,f) end end return makelist(res) end local function _listfiles(dir,filemode,match) local res = {} local check = utils.choose(filemode,path.isfile,path.isdir) if not dir then dir = '.' end for f in ldir(dir) do if f ~= '.' and f ~= '..' then local p = path.join(dir,f) if check(p) and (not match or match(f)) then append(res,p) end end end return makelist(res) end --- return a list of all files in a directory which match the a shell pattern. -- @string dir A directory. If not given, all files in current directory are returned. -- @string mask A shell pattern. If not given, all files are returned. -- @treturn {string} list of files -- @raise dir and mask must be strings function dir.getfiles(dir,mask) assert_dir(1,dir) if mask then assert_string(2,mask) end local match if mask then mask = filemask(mask) match = function(f) return path.normcase(f):find(mask) end end return _listfiles(dir,true,match) end --- return a list of all subdirectories of the directory. -- @string dir A directory -- @treturn {string} a list of directories -- @raise dir must be a a valid directory function dir.getdirectories(dir) assert_dir(1,dir) return _listfiles(dir,false) end local alien,ffi,ffi_checked,CopyFile,MoveFile,GetLastError,win32_errors,cmd_tmpfile local function execute_command(cmd,parms) if not cmd_tmpfile then cmd_tmpfile = path.tmpname () end local err = path.is_windows and ' > ' or ' 2> ' cmd = cmd..' '..parms..err..utils.quote_arg(cmd_tmpfile) local ret = utils.execute(cmd) if not ret then local err = (utils.readfile(cmd_tmpfile):gsub('\n(.*)','')) remove(cmd_tmpfile) return false,err else remove(cmd_tmpfile) return true end end local function find_ffi_copyfile () if not ffi_checked then ffi_checked = true local res res,alien = pcall(require,'alien') if not res then alien = nil res, ffi = pcall(require,'ffi') end if not res then ffi = nil return end else return end if alien then -- register the Win32 CopyFile and MoveFile functions local kernel = alien.load('kernel32.dll') CopyFile = kernel.CopyFileA CopyFile:types{'string','string','int',ret='int',abi='stdcall'} MoveFile = kernel.MoveFileA MoveFile:types{'string','string',ret='int',abi='stdcall'} GetLastError = kernel.GetLastError GetLastError:types{ret ='int', abi='stdcall'} elseif ffi then ffi.cdef [[ int CopyFileA(const char *src, const char *dest, int iovr); int MoveFileA(const char *src, const char *dest); int GetLastError(); ]] CopyFile = ffi.C.CopyFileA MoveFile = ffi.C.MoveFileA GetLastError = ffi.C.GetLastError end win32_errors = { ERROR_FILE_NOT_FOUND = 2, ERROR_PATH_NOT_FOUND = 3, ERROR_ACCESS_DENIED = 5, ERROR_WRITE_PROTECT = 19, ERROR_BAD_UNIT = 20, ERROR_NOT_READY = 21, ERROR_WRITE_FAULT = 29, ERROR_READ_FAULT = 30, ERROR_SHARING_VIOLATION = 32, ERROR_LOCK_VIOLATION = 33, ERROR_HANDLE_DISK_FULL = 39, ERROR_BAD_NETPATH = 53, ERROR_NETWORK_BUSY = 54, ERROR_DEV_NOT_EXIST = 55, ERROR_FILE_EXISTS = 80, ERROR_OPEN_FAILED = 110, ERROR_INVALID_NAME = 123, ERROR_BAD_PATHNAME = 161, ERROR_ALREADY_EXISTS = 183, } end local function two_arguments (f1,f2) return utils.quote_arg(f1)..' '..utils.quote_arg(f2) end local function file_op (is_copy,src,dest,flag) if flag == 1 and path.exists(dest) then return false,"cannot overwrite destination" end if is_windows then -- if we haven't tried to load Alien/LuaJIT FFI before, then do so find_ffi_copyfile() -- fallback if there's no Alien, just use DOS commands *shudder* -- 'rename' involves a copy and then deleting the source. if not CopyFile then src = path.normcase(src) dest = path.normcase(dest) local cmd = is_copy and 'copy' or 'rename' local res, err = execute_command('copy',two_arguments(src,dest)) if not res then return false,err end if not is_copy then return execute_command('del',utils.quote_arg(src)) end return true else if path.isdir(dest) then dest = path.join(dest,path.basename(src)) end local ret if is_copy then ret = CopyFile(src,dest,flag) else ret = MoveFile(src,dest) end if ret == 0 then local err = GetLastError() for name,value in pairs(win32_errors) do if value == err then return false,name end end return false,"Error #"..err else return true end end else -- for Unix, just use cp for now return execute_command(is_copy and 'cp' or 'mv', two_arguments(src,dest)) end end --- copy a file. -- @string src source file -- @string dest destination file or directory -- @bool flag true if you want to force the copy (default) -- @treturn bool operation succeeded -- @raise src and dest must be strings function dir.copyfile (src,dest,flag) assert_string(1,src) assert_string(2,dest) flag = flag==nil or flag return file_op(true,src,dest,flag and 0 or 1) end --- move a file. -- @string src source file -- @string dest destination file or directory -- @treturn bool operation succeeded -- @raise src and dest must be strings function dir.movefile (src,dest) assert_string(1,src) assert_string(2,dest) return file_op(false,src,dest,0) end local function _dirfiles(dir,attrib) local dirs = {} local files = {} for f in ldir(dir) do if f ~= '.' and f ~= '..' then local p = path.join(dir,f) local mode = attrib(p,'mode') if mode=='directory' then append(dirs,f) else append(files,f) end end end return makelist(dirs), makelist(files) end local function _walker(root,bottom_up,attrib) local dirs,files = _dirfiles(root,attrib) if not bottom_up then yield(root,dirs,files) end for i,d in ipairs(dirs) do _walker(root..path.sep..d,bottom_up,attrib) end if bottom_up then yield(root,dirs,files) end end --- return an iterator which walks through a directory tree starting at root. -- The iterator returns (root,dirs,files) -- Note that dirs and files are lists of names (i.e. you must say path.join(root,d) -- to get the actual full path) -- If bottom_up is false (or not present), then the entries at the current level are returned -- before we go deeper. This means that you can modify the returned list of directories before -- continuing. -- This is a clone of os.walk from the Python libraries. -- @string root A starting directory -- @bool bottom_up False if we start listing entries immediately. -- @bool follow_links follow symbolic links -- @return an iterator returning root,dirs,files -- @raise root must be a directory function dir.walk(root,bottom_up,follow_links) assert_dir(1,root) local attrib if path.is_windows or not follow_links then attrib = path.attrib else attrib = path.link_attrib end return wrap(function () _walker(root,bottom_up,attrib) end) end --- remove a whole directory tree. -- @string fullpath A directory path -- @return true or nil -- @return error if failed -- @raise fullpath must be a string function dir.rmtree(fullpath) assert_dir(1,fullpath) if path.islink(fullpath) then return false,'will not follow symlink' end for root,dirs,files in dir.walk(fullpath,true) do for i,f in ipairs(files) do local res, err = remove(path.join(root,f)) if not res then return nil,err end end local res, err = rmdir(root) if not res then return nil,err end end return true end local dirpat if path.is_windows then dirpat = '(.+)\\[^\\]+$' else dirpat = '(.+)/[^/]+$' end local _makepath function _makepath(p) -- windows root drive case if p:find '^%a:[\\]*$' then return true end if not path.isdir(p) then local subp = p:match(dirpat) local ok, err = _makepath(subp) if not ok then return nil, err end return mkdir(p) else return true end end --- create a directory path. -- This will create subdirectories as necessary! -- @string p A directory path -- @return true on success, nil + errormsg on failure -- @raise failure to create function dir.makepath (p) assert_string(1,p) return _makepath(path.normcase(path.abspath(p))) end --- clone a directory tree. Will always try to create a new directory structure -- if necessary. -- @string path1 the base path of the source tree -- @string path2 the new base path for the destination -- @func file_fun an optional function to apply on all files -- @bool verbose an optional boolean to control the verbosity of the output. -- It can also be a logging function that behaves like print() -- @return true, or nil -- @return error message, or list of failed directory creations -- @return list of failed file operations -- @raise path1 and path2 must be strings -- @usage clonetree('.','../backup',copyfile) function dir.clonetree (path1,path2,file_fun,verbose) assert_string(1,path1) assert_string(2,path2) if verbose == true then verbose = print end local abspath,normcase,isdir,join = path.abspath,path.normcase,path.isdir,path.join local faildirs,failfiles = {},{} if not isdir(path1) then return raise 'source is not a valid directory' end path1 = abspath(normcase(path1)) path2 = abspath(normcase(path2)) if verbose then verbose('normalized:',path1,path2) end -- particularly NB that the new path isn't fully contained in the old path if path1 == path2 then return raise "paths are the same" end local i1,i2 = path2:find(path1,1,true) if i2 == #path1 and path2:sub(i2+1,i2+1) == path.sep then return raise 'destination is a subdirectory of the source' end local cp = path.common_prefix (path1,path2) local idx = #cp if idx == 0 then -- no common path, but watch out for Windows paths! if path1:sub(2,2) == ':' then idx = 3 end end for root,dirs,files in dir.walk(path1) do local opath = path2..root:sub(idx) if verbose then verbose('paths:',opath,root) end if not isdir(opath) then local ret = dir.makepath(opath) if not ret then append(faildirs,opath) end if verbose then verbose('creating:',opath,ret) end end if file_fun then for i,f in ipairs(files) do local p1 = join(root,f) local p2 = join(opath,f) local ret = file_fun(p1,p2) if not ret then append(failfiles,p2) end if verbose then verbose('files:',p1,p2,ret) end end end end return true,faildirs,failfiles end --- return an iterator over all entries in a directory tree -- @string d a directory -- @return an iterator giving pathname and mode (true for dir, false otherwise) -- @raise d must be a non-empty string function dir.dirtree( d ) assert( d and d ~= "", "directory parameter is missing or empty" ) local exists, isdir = path.exists, path.isdir local sep = path.sep local last = sub ( d, -1 ) if last == sep or last == '/' then d = sub( d, 1, -2 ) end local function yieldtree( dir ) for entry in ldir( dir ) do if entry ~= "." and entry ~= ".." then entry = dir .. sep .. entry if exists(entry) then -- Just in case a symlink is broken. local is_dir = isdir(entry) yield( entry, is_dir ) if is_dir then yieldtree( entry ) end end end end end return wrap( function() yieldtree( d ) end ) end --- Recursively returns all the file starting at _path_. It can optionally take a shell pattern and -- only returns files that match _shell_pattern_. If a pattern is given it will do a case insensitive search. -- @string start_path A directory. If not given, all files in current directory are returned. -- @string shell_pattern A shell pattern. If not given, all files are returned. -- @treturn List(string) containing all the files found recursively starting at _path_ and filtered by _shell_pattern_. -- @raise start_path must be a directory function dir.getallfiles( start_path, shell_pattern ) assert_dir(1,start_path) shell_pattern = shell_pattern or "*" local files = {} local normcase = path.normcase for filename, mode in dir.dirtree( start_path ) do if not mode then local mask = filemask( shell_pattern ) if normcase(filename):find( mask ) then files[#files + 1] = filename end end end return makelist(files) end pl.file = file pl.path = path pl.utils = utils pl.dir = dir return pl
local Aye = Aye; Aye.utils.Buffs = Aye.utils.Buffs or {}; -- Check if @unitID can detect demons -- -- @param {uint} unitID @unitID should be visible (UnitIsVisible) -- @return {0|1} buff if unit can detect demons Aye.utils.Buffs.UnitCanDetectDemons = Aye.utils.Buffs.UnitCanDetectDemons or function(unitID) -- Rune for _, buffID in pairs({ 47524, -- Sense Demons 11407, -- Detect Demon }) do local _, _, _, _, _, _, expires = UnitBuff(unitID, GetSpellInfo(buffID)); if type(expires) =="number" then return 1; end; end; local _, _, classID = UnitClass(unitID); if classID == 3 -- Hunter or classID == 12 -- Demon Hunter then return 1; end; -- No Rune return 0; end;
#!/usr/bin/env texlua module = "gbt7714" installfiles = {"*.sty", "*.bst"} textfiles = {"README.md", "LICENSE"} checkengines = {"xetex"} stdengine = "xetex" typesetexe = "xelatex" unpackexe = "xetex" checkruns = 3 checkopts = "-file-line-error -halt-on-error -interaction=nonstopmode" typesetopts = "-file-line-error -halt-on-error -interaction=nonstopmode" function runtest_tasks(name) return "bibtex -terse " .. name end kpse.set_program_name("kpsewhich") dofile(kpse.lookup("l3build.lua"))
a = 5 * 6 b = 6 + 7 * 3 c = true and false
local the = require"the" local shuffle,top,map,push,sort,firsts = the.get"tables shuffle top map push sort firsts" local shout,out = the.get"prints shout out" local e,rnd = the.get"maths e round" local obj,has = the.get"metas obj has" local Num,Sym,Skip = require"num", require"sym", require"skip" local goalp,klassp,nump,skipp function goalp(v) return klassp(v) or v:find"+" or v:find"-" end function klassp(v) return v:find"!" end function nump(v) return v:match("^[A-Z]") end function skipp(v) return v:find":" end -- New columns are either `Skip`s or `Num`s or `Sym`s. -- New columns are always stored in `all` and -- independent/dependent columns (that we are not `skipp`ing) -- are stored in `xs` or `ys` respectively. Summary= obj"Summary" --------------------------------------------------------- function Summary.new(lst, self,now,what) self = has(Summary, {header=lst,all={},xs={},ys={},klass=nil}) for k,v in pairs(lst) do what = (skipp(v) and Skip) or (nump(v) and Num) or Sym now = what(k,v) push(self.all, now) if not skipp(v) then if klassp(v) then self.klass=now end push(goalp(v) and self.ys or self.xs, now) end end return self end function Summary:add(t) for k,x in pairs(t) do self.all[k]:add(x) end; return t end function Summary:better(row1,row2) local n,a,b,s1,s2 s1, s2, n = 0, 0, #self.ys for _,col in pairs(self.ys) do a = col:norm(row1[col.at]) --normalize to avoid explosion in exponentiation b = col:norm(row2[col.at]) s1 = s1 - e^(col.w * (a - b) / n) s2 = s2 - e^(col.w * (b - a) / n) end return s1 / n < s2 / n end function Summary:dist(row1, row2, cols) local d,n,p = 0,0,the.p for _,col in pairs(cols or self.xs) do inc = col:dist(row1[col.at], row2[col.at]) n,d = n + 1, d + inc^p print(col.at, n, rnd(d,3), row1[col.at], row2[col.at], inc) end return (d/n)^(1/p) end function Summary:neighbors(row1,rows, some,dist) some = top(the.some, shuffle(rows)) function dist(_,row2) return {self:dist(row1,row2),row2} end return sort(map(some, dist), firsts) end return Summary
class "PhysFSFileProvider" function PhysFSFileProvider:PhysFSFileProvider(...) local arg = {...} for k,v in pairs(arg) do if type(v) == "table" then if v.__ptr ~= nil then arg[k] = v.__ptr end end end if self.__ptr == nil and arg[1] ~= "__skip_ptr__" then self.__ptr = Polycode.PhysFSFileProvider(unpack(arg)) end end function PhysFSFileProvider:openFile(fileName, opts) local retVal = Polycode.PhysFSFileProvider_openFile(self.__ptr, fileName, opts) if retVal == nil then return nil end local __c = _G["CoreFile"]("__skip_ptr__") __c.__ptr = retVal return __c end function PhysFSFileProvider:closeFile(file) local retVal = Polycode.PhysFSFileProvider_closeFile(self.__ptr, file.__ptr) end function PhysFSFileProvider:parseFolder(pathString, showHidden, targetVector) local retVal = Polycode.PhysFSFileProvider_parseFolder(self.__ptr, pathString, showHidden, targetVector.__ptr) return retVal end function PhysFSFileProvider:addSource(source) local retVal = Polycode.PhysFSFileProvider_addSource(self.__ptr, source) end function PhysFSFileProvider:removeSource(source) local retVal = Polycode.PhysFSFileProvider_removeSource(self.__ptr, source) end function PhysFSFileProvider:__delete() if self then Polycode.delete_PhysFSFileProvider(self.__ptr) end end
local response = require "wsapi.response" local cgilua = require "cgilua.main" local _M = {} function _M.run(wsapi_env) _G.CGILUA_APPS = _G.CGILUA_APPS or wsapi_env.DOCUMENT_ROOT .. "/cgilua" _G.CGILUA_CONF = _G.CGILUA_CONF or wsapi_env.DOCUMENT_ROOT .. "/cgilua" _G.CGILUA_TMP = _G.CGILUA_TMP or os.getenv("TMP") or os.getenv("TEMP") or "/tmp" _G.CGILUA_ISDIRECT = true local res = response.new() _G.SAPI = { Info = { _COPYRIGHT = "Copyright (C) 2007 Kepler Project and ABBA 2019 (C) Project", _DESCRIPTION = "WSAPI SAPI implementation", _VERSION = "WSAPI SAPI 1.0", ispersistent = false, }, Request = { servervariable = function (name) return wsapi_env[name] end, getpostdata = function (n) return wsapi_env.input:read(n) end }, Response = { contenttype = function (header) res:content_type(header) end, errorlog = function (msg, errlevel) wsapi_env.error:write (msg) end, header = function (header, value) if res.headers[header] then if type(res.headers[header]) == "table" then table.insert(res.headers[header], value) else res.headers[header] = { res.headers[header], value } end else res.headers[header] = value end end, redirect = function (url) res.status = 302 res.headers["Location"] = url end, write = function (...) res:write({...}) end, }, } cgilua.main(wsapi_env, res) return res:finish() end return _M
--[[ Name: furn_store.lua ]]-- local MapProp = {} MapProp.ID = "furn_store" MapProp.m_tblSpawn = { { mdl = 'models/props_trainstation/trainstation_clock001.mdl',pos = Vector('1542.281250 1987.125000 680.718750'), ang = Angle('0.000 0.000 0.000'), }, { mdl = 'models/props/cs_militia/barstool01.mdl',pos = Vector('2046.562500 2112.437500 544.218750'), ang = Angle('-0.044 -90.000 0.132'), }, { mdl = 'models/sunabouzu/lobby_poster.mdl',pos = Vector('1773.312500 2171.468750 643.593750'), ang = Angle('0.000 -90.000 0.000'), }, { mdl = 'models/props/cs_militia/gun_cabinet.mdl',pos = Vector('1555.781250 2016.531250 544.406250'), ang = Angle('-0.044 -0.967 -0.088'), }, { mdl = 'models/props_c17/furniturecupboard001a.mdl',pos = Vector('1887.906250 2160.843750 606.406250'), ang = Angle('0.000 -90.000 0.000'), }, { mdl = 'models/props_interiors/magazine_rack.mdl',pos = Vector('1552.375000 1855.750000 544.406250'), ang = Angle('0.000 0.000 -0.044'), }, { mdl = 'models/props/cs_office/table_coffee.mdl',pos = Vector('1772.656250 2097.531250 544.343750'), ang = Angle('0.000 -90.000 0.000'), }, { mdl = 'models/props/cs_office/offinspa.mdl',pos = Vector('2014.093750 1796.406250 622.500000'), ang = Angle('0.000 0.000 0.000'), }, { mdl = 'models/props_combine/breenchair.mdl',pos = Vector('2156.375000 2146.531250 544.406250'), ang = Angle('0.176 -108.721 0.132'), }, { mdl = 'models/props/cs_office/sofa_chair.mdl',pos = Vector('1696.656250 2097.750000 544.375000'), ang = Angle('-0.044 -1.011 -0.044'), }, { mdl = 'models/props_interiors/furniture_shelf01a.mdl',pos = Vector('2018.406250 2162.406250 587.593750'), ang = Angle('0.132 -90.000 -0.044'), }, { mdl = 'models/props_c17/furnituredresser001a.mdl',pos = Vector('1961.125000 2155.500000 585.406250'), ang = Angle('1.582 -90.000 0.000'), }, { mdl = 'models/props/cs_office/sofa_chair.mdl',pos = Vector('1850.000000 2095.062500 544.312500'), ang = Angle('-0.044 178.989 -0.044'), }, { mdl = 'models/props/cs_office/sofa.mdl',pos = Vector('1772.656250 2150.406250 544.343750'), ang = Angle('0.088 -90.088 -0.044'), }, { mdl = 'models/props_interiors/chair_thonet.mdl',pos = Vector('1749.062500 1861.375000 544.406250'), ang = Angle('-0.132 -96.855 0.923'), }, { mdl = 'models/props_combine/breendesk.mdl',pos = Vector('2097.968750 2114.843750 544.343750'), ang = Angle('-0.132 180.000 0.000'), }, { mdl = 'models/props/cs_office/plant01.mdl',pos = Vector('2209.187500 1819.187500 543.687500'), ang = Angle('-0.220 -87.231 -0.220'), }, { mdl = 'models/props_interiors/chair_thonet.mdl',pos = Vector('1787.812500 1824.406250 544.437500'), ang = Angle('0.000 165.542 -0.088'), }, { mdl = 'models/props_interiors/chair_thonet.mdl',pos = Vector('1713.031250 1823.125000 544.468750'), ang = Angle('0.439 0.747 -0.396'), }, { mdl = 'models/props_interiors/furniture_lamp01a.mdl',pos = Vector('2208.187500 2152.656250 577.625000'), ang = Angle('-0.088 180.000 -0.044'), }, { mdl = 'models/props_c17/furnituredrawer002a.mdl',pos = Vector('2204.343750 2056.781250 560.843750'), ang = Angle('0.088 180.000 0.000'), }, { mdl = 'models/props_interiors/furniture_desk01a.mdl',pos = Vector('2205.687500 2106.875000 563.937500'), ang = Angle('-0.132 179.956 0.000'), }, { mdl = 'models/testmodels/coffee_table_long.mdl',pos = Vector('1952.281250 1891.281250 544.343750'), ang = Angle('0.088 90.044 0.132'), }, { mdl = 'models/props_combine/breenglobe.mdl',pos = Vector('2088.656250 2148.812500 584.656250'), ang = Angle('0.044 -122.168 0.044'), }, { mdl = 'models/props_combine/breenclock.mdl',pos = Vector('2087.718750 2115.687500 579.843750'), ang = Angle('0.000 180.000 0.000'), }, { mdl = 'models/testmodels/sofa_double.mdl',pos = Vector('1946.781250 1823.125000 544.656250'), ang = Angle('-0.044 90.000 -0.044'), }, { mdl = 'models/splayn/rp/lr/chair.mdl',pos = Vector('2049.968750 1816.531250 544.406250'), ang = Angle('-0.132 89.956 -0.044'), }, { mdl = 'models/splayn/rp/lr/couch.mdl',pos = Vector('2133.062500 1879.625000 544.312500'), ang = Angle('0.000 90.000 0.000'), }, { mdl = 'models/props_interiors/desk_executive.mdl',pos = Vector('1614.687500 1989.093750 544.281250'), ang = Angle('0.000 179.868 0.000'), }, { mdl = 'models/props_c17/furnituredrawer001a.mdl',pos = Vector('1877.656250 2157.875000 564.437500'), ang = Angle('0.571 -90.044 0.132'), }, { mdl = 'models/testmodels/sofa_single.mdl',pos = Vector('1871.906250 1847.250000 545.625000'), ang = Angle('0.000 89.956 -0.044'), }, { mdl = 'models/sunabouzu/theater_table.mdl',pos = Vector('1847.093750 1891.718750 560.437500'), ang = Angle('0.044 -179.956 0.000'), }, { mdl = 'models/props_interiors/dining_table_round.mdl',pos = Vector('1749.875000 1826.812500 544.312500'), ang = Angle('0.044 131.396 0.000'), }, { mdl = 'models/props_interiors/cashregister01.mdl',pos = Vector('1612.375000 1976.031250 582.656250'), ang = Angle('-0.571 148.447 0.132'), }, { mdl = 'models/props_interiors/phone.mdl',pos = Vector('1601.281250 2024.343750 583.125000'), ang = Angle('0.132 179.297 0.483'), }, { mdl = 'models/props_c17/furnituredrawer003a.mdl',pos = Vector('1923.468750 2165.218750 566.625000'), ang = Angle('0.176 -90.000 0.000'), }, { mdl = 'models/splayn/rp/lr/couch.mdl',pos = Vector('2138.718750 1817.468750 544.312500'), ang = Angle('-0.044 89.868 -0.044'), }, { mdl = 'models/props/cs_militia/barstool01.mdl',pos = Vector('2023.093750 2112.437500 544.156250'), ang = Angle('-0.044 -90.000 0.132'), }, { mdl = 'models/props/cs_militia/barstool01.mdl',pos = Vector('1999.593750 2112.437500 544.125000'), ang = Angle('-0.044 -90.000 0.132'), }, } GAMEMODE.Map:RegisterMapProp( MapProp )
ITEM.name = "9x21mm Gyurza SP-10 (7N29)" ITEM.model = "models/lostsignalproject/items/ammo/9x19_p.mdl" ITEM.ammo = "9x21MM -AP-" // type of the ammo ITEM.ammoAmount = 60 // amount of the ammo ITEM.description = "" ITEM.quantdesc = "A box that contains %s rounds of 9x21mm Gyurza SP-10 (7N29) ammo. " ITEM.longdesc = "An overpressure cartridge sporting a hardened steel core, with the outer layer being seperated by a polyethylene layer. This allows it to be effective against both armored and unarmored targets, as if it hits an unarmored target, the polyethylene layer will keep the outer jacket and steel core together resulting in larger wounds. However, if striking an armored target, the outer sleeve will be stripped away by the armor and allow the hardened steel core to penetrate by itself." ITEM.price = 750 ITEM.busflag = {"ammo1"} ITEM.img = ix.util.GetMaterial("cotz/icons/ammo/ammo_short_7_1.png") ITEM.weight = 0.010 ITEM.flatweight = 0.05 function ITEM:GetWeight() return self.flatweight + (self.weight * self:GetData("quantity", self.ammoAmount)) end
--[[ Math stuff ]] local scrW, scrH local cos, sin, pi = math.cos, math.sin, math.pi --(1 - t) * from + t * to function LerpColor(t, from, to) return Color( (1 - t) * from.r + t * to.r, (1 - t) * from.g + t * to.g, (1 - t) * from.b + t * to.b, (1 - t) * from.a + t * to.a ) end --[[ Config ]] local col_shadow = Color(0, 0, 0, 145) local col_half_shadow = Color(0, 0, 0, 110) local shadow_x = 1 local shadow_y = 0 --[[ Blur ]] local blur = Material("pp/blurscreen") local pan_x, pan_y function surface.DrawPanelBlur(panel, amount) pan_x, pan_y = panel:LocalToScreen(0, 0) surface.SetDrawColor(color_white) surface.SetMaterial(blur) for i = 1, 3 do blur:SetFloat("$blur", (i / 3) * (amount or 6)) blur:Recompute() render.UpdateScreenEffectTexture() surface.DrawTexturedRect(pan_x * -1, pan_y * -1, ScrW(), ScrH()) end end --[[ Material ]] function surface.DrawMaterial(material, xalign, yalign, x, y, color) surface.SetDrawColor(color or color_white) surface.SetMaterial(material) surface.DrawTexturedRect(xalign, yalign, x, y) end function surface.DrawShadowMaterial(material, xalign, yalign, x, y, color) surface.SetDrawColor(col_shadow) surface.SetMaterial(material) surface.DrawTexturedRect(xalign, yalign, x, y + 3) surface.SetDrawColor(col_half_shadow) surface.SetMaterial(material) surface.DrawTexturedRect(xalign, yalign, x + shadow_x , y + shadow_y) surface.SetDrawColor(color or color_white) surface.SetMaterial(material) surface.DrawTexturedRect(xalign, yalign, x, y) end --[[ crestr, add description later, please ]] function draw.NoRoundedBox(x, y, w, h, color) draw.NoTexture() surface.SetDrawColor(color or color_white) surface.DrawRect(x, y, w, h) end --[[ Rounded stuff ]] function surface.PrecacheRoundedRect(x, y, w, h, r, seg) local min = (w > h and h or w) * 0.5 r = r > min and min or r local poly = {} for i = 0, seg do local a = pi * 0.5 * i / seg local cosine, sine = r * cos(a), r * sin(a) poly[i+1] = { x = x + r - cosine, y = y + r - sine } poly[i + seg + 1] = { x = x + w - r + sine, y = y + r - cosine } poly[i + seg * 2 + 1] = { x = x + w - r + cosine, y = y + h - r + sine } poly[i + seg * 3 + 1] = { x = x + r - sine, y = y + h - r + cosine } end return poly end local poly = {} function surface.DrawRoundedRect(x, y, w, h, r, seg) local min = (w > h and h or w) * 0.5 r = r > min and min or r poly = {} for i = 0, seg do local a = pi * 0.5 * i / seg local cosine, sine = r * cos(a), r * sin(a) poly[i] = { x = x + r - cosine, y = y + r - sine } poly[i + seg + 1] = { x = x + w - r + sine, y = y + r - cosine } poly[i + seg * 2 + 1] = { x = x + w - r + cosine, y = y + h - r + sine } poly[i + seg * 3 + 1] = { x = x + r - sine, y = y + h - r + cosine } end surface.DrawPoly(poly) end
local x = 250 local y = 250 local r = 4 local d_r = 7 local t = 0.0001 local a = -0.035 clear() local color = {} color.alpha = 255 for i = 1, 50 do for angle = 0, 360, 1 do d_x = r * math.cos(angle * math.pi / 180) d_y = r * math.sin(angle * math.pi / 180) color.red = 125 * math.sin(0.5 * angle - 0) + 75 color.green = 125 * math.sin(0.5 * angle - 120) + 75 color.blue = 125 * math.sin(0.5 * angle - 240) + 75 draw(x + d_x, y + d_y, 5, color) sleep(t) r = r + d_r / 360 end a = a + 0.0005 print(a) end
USER_ID = "2001370210" KEY = "56b74108e785b589" DEV_CLASS = 'A' HOST = "115.28.93.201" PORT = 7005 VER = "32" udpSocket = net.createUDPSocket() function packSend(data) local status = "1234" local packet_class = "01" local sta = data local packet_len = string.format("%04d",41+string.len(sta)) packet = packet_len..VER..DEV_CLASS..packet_class..USER_ID..KEY..status..sta..'05' if (DEBUG) then print("[UDP ] 发送数据包"..packet) end udpSocket:send(PORT,HOST,packet) end function heartBeat(text) packSend("01"..text) end function warning(text) packSend("02"..text) end function ValUpload(id,data) sta = string.format("0B%s1%03d%d%s",USER_ID,id,#data,data) packSend(sta) end function packRece(s,data,serverport,serverip) if (DEBUG) then print("[UDP ] 接收到数据:"..data) print(string.format("[UDP ] 来自服务器: %s:%d",serverip, serverport)) end local cls = string.sub(data,8,9) if(cls == "01") then local code = string.sub(data,14,15) if (code == "01") then print("[UDP ] 收到心跳包回复") elseif(code == "02") then print("[UDP ] 报警上传成功") elseif(code == "03") then print("[UDP ] 获取到公网ip") end elseif (cls == "08") then local cmdEnd = tonumber(string.sub(data,1,4))-36+33 local cmd = string.sub(data,34,cmdEnd) print("[UDP ] 接收到命令"..cmd) fuhome_callback(cmd) packSend(string.format("09%sOK",string.sub(data,14,23))) end end udpSocket:on("receive", packRece) --warning("閽熷伐鍨冨溇") --钟工垃圾
-- $Id: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/SpaceMode/EscortPlan.lua#1 $ --///////////////////////////////////////////////////////////////////////////////////////////////// -- -- (C) Petroglyph Games, Inc. -- -- -- ***** ** * * -- * ** * * * -- * * * * * -- * * * * * * * * -- * * *** ****** * ** **** *** * * * ***** * *** -- * ** * * * ** * ** ** * * * * ** ** ** * -- *** ***** * * * * * * * * ** * * * * -- * * * * * * * * * * * * * * * -- * * * * * * * * * * ** * * * * -- * ** * * ** * ** * * ** * * * * -- ** **** ** * **** ***** * ** *** * * -- * * * -- * * * -- * * * -- * * * * -- **** * * -- --///////////////////////////////////////////////////////////////////////////////////////////////// -- C O N F I D E N T I A L S O U R C E C O D E -- D O N O T D I S T R I B U T E --///////////////////////////////////////////////////////////////////////////////////////////////// -- -- $File: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/SpaceMode/EscortPlan.lua $ -- -- Original Author: Brian Hayes -- -- $Author: Andre_Arsenault $ -- -- $Change: 37816 $ -- -- $DateTime: 2006/02/15 15:33:33 $ -- -- $Revision: #1 $ -- --///////////////////////////////////////////////////////////////////////////////////////////////// require("pgevents") -- -- Space Mode Escort -- function Definitions() DebugMessage("%s -- In Definitions", tostring(Script)) AllowEngagedUnits = false Category = "Space_Escort_Goal" IgnoreTarget = true TaskForce = { -- First Task Force { "MainForce" ,"Fighter = 1,4" ,"Interdictor_Cruiser = 0,1" } } end function MainForce_Thread() DebugMessage("%s -- In MainForce_Thread.", tostring(Script)) BlockOnCommand(MainForce.Produce_Force()); QuickReinforce(PlayerObject, AITarget, MainForce) DebugMessage("MainForce constructed at stage area!") Sleep(1) DebugMessage("Taskforce %s (of var type: %s) following object %s.", tostring(MainForce), type(MainForce), tostring(Target)) --BlockOnCommand(MainForce.Follow_Target(AITarget)) -- Give an initial order to put the escorts in a state that the Escort function expects MainForce.Guard_Target(AITarget) while true do Escort(MainForce, AITarget) end DebugMessage("%s -- MainForce Done! Exiting Script!", tostring(Script)) ScriptExit() end
local utils = require("utils") function clone(object, object_type, new_name) local prototype = data.raw[object_type][object] if not prototype.type or not prototype.name then error("Invalid prototype: prototypes must have name and type properties.") return nil end local p = table.deepcopy(prototype) p.name = new_name if p.minable and p.minable.result then p.minable.result = new_name end if p.place_result then p.place_result = new_name end if p.result then p.result = new_name end if p.results then for _, result in pairs(p.results) do if result.name == prototype.name then result.name = new_name end end end return p end require("prototypes.technology") require("prototypes.recipes") require("prototypes.items") require("prototypes.entities")
local mpath = pathJoin(os.getenv("MODULEPATH_ROOT"),"Compiler",myModuleFullName()) prepend_path("MODULEPATH",mpath)
local ip = ngx.var.binary_remote_addr -- ngx.say(ngx.var.remote_addr) -- ngx.exit(200) local limit = ngx.shared.limit local req, _ = limit:get(ip) if req then if req > 20 then ngx.exit(503) else limit:incr(ip, 1) end else limit:set(ip, 1, 10) end local jsjump = ngx.shared.jsjump local uri = ngx.var.request_uri local jspara,flags = jsjump:get(ip) local args = ngx.req.get_uri_args() if jspara then if flags then ngx.exec("@cc") else local p_jskey='' if args["jskey"] and type(args["jskey"])=='table' then p_jskey=args["jskey"][table.getn(args["jskey"])] else p_jskey=args["jskey"] end if p_jskey and p_jskey == tostring(jspara) then jsjump:set(ip, jspara, 3600, 1) ngx.exec("@cc") else local url='' if ngx.var.args then url=ngx.var.scheme.."://"..ngx.var.host..":"..ngx.var.server_port..uri.."&jskey="..jspara else url=ngx.var.scheme.."://"..ngx.var.host..":"..ngx.var.server_port..uri.."?jskey="..jspara end local jscode="<script>window.location.href='"..url.."';</script>" ngx.say(jscode) end end else math.randomseed( os.time() ); local random = math.random(100000,999999) jsjump:set(ip, random, 60) local url = '' if ngx.var.args then url = ngx.var.scheme.."://"..ngx.var.host..":"..ngx.var.server_port..uri.."&jskey="..random else url = ngx.var.scheme.."://"..ngx.var.host..":"..ngx.var.server_port..uri.."?jskey="..random end local jscode="<script>window.location.href='"..url.."';</script>" ngx.say(jscode) end
AddCSLuaFile() ENT.Type = "anim" ENT.PrintName = "Doorbust Charge" ENT.Author = "Black Tea" ENT.Spawnable = true ENT.AdminOnly = true ENT.Category = "NutScript - Weapons" ENT.RenderGroup = RENDERGROUP_BOTH ENT.radius = 32 ENT.burstTime = 5 ENT.doorRestore = 300 function ENT:SpawnFunction(client, trace, className) if (!trace.Hit or trace.HitSky) then return end local spawnPosition = trace.HitPos + trace.HitNormal * 16 local ent = ents.Create(className) local target = trace.Entity if (target and IsValid(target)) then local angles = trace.HitNormal:Angle() local axis = Angle(angles[1], angles[2], angles[3]) angles:RotateAroundAxis(axis:Right(), 90) ent:SetParent(target) ent:SetPos(spawnPosition - trace.HitNormal*13) ent:SetAngles(angles) ent:Spawn() ent:Activate() ent:ManipulateBoneScale(0, Vector(1, 1, 1)*.5) end return ent end if (SERVER) then function ENT:Initialize() self:SetModel("models/props_c17/consolebox05a.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_NONE) self:SetCollisionGroup(COLLISION_GROUP_WEAPON) self:SetDTBool(0,true) self:SetUseType(SIMPLE_USE) self.lifetime = CurTime() + self.burstTime self:EmitSound("buttons/button5.wav") local physicsObject = self:GetPhysicsObject() if (IsValid(physicsObject)) then physicsObject:Wake() end end function ENT:Explode() self:EmitSound("ambient/explosions/explode_1.wav", 120, 200) local doors = ents.FindInSphere(self:GetPos(), self.radius) for k, v in ipairs(doors) do if (v:isDoor()) then local dir = v:GetPos() - self:GetPos() dir:Normalize() v:blastDoor(dir * 300, 20, true) end if (v.fadeActivate) then -- isFadingdoor v:fadeActivate() timer.Simple(5, function() if IsValid(v) and v.fadeActive then v:fadeDeactivate() end end) end end local e = EffectData() e:SetStart(self:GetPos() + self:OBBCenter()) util.Effect( "doorCharge", e ) end function ENT:OnRemove() end function ENT:Think() if self.lifetime < CurTime() then self:Explode() self:Remove() end return CurTime() end function ENT:Use(activator) end else function ENT:Initialize() self.schema = self:GetDTInt(0) self.lifetime = CurTime() + self.burstTime self.beep = 255 end local GLOW_MATERIAL = Material("sprites/glow04_noz.vmt") function ENT:Draw() self:DrawModel() end function ENT:BeepLight() local firepos = self:GetPos() + ( self:GetUp() * 5 ) local col = Color(255, 0, 0) local dlight = DynamicLight(self:EntIndex()) dlight.Pos = firepos dlight.r = col.r dlight.g = col.g dlight.b = col.b dlight.Brightness = 2 dlight.Size = 64 dlight.Decay = 512 dlight.DieTime = CurTime() + 0.5 end function ENT:Think() if self:GetDTBool(0) then local burst = self.burstTime + (CurTime() - self.lifetime) self.beep = self.beep - FrameTime()*450*burst if self.beep <= 0 then self.beep = 255 local snd = "common/warning.wav" local rnd = { 150, 150 } self:EmitSound( snd, 70, math.random(rnd[1], rnd[2]) ) self:BeepLight() end else self.beep = 0 end end function ENT:DrawTranslucent() if self:GetDTBool(0) then local firepos = self:GetPos() - ( self:GetUp() * 2 ) local size = math.Clamp(self.beep/10, 0, 40) local col = Color(255, 0, 0) render.SetMaterial(GLOW_MATERIAL) render.DrawSprite(firepos, size, size, col ) end end end
-- Includes #include 'include/config.lua' -- Defines #POINTS_FACTOR = 1 -- Globals local g_Stats = { 'cash', 'points', 'mapsPlayed', 'mapsBought', 'mapsRated', #if(DM_STATS) then 'dmVictories', 'huntersTaken', 'dmPlayed', #end #if(DD_STATS) then 'ddVictories', 'ddPlayed', 'kills', #end #if(RACE_STATS) then 'raceVictories', 'racesFinished', 'racesPlayed', #end 'maxWinStreak', #if(TOP_TIMES) then 'toptimes_count', #end 'bidlvl', 'time_here', 'exploded', 'drowned'} PlayersTable:addColumns{ -- Old stats {'cash', 'INT', default = 0}, {'points', 'MEDIUMINT', default = 0}, {'exploded', 'MEDIUMINT UNSIGNED', default = 0}, {'drowned', 'MEDIUMINT UNSIGNED', default = 0}, -- New stats {'maxWinStreak', 'SMALLINT UNSIGNED', default = 0}, {'mapsPlayed', 'MEDIUMINT UNSIGNED', default = 0}, {'mapsBought', 'MEDIUMINT UNSIGNED', default = 0}, {'mapsRated', 'SMALLINT UNSIGNED', default = 0}, #if(DM_STATS) then {'huntersTaken', 'MEDIUMINT UNSIGNED', default = 0}, {'dmVictories', 'MEDIUMINT UNSIGNED', default = 0}, {'dmPlayed', 'MEDIUMINT UNSIGNED', default = 0}, #end #if(DD_STATS) then {'ddVictories', 'MEDIUMINT UNSIGNED', default = 0}, {'ddPlayed', 'MEDIUMINT UNSIGNED', default = 0}, {'kills', 'MEDIUMINT UNSIGNED', default = 0}, #end #if(RACE_STATS) then {'raceVictories', 'MEDIUMINT UNSIGNED', default = 0}, {'racesFinished', 'MEDIUMINT UNSIGNED', default = 0}, {'racesPlayed', 'MEDIUMINT UNSIGNED', default = 0}, #end {'achvCount', 'TINYINT UNSIGNED', default = 0}, -- Effectiveness (TODO) --[[{'efectiveness', 'FLOAT', default = 0}, {'efectiveness_dd', 'FLOAT', default = 0}, {'efectiveness_dm', 'FLOAT', default = 0}, {'efectiveness_race', 'FLOAT', default = 0},]] } local function StAccountDataChange(accountData, name, newValue) if(not table.find(g_Stats, name)) then return end -- not a stat local player = Player.fromId(accountData.id) if(not player) then return end if(name == 'points') then setPlayerAnnounceValue(player.el, 'score', tostring(newValue)) if(Settings.scoreboard_exp) then setElementData(player.el, 'exp', formatNumber(newValue)) end if(StDetectRankChange) then StDetectRankChange(player, accountData.points, newValue) end StDetectLevelChange(player, accountData.points, newValue) end if(name == 'cash' and Settings.scoreboard_cash) then setElementData(player.el, 'cash', formatMoney(newValue)) end end local function StAccountDataChangeDone(accountData, name) if(not table.find(g_Stats, name)) then return end -- not a stat local player = Player.fromId(accountData.id) if(player) then AchvCheckPlayer(player.el) end notifySyncerChange('stats', accountData.id) end local function StPlayerStatsSyncCallback(idOrPlayer) local id = touint(idOrPlayer) local player = (id and Player.fromId(id)) or Player.fromEl(idOrPlayer) local accountData if(player) then accountData = player.accountData elseif(id) then accountData = AccountData.create(id) else return false end local data = accountData:getTbl() if(not data) then return false end data._rank = StRankFromPoints(data.points) if(player) then -- send timestamp as string, because MTA converts all number to float (low precision) data._loginTimestamp = tostring(player.loginTimestamp) end data.name = data.name:gsub('#%x%x%x%x%x%x', '') return data end local function StUpdatePlayerScoreboardData(player) local pts = player.accountData.points setPlayerAnnounceValue(player.el, 'score', tostring(pts)) if(Settings.scoreboard_lvl) then local lvl = LvlFromExp(pts) setElementData(player.el, 'lvl', lvl) end if(Settings.scoreboard_exp) then setElementData(player.el, 'exp', formatNumber(pts)) end if(Settings.scoreboard_cash) then setElementData(player.el, 'cash', formatMoney(player.accountData.cash)) end end local function StOnPlayerJoinOrLogin() local player = Player.fromEl(source) StUpdatePlayerScoreboardData(player) end local function StOnPlayerWasted(totalAmmo, killer, weapon) local player = Player.fromEl(source) if(not player) then return end if(weapon == 53) then -- drowned player.accountData:add('drowned', 1) end end local function StOnVehicleExplode() local playerEl = getVehicleOccupant(source) local player = playerEl and Player.fromEl(playerEl) if(not player) then return end -- Note: Blow in Admin Panel generates two onVehicleExplode but only one has health > 0 if(getElementHealth(source) > 0) then player.accountData:add('exploded', 1) end end -- Called from maps function StMapStart(room) local mapTypeCounter = false local map = getCurrentMap(room) local mapType = map:getType() if(false) then #if(RACE_STATS) then elseif(room.isRace) then mapTypeCounter = 'racesPlayed' #end #if(DM_STATS) then elseif(mapType.name == 'DM') then mapTypeCounter = 'dmPlayed' #end #if(DD_STATS) then elseif(mapType.name == 'DD') then mapTypeCounter = 'ddPlayed' #end end for el, player in pairs(g_Players) do player.accountData:add('mapsPlayed', 1) if(mapTypeCounter) then player.accountData:add(mapTypeCounter, 1) end end if(DdMapStart) then DdMapStart(room) end end -- Called from maps function StMapStop(room) if(DdMapStop) then DdMapStop(room) end end function StPlayerWin(player) local room = player.room local map = getCurrentMap(room) local mapType = map and map:getType() local winCounter = false if(not mapType) then Debug.warn('unknown map type', 2) #if(RACE_STATS) then elseif(room.isRace) then winCounter = 'raceVictories' #end -- RACE_STATS #if(DM_STATS) then elseif(mapType.name == 'DM') then winCounter = 'dmVictories' #end -- DM_STATS #if(DD_STATS) then elseif(mapType.name == 'DD') then winCounter = 'ddVictories' #end -- DD_STATS end if(winCounter) then player.accountData:add(winCounter, 1) end if(room.winStreakPlayer == player.el) then room.winStreakLen = room.winStreakLen + 1 if(g_PlayersCount > 1) then scriptMsg("%s is on a winning streak! It's his %u. victory.", player:getName(), room.winStreakLen) end else room.winStreakPlayer = player.el room.winStreakLen = 1 end local maxStreak = player.accountData.maxWinStreak if(room.winStreakLen > maxStreak) then player.accountData.maxWinStreak = room.winStreakLen end #if(DD_TOPS) then if(mapType and mapType.name == 'DD' and DdAddVictory) then DdAddVictory(player, map) end #end -- DD_TOPS end -- Called from maps function StHunterTaken(player) #if(DM_STATS) then local map = getCurrentMap(player.room) local mapType = map and map:getType() if(not mapType or mapType.name ~= 'DM') then return end local ptsAdd = 5 player.accountData:add('huntersTaken', 1) player.accountData:add('points', ptsAdd) player:addNotify{ icon = 'stats/img/icon.png', {"You earned %s points. Total: %s.", formatNumber(ptsAdd), formatNumber(player.accountData.points)}, } #end end function StPlayerFinish(player, rank, ms) local room = player.room local map = getCurrentMap(player.room) local mapType = map and map:getType() if(not mapType) then return end local kills = player.currentMapKills or 0 player.currentMapKills = 0 if(room.isRace or mapType.name == 'DD' or rank == 1) then #if(RACE_STATS) then if(room.isRace) then player.accountData:add('racesFinished', 1) end #end local cashadd = math.floor(1000 * g_PlayersCount / rank) local pointsadd = math.floor($POINTS_FACTOR * g_PlayersCount / rank) local stats = {} stats.cash = player.accountData.cash + cashadd stats.points = player.accountData.points + pointsadd player.accountData:set(stats) local notify = { icon = 'stats/img/coins.png', {"%s added to your cash! Total: %s.", formatMoney(cashadd), formatMoney(stats.cash)}, {"You earned %s points. Total: %s.", formatNumber(pointsadd), formatNumber(stats.points)}, } if(mapType.name == 'DD' and kills > 0) then table.insert(notify, {"You have killed a total of %u players.", kills}) end player:addNotify(notify) end if(rank == 1) then StPlayerWin(player) end end -- Called from core function StSetupScoreboard(res) if(Settings.scoreboard_lvl) then call(res, 'scoreboardAddColumn', 'lvl', g_Root, 25, 'Lvl', false) end if(Settings.scoreboard_exp) then call(res, 'scoreboardAddColumn', 'exp', g_Root, 40, 'EXP', false) end if(Settings.scoreboard_cash) then call(res, 'scoreboardAddColumn', 'cash', g_Root, 70, 'Cash', false) end end local function StInit() if(StLoadRanks) then StLoadRanks() end for el, player in pairs(g_Players) do if(not player.is_console) then StUpdatePlayerScoreboardData(player) end end addSyncer('stats', StPlayerStatsSyncCallback) addEventHandler('onPlayerJoin', g_Root, StOnPlayerJoinOrLogin) Event('onPlayerLogin'):addHandler(StOnPlayerJoinOrLogin) addEventHandler('onPlayerLogout', g_Root, StOnPlayerJoinOrLogin) addEventHandler('onPlayerWasted', g_Root, StOnPlayerWasted) addEventHandler('onVehicleExplode', g_Root, StOnVehicleExplode) table.insert(AccountData.onChangeHandlers, StAccountDataChange) table.insert(AccountData.onChangeDoneHandlers, StAccountDataChangeDone) end addInitFunc(StInit)
require 'sys' require 'cunn' require 'ccn2' require 'cudnn' cudnn.benchmark = true -- run manual auto-tuner provided by cudnn cudnn.verbose = false -- require 'fbcunn' -- require 'nnbhwd' print('Running on device: ' .. cutorch.getDeviceProperties(cutorch.getDevice()).name) steps = 10 -- nb of steps in loop to average perf runs = { { -- first layer ni = 3, no = 96, kw = 11, kh = 11, iw = 128, ih = 128, bs = 128, dw = 1, dh = 1, }, { -- second layer ni = 64, no = 128, kw = 9, kh = 9, iw = 64, ih = 64, bs = 128, dw = 1, dh = 1, }, { -- third layer ni = 128, no = 128, kw = 9, kh = 9, iw = 32, ih = 32, bs = 128, dw = 1, dh = 1, }, { -- fourth layer ni = 128, no = 128, kw = 7, kh = 7, iw = 16, ih = 16, bs = 128, dw = 1, dh = 1, }, { -- layers with small inputs/kernels, seen at the lower ends of the network ni = 384, no = 384, kw = 3, kh = 3, iw = 13, ih = 13, bs = 128, dw = 1, dh = 1, }, } for i,run in ipairs(runs) do -- params for run: local ni,no,kw,kh,bs,iw,ih,dw,dh = run.ni,run.no,run.kw,run.kh,run.bs,run.iw,run.ih,run.dw,run.dh print('') print('CONFIG: input = ' .. ni..'x'..iw..'x'..ih..' * ker = ' .. ni..'x'..no..'x'..kw..'x'..kh .. ' (bs = '..bs..', stride = ' .. dw .. ')') local mods = {} mods[1] = cudnn.SpatialConvolution(ni,no,kw,kh,dw,dh):cuda() mods[2] = nn.SpatialConvolutionMM(ni,no,kw,kh,dw,dh):cuda() -- mods[3] = ccn2.SpatialConvolution(ni,no,kw,dw,0,1,4):cuda() -- mods[4] = nn.SpatialConvolutionCuFFT(ni,no,kw,kh,dw,dh):cuda() -- mods[4] = nn.SpatialConvolutionBHWD(ni,no,kw,kh,dw,dh):cuda() for j=1,#mods do local tmf, tmbi, tmbg collectgarbage() if torch.typename(mods[j]) == 'ccn2.SpatialConvolution' then i1 = torch.randn(ni, ih, iw, bs):cuda(); elseif torch.typename(mods[j]) == 'nn.SpatialConvolutionBHWD' then i1 = torch.randn(bs, ih, iw, ni):cuda(); else i1 = torch.randn(bs, ni, ih, iw):cuda() end collectgarbage() local o1 = mods[j]:forward(i1) cutorch.synchronize() collectgarbage() sys.tic() for t = 1,steps do o1 = mods[j]:updateOutput(i1) end cutorch.synchronize() tmf = sys.toc()/steps print(string.format("%-30s %25s %10.2f", torch.typename(mods[j]), ':updateOutput():', tmf*1000)) cutorch.synchronize() collectgarbage() sys.tic() for t = 1,steps do mods[j]:updateGradInput(i1, o1) end cutorch.synchronize() tmbi = sys.toc()/steps print(string.format("%-30s %25s %10.2f", torch.typename(mods[j]), ':updateGradInput():', tmbi*1000)) cutorch.synchronize() collectgarbage() sys.tic() local ok = 1 for t = 1,steps do ok = pcall(function() mods[j]:accGradParameters(i1, o1) end) end cutorch.synchronize() tmbg = sys.toc()/steps if not ok then print(string.format("%-30s %25s %s", torch.typename(mods[j]), ':accGradParameters():', 'FAILED!')) else print(string.format("%-30s %25s %10.2f", torch.typename(mods[j]), ':accGradParameters():', tmbg*1000)) end print(string.format("%-30s %25s %10.2f", torch.typename(mods[j]), ':TOTAL:', (tmf+tmbi+tmbg)*1000)) print() end end print('')
admins = {"arts@psto.net", "arts@point.im" } use_libevent = true; modules_enabled = { "roster"; "saslauth"; "tls"; "dialback"; "disco"; "private"; "vcard"; "legacyauth"; "ping"; "pep"; "register"; "adhoc"; "admin_adhoc"; "admin_telnet"; "posix"; "s2s_blackwhitelist"; -- http://code.google.com/p/prosody-modules/wiki/mod_s2s_blackwhitelist "s2s_auth_compat"; -- for ya.ru }; modules_disabled = { }; allow_registration = false; -- s2s blacklisting s2s_enable_blackwhitelist = "blacklist" s2s_blacklist = { "gomorra.dyndns-remote.com" } authentication = "internal_plain" log = { {levels = {min = "info"}, to = "console"}; } daemonize = false; VirtualHost "point.im" ssl = { key = "/home/point/ssl/server.key"; certificate = "/home/point/ssl/server.crt"; }
--[[ Module\Focus\focus.lua Move MyfocusFrame here Terry@bf 2010 - 09 - 29 ]] local T = LibStub("AceAddon-3.0"):GetAddon("TUnitFrame") if not T then return end local M = T:NewModule("FocusFrame") if not M then return end function M:OnInitialize() T:Debug("FocusFrame Module initialized") end function M:OnEnable() T:Debug("FocusFrame Module enabled") end function M:OnDisable() T:Debug("FocusFrame Module Disabled") end
local utils = {} -- Transform the coordinates from the original image space to the cropped one function utils.transform(pt, center, scale, res, invert) -- Define the transformation matrix local pt_new = torch.ones(3) pt_new[1], pt_new[2] = pt[1], pt[2] local h = 200*scale local t = torch.eye(3) t[1][1], t[2][2] = res/h, res/h t[1][3], t[2][3] = res*(-center[1]/h+0.5), res*(-center[2]/h+0.5) if invert then t = torch.inverse(t) end local new_point = (t*pt_new):sub(1,2):int() return new_point end -- Crop based on the image center & scale function utils.crop(img, center, scale, res) local l1 = utils.transform({1,1}, center, scale, res, true) local l2 = utils.transform({res,res}, center, scale, res, true) local pad = math.floor(torch.norm((l1 - l2):float())/2 - (l2[1]-l1[1])/2) if img:nDimension() < 3 then img = torch.repeatTensor(img,3,1,1) end local newDim = torch.IntTensor({img:size(1), l2[2] - l1[2], l2[1] - l1[1]}) local newImg = torch.zeros(newDim[1],newDim[2],newDim[3]) local height, width = img:size(2), img:size(3) local newX = torch.Tensor({math.max(1, -l1[1]+1), math.min(l2[1], width) - l1[1]}) local newY = torch.Tensor({math.max(1, -l1[2]+1), math.min(l2[2], height) - l1[2]}) local oldX = torch.Tensor({math.max(1, l1[1]+1), math.min(l2[1], width)}) local oldY = torch.Tensor({math.max(1, l1[2]+1), math.min(l2[2], height)}) newImg:sub(1,newDim[1],newY[1],newY[2],newX[1],newX[2]):copy(img:sub(1,newDim[1],oldY[1],oldY[2],oldX[1],oldX[2])) newImg = image.scale(newImg,res,res) return newImg end function utils.getPreds(heatmaps, center, scale) if heatmaps:nDimension() == 3 then heatmaps = heatmaps:view(1, unpack(heatmaps:size():totable())) end -- Get locations of maximum activations local max, idx = torch.max(heatmaps:view(heatmaps:size(1), heatmaps:size(2), heatmaps:size(3) * heatmaps:size(4)), 3) local preds = torch.repeatTensor(idx, 1, 1, 2):float() preds[{{}, {}, 1}]:apply(function(x) return (x - 1) % heatmaps:size(4) + 1 end) preds[{{}, {}, 2}]:add(-1):div(heatmaps:size(3)):floor():add(1) for i = 1,preds:size(1) do for j = 1,preds:size(2) do local hm = heatmaps[{i,j,{}}] local pX, pY = preds[{i,j,1}], preds[{i,j,2}] if pX > 1 and pX < 64 and pY > 1 and pY < 64 then local diff = torch.FloatTensor({hm[pY][pX+1]-hm[pY][pX-1], hm[pY+1][pX]-hm[pY-1][pX]}) preds[i][j]:add(diff:sign():mul(.25)) end end end preds:add(-0.5) -- Get the coordinates in the original space local preds_orig = torch.zeros(preds:size()) for i = 1, heatmaps:size(1) do for j = 1, heatmaps:size(2) do preds_orig[i][j] = utils.transform(preds[i][j],center,scale,heatmaps:size(3),true) end end return preds, preds_orig end function utils.shuffleLR(x) local dim if x:nDimension() == 4 then dim = 2 else assert(x:nDimension() == 3) dim = 1 end local matched_parts = { {1,6}, {2,5}, {3,4}, {11,16}, {12,15}, {13,14} } for i = 1,#matched_parts do local idx1, idx2 = unpack(matched_parts[i]) local tmp = x:narrow(dim, idx1, 1):clone() x:narrow(dim, idx1, 1):copy(x:narrow(dim, idx2, 1)) x:narrow(dim, idx2, 1):copy(tmp) end return x end function utils.flip(x) local y = torch.FloatTensor(x:size()) for i = 1, x:size(1) do image.hflip(y[i], x[i]:float()) end return y:typeAs(x) end function utils.calcDistance(predictions,groundTruth) local n = predictions:size()[1] gnds = torch.Tensor(n,16,2) for i=1,n do gnds[{{i},{},{}}] = groundTruth[i].points end local dists = torch.Tensor(predictions:size(2),predictions:size(1)) -- Calculate L2 for i = 1,predictions:size(1) do for j = 1,predictions:size(2) do if gnds[i][j][1] > 1 and gnds[i][j][2] > 1 then dists[j][i] = torch.dist(gnds[i][j],predictions[i][j])/groundTruth[i].headSize else dists[j][i] = -1 end end end return dists end function utils.getFileList(opts) local fileLists = {} tempFileList = torch.load('dataset/mpii_dataset.t7') if opts.mode == 'demo' then local idxs = {1,5,16,17,18,24,28,63,66,104} for i = 1, #idxs do fileLists[i] = tempFileList[idxs[i]] end else for i = 1, #tempFileList do if tempFileList[i]['type'] == 0 then fileLists[#fileLists+1] = tempFileList[i] end end end return fileLists end -- Requires gnuplot function utils.plot(surface, points, size) points = points:view(16,2) local matched_parts = { {1,2}, {2,3}, {3,7}, {4,5}, {5,6}, {4,7}, {9,10},{7,8}, {11,12}, {12,13}, {13,8}, {8,14}, {14,15}, {15,16} } local parts_colours = { "blue", "blue", "blue", "red", "red", "red", "#9400D3", "#9400D3", "blue", "blue", "blue", "red", "red", "red" } gnuplot.figure(1) gnuplot.raw("set size ratio -1") gnuplot.raw("set xrange [0:"..size[1].."]") gnuplot.raw("set yrange [0:"..size[2].."]") gnuplot.raw("unset key; unset tics; unset border;") gnuplot.raw("set multiplot layout 1,1 margins 0.05,0.95,.1,.99 spacing 0,0") gnuplot.raw("plot '"..surface.."' binary filetype=jpg with rgbimage") gnuplot.raw(" set yrange ["..size[2]..":0] ") commands = {} for i = 1, #matched_parts do commands[i] = {torch.Tensor{points[matched_parts[i][1]][1],points[matched_parts[i][2]][1]},torch.Tensor{points[matched_parts[i][1]][2],points[matched_parts[i][2]][2]},'with lines lw 5 linecolor rgb "'..parts_colours[i]..'"'} end gnuplot.plot(unpack(commands)) gnuplot.raw("unset multiplot") end local function displayPCKh(dists, idxs, title, disp_key) local xs = torch.linspace(0,0.5,30) local ys = torch.zeros(xs:size(1)) local total = {dists[{idxs[1],{}}]:gt(-1):sum(), dists[{idxs[2],{}}]:gt(-1):sum()} for i = 1, xs:size(1) do ys[i] = 0.5*((dists[{idxs[1],{}}]:lt(xs[i]):sum()-(dists:size(2)-total[1]))/total[1]+(dists[{idxs[2],{}}]:lt(xs[i]):sum()-(dists:size(2)-total[2]))/total[2]) end local command = {xs,ys,'-'} gnuplot.raw('set title "'..title..'"') if not disp_key then gnuplot.raw('unset key') else gnuplot.raw('set key font ",6" right bottom') end gnuplot.raw('set xrange [0:0.5]') gnuplot.raw('set yrange [0:1]') gnuplot.plot(unpack(command)) end function utils.calculateMetrics(dists) gnuplot.raw('set bmargin 1') gnuplot.raw('set lmargin 3.2') gnuplot.raw('set rmargin 2') gnuplot.raw('set multiplot layout 2,3 title "MPII Validation (PCKh)"') gnuplot.raw('set xtics font ",6"') gnuplot.raw('set xtics font ",6"') displayPCKh(dists, {9,10}, 'Head') displayPCKh(dists, {2,5}, 'Knee') displayPCKh(dists, {1,6}, 'Ankle') gnuplot.raw('set tmargin 2.5') gnuplot.raw('set bmargin 1.5') displayPCKh(dists, {13,14}, 'Shoulder') displayPCKh(dists, {12,15}, 'Elbow') displayPCKh(dists, {11,16}, 'Wrist', true) gnuplot.raw('unset multiplot') local threshold = 0.5 dists:apply(function(x) if x>=0 and x<= threshold then return 1 elseif x>threshold then return 0 end end) local count = torch.zeros(16) local sums = torch.zeros(16) for i=1,16 do dists[i]:apply(function(x) if x ~= -1 then count[i] = count[i] + 1 sums[i] = sums[i] + x end end) end local partNames = {'Head', 'Knee', 'Ankle', 'Shoulder', 'Elbow', 'Wrist', 'Hip'} local partsC = torch.Tensor({{9,10},{2,5},{1,6},{13,14},{12,15},{11,16},{3,4}}) print('PCKh results:') for i=1,#partNames do print(partNames[i]..': ',(sums[partsC[i][1]]/count[partsC[i][1]]+sums[partsC[i][2]]/count[partsC[i][1]])*100/2) end end return utils
local exit = os.exit local dofile = dofile local getpid = require('testcase.getpid') local PID = getpid() for _, pathname in ipairs({ 'test/eval_test.lua', 'test/exit_test.lua', 'test/filesystem_test.lua', 'test/getopts_test.lua', 'test/getpid_test.lua', 'test/iohook_test.lua', 'test/printer_test.lua', 'test/registry_test.lua', 'test/runner_test.lua', 'test/testcase_test.lua', 'test/timer_test.lua', }) do dofile(pathname) if getpid() ~= PID then exit(0) end end
--script at workspace.boot_button.Script --Generate a part that will call a touched() event at BIOS function callBIOS() local currentPos = script.Parent.Position currentPos = Vector3.new(currentPos.X - 2, currentPos.Y + 1, currentPos.Z) local caller = Instance.new("Part") caller.Position = currentPos caller.Size = Vector3.new(1, 1, 1) caller.Name = "Power On" caller.Parent = workspace end script.Parent.ClickDetector.MouseClick:Connect(callBIOS)
require("hall/password/type/passwordTypeObject"); local PasswordTypeObjectMatchInvite = class(PasswordTypeObject); -- virtual PasswordTypeObjectMatchInvite.generateData = function(self) local info = table.verify(InvitationalDataInterface.getInstance():getCurMyMatchItemData()); local data = { matchId = info.matchId, } return data end -- virtual PasswordTypeObjectMatchInvite.analyseData = function(self, data) data.matchId = tonumber(data.matchId) or 0; return data; end -- virtual PasswordTypeObjectMatchInvite.executeOnShow = function(self, obj, func, sourceType) if obj and func then func(obj); end StateMachine.getInstance():pushState(States.Invitational) InvitationalDataInterface.getInstance():enterMatch({code = self.m_data.matchId}) end -- virtual PasswordTypeObjectMatchInvite.shareByWechat = function(self, password, qrFileName) Log.v("PasswordTypeObjectMatchInvite.shareByWechat", password, qrFileName) local data = InvitationalDataInterface.getInstance():getCurMyMatchItemData() if not data or not password or not qrFileName then return end self:createShareLayer(data, qrFileName) self:offscreenRender() end PasswordTypeObjectMatchInvite.offscreenRender = function(self) if self.m_isScreening then return end self.m_isScreening = true local path = System.offscreenRender(self.m_shareLayer) if self.m_shareLayer then delete(self.m_shareLayer) self.m_shareLayer = self.m_shareLayer end if not string.isEmpty(path) then Clock.instance():schedule_once(function() Log.v("PasswordTypeObjectMatchInvite.offscreenRender====", path) self.m_isScreening = nil WeixinShareUtil.getInstance():weixinSendImage(path, false) end) end end --创建分享层 PasswordTypeObjectMatchInvite.createShareLayer = function(self, data, qrFileName) local InvitationalShare = require("hall/invitational/widget/invitationalShare") self.m_shareLayer = new(InvitationalShare) self.m_shareLayer:setName(kUserInfoData:getNickname()) self.m_shareLayer:setTitle(data.matchName) self.m_shareLayer:setRoomId(data.matchId) self.m_shareLayer:setHead(data.headFileName) self.m_shareLayer:setQR(qrFileName) end -- virtual PasswordTypeObjectMatchInvite.shareByQQ = function(self, password) local data = InvitationalDataInterface.getInstance():getCurMyMatchItemData() if not password or not data then return end local text = self:getQQShareContentText(data, password) PasswordDataInterface.getInstance():setTextToClipboard(text) WeixinShareUtil.getInstance():openQQ() end --获取分享内容 PasswordTypeObjectMatchInvite.getQQShareContentText = function(self, data, password) local appName = RegionConfigDataInterface.getInstance():getRegionProductName() local region = kClientInfo:getRegionId() local url = self:_getShareContent(password) local matchId = data.matchId or "" local token = "★" token = string.format("%s%s%s", token, password, token) return string.format("%s【邀请赛】比赛编号:%s,长按→复制这条消息,打开 %s 跟我一起玩!%s", appName, matchId, url, token) end -- virtual PasswordTypeObjectMatchInvite.shareByQr = function(self, password) local wechatUrl = self:_getShareContent(password); return _, wechatUrl; end PasswordTypeObjectMatchInvite._getShareContent = function(self, password) local data = InvitationalDataInterface.getInstance():getCurMyMatchItemData() local url = InvitationalDataInterface.getInstance():getQcodeUrl() or "" local str = string.format("%s&matchid=%s", url, data and data.matchId or ""); local urlWithPassword = PasswordDataInterface.getInstance():generateUrlWithPassword(str, password); return urlWithPassword; end return PasswordTypeObjectMatchInvite;
---------------------------------- -- Author : Jean Loup Pecquais -- Name : Group/Ungroup selected item ---------------------------------- local function main() reaper.Undo_BeginBlock() local item_count = reaper.CountSelectedMediaItems(0) local GroupeState = 0 for i = 0, item_count - 1 do local sel_item = reaper.GetSelectedMediaItem(0,i) isGrouped = reaper.GetMediaItemInfo_Value(sel_item, "I_GROUPID") if isGrouped ~= 0 then GroupeState = GroupeState + 1 end end if GroupeState ~= 0 then reaper.Main_OnCommandEx(40033, 1, 0) reaper.Undo_EndBlock("Ungroup item(s)", 0) else reaper.Main_OnCommandEx(40032, 1, 0) reaper.Undo_EndBlock("Group item(s)", 0) end -- new code --[[ local itemCount = reaper.CountSelectedMediaItems(0) for i = 0, itemCount - 1 do local item = reaper.GetSelectedMediaItem(0,i) local itemGroup = reaper.GetMediaItemInfo_Value(item, "I_GROUPID") print(itemGroup) if itemGroup == 0 then local groupID = getEmptyItemGroup() reaper.SetMediaItemInfo_Value( item, "I_GROUPID", groupID) reaper.Undo_EndBlock("Group item(s)", 0) else local itemArr = getItemsFromGroup( itemGroup ) setItemsToNewGroup( itemArr, 0 ) reaper.Undo_EndBlock("Ungroup item(s)", 0) end end --]] end ---------------------------------------------------------------- main()
---@class CS.FairyEditor.Component.FontSizeInput : CS.FairyGUI.GLabel ---@field public value number ---@field public max number ---@type CS.FairyEditor.Component.FontSizeInput CS.FairyEditor.Component.FontSizeInput = { } ---@return CS.FairyEditor.Component.FontSizeInput function CS.FairyEditor.Component.FontSizeInput.New() end ---@param xml CS.FairyGUI.Utils.XML function CS.FairyEditor.Component.FontSizeInput:ConstructFromXML(xml) end return CS.FairyEditor.Component.FontSizeInput
giant_decay_mite_hatchling = Creature:new { objectName = "@mob/creature_names:giant_decay_mite_hatchling", socialGroup = "mite", faction = "", level = 7, chanceHit = 0.25, damageMin = 50, damageMax = 55, baseXp = 187, baseHAM = 113, baseHAMmax = 138, armor = 0, resists = {110,110,0,0,0,0,0,-1,-1}, meatType = "meat_insect", meatAmount = 5, hideType = "hide_scaley", hideAmount = 4, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK, optionsBitmask = AIENABLED, diet = CARNIVORE, templates = {"object/mobile/decay_mite.iff"}, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { {"",""}, {"milddisease",""} } } CreatureTemplates:addCreatureTemplate(giant_decay_mite_hatchling, "giant_decay_mite_hatchling")
--[[This file calls the main objects]]-- -- Creates objects -- local loader = {} local input = {} local audio = {} local screen = {} -- Main loader function -- function love.load() -- Main objects and initialization -- screen = require("objects.screen") audio = require("objects.audio") input = require("objects.input") loader = require("objects.loader") screen.initialize(loader, input) audio.initialize(loader) input.initialize(loader) loader.initialize(screen, audio, input) font = love.graphics.newFont("font/pc98.ttf", 50) love.graphics.setFont(font) end -- Main draw function -- function love.draw() love.graphics.scale(screen.width/800, screen.height/600) loader.draw() screen.draw() end function love.conf(t) -- The LÖVE version this game was made for (string) t.console = true end -- Main update function -- function love.update(dt) screen.update(dt) input.getJoystick() audio.update(dt) input.update(dt) loader.update(dt) end
local activewidget = nil; local activenode = nil; function onInit() -- create the active indicator widget activewidget = addBitmapWidget(activeicon[1]); activewidget.setVisible(false); -- get the active node if User.isHost() then activenode = window.getDatabaseNode().createChild("actor.active", "number"); if activenode then if activenode.getValue() ~= 1 then activenode.setValue(0); end end else Debug.console("actoractiveindicator.lua: onInit() - window.getDatabaseNode().getNodeName() = " .. window.getDatabaseNode().getNodeName()); --activenode = window.getDatabaseNode().createChild("actor.active"); activenode = DB.findNode(window.getDatabaseNode().getNodeName() .. ".actor.active"); --Debug.console("actoractiveindicator.lua: onInit() - activenode.getNodeName() = " .. activenode.getNodeName()); end activenode.onUpdate = onUpdate; onUpdate(activenode); end function onUpdate(source) if activenode then if activenode.getValue() == 1 then activewidget.setVisible(true); else activewidget.setVisible(false); end end end function onClickDown(button, x, y) return true; end function onClickRelease(button, x, y) return InitiativeManager.activateActor(window.getDatabaseNode()); end
--region super.lua --Author : jefflwq --Date : 2016/02/24 --说明 : 用于在类中调用基类成员函数 --用例 -- class "clsA" -- { -- clsA = -- function(self, name) -- print("In clsA.") -- end, -- PrintName = -- function(self) -- print("In clsA.PrintName") -- end, -- }, -- class "clsB" : clsA --继承自clsA -- { -- clsB1 = -- function(self, name) -- print("In clsB.") -- self.super("", name) --调用基类的构造函数 -- end, -- PrintName = -- function(self) -- print("In clsB.PrintName") -- self.super("PrintName") --调用基类的成员函数 -- end, -- }, --endregion using "Joop" local CurrentObj = false --调用super的对象 local SuperClass = false local Func = false local function InvalidSyntax() Error("Invalid syntax for using 'super' keyword", 2) return end local function CallSuperFunc(self, ...) if Func then --调用一个函数 return Func(CurrentObj, ...) end --调用ctor local f = SuperClass.___ctor if f then return f(CurrentObj, ...) end end local function Init(obj, superClass) CurrentObj = obj SuperClass = superClass Func = false end local function FindSuperFunc(self, key) if type(key) == "string" then local f = SuperClass[key] if f == nil then Error(key .. " is not found in this class' super.", 4) end if type(f) ~= "function" then Error(key .. " must be a function of this class' super.", 4) end Func = f return self end end local _super = { } setmetatable(_super, {__index = FindSuperFunc, __newindex = InvalidSyntax, __call = CallSuperFunc}) local function CallingSuper(_, obj, isObj) --local fenv = getfenv(isObj and 3 or 4) local fenv = getfenv(3) --if table.IsTypeOf(fenv) then local superClass = rawget(fenv, "___super") if superClass then Init(obj, superClass) return _super else Error(GetJoopTypeName(obj) .. " has no super.", 4) end --end Error("Usage: self.super.Func(...)", 3) return nil end keyword "super" { ___super = function(self) Joop.SetOnNewindex(self, InvalidSyntax) Joop.SetOnCall(self, CallingSuper) end, }