content
stringlengths
5
1.05M
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file find_package.lua -- -- imports import("lib.detect.find_file") import("lib.detect.find_library") import("lib.detect.find_tool") import("core.project.config") import("core.project.target") -- find vcpkg root directory function _find_vcpkgdir() local vcpkgdir = _g.vcpkgdir if vcpkgdir == nil then local vcpkg = find_tool("vcpkg") if vcpkg then local dir = path.directory(vcpkg.program) if os.isdir(path.join(dir, "installed")) then vcpkgdir = dir elseif is_host("macosx", "linux") then local brew = find_tool("brew") if brew then dir = try { function () return os.iorunv(brew.program, {"--prefix", "vcpkg"}) end } end if dir then dir = path.join(dir:trim(), "libexec") if os.isdir(path.join(dir, "installed")) then vcpkgdir = dir end end end end _g.vcpkgdir = vcpkgdir or false end return vcpkgdir or nil end -- find package from the vcpkg package manager -- -- @param name the package name, e.g. zlib, pcre -- @param opt the options, e.g. {verbose = true, version = "1.12.x") -- function main(name, opt) -- attempt to find vcpkg directory local vcpkgdir = _find_vcpkgdir() if not vcpkgdir then return end -- fix name, e.g. ffmpeg[x264] as ffmpeg -- @see https://github.com/xmake-io/xmake/issues/925 name = name:gsub("%[.-%]", "") -- get arch, plat and mode local arch = opt.arch local plat = opt.plat local mode = opt.mode -- mapping plat if plat == "macosx" then plat = "osx" end -- archs mapping for vcpkg local archs = { x86_64 = "x64", i386 = "x86", -- android: armeabi armeabi-v7a arm64-v8a x86 x86_64 mips mip64 -- Offers a doc: https://github.com/microsoft/vcpkg/blob/master/docs/users/android.md ["armeabi-v7a"] = "arm", ["arm64-v8a"] = "arm64", -- ios: arm64 armv7 armv7s i386 armv7 = "arm", armv7s = "arm", arm64 = "arm64", } -- mapping arch arch = archs[arch] or arch -- get the vcpkg installed directory local installdir = path.join(vcpkgdir, "installed") -- get the vcpkg info directory local infodir = path.join(installdir, "vcpkg", "info") -- find the package info file, e.g. zlib_1.2.11-3_x86-windows[-static].list local triplet = arch .. "-" .. plat local pkgconfigs = opt.pkgconfigs if plat == "windows" and pkgconfigs and pkgconfigs.shared ~= true then triplet = triplet .. "-static" if pkgconfigs.vs_runtime and pkgconfigs.vs_runtime:startswith("MD") then triplet = triplet .. "-md" end end local infofile = find_file(format("%s_*_%s.list", name, triplet), infodir) -- save includedirs, linkdirs and links local result = nil local info = infofile and io.readfile(infofile) or nil if info then for _, line in ipairs(info:split('\n')) do line = line:trim() if plat == "windows" then line = line:lower() end -- get includedirs if line:endswith("/include/") then result = result or {} result.includedirs = result.includedirs or {} table.insert(result.includedirs, path.join(installdir, line)) end -- get linkdirs and links if (plat == "windows" and line:endswith(".lib")) or line:endswith(".a") then if line:find(triplet .. (mode == "debug" and "/debug" or "") .. "/lib/", 1, true) then result = result or {} result.links = result.links or {} result.linkdirs = result.linkdirs or {} result.libfiles = result.libfiles or {} table.insert(result.linkdirs, path.join(installdir, path.directory(line))) table.insert(result.links, target.linkname(path.filename(line))) table.insert(result.libfiles, path.join(installdir, path.directory(line), path.filename(line))) end end -- add shared library directory (/bin/) to linkdirs for running with PATH on windows if plat == "windows" and line:endswith(".dll") then if line:find(plat .. (mode == "debug" and "/debug" or "") .. "/bin/", 1, true) then result = result or {} result.linkdirs = result.linkdirs or {} result.libfiles = result.libfiles or {} table.insert(result.linkdirs, path.join(installdir, path.directory(line))) table.insert(result.libfiles, path.join(installdir, path.directory(line), path.filename(line))) end end end end -- save version if result and infofile then local infoname = path.basename(infofile) result.version = infoname:match(name .. "_(%d+%.?%d*%.?%d*.-)_" .. arch) if not result.version then result.version = infoname:match(name .. "_(%d+%.?%d*%.-)_" .. arch) end end -- remove repeat if result then if result.linkdirs then result.linkdirs = table.unique(result.linkdirs) end if result.includedirs then result.includedirs = table.unique(result.includedirs) end end return result end
require 'paths' require 'torch' require 'xlua' require 'optim' require 'nn' require 'nngraph' require 'string' require 'image' require 'cutorch' require 'cunn' require 'cudnn' optnet = require 'optnet' torch.setdefaulttensortype('torch.FloatTensor') opt = {} opt.dropout = 0 opt.spatialdropout = 0.2 opt.nonlinearity = 'relu' opt.nFeats = 256 opt.nStack = 8 opt.inputRes = 256 opt.outputRes = 256 outputDim = {{16}} local Residual, relu = paths.dofile('../models/layers/ResidualSML.lua') local function model_maxpool_upsampling() local input = nn.Identity()() -- Initial processing of the image local cnv1 = nn.Sequential() :add(nn.SpatialConvolution(3,64,7,7,2,2,3,3)) -- 128 :add(nn.SpatialBatchNormalization(64)) :add(relu())(input) local r1 = Residual(64,128)(cnv1) -- 64 local pool1 = nn.SpatialMaxPooling(2,2,2,2)(r1) local r2 = Residual(128,128)(pool1) local pool2 = nn.SpatialMaxPooling(2,2,2,2)(r2) local r3 = Residual(128,128)(pool2) local up1 = nn.SpatialUpSamplingNearest(2)(r3) local r4 = Residual(128,256)(up1) local up2 = nn.SpatialUpSamplingNearest(2)(r4) return nn.gModule({input}, {up2}) end local function model_fullconv() local input = nn.Identity()() -- Initial processing of the image local cnv1 = nn.Sequential() :add(nn.SpatialConvolution(3,64,7,7,2,2,3,3)) -- 128 :add(nn.SpatialBatchNormalization(64)) :add(relu())(input) local r1 = Residual(64,128, 'D')(cnv1) -- 64 local r2 = Residual(128,128, 'D')(r1) local r3 = Residual(128,128, 'U')(r2) local r4 = Residual(128,256, 'U')(r3) return nn.gModule({input}, {r4}) end print('\n****************************************') print('Testing models memory usage: ') print(' - Model1 (maxpool + upsampling layers)') print(' - Model2 (full convolutions)') print('****************************************\n') --[[ Setup Input tensor ]]-- local input = torch.Tensor(4,3,256,256):uniform() --[[ Test model with maxpool+upsampling layers]] local mem1, mem2 do local model = model_maxpool_upsampling() local res = model:forward(input) mem1 = optnet.countUsedMemory(model) print('Model1 memory usage: ' .. mem1.total_size/1024/1024) end --[[ Test model without maxpool+upsampling layers]] do local model = model_fullconv() local res = model:forward(input) mem2 = optnet.countUsedMemory(model) print('Model2 memory usage: ' .. mem2.total_size/1024/1024) end print('Memory savings: ' .. (mem2.total_size/mem1.total_size))
return { active = true, on = { devices = {'VS PIR Woonkamer'} }, execute = function(domoticz, pirLivingRoom) if (pirLivingRoom.state == 'On' and domoticz.time.isNightTime --and domoticz.devices('PIRL Woonkamer').state == 'On' -- it's dark and domoticz.devices('VS Staande lamp').state == 'Off') then domoticz.devices('VS Staande lamp').switchOn() end end }
local utils = require 'misc.utils' local net_utils = {} -- take a raw CNN from Caffe and perform surgery. Note: VGG-16 SPECIFIC! function net_utils.build_cnn(cnn, opt) local layer_num = utils.getopt(opt, 'layer_num', 38) local backend = utils.getopt(opt, 'backend', 'cudnn') local encoding_size = utils.getopt(opt, 'encoding_size', 512) if backend == 'cudnn' then require 'cudnn' backend = cudnn elseif backend == 'nn' then require 'nn' backend = nn else error(string.format('Unrecognized backend "%s"', backend)) end -- copy over the first layer_num layers of the CNN local cnn_part = nn.Sequential() for i = 1, layer_num do local layer = cnn:get(i) if i == 1 then -- convert kernels in first conv layer into RGB format instead of BGR, -- which is the order in which it was trained in Caffe local w = layer.weight:clone() -- swap weights to R and B channels print('converting first layer conv filters from BGR to RGB...') layer.weight[{ {}, 1, {}, {} }]:copy(w[{ {}, 3, {}, {} }]) layer.weight[{ {}, 3, {}, {} }]:copy(w[{ {}, 1, {}, {} }]) end cnn_part:add(layer) end cnn_part:add(nn.Linear(4096,encoding_size)) cnn_part:add(backend.ReLU(true)) return cnn_part end -- takes a batch of images and preprocesses them -- VGG-16 network is hardcoded, as is 224 as size to forward function net_utils.prepro(imgs, data_augment, on_gpu) assert(data_augment ~= nil, 'pass this in. careful here.') assert(on_gpu ~= nil, 'pass this in. careful here.') local h,w = imgs:size(3), imgs:size(4) local cnn_input_size = 224 -- cropping data augmentation, if needed if h > cnn_input_size or w > cnn_input_size then local xoff, yoff if data_augment then xoff, yoff = torch.random(w-cnn_input_size), torch.random(h-cnn_input_size) else -- sample the center xoff, yoff = math.ceil((w-cnn_input_size)/2), math.ceil((h-cnn_input_size)/2) end -- crop. imgs = imgs[{ {}, {}, {yoff,yoff+cnn_input_size-1}, {xoff,xoff+cnn_input_size-1} }] end -- ship to gpu or convert from byte to float if on_gpu then imgs = imgs:cuda() else imgs = imgs:float() end -- lazily instantiate vgg_mean if not net_utils.vgg_mean then net_utils.vgg_mean = torch.FloatTensor{123.68, 116.779, 103.939}:view(1,3,1,1) -- in RGB order end net_utils.vgg_mean = net_utils.vgg_mean:typeAs(imgs) -- a noop if the types match -- subtract vgg mean imgs:add(-1, net_utils.vgg_mean:expandAs(imgs)) return imgs end function net_utils.list_nngraph_modules(g) local omg = {} for i,node in ipairs(g.forwardnodes) do local m = node.data.module if m then table.insert(omg, m) end end return omg end function net_utils.listModules(net) local t = torch.type(net) local moduleList if t == 'nn.gModule' then moduleList = net_utils.list_nngraph_modules(net) else moduleList = net:listModules() end return moduleList end function net_utils.sanitize_gradients(net) local moduleList = net_utils.listModules(net) for k,m in ipairs(moduleList) do if m.weight and m.gradWeight then m.gradWeight = nil end if m.bias and m.gradBias then m.gradBias = nil end end end function net_utils.unsanitize_gradients(net) local moduleList = net_utils.listModules(net) for k,m in ipairs(moduleList) do if m.weight and (not m.gradWeight) then m.gradWeight = m.weight:clone():zero() end if m.bias and (not m.gradBias) then m.gradBias = m.bias:clone():zero() end end end function net_utils.decode_sequence(ix_to_word, seq) local D,N = seq:size(1), seq:size(2) local out = {} for i=1,N do local txt = '' for j=1,D do local ix = seq[{j,i}] local word = ix_to_word[tostring(ix)] if not word then break end -- END token, likely. Or null token if word ~= '' then if j >= 2 then txt = txt .. ' ' end txt = txt .. word end end table.insert(out, txt) end return out end function net_utils.clone_list(lst) -- takes list of tensors, clone all local new = {} for k,v in pairs(lst) do new[k] = v:clone() end return new end return net_utils
local on_attach = require('lsp.on_attach') local capabilities = require('cmp_nvim_lsp').update_capabilities( vim.lsp.protocol.make_client_capabilities() ) capabilities.textDocument.completion.completionItem.snippetSupport = true return { on_attach = function(client) client.resolved_capabilities.document_formatting = false on_attach(client) end, capabilities = capabilities, filetypes = { 'css', 'scss' }, }
xivopeners_dnc = {} xivopeners_dnc.debug = false xivopeners_dnc.supportedLevel = 60 xivopeners_dnc.openerAbilities = { StandardStep = ActionList:Get(1, 15997), StandardFinish = ActionList:Get(1, 16192), StandardDance = {name = "Standard Dance", id = 0, cd = 0, cdmax = 0, range = 0}; Emboite = ActionList:Get(1, 15999), Entrechat = ActionList:Get(1, 16000), Jete = ActionList:Get(1, 16001), Pirouette = ActionList:Get(1, 16002), TechnicalStep = ActionList:Get(1, 15998), TechnicalFinish = ActionList:Get(1, 16196), TechnicalDance = {name = "Technical Dance", id = 0, cd = 0, cdmax = 0, range = 0}; Flourish = ActionList:Get(1, 16013), RisingWindmill = ActionList:Get(1, 15995), Devilment = ActionList:Get(1, 16011), StandardStepBuffID = 1818, StandardFinishBuffID = 1821, Tincture = {name = "Tincture", ids = {27996, 27787}, range = 0}, MedicineBuffID = 49, } xivopeners_dnc.openerInfo = { listOpeners = {"Preferred", "Early Devilment"}, } xivopeners_dnc.openers = { preferred = { xivopeners_dnc.openerAbilities.StandardStep, xivopeners_dnc.openerAbilities.StandardDance, xivopeners_dnc.openerAbilities.StandardDance, xivopeners_dnc.openerAbilities.StandardFinish, xivopeners_dnc.openerAbilities.TechnicalStep, xivopeners_dnc.openerAbilities.TechnicalDance, xivopeners_dnc.openerAbilities.TechnicalDance, xivopeners_dnc.openerAbilities.TechnicalDance, xivopeners_dnc.openerAbilities.TechnicalDance, xivopeners_dnc.openerAbilities.TechnicalFinish, xivopeners_dnc.openerAbilities.Flourish, xivopeners_dnc.openerAbilities.RisingWindmill, xivopeners_dnc.openerAbilities.Devilment, }, earlyDevilment = { xivopeners_dnc.openerAbilities.StandardStep, xivopeners_dnc.openerAbilities.StandardDance, xivopeners_dnc.openerAbilities.StandardDance, xivopeners_dnc.openerAbilities.StandardFinish, xivopeners_dnc.openerAbilities.Devilment, xivopeners_dnc.openerAbilities.TechnicalStep, xivopeners_dnc.openerAbilities.TechnicalDance, xivopeners_dnc.openerAbilities.TechnicalDance, xivopeners_dnc.openerAbilities.TechnicalDance, xivopeners_dnc.openerAbilities.TechnicalDance, xivopeners_dnc.openerAbilities.TechnicalFinish, xivopeners_dnc.openerAbilities.Flourish, xivopeners_dnc.openerAbilities.RisingWindmill, } } xivopeners_dnc.danceStepCombo = { -- gauge 3 is first one, gauge 4 is second one, gauge 7 tells the current index xivopeners_dnc.openerAbilities.Emboite, xivopeners_dnc.openerAbilities.Entrechat, xivopeners_dnc.openerAbilities.Jete, xivopeners_dnc.openerAbilities.Pirouette, } xivopeners_dnc.abilityQueue = {} xivopeners_dnc.lastCastFromQueue = nil -- might need this for some more complex openers with conditions xivopeners_dnc.openerStarted = false xivopeners_dnc.lastcastid = 0 xivopeners_dnc.lastcastid2 = 0 function xivopeners_dnc.getTincture() for i = 0, 3 do for _, id in pairs(xivopeners_dnc.openerAbilities.Tincture.ids) do local tincture = Inventory:Get(i):Get(id) if (tincture) then return tincture end end end return nil end function xivopeners_dnc.getOpener() if (xivopeners.settings[Player.job].currentOpenerIndex == 1) then return xivopeners_dnc.openers.preferred else return xivopeners_dnc.openers.earlyDevilment end end function xivopeners_dnc.checkOpenerIds() for key, action in pairs(xivopeners_dnc.getOpener()) do if (action == nil) then xivopeners.log("WARNING: Action at index " .. tostring(key) .. " was nil! The id is likely incorrect.") end end end function xivopeners_dnc.openerAvailable() -- check cooldowns for _, action in pairs(xivopeners_dnc.getOpener()) do if (action == xivopeners_dnc.openerAbilities.Tincture) then local tincture = xivopeners_dnc.getTincture() if (tincture and xivopeners.settings[Player.job].useTincture and tincture:GetAction().cd >= 1.5 and not HasBuff(Player.id, xivopeners_dnc.openerAbilities.MedicineBuffID)) then return false end elseif (action == xivopeners_dnc.openerAbilities.StandardStep) then if (action.cd >= 1.5 and not HasBuff(Player.id, xivopeners_dnc.openerAbilities.StandardStepBuffID)) then return false end elseif (action.cd >= 1.5) then return false end end return true end function xivopeners_dnc.queueOpener() -- the only time this gets called is when the main script is toggled, so we can do more than just queue the opener -- empty queue first xivopeners_dnc.abilityQueue = {} for _, action in pairs(xivopeners_dnc.getOpener()) do xivopeners_dnc.enqueue(action) end -- xivopeners.log("queue:") -- for _, v in pairs(xivopeners_dnc.abilityQueue) do -- xivopeners.log(v.name) -- end xivopeners_dnc.lastCastFromQueue = nil xivopeners_dnc.openerStarted = false if (xivopeners.settings[Player.job].useTincture and not xivopeners_dnc.getTincture()) then xivopeners.settings[Player.job].useTincture = false end end function xivopeners_dnc.updateLastCast() -- xivopeners.log(tostring(xivopeners_dnc.lastcastid) .. ", " .. tostring(xivopeners_dnc.lastcastid2) .. ", " .. tostring(Player.castinginfo.lastcastid)) if (xivopeners_dnc.lastCastFromQueue) then if (xivopeners_dnc.lastcastid == -1) then -- compare the real castid and see if it changed, if it did, update from -1 if (xivopeners_dnc.lastcastid2 ~= Player.castinginfo.castingid) then xivopeners.log("cast changed") xivopeners_dnc.lastcastid = Player.castinginfo.castingid xivopeners_dnc.lastcastid2 = Player.castinginfo.castingid end elseif (xivopeners_dnc.lastcastid ~= Player.castinginfo.castingid) then xivopeners_dnc.lastcastid = Player.castinginfo.castingid xivopeners_dnc.lastcastid2 = Player.castinginfo.castingid end end end function xivopeners_dnc.drawCall(event, tickcount) GUI:AlignFirstTextHeightToWidgets() GUI:BeginGroup() GUI:Text("Use Tincture") GUI:NextColumn() xivopeners.settings[Player.job].useTincture = GUI:Checkbox("##xivopeners_dnc_tincturecheck", xivopeners.settings[Player.job].useTincture) GUI:EndGroup() GUI:NextColumn() if (xivopeners_dnc.debug) then GUI:AlignFirstTextHeightToWidgets() GUI:Text("lastcastid") GUI:NextColumn() GUI:InputText("##xivopeners_dnc_lastcastid_display", tostring(xivopeners_dnc.lastcastid)) GUI:NextColumn() GUI:AlignFirstTextHeightToWidgets() GUI:Text("lastcastid2") GUI:NextColumn() GUI:InputText("##xivopeners_dnc_lastcastid2_display", tostring(xivopeners_dnc.lastcastid2)) GUI:NextColumn() GUI:AlignFirstTextHeightToWidgets() GUI:Text("lastcastid_o") GUI:NextColumn() GUI:InputText("##xivopeners_dnc_lastcastid_original_display", tostring(Player.castinginfo.lastcastid)) GUI:NextColumn() GUI:AlignFirstTextHeightToWidgets() GUI:Text("castingid") GUI:NextColumn() GUI:InputText("##xivopeners_dnc_castingid", tostring(Player.castinginfo.castingid)) GUI:NextColumn() if (xivopeners_dnc.abilityQueue[1]) then GUI:AlignFirstTextHeightToWidgets() GUI:Text("queue[1]") GUI:NextColumn() GUI:InputText("##xivopeners_dnc_queue[1]", xivopeners_dnc.abilityQueue[1].name) GUI:NextColumn() end if (xivopeners_dnc.lastCastFromQueue) then GUI:AlignFirstTextHeightToWidgets() GUI:Text("lastCastFromQueue") GUI:NextColumn() GUI:InputText("##xivopeners_dnc_lastcastfromqueue", xivopeners_dnc.lastCastFromQueue.name) GUI:NextColumn() end end end function xivopeners_dnc.main(event, tickcount) if (Player.level >= xivopeners_dnc.supportedLevel) then local target = Player:GetTarget() if (not target or not target.attackable) then return end if (not xivopeners_dnc.openerAvailable() and not xivopeners_dnc.openerStarted) then return end -- don't start opener if it's not available, if it's already started then yolo if (xivopeners_dnc.openerStarted and next(xivopeners_dnc.abilityQueue) == nil) then -- opener is finished, pass control to ACR xivopeners.log("Finished openers, handing control to ACR") xivopeners_dnc.openerStarted = false if (xivopeners.running) then xivopeners.ToggleRun() end if (not FFXIV_Common_BotRunning) then ml_global_information.ToggleRun() end return end xivopeners_dnc.updateLastCast() if (not xivopeners_dnc.openerStarted) then -- technically, even if you use an ability from prepull, it should still work, since the next time this loop runs it'll jump to the elseif xivopeners.log("Starting opener") xivopeners_dnc.openerStarted = true xivopeners_dnc.useNextAction(target) -- rewrite this to be for dnc procs -- elseif (xivopeners_dnc.abilityQueue[1] == xivopeners_dnc.openerAbilities.RefulgentArrow and xivopeners_dnc.abilityQueue[2] == xivopeners_dnc.openerAbilities.Barrage and (xivopeners_dnc.abilityQueue[1].cdmax - xivopeners_dnc.abilityQueue[1].cd < 1.5) and not HasBuff(Player.id, xivopeners_dnc.openerAbilities.StraightShotReadyBuffID)) then -- xivopeners.log("Didn't get RA proc before Barrage, dequeuing") -- -- need to insert burst shot back in between Sidewinder and BL -- -- i could just do table.insert(queue, 5, burstshot) and it would be faster than looping through, but looping would be more reliable and flexible to opener changes in the future -- for k, v in ipairs(xivopeners_dnc.abilityQueue) do -- if (v == xivopeners_dnc.openerAbilities.Sidewinder) then -- xivopeners.log("Added BurstShot back") -- table.insert(xivopeners_dnc.abilityQueue, k + 1, xivopeners_dnc.openerAbilities.BurstShot) -- break -- end -- end -- xivopeners_dnc.dequeue() -- xivopeners_dnc.useNextAction(target) elseif (xivopeners_dnc.lastCastFromQueue and xivopeners_dnc.lastcastid == xivopeners_dnc.lastCastFromQueue.id) then xivopeners_dnc.lastcastid = -1 xivopeners_dnc.dequeue() xivopeners_dnc.useNextAction(target) else xivopeners_dnc.useNextAction(target) end end end function xivopeners_dnc.enqueueNext(action) table.insert(xivopeners_dnc.abilityQueue, 1, action) end function xivopeners_dnc.enqueue(action) -- implementation of the queue can be changed later table.insert(xivopeners_dnc.abilityQueue, action) end function xivopeners_dnc.dequeue() xivopeners.log("Dequeing " .. xivopeners_dnc.abilityQueue[1].name) table.remove(xivopeners_dnc.abilityQueue, 1) end function xivopeners_dnc.getNextStdStep() -- gauge 3 is first one, gauge 4 is second one, gauge 7 tells the current index local stepIndexes = { Player.gauge[3], Player.gauge[4], } return xivopeners_dnc.danceStepCombo[stepIndexes[Player.gauge[7] + 1]] end function xivopeners_dnc.getNextTechStep() -- gauge 3 is first one, gauge 4 is second one, gauge 7 tells the current index local stepIndexes = { Player.gauge[3], Player.gauge[4], Player.gauge[5], Player.gauge[6], } return xivopeners_dnc.danceStepCombo[stepIndexes[Player.gauge[7] + 1]] end function xivopeners_dnc.useNextAction(target) -- do the actual opener -- the current implementation uses a queue system if (target and target.attackable and xivopeners_dnc.abilityQueue[1] and (xivopeners_dnc.abilityQueue[1].range <= 0 or target.distance2d <= xivopeners_dnc.abilityQueue[1].range)) then -- tincture check if (xivopeners_dnc.abilityQueue[1] == xivopeners_dnc.openerAbilities.Tincture) then local tincture = xivopeners_dnc.getTincture() if (HasBuff(Player.id, xivopeners_dnc.openerAbilities.MedicineBuffID) or not xivopeners.settings[Player.job].useTincture or not tincture) then xivopeners.log("Tincture already used during opener, not enabled, or not available, dequeueing") xivopeners_dnc.dequeue() return end if (tincture) then xivopeners.log("Casting tincture") tincture:Cast() xivopeners_dnc.lastCastFromQueue = tincture:GetAction() end -- don't want to continue past this point or we risk breaking shit return end -- check if we're already in std step if (xivopeners_dnc.abilityQueue[1] == xivopeners_dnc.openerAbilities.StandardStep and HasBuff(Player.id, xivopeners_dnc.openerAbilities.StandardStepBuffID)) then xivopeners.log("Player already used standard step prepull, continue with opener") xivopeners_dnc.dequeue() return end -- handle std steps if (xivopeners_dnc.abilityQueue[1] == xivopeners_dnc.openerAbilities.StandardDance) then -- dequeue all steps if we've already done if (Player.gauge[7] == 2) then xivopeners_dnc.dequeue() return end local nextDanceStep = xivopeners_dnc.getNextStdStep() if (nextDanceStep) then nextDanceStep:Cast(target.id) xivopeners_dnc.lastCastFromQueue = nextDanceStep end return end -- handle tech steps if (xivopeners_dnc.abilityQueue[1] == xivopeners_dnc.openerAbilities.TechnicalDance) then -- dequeue all steps if we've already done if (Player.gauge[7] == 4) then xivopeners_dnc.dequeue() return end local nextDanceStep = xivopeners_dnc.getNextTechStep() if (nextDanceStep) then nextDanceStep:Cast(target.id) xivopeners_dnc.lastCastFromQueue = nextDanceStep end return end -- idk how to make it not spam console -- xivopeners.log("Casting " .. xivopeners_dnc.abilityQueue[1].name) xivopeners_dnc.abilityQueue[1]:Cast(target.id) xivopeners_dnc.lastCastFromQueue = xivopeners_dnc.abilityQueue[1] end end
term1 = math.random(890) + 100; term2 = math.random(9) + 1; result = math.floor(term1/term2); rest = term1 - result * term2 term1 = term1 - rest
local draw = {} local string, game, setmetatable, math, objmanager, myHero, print, tostring, type, enum= string, game, setmetatable, math, objmanager, objmanager.player, print, tostring, type, enum function draw.GetDistanceSqr(p1,p2) if(not p1 or not p2)then return math.huge end local xSqr = (p1.x - p2.x) * (p1.x - p2.x) local ySqr = (p1.y - p2.y) * (p1.y - p2.y) local zSqr = (p1.z - p2.z) * (p1.z - p2.z) return xSqr + ySqr + zSqr end function draw.GetDistance(p1,p2) return math.sqrt(draw.GetDistanceSqr(p1,p2)) end function draw.vec2IsOnScreen(pos) if pos.x > glx.screenX then return false end if pos.y > glx.screenY then return false end if(pos.x < 0 or pos.y < 0)then return false end return true end function draw.vec3IsOnScreen(pos) return draw.vec2IsOnScreen(glx.world.toscreen(pos)) end function draw.text(str, size, x, y, c, h, v) local color, dx, dy = c or draw.color.white, glx.textArea(str, size) if h then if h == "center" then x = x - (dx / 2) elseif h == "right" then x = x - dx end if v and v ~= "middle" then if v == "top" then y = y + (dy / 2) elseif v == "bottom" then y = y - (dy / 2) end end end glx.screen.drawText(str, size, x, y, color) end draw.color = { alice_blue = glx.argb(255,240,248,255), antique_white = glx.argb(255,250,235,215), aqua = glx.argb(255,0,255,255), aqua_marine = glx.argb(255,127,255,212), azure = glx.argb(255,240,255,255), beige = glx.argb(255,245,245,220), bisque = glx.argb(255,255,228,196), black = glx.argb(255,0,0,0), blanched_almond = glx.argb(255,255,235,205), blue = glx.argb(255,0,0,255), blue_violet = glx.argb(255,138,43,226), brown = glx.argb(255,165,42,42), burly_wood = glx.argb(255,222,184,135), cadet_blue = glx.argb(255,95,158,160), chart_reuse = glx.argb(255,127,255,0), chocolate = glx.argb(255,210,105,30), coral = glx.argb(255,255,127,80), corn_flower_blue = glx.argb(255,100,149,237), corn_silk = glx.argb(255,255,248,220), crimson = glx.argb(255,220,20,60), cyan = glx.argb(255,0,255,255), dark_blue = glx.argb(255,0,0,139), dark_cyan = glx.argb(255,0,139,139), dark_golden_rod = glx.argb(255,184,134,11), dark_gray = glx.argb(255,169,169,169), dark_green = glx.argb(255,0,100,0), dark_khaki = glx.argb(255,189,183,107), dark_magenta = glx.argb(255,139,0,139), dark_olive_green = glx.argb(255,85,107,47), dark_orange = glx.argb(255,255,140,0), dark_orchid = glx.argb(255,153,50,204), dark_red = glx.argb(255,139,0,0), dark_salmon = glx.argb(255,233,150,122), dark_sea_green = glx.argb(255,143,188,143), dark_slate_blue = glx.argb(255,72,61,139), dark_slate_gray = glx.argb(255,47,79,79), dark_turquoise = glx.argb(255,0,206,209), dark_violet = glx.argb(255,148,0,211), deep_pink = glx.argb(255,255,20,147), deep_sky_blue = glx.argb(255,0,191,255), dim_gray = glx.argb(255,105,105,105), dodger_blue = glx.argb(255,30,144,255), firebrick = glx.argb(255,178,34,34), floral_white = glx.argb(255,255,250,240), forest_green = glx.argb(255,34,139,34), gainsboro = glx.argb(255,220,220,220), ghost_white = glx.argb(255,248,248,255), gold = glx.argb(255,255,215,0), golden_rod = glx.argb(255,218,165,32), gray = glx.argb(255,128,128,128), green = glx.argb(255,0,128,0), green_yellow = glx.argb(255,173,255,47), honeydew = glx.argb(255,240,255,240), hot_pink = glx.argb(255,255,105,180), indian_red = glx.argb(255,205,92,92), indigo = glx.argb(255,75,0,130), ivory = glx.argb(255,255,255,240), khaki = glx.argb(255,240,230,140), lavender = glx.argb(255,230,230,250), lavender_blush = glx.argb(255,255,240,245), lawn_green = glx.argb(255,124,252,0), lemon_chiffon = glx.argb(255,255,250,205), light_blue = glx.argb(255,173,216,230), light_coral = glx.argb(255,240,128,128), light_cyan = glx.argb(255,224,255,255), light_golden_rod_yellow = glx.argb(255,250,250,210), light_gray = glx.argb(255,211,211,211), light_green = glx.argb(255,144,238,144), light_pink = glx.argb(255,255,182,193), light_salmon = glx.argb(255,255,160,122), light_sea_green = glx.argb(255,32,178,170), light_sky_blue = glx.argb(255,135,206,250), light_slate_gray = glx.argb(255,119,136,153), light_steel_blue = glx.argb(255,176,196,222), light_yellow = glx.argb(255,255,255,224), lime = glx.argb(255,0,255,0), lime_green = glx.argb(255,50,205,50), linen = glx.argb(255,250,240,230), magenta = glx.argb(255,255,0,255), maroon = glx.argb(255,128,0,0), medium_aqua_marine = glx.argb(255,102,205,170), medium_blue = glx.argb(255,0,0,205), medium_orchid = glx.argb(255,186,85,211), medium_purple = glx.argb(255,147,112,219), medium_sea_green = glx.argb(255,60,179,113), medium_slate_blue = glx.argb(255,123,104,238), medium_spring_green = glx.argb(255,0,250,154), medium_turquoise = glx.argb(255,72,209,204), medium_violet_red = glx.argb(255,199,21,133), midnight_blue = glx.argb(255,25,25,112), mint_cream = glx.argb(255,245,255,250), misty_rose = glx.argb(255,255,228,225), moccasin = glx.argb(255,255,228,181), navajo_white = glx.argb(255,255,222,173), navy = glx.argb(255,0,0,128), old_lace = glx.argb(255,253,245,230), olive = glx.argb(255,128,128,0), olive_drab = glx.argb(255,107,142,35), orange = glx.argb(255,255,165,0), orange_red = glx.argb(255,255,69,0), orchid = glx.argb(255,218,112,214), pale_golden_rod = glx.argb(255,238,232,170), pale_green = glx.argb(255,152,251,152), pale_turquoise = glx.argb(255,175,238,238), pale_violet_red = glx.argb(255,219,112,147), papaya_whip = glx.argb(255,255,239,213), peach_puff = glx.argb(255,255,218,185), peru = glx.argb(255,205,133,63), pink = glx.argb(255,255,192,203), plum = glx.argb(255,221,160,221), powder_blue = glx.argb(255,176,224,230), purple = glx.argb(255,128,0,128), red = glx.argb(255,255,0,0), rosy_brown = glx.argb(255,188,143,143), royal_blue = glx.argb(255,65,105,225), saddle_brown = glx.argb(255,139,69,19), salmon = glx.argb(255,250,128,114), sandy_brown = glx.argb(255,244,164,96), sea_green = glx.argb(255,46,139,87), sea_shell = glx.argb(255,255,245,238), sienna = glx.argb(255,160,82,45), silver = glx.argb(255,192,192,192), sky_blue = glx.argb(255,135,206,235), slate_blue = glx.argb(255,106,90,205), slate_gray = glx.argb(255,112,128,144), snow = glx.argb(255,255,250,250), spring_green = glx.argb(255,0,255,127), steel_blue = glx.argb(255,70,130,180), tan = glx.argb(255,210,180,140), teal = glx.argb(255,0,128,128), thistle = glx.argb(255,216,191,216), tomato = glx.argb(255,255,99,71), turquoise = glx.argb(255,64,224,208), violet = glx.argb(255,238,130,238), wheat = glx.argb(255,245,222,179), white = glx.argb(255,255,255,255), white_smoke = glx.argb(255,245,245,245), yellow = glx.argb(255,255,255,0), yellow_green = glx.argb(255,154,205,50), } return draw
-- This file contains list of tests which you want to exclude -- Provide relative path from q_src_root along with the test-case file name --[[ local blacklist_files = { "TEST_RUNNER/test_test1.lua", "TEST_RUNNER/test_test2.lua", "TEST_RUNNER/test_run_func.lua", "TESTS/test_log_reg_1.lua", "TESTS/test_log_reg_2.lua", "ML/LOGISTIC_REGRESSION/test/test_simple.lua", -- below is not a test "UTILS/lua/test_init.lua", -- below is not a test "UTILS/lua/test_utils.lua", -- Mail subject : List of failure tests in dev branch -- Let’s move the others into the black list "OPERATORS/APPROX/FREQUENT/test/test_approx_frequent.lua", "ML/LOGISTIC_REGRESSION/test/test_mnist.lua", "ML/LOGISTIC_REGRESSION/test/test_logistic_regression.lua", "OPERATORS/PCA/test/test_pca.lua", "ML/LOGISTIC_REGRESSION/test/test_really_simple.lua", "OPERATORS/MM/test/test_mv_mul.lua", "OPERATORS/PCA/test/test_eigen.lua", "OPERATORS/APPROX/QUANTILE/test/test_aq.lua", -- below test file requires python tests(Q/ML/DT/python/Dtree_sklearn*.py) to be executed first "ML/DT/test/test_accuracy_results/test_import_sklearn_in_q.lua" } return blacklist_files --]] return {}
------------------------------------------------------------------- -- This script is created by zdroid9770; please do not edit this -- -- script and claim it as your own, as of All rights are claimed -- -- by me. -- -- Copyright (c) zdroid9770 -- ------------------------------------------------------------------- --[[ ----Quotes ----Spells-ID Fire Ward-15041 Flame Shock-15616 Molten Blast-15095 Scorching Totem-15038 ]]-- function PMLG_OnCombat(pUnit, event) pUnit:RegisterEvent("PMLG_SearingTotems", 5000, 0) pUnit:RegisterEvent("PMLG_FireWard", 25000, 0) pUnit:RegisterEvent("PMLG_MoltenBlast", 30000, 0) pUnit:RegisterEvent("PMLG_FlameShock", 50000, 0) end function PMLG_SearingTotems(pUnit, Event) pUnit:FullCastSpell(15038) end function PMLG_FireWard(pUnit, Event) pUnit:FullCastSpell(15041) end function PMLG_MoltenBlast(pUnit, Event) pUnit:FullCastSpellOnTarget(15095) end function PMLG_FlameShock(Unit, Event) pUnit:CastSpellOnTarget(15616) end function PMLG_OnLeaveCombat(pUnit, event) pUnit:RemoveEvents() end function PMLG_OnDeath(pUnit, event) pUnit:RemoveEvents() end RegisterUnitEvent(9024, 1, "PMLG_OnCombat") RegisterUnitEvent(9024, 2, "PMLG_OnLeaveCombat") RegisterUnitEvent(9024, 3, "PMLG_OnDeath")
local Point2 = _radiant.csg.Point2 local Point3 = _radiant.csg.Point3 local Cube3 = _radiant.csg.Cube3 local Region2 = _radiant.csg.Region2 local Region3 = _radiant.csg.Region3 local rng = _radiant.math.get_default_rng() local csg_lib = require 'stonehearth.lib.csg.csg_lib' local landmark_lib = require 'stonehearth.lib.landmark.landmark_lib' local render_lib = require 'tower_defense.lib.render.render_lib' local validator = radiant.validator local log = radiant.log.create_logger('world_generation') GameCreationService = class() function GameCreationService:new_game_command(session, response, num_tiles_x, num_tiles_y, seed, options, starting_data) --if no kingdom has been set for the player yet, set it to ascendancy if not stonehearth.player:get_kingdom(session.player_id) then stonehearth.player:add_kingdom(session.player_id, "stonehearth:kingdoms:ascendancy") end local pop = stonehearth.population:get_population(session.player_id) pop:set_game_options(options) tower_defense.game:set_game_options(options) stonehearth.world_generation:create_empty_world(options.biome_src) local result = { map_info = { biome_src = options.biome_src } } return result end function GameCreationService:generate_start_location_command(session, response, feature_cell_x, feature_cell_y, map_info) self:_generate_world(session, response, map_info) self:start_game(session) response:resolve({}) end function GameCreationService:_generate_world(session, response, map_info) if validator.is_host_player(session) then stonehearth.terrain._enable_full_vision = true -- generate the world! local biome = radiant.resources.load_json(map_info.biome_src) -- default if not specified is the burbenog map local map = radiant.resources.load_json(biome.tower_defense_generation_file or 'tower_defense:data:map_generation:desert') -- first generate the world terrain local block_types = radiant.terrain.get_block_types() local terrain = Region3() local world = map.world local size = world.size or 32 assert(size % 2 == 0) local half_size = size / 2 local height = 0 for _, layer in ipairs(world.layers) do terrain:add_cube(Cube3(Point3(0, height, 0), Point3(size, layer.height + height, size), block_types[layer.terrain])) height = height + layer.height end -- hacky edge shading fix (add a null terrain block super far below us) terrain:add_cube(Cube3(Point3(-1, -999999, -1), Point3(0, -999998, 0), block_types.null)) --move the region to be centered local center_point = Point3(-half_size, 0, -half_size) terrain = terrain:translated(center_point) radiant.terrain.get_terrain_component():add_tile(terrain) -- create primary terrain landmark if there is one if map.terrain_landmark then self:_create_landmark(map.terrain_landmark, center_point) end -- add landmarks to edges of map self:_create_landmarks(map.landmarks, size, Point3(0, height, 0)) -- if we're having the path cut into the terrain, subtract 1 from the height local top = center_point + Point3(0, height - (map.path.width and 1 or 0), 0) local air_top = Point3(0, map.air_path.height, 0) local sub_terrain = Region3() local first_point, last_point, path_region, path_entity, add_terrain = self:_create_path(map.path.points, top, false, map.path.width or 3, sub_terrain, map.path.block_type and block_types[map.path.block_type]) local air_first_point, air_last_point, air_path_region, air_path_entity = self:_create_path(map.air_path.points, top + air_top, true, map.path.width or 3, sub_terrain) -- apply path block type terrain radiant.terrain.add_region(add_terrain) -- subtract the path from the world terrain radiant.terrain.subtract_region(sub_terrain) -- place path entities with movement modifiers --path_entity:add_component('tower_defense:region_renderer'):set_options('path', {face_color = {128, 51, 0, 96}}) radiant.terrain.place_entity_at_exact_location(path_entity, first_point + top) --radiant.terrain.place_entity_at_exact_location(path_neighbor_entity, first_point + top) --air_path_entity:add_component('tower_defense:region_renderer'):set_options('path', {face_color = {224, 64, 224, 96}}) radiant.terrain.place_entity_at_exact_location(air_path_entity, air_first_point + top + air_top) -- finally, add any entities that should start out in the world local entities = map.entities local offset = center_point + Point3(0, height, 0) for uri, entity_list in pairs(entities) do for _, entity_data in ipairs(entity_list) do local entity = radiant.entities.create_entity(uri, { owner = '' }) radiant.terrain.place_entity_at_exact_location(entity, Point3(unpack(entity_data.location)) + offset, { force_iconic = false }) local facing = entity_data.facing or 0 if facing == 'random' then facing = rng:get_int(0, 3) * 90 end radiant.entities.turn_to(entity, facing) end end self:on_world_generation_complete() if map.tower_placeable_region then local reg = Region3() for _, cube in ipairs(map.tower_placeable_region) do reg:add_cube(Cube3(Point3(unpack(cube[1])), Point3(unpack(cube[2])))) end reg:translate(offset) reg:optimize('tower placeable region') map.tower_placeable_region = reg else map.tower_placeable_region = Region3(Cube3(Point3(-half_size, height, -half_size), Point3(half_size - 1, height + 1, half_size - 1))) end map.spawn_location = first_point + top map.air_spawn_location = air_first_point + top + air_top map.end_point = last_point + offset - Point3(0, 1, 0) map.air_end_point = air_last_point + air_top + offset - Point3(0, 1, 0) map.ground_path_region = path_region:translated(map.spawn_location) map.air_path_region = air_path_region:translated(map.air_spawn_location) tower_defense.game:set_map_data(map) end end function GameCreationService:_create_path(path_array, top, is_air, width, sub_terrain, path_block_type) local path_region = Region3() local trans_path_region local path_neighbor = Region3() local first_point local last_point local path_cubes = {} for i, point in ipairs(path_array) do local this_point = Point3(unpack(point)) if not first_point then first_point = this_point end if last_point then local cube -- if it's the final point, make sure it extends all the way (important for air path, otherwise they can't run the final segment) if i == #path_array then cube = csg_lib.create_cube(last_point + top, this_point + top) else cube = render_lib.shy_cube(last_point + top, this_point + top) end table.insert(path_cubes, cube) path_region:add_cube(cube) if width and width >= 0 and sub_terrain then local extruded_cube = cube:extruded('x', width, width):extruded('z', width, width) path_neighbor:add_cube(extruded_cube) extruded_cube = extruded_cube:extruded('y', 0, 4) -- TODO: maybe have this height be customizable sub_terrain:add_cube(extruded_cube) -- also remove any non-terrain entities in this area (plus 1 higher y) for _, entity in pairs(radiant.terrain.get_entities_in_cube(extruded_cube:extruded('y', 0, 1))) do if not entity:get_component('terrain') then local water_comp = entity:get_component('stonehearth:water') if water_comp then -- if it's water, just subtract the part that intersects the path water_comp:remove_from_region(sub_terrain) else radiant.entities.destroy_entity(entity) end end end end end last_point = this_point end path_neighbor:subtract_region(path_region) trans_path_region = path_region:translated(-(first_point + top)) -- create path entity with movement modifier local path_entity = radiant.entities.create_entity('tower_defense:path', { owner = '' }) local path_entity_region = path_entity:add_component('movement_modifier_shape') path_entity_region:set_region(_radiant.sim.alloc_region3()) path_entity_region:get_region():modify(function(mod_region) mod_region:copy_region(trans_path_region) mod_region:set_tag(0) mod_region:optimize_by_defragmentation('path movement modifier shape') end) -- local hues -- local hue_range -- if is_air then -- hues = {0, 60} -- else -- hues = {120, 300} -- end -- hue_range = hues[2] - hues[1] -- local cur_hue = hues[1] -- if #path_cubes == 1 then -- cur_hue = hue_range / 2 + cur_hue -- end -- local render_comp = path_entity:add_component('tower_defense:region_renderer') -- for i, cube in ipairs(path_cubes) do -- local color = render_lib.hsv_to_rgb(cur_hue, 0.75, 1) -- render_comp:add_render_region('path'..i, { -- ui_modes = { -- hud = true -- }, -- -- transformations = { -- -- { -- -- name = 'inflated', -- -- params = { -- -- x = 0, -- -- y = -0.49, -- -- z = 0 -- -- } -- -- } -- -- }, -- material = '/stonehearth/data/horde/materials/transparent_box.material.json', -- face_color = {color.x, color.y, color.z, 51}, -- region = Region3(cube:translated(-(first_point + top))) -- }) -- cur_hue = (hue_range / (#path_cubes - 1)) * i + hues[1] -- end -- local path_neighbor_entity = radiant.entities.create_entity('tower_defense:path_neighbor', { owner = '' }) -- local path_neighbor_entity_region = path_neighbor_entity:add_component('movement_modifier_shape') -- path_neighbor_entity_region:set_region(_radiant.sim.alloc_region3()) -- path_neighbor_entity_region:get_region():modify(function(mod_region) -- mod_region:copy_region(path_neighbor:translated(-(first_point + top))) -- mod_region:set_tag(0) -- mod_region:optimize_by_defragmentation('path movement modifier shape') -- end) local add_terrain = Region3() if is_air then -- if it's air, we need to specify a collision region directly under the path path_entity_region = path_entity:add_component('region_collision_shape') path_entity_region:set_region_collision_type(_radiant.om.RegionCollisionShape.PLATFORM) path_entity_region:set_region(_radiant.sim.alloc_region3()) path_entity_region:get_region():modify(function(mod_region) mod_region:copy_region(trans_path_region:inflated(Point3(0, -0.45, 0)):translated(Point3(0, -0.55, 0))) --mod_region:optimize_by_defragmentation('path region collision shape') end) elseif path_block_type then -- if it's ground, modify the terrain directly under the path so it's a different shade path_region = path_region:duplicate() path_region:set_tag(path_block_type) path_region:translate(Point3(0, -1, 0)) add_terrain:add_region(path_region) end return first_point, last_point, trans_path_region, path_entity, add_terrain end function GameCreationService:_create_landmarks(landmarks, world_size, center_point) if not landmarks or #landmarks < 1 then return end -- prefer to use landmarks that haven't already been used landmarks = radiant.shallow_copy(landmarks) local directions = { Point3( 1, 0, -1), Point3(-1, 0, -1), Point3( -1, 0, 1), Point3( 1, 0, 1) } local used = {} for i = 0, 3 do local landmark = table.remove(landmarks, rng:get_int(1, #landmarks)) table.insert(used, landmark) if #landmarks < 1 then landmarks = used used = {} end -- try to load the landmark at the appropriate location/rotation local json = radiant.resources.load_json(landmark) if json then local size = json.size or Point3(32, 0, 32) local direction = directions[i + 1] local translation = Point3(direction.x * math.floor((world_size - size.x) / 2), 0, direction.z * math.floor((world_size - size.z) / 2)) self:_create_landmark(json, center_point, translation, i * 90) end end end function GameCreationService:_create_landmark(landmark, location, translation, rotation) -- try to load the landmark at the appropriate location/rotation if type(landmark) == 'string' then landmark = radiant.resources.load_json(landmark) end if landmark then landmark_lib.create_landmark(location, { translation = (translation or Point3.zero) + (radiant.util.to_point3(landmark.offset) or Point3.zero), rotation = (rotation or 0) + (landmark.rotation or 0), landmark_block_types = landmark.landmark_block_types or 'stonehearth:landmark_blocks', brush = landmark.brush }) end end function GameCreationService:start_game(session) local player_id = session.player_id local pop = stonehearth.population:get_population(player_id) local game_options = pop:get_game_options() tower_defense.game:add_player(player_id) --stonehearth.world_generation:set_starting_location(Point2(0, 0)) -- as soon as the host clicks to start the game, start it up if validator.is_host_player(session) then stonehearth.calendar:start() stonehearth.hydrology:start() stonehearth.mining:start() if game_options.remote_connections_enabled then stonehearth.session_server:set_remote_connections_enabled(true) end -- Set max number of remote players if specified if game_options.max_players then stonehearth.session_server:set_max_players(game_options.max_players) end -- Set whether clients can control game speed if game_options.game_speed_anarchy_enabled then stonehearth.game_speed:set_anarchy_enabled(game_options.game_speed_anarchy_enabled) end -- switch to having the host manually tell the game to start --stonehearth.game_speed:set_game_speed(0, true) --tower_defense.game:start() end stonehearth.terrain:set_fow_enabled(player_id, false) pop:place_camp() end function GameCreationService:get_game_world_options_commands(session, response) response:resolve({ game_mode = self._sv.game_mode, biome = stonehearth.world_generation:get_biome_alias(), -- any other options, like more generous starting gold, etc. }) end return GameCreationService
--[[This is a lua script for use in conky. You will need to add the following to your .conkyrc before the TEXT section: lua_load $HOME/.config/conky/LUA/dorfs.lua (or wherever you put your luas) lua_draw_hook_pre conky_dorfs I am not even close to being a programmer. It couldn't have been done without the help of the wonderful guide on the #! forums. http://crunchbang.org/forums/viewtopic.php?id=17246 ]] require 'cairo' function conky_dorfs() if conky_window == nil then return end w=conky_window.width h=conky_window.height local cs = cairo_xlib_surface_create(conky_window.display, conky_window.drawable, conky_window.visual, w, h) cr = cairo_create(cs) local updates=tonumber(conky_parse('${updates}')) if w<h then sm=w else sm=h end if updates>1 then --update tick counter ---------------------Settings local number_of_dorfs=6 local tile_size=sm/10 ---number of pixels per "square", also size of dorfs ---------------------Calculations local GridX=math.floor(w/tile_size) local GridY=math.floor(h/tile_size) if updates==2 then GridPosX={} GridPosY={} dorf={} for i=1, number_of_dorfs do dorf[i]={} GridPosX[i]=GridX/2 GridPosY[i]=GridY/2 for j=1,4 do if j==4 then dorf[i][j]=1 -----Sets alpha else dorf[i][j]=math.random() end end end end ---------------------Draw Dorfs for i=1, number_of_dorfs do deltaX=math.random(-1,1) if deltaX<=-0.5 then deltaX=-1 else if deltaX>=0.5 then deltaX=1 else deltaX=0 end end deltaY=math.random(-1,1) if deltaY<=-0.5 then deltaY=-1 else if deltaY>=0.5 then deltaY=1 else deltaY=0 end end GridPosX[i]=GridPosX[i]+deltaX GridPosY[i]=GridPosY[i]+deltaY if GridPosX[i]>GridX then GridPosX[i]=GridX else if GridPosX[i]<0 then GridPosX[i]=0 end end if GridPosY[i]>GridY then GridPosY[i]=GridY else if GridPosY[i]<1 then GridPosY[i]=1 end end PosX=GridPosX[i]*tile_size PosY=GridPosY[i]*tile_size cairo_select_font_face(cr,"dwarffortressvan",CAIRO_FONT_SLANT_NORMAL,CAIRO_FONT_WEIGHT_NORMAL) cairo_set_font_size(cr,tile_size) cairo_set_source_rgba(cr,dorf[i][1],dorf[i][2],dorf[i][3],dorf[i][4]) cairo_move_to(cr,PosX,PosY) cairo_show_text(cr,'®') cairo_stroke(cr) end ---------------------Finishing up else cairo_select_font_face(cr,"dwarffortressvan",CAIRO_FONT_SLANT_NORMAL,CAIRO_FONT_WEIGHT_NORMAL) cairo_set_font_size(cr,18) cairo_set_source_rgba(cr,0,0,0,1) cairo_move_to(cr,0,h/2) cairo_show_text(cr,'Preparing for embark...') cairo_stroke(cr) end --update tick counter cairo_destroy(cr) cairo_surface_destroy(cs) cr=nil end-- end main function
local cartographer = require 'cartographer' local testMap = cartographer.load 'demos/rpg/rpg.lua' function love.update(dt) testMap:update(dt) end function love.draw() testMap:draw() love.graphics.print('FPS: ' .. love.timer.getFPS()) love.graphics.print('Memory usage: ' .. math.floor(collectgarbage 'count') .. 'kb', 0, 16) end
------------------------------ local p = {["a"]=1} ------------------------------ success compiling learn.lua ; source chunk: learn.lua ; x86 standard (32-bit, little endian, doubles) ; function [0] definition (level 1) 0 ; 0 upvalues, 0 params, is_vararg = 2, 2 stacks .function 0 0 2 2 .local "p" ; 0 .const "a" ; 0 .const 1 ; 1 [1] newtable 0 0 1 ; R0 := {} , array=0, hash=1 [2] settable 0 256 257 ; R0["a"] := 1 [3] return 0 1 ; return ; end of function 0 ; source chunk: luac.out ; x86 standard (32-bit, little endian, doubles) ; function [0] definition (level 1) 0 ; 0 upvalues, 0 params, is_vararg = 2, 2 stacks .function 0 0 2 2 .local "p" ; 0 .const "a" ; 0 .const 1 ; 1 [1] newtable 0 0 1 ; R0 := {} , array=0, hash=1 [2] settable 0 256 257 ; R0["a"] := 1 [3] return 0 1 ; return ; end of function 0 ------------------------------ success compiling learn.lua Pos Hex Data Description or Code ------------------------------------------------------------------------ 0000 ** source chunk: learn.lua ** global header start ** 0000 1B4C7561 header signature: "\27Lua" 0004 51 version (major:minor hex digits) 0005 00 format (0=official) 0006 01 endianness (1=little endian) 0007 04 size of int (bytes) 0008 08 size of size_t (bytes) 0009 04 size of Instruction (bytes) 000A 08 size of number (bytes) 000B 00 integral (1=integral) * number type: double * x86 standard (32-bit, little endian, doubles) ** global header end ** 000C ** function [0] definition (level 1) 0 ** start of function 0 ** 000C 0B00000000000000 string size (11) 0014 406C6561726E2E6C+ "@learn.l" 001C 756100 "ua\0" source name: @learn.lua 001F 00000000 line defined (0) 0023 00000000 last line defined (0) 0027 00 nups (0) 0028 00 numparams (0) 0029 02 is_vararg (2) 002A 02 maxstacksize (2) * code: 002B 03000000 sizecode (3) 002F 0A400000 [1] newtable 0 0 1 ; R0 := {} , array=0, hash=1 0033 09404080 [2] settable 0 256 257 ; R0["a"] := 1 0037 1E008000 [3] return 0 1 ; return * constants: 003B 02000000 sizek (2) 003F 04 const type 4 0040 0200000000000000 string size (2) 0048 6100 "a\0" const [0]: "a" 004A 03 const type 3 004B 000000000000F03F const [1]: (1) * functions: 0053 00000000 sizep (0) * lines: 0057 03000000 sizelineinfo (3) [pc] (line) 005B 01000000 [1] (1) 005F 01000000 [2] (1) 0063 01000000 [3] (1) * locals: 0067 01000000 sizelocvars (1) 006B 0200000000000000 string size (2) 0073 7000 "p\0" local [0]: p 0075 02000000 startpc (2) 0079 02000000 endpc (2) * upvalues: 007D 00000000 sizeupvalues (0) ** end of function 0 ** 0081 ** end of chunk ** Pos Hex Data Description or Code ------------------------------------------------------------------------ 0000 ** source chunk: luac.out ** global header start ** 0000 1B4C7561 header signature: "\27Lua" 0004 51 version (major:minor hex digits) 0005 00 format (0=official) 0006 01 endianness (1=little endian) 0007 04 size of int (bytes) 0008 08 size of size_t (bytes) 0009 04 size of Instruction (bytes) 000A 08 size of number (bytes) 000B 00 integral (1=integral) * number type: double * x86 standard (32-bit, little endian, doubles) ** global header end ** 000C ** function [0] definition (level 1) 0 ** start of function 0 ** 000C 0B00000000000000 string size (11) 0014 406C6561726E2E6C+ "@learn.l" 001C 756100 "ua\0" source name: @learn.lua 001F 00000000 line defined (0) 0023 00000000 last line defined (0) 0027 00 nups (0) 0028 00 numparams (0) 0029 02 is_vararg (2) 002A 02 maxstacksize (2) * code: 002B 03000000 sizecode (3) 002F 0A400000 [1] newtable 0 0 1 ; R0 := {} , array=0, hash=1 0033 09404080 [2] settable 0 256 257 ; R0["a"] := 1 0037 1E008000 [3] return 0 1 ; return * constants: 003B 02000000 sizek (2) 003F 04 const type 4 0040 0200000000000000 string size (2) 0048 6100 "a\0" const [0]: "a" 004A 03 const type 3 004B 000000000000F03F const [1]: (1) * functions: 0053 00000000 sizep (0) * lines: 0057 03000000 sizelineinfo (3) [pc] (line) 005B 01000000 [1] (1) 005F 01000000 [2] (1) 0063 01000000 [3] (1) * locals: 0067 01000000 sizelocvars (1) 006B 0200000000000000 string size (2) 0073 7000 "p\0" local [0]: p 0075 02000000 startpc (2) 0079 02000000 endpc (2) * upvalues: 007D 00000000 sizeupvalues (0) ** end of function 0 ** 0081 ** end of chunk **
require "import" import "android.app.*" import "android.os.*" import "android.widget.*" import "android.view.*" import "android.graphics.SweepGradient" import "com.androlua.LuaDrawable" import "android.graphics.RectF" import "android.graphics.DashPathEffect" import "android.graphics.Color" import "android.graphics.Path" import "android.graphics.BitmapFactory" import "com.android.qrcode.*" import "android.content.Intent" import "layout" activity.setTitle('logo二维码制作') activity.setTheme(android.R.style.Theme_Holo_Light) activity.setContentView(loadlayout(layout)) function ChooseFile(type,Callback) intent = Intent(Intent.ACTION_GET_CONTENT) intent.setType(type); intent.addCategory(Intent.CATEGORY_OPENABLE) activity.startActivityForResult(intent,1); function onActivityResult(requestCode,resultCode,data) if resultCode == Activity.RESULT_OK then local uri = data.getData() import "com.library.Module"--导入模块 Callback(Module.UriToFilePath(this,uri)) end end end a1_1,a1_2,v5="带图标","不带图标",true --状态 tittle={"说明","选择类型→",a1_1,a1_2} function onCreateOptionsMenu(menu) for k,v in ipairs(tittle) do if tittle[v] then local m=menu.addSubMenu(v) for k,v in ipairs(tittle[v]) do m.add(v) end else local m=menu.add(v) m.setShowAsActionFlags(1) end end end function onMenuItemSelected(id,tittle) if tostring(tittle) == a1_1 then v5=true logo.setVisibility(View.VISIBLE) elseif tostring(tittle) == a1_2 then logo.setVisibility(View.INVISIBLE) v5=false elseif tostring(tittle) == "说明" then AlertDialog.Builder(this) .setTitle("说明") .setMessage(" 图片尽量使用半透明图片\n 生成出来的时候记得自己试一下\n 有时候无法扫描!\n 字数尽量大于10个,否则有可能扫描不出来\n\n感谢使用") .setPositiveButton("朕知道了",{onClick=function(v) end}) .show() end end logoxz.onClick=function() ChooseFile("image/*",function(path)--所有类型文件 path1=path:match("/([^/]+)$") logoml.text=path1 logotb.setImageBitmap(loadbitmap(path)) v3=path end) end but.onClick=function() local v1 = edit.Text if v1~="" then local v3=v3 local v2=1000 local v4=0xff00a2ff activity.newActivity("main1",{v1,v2,v3,v4,v5}) else print("请输入二维码内容") end --[[ Bit = BitmapFactory.decodeFile("/storage/emulated/0/AndroLua/project/GTpor多功能/icon.png") local t = edit.Text if t ~= "" then i = 二维码类.带图标二维码(t,400,Bit,0xff00a2ff) activity.newActivity("main1",{i}) --img.setImageBitmap(i) else print("请输入二维码内容") end]] end
--天気予報 --Script by Chrono-Genex function c101108063.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCountLimit(1,101108063+EFFECT_COUNT_CODE_OATH) e1:SetOperation(c101108063.activate) c:RegisterEffect(e1) --extra material local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_EXTRA_LINK_MATERIAL) e2:SetRange(LOCATION_FZONE) e2:SetTargetRange(LOCATION_SZONE,0) e2:SetCountLimit(1,101108063+100) e2:SetTarget(c101108063.mattg) e2:SetValue(c101108063.matval) c:RegisterEffect(e2) --summon local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(101108063,0)) e3:SetCategory(CATEGORY_SUMMON) e3:SetType(EFFECT_TYPE_IGNITION) e3:SetRange(LOCATION_FZONE) e3:SetCountLimit(1,101108063+200) e3:SetTarget(c101108063.sumtg) e3:SetOperation(c101108063.sumop) c:RegisterEffect(e3) if not aux.link_mat_hack_check then aux.link_mat_hack_check=true _IsCanBeLinkMaterial=Card.IsCanBeLinkMaterial function Card.IsCanBeLinkMaterial(c,lc) if c:GetOriginalType()&TYPE_MONSTER~=0 then return _IsCanBeLinkMaterial(c,lc) end if c:IsForbidden() then return false end local le={c:IsHasEffect(EFFECT_CANNOT_BE_LINK_MATERIAL)} for _,te in pairs(le) do local tf=te:GetValue() local tval=tf(te,lc) if tval then return false end end return true end end end function c101108063.tffilter(c,tp) return c:IsType(TYPE_SPELL+TYPE_TRAP) and not c:IsType(TYPE_FIELD) and c:IsSetCard(0x109) and not c:IsForbidden() and c:CheckUniqueOnField(tp) end function c101108063.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(c101108063.tffilter,tp,LOCATION_DECK,0,nil,tp) if g:GetCount()>0 and Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.SelectYesNo(tp,aux.Stringid(101108063,1)) then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOFIELD) local sg=g:Select(tp,1,1,nil) Duel.MoveToField(sg:GetFirst(),tp,tp,LOCATION_SZONE,POS_FACEUP,true) end end function c101108063.mattg(e,c) return c:IsSetCard(0x109) and c:GetSequence()<5 end function c101108063.matval(e,lc,mg,c,tp) if not (lc:IsSetCard(0x109) and e:GetHandlerPlayer()==tp) then return false,nil end return true,true end function c101108063.sumfilter(c) return c:IsSetCard(0x109) and c:IsSummonable(true,nil) end function c101108063.sumtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c101108063.sumfilter,tp,LOCATION_HAND,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_SUMMON,nil,1,0,0) end function c101108063.sumop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SUMMON) local g=Duel.SelectMatchingCard(tp,c101108063.sumfilter,tp,LOCATION_HAND,0,1,1,nil) local tc=g:GetFirst() if tc then Duel.Summon(tp,tc,true,nil) end end
local plugin_loader = {} function plugin_loader.init(plugins) local fn = vim.fn local install_path = DATA .. "/site/pack/packer/start/packer.nvim" if fn.empty(fn.glob(install_path)) > 0 then packer_bootstrap = fn.system({ "git", "clone", "--depth", "1", "https://github.com/wbthomason/packer.nvim", install_path, }) end require("packer").startup(function(use) for _, plugin in ipairs(plugins) do use(plugin) end if packer_bootstrap then require("packer").sync() end end) end return plugin_loader
local BONES = { --[[Pelvis]][11816] = true, --[[SKEL_L_Thigh]][58271] = true, --[[SKEL_L_Calf]][63931] = true, --[[SKEL_L_Foot]][14201] = true, --[[SKEL_L_Toe0]][2108] = true, --[[IK_L_Foot]][65245] = true, --[[PH_L_Foot]][57717] = true, --[[MH_L_Knee]][46078] = true, --[[SKEL_R_Thigh]][51826] = true, --[[SKEL_R_Calf]][36864] = true, --[[SKEL_R_Foot]][52301] = true, --[[SKEL_R_Toe0]][20781] = true, --[[IK_R_Foot]][35502] = true, --[[PH_R_Foot]][24806] = true, --[[MH_R_Knee]][16335] = true, --[[RB_L_ThighRoll]][23639] = true, --[[RB_R_ThighRoll]][6442] = true, } Citizen.CreateThread(function() while true do Citizen.Wait(0) local ped = GetPlayerPed(-1) --if IsShockingEventInSphere(102, 235.497,2894.511,43.339,999999.0) then if HasEntityBeenDamagedByAnyPed(ped) then --if GetPedLastDamageBone(ped) = Disarm(ped) end ClearEntityLastDamageEntity(ped) end end) function Bool (num) return num == 1 or num == true end -- WEAPON DROP OFFSETS local function GetDisarmOffsetsForPed (ped) local v if IsPedWalking(ped) then v = { 0.6, 4.7, -0.1 } elseif IsPedSprinting(ped) then v = { 0.6, 5.7, -0.1 } elseif IsPedRunning(ped) then v = { 0.6, 4.7, -0.1 } else v = { 0.4, 4.7, -0.1 } end return v end function Disarm (ped) if IsEntityDead(ped) then return false end local boneCoords local hit, bone = GetPedLastDamageBone(ped) hit = Bool(hit) if hit then if BONES[bone] then boneCoords = GetWorldPositionOfEntityBone(ped, GetPedBoneIndex(ped, bone)) SetPedToRagdoll(GetPlayerPed(-1), 5000, 5000, 0, 0, 0, 0) return true end end return false end
local resource_suggesttips={ {key="小贴士.1",value="每个角色同时只能装备一种内功。",}, {key="小贴士.2",value="战斗中路过敌人身边时是会受到阻碍的,天赋“轻功大师”可以忽略该项阻碍。",}, {key="小贴士.3",value="天赋“猎人”可以使得角色对动物类敌人攻击加成。",}, {key="小贴士.4",value="段誉的六脉神剑时灵时不灵,但偶尔可以造成非常恐怖的伤害。",}, {key="小贴士.5",value="受到“内伤”的角色每回合将损失内力,且使用技能时将消耗更高的内力。",}, {key="小贴士.6",value="带“缓速”的武功有一定概率将对方打得行动缓慢。",}, {key="小贴士.7",value="兵刃的熟练度对武器的攻击评估影响极大。",}, {key="小贴士.8",value="内功对外功适性相同的话,能够发挥武学最大优势,调和型的技能对内功适性无依赖。",}, {key="小贴士.9",value="根骨对内功评估影响最大。",}, {key="小贴士.10",value="拳掌系外功一般是点攻击,而剑系武学一般是直线型攻击。",}, {key="小贴士.11",value="很多武功(尤其是高等武功)自带有威力较大的《专属绝技》,需要修炼武功到一定等级之后才会出现。施展绝技一般需要消耗怒气点数。",}, {key="小贴士.12",value="在攻击、防御时均有概率积攒怒气,另外带“集气”的技能对怒气积攒也有帮助。",}, {key="小贴士.13",value="脾气暴躁有时是好事,也有时是坏事。天赋“暴躁”使得角色更容易受到致命一击,也更容易在战斗获得怒气。",}, {key="小贴士.14",value="一些任性的大小姐会给团队整体带来减益,但是她自己却会增强。降低所有队友能力,提高自己能力,俗称坑队友。坑得越多,自己越强。",}, {key="小贴士.15",value="天赋“普照”可以使得每回合自己及周围队友获得一个恢复BUFF。",}, {key="小贴士.16",value="对于修研毒功的角色,如果能够获得“毒系精通”或“毒圣”的天赋,将事半功倍。",}, {key="小贴士.17",value="自宫将导致所有情况下内力消耗翻倍,所以内力不强劲还是不要自宫的好……",}, {key="小贴士.18",value="致命一击概率和内外功适性匹配度、福缘、定力、所属武器技能熟练度,以及内功加成相关。",}, {key="小贴士.19",value="游戏中存在时间的概念,从一个地点移动到另一个地点需要消耗与距离相关的时间。经常做江南到漠北的长途旅行,时间会走得很快!",}, {key="小贴士.20",value="装上武功秘籍将使武功升级速度加快,但是从武功秘籍上学习武功往往不能达到顶级,需要通过各种机缘来解锁武功等级限制。",}, {key="小贴士.21",value="外功存在阴阳适性(也有阴阳调和的高级外功),每种内功对阴阳性的外功存在不同程度的威力加成/削弱。",}, {key="小贴士.22",value="每个角色最多学习10种外功和5种内功。",}, {key="小贴士.23",value="野球拳等少数武功具有极其罕见的DEBUFF“晕眩”,命中与定力有关。体会把敌人晕倒天荒地老的快感吧!",}, {key="小贴士.24",value="玉女素心剑等少数武功具有极其罕见的BUFF“左右互搏”,一定概率每回合可出招两次!",}, {key="小贴士.25",value="有一些神奇的武功,具有BUFF“神速攻击”,一定概率每回合可出招1~3次!",}, {key="小贴士.26",value="游戏中大部分剧情相关事件都只能在某些特定的时间段触发,过期不候了!",}, {key="小贴士.27",value="很多内功在达到一定等级时,将会附带有天赋效果。装备该内功即可获得相关天赋。",}, {key="小贴士.28",value="一些神秘物品也附带天赋,装备该物品即可获得相关天赋。",}, {key="小贴士.30",value="战斗时间到了以后则算战斗失败。",}, {key="小贴士.34",value="学会一些武学组合可能能够达到施展奥义绝学的效果。",}, {key="小贴士.35",value="喝醉酒可能会误事,也可能会对攻击造成很大的提升。",}, {key="小贴士.36",value="韦小宝的火枪可以对敌人造成真实伤害,但是需要一个回合来装填子弹。",}, {key="小贴士.37",value="一些女孩的歌声可以造成覆盖整个战场的帮助。",}, {key="小贴士.38",value="天关模式的战斗下,需要规划好每一场出战的队友,因为每个人只能出场一次!",}, {key="小贴士.39",value="大部分角色在战斗中都只能对自己使用物品,但是也有例外,如韦小宝和黄蓉。",}, {key="小贴士.40",value="段王爷英俊的面庞不单是女性有极大杀伤力,连太监也被他深深吸引……",}, {key="小贴士.41",value="传说血刀门的武功可以在攻击时吸取对方的体力。",}, {key="小贴士.42",value="做一个无门无派的百姓,总有一天你会逆袭!",}, {key="小贴士.43",value="走迷宫时请多注意各个场景的提示!",}, {key="小贴士.44",value="中毒的角色是不会死亡的,最多掉到剩1HP。",}, {key="小贴士.45",value="温馨提示:武功的上限不是10级哟,用心的话,你会找到一些解锁升级的方法。",}, {key="小贴士.46",value="战斗中不妨思考一下,如何利用位移技能来调整敌我阵型以达到最大化攻击的效果。",}, {key="小贴士.48",value="除简单难度以外,AOE技能是会对友军造成伤害的,但奥义绝学不会。",}, {key="小贴士.49",value="在WEB浏览器中,你可以使用CTRL+滚轮来缩放整个游戏画面的大小。",}, {key="小贴士.50",value="称号可以在日志面板里进行切换。",}, {key="小贴士.51",value="第一次载入战斗资源的时候可能会比较慢,请耐心等待。",}, {key="小贴士.52",value="不同的人物在升级时提高的能力也是不同的喔。",}, {key="小贴士.53",value="血刀门的心法能大幅度增加攻击力,但缺点是防御力实在是太差了。",}, {key="小贴士.54",value="简单难度是不会掉落武学残章的,炼狱难度的掉落概率比普通难度要大。",}, {key="小贴士.55",value="残章可以提高武学上限,外功和内功最多提高到20级。",}, {key="小贴士.56",value="所有的武功都可以被动的提高该系武学的威力。",}, {key="小贴士.57",value="随着时间的流逝,NPC可是会成长的噢!也就是说第二年挑战某NPC和第四年挑战他难度大为不同,所以尽快解决战斗吧!",}, {key="小贴士.58",value="在进入下一周目前,请把你的极品装备都放到松鼠旅馆的储物箱里吧!",}, {key="小贴士.59",value="如果你玩游戏切换场景时很卡,请尝试删除一些存档或者将自动存档不勾选。",}, {key="小贴士.60",value="打开日志,可以知道有哪些剧情没有完成,找到没触发的剧情",}, {key="小贴士.61",value="影响角色战斗集气速度的包括身法、根骨,武学、装备加成以及一些当前的角色BUFF。",}, {key="小贴士.62",value="你可以在人物面板中选择角色的武学是否在战斗中启用。禁用的武学在战斗中无论是AI还是玩家都不能使用它。",}, {key="小贴士.63",value="一些时候,夫妻一起上战场会互相激励而有加成效果。",}, {key="小贴士.64",value="一些特殊事件(如灭门门派)可能会导致队友对你有看法而离你而去。",}, {key="小贴士.65",value="在战场中,每个角色都是有隐藏的行动值的。“集气速度”影响了角色的行动值增长速度。行动值满以后角色才可以行动。",}, {key="小贴士.66",value="武学常识决定了一个角色可以学习到的天赋数量,每个天赋都会消耗一定的武学常识。",}, {key="小贴士.67",value="泡妞也是一门学问,在一些特殊剧情中,甚至都有机会与对方一亲芳泽喔。",}, {key="小贴士.68",value="位于香格里拉的北丑守护者一个巨大的宝藏,等大家去探索。",}, {key="小贴士.69",value="珍珑棋局幻境中,你可以挑战虚幻的敌人,来赢取最大的隐藏奖励。",}, {key="小贴士.70",value="一些天关的解锁需要靠天关令牌,天关令牌基本是世界掉落的。也就是说,每一个你打败的敌人都可能会掉落。",}, {key="小贴士.71",value="霹雳堂的孔八拉可以对你的角色进行试炼,如果能够通过,则将大大增强该角色。",}, {key="小贴士.72",value="一些将敌人击飞、位移的技能,将附带真实伤害。",}, {key="小贴士.73",value="元宝是全存档全周目共享的,所以珍惜它,将它用在最合理处吧。",}, {key="小贴士.74",value="传闻东海剑池的剑气可以将你的装备重铸。",}, {key="小贴士.75",value="战斗中控制内力将是一种战术,一些特殊的武功可以吸取或者化去对方的内力值。",}, {key="小贴士.76",value="自动战斗打不过的关卡,请尝试手动操作吧!你的智慧将会大大提高战斗的胜率。",}, {key="小贴士.77",value="王语嫣姑娘对于武学的笔记,将大大提升角色对武学奥义的理解。",}, {key="小贴士.78",value="慕容世家的斗转星移,将能在战斗中一定概率反弹伤害。",}, {key="小贴士.79",value="被钟灵姑娘的闪电貂咬中的敌人,将身中剧毒。",}, {key="小贴士.80",value="一些具有医术的角色,将能够很大程度扭转战局。",}, {key="小贴士.81",value="阿碧姑娘的歌声优美,或许也可以作为一门武学……",}, {key="小贴士.82",value="一些武学可以相互加成,所以请仔细思考,如何搭配武学,才能发挥最大威力。",}, {key="小贴士.83",value="东方不败的鬼魅身法,可以使他在战斗中出手迅捷无比。",}, {key="小贴士.84",value="侠客岛的赏善罚恶二使,在寻找江湖各个门派的掌门人赴侠客岛……",}, {key="小贴士.85",value="若将九阴真经逆运,将会出现什么样的效果呢?……",}, {key="小贴士.86",value="血刀门的胜谛是个大色鬼,满足他的心愿,他会给你好处噢",}, {key="小贴士.87",value="全真教的赵志敬喜欢拍马屁的弟子。",}, {key="小贴士.88",value="传闻灵鹫宫的李秋水和天山童姥不合。",}, {key="小贴士.89",value="福建南少林的大小洪拳也有它的过人之处。",}, {key="小贴士.90",value="如来神掌这门武学的下落一直是一个迷……",}, {key="小贴士.91",value="少林叛徒火工头陀的大力金刚指号称江湖指法一绝。",}, {key="小贴士.92",value="武当派以内功见长,纯阳无极功将给太极拳、剑提供极大的加成。",}, {key="小贴士.93",value="武当派的神门十三剑、倚天屠龙笔法均可以作为非常优秀的辅助技能。",}, {key="小贴士.94",value="电脑版和网页版战斗按TAB键可以显示角色生命、内力和怒气。",}, } return resource_suggesttips
local lspconfig = require 'lspconfig' local lspinstall = require 'lspinstall' lspinstall.setup() local servers = lspinstall.installed_servers() for _, server in pairs(servers) do lspconfig[server].setup{} end function compe() require 'compe'.setup { enabled = true, debug = false, autocomplete = true, documentation = true, preselect = 'enable', min_length = 1, throttle_time = 80, source_timeout = 200, incomplete_delay = 400, max_abbr_width = 100, max_kind_width = 100, max_menu_width = 100, source = { buffer = true, tags = true, spell = true, path = true, calc = true, nvim_lsp = true, nvim_lua = false, vsnip = false, -- buffer = {kind = "  (Buff)",priority = 1}, -- tags = true, -- spell = true, -- path = {kind = "  (Path)"}, -- calc = true; -- nvim_lsp = {kind = "  (Lsp)",priority = 2}, -- nvim_lua = true; -- vsnip = {kind = "  (Snip)",priority = 1}, } } end vim.lsp.protocol.CompletionItemKind = { "  (Text) ", "  (Method)", "  (Function)", "  (Constructor)", " ﴲ (Field)", "[] (Variable)", "  (Class)", " ﰮ (Interface)", "  (Module)", " 襁 (Property)", "  (Unit)", "  (Value)", " 練 (Enum)", "  (Keyword)", "  (Snippet)", "  (Color)", "  (File)", "  (Reference)", "  (Folder)", "  (EnumMember)", " ﲀ (Constant)", " ﳤ (Struct)", "  (Event)", "  (Operator)", "  (TypeParameter)" } compe()
local skynet = require "skynet" local ChatConst = require "game.chat.ChatConst" local table_insert = table.insert local ErrorCode = require "game.config.ErrorCode" local succeed = {ret=ErrorCode.Succeed} local unknow = {ret=ErrorCode.Unknow} local NORET = {} local CMD = {} local this = {} local getRoleInfo = function ( roleID ) local info = this.cacheRoleInfos[roleID] print("Cat:chat [start:10] ", info, roleID) if not info then local is_ok, role_info = skynet.call(this.db, "lua", "select_one_by_key", "RoleBaseInfo", "role_id", roleID) print("Cat:chat [start:12] ", is_ok, role_info) if is_ok then info = role_info this.cacheRoleInfos[roleID] = info end end return info end function CMD.get_handlers() local handlers = {} for k,v in pairs(CMD) do table.insert(handlers, k) end return handlers end function CMD.Chat_GetHistory( user_info, req_data ) print("Cat:chat [start:11] ", user_info, req_data) return {channel=req_data.channel, list={}} end function CMD.Chat_Send( user_info, req_data ) local roleInfo = getRoleInfo(user_info.cur_role_id) if not roleInfo then return unknow end local chatInfo = { roleID = user_info.cur_role_id, name = roleInfo.name, career = roleInfo.career, vip = roleInfo.vip or 0, headID = roleInfo.headID or 0, headUrl = roleInfo.headUrl or "", bubbleID = roleInfo.bubbleID or 0, channel = req_data.channel, content = req_data.content, extra = req_data.extra, time = Time.timeMS, id = this.ids[req_data.channel], } this.ids[req_data.channel] = this.ids[req_data.channel] + 1 local hisy = this.history[req_data.channel] table_insert(hisy, chatInfo) table_insert(this.newChatList, chatInfo) return succeed end function CMD.Chat_GetNew( user_info, req_data ) local ack = this.ackGetNews[user_info.cur_role_id] if not ack then this.ackGetNews[user_info.cur_role_id] = skynet.response() end return NORET end --Cat_Todo : 要不要改成组播的形式 local boardcast = function ( ) end local init = function ( ) this.history = {} this.ids = {} for i = ChatConst.Channel.World, ChatConst.Channel.Count do this.history[i] = {} this.ids[i] = 0 end this.newChatList = {} this.cacheRoleInfos = {} setmetatable(this.cacheRoleInfos, {__mode = "v"}) this.db = skynet.localname(".GameDBServer") this.ackGetNews = {} this.interestChannel = {} end skynet.start (function () init() skynet.fork(function() while true do boardcast() skynet.sleep(50) end end) skynet.dispatch ("lua", function (_, _, command, ...) local f = assert(CMD[command]) local r = f(...) if r ~= NORET then skynet.retpack(r) end end) end)
--[[ # Packages --]] -- #T# Table of contents -- #C# Importing packages -- #T# Beginning of content -- #C# Importing packages -- # |------------------------------------------------------------- -- #T# a package is imported with the require function applied to each lua file in the package -- # SYNTAX require("/path/to/file1") -- #T# file1 is a lua file require("S06_Functions") -- #| this file should be executed from a directory that contains both this file and S06_Functions.lua clo1 = func1() -- # func1 comes from the imported file print(clo1(3)) -- # 3 print(clo1(4)) -- # 7 -- # |-------------------------------------------------------------
ITEM.name = "PS5-M" ITEM.model ="models/kek1ch/stalker_outfit.mdl" ITEM.newModel ="models/stalkerisaac/playermodel/male_01_sunset.mdl" ITEM.description= "PS5-M Universal Protection Suit." ITEM.longdesc = "This modern version of the Duty bodysuit is better suited for stalker recruits who are used to lightweight suits. Unlike the SKAT series, the suit provides reasonable protection against anomalies while also being capable of stopping a pistol bullet." ITEM.width = 2 ITEM.height = 3 ITEM.price = 35000 ITEM.busflag = "dev" ITEM.br = 0.2 ITEM.fbr = 7 ITEM.ar = 0.2 ITEM.far = 3 ITEM.repairCost = ITEM.price/100*1 ITEM.ballisticlevels = {"0","ll","ll","l","l"} ITEM.img = ix.util.GetMaterial("vgui/hud/ps5m.png") ITEM.weight = 8.100 ITEM.miscslots = 3 ITEM.newSkin = 0 ITEM.bodygroup = {0} ITEM.bodygroupsub = {0} ITEM.skincustom[1] = { name = "Skin 0", skingroup = 0, } ITEM.skincustom[2] = { name = "Skin 1", skingroup = 1, } ITEM.skincustom[3] = { name = "Skin 2", skingroup = 2, } ITEM.skincustom[4] = { name = "Skin 3", skingroup = 3, } ITEM.skincustom[5] = { name = "Skin 4", skingroup = 4, } ITEM.skincustom[6] = { name = "Skin 5", skingroup = 5, } ITEM.skincustom[7] = { name = "Skin 6", skingroup = 6, } ITEM.skincustom[8] = { name = "Skin 7", skingroup = 7, } ITEM.skincustom[9] = { name = "Skin 8", skingroup = 8, } ITEM.skincustom[10] = { name = "Skin 9", skingroup = 9, }
local M = {} local Z = {} function M.init(use) use { 'code-biscuits/nvim-biscuits' } return Z; end function Z.setup() local ok, lib = pcall(require, 'nvim-biscuits') if not ok then return; end lib.setup({ cursor_line_only = true, toggle_keybind = "<leader>cb", show_on_start = true, default_config = { max_length = 30, min_distance = 10, prefix_string = " 📎 " }, language_config = { html = { prefix_string = " 🌐 " }, javascript = { prefix_string = " ✨ ", max_length = 80 }, python = { disabled = true } } }) end return M
local api = require 'api' local socket = require "socket" local username = assert(os.getenv('UDM_USER'), 'No UDM_USER env variable') local password = assert(os.getenv('PASSWORD'), 'No UDM_USER env variable') local client = assert(os.getenv('UDM_TARGET'), 'No UDM_TARGET env variable') local ip = os.getenv('UDM_IP') or '192.168.1.1' local cookie, xsrf cookie, xsrf = assert(api.login(ip, username, password)) while true do local is_present, err = api.check_for_presence(ip, client, cookie, xsrf) assert(type(is_present) == "boolean") assert(not err, string.format("%q", err)) print(string.format("%s is %s", client, (is_present and "present") or "not present")) socket.sleep(5) end
grid_serial_number = 7165 function calculate_power_level( x, y ) local rack_id = x + 10 local power_level = rack_id * y power_level = power_level + grid_serial_number power_level = power_level * rack_id power_level = tostring( power_level ) power_level = string.sub( power_level, -3, -3 ) return tonumber( power_level ) - 5 end grid = {} for x = 1, 300 do grid[x] = {} for y = 1, 300 do grid[x][y] = calculate_power_level( x, y ) end end function power_of_subgrid( x, y, size ) local power = 0 for i = x, x + ( size - 1 ) do for j = y, y + ( size - 1 ) do power = power + grid[i][j] end end return power end function calculate_max_power( size ) x = nil y = nil max_power = nil local limit = 300 - size - 1 for i = 1, limit do for j = 1, limit do local power = power_of_subgrid( i, j, size ) if max_power == nil or max_power < power then x = i y = j max_power = power end end end return x, y, max_power end max_i = nil max_x = nil max_y = nil max_power = nil for i = 1, 300 do local x, y, power = calculate_max_power( i ) if max_power == nil or power > max_power then max_i = i max_x = x max_y = y max_power = power end print( i ) end print( max_i, "(", max_x, max_y, ")", max_power )
local function split(str, pattern) local t = { } local function helper(line) table.insert(t, line) return "" end helper((str:gsub(pattern, helper))) return t end local hasMain local luaPaths = package and package.path and split(package.path, '(.-);') or { } for i = 1, #luaPaths do if luaPaths[i] == '?' or luaPaths[i] == '?.lua' or luaPaths[i] == '?/init.lua' then luaPaths[i] = nil elseif string.find(luaPaths[i], '/rom/modules/main') then hasMain = true end end table.insert(luaPaths, 1, '?.lua') table.insert(luaPaths, 2, '?/init.lua') table.insert(luaPaths, 3, '/usr/modules/?.lua') table.insert(luaPaths, 4, '/usr/modules/?/init.lua') if not hasMain then table.insert(luaPaths, 5, '/rom/modules/main/?') table.insert(luaPaths, 6, '/rom/modules/main/?.lua') table.insert(luaPaths, 7, '/rom/modules/main/?/init.lua') end table.insert(luaPaths, '/sys/modules/?.lua') table.insert(luaPaths, '/sys/modules/?/init.lua') local DEFAULT_PATH = table.concat(luaPaths, ';') local fs = _G.fs local os = _G.os local string = _G.string -- Add require and package to the environment return function(env) local function preloadSearcher(modname) if env.package.preload[modname] then return function() return env.package.preload[modname](modname, env) end end end local function loadedSearcher(modname) if env.package.loaded[modname] then return function() return env.package.loaded[modname] end end end local sentinel = { } local function pathSearcher(modname) if env.package.loaded[modname] == sentinel then error("loop or previous error loading module '" .. modname .. "'", 0) end env.package.loaded[modname] = sentinel local fname = modname:gsub('%.', '/') for pattern in string.gmatch(env.package.path, "[^;]+") do local sPath = string.gsub(pattern, "%?", fname) -- TODO: if there's no shell, we should not be checking relative paths below -- as they will resolve to root directory if env.shell and type(env.shell.getRunningProgram) == 'function' and sPath:sub(1, 1) ~= "/" then sPath = fs.combine(fs.getDir(env.shell.getRunningProgram() or ''), sPath) end if fs.exists(sPath) and not fs.isDir(sPath) then return loadfile(sPath, env) end end end -- place package and require function into env env.package = { path = env.LUA_PATH or _G.LUA_PATH or DEFAULT_PATH, config = '/\n:\n?\n!\n-', preload = { }, loaded = { coroutine = coroutine, io = io, math = math, os = os, string = string, table = table, }, loaders = { preloadSearcher, loadedSearcher, pathSearcher, } } function env.require(modname) for _,searcher in ipairs(env.package.loaders) do local fn, msg = searcher(modname) if fn then local module, msg2 = fn(modname, env) if not module then error(msg2 or (modname .. ' module returned nil'), 2) end env.package.loaded[modname] = module return module end if msg then error(msg, 2) end end error('Unable to find module ' .. modname, 2) end return env.require -- backwards compatible end
data.raw.item["bauxite-ore"].subgroup = "plates-ore" data.raw.item["gold-ore"].subgroup = "plates-ore" data.raw.item["lead-ore"].subgroup = "plates-ore" data.raw.item["tin-ore"].subgroup = "plates-ore" data.raw.item["zinc-ore"].subgroup = "plates-ore"
package.path = package.path .. ";../lib/?.lua;?.lua" local Parser = require("com.blacksheepherd.roml.RomlParser") local Tester = require("com.blacksheepherd.test.Tester") local File = require("com.blacksheepherd.io.File") local t = Tester("ParseTest") local function createParseTest(filename) return function() local parsedRoml = Parser.Parse(File.FileToString("./data/roml/roml/roml_" .. filename .. ".roml")) local parseTree = require("data.roml.parsetrees.parsetree_" .. filename) return Tester.AssertEqual(parsedRoml, parseTree) end end t:AddTest("RoML file with only objects (no children).", createParseTest("objects")) t:AddTest("RoML file with only objects (with children).", createParseTest("children")) t:AddTest("Objects with inline properties.", createParseTest("properties")) t:AddTest("Objects with classes.", createParseTest("classes")) t:AddTest("Objects with an id.", createParseTest("id")) t:AddTest("ROBLOX object clone.", createParseTest("clone")) t:AddTest("Objects with a variable class.", createParseTest("var_class")) t:AddTest("Objects with variable properties.", createParseTest("var_properties")) t:AddTest("Conditional statements.", createParseTest("conditionals")) t:AddTest("For loops.", createParseTest("loops")) t:AddTest("Nested conditionals/for loops.", createParseTest("nesting")) t:RunTests()
--- This directs all drawing to be done to a certain 2D or 3D plane or position, until the corresponding "End" function is called. --- The matrix functions exist, but are mostly unusable unless you're familiar with the source engine's layout for each aspect. _G.cam = {} --- Shakes the screen at a certain position. --- @param pos GVector @Origin of the shake. --- @param angles GAngle @Angles of the shake. --- @param factor number @The shake factor. function cam.ApplyShake(pos, angles, factor) end --- Switches the renderer back to the previous drawing mode from a 3D context. --- This function is an alias of cam.End3D. --- 🦟 **BUG**: [This will crash the game if there is no context to end.](https://github.com/Facepunch/garrysmod-issues/issues/1091) function cam.End() end --- Switches the renderer back to the previous drawing mode from a 2D context. --- 🦟 **BUG**: [This will crash the game if there is no context to end.](https://github.com/Facepunch/garrysmod-issues/issues/1091) function cam.End2D() end --- Switches the renderer back to the previous drawing mode from a 3D context. --- 🦟 **BUG**: [This will crash the game if there is no context to end.](https://github.com/Facepunch/garrysmod-issues/issues/1091) function cam.End3D() end --- Switches the renderer back to the previous drawing mode from a 3D2D context. --- 🦟 **BUG**: [This will crash the game if there is no context to end.](https://github.com/Facepunch/garrysmod-issues/issues/1091) function cam.End3D2D() end --- Switches the renderer back to the previous drawing mode from a 3D orthographic rendering context. function cam.EndOrthoView() end --- Returns the currently active model matrix. --- ⁉ **VALIDATE**: Does this actually mean the matrix on top of the stack? Probably --- @return GVMatrix @The currently active matrix. function cam.GetModelMatrix() end --- Tells the renderer to ignore the depth buffer and draw any upcoming operation "ontop" of everything that was drawn yet. --- @param ignoreZ boolean @Determines whenever to ignore the depth buffer or not. function cam.IgnoreZ(ignoreZ) end --- Pops the current active rendering matrix from the stack and reinstates the previous one. function cam.PopModelMatrix() end --- Pushes the specified matrix onto the render matrix stack. Unlike opengl, this will replace the current model matrix. --- ℹ **NOTE**: This does not work with cam.Start3D2D if `multiply` is false. --- @param matrix GVMatrix @The matrix to push. --- @param multiply boolean @If set, multiplies given matrix with currently active matrix (cam.GetModelMatrix) before pushing. function cam.PushModelMatrix(matrix, multiply) end --- Sets up a new rendering context. This is an extended version of cam.Start3D and cam.Start2D. Must be finished by cam.End3D or cam.End2D. --- 🦟 **BUG**: [This will not update current view properties for 3D contexts.](https://github.com/Facepunch/garrysmod-issues/issues/2682) --- @param dataTbl table @Render context config function cam.Start(dataTbl) end --- Sets up a new 2D rendering context. Must be finished by cam.End2D. --- This is almost always used with a render target from the render. To set its position use render.SetViewPort with a target already stored. --- ℹ **NOTE**: This will put an identity matrix at the top of the model matrix stack. If you are trying to use cam.PushModelMatrix, call it after this function and not before. --- 🟥 **NOTE**: Provides a 2D rendering context function cam.Start2D() end --- Sets up a new 3D rendering context. Must be finished by cam.End3D. --- For more advanced settings such as an orthographic view, use cam.Start instead. --- 🧱 **NOTE**: Provides a 3D rendering context --- ℹ **NOTE**: Both zNear and zFar need a value before any of them work. --- zNear also requires a value higher than 0. --- 🦟 **BUG**: [Negative x/y values won't work.](https://github.com/Facepunch/garrysmod-issues/issues/1995) --- 🦟 **BUG**: [This will not update current view properties.](https://github.com/Facepunch/garrysmod-issues/issues/2682) --- @param pos GVector @Render cam position. --- @param angles GAngle @Render cam angles. --- @param fov number @Field of view. --- @param x number @X coordinate of where to start the new view port. --- @param y number @Y coordinate of where to start the new view port. --- @param w number @Width of the new viewport. --- @param h number @Height of the new viewport. --- @param zNear number @Distance to near clipping plane. --- @param zFar number @Distance to far clipping plane. function cam.Start3D(pos, angles, fov, x, y, w, h, zNear, zFar) end --- Sets up a new 2D rendering context. Must be finished by cam.End3D2D. This function pushes a new matrix onto the stack. (cam.PushModelMatrix) --- Matrix formula: --- ``` --- local m = Matrix() --- m:SetAngles(angles) --- m:SetTranslation(pos) --- m:SetScale(Vector(scale, -scale, 1)) --- ``` --- 🟥 **NOTE**: Provides a 2D rendering context --- <rendercontext hook="false" type="3D"></rendercontext> --- ⚠ **WARNING**: This should be closed by cam.End3D2D otherwise the game crashes --- @param pos GVector @Origin of the 3D2D context, ie --- @param angles GAngle @Angles of the 3D2D context --- @param scale number @The scale of the render context function cam.Start3D2D(pos, angles, scale) end --- Sets up a new 3d context using orthographic projection. --- @param leftOffset number @The left plane offset. --- @param topOffset number @The top plane offset. --- @param rightOffset number @The right plane offset. --- @param bottomOffset number @The bottom plane offset. function cam.StartOrthoView(leftOffset, topOffset, rightOffset, bottomOffset) end
local AnimationTree = {} -- TODO return setmetatable(AnimationTree, { __call = function(t, ...) return AnimationTree.new(...) end })
-- some random shadow realm things realm = {} local modstorage = minetest.get_mod_storage() realm.is_gargantuan_defeated = modstorage:get_int("dead") == 1 realm.on_gargantuan_death = function() minetest.chat_send_all("A Gargantuan, one of the servants of Cerdon, has been slain!") realm.is_gargantuan_defeated = true modstorage:set_int("dead", 1) end -- as long as gargantuan remains undefeated local timer = 0 minetest.register_globalstep(function(dtime) if not realm.is_gargantuan_defeated and dtime then timer = timer + dtime if not (timer >= 1) then return end timer = 0 for _, player in pairs(minetest.get_connected_players()) do local pos = player:get_pos() if pos.y < -200 then player:set_hp(player:get_hp()-1) end end end end)
local _, wt = ... if (wt.currentClass ~= "DRUID") then return end local demoralizingRoar = {99,1735,9490,9747,9898,26998} local swipe = {779,780,769,9754,9908,26997} local rip = {1079,9492,9493,9752,9894,9896,27008} local claw = {1082,3029,5201,9849,9850,27000} local rake = {1822,1823,1824,9904,27003} local dash = {1850,9821,33357} local bash = {5211,6798,8983} local prowl = {5215,6783,9913} local tigersFury = {5217,6793,9845,9846} local shred = {5221,6800,8992,9829,9830,27001,27002} local ravage = {6785,6787,9866,9867,27005} local maul = {6807,6808,6809,8972,9745,9880,9881,26996} local cower = {8998,9000,9892,31709,27004} local pounce = {9005,9823,9827,27006} local ferociousBite = {22568,22827,22828,22829,31018,24248} local frenziedRegeneration = {22842,22895,22896,26999} local mangleCat = {33876,33982,33983} local mangleBear = {33878,33986,33987} local faerieFireFeral = {16857,17390,17391,17392,27011} wt:AddOverriddenSpells(demoralizingRoar,swipe,rip,claw,rake,dash,bash,prowl,tigersFury,shred,ravage,maul,cower,pounce,ferociousBite,frenziedRegeneration,mangleCat,mangleBear,faerieFireFeral) wt.SpellsByLevel = { [1] = {{id = 1126, cost = 10},}, [4] = {{id = 8921, cost = 100},{id = 774, cost = 100},}, [6] = {{id = 467, cost = 100},{id = 5177, cost = 100, requiredIds = {5176}},}, [8] = {{id = 339, cost = 200},{id = 5186, cost = 200, requiredIds = {5185}},}, [10] = {{id = 8924, cost = 300, requiredIds = {8921}},{id = 99, cost = 300, requiredIds = {5487}},{id = 5232, cost = 300, requiredIds = {1126}},{id = 1058, cost = 300, requiredIds = {774}},}, [12] = {{id = 5229, cost = 800, requiredIds = {5487}},{id = 8936, cost = 800},}, [14] = {{id = 782, cost = 900, requiredIds = {467}},{id = 5178, cost = 900, requiredIds = {5177}},{id = 5211, cost = 900, requiredIds = {5487}},{id = 5187, cost = 900, requiredIds = {5186}},}, [16] = {{id = 8925, cost = 1800, requiredIds = {8924}},{id = 779, cost = 1800, requiredIds = {5487}},{id = 1430, cost = 1800, requiredIds = {1058}},}, [18] = {{id = 1062, cost = 1900, requiredIds = {339}},{id = 770, cost = 1900},{id = 2637, cost = 1900},{id = 16810, cost = 95, requiredIds = {16689,1062}, requiredTalentId = 16689},{id = 6808, cost = 1900, requiredIds = {6807}},{id = 8938, cost = 1900, requiredIds = {8936}},}, [20] = {{id = 2912, cost = 2000},{id = 768, cost = 2000},{id = 1082, cost = 2000, requiredIds = {768}},{id = 1735, cost = 2000, requiredIds = {99}},{id = 5215, cost = 2000, requiredIds = {768}},{id = 1079, cost = 2000, requiredIds = {768}},{id = 5188, cost = 2000, requiredIds = {5187}},{id = 6756, cost = 2000, requiredIds = {5232}},{id = 20484, cost = 2000},}, [22] = {{id = 8926, cost = 3000, requiredIds = {8925}},{id = 2908, cost = 3000},{id = 5179, cost = 3000, requiredIds = {5178}},{id = 5221, cost = 3000, requiredIds = {768}},{id = 2090, cost = 3000, requiredIds = {1430}},}, [24] = {{id = 1075, cost = 4000, requiredIds = {782}},{id = 1822, cost = 4000, requiredIds = {768}},{id = 780, cost = 4000, requiredIds = {779}},{id = 5217, cost = 4000, requiredIds = {768}},{id = 8939, cost = 4000, requiredIds = {8938}},{id = 2782, cost = 4000},}, [26] = {{id = 8949, cost = 4500, requiredIds = {2912}},{id = 1850, cost = 4500, requiredIds = {768}},{id = 6809, cost = 4500, requiredIds = {6808}},{id = 2893, cost = 4500},{id = 5189, cost = 4500, requiredIds = {5188}},}, [28] = {{id = 5195, cost = 5000, requiredIds = {1062}},{id = 8927, cost = 5000, requiredIds = {8926}},{id = 16811, cost = 250, requiredIds = {16810,5195}, requiredTalentId = 16689},{id = 5209, cost = 5000, requiredIds = {5487}},{id = 3029, cost = 5000, requiredIds = {1082}},{id = 8998, cost = 5000, requiredIds = {768}},{id = 9492, cost = 5000, requiredIds = {1079}},{id = 2091, cost = 5000, requiredIds = {2090}},}, [30] = {{id = 778, cost = 6000, requiredIds = {770}},{id = 24974, cost = 300, requiredIds = {5570}, requiredTalentId = 5570},{id = 5180, cost = 6000, requiredIds = {5179}},{id = 6798, cost = 6000, requiredIds = {5211}},{id = 17390, cost = 300, requiredIds = {16857}, requiredTalentId = 16857},{id = 6800, cost = 6000, requiredIds = {5221}},{id = 783, cost = 6000},{id = 5234, cost = 6000, requiredIds = {6756}},{id = 20739, cost = 6000, requiredIds = {20484}},{id = 8940, cost = 6000, requiredIds = {8939}},{id = 740, cost = 6000},}, [32] = {{id = 9490, cost = 8000, requiredIds = {1735}},{id = 22568, cost = 8000, requiredIds = {768}},{id = 6785, cost = 8000, requiredIds = {768}},{id = 5225, cost = 8000, requiredIds = {768}},{id = 6778, cost = 8000, requiredIds = {5189}},}, [34] = {{id = 8928, cost = 10000, requiredIds = {8927}},{id = 8950, cost = 10000, requiredIds = {8949}},{id = 8914, cost = 10000, requiredIds = {1075}},{id = 8972, cost = 10000, requiredIds = {6809}},{id = 1823, cost = 10000, requiredIds = {1822}},{id = 769, cost = 10000, requiredIds = {780}},{id = 3627, cost = 10000, requiredIds = {2091}},}, [36] = {{id = 22842, cost = 11000, requiredIds = {5487}},{id = 9005, cost = 11000, requiredIds = {768}},{id = 9493, cost = 11000, requiredIds = {9492}},{id = 6793, cost = 11000, requiredIds = {5217}},{id = 8941, cost = 11000, requiredIds = {8940}},}, [38] = {{id = 5196, cost = 12000, requiredIds = {5195}},{id = 18657, cost = 12000, requiredIds = {2637}},{id = 16812, cost = 600, requiredIds = {16811,5196}, requiredTalentId = 16689},{id = 8955, cost = 12000, requiredIds = {2908}},{id = 6780, cost = 12000, requiredIds = {5180}},{id = 5201, cost = 12000, requiredIds = {3029}},{id = 8992, cost = 12000, requiredIds = {6800}},{id = 8903, cost = 12000, requiredIds = {6778}},}, [40] = {{id = 16914, cost = 14000},{id = 29166, cost = 14000},{id = 24975, cost = 700, requiredIds = {24974}, requiredTalentId = 5570},{id = 8929, cost = 14000, requiredIds = {8928}},{id = 9000, cost = 14000, requiredIds = {8998}},{id = 9634, cost = 14000, requiredIds = {5487}},{id = 20719, cost = 14000, requiredIds = {768}},{id = 22827, cost = 14000, requiredIds = {22568}},{id = 6783, cost = 14000, requiredIds = {5215}},{id = 8907, cost = 14000, requiredIds = {5234}},{id = 20742, cost = 14000, requiredIds = {20739}},{id = 8910, cost = 14000, requiredIds = {3627}},{id = 8918, cost = 14000, requiredIds = {740}},}, [42] = {{id = 9749, cost = 16000, requiredIds = {778}},{id = 8951, cost = 16000, requiredIds = {8950}},{id = 9747, cost = 16000, requiredIds = {9490}},{id = 17391, cost = 800, requiredIds = {17390}, requiredTalentId = 16857},{id = 9745, cost = 16000, requiredIds = {8972}},{id = 6787, cost = 16000, requiredIds = {6785}},{id = 9750, cost = 16000, requiredIds = {8941}},}, [44] = {{id = 22812, cost = 18000},{id = 9756, cost = 18000, requiredIds = {8914}},{id = 1824, cost = 18000, requiredIds = {1823}},{id = 9752, cost = 18000, requiredIds = {9493}},{id = 9754, cost = 18000, requiredIds = {769}},{id = 9758, cost = 18000, requiredIds = {8903}},}, [46] = {{id = 9833, cost = 20000, requiredIds = {8929}},{id = 8905, cost = 20000, requiredIds = {6780}},{id = 8983, cost = 20000, requiredIds = {6798}},{id = 9821, cost = 20000, requiredIds = {1850}},{id = 22895, cost = 20000, requiredIds = {22842}},{id = 9823, cost = 20000, requiredIds = {9005}},{id = 9829, cost = 20000, requiredIds = {8992}},{id = 9839, cost = 20000, requiredIds = {8910}},}, [48] = {{id = 9852, cost = 22000, requiredIds = {5196}},{id = 16813, cost = 1100, requiredIds = {16812,9852}, requiredTalentId = 16689},{id = 9849, cost = 22000, requiredIds = {5201}},{id = 22828, cost = 22000, requiredIds = {22827}},{id = 9845, cost = 22000, requiredIds = {6793}},{id = 9856, cost = 22000, requiredIds = {9750}},}, [50] = {{id = 17401, cost = 23000, requiredIds = {16914}},{id = 24976, cost = 1150, requiredIds = {24975}, requiredTalentId = 5570},{id = 9875, cost = 23000, requiredIds = {8951}},{id = 9880, cost = 23000, requiredIds = {9745}},{id = 9866, cost = 23000, requiredIds = {6787}},{id = 21849, cost = 23000, requiredIds = {9884}},{id = 9888, cost = 23000, requiredIds = {9758}},{id = 9884, cost = 23000, requiredIds = {8907}},{id = 20747, cost = 23000, requiredIds = {20742}},{id = 9862, cost = 23000, requiredIds = {8918}},}, [52] = {{id = 9834, cost = 26000, requiredIds = {9833}},{id = 9892, cost = 26000, requiredIds = {9000}},{id = 9898, cost = 26000, requiredIds = {9747}},{id = 9894, cost = 26000, requiredIds = {9752}},{id = 9840, cost = 26000, requiredIds = {9839}},}, [54] = {{id = 9907, cost = 28000, requiredIds = {9749}},{id = 9901, cost = 28000, requiredIds = {8955}},{id = 9910, cost = 28000, requiredIds = {9756}},{id = 9912, cost = 28000, requiredIds = {8905}},{id = 17392, cost = 1400, requiredIds = {17391}, requiredTalentId = 16857},{id = 9904, cost = 28000, requiredIds = {1824}},{id = 9830, cost = 28000, requiredIds = {9829}},{id = 9908, cost = 28000, requiredIds = {9754}},{id = 9857, cost = 28000, requiredIds = {9856}},}, [56] = {{id = 22829, cost = 30000, requiredIds = {22828}},{id = 22896, cost = 30000, requiredIds = {22895}},{id = 9827, cost = 30000, requiredIds = {9823}},{id = 9889, cost = 30000, requiredIds = {9888}},}, [58] = {{id = 9853, cost = 32000, requiredIds = {9852}},{id = 18658, cost = 32000, requiredIds = {18657}},{id = 9835, cost = 32000, requiredIds = {9834}},{id = 17329, cost = 1600, requiredIds = {16813,9853}, requiredTalentId = 16689},{id = 9876, cost = 32000, requiredIds = {9875}},{id = 9850, cost = 32000, requiredIds = {9849}},{id = 33986, cost = 1700, requiredIds = {33878}, requiredTalentId = 33917},{id = 33982, cost = 1700, requiredIds = {33876}, requiredTalentId = 33917},{id = 9881, cost = 32000, requiredIds = {9880}},{id = 9867, cost = 32000, requiredIds = {9866}},{id = 9841, cost = 32000, requiredIds = {9840}},}, [60] = {{id = 17402, cost = 34000, requiredIds = {17401}},{id = 24977, cost = 1700, requiredIds = {24976}, requiredTalentId = 5570},{id = 25298, cost = 34000, requiredIds = {9876}},{id = 31709, cost = 34000, requiredIds = {9892}},{id = 31018, cost = 30000, requiredIds = {22829}},{id = 9913, cost = 34000, requiredIds = {6783}},{id = 9896, cost = 34000, requiredIds = {9894}},{id = 9846, cost = 34000, requiredIds = {9845}},{id = 21850, cost = 34000, requiredIds = {21849}},{id = 25297, cost = 34000, requiredIds = {9889}},{id = 9885, cost = 34000, requiredIds = {9884}},{id = 20748, cost = 34000, requiredIds = {20747}},{id = 9858, cost = 34000, requiredIds = {9857}},{id = 25299, cost = 34000, requiredIds = {9841}},{id = 9863, cost = 34000, requiredIds = {9862}},}, [61] = {{id = 26984, cost = 39000, requiredIds = {9912}},{id = 27001, cost = 39000, requiredIds = {9830}},}, [62] = {{id = 26998, cost = 43000, requiredIds = {9898}},{id = 22570, cost = 43000},{id = 26978, cost = 43000, requiredIds = {25297}},}, [63] = {{id = 26987, cost = 48000, requiredIds = {9835}},{id = 24248, cost = 48000, requiredIds = {31018}},{id = 26981, cost = 48000, requiredIds = {25299}},}, [64] = {{id = 26992, cost = 53000, requiredIds = {9910}},{id = 27003, cost = 53000, requiredIds = {9904}},{id = 26997, cost = 53000, requiredIds = {9908}},{id = 33763, cost = 53000},}, [65] = {{id = 33357, cost = 59000, requiredIds = {9821}},{id = 26999, cost = 59000, requiredIds = {22896}},{id = 26980, cost = 59000, requiredIds = {9858}},}, [66] = {{id = 26993, cost = 34000, requiredIds = {9907}},{id = 27011, cost = 1700, requiredIds = {17392}, requiredTalentId = 16857},{id = 33745, cost = 66000},{id = 27006, cost = 66000, requiredIds = {9827}},{id = 27005, cost = 66000, requiredIds = {9867}},}, [67] = {{id = 26986, cost = 73000, requiredIds = {25298}},{id = 27000, cost = 73000, requiredIds = {9850}},{id = 26996, cost = 73000, requiredIds = {9881}},{id = 27008, cost = 73000, requiredIds = {9896}},}, [68] = {{id = 26989, cost = 81000, requiredIds = {9853}},{id = 27009, cost = 1700, requiredIds = {17329,26989}, requiredTalentId = 16689},{id = 33987, cost = 1900, requiredIds = {33986}, requiredTalentId = 33917},{id = 33983, cost = 1700, requiredIds = {33982}, requiredTalentId = 33917},{id = 33943, cost = 81000},}, [69] = {{id = 26985, cost = 90000, requiredIds = {26984}},{id = 27004, cost = 90000, requiredIds = {31709}},{id = 26979, cost = 90000, requiredIds = {26978}},{id = 26994, cost = 90000, requiredIds = {20748}},{id = 26982, cost = 90000, requiredIds = {26981}},}, [70] = {{id = 33786, cost = 100000},{id = 27012, cost = 100000, requiredIds = {17402}},{id = 27013, cost = 2500, requiredIds = {24977}, requiredTalentId = 5570},{id = 26988, cost = 100000, requiredIds = {26987}},{id = 26995, cost = 100000, requiredIds = {9901}},{id = 27002, cost = 100000, requiredIds = {27001}},{id = 26990, cost = 100000, requiredIds = {9885}},{id = 26983, cost = 100000, requiredIds = {9863}},}, }
-- base specs local zombie = { modes = { idle = {chance=0.7, duration=3, update_yaw=6}, walk = {chance=0.3, duration=5.5, moving_speed=1.5}, attack = {chance=0, moving_speed=2.5}, }, mesh = "creatures_zombie.b3d", collisionbox = {-0.25, -0.01, -0.25, 0.25, 1.65, 0.25}, rotation = -90.0, animations = { idle = {start=0, stop=80, speed=15}, walk = {start=102, stop=122, speed=15.5}, attack = {start=102, stop=122, speed=25}, death = {start=81, stop=101, speed=28, loop=false, duration=2.12}, }, sounds = { on_damage = {name="creatures_zombie_hit", gain=0.4, distance=10}, on_death = {name="creatures_zombie_death", gain=0.7, distance=10}, swim = {name="creatures_splash", gain=1.0, distance=10}, random = { idle = {name="creatures_zombie", gain=0.7, distance=12}, }, }, drops = { {"creatures:rotten_flesh", {min=1, max=2}, chance=0.7}, }, nodes = { spawn_on = {"default:stone", "default:dirt_with_grass", "default:dirt", "default:cobblestone", "default:mossycobble", "group:sand"}, }, } creatures.register_mob({ -- general name = ":creatures:zombie", nametag = creatures.feature_nametags and "Zombie" or nil, stats = { hp = 20, lifetime = cmer_zombie.lifetime, can_jump = 1, can_swim = true, can_burn = true, has_falldamage = true, has_knockback = true, light = {min=0, max=8}, hostile = true, }, modes = zombie.modes, model = { mesh = zombie.mesh, textures = {"creatures_zombie.png"}, collisionbox = zombie.collisionbox, rotation = zombie.rotation, animations = zombie.animations, }, sounds = zombie.sounds, combat = { attack_damage = 1, attack_speed = 0.6, attack_radius = 1.1, search_enemy = true, search_timer = 2, search_radius = 12, search_type = "player", }, spawning = { abm_nodes = zombie.nodes, abm_interval = cmer_zombie.spawn_interval, abm_chance = cmer_zombie.spawn_chance, max_number = 1, number = 2, light = {min=0, max=8}, height_limit = {min=-200, max=50}, spawner = { description = "Zombie Spawner", range = 8, number = 6, light = {min=0, max=8}, } }, drops = zombie.drops, }) if core.global_exists("asm") then asm.addEgg({ name = "zombie", spawn = "creatures:zombie", inventory_image = "creatures_zombie_inv.png", ingredient = "creatures:rotten_flesh", }) end core.register_alias("creatures:zombie", "spawneggs:zombie") -- harder zombie creatures.register_mob({ name = ":creatures:zombie_manic", nametag = creatures.feature_nametags and "Manic Zombie" or nil, stats = { hp = 75, lifetime = cmer_zombie.lifetime, can_jump = 1, can_swim = true, can_burn = true, has_falldamage = true, has_knockback = true, light = {min=0, max=8}, hostile = true, }, modes = zombie.modes, model = { mesh = zombie.mesh, textures = {"creatures_zombie_manic.png"}, collisionbox = zombie.collisionbox, rotation = zombie.rotation, animations = zombie.animations, }, sounds = zombie.sounds, combat = { attack_damage = 15, attack_speed = 0.6, attack_radius = 1.1, search_enemy = true, search_timer = 2, search_radius = 20, search_type = "player", }, drops = zombie.drops, spawning = { abm_nodes = zombie.nodes, abm_interval = cmer_zombie.spawn_interval + math.floor(cmer_zombie.spawn_interval / 2), abm_chance = cmer_zombie.spawn_chance + math.floor(cmer_zombie.spawn_chance / 2), max_number = 1, number = 1, light = {min=0, max=8}, height_limit = {min=-32000, max=500}, }, })
help( [[ HMMER is used for searching sequence databases for homologs of protein sequences, and for making protein sequence alignments. It implements methods using probabilistic models called profile hidden Markov models (profile HMMs). Compared to BLAST, FASTA, and other sequence alignment and database search tools based on older scoring methodology, HMMER aims to be significantly more accurate and more able to detect remote homologs because of the strength of its underlying mathematical models. In the past, this strength came at significant computational expense, but in the new HMMER3 project, HMMER is now essentially as fast as BLAST. ]]) local version = "3.1" local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/hmmer/"..version whatis("HMMER is used for searching for homologs of protein sequences, and for making protein sequence alignments.") prepend_path("PATH", pathJoin(base, "bin")) prepend_path("LD_LIBRARY_PATH", pathJoin(base, "lib")) prepend_path("CPATH", pathJoin(base, "include")) prepend_path("LIBRARY_PATH", pathJoin(base, "lib")) family('hmmer')
local Iterator = require(script.Parent.Parent.Iterator) local Hash = setmetatable({}, Iterator) Hash.__index = Hash Hash.__call = Iterator.__call function Hash.new(hash) return setmetatable({ hash = hash, lastKey = nil, }, Hash) end function Hash:after() local key, value = next(self.hash, self.lastKey) self.lastKey = key return value ~= nil and { key, value } or nil end return Hash
gr_bocatt = Creature:new { customName = "Bocatt", socialGroup = "bocatt", faction = "", level = 80, chanceHit = 3.32, damageMin = 160, damageMax = 170, baseXp = 1278, baseHAM = 15000, baseHAMmax = 21000, armor = 0, resists = {5,5,5,140,-1,-1,-1,-1,-1}, meatType = "meat_reptilian", meatAmount = 100, hideType = "hide_leathery", hideAmount = 60, boneType = "bone_mammal", boneAmount = 35, milk = 0, tamingChance = 0.25, ferocity = 7, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK + STALKER, optionsBitmask = AIENABLED, diet = CARNIVORE, templates = {"object/mobile/bocatt.iff"}, --controlDeviceTemplate = "object/intangible/pet/bocatt_hue.iff", lootGroups = {}, weapons = {"creature_spit_small_yellow"}, conversationTemplate = "", attacks = { {"posturedownattack",""}, {"stunattack",""} } } CreatureTemplates:addCreatureTemplate(gr_bocatt, "gr_bocatt")
AddCSLuaFile() local Entity = FindMetaTable "Entity" function Entity:IsPiano() return false end
print ("hello, world");
require "prefabutil" local assets = { Asset("ANIM", "anim/sch_teatree_nut.zip"), Asset("ATLAS", "images/inventoryimages/sch_teatree_piko.xml"), Asset("IMAGE", "images/inventoryimages/sch_teatree_piko.tex"), Asset("ATLAS", "images/inventoryimages/sch_teatree_piko_cooked.xml"), Asset("IMAGE", "images/inventoryimages/sch_teatree_piko_cooked.tex"), } local prefabs = { "spoiled_food" } local function plant(inst, growtime) local sapling = SpawnPrefab("acorn_sapling") sapling:StartGrowing() sapling.Transform:SetPosition(inst.Transform:GetWorldPosition()) sapling.SoundEmitter:PlaySound("dontstarve/wilson/plant_tree") inst:Remove() end local function domonsterstop(ent) ent.monster_stop_task = nil ent:StopMonster() end local function ondeploy(inst, pt) inst = inst.components.stackable:Get() inst.Transform:SetPosition(pt:Get()) local timeToGrow = GetRandomWithVariance(TUNING.ACORN_GROWTIME.base, TUNING.ACORN_GROWTIME.random) plant(inst, timeToGrow) -- Pacify a nearby monster tree local ent = FindEntity(inst, TUNING.DECID_MONSTER_ACORN_CHILL_RADIUS, nil, {"birchnut", "monster"}, {"stump", "burnt", "FX", "NOCLICK","DECOR","INLIMBO"}) if ent ~= nil then if ent.monster_start_task ~= nil then ent.monster_start_task:Cancel() ent.monster_start_task = nil end if ent.monster and ent.monster_stop_task == nil and not (ent.components.burnable ~= nil and ent.components.burnable:IsBurning()) and not (ent:HasTag("stump") or ent:HasTag("burnt")) then ent.monster_stop_task = ent:DoTaskInTime(math.random(0, 3), domonsterstop) end end end local function OnLoad(inst, data) if data and data.growtime then plant(inst, data.growtime) end end local function fn() local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddSoundEmitter() inst.entity:AddNetwork() MakeInventoryPhysics(inst) inst.entity:AddMiniMapEntity() inst.entity:SetPristine() inst.AnimState:SetBank("teatree_nut") inst.AnimState:SetBuild("sch_teatree_nut") inst.AnimState:PlayAnimation("idle") inst.MiniMapEntity:SetIcon( "sch_teatree_piko.tex" ) inst:AddTag("cattoy") inst:AddTag("cookable") inst:AddTag("deployedplant") inst:AddTag("icebox_valid") inst:AddTag("show_spoilage") if not TheWorld.ismastersim then return inst end inst:AddComponent("cookable") inst.components.cookable.product = "sch_teatree_nut_cooked_piko" inst:AddComponent("tradable") inst:AddComponent("perishable") inst.components.perishable:StartPerishing() inst.components.perishable:SetPerishTime(TUNING.PERISH_SLOW) inst.components.perishable.onperishreplacement = "spoiled_food" inst:AddComponent("edible") inst.components.edible.hungervalue = TUNING.CALORIES_TINY inst.components.edible.healthvalue = TUNING.HEALING_TINY inst.components.edible.foodtype = FOODTYPE.RAW inst:AddComponent("stackable") inst.components.stackable.maxsize = TUNING.STACK_SIZE_SMALLITEM inst:AddComponent("inspectable") MakeSmallBurnable(inst, TUNING.SMALL_BURNTIME) MakeSmallPropagator(inst) inst:AddComponent("inventoryitem") inst.components.inventoryitem.imagename = "sch_teatree_piko" inst.components.inventoryitem.atlasname = "images/inventoryimages/sch_teatree_piko.xml" inst:AddComponent("deployable") inst.components.deployable:SetDeployMode(DEPLOYMODE.PLANT) inst.components.deployable.ondeploy = ondeploy inst:AddComponent("winter_treeseed") inst.components.winter_treeseed:SetTree("winter_deciduoustree") MakeHauntableLaunchAndIgnite(inst) inst.OnLoad = OnLoad return inst end local function cooked() local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddSoundEmitter() inst.entity:AddNetwork() inst.entity:SetPristine() inst.entity:AddMiniMapEntity() MakeInventoryPhysics(inst) inst.AnimState:SetBank("teatree_nut") inst.AnimState:SetBuild("sch_teatree_nut") inst.AnimState:PlayAnimation("cooked") inst.MiniMapEntity:SetIcon("sch_teatree_piko_cooked.tex") if not TheWorld.ismastersim then return inst end inst:AddComponent("edible") inst.components.edible.hungervalue = TUNING.CALORIES_TINY inst.components.edible.healthvalue = TUNING.HEALING_TINY inst.components.edible.foodtype = "SEEDS" inst:AddComponent("perishable") inst.components.perishable:StartPerishing() inst.components.perishable:SetPerishTime(TUNING.PERISH_SLOW) inst.components.perishable.onperishreplacement = "spoiled_food" inst:AddComponent("stackable") inst.components.stackable.maxsize = TUNING.STACK_SIZE_SMALLITEM inst:AddComponent("inspectable") MakeSmallBurnable(inst, TUNING.SMALL_BURNTIME) MakeSmallPropagator(inst) inst:AddComponent("inventoryitem") inst.components.inventoryitem.imagename = "sch_teatree_piko_cooked" inst.components.inventoryitem.atlasname = "images/inventoryimages/sch_teatree_piko_cooked.xml" MakeHauntableLaunch(inst) return inst end return Prefab("sch_teatree_nut_piko", fn, assets, prefabs), Prefab("sch_teatree_nut_cooked_piko", cooked, assets), MakePlacer("sch_teatree_nut_piko_placer", "teatree_nut", "sch_teatree_nut", "idle_planted")
--[[ Upbit Open API ## REST API for Upbit Exchange - Base URL: [https://api.upbit.com] - Official Upbit API Documents: [https://docs.upbit.com] - Official Support email: [open-api@upbit.com] OpenAPI spec version: 1.0.0 Contact: ujhin942@gmail.com Generated by: https://github.com/swagger-api/swagger-codegen.git ]] -- member_level class local member_level = {} local member_level_mt = { __name = "member_level"; __index = member_level; } local function cast_member_level(t) return setmetatable(t, member_level_mt) end local function new_member_level(security_level, fee_level, email_verified, identity_auth_verified, bank_account_verified, kakao_pay_auth_verified, locked, wallet_locked) return cast_member_level({ ["security_level"] = security_level; ["fee_level"] = fee_level; ["email_verified"] = email_verified; ["identity_auth_verified"] = identity_auth_verified; ["bank_account_verified"] = bank_account_verified; ["kakao_pay_auth_verified"] = kakao_pay_auth_verified; ["locked"] = locked; ["wallet_locked"] = wallet_locked; }) end return { cast = cast_member_level; new = new_member_level; }
io.stdout:setvbuf'no' audio = require "wave" --require the library love.window.setTitle("Press Space to switch examples") examples = {} example = 1 require "examples/1" require "examples/2" require "examples/3" require "examples/4" function love.keypressed(key, scancode, isrepeat) if key == "space" then example = (example < #examples) and example + 1 or 1 if love.unload then love.unload() end love.filedropped = function () end love.update = function () end love.draw = function () end examples[example]() love.load() else if love.key then love.key(key) end end end examples[example]()
ITEM.name = "Base Blueprint" ITEM.category = "Чертежи" ITEM.model = "models/toussaint_paper6.mdl"
function new_ISO_Time(i_epoch_str, i_delta_m, i_delta_p) if i_epoch_str == nil then i_epoch_str = "" end local y,m,d,h,mi,s,fs = string.match(i_epoch_str, "(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d%d)([.%d]-)Z") local l_fs = (fs ~= nil and tonumber(fs) or 0) function to_seconds() local l_seconds = 0 if y ~= nil then l_seconds = os.time({ year=y, month=m, day=d, hour=h, min=mi, sec=s }) end return l_seconds end local m_data = { m_delta_m = i_delta_m ~= nil and -tonumber(i_delta_m) or 0, m_delta_p = i_delta_p ~= nil and tonumber(i_delta_p) or 0, m_secs = to_seconds(), m_fsecs = l_fs } function m_data:get_iso_str() return i_epoch_str end function m_data:is_in_delta_range(i_iso_time) local l_diff = i_iso_time.m_secs - self.m_secs + ((i_iso_time.m_fsecs - self.m_fsecs) * 10^-12) local l_return = 0 if l_diff < self.m_delta_m then print("x", i_iso_time:get_iso_str()) l_return = -1 elseif l_diff >= self.m_delta_p then l_return = 1 end return l_return end function m_data:is_valid() return self.m_secs ~= 0 end function m_data:diff(i_iso_time) local l_diff = 0 if self:is_valid() and i_iso_time:is_valid() then l_diff = self.m_secs - i_iso_time.m_secs + (self.m_fsecs - i_iso_time.m_fsecs) end return l_diff end return m_data end
local player_settings = require("globals.player-settings") local stdlib_Is = require("__stdlib__/stdlib/utils/is") local common = {} -- Gets the player object by player reference -- @param player_index The index of the player ref function common.get_player(player_index) return game.get_player(player_index) end -- Logs the message to the player in the console only if debug_mode is enabled. -- @param player_index LuaPlayer function common.debug_log(player_index, message) if player_settings.get_debug_mode_setting(player_index) then common.get_player(player_index).print(message) end end function common.min(array) local min = 0 for key, value in pairs(array) do if min == 0 or value < min then min = value end end return min end function common.max(array) local max = 0 for key, value in pairs(array) do if value > max then max = value end end return max end function common.valid(object) if object == nil then return false end if object == {} then return false end return stdlib_Is(object) end function common.short_if(condition, true_result, false_result) if condition then return true_result end return false_result end return common
require "warp" local Cosine = {} function Cosine:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end function Cosine:warp(x, y, z) return warp(x, y, z) end function Cosine:mu(x, y, z) return 1.0 end function Cosine:lam(x, y, z) return 2.0 end function Cosine:force(x, y, z) return math.pi*(-3.0*math.pi*math.sin(math.pi*x)*math.sin(math.pi*z) + 5.0*math.pi*math.cos(math.pi*x)*math.cos(math.pi*y)), -3.0*math.pi^2*math.sin(math.pi*x)*math.sin(math.pi*y), 5.0*math.pi^2*math.cos(math.pi*x)*math.cos(math.pi*z) end function Cosine:solution(x, y, z) return math.cos(math.pi * x) * math.cos(math.pi * y), 0, math.cos(math.pi * x) * math.cos(math.pi * z) end function Cosine:solution_jacobian(x, y, z) return -math.pi * math.sin(math.pi * x) * math.cos(math.pi * y), -math.pi * math.cos(math.pi * x) * math.sin(math.pi * y), 0, 0, 0, 0, -math.pi * math.sin(math.pi * x) * math.cos(math.pi * z), 0, -math.pi * math.cos(math.pi * x) * math.sin(math.pi * z) end function Cosine:boundary(x, y, z) return self:solution(x, y, z) end cosine = Cosine:new()
local ADDON_NAME = ... local logger = CodexCountLogger local CCEvents = CreateFrame("FRAME", ADDON_NAME) local currentCount = 0 local CCLDB = LibStub("LibDataBroker-1.1"):NewDataObject( ADDON_NAME, { type = "data source", text = ADDON_NAME, label = ADDON_NAME, icon = "Interface\\Icons\\inv_relics_6orunestone_ogremissive", OnTooltipShow = function(tooltip) if (not tooltip or not tooltip.AddLine) then return end local expectedRep = floor(currentCount / 2) tooltip:AddLine("|cFFFFFFFF" .. ADDON_NAME .. "|r") tooltip:AddLine("You have " .. currentCount .. " Cataloged Research, worth " .. expectedRep .. " reputation.") end } ) local CCIcon = LibStub("LibDBIcon-1.0") -- Map of item ID to their Cataloged Research value local ITEM_VALUES = { [186685] = 1, -- Relic Fragment [187322] = 8, -- Crumbling Stone Tablet [187457] = 8, -- Engraved Glass Pane [187324] = 8, -- Gnawed Ancient Idol [187323] = 8, -- Runic Diagram [187460] = 8, -- Strangely Intricate Key [187458] = 8, -- Unearthed Teleporter Sigil [187459] = 8, -- Vial of Mysterious Liquid [187465] = 48, -- Complicated Organism Harmonizer [187327] = 48, -- Encrypted Korthian Journal [187463] = 48, -- Enigmatic Map Fragments [187325] = 48, -- Faded Razorwing Anatomy Illustration [187326] = 48, -- Half-Completed Runeforge Pattern [187462] = 48, -- Scroll of Shadowlands Fables [187478] = 48, -- White Razorwing Talon [187336] = 100, -- Forbidden Weapon Schematics [187466] = 100, -- Korthian Cypher Book [187332] = 100, -- Recovered Page of Voices [187328] = 100, -- Ripped Cosmology Chart [187334] = 100, -- Shattered Void Tablet [187330] = 150, -- Naaru Shard Fragment [187329] = 150, -- Old God Specimen Jar [187467] = 150, -- Perplexing Rune-Cube [187331] = 150, -- Tattered Fae Designs [187311] = 300, -- Azgoth's Tattered Maps [187333] = 300, -- Core of an Unknown Titan [187350] = 300, -- Displaced Relic [187335] = 300 -- Maldraxxus Larva Shell } local function OnBagUpdated() local count = 0 for bag = 0, NUM_BAG_SLOTS do for slot = 1, GetContainerNumSlots(bag) do local itemId = GetContainerItemID(bag, slot) local itemValue = ITEM_VALUES[itemId] if (itemValue) then local _, itemCount = GetContainerItemInfo(bag, slot) count = count + itemValue * itemCount end end end logger.log("Updated count: " .. count) currentCount = count end local function OnAddonLoaded(addonName) if (addonName == ADDON_NAME) then CCEvents:UnregisterEvent("ADDON_LOADED") CCEvents:RegisterEvent("BAG_UPDATE") end end local function HandleEvent(_, event, ...) logger.log("Handling event " .. event) if (event == "ADDON_LOADED") then OnAddonLoaded(...) elseif (event == "BAG_UPDATE") then OnBagUpdated() end end local function Init() if (CCMinimapIcon == nil) then CCMinimapIcon = {} end CCIcon:Register(ADDON_NAME, CCLDB, CCMinimapIcon) CCEvents:SetScript("OnEvent", HandleEvent) CCEvents:RegisterEvent("ADDON_LOADED") end logger.log("Loading...") Init()
local gen_def = dofile(minetest.get_modpath("more_chests") .. "/utils/base.lua") local S = minetest.get_translator("more_chests") local function register_toolbox(description, material, side_tile, craft_item) local def = gen_def({ description = description, type = "toolbox", size = "big", -- node_box = {-0.5, -0.5, -0.5, 1.5, 0.5, 0.5}, -- makes it two blocks wide tiles = { side = side_tile, front = "toolbox_" .. material .. "_front.png", top = "toolbox_" .. material .. "_top.png", }, }) minetest.register_node("more_chests:toolbox_" .. material, def) minetest.register_craft({ output = "more_chests:toolbox_" .. material, recipe = { {craft_item, craft_item, craft_item}, {craft_item, "group:pickaxe", craft_item}, {craft_item, craft_item, craft_item} } }) end register_toolbox(S("Wooden Toolbox"), "wood", "default_wood.png", "default:wood") register_toolbox(S("Aspen Wood Toolbox"), "aspen", "default_aspen_wood.png", "default:aspen_wood") register_toolbox(S("Acacia Wood Toolbox"), "acacia", "default_acacia_wood.png", "default:acacia_wood") register_toolbox(S("Junglewood Toolbox"), "jungle", "default_junglewood.png", "default:junglewood") register_toolbox(S("Pine Wood Toolbox"), "pine", "default_pine_wood.png", "default:pine_wood") register_toolbox(S("Steel Toolbox"), "steel", "default_steel_block.png", "default:steel_ingot")
-- -- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You 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 rediscluster = require("resty.rediscluster") local core = require("apisix.core") local resty_lock = require("resty.lock") local setmetatable = setmetatable local tostring = tostring local ipairs = ipairs local _M = {} local mt = { __index = _M } local function new_redis_cluster(conf) local config = { name = "apisix-redis-cluster", serv_list = {}, read_timeout = conf.redis_timeout, auth = conf.redis_password, dict_name = "plugin-limit-count-redis-cluster-slot-lock", } for i, conf_item in ipairs(conf.redis_cluster_nodes) do local host, port, err = core.utils.parse_addr(conf_item) if err then return nil, "failed to parse address: " .. conf_item .. " err: " .. err end config.serv_list[i] = {ip = host, port = port} end local red_cli, err = rediscluster:new(config) if not red_cli then return nil, "failed to new redis cluster: " .. err end return red_cli end function _M.new(plugin_name, limit, window, conf) local red_cli, err = new_redis_cluster(conf) if not red_cli then return nil, err end local self = { limit = limit, window = window, conf = conf, plugin_name = plugin_name, red_cli =red_cli } return setmetatable(self, mt) end function _M.incoming(self, key) local red = self.red_cli local limit = self.limit local window = self.window key = self.plugin_name .. tostring(key) local remaining,err = red:eval("if redis.call('ttl',KEYS[1]) < 0 then redis.call('set',KEYS[1],ARGV[1]-1,'EX',ARGV[2]) return ARGV[1]-1 end return redis.call('incrby',KEYS[1],-1)",1,key,limit,window) if err then return nil,err end if remaining <0 then core.log.error(remaining) return nil,"rejected" end return 0,remaining end return _M
local database_connection addEventHandler('onResourceStart', resourceRoot, function() database_connection = dbConnect('sqlite', ':/global.db') if database_connection then outputDebugString('SQLite baglantisi basariyla saglandi.', 3, 0, 255, 0) else outputDebugString('SQLite baglantisi saglanirken bir hata meydana geldi!', 1, 255, 0, 0) end end) getConnection = function() return database_connection end
---------------------------------------------------------------------------------------------------- -- Class to fill a rectangle. -- <p> -- NOTE: This uses immediate mode drawing and so has a high performance impact when -- used on mobile devices. You may wish to use a 1-pixel high Image instead if you -- wish to minimize draw calls. -- </p> -- -- <h4>Extends:</h4> -- <ul> -- <li><a href="flower.DrawableObject.html">DrawableObject</a><l/i> -- </ul> -- -- @author Makoto -- @release V3.0.0 ---------------------------------------------------------------------------------------------------- -- import local class = require "flower.class" local DrawableObject = require "flower.DrawableObject" -- class local DrawableRect = class(DrawableObject) --- -- This is the function called when drawing. -- @param index index of DrawCallback. -- @param xOff xOff of DrawCallback. -- @param yOff yOff of DrawCallback. -- @param xFlip xFlip of DrawCallback. -- @param yFlip yFlip of the Prop. function DrawableRect:onDraw(index, xOff, yOff, xFlip, yFlip) local w, h, d = self:getSize() MOAIGfxDevice.setPenColor(self:getColor()) MOAIDraw.fillRect(0, 0, w, h) end return DrawableRect
-- Description: GUI styles Textfield local default_gui = data.raw["gui-style"].default ------------------------------------------------------------------------------- -- Style Textfield -- -- @type Textfield -- ------------------------------------------------------------------------------- -- Style of default -- -- @field [parent=#Textfield] default default_gui[Constants.Names.Styles.Textfields.SELogisticsTextfield] = { type = "textbox_style", parent = "search_textfield_with_fixed_width", width = 50 }
local ui = { list = {}, atlas = false } function ui:load() self.atlas, self.quad = loadAtlas("data/art/img/ui.png", assetSize, assetSize, 0) self.smoof = 6 self.smoofSnap = 1 end --UTILITY SHIT function ui:clear() self.list = {} end function ui.getTextDimensions(text, font) local width = font:getWidth(text) local height = (font:getAscent() - font:getDescent()) return width, height end function ui:printCenter(font, text, x, y, width, height) local textWidth, textHeight = ui.getTextDimensions(text, font) lg.setFont(font) lg.print(text, x + (width / 2) - (textWidth / 2), y + (height / 2) - (textHeight / 2)) end --Wrapper for lg.newQuad because it makes shit simpler function ui:newQuad(x, y, width, height) return lg.newQuad(x, y, width, height, self.atlas:getWidth(), self.atlas:getHeight()) end function ui:getHidePosition(hideDirection, x, y, width, height) local hideX, hideY = x, y if hideDirection == "top" then hideY = -(height * 2) elseif hideDirection == "bottom" then hideY = lg.getHeight() + (height * 2) elseif hideDirection == "left" then hideX = -(width * 2) elseif hideDirection == "right" then hideX = lg.getWidth() + (width * 2) end return hideX, hideY end --ELEMENT CREATING SHIT --Creates image object. --Source: Source image, quad: Quad. X & y: Position --hideDirection: "top", "bottom", "left", "right", Decies where the object goes when hidden function ui:newImage(func, atlas, quad, x, y, scale, hideDirection) func = func or false local _x, _y, width, height = quad:getViewport() width = width * scale height = height * scale local hideX, hideY = self:getHidePosition(hideDirection, x, y, width, height) self.list[#self.list + 1] = { type = "image", func = func, atlas = atlas, quad = quad, hideDirection = hideDirection, --Status hidden = false, offScreen = false, enabled = true, --UNSCALED DIMENSIONS! width = width, height = height, scale = scale, --Current position x = x, y = y, --target position targetX = x, targetY = y, --Visible position visibleX = x, visibleY = y, --Hidden position hiddenX = hideX, hiddenY = hideY, -- screen = "" } return self.list[#self.list] end function ui:newButton(func, text, font, x, y, width, height, hideDirection) local hideX, hideY = self:getHidePosition(hideDirection, x, y, width, height) self.list[#self.list + 1] = { type = "button", func = func, text = text, hideDirection = hideDirection, font = font, --Status hidden = false, offScreen = false, enabled = true, width = width, height = height, --Current position x = x, y = y, --target position targetX = x, targetY = y, --Visible position visibleX = x, visibleY = y, --Hidden position hiddenX = hideX, hiddenY = hideY, screen = "" } return self.list[#self.list] end function ui:newCheckBox(func, text, x, y, scale, hideDirection) local font = font.tiny local hideX, hideY = self:getHidePosition(hideDirection, x, y, assetSize * scale, assetSize * scale) local textWidth = font:getWidth(text) self.list[#self.list + 1] = { type = "checkBox", func = func, checked = false, text = text, hideDirection = hideDirection, font = font, --Status hidden = false, offScreen = false, enabled = true, textWidth = textWidth, width = assetSize * scale + textWidth, height = assetSize * scale, scale = scale, --Current position x = x, y = y, --target position targetX = x, targetY = y, --Visible position visibleX = x, visibleY = y, --Hidden position hiddenX = hideX, hiddenY = hideY, screen = "" } return self.list[#self.list] end function ui:newText(func, text, x, y, font, color, hideDirection) local width, height = ui.getTextDimensions(text, font) local hideX, hideY = self:getHidePosition(hideDirection, x, y, width, height) self.list[#self.list + 1] = { type = "text", func = func, text = text, hideDirection = hideDirection, font = font, color = color, --Status hidden = false, offScreen = false, enabled = true, width = width, height = height, --Current position x = x, y = y, --target position targetX = x, targetY = y, --Visible position visibleX = x, visibleY = y, --Hidden position hiddenX = hideX, hiddenY = hideY, screen = "" } return self.list[#self.list] end function ui:newPanel(color, x, y, width, height, hideDirection) local hideX, hideY = self:getHidePosition(hideDirection, x, y, width, height) self.list[#self.list + 1] = { type = "panel", color = color, hideDirection = hideDirection, --Status hidden = false, offScreen = false, enabled = true, width = width, height = height, --Current position x = x, y = y, --target position targetX = x, targetY = y, --Visible position visibleX = x, visibleY = y, --Hidden position hiddenX = hideX, hiddenY = hideY, screen = "" } return self.list[#self.list] end --CONTROLLING SHIT function ui:show(element, instant) instant = instant or false element.hidden = false element.targetX = element.visibleX element.targetY = element.visibleY if instant then element.x = element.targetX element.y = element.targetY end end function ui:hide(element, instant) instant = instant or false element.hidden = true element.targetX = element.hiddenX element.targetY = element.hiddenY if instant then element.x = element.targetX element.y = element.targetY end end function ui:center(element, x, y, move) move = move or false if x then element.visibleX = (lg.getWidth() / 2) - (element.width / 2) end if y then element.visibleY = (lg.getHeight() / 2) - (element.height / 2) end if move then element.x = element.visibleX element.y = element.visibleY end --Updating hide positions local hideX, hideY = self:getHidePosition(element.hideDirection, element.visibleX, element.visibleY, element.width, element.height) element.hiddenX = hideX element.hiddenY = hideY element.center = true end function ui:setEnabled(element, enabled) element.enabled = enabled end function ui:setFont(element, font) element.font = font end function ui:setScreen(element, screen) element.screen = screen end function ui:showScreen(screen) for i,v in ipairs(self.list) do if v.screen == screen then self:show(v) end end end function ui:hideScreen(screen) for i,v in ipairs(self.list) do if v.screen == screen then self:hide(v) end end end function ui:deleteScreen(screen) for i,v in ipairs(self.list) do if v.screen == screen then table.remove(self.list, i) end end end --CALLBACK SHIT function ui:update(dt) for i,v in ipairs(self.list) do --Updating position v.x = v.x + (v.targetX - v.x) * self.smoof * dt v.y = v.y + (v.targetY - v.y) * self.smoof * dt if math.abs(v.x - v.targetX) < self.smoofSnap then v.x = v.targetX end if math.abs(v.y - v.targetY) < self.smoofSnap then v.y = v.targetY end end end function ui:draw() for i,v in ipairs(self.list) do if v.type == "image" then lg.setColor(1, 1, 1, 1) lg.draw(v.atlas, v.quad, v.x, v.y, 0, v.scale, v.scale) elseif v.type == "button" then lg.setColor(1, 1, 1, 1) --LEFT lg.draw(self.atlas, self.quad[1], v.x, v.y, 0, v.height / assetSize, v.height / assetSize) --RIGHT lg.draw(self.atlas, self.quad[3], (v.x + v.width) - v.height, v.y, 0, v.height / assetSize, v.height / assetSize) --CENTER local edge = (v.height / assetSize) * 3 local gap = (v.x + v.width) - edge - (v.x + edge) if gap > 0 then lg.draw(self.atlas, self.quad[2], (v.x + edge), v.y, 0, gap / assetSize, v.height / assetSize) end --Text lg.setColor(1, 1, 1, 1) self:printCenter(v.font, v.text, v.x, v.y, v.width, v.height) elseif v.type == "text" then lg.setColor(v.color) lg.setFont(v.font) if v.center then lg.printf(v.text, 0, v.y, lg.getWidth(), "center") else lg.print(v.text, v.x, v.y) end elseif v.type == "panel" then lg.setColor(v.color) lg.rectangle("fill", v.x, v.y, v.width, v.height) lg.setColor(0, 0, 0, 1) lg.rectangle("line", v.x, v.y, v.width, v.height) elseif v.type == "checkBox" then lg.setColor(1, 1, 1, 1) if not v.enabled then lg.setColor(1, 1, 1, 0.4) end local quad = self.quad[14] if v.checked then quad = self.quad[15] end lg.draw(self.atlas, quad, v.x, v.y, 0, v.scale, v.scale) lg.setFont(v.font) local textHeight = v.font:getAscent() - v.font:getDescent() lg.print(v.text, v.x + v.width - v.textWidth, v.y + (v.height / 2) - (textHeight / 2)) end --lg.setColor(1, 0, 1, 1) --lg.print(v.screen, v.x, v.y) end end function ui:drawBounds() lg.setColor(1, 0, 1, 1) for i,v in ipairs(self.list) do lg.rectangle("line", v.x, v.y, v.width, v.height) end end function ui:press(x, y) local pressed = false for i,v in ipairs(self.list) do if pointInRect(x, y, v.x, v.y, v.width, v.height) then --Checkbox Toggling if v.type == "checkBox" then if v.enabled then v.checked = not v.checked end end if type(v.func) == "function" then if v.enabled then v.func(v) pressed = true end end end end return pressed end function ui:release(x, y) end return ui
local M = {} M.on_attach = function(client) local ts_utils = require('nvim-lsp-ts-utils') client.resolved_capabilities.document_formatting = false -- defaults ts_utils.setup({ debug = false, disable_commands = false, enable_import_on_completion = false, -- import all import_all_timeout = 5000, -- ms -- lower numbers = higher priority import_all_priorities = { same_file = 1, -- add to existing import statement local_files = 2, -- git files or files with relative path markers buffer_content = 3, -- loaded buffer content buffers = 4, -- loaded buffer names }, import_all_scan_buffers = 100, import_all_select_source = false, -- if false will avoid organizing imports always_organize_imports = false, -- filter diagnostics filter_out_diagnostics_by_severity = {}, filter_out_diagnostics_by_code = {}, -- inlay hints auto_inlay_hints = true, inlay_hints_highlight = 'Comment', inlay_hints_priority = 200, -- priority of the hint extmarks inlay_hints_throttle = 150, -- throttle the inlay hint request inlay_hints_format = { -- format options for individual hint kind Type = {}, Parameter = {}, Enum = {}, -- Example format customization for `Type` kind: -- Type = { -- highlight = "Comment", -- text = function(text) -- return "->" .. text:sub(2) -- end, -- }, }, -- update imports on file move update_imports_on_move = false, require_confirmation_on_move = true, watch_dir = nil, }) -- required to fix code action ranges and filter diagnostics ts_utils.setup_client(client) end M.init_options = require('nvim-lsp-ts-utils').init_options return M
local scene = {} scene.state = {} function scene:__exit() if self.state.onExit then self.state:onExit() end end function scene:__load() if self.state.onLoad then self.state:onLoad() end end function scene:setScene(s) self:__exit() self.state = nil collectgarbage("collect") self.state = require(s) self.current = s self:__load() end function scene:reload() self:__exit() self.state = nil collectgarbage("collect") self.state = require(self.lib) self:__load() end local mt = { __index = function(table, key) if table.state[key] then return table.state[key] end end } setmetatable(scene, mt) return scene
object_draft_schematic_weapon_loot_heartstriker = object_draft_schematic_weapon_shared_loot_heartstriker:new { } ObjectTemplates:addTemplate(object_draft_schematic_weapon_loot_heartstriker, "object/draft_schematic/weapon/loot_heartstriker.iff")
local function setup() local has_packer, packer = pcall(require, 'packer') if not has_packer then error('Expected packer to be installed') end vim.keymap.set('n', '<leader>Pc', packer.compile) vim.keymap.set('n', '<leader>PC', packer.clean) vim.keymap.set('n', '<leader>Pi', packer.install) vim.keymap.set('n', '<leader>PI', packer.install) vim.keymap.set('n', '<leader>Pu', packer.update) vim.keymap.set('n', '<leader>PU', packer.update) vim.keymap.set('n', '<leader>Ps', packer.status) vim.keymap.set('n', '<leader>PS', function () packer.snapshot(os.date('!%Y-%m-%d_%T')) packer.sync() end) end return { setup = setup }
--[[ Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]] local addslap = {} local mattata = require('mattata') local redis = require('libs.redis') function addslap:init() addslap.commands = mattata.commands(self.info.username):command('addslap').table addslap.help = '/addslap <slap> - Adds a new slap to /slap. Slaps must only contain letters, numbers, hyphens, underscores, commands, forward slashes or full stops. Use the placeholders {ME} for the person slapping, and {THEM} for the person being slapped. An example would be: {ME} threw {THEM} into a house fire. Slaps can be no longer than 256 characters long, but there is currently no limit to how many you can add. This feature is in beta, and there is currently no way to delete a slap you add - this will be added later. If you want to delete yours, send a PM to @wrxck.' end function addslap.on_message(_, message, _, language) if message.chat.type == 'private' then return mattata.send_reply(message, language['addslap']['1']) elseif not mattata.is_group_admin(message.chat.id, message.from.id) then return mattata.send_reply(message, language.errors.admin) end local input = mattata.input(message.text) if not input then return mattata.send_reply(message, addslap.help) elseif not input:match('{ME}') or not input:match('{THEM}') then return mattata.send_reply(message, language['addslap']['5']) end local valid = input:gsub('{ME}', ''):gsub('{THEM}', '') if valid:match('[{}]') then return mattata.send_reply(message, language['addslap']['2']) elseif input:len() > 256 then return mattata.send_reply(message, language['addslap']['3']) end redis:sadd('slaps:' .. message.chat.id, input) return mattata.send_reply(message, language['addslap']['4']) end return addslap
local gameOver = {} local Gamestate = require "hump.gamestate" local game local score local debug function gameOver:enter(previous, newScore) score = newScore game = previous end --there are better ways to line that up function gameOver:draw() love.graphics.print("Your score : " .. score, 300, 200) love.graphics.print("Retry", 350, 300) love.graphics.print("Menu", 355, 400) end function gameOver:mousepressed(x, y, button) if button == "l" then if(x >= 350 and y >= 300 and x < 425 and y < 325) then Gamestate.switch(game) end if(x >= 355 and y >= 400 and x < 425 and y < 425) then Gamestate.switch(menu) end end end return gameOver
-- simpleButtons: provides various functions for UI pieces: -- enables pieces to be initialized with defaults -- manages how pieces look and behave simpleButtons = {} simpleButtons.standardLineHeight = function() pushStyle() textWrapWidth(0) _, lineHeight = textSize("ABCDEFGHIJKLMNOPQRSTUVWXYZ") popStyle() return lineHeight end simpleButtons.buttonDimensionsFor = function(thisText) local boundsW, boundsH = textSize(thisText) lineHeight = simpleButtons.standardLineHeight() boundsW = boundsW + (lineHeight * 1.8) boundsH = boundsH + lineHeight return boundsW, boundsH end simpleButtons.baseFontSize = math.max(WIDTH, HEIGHT) * 0.027 simpleButtons.cornerRadius = simpleButtons.baseFontSize * 1.25 simpleButtons.marginPaddingH = simpleButtons.baseFontSize * 0.5 simpleButtons.marginPaddingW = simpleButtons.baseFontSize simpleButtons.ui = {} simpleButtons.useGrid = false simpleButtons.gridSize = 15 simpleButtons.secondLineInfoFrom = function(traceback) local iterator = string.gmatch(traceback,"(%g*):(%g*): in function '(%g*)'") iterator() -- not interested in first line bc it'll always be from here local tab, lineNumber, functionName = iterator() return {tab = tab, functionName = functionName, lineNumber = functionName, all = tab..","..functionName..","..lineNumber} end parameter.boolean("buttons are draggable", false) parameter.boolean("snap_to_grid", false, function() simpleButtons.useGrid = snap_to_grid end) simpleButtons.defaultButton = function(bText, traceback) simpleButtons.ui[traceback] = {text=bText, x=0.5, y=0.5, action=simpleButtons.defaultButtonAction} return simpleButtons.ui[traceback] end simpleButtons.defaultButtonAction = function() print("this is the default button action") end simpleButtons.doAction = function(traceback) if simpleButtons.ui[traceback].action == nil then return else simpleButtons.ui[traceback].action() end end simpleButtons.clearRenderFlags = function() for _, ui in pairs(simpleButtons.ui) do ui.didRenderAlready = false --now see if rendering is triggered at the right time end end --evaluateTouchFor: called by each button inside the button() function --precondition: to use CurrentTouch, pass nothing to the touch value --postcondition: one of these: -- a new activatedButton is set (if touch began on this piece) -- activatedButton has been cleared (touch ended) -- a button tap has occurred (for detecting button presses in editable mode) -- a button has been moved (activatedButton was dragged in editable mode) -- nothing (this piece did not interact with the touch) simpleButtons.evaluateTouchFor = function(traceback, touch) if touch == nil then touch = CurrentTouch end if simpleButtons.thisButtonIsActivated(traceback, touch) then simpleButtons.makeActivatedButtonRespond(traceback, touch) end end --thisButtonIsActivated: called to decide if this button should respond to this touch --precondition: name and touch cannot be nil --postconditions: -- activatedButton has been set or unchanged (note that it is never cleared here) -- boolean returned true if the given button is the activatedButton, false if not simpleButtons.thisButtonIsActivated = function(traceback, touch) --if there is already an activatedButton and this isn't it, return false if activatedButton ~= nil and activatedButton ~= traceback then return false end --if there is no activatedButton, see if this should become activatedButton if activatedButton == nil then --if touch state is BEGAN and touch is inside button, set it to activatedButton if touch.state == BEGAN and simpleButtons.touchIsInside(traceback, touch) then activatedButton = traceback else --otherwise return false return false end end --here only reached if this is activated button (or has become it), so return true return true end --simpleButtons.touchIsInside: calculated using touch's distance from this piece --preconditions: name and touch cannot be nil, and touched object is basically rectangular simpleButtons.touchIsInside = function(traceback, touch) local adjX, adjY = simpleButtons.ui[traceback].x*WIDTH, simpleButtons.ui[traceback].y*HEIGHT local xDistance = math.abs(touch.x-adjX) local yDistance = math.abs(touch.y-adjY) insideX = xDistance < simpleButtons.ui[traceback].width /2 insideY = yDistance < simpleButtons.ui[traceback].height /2 if insideX and insideY then return true else return false end end --makeActivatedButtonRespond: decide how the given button should react to given touch --precondition: button and touch cannot be nil, button must be activatedButton simpleButtons.makeActivatedButtonRespond = function(traceback, touch) --move button if it should be moved if buttons_are_draggable then simpleButtons.evaluateDrag(traceback, touch) end if touch.state == BEGAN or touch.state == MOVING then simpleButtons.ui[traceback].isTapped = true end --if this is an end touch, do a button action, or save new position, or do nothing if touch.state == ENDED or touch.state == CANCELLED or not touch then if buttons_are_draggable then if touch.tapCount == 1 then simpleButtons.ui[traceback].isTapped = true simpleButtons.doAction(traceback) else simpleButtons.savePositions() end elseif simpleButtons.touchIsInside(traceback, touch) then simpleButtons.ui[traceback].isTapped = true simpleButtons.doAction(traceback) end activatedButton = nil end end simpleButtons.evaluateDrag = function (traceback, touch) if touch.state == MOVING then local x,y = touch.x, touch.y --make x and y into percentages of width and height x, y = x / WIDTH, y/HEIGHT --rounds x and y if using grid if simpleButtons.useGrid then local divisions = 40 local gridW, gridH = WIDTH / divisions, HEIGHT / divisions x = touch.x + simpleButtons.gridSize - (touch.x + simpleButtons.gridSize) % (simpleButtons.gridSize * 2) y = touch.y + simpleButtons.gridSize - (touch.y + simpleButtons.gridSize) % (simpleButtons.gridSize * 2) end simpleButtons.ui[traceback].x = x simpleButtons.ui[traceback].y = y end end simpleButtons.savePositions = function () --[[ --old method for writing buttons at the bottom of this tab --required this line to be put between code and button tables: --#*@savedButtonTablesWillBeWrittenAfterHere local temp=readProjectTab("SimpleButtons") dataString = "" local dividerString = "--#*@savedButtonTables" dividerString = dividerString.."WillBeWrittenAfterHere" local pos, term=string.find(temp,dividerString) if pos~=nil then local str=string.sub(temp,1,term) dataString = dataString..str.."\n\n\n" end ]] local dataString = "" for traceback, ui in pairs(simpleButtons.ui) do dataString = dataString.."simpleButtons.ui[ [["..traceback.."]] ] = \n" dataString = dataString.." {text = [["..ui.text.."]],\n" dataString = dataString.." x = "..ui.x dataString = dataString..", y = "..ui.y..",\n" dataString = dataString.." action = simpleButtons.defaultButtonAction\n}\n\n" end saveProjectTab("ButtonTables",dataString) end --button only actually needs a name to work, the rest have defaults function button(bText, action, width, height, fontColor, x, y, specTable) --get traceback info --buttons have to be indexed by traceback --this lets different buttons have the same texts local trace = simpleButtons.secondLineInfoFrom(debug.traceback()) --check for existing table matching key local tableToDraw = simpleButtons.ui[trace.all] --reject the table if the text doesn't match, though if tableToDraw and tableToDraw.text ~= bText then -- print("found table from trace but text doesn't match "..'"'..bText..'"') --store table that was found under a modified key, so table doesn't get overwritten local newKey = trace.all.."+"..tableToDraw.text simpleButtons.ui[newKey] = tableToDraw tableToDraw = nil end --if there's no matching table look for an identical one if not tableToDraw then --Make a function to replace any identical table found function setTableToDrawUsingNewId(newId, tableToUpdate, oldId) --update table to use new traceback id simpleButtons.ui[newId] = tableToUpdate --clear the old traceback id simpleButtons.ui[oldId] = nil --and set this as tableToDraw tableToDraw = simpleButtons.ui[newId] end --find any buttons that match text -- print("finding buttons with text: "..bText) local textMatches = {} for k, buttonTable in pairs(simpleButtons.ui) do if buttonTable.text == bText then if type(k) == "string" then table.insert(textMatches, buttonTable) --add table's key to table (won't be stored permanently, so no worries) buttonTable.key = k -- print("button matches text:") -- print(buttonTable.x) else -- print("found key that's not a string: ", k) end end end -- print("found "..#textMatches.." with same text") --if only 1 button matches text, use its values but replace its key if #textMatches == 1 then setTableToDrawUsingNewId(trace.all, textMatches[1], textMatches[1].key) --if more than one button matches text elseif #textMatches > 1 then --find out how many match this tab and function --print("finding matches for tab and function: "..trace.tab..", "..trace.functionName) local matchers = {} for _, buttonTable in ipairs(textMatches) do --extract the tab and functiom local tab, functionName = string.gmatch(buttonTable.key,"(%g*),(%g*),")() -- print(buttonTable.text) -- print("extracted: ", tab, ", ",functionName) -- print("current: ", trace.tab, ", ", trace.functionName) --compare to current if tab == trace.tab and functionName == trace.functionName then --store matches -- print("storing match") table.insert(matchers, buttonTable) end end --if only 1 button matches tab and function and text, use it if #matchers == 1 then -- print("only one match, should use found values") setTableToDrawUsingNewId(trace.all, matchers[1], matchers[1].key) --if more than one button matches tab and function and text elseif #matchers > 1 then -- print("more than one match, have to guess!") --just gonna have to guess! --find the first one without an 'assigned' value for _, buttonTable in ipairs(matchers) do if not buttonTable.assigned then --update it to use *this* traceback id setTableToDrawUsingNewId(trace.all, buttonTable, buttonTable.key) --mark it 'assigned' simpleButtons[trace.all].assigned = true end end else -- print("no buttons match text, tab, and function") end end else -- print("found table to draw") -- print(tableToDraw.x) end --if there's still not a tableToDraw, make a new one if not tableToDraw or tableToDraw.text ~= bText then tableToDraw = simpleButtons.defaultButton(bText, trace.all) end tableToDraw.specTable = specTable --if x and y were explicitly stated, they should be ordinary numbers --so make them into percentages if x then x = x/WIDTH end if y then y = y/HEIGHT end --get the bounds of the button text if any dimension is undefined local boundsW, boundsH, lineHeight if width == nil or height == nil then boundsW, boundsH = textSize(bText) _, lineHeight = textSize("ABCDEFGHIJKLMNOPQRSTUVWXYZ") end width = width or boundsW + (simpleButtons.marginPaddingW * 2) height = height or boundsH + (simpleButtons.marginPaddingH * 2) --set empty specTable if none specTable = specTable or {} --set button drawing values, using saved values if none passed in --the saved values should already be percentages local x,y = x or tableToDraw.x, y or tableToDraw.y --update the stored values if necessary if x ~= tableToDraw.x then simpleButtons.ui[trace.all].x = x end if y ~= tableToDraw.y then simpleButtons.ui[trace.all].y = y end if width ~= tableToDraw.width then simpleButtons.ui[trace.all].width = width end if height ~= tableToDraw.height then simpleButtons.ui[trace.all].height = height end --can't use fill() as font color so default to white fontColor = fontColor or color(255) --'action' is called outside of this function if action then simpleButtons.ui[trace.all].action = action end --get the actual x and y from the percentages x, y = x*WIDTH, y*HEIGHT pushStyle() local startingFill = color(fill()) if tableToDraw.isTapped == true and not specTable.isWindow then fill(fontColor) stroke(startingFill) end local radius = simpleButtons.cornerRadius --draw the button roundedRectangle{ x=x,y=y,w=width,h=height, radius=radius } --draw the text if tableToDraw.isTapped == true then fill(startingFill) else fill(fontColor) end text(bText, x, y) popStyle() simpleButtons.ui[trace.all].isTapped = false --handle touches (wherein action gets called or not) simpleButtons.evaluateTouchFor(trace.all) --set the flag that shows we rendered (used with blurring) simpleButtons.ui[trace.all].didRenderAlready = true return simpleButtons.ui[trace.all] end --[[ true mesh rounded rectangle. Original by @LoopSpace with anti-aliasing, optional fill and stroke components, optional texture that preserves aspect ratio of original image, automatic mesh caching usage: RoundedRectangle{key = arg, key2 = arg2} required: x;y;w;h: dimensions of the rectangle optional: radius: corner rounding radius, defaults to 6; corners: bitwise flag indicating which corners to round, defaults to 15 (all corners). Corners are numbered 1,2,4,8 starting in lower-left corner proceeding clockwise eg to round the two bottom corners use: 1 | 8 to round all the corners except the top-left use: ~ 2 tex: texture image texCoord: vec4 specifying x,y,width,and height to use as texture coordinates scale: size of rect (using scale) use standard fill(), stroke(), strokeWidth() to set body fill color, outline stroke color and stroke width ]] local __RRects = {} function roundedRectangle(t) local s = t.radius or 8 local c = t.corners or 15 local w = math.max(t.w+1,2*s)+1 local h = math.max(t.h,2*s)+2 local hasTexture = 0 local texCoord = t.texCoord or vec4(0,0,1,1) --default to bottom-left-most corner, full with and height if t.tex then hasTexture = 1 end local label = table.concat({w,h,s,c,hasTexture,texCoord.x,texCoord.y},",") if not __RRects[label] then local rr = mesh() rr.shader = shader(rrectshad.vert, rrectshad.frag) local v = {} local no = {} local n = math.max(3, s//2) local o,dx,dy local edge, cent = vec3(0,0,1), vec3(0,0,0) for j = 1,4 do dx = 1 - 2*(((j+1)//2)%2) dy = -1 + 2*((j//2)%2) o = vec2(dx * (w * 0.5 - s), dy * (h * 0.5 - s)) -- if math.floor(c/2^(j-1))%2 == 0 then local bit = 2^(j-1) if c & bit == bit then for i = 1,n do v[#v+1] = o v[#v+1] = o + vec2(dx * s * math.cos((i-1) * math.pi/(2*n)), dy * s * math.sin((i-1) * math.pi/(2*n))) v[#v+1] = o + vec2(dx * s * math.cos(i * math.pi/(2*n)), dy * s * math.sin(i * math.pi/(2*n))) no[#no+1] = cent no[#no+1] = edge no[#no+1] = edge end else v[#v+1] = o v[#v+1] = o + vec2(dx * s,0) v[#v+1] = o + vec2(dx * s,dy * s) v[#v+1] = o v[#v+1] = o + vec2(0,dy * s) v[#v+1] = o + vec2(dx * s,dy * s) local new = {cent, edge, edge, cent, edge, edge} for i=1,#new do no[#no+1] = new[i] end end end -- print("vertices", #v) -- r = (#v/6)+1 rr.vertices = v rr:addRect(0,0,w-2*s,h-2*s) rr:addRect(0,(h-s)/2,w-2*s,s) rr:addRect(0,-(h-s)/2,w-2*s,s) rr:addRect(-(w-s)/2, 0, s, h - 2*s) rr:addRect((w-s)/2, 0, s, h - 2*s) --mark edges local new = {cent,cent,cent, cent,cent,cent, edge,cent,cent, edge,cent,edge, cent,edge,edge, cent,edge,cent, edge,edge,cent, edge,cent,cent, cent,cent,edge, cent,edge,edge} for i=1,#new do no[#no+1] = new[i] end rr.normals = no --texture if true==false then if t.tex then rr.shader.fragmentProgram = rrectshad.fragTex rr.texture = t.tex local w,h = t.tex.width,t.tex.height local textureOffsetX,textureOffsetY = texCoord.x,texCoord.y local coordTable = {} for i,v in ipairs(rr.vertices) do coordTable[i] = vec2((v.x + textureOffsetX)/w, (v.y + textureOffsetY)/h) end rr.texCoords = coordTable end end local sc = 1/math.max(2, s) rr.shader.scale = sc --set the scale, so that we get consistent one pixel anti-aliasing, regardless of size of corners __RRects[label] = rr end __RRects[label].shader.fillColor = color(fill()) if strokeWidth() == 0 then __RRects[label].shader.strokeColor = color(fill()) else __RRects[label].shader.strokeColor = color(stroke()) end if t.resetTex then __RRects[label].texture = t.resetTex t.resetTex = nil end local sc = 0.25/math.max(2, s) __RRects[label].shader.strokeWidth = math.min( 1 - sc*3, strokeWidth() * sc) pushMatrix() translate(t.x,t.y) scale(t.scale or 1) __RRects[label]:draw() popMatrix() end rrectshad ={ vert=[[ uniform mat4 modelViewProjection; attribute vec4 position; //attribute vec4 color; attribute vec2 texCoord; attribute vec3 normal; //varying lowp vec4 vColor; varying highp vec2 vTexCoord; varying vec3 vNormal; void main() { // vColor = color; vTexCoord = texCoord; vNormal = normal; gl_Position = modelViewProjection * position; } ]], frag=[[ precision highp float; uniform lowp vec4 fillColor; uniform lowp vec4 strokeColor; uniform float scale; uniform float strokeWidth; //varying lowp vec4 vColor; varying highp vec2 vTexCoord; varying vec3 vNormal; void main() { lowp vec4 col = mix(strokeColor, fillColor, smoothstep((1. - strokeWidth) - scale * 0.5, (1. - strokeWidth) - scale * 1.5 , vNormal.z)); //0.95, 0.92, col = mix(vec4(col.rgb, 0.), col, smoothstep(1., 1.-scale, vNormal.z) ); // col *= smoothstep(1., 1.-scale, vNormal.z); gl_FragColor = col; } ]], fragTex=[[ precision highp float; uniform lowp sampler2D texture; uniform lowp vec4 fillColor; uniform lowp vec4 strokeColor; uniform float scale; uniform float strokeWidth; //varying lowp vec4 vColor; varying highp vec2 vTexCoord; varying vec3 vNormal; void main() { vec4 pixel = texture2D(texture, vTexCoord) * fillColor; lowp vec4 col = mix(strokeColor, pixel, smoothstep(1. - strokeWidth - scale * 0.5, 1. - strokeWidth - scale * 1.5, vNormal.z)); //0.95, 0.92, // col = mix(vec4(0.), col, smoothstep(1., 1.-scale, vNormal.z) ); col *= smoothstep(1., 1.-scale, vNormal.z); gl_FragColor = col; } ]] }
local json = require 'dkjson' local output_helper = require 'nginx-metrix.output.helper' local namespaces = require 'nginx-metrix.storage.namespaces' local collectors = require 'nginx-metrix.collectors' local lust = require 'Lust' local get_vhosts_json = function(vhosts) return json.encode(vhosts:totable()) end local get_stats_json = function(vhosts) local stats = {} vhosts:each(function(vhost) namespaces.activate(vhost) stats[vhost] = collectors.all:reduce( function(collectors_stats, collector) if is.callable(collector.get_raw_stats) then collectors_stats[collector.name] = collector:get_raw_stats():tomap() end return collectors_stats end, {} ) stats[vhost].vhost = vhost namespaces.reset_active() end) if vhosts:length() == 1 then stats = stats[vhosts:head()] or {} end stats['service'] = 'nginx-metrix' return json.encode(stats) end local get_vhosts_text = function(vhosts) return vhosts:reduce( function(str, vhost) return str .. "\n\t- " .. vhost end, 'vhosts:' ) end local get_stats_text = function(vhosts) local text = output_helper.text local stats = vhosts:reduce( function(stats, vhost) namespaces.activate(vhost) stats = collectors.all:reduce( function(collector_stats, collector) if is.callable(collector.get_text_stats) then collector_stats = collector_stats .. text.section_template(collector:get_text_stats(text)):gen { namespace = vhost, collector = collector.name } end return collector_stats end, stats ) namespaces.reset_active() return stats end, '' ) return text.header() .. stats end local get_vhosts_html = function(vhosts) return output_helper.html.page_template(output_helper.html.section_template(lust { [[<ul class="list-group">@map{ vhost=vhosts }:{{<li class="list-group-item">$vhost</li>}}</ul>]] }:gen { vhosts = vhosts:totable() }):gen { name = 'vhosts' }):gen {} end local get_stats_html = function(vhosts) local is_many_vhosts = vhosts:length() > 1 local html = output_helper.html local content = vhosts:reduce( function(vhost_stats, vhost) namespaces.activate(vhost) local collectors_stats = collectors.all:reduce( function(collector_stats, collector) if is.callable(collector.get_html_stats) then collector_stats = collector_stats .. collector:get_html_stats(html) end return collector_stats end, '' ) if is_many_vhosts then collectors_stats = html.section_template(collectors_stats):gen { name = vhost, class = 'primary' } end namespaces.reset_active() return vhost_stats .. collectors_stats end, '' ) return html.page_template(content):gen {} end local render_vhosts = function(vhosts) local format = output_helper.get_format() if format == 'json' then return get_vhosts_json(vhosts) end if format == 'text' then return get_vhosts_text(vhosts) end if format == 'html' then return get_vhosts_html(vhosts) end end local render_stats = function(vhosts) local format = output_helper.get_format() if format == 'json' then return get_stats_json(vhosts) end if format == 'text' then return get_stats_text(vhosts) end if format == 'html' then return get_stats_html(vhosts) end end local filter_vhosts = function(vhosts, filter) vhosts = iter(vhosts) if filter then local filter_func if type(filter) == 'string' then filter_func = function(vhost) return vhost:match(filter) end elseif type(filter) == 'table' then filter_func = function(vhost) return index(vhost, filter) ~= nil end elseif type(filter) == 'function' then filter_func = filter else filter_func = function() return true end end vhosts = vhosts:filter(filter_func) end return vhosts end local render = function(options) local vhosts = filter_vhosts(namespaces.list(), options.vhosts_filter) local content if ngx.req.get_uri_args().list_vhosts ~= nil then content = render_vhosts(vhosts) else if ngx.req.get_uri_args().vhost ~= nil then vhosts = filter_vhosts(vhosts, '^' .. ngx.req.get_uri_args().vhost:gsub("([().%+-*?[^$])", "[%1]") .. '$') end content = render_stats(vhosts) end output_helper.set_content_type_header() ngx.say(content) end -------------------------------------------------------------------------------- -- EXPORTS -------------------------------------------------------------------------------- local exports = {} exports.render = render if __TEST__ then exports.__private__ = { get_vhosts_json = get_vhosts_json, get_stats_json = get_stats_json, get_vhosts_text = get_vhosts_text, get_stats_text = get_stats_text, get_vhosts_html = get_vhosts_html, get_stats_html = get_stats_html, filter_vhosts = filter_vhosts, render_vhosts = render_vhosts, render_stats = render_stats, } end return exports
ITEM.name = "Doorbust Charge" ITEM.model = "models/props_c17/consolebox05a.mdl" ITEM.width = 1 ITEM.height = 1 ITEM.price = 25 ITEM.desc = "doorChargeDesc" -- You can use hunger table? i guess? ITEM.functions = ITEM.functions or {} ITEM.functions.throw = { name = "Charge", tip = "useTip", icon = "icon16/brick.png", onRun = function(item) local client = item.player local data = {} data.start = client:GetShootPos() data.endpos = data.start + client:GetAimVector()*96 data.filter = client local trace = util.TraceLine(data) local target = trace.Entity if (IsValid(client)) then local char = client:getChar() local class = char:getClass() local classData = nut.class.list[class] if (!classData.law) then client:notifyLocalized("notLaw") return false end end local auth = hook.Run("CanUseDoorbust", client, target) if (auth == false) then return false end if (IsValid(target) and (target:isDoor() or target.fadeActivate)) then local ent = ents.Create("nut_dcharge") local angles = trace.HitNormal:Angle() local axis = Angle(angles[1], angles[2], angles[3]) angles:RotateAroundAxis(axis:Right(), 90) ent:SetParent(target) ent:SetPos(trace.HitPos + trace.HitNormal * 3) ent:SetAngles(angles) ent:Spawn() ent:Activate() ent:ManipulateBoneScale(0, Vector(1, 1, 1)*.5) return true end return false end, }
local core = require 'core.document-symbol' local files = require 'files' local define = require 'proto.define' rawset(_G, 'TEST', true) local EXISTS = {} local function eq(a, b) if a == EXISTS and b ~= nil then return true end local tp1, tp2 = type(a), type(b) if tp1 ~= tp2 then return false end if tp1 == 'table' then local mark = {} for k in pairs(a) do if not eq(a[k], b[k]) then return false end mark[k] = true end for k in pairs(b) do if not mark[k] then return false end end return true end return a == b end local function checkArcoss(symbols) local lastFinish = 0 for _, symbol in ipairs(symbols) do assert(symbol.range[1] <= symbol.selectionRange[1]) assert(symbol.range[2] >= symbol.selectionRange[2]) assert(symbol.range[2] > lastFinish) lastFinish = symbol.range[2] if symbol.children then checkArcoss(symbol.children) end end end function TEST(script) return function (expect) files.removeAll() files.setText('', script) local result = core('') assert(eq(expect, result)) checkArcoss(result) end end TEST [[ A = 1 ]] { [1] = { name = 'A', detail = 'global number = 1', kind = define.SymbolKind.Class, range = {0, 5}, selectionRange = {0, 1}, } } TEST [[ local function f() end ]] { [1] = { name = 'f', detail = 'function ()', kind = define.SymbolKind.Function, range = {6, 10003}, selectionRange = {15, 16}, valueRange = {6, 10003}, } } TEST [[ function f() end ]] { [1] = { name = 'f', detail = 'function ()', kind = define.SymbolKind.Function, range = {0, 10003}, selectionRange = {9, 10}, valueRange = {0, 10003}, } } TEST [[ return function () end ]] { [1] = { name = '', detail = 'return function ()', kind = define.SymbolKind.Function, range = {7, 10003}, selectionRange = {7, 15}, valueRange = {7, 10003}, } } TEST [[ f = function () end ]] { [1] = { name = 'f', detail = 'function ()', kind = define.SymbolKind.Function, range = {0, 10003}, selectionRange = {0, 1}, valueRange = {4, 10003}, } } TEST [[ local f = function () end ]] { [1] = { name = 'f', detail = 'function ()', kind = define.SymbolKind.Function, range = {6, 10003}, selectionRange = {6, 7}, valueRange = {10, 10003}, } } TEST [[ function mt:add() end ]] { [1] = { name = 'mt:add', detail = 'function ()', kind = define.SymbolKind.Method, range = {0, 10003}, selectionRange = {9, 15}, valueRange = {0, 10003}, } } TEST [[ function A() function A1() end function A2() end end function B() end ]] { [1] = { name = 'A', detail = 'function ()', kind = define.SymbolKind.Function, range = {0, 50003}, selectionRange = {9, 10}, valueRange = {0, 50003}, children = { [1] = { name = 'A1', detail = 'function ()', kind = define.SymbolKind.Function, range = {10004, 20007}, selectionRange = {10013, 10015}, valueRange = {10004, 20007}, }, [2] = { name = 'A2', detail = 'function ()', kind = define.SymbolKind.Function, range = {30004, 40007}, selectionRange = {30013, 30015}, valueRange = {30004, 40007}, }, }, }, [2] = { name = 'B', detail = 'function ()', kind = define.SymbolKind.Function, range = {60000, 70003}, selectionRange = {60009, 60010}, valueRange = {60000, 70003}, }, } TEST [[ local x = 1 local function f() local x = 'x' local y = {} --= 1 end local y = true local z ]] { [1] = { name = 'x', detail = 'local number = 1', kind = define.SymbolKind.Variable, range = {6, 11}, selectionRange = {6, 7}, }, [2] = { name = 'f', detail = 'function ()', kind = define.SymbolKind.Function, range = {10006, 50003}, selectionRange = {10015, 10016}, valueRange = {10006, 50003}, children = { [1] = { name = 'x', detail = 'local string = "x"', kind = define.SymbolKind.Variable, range = {20010, 20017}, selectionRange = {20010, 20011}, }, [2] = { name = 'y', detail = 'local {}', kind = define.SymbolKind.Variable, range = {30010, 30016}, selectionRange = {30010, 30011}, valueRange = {30014, 30016}, }, --[3] = { -- name = 'z', -- detail = 'global z: number = 1', -- kind = define.SymbolKind.Object, -- range = {71, 71}, -- selectionRange = {71, 71}, -- valueRange = {75, 75}, --}, }, }, [3] = { name = 'y', detail = 'local boolean = true', kind = define.SymbolKind.Variable, range = {60006, 60014}, selectionRange = {60006, 60007}, }, [4] = { name = 'z', detail = 'local', kind = define.SymbolKind.Variable, range = {70006, 70007}, selectionRange = {70006, 70007}, }, } TEST [[ local t = { a = 1, b = 2, c = 3, } ]] { [1] = { name = 't', detail = 'local {a, b, c}', kind = define.SymbolKind.Variable, range = {6, 40001}, selectionRange = {6, 7}, valueRange = {10, 40001}, children = { [1] = { name = 'a', detail = 'field number = 1', kind = define.SymbolKind.Property, range = {10004, 10009}, selectionRange = {10004, 10005}, }, [2] = { name = 'b', detail = 'field number = 2', kind = define.SymbolKind.Property, range = {20004, 20009}, selectionRange = {20004, 20005}, }, [3] = { name = 'c', detail = 'field number = 3', kind = define.SymbolKind.Property, range = {30004, 30009}, selectionRange = {30004, 30005}, }, } } } TEST [[ local t = { a = { b = 1, } } ]] { [1] = { name = 't', detail = 'local {a}', kind = define.SymbolKind.Variable, range = {6, 40001}, selectionRange = {6, 7}, valueRange = {10, 40001}, children = { [1] = { name = 'a', detail = 'field {b}', kind = define.SymbolKind.Property, range = {10004, 30005}, selectionRange = {10004, 10005}, valueRange = {10008, 30005}, children = { [1] = { name = 'b', detail = EXISTS, kind = define.SymbolKind.Property, range = {20008, 20013}, selectionRange = {20008, 20009}, } } }, } } } TEST[[ local function g() end g = 1 ]]{ [1] = { name = 'g', detail = 'function ()', kind = define.SymbolKind.Function, range = {6, 10003}, selectionRange = {15, 16}, valueRange = {6, 10003}, }, [2] = { name = 'g', detail = 'setlocal number = 1', kind = define.SymbolKind.Variable, range = {30000, 30005}, selectionRange = {30000, 30001}, } } TEST[[ function f(a, b, ...) local x = ... print(x.a) end ]]{ [1] = { name = 'f', detail = 'function (a, b, ...)', kind = define.SymbolKind.Function, range = {0, 30003}, selectionRange = {9, 10}, valueRange = {0, 30003}, children = { [1] = { name = 'a', detail = 'param', kind = define.SymbolKind.Constant, range = {11, 12}, selectionRange = {11, 12}, }, [2] = { name = 'b', detail = 'param', kind = define.SymbolKind.Constant, range = {14, 15}, selectionRange = {14, 15}, }, [3] = { name = 'x', detail = 'local', kind = define.SymbolKind.Variable, range = {10010, 10017}, selectionRange = {10010, 10011}, } } }, } TEST [[ local t = { a = 1, b = 2, } local v = t ]]{ [1] = { name = 't', detail = 'local {a, b}', kind = define.SymbolKind.Variable, range = {6, 30001}, selectionRange = {6, 7}, valueRange = {10, 30001}, children = EXISTS, }, [2] = { name = 'v', detail = 'local', kind = define.SymbolKind.Variable, range = {50006, 50011}, selectionRange = {50006, 50007}, }, } TEST [[ local x local function ]]{ [1] = { name = 'x', detail = 'local', kind = define.SymbolKind.Variable, range = {6, 7}, selectionRange = {6, 7}, }, [2] = { name = "", detail = "function ()", kind = 12, range = {10006, 10014}, selectionRange = {10006, 10014}, valueRange = {10006, 10014}, }, } TEST [[ local a, b = { x1 = 1, y1 = 1, z1 = 1, }, { x2 = 1, y2= 1, z2 = 1, } ]]{ [1] = { name = 'a', detail = 'local {x1, y1, z1}', kind = define.SymbolKind.Variable, range = {6, 40001}, selectionRange = {6, 7}, valueRange = {13, 40001}, children = EXISTS, }, [2] = { name = 'b', detail = 'local {x2, y2, z2}', kind = define.SymbolKind.Variable, range = {9, 80001}, selectionRange = {9, 10}, valueRange = {40003, 80001}, children = EXISTS, } } TEST [[ local function x() end local function f() local c end ]] { [1] = { name = 'x', detail = 'function ()', kind = define.SymbolKind.Function, range = {6, 10003}, selectionRange = {15, 16}, valueRange = {6, 10003}, }, [2] = { name = 'f', detail = 'function ()', kind = define.SymbolKind.Function, range = {30006, 50003}, selectionRange = {30015, 30016}, valueRange = {30006, 50003}, children = { [1] = { name = 'c', detail = 'local', kind = define.SymbolKind.Variable, range = {40010, 40011}, selectionRange = {40010, 40011}, }, }, } } TEST [[ local t = f({ k = 1 }) ]] { [1] = { name = 't', detail = 'local', kind = define.SymbolKind.Variable, range = {6, 20002}, selectionRange = {6, 7}, valueRange = {10, 20002}, children = { [1] = { name = 'k', detail = 'field number = 1', kind = define.SymbolKind.Property, range = {10004, 10009}, selectionRange = {10004, 10005}, } } } } TEST [[ local t = {} local function f(a, b) end ]] { [1] = { name = 't', detail = 'local {}', kind = define.SymbolKind.Variable, range = {6, 12}, selectionRange = {6, 7}, valueRange = {10, 12}, }, [2] = { name = 'f', detail = 'function (a, b)', kind = define.SymbolKind.Function, range = {20006, 30003}, selectionRange = {20015, 20016}, valueRange = {20006, 30003}, children = { [1] = { name = 'a', detail = 'param', kind = define.SymbolKind.Constant, range = {20017, 20018}, selectionRange = {20017, 20018}, }, [2] = { name = 'b', detail = 'param', kind = define.SymbolKind.Constant, range = {20020, 20021}, selectionRange = {20020, 20021}, } } } } TEST [[ local a = f { x = function () end } ]] { [1] = { name = 'a', detail = 'local', kind = define.SymbolKind.Variable, range = {6, 30001}, selectionRange = {6, 7}, valueRange = {10, 30001}, children = { [1] = { name = 'x', detail = 'function ()', kind = define.SymbolKind.Function, range = {10004, 20007}, selectionRange = {10004, 10005}, valueRange = {10008, 20007}, } } } } TEST [[ table.sort(t, function (a, b) return false end) ]] { [1] = { name = '', detail = 'table.sort -> function (a, b)', kind = define.SymbolKind.Function, range = {14, 20003}, selectionRange = {14, 22}, valueRange = {14, 20003}, children = EXISTS, } } TEST [[ local root = { inner_function = function () local function function_inside_function() end end } ]] { [1] = { name = 'root', detail = 'local {inner_function}', kind = define.SymbolKind.Variable, range = {6, 50001}, selectionRange = {6, 10}, valueRange = {13, 50001}, children = { [1] = { name = 'inner_function', detail = 'function ()', kind = define.SymbolKind.Function, range = {10004, 40007}, selectionRange = {10004, 10018}, valueRange = {10021, 40007}, children = { [1] = { name = 'function_inside_function', detail = 'function ()', kind = define.SymbolKind.Function, range = {20014, 30011}, selectionRange = {20023, 20047}, valueRange = {20014, 30011}, }, }, }, }, } }
if not modules then modules = { } end modules ['lpdf-u3d'] = { version = 1.001, comment = "companion to lpdf-ini.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } -- The following code is based on a working prototype provided -- by Michael Vidiassov. It is rewritten using the lpdf library -- and different checking is used. The macro calls are adapted -- (and will eventually be removed). The user interface needs -- an overhaul. There are some messy leftovers that will be -- removed in future versions. -- For some reason no one really tested this code so at some -- point we will end up with a reimplementation. For instance -- it makes sense to add the same activation code as with swf. local tonumber = tonumber local formatters, find = string.formatters, string.find local cos, sin, sqrt, pi, atan2, abs = math.cos, math.sin, math.sqrt, math.pi, math.atan2, math.abs local backends, lpdf = backends, lpdf local nodeinjections = backends.pdf.nodeinjections local pdfconstant = lpdf.constant local pdfboolean = lpdf.boolean local pdfnumber = lpdf.number local pdfunicode = lpdf.unicode local pdfdictionary = lpdf.dictionary local pdfarray = lpdf.array local pdfnull = lpdf.null local pdfreference = lpdf.reference local pdfflushstreamobject = lpdf.flushstreamobject local pdfflushstreamfileobject = lpdf.flushstreamfileobject local checkedkey = lpdf.checkedkey local limited = lpdf.limited local schemes = table.tohash { "Artwork", "None", "White", "Day", "Night", "Hard", "Primary", "Blue", "Red", "Cube", "CAD", "Headlamp", } local modes = table.tohash { "Solid", "SolidWireframe", "Transparent", "TransparentWireframe", "BoundingBox", "TransparentBoundingBox", "TransparentBoundingBoxOutline", "Wireframe", "ShadedWireframe", "HiddenWireframe", "Vertices", "ShadedVertices", "Illustration", "SolidOutline", "ShadedIllustration", } local function normalize(x, y, z) local modulo = sqrt(x*x + y*y + z*z); if modulo ~= 0 then return x/modulo, y/modulo, z/modulo else return x, y, z end end local function rotate(vect_x,vect_y,vect_z, tet, axis_x,axis_y,axis_z) -- rotate vect by tet about axis counterclockwise local c, s = cos(tet*pi/180), sin(tet*pi/180) local r = 1 - c local n = sqrt(axis_x*axis_x+axis_y*axis_y+axis_z*axis_z) axis_x, axis_y, axis_z = axis_x/n, axis_y/n, axis_z/n return (axis_x*axis_x*r+c )*vect_x + (axis_x*axis_y*r-axis_z*s)*vect_y + (axis_x*axis_z*r+axis_y*s)*vect_z, (axis_x*axis_y*r+axis_z*s)*vect_x + (axis_y*axis_y*r+c )*vect_y + (axis_y*axis_z*r-axis_x*s)*vect_z, (axis_x*axis_z*r-axis_y*s)*vect_x + (axis_y*axis_z*r+axis_x*s)*vect_y + (axis_z*axis_z*r+c )*vect_z end local function make3dview(view) local name = view.name local name = pdfunicode(name ~= "" and name or "unknown view") local viewdict = pdfdictionary { Type = pdfconstant("3DView"), XN = name, IN = name, NR = true, } local bg = checkedkey(view,"bg","table") if bg then viewdict.BG = pdfdictionary { Type = pdfconstant("3DBG"), C = pdfarray { limited(bg[1],1,1,1), limited(bg[2],1,1,1), limited(bg[3],1,1,1) }, } end local lights = checkedkey(view,"lights","string") if lights and schemes[lights] then viewdict.LS = pdfdictionary { Type = pdfconstant("3DLightingScheme"), Subtype = pdfconstant(lights), } end -- camera position is taken from 3d model local u3dview = checkedkey(view, "u3dview", "string") if u3dview then viewdict.MS = pdfconstant("U3D") viewdict.U3DPath = u3dview end -- position the camera as given local c2c = checkedkey(view, "c2c", "table") local coo = checkedkey(view, "coo", "table") local roo = checkedkey(view, "roo", "number") local azimuth = checkedkey(view, "azimuth", "number") local altitude = checkedkey(view, "altitude", "number") if c2c or coo or roo or azimuth or altitude then local pos = checkedkey(view, "pos", "table") local dir = checkedkey(view, "dir", "table") local upv = checkedkey(view, "upv", "table") local roll = checkedkey(view, "roll", "table") local coo_x, coo_y, coo_z = 0, 0, 0 local dir_x, dir_y, dir_z = 0, 0, 0 local trans_x, trans_y, trans_z = 0, 0, 0 local left_x, left_y, left_z = 0, 0, 0 local up_x, up_y, up_z = 0, 0, 0 -- point camera is aimed at if coo then coo_x, coo_y, coo_z = tonumber(coo[1]) or 0, tonumber(coo[2]) or 0, tonumber(coo[3]) or 0 end -- distance from camera to target if roo then roo = abs(roo) end if not roo or roo == 0 then roo = 0.000000000000000001 end -- set it via camera position if pos then dir_x = coo_x - (tonumber(pos[1]) or 0) dir_y = coo_y - (tonumber(pos[2]) or 0) dir_z = coo_z - (tonumber(pos[3]) or 0) if not roo then roo = sqrt(dir_x*dir_x + dir_y*dir_y + dir_z*dir_z) end if dir_x == 0 and dir_y == 0 and dir_z == 0 then dir_y = 1 end dir_x, dir_y, dir_z = normalize(dir_x,dir_y,dir_z) end -- set it directly if dir then dir_x, dir_y, dir_z = tonumber(dir[1] or 0), tonumber(dir[2] or 0), tonumber(dir[3] or 0) if dir_x == 0 and dir_y == 0 and dir_z == 0 then dir_y = 1 end dir_x, dir_y, dir_z = normalize(dir_x,dir_y,dir_z) end -- set it movie15 style with vector from target to camera if c2c then dir_x, dir_y, dir_z = - tonumber(c2c[1] or 0), - tonumber(c2c[2] or 0), - tonumber(c2c[3] or 0) if dir_x == 0 and dir_y == 0 and dir_z == 0 then dir_y = 1 end dir_x, dir_y, dir_z = normalize(dir_x,dir_y,dir_z) end -- set it with azimuth and altitutde if altitude or azimuth then dir_x, dir_y, dir_z = -1, 0, 0 if altitude then dir_x, dir_y, dir_z = rotate(dir_x,dir_y,dir_z, -altitude, 0,1,0) end if azimuth then dir_x, dir_y, dir_z = rotate(dir_x,dir_y,dir_z, azimuth, 0,0,1) end end -- set it with rotation like in MathGL if rot then if dir_x == 0 and dir_y == 0 and dir_z == 0 then dir_z = -1 end dir_x,dir_y,dir_z = rotate(dir_x,dir_y,dir_z, tonumber(rot[1]) or 0, 1,0,0) dir_x,dir_y,dir_z = rotate(dir_x,dir_y,dir_z, tonumber(rot[2]) or 0, 0,1,0) dir_x,dir_y,dir_z = rotate(dir_x,dir_y,dir_z, tonumber(rot[3]) or 0, 0,0,1) end -- set it with default movie15 orientation looking up y axis if dir_x == 0 and dir_y == 0 and dir_z == 0 then dir_y = 1 end -- left-vector -- up-vector if upv then up_x, up_y, up_z = tonumber(upv[1]) or 0, tonumber(upv[2]) or 0, tonumber(upv[3]) or 0 else -- set default up-vector if abs(dir_x) == 0 and abs(dir_y) == 0 then if dir_z < 0 then up_y = 1 -- top view else up_y = -1 -- bottom view end else -- other camera positions than top and bottom, up-vector = up_world - (up_world dot dir) dir up_x, up_y, up_z = - dir_z*dir_x, - dir_z*dir_y, - dir_z*dir_z + 1 end end -- normalize up-vector up_x, up_y, up_z = normalize(up_x,up_y,up_z) -- left vector = up x dir left_x, left_y, left_z = dir_z*up_y - dir_y*up_z, dir_x*up_z - dir_z*up_x, dir_y*up_x - dir_x*up_y -- normalize left vector left_x, left_y, left_z = normalize(left_x,left_y,left_z) -- apply camera roll if roll then local sinroll = sin((roll/180.0)*pi) local cosroll = cos((roll/180.0)*pi) left_x = left_x*cosroll + up_x*sinroll left_y = left_y*cosroll + up_y*sinroll left_z = left_z*cosroll + up_z*sinroll up_x = up_x*cosroll + left_x*sinroll up_y = up_y*cosroll + left_y*sinroll up_z = up_z*cosroll + left_z*sinroll end -- translation vector trans_x, trans_y, trans_z = coo_x - roo*dir_x, coo_y - roo*dir_y, coo_z - roo*dir_z viewdict.MS = pdfconstant("M") viewdict.CO = roo viewdict.C2W = pdfarray { left_x, left_y, left_z, up_x, up_y, up_z, dir_x, dir_y, dir_z, trans_x, trans_y, trans_z, } end local aac = tonumber(view.aac) -- perspective projection local mag = tonumber(view.mag) -- ortho projection if aac and aac > 0 and aac < 180 then viewdict.P = pdfdictionary { Subtype = pdfconstant("P"), PS = pdfconstant("Min"), FOV = aac, } elseif mag and mag > 0 then viewdict.P = pdfdictionary { Subtype = pdfconstant("O"), OS = mag, } end local mode = modes[view.rendermode] if mode then pdfdictionary { Type = pdfconstant("3DRenderMode"), Subtype = pdfconstant(mode), } end -- crosssection local crosssection = checkedkey(view,"crosssection","table") if crosssection then local crossdict = pdfdictionary { Type = pdfconstant("3DCrossSection") } local c = checkedkey(crosssection,"point","table") or checkedkey(crosssection,"center","table") if c then crossdict.C = pdfarray { tonumber(c[1]) or 0, tonumber(c[2]) or 0, tonumber(c[3]) or 0 } end local normal = checkedkey(crosssection,"normal","table") if normal then local x, y, z = tonumber(normal[1] or 0), tonumber(normal[2] or 0), tonumber(normal[3] or 0) if sqrt(x*x + y*y + z*z) == 0 then x, y, z = 1, 0, 0 end crossdict.O = pdfarray { pdfnull, atan2(-z,sqrt(x*x + y*y))*180/pi, atan2(y,x)*180/pi, } end local orient = checkedkey(crosssection,"orient","table") if orient then crossdict.O = pdfarray { tonumber(orient[1]) or 1, tonumber(orient[2]) or 0, tonumber(orient[3]) or 0, } end crossdict.IV = cross.intersection or false crossdict.ST = cross.transparent or false viewdict.SA = next(crossdict) and pdfarray { crossdict } -- maybe test if # > 1 end local nodes = checkedkey(view,"nodes","table") if nodes then local nodelist = pdfarray() for i=1,#nodes do local node = checkedkey(nodes,i,"table") if node then local position = checkedkey(node,"position","table") nodelist[#nodelist+1] = pdfdictionary { Type = pdfconstant("3DNode"), N = node.name or ("node_" .. i), -- pdfunicode ? M = position and #position == 12 and pdfarray(position), V = node.visible or true, O = node.opacity or 0, RM = pdfdictionary { Type = pdfconstant("3DRenderMode"), Subtype = pdfconstant(node.rendermode or "Solid"), }, } end end viewdict.NA = nodelist end return viewdict end local stored_js, stored_3d, stored_pr, streams = { }, { }, { }, { } local function insert3d(spec) -- width, height, factor, display, controls, label, foundname local width, height, factor = spec.width, spec.height, spec.factor or number.dimenfactors.bp local display, controls, label, foundname = spec.display, spec.controls, spec.label, spec.foundname local param = (display and parametersets[display]) or { } local streamparam = (controls and parametersets[controls]) or { } local name = "3D Artwork " .. (param.name or label or "Unknown") local activationdict = pdfdictionary { TB = pdfboolean(param.toolbar,true), NP = pdfboolean(param.tree,false), } local stream = streams[label] if not stream then local subtype, subdata = "U3D", io.loaddata(foundname) or "" if find(subdata,"^PRC") then subtype = "PRC" elseif find(subdata,"^U3D") then subtype = "U3D" elseif file.suffix(foundname) == "prc" then subtype = "PRC" end local attr = pdfdictionary { Type = pdfconstant("3D"), Subtype = pdfconstant(subtype), } local streamviews = checkedkey(streamparam, "views", "table") if streamviews then local list = pdfarray() for i=1,#streamviews do local v = checkedkey(streamviews, i, "table") if v then list[#list+1] = make3dview(v) end end attr.VA = list end if checkedkey(streamparam, "view", "table") then attr.DV = make3dview(streamparam.view) elseif checkedkey(streamparam, "view", "string") then attr.DV = streamparam.view end local js = checkedkey(streamparam, "js", "string") if js then local jsref = stored_js[js] if not jsref then jsref = pdfflushstreamfileobject(js) stored_js[js] = jsref end attr.OnInstantiate = pdfreference(jsref) end stored_3d[label] = pdfflushstreamfileobject(foundname,attr) stream = 1 else stream = stream + 1 end streams[label] = stream local name = pdfunicode(name) local annot = pdfdictionary { Subtype = pdfconstant("3D"), T = name, Contents = name, NM = name, ["3DD"] = pdfreference(stored_3d[label]), ["3DA"] = activationdict, } if checkedkey(param,"view","table") then annot["3DV"] = make3dview(param.view) elseif checkedkey(param,"view","string") then annot["3DV"] = param.view end local preview = checkedkey(param,"preview","string") if preview then activationdict.A = pdfconstant("XA") local tag = formatters["%s:%s:%s"](label,stream,preview) local ref = stored_pr[tag] if not ref then local figure = img.immediatewrite { filename = preview, width = width, height = height } ref = figure.objnum stored_pr[tag] = ref end if ref then -- see back-pdf ** .. here we have a local /IM ! local zero, one = pdfnumber(0), pdfnumber(1) -- not really needed local pw = pdfdictionary { Type = pdfconstant("XObject"), Subtype = pdfconstant("Form"), FormType = one, BBox = pdfarray { zero, zero, pdfnumber(factor*width), pdfnumber(factor*height) }, Matrix = pdfarray { one, zero, zero, one, zero, zero }, Resources = pdfdictionary { XObject = pdfdictionary { IM = pdfreference(ref) } }, ExtGState = pdfdictionary { GS = pdfdictionary { Type = pdfconstant("ExtGState"), CA = one, ca = one, } }, ProcSet = pdfarray { pdfconstant("PDF"), pdfconstant("ImageC") }, } local pwd = pdfflushstreamobject(formatters["q /GS gs %.6F 0 0 %.6F 0 0 cm /IM Do Q"](factor*width,factor*height),pw) annot.AP = pdfdictionary { N = pdfreference(pwd) } end return annot, figure, ref else activationdict.A = pdfconstant("PV") return annot, nil, nil end end function nodeinjections.insertu3d(spec) local annotation, preview, ref = insert3d { -- just spec foundname = spec.foundname, width = spec.width, height = spec.height, factor = spec.factor, display = spec.display, controls = spec.controls, label = spec.label, } node.write(nodeinjections.annotation(spec.width,spec.height,0,annotation())) end
local EntityFactory = Class("game.EntityFactory") function EntityFactory:initialize() self.components = {} end function EntityFactory:addComponent(name, ...) table.insert(self.components, {name, ...}) return self end function EntityFactory:spawn(...) local entity = Entity:new(...) for name, component in pairs(self.components) do entity:addComponent(unpack(component)) end return entity end return EntityFactory
--====================================================================-- -- dmc_ui/dmc_widget/widget_navitem.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2015 David McCuskey 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. --]] --====================================================================-- --== DMC Corona UI : NavItem Widget --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.0" --====================================================================-- --== DMC UI Setup --====================================================================-- local dmc_ui_data = _G.__dmc_ui local dmc_ui_func = dmc_ui_data.func local ui_find = dmc_ui_func.find --====================================================================-- --== DMC UI : newNavItem --====================================================================-- --====================================================================-- --== Imports local Objects = require 'dmc_objects' local LifecycleMixModule = require 'dmc_lifecycle_mix' local StyleMixModule = require( ui_find( 'dmc_style.style_mix' ) ) local uiConst = require( ui_find( 'ui_constants' ) ) --====================================================================-- --== Setup, Constants local ObjectBase = Objects.ObjectBase local LifecycleMix = LifecycleMixModule.LifecycleMix local StyleMix = StyleMixModule.StyleMix local tinsert = table.insert local tremove = table.remove --== To be set in initialize() local dUI = nil local Widget = nil --====================================================================-- --== Nav Item Widget Class --====================================================================-- --- Nav Item Module. -- a navigation component used with a NavBar widget. this is essentially a container of items to show in a NavBar. -- -- @classmod Widget.NavItem -- @usage -- local dUI = require 'dmc_ui' -- local widget = dUI.newNavItem() local NavItem = newClass( { StyleMix, ObjectBase, LifecycleMix }, {name="Nav Item"} ) --== Style/Theme Constants NavItem.STYLE_CLASS = nil -- added later NavItem.STYLE_TYPE = uiConst.NAVITEM --======================================================-- -- Start: Setup DMC Objects --== Init function NavItem:__init__( params ) -- print( "NavItem:__init__" ) params = params or {} if params.titleText==nil then params.titleText="" end self:superCall( LifecycleMix, '__init__', params ) self:superCall( ObjectBase, '__init__', params ) self:superCall( StyleMix, '__init__', params ) --==-- --== Create Properties ==-- -- properties stored in Class self._titleText = '' -- properties stored in Style self._debugOn_dirty=true self._width_dirty=true self._height_dirty=true self._anchorX_dirty=true self._anchorY_dirty=true -- "Virtual" properties self._widgetStyle_dirty=true --== Object References ==-- self._wgtBtnBack = nil -- Back button widget self._wgtBtnBack_dirty=true self._wgtBtnBackStyle_dirty=true self._wgtText = nil -- text widget (for title) self._wgtText_f = nil -- widget handler self._wgtText_dirty=true self._wgtTextStyle_dirty=true self._wgtTextText_dirty=true self._btnLeft = nil self._btnLeftStyle_dirty=true self._btnRight = nil self._btnRightStyle_dirty=true self._ni_tmp_params = params -- save end --[[ function NavItem:_undoInit() -- print( "NavItem:_undoInit" ) --==-- self:superCall( "_undoInit" ) end --]] -- __initComplete__() -- function NavItem:__initComplete__() --print( "NavItem:__initComplete__" ) self:superCall( StyleMix, '__initComplete__' ) self:superCall( ObjectBase, '__initComplete__' ) --==-- local tmp = self._ni_tmp_params self.style = tmp.style self.rightButton = tmp.rightButton -- setter self.leftButton = tmp.leftButton -- setter self:_createText() self:_createBackButton() self.titleText = tmp.titleText self._ni_tmp_params = nil end function NavItem:__undoInitComplete__() -- print( "NavItem:__undoInitComplete__" ) self:_removeBackButton() self:_removeText() --== Though not default, check them o = self._btnLeft if o then o:removeSelf() self._btnLeft = nil end o = self._btnRight if o then o:removeSelf() self._btnRight = nil end --==-- self:superCall( ObjectBase, '__undoInitComplete__' ) self:superCall( StyleMix, '__undoInitComplete__' ) end -- END: Setup DMC Objects --======================================================-- --====================================================================-- --== Static Methods function NavItem.initialize( manager ) -- print( "NavItem.initialize" ) dUI = manager Widget = dUI.Widget local Style = dUI.Style NavItem.STYLE_CLASS = Style.NavItem Style.registerWidget( NavItem ) end --====================================================================-- --== Public Methods --- get backButton object. -- -- @within Properties -- @function .backButton -- @usage print( widget.backButton ) function NavItem.__getters:backButton() -- print( "NavItem.__getters:backButton" ) return self._wgtBtnBack end --- set/get leftButton object. -- -- @within Properties -- @function .leftButton -- @usage widget.leftButton = <DMC PushButton> -- @usage print( widget.leftButton ) function NavItem.__getters:leftButton() -- print( "NavItem.__getters:leftButton" ) return self._btnLeft end function NavItem.__setters:leftButton( button ) -- print( "NavItem.__setters:leftButton", button ) local bType = type(button) assert( bType=='nil' or bType=='table', "wrong type for button" ) --==-- if bType=='table' then assert( button.isa and button:isa( Widget.ButtonFactory.Base ), "button not object" ) end self._btnLeft = button self._btnLeftStyle_dirty=true self:__invalidateProperties__() end --- set/get rightButton object. -- -- @within Properties -- @function .rightButton -- @usage widget.rightButton = <DMC PushButton> -- @usage print( widget.rightButton ) function NavItem.__getters:rightButton() -- print( "NavItem.__getters:rightButton" ) return self._btnRight end function NavItem.__setters:rightButton( button ) -- print( "NavItem.__setters:rightButton", button ) local bType = type(button) assert( bType=='nil' or bType=='table', "wrong type for button" ) --==-- if bType=='table' then assert( button.isa and button:isa( Widget.ButtonFactory.Base ), "button not object" ) end self._btnRight = button self._btnRightStyle_dirty=true self:__invalidateProperties__() end --- get title Text Widget of Nav Item. -- -- @within Properties -- @function .title -- @usage print( widget.title ) function NavItem.__getters:title() -- print( "NavItem.__getters:title" ) return self._wgtText end --- set/get title of Nav Item. -- value should be string -- -- @within Properties -- @function .titleText -- @usage widget.titleText = "My Title" -- @usage print( widget.titleText ) function NavItem.__getters:titleText() -- print( "NavItem.__getters:titleText" ) return self._titleText end function NavItem.__setters:titleText( value ) -- print( "NavItem.__setters:titleText", button ) assert( type(value)=='string', "title must be a string" ) --==-- self._titleText = value self._wgtTextText_dirty=true self:__invalidateProperties__() end --======================================================-- -- Theme Methods -- afterAddStyle() -- function NavItem:afterAddStyle() -- print( "NavItem:afterAddStyle", self ) self._widgetStyle_dirty=true self:__invalidateProperties__() end -- beforeRemoveStyle() -- function NavItem:beforeRemoveStyle() -- print( "NavItem:beforeRemoveStyle", self ) self._widgetStyle_dirty=true self:__invalidateProperties__() end --====================================================================-- --== Private Methods --== Create/Destroy Text Widget function NavItem:_removeBackButton() -- print( "NavItem:_removeBackButton" ) local o = self._wgtBtnBack if not o then return end o:removeSelf() self._wgtBtnBack = nil end function NavItem:_createBackButton() -- print( "NavItem:_createBackButton" ) self:_removeBackButton() local o = Widget.newButton{ labelText="< Back", defaultStyle = self.defaultStyle.backButton } self._wgtBtnBack = o --== Reset properties self._wgtBtnBackStyle_dirty=true end --== Create/Destroy Text Widget function NavItem:_removeText() -- print( "NavItem:_removeText" ) local o = self._wgtText if not o then return end o.onUpdate=nil o:removeSelf() self._wgtText = nil end function NavItem:_createText() -- print( "NavItem:_createText" ) self:_removeText() local o = Widget.newText{ defaultStyle = self.defaultStyle.title } self._wgtText = o --== Reset properties self._wgtTextStyle_dirty=true self._wgtTextText_dirty=true end function NavItem:__commitProperties__() -- print( 'NavItem:__commitProperties__' ) --== Update Widget View ==-- local style = self.curr_style local view = self.view local text = self._wgtText local back = self._wgtBtnBack local left = self._btnLeft local right = self._btnRight --== Set Styles if self._wgtBtnBackStyle_dirty then back:setActiveStyle( style.backButton, {copy=false} ) self._wgtBtnBackStyle_dirty=false end -- TODO: check widget type (apply style if Widget) if left and self._btnLeftStyle_dirty then left:setActiveStyle( style.leftButton, {copy=false} ) self._btnLeftStyle_dirty=false end -- TODO: check widget type (apply style if Widget) if right and self._btnRightStyle_dirty then right:setActiveStyle( style.rightButton, {copy=false} ) self._btnRightStyle_dirty=false end if self._wgtTextText_dirty then text.text=self._titleText self._wgtTextText_dirty=false end if self._wgtTextStyle_dirty then text:setActiveStyle( style.title, {copy=false} ) self._wgtTextStyle_dirty=false end end --====================================================================-- --== Event Handlers function NavItem:stylePropertyChangeHandler( event ) -- print( "NavItem:stylePropertyChangeHandler", event.property, event.value ) local style = event.target local etype= event.type local property= event.property local value = event.value -- Utils.print( event ) -- print( "Style Changed", etype, property, value ) if etype==style.STYLE_RESET then self._debugOn_dirty = true self._width_dirty=true self._height_dirty=true self._anchorX_dirty=true self._anchorY_dirty=true self._wgtBtnBackStyle_dirty=true self._btnLeftStyle_dirty=true self._btnRightStyle_dirty=true self._wgtTextStyle_dirty=true property = etype else if property=='debugActive' then self._debugOn_dirty=true elseif property=='width' then self._width_dirty=true elseif property=='height' then self._height_dirty=true elseif property=='anchorX' then self._anchorX_dirty=true elseif property=='anchorY' then self._anchorY_dirty=true end end self:__invalidateProperties__() self:__dispatchInvalidateNotification__( property, value ) end return NavItem
-- Copyright (c) 2021 Trevor Redfern -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT local Audio = require "moonpie.audio" local pitchShifter = require "moonpie.audio.effects.random_pitch" local sounds = { attack = Audio.getStatic("assets/sounds/attack.wav"), click = pitchShifter(Audio.getStatic("assets/sounds/click_sound.wav"), 0.9, 1.3), hit = Audio.getStatic("assets/sounds/hit.wav"), hover = pitchShifter(Audio.getStatic("assets/sounds/hover_sound.wav"), 0.9, 1.3), titleTrack = Audio.getStreaming("assets/music/title.ogg"), walk = Audio.getStatic("assets/sounds/walk.wav"), } sounds.attack.source:setVolume(0.05) sounds.click.source:setVolume(0.08) sounds.hit.source:setVolume(0.05) sounds.hover.source:setVolume(0.03) sounds.titleTrack.source:setLooping(true) sounds.titleTrack.source:setVolume(0.5) sounds.walk.source:setVolume(0.05) return sounds
SKILL.name = "Bladewind" SKILL.LevelReq = 5 SKILL.SkillPointCost = 1 SKILL.Incompatible = { } SKILL.RequiredSkills = { } SKILL.icon = "vgui/skills/ability_warrior_bladestorm.png" SKILL.category = "Dark Magic" SKILL.slot = "AOE" -- ULT, RANGED, MELEE, AOE, PASSIVE SKILL.class = { "asp_sorcerer" } SKILL.desc = [[ A clutch of hungry swords sweep across the battlefield. Cost: 100 Energy Cooldown: 60 Seconds Ability Slot: 3 Class Restriction: Aspiring Sorcerer Level Requirement: ]] .. SKILL.LevelReq .. [[ Skill Point Cost:]] .. SKILL.SkillPointCost .. [[ ]] SKILL.coolDown = 30 local function ability(SKILL, ply ) local nospam = ply:GetNWBool( "nospamAOE" ) // nospamRanged, nospamUlt, nospamAOE, nospamMelee if (nospam) then if timer.Exists(ply:SteamID().."nospamAOE") then return end timer.Create(ply:SteamID().."nospamAOE", SKILL.coolDown, 1, function() ply:SetNWBool( "nospamAOE", false ) end) return end local mana = ply:getLocalVar("mana", 0) if mana < 20 then return end ply:setLocalVar("mana", mana - 20) local Ent = ents.Create("sent_zad_bladewind") local OwnerPos = ply:GetShootPos() local OwnerAng = ply:GetAimVector():Angle() OwnerPos = OwnerPos + OwnerAng:Forward()*-20 + OwnerAng:Up()*-9 + OwnerAng:Right()*10 if ply:IsPlayer() then Ent:SetPos(OwnerPos) end if ply:IsPlayer() then Ent:SetAngles(OwnerAng) else Ent:SetAngles(ply:GetAngles()) end Ent:SetOwner(ply) Ent:Spawn() if SERVER then ply:SetNWBool( "nospamAOE", true ) print("Cdstart") net.Start( "AOEActivated" ) // RangedActivated, UltActivated, AOEActivated, MeleeActivated net.Send( ply ) if timer.Exists(ply:SteamID().."nospamAOE") then return end timer.Create(ply:SteamID().."nospamAOE", SKILL.coolDown, 1, function() ply:SetNWBool( "nospamAOE", false ) end) end end SKILL.ability = ability
keyjustpressed = {} -- function justpressedUpdate() -- for i, _ in pairs(justpressed) do -- justpressed[i] = false -- end -- end function love.keypressed(key) keyjustpressed[key] = true end return keyjustpressed
if #arg > 1 then print(string.reverse(arg[1])) end
--[[ telepickups - wejscia do budynkow @author Jakub 'XJMLN' Starzak <jack@pszmta.pl @package PSZMTA.psz-telepickups @copyright Jakub 'XJMLN' Starzak <jack@pszmta.pl> Nie mozesz uzywac tego skryptu bez mojej zgody. Napisz - byc moze sie zgodze na uzycie. ]]-- local tepi={} local interiory={} local dane=exports["psz-mysql"]:pobierzTabeleWynikow("SELECT id,interior,dimension,entrance,`exit` FROM psz_interiory WHERE `exit` IS NOT NULL AND active=1") for _,v in ipairs(dane) do local ii = tonumber(v.id) v.entrance=split(v.entrance,",") -- miejsce w ktorym pojawi sie gracz v.exit=split(v.exit,",") -- wyjscie v.id=nil interiory[ii]=v end local function usunTepi(id) if isElement(tepi[id].wyjscie) then destroyElement(tepi[id].wyjscie) end if isElement(tepi[id].wejscie) then destroyElement(tepi[id].wejscie) end if isElement(tepi[id].text) then destroyElement(tepi[id].text) end if isElement(tepi[id].blip) then destroyElement(tepi[id].blip) end tepi[id]=nil end local function dodajTepi(v) if not interiory[v.interiorid] then return false end if tepi[v.id] then usunTepi(v.id) end v.pos=split(v.wejscie,",") for ii,vv in ipairs(v.pos) do v.pos[ii]=tonumber(vv) end v.punkt_wyjscia=split(v.punkt_wyjscia,",") for ii,vv in ipairs(v.punkt_wyjscia) do v.punkt_wyjscia[ii]=tonumber(vv) end v.wejscie = createMarker(v.pos[1],v.pos[2],v.pos[3],"arrow",1,255,0,0) setElementInterior(v.wejscie,v.i) setElementDimension(v.wejscie,v.vwe) if (tonumber(v.i)==0 and tonumber(v.vwe)==0) then v.blip=createBlip(v.pos[1], v.pos[2], v.pos[3], 0, 1, 255,105,5,155, -1000, 200) end v.text = createElement("text") setElementPosition(v.text,v.pos[1],v.pos[2],v.pos[3]+0.5) setElementData(v.text,"text",("(( "..v.descr.." ))" or "(( Przejście ))")) setElementDimension(v.text,v.vwe) setElementInterior(v.text,v.i) local interior_dimension=v.vwi or interiory[v.interiorid].dimension or 0 setElementData(v.wejscie,"tepi", { ["zamkniety"]=v.zamkniety>0 and true or false, ["id"]=v.id, ["descr"]=v.descr or "(( Przejście ))", ["dimension"]=interior_dimension, ["interior"]=interiory[v.interiorid].interior, ["interior_loc"]=interiory[v.interiorid].entrance, ["exit_loc"]=v.punkt_wyjscia, }) -- dodajemy wyjscie v.wyjscie=createMarker(interiory[v.interiorid].exit[1], interiory[v.interiorid].exit[2], interiory[v.interiorid].exit[3]+0.5, "arrow",1) setElementDimension(v.wyjscie, interior_dimension) setElementInterior(v.wyjscie, interiory[v.interiorid].interior) setElementData(v.wyjscie,"tpto", {pos=v.punkt_wyjscia,int=v.i,dim=v.vwe}) if v.id == 22 then setElementData(v.wyjscie,"tpto", {pos=v.punkt_wyjscia,int=v.i,dim=v.vwe,c_onExit=true}) end local dbid=v.id v.id=nil tepi[dbid]=v return true end function tepiGetInfo(id) return tepi[id] end local function zaladujCzescTepi(procent) local tt=getTickCount() i=0 local dbtepi dbtepi=exports["psz-mysql"]:pobierzTabeleWynikow("SELECT t.id,t.descr,t.wejscie,t.punkt_wyjscia,t.interiorid,t.i,t.vwe,t.vwi,t.zamkniety FROM psz_telepickups t WHERE t.active=1;") for __,v in ipairs(dbtepi) do if math.random(0,100)<=procent then if dodajTepi(v) then i=i+1 end end end outputDebugString("Zaladowano teleportow: "..i.." w "..(getTickCount()-tt).."ms") setInteriorSoundsEnabled(false) end addEventHandler("onResourceStart",resourceRoot,function() zaladujCzescTepi(100) end) local function zaladujZmienioneTepi() local i=0 local dbtepi=exports["psz-mysql"]:pobierzTabeleWynikow("SELECT t.id,t.descr,t.wejscie,t.punkt_wyjscia,t.interiorid,t.i,t.vwe,t.vwi,t.zamkniety FROM psz_telepickups t WHERE t.active=1 AND timediff(now(),t.updated)<'00:09:00' AND datediff(now(),t.updated)<1") for __,v in ipairs(dbtepi) do if dodajTepi(v) then i=i+1 end end outputDebugString("Zaladowano zmienionych teleportow: "..i) end setTimer(zaladujZmienioneTepi, 150000,0) function tepiReload(id) local dbtepi=exports["psz-mysql"]:pobierzWyniki("SELECT t.id,t.descr,t.wejscie,t.punkt_wyjscia,t.interiorid,t.i,t.vwe,t.vwi,t.zamkniety FROM psz_telepickups t WHERE t.active=1 and t.id=?;",id) if dbtepi then return dodajTepi(dbtepi) end return false end function moveMeTo(x,y,z,i,d,executor) -- executor XDD coś ty jarał setElementDimension(executor, d) setElementInterior(executor,i,x,y,z) setElementPosition(executor,x,y,z) setElementInterior(executor,i) end function tepiEnter(hitElement,matchingDimension) if (getElementType(hitElement)~="player") then return end if (not matchingDimension) then return end if (getElementInterior(hitElement)~=getElementInterior(source)) then return end if (getPedOccupiedVehicle(hitElement)) then return end local tepi=getElementData(source,"tepi") if not tepi then return end local level = getElementData(hitElement,"level") or 0 if (not tepi.zamkniety) or (tepi.zamkniety and level == 3) then moveMeTo(tepi.interior_loc[1],tepi.interior_loc[2],tepi.interior_loc[3],tepi.interior,tepi.dimension,hitElement) elseif tepi.zamkniety and level ~= 3 then outputChatBox("Budynek jest zamknięty",hitElement) return false end end addEventHandler( "onMarkerHit", resourceRoot, tepiEnter) addEventHandler("onMarkerHit", resourceRoot, function(el,md) if getElementType(el)~="player" or not md then return end if getElementInterior(el)~=getElementInterior(source) then return end local tpto=getElementData(source,"tpto") if not tpto then return end setElementPosition(el, tpto.pos[1], tpto.pos[2],tpto.pos[3]) setElementInterior(el, tpto.int) setElementDimension(el, tpto.dim) if tpto[4] then setPedRotation(el, tpto.pos[4]) end if tpto.c_onExit then local fr = getElementData(el,"faction:data") if fr and fr.id == 6 then exports['psz-grupy']:grupy_quitJob('bpracy',el) outputChatBox("Opuściłeś teren klubu, zostałeś wyrzucony z grupy DJ.",el) end end end )
AddCSLuaFile() SWEP.Category = "Minecraft" SWEP.Spawnable = true -- SWEP.AdminOnly = false SWEP.PrintName = "Handheld Rocket [BETA]" -- SWEP.Base = weapon_base SWEP.m_WeaponDeploySpeed= 1 SWEP.Author = "Piengineer" SWEP.Contact = "http://steamcommunity.com/id/Piengineer12/" SWEP.Purpose = "A launchable firework. Be careful not to let it explode in your face." SWEP.Instructions = "Primary: Light fuse and release rocket.\nSecondary: Light fuse without releasing, use Primary Fire after to release." SWEP.ViewModel = ""--"models/weapons/c_stunstick.mdl" -- SWEP.ViewModelFlip = false -- SWEP.ViewModelFlip1 = false -- SWEP.ViewModelFlip2 = false -- SWEP.ViewModelFOV = 62 SWEP.WorldModel = "models/weapons/w_crowbar.mdl" SWEP.AutoSwitchFrom = false SWEP.AutoSwitchTo = false -- SWEP.Weight = 5 -- SWEP.BobScale = 1 -- SWEP.SwayScale = 1 SWEP.BounceWeaponIcon = false -- SWEP.DrawWeaponInfoBox = true SWEP.DrawAmmo = false -- SWEP.DrawCrosshair = true -- SWEP.RenderGroup = RENDERGROUP_OPAQUE SWEP.Slot = 2 -- SWEP.SlotPos = 10 -- SWEP.SpeechBubbleLid = surface.GetTextureID("gui/speech_lid") SWEP.WepSelectIcon = CLIENT and surface.GetTextureID("weapons/weapon_minecraft_firework") -- SWEP.CSMuzzleFlashes = false -- SWEP.CSMuzzleX = false SWEP.Primary = { Ammo = "none", ClipSize = -1, DefaultClip = -1, Automatic = false } SWEP.Secondary = { Ammo = "none", ClipSize = -1, DefaultClip = -1, Automatic = false } SWEP.UseHands = true -- SWEP.AccurateCrosshair = false -- SWEP.DisableDuplicator = false SWEP.m_bPlayPickupSound = false local fireworkModel = "models/mcitems3d_mariro/firework_rocket.mdl" local altFireworkModel = false if not util.IsValidModel(fireworkModel) then fireworkModel = "models/mcmodelpack/items/rocket.mdl" altFireworkModel = true end function SWEP:SetupDataTables() self:NetworkVar("Int",0,"LaunchVelocity") end function SWEP:CreateFirework() local firework = ents.Create("minecraft_firework_rocket") local angs = self.Owner:EyeAngles() firework:SetPos(self.Owner:EyePos() + angs:Forward() * 24) angs.y = angs.y - 90 firework:SetAngles(angs) firework:SetCreator(self.Owner) firework:SetLifeTime(self.Firework.Duration+1) firework.FireworkStars = self.Firework.FireworkStars firework:Spawn() return firework end function SWEP:ApplyFireworkForce(firework) local physobj = firework:GetPhysicsObject() if IsValid(physobj) then local angs = self.Owner:EyeAngles() local velocityDir = angs:Forward() velocityDir:Mul(self:GetLaunchVelocity()) physobj:SetVelocity(velocityDir) end end function SWEP:ThrowFirework() if IsValid(self.FireworkEntity) then self.FireworkEntity:SetParent(NULL) self.FireworkEntity:SetMoveType(MOVETYPE_VPHYSICS) if (PPM2 and self.Owner:IsPlayer() and self.Owner:IsPonyCached()) then -- this may get interesting! local data = self.Owner:GetPonyData() if (data and data:GetFly()) then -- don't spawn the firework in front of the player, as it can be very painful! self.FireworkEntity:SetPos(self.Owner:EyePos() + self.Owner:EyeAngles():Forward() * -64) else self.FireworkEntity:SetPos(self.Owner:EyePos() + self.Owner:EyeAngles():Forward() * 32) end else self.FireworkEntity:SetPos(self.Owner:EyePos() + self.Owner:EyeAngles():Forward() * 32) end self.FireworkEntity:SetTrigger(true) self.FireworkEntity:SetNotSolid(false) self:ApplyFireworkForce(self.FireworkEntity) self.FireworkEntity = nil else local firework = self:CreateFirework() self:ApplyFireworkForce(firework) end end function SWEP:LightFirework() if not IsValid(self.FireworkEntity) then self.FireworkEntity = self:CreateFirework() self.FireworkEntity:SetPos(self:GetPos()) self.FireworkEntity:SetMoveType(MOVETYPE_NONE) self.FireworkEntity:SetParent(self.Owner) self.FireworkEntity:SetTrigger(false) self.FireworkEntity:SetNotSolid(true) end end function SWEP:ClientFire() if CLIENT and self:GetNextPrimaryFire() < CurTime() then self:SetNextPrimaryFire(CurTime() + 1) if (not self.Firework or self.Owner:IsFlagSet(FL_DUCKING)) and self.Owner:IsPlayer() then MFR_SelectFireworkRocket(function(rocket, velocity) if IsValid(self) then self.Firework = rocket local resStr = util.Compress(util.TableToJSON(rocket)) net.Start("minecraft_firework") net.WriteString("receive") net.WriteUInt(#resStr, 16) net.WriteData(resStr, #resStr) net.WriteEntity(self) net.WriteUInt(math.Round(velocity), 32) net.SendToServer() end end, self:GetLaunchVelocity()) end end end function SWEP:CheckProxyModel() if (self.RegenerateNextClientModelTime or 0) > RealTime() then return false end if not IsValid(self.ClientModel) then self.ClientModel = ClientsideModel(fireworkModel, RENDERGROUP_OPAQUE) self.ClientModel:SetNoDraw(true) end return IsValid(self.ClientModel) end function SWEP:Initialize() self:SetLaunchVelocity(1000) end function SWEP:PostDrawViewModel() if (CLIENT and self:CheckProxyModel()) then local pos = self.Owner:GetBonePosition(self.Owner:LookupBone("ValveBiped.Bip01_R_Hand") or -1) if pos == self.Owner:GetPos() then pos = self.Owner:GetBoneMatrix(self.Owner:LookupBone("ValveBiped.Bip01_R_Hand") or -1):GetTranslation() end if pos and not self.Owner:IsDormant() then self.ClientModel:SetPos(pos) local fAng = self.Owner:GetAngles() fAng.p = 0 if altFireworkModel then fAng.y = fAng.y - 90 fAng.r = 0 else fAng.r = -180 end self.ClientModel:SetAngles(fAng) self.ClientModel:SetupBones() self.ClientModel:DrawModel() else self.RegenerateNextClientModelTime = RealTime() + 1 self.ClientModel:Remove() end end end SWEP.DrawWorldModel = SWEP.PostDrawViewModel --[[function SWEP:ViewModelDrawn(vm) if self:CheckProxyModel() and IsValid(vm) then if not self.ClientModel.NoCrowbar then self.ClientModel.NoCrowbar = true vm:SetMaterial("models/effects/vol_light001") end local pos = vm:GetBonePosition(vm:LookupBone("ValveBiped.Bip01_R_Hand")) if pos == vm:GetPos() then pos = vm:GetBoneMatrix(vm:LookupBone("ValveBiped.Bip01_R_Hand")):GetTranslation() end self.ClientModel:SetPos(pos) local fAng = vm:GetAngles() fAng.p = 0 if altFireworkModel then fAng.y = fAng.y - 90 fAng.r = 0 else fAng.r = -180 end self.ClientModel:SetAngles(fAng) end end]] function SWEP:Holster() if IsValid(self.ClientModel) then self.ClientModel:Remove() end return true end function SWEP:OnRemove() if IsValid(self.ClientModel) then self.ClientModel:Remove() end end function SWEP:CanPrimaryAttack() return self.Firework and IsValid(self.Owner) and not self.Owner:IsFlagSet(FL_DUCKING) end function SWEP:PrimaryAttack() self:ClientFire() if SERVER and (IsFirstTimePredicted() or game.SinglePlayer()) then if game.SinglePlayer() then self:CallOnClient("PrimaryAttack") end if self:CanPrimaryAttack() then self:ThrowFirework() end end end function SWEP:SecondaryAttack() self:ClientFire() if SERVER and (IsFirstTimePredicted() or game.SinglePlayer()) then if game.SinglePlayer() then self:CallOnClient("PrimaryAttack") end if self:CanPrimaryAttack() then self:LightFirework() end end end
local class = require('middleclass') local ViewController = require('guihua.viewctrl') local error = require('guihua.log').error -- local util = require('guihua.util') local log = require('guihua.log').info local trace = require('guihua.log').trace TextView = TextView or require('guihua.textview') if ListViewCtrl == nil then ListViewCtrl = class('ListViewCtrl', ViewController) end local function gh_jump_to_win() local currentWinnr = vim.api.nvim_get_current_win() local jumpto = TextView.ActiveTextView.win if jumpto == currentWinnr then jumpto = ListView.Winnr end if jumpto ~= nil and vim.api.nvim_win_is_valid(jumpto) then log('jump from ', currentWinnr, 'to', jumpto) vim.api.nvim_set_current_win(jumpto) end end function _G.gh_jump_to_list() if ListView == nil then return end local jumpto = ListView.Winnr if jumpto ~= nil and vim.api.nvim_win_is_valid(jumpto) then log('jump to', jumpto) vim.cmd(string.format('noa call nvim_set_current_win(%s)', jumpto)) return end end function _G.gh_jump_to_preview() if TextView == nil or TextView.ActiveTextView == nil then return end local jumpto = TextView.ActiveTextView.win if jumpto ~= nil and vim.api.nvim_win_is_valid(jumpto) then log('jump to', jumpto) vim.cmd(string.format('noa call nvim_set_current_win(%s)', jumpto)) return end end function on_preview() if TextView == nil or TextView.ActiveTextView == nil then return false end local jumpto = TextView.ActiveTextView.win return jumpto ~= nil and vim.api.nvim_win_is_valid(jumpto) end function ListViewCtrl:initialize(delegate, ...) trace(debug.traceback()) ViewController:initialize(delegate, ...) self.m_delegate = delegate self.selected_line = 1 -- local opts = select(1, ...) or {} -- trace("listview ctrl opts", opts) self.data = opts.data or {} self.preview = opts.preview or false self.prompt = opts.prompt self.display_height = self.m_delegate.display_height or 10 self.display_start_at = 1 self.on_move = opts.on_move or function(...) end self.on_confirm = opts.on_confirm if #self.data <= self.display_height then self.display_data = opts.data else self.display_data = {} for i = 1, self.display_height, 1 do table.insert(self.display_data, self.data[i]) end end log('init display: ', self.display_height, self.selected_line) trace('init display: ', self.display_data, self.display_height, self.selected_line) -- ... is the view -- todo location, readonly? and filetype if delegate.buf == nil or delegate.buf == 0 then log('should not bind to current buffer') end vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<C-p>', '<cmd> lua ListViewCtrl:on_prev()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'i', '<C-p>', '<cmd> lua ListViewCtrl:on_prev()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<C-n>', '<cmd> lua ListViewCtrl:on_next()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'i', '<C-n>', '<cmd> lua ListViewCtrl:on_next()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<Enter>', '<cmd> lua ListViewCtrl:on_confirm()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'i', '<Enter>', '<cmd> lua ListViewCtrl:on_confirm() <CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<C-w>j', '<cmd> lua gh_jump_to_preview()<CR>', {}) -- vim.api.nvim_buf_set_keymap(delegate.buf, "i", "<Enter>", -- "<cmd> lua ListViewCtrl:on_search()<CR>", {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<Up>', '<cmd> lua ListViewCtrl:on_prev()<CR>', {}) -- vim.api.nvim_buf_set_keymap(delegate.buf, 'n', 'k', '<cmd> lua ListViewCtrl:on_prev()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<Down>', '<cmd> lua ListViewCtrl:on_next()<CR>', {}) -- vim.api.nvim_buf_set_keymap(delegate.buf, 'n', 'j', '<cmd> lua ListViewCtrl:on_next()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'i', '<Up>', '<cmd> lua ListViewCtrl:on_prev()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'i', '<Down>', '<cmd> lua ListViewCtrl:on_next()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'i', '<C-b>', '<cmd> lua ListViewCtrl:on_pageup()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'i', '<C-f>', '<cmd> lua ListViewCtrl:on_pagedown()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'i', '<PageUp>', '<cmd> lua ListViewCtrl:on_pageup()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'i', '<PageDown>', '<cmd> lua ListViewCtrl:on_pagedown()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<C-b>', '<cmd> lua ListViewCtrl:on_pageup()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<C-f>', '<cmd> lua ListViewCtrl:on_pagedown()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<PageUp>', '<cmd> lua ListViewCtrl:on_pageup()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<PageDown>', '<cmd> lua ListViewCtrl:on_pagedown()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<C-o>', '<cmd> lua ListViewCtrl:on_confirm()<CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<C-v>', "<cmd> lua ListViewCtrl:on_confirm({split='v'})<CR>", {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<C-s>', "<cmd> lua ListViewCtrl:on_confirm({split='s'})<CR>", {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'i', '<C-o>', '<cmd> lua ListViewCtrl:on_confirm()<CR>', {}) log('bind close', self.m_delegate.win, delegate.buf) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<C-e>', '<cmd> lua ListViewCtrl:on_close() <CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<C-c>', '<cmd> lua ListViewCtrl:on_close() <CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', '<ESC>', '<cmd> lua ListViewCtrl:on_close() <CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'i', '<BS>', '<cmd> lua ListViewCtrl:on_backspace() <CR>', {}) vim.api.nvim_buf_set_keymap(delegate.buf, 'i', '<C-W>', '<cmd> lua ListViewCtrl:on_backspace(true) <CR>', {}) for i = 1, 9 do local cmd = string.format('<cmd> lua ListViewCtrl:on_item(%i)<CR>', i) vim.api.nvim_buf_set_keymap(delegate.buf, 'n', tostring(i), cmd, {}) -- vim.api.nvim_buf_set_keymap(delegate.buf, 'i', tostring(i), cmd, {}) end vim.cmd([[ autocmd TextChangedI,TextChanged <buffer> lua ListViewCtrl:on_search() ]]) vim.cmd([[ autocmd WinLeave <buffer> ++once lua ListViewCtrl:on_leave() ]]) -- ListViewCtrl._viewctlobject = self -- self:on_draw(self.display_data) -- self.m_delegate:set_pos(self.selected_line) -- trace("listview ctrl created ", self) log('listview ctrl created ') end function ListViewCtrl:get_ui() return self.m_delegate end function ListViewCtrl:wrap_closer(o) if o == nil then log('nil closer', debug.traceback()) return end if o.class and o.class.name == 'TextView' then -- ListViewCtrl._viewctlobject.win = o.ActiveView.win -- ListViewCtrl._viewctlobject.buf = o.ActiveView.buf log('bind closer', o.class.name) end end function ListViewCtrl:on_next() local listobj = ListViewCtrl._viewctlobject if listobj.selected_line == nil then listobj.selected_line = 1 end local l = listobj.selected_line + 1 local data_collection = listobj.data if listobj.filter_applied then data_collection = listobj.filtered_data end if #data_collection == 0 then return {} end local disp_h = listobj.display_height if listobj.m_delegate.prompt == true then disp_h = disp_h - 1 end trace('next: ', listobj.selected_line, listobj.display_start_at, listobj.display_height, l, disp_h) if l > #data_collection then -- listobj.m_delegate:set_pos(disp_h) -- do not move to next -- listobj.on_move(data_collection[#data_collection]) log('out of boundary next should show at: ', #listobj.data, 'set: l', l, 'disp_h', disp_h, listobj.display_height) return {} end local skipped_fn = 1 if data_collection[l].filename_only then if l + 1 <= #data_collection then l = l + 1 skipped_fn = 2 else return {} end end if l + 1 > listobj.display_start_at + disp_h then -- need to scroll next listobj.display_start_at = listobj.display_start_at + skipped_fn listobj.display_data = { unpack(data_collection, listobj.display_start_at, listobj.display_start_at + disp_h - 1), } trace('disp', listobj.display_data, disp_h, listobj.display_start_at) listobj.m_delegate:on_draw(listobj.display_data) listobj.m_delegate:set_pos(disp_h) else -- preview here -- listobj.m_delegate:on_draw(listobj.display_data) listobj.m_delegate:set_pos(l - listobj.display_start_at + 1) end -- log("next should show: ", listobj.display_data[l].text or listobj.display_data[l], listobj.display_start_at) listobj.selected_line = l self:wrap_closer(listobj.on_move(data_collection[l])) return data_collection[listobj.selected_line] end local function item_text(data_collection, idx) local text if idx < 1 or idx > #data_collection then error('error: idx out of range', #data_collection, idx) end if type(data_collection[idx]) == 'string' then text = data_collection[idx] elseif data_collection[idx].display_data ~= nil then text = data_collection[idx].display_data elseif data_collection[idx].text ~= nil then text = data_collection[idx].text end return text end -- if list start with [i] then select the [i], otherwise return ith item function ListViewCtrl:on_item(i) if i < 1 then i = 1 end local listobj = ListViewCtrl._viewctlobject if listobj == nil then log('incorrect on_prev context', ListViewCtrl) return end local data_collection = listobj.data if i > #data_collection then i = #data_collection end local idx for j = i, i + 3 do log(data_collection[j]) if j > #data_collection then break end if data_collection[j] and data_collection[j].idx == i then idx = j break end local t = item_text(data_collection, j) local f = string.find(t or '', tostring(i)) if f ~= nil and f < 4 then idx = j break end end if idx then i = idx end listobj.m_delegate:set_pos(i) listobj.selected_line = i log('select ', i, data_collection[listobj.selected_line]) self:wrap_closer(listobj.on_move(data_collection[i])) return data_collection[listobj.selected_line] end function ListViewCtrl:on_prev() local listobj = ListViewCtrl._viewctlobject if listobj == nil then log('incorrect on_prev context', ListViewCtrl) return end local disp_h = listobj.display_height if listobj.m_delegate.prompt == true then disp_h = disp_h - 1 end log( 'on prev: ', listobj.selected_line, listobj.display_start_at, disp_h, listobj.display_height, listobj.m_delegate.prompt ) local data_collection = listobj.data if listobj.filter_applied then data_collection = listobj.filtered_data end if #data_collection == 0 then return {} end if listobj.selected_line == nil then listobj.selected_line = 1 end local l = listobj.selected_line - 1 if l < 1 then listobj.m_delegate:set_pos(1) self:wrap_closer(listobj.on_move(data_collection[1])) return end local skipped_fn = 1 if data_collection[l].filename_only and l > 1 then trace('skip filename') skipped_fn = 2 l = l - 1 end if l < listobj.display_start_at and listobj.display_start_at >= 1 then -- need to scroll back log('roll back to ', listobj.display_start_at - 1) listobj.display_start_at = listobj.display_start_at - skipped_fn listobj.display_data = { unpack(data_collection, listobj.display_start_at, listobj.display_start_at + disp_h - 1), } trace('dispdata', listobj.display_data) listobj.m_delegate:on_draw(listobj.display_data) listobj.m_delegate:set_pos(1) else -- listobj:on_draw(listobj.display_data) log('move to', l, listobj.display_start_at, l - listobj.display_start_at + 1) listobj.m_delegate:set_pos(l - listobj.display_start_at + 1) end log('prev: ', l) -- log("prev: ", l, listobj.display_data[l].text or listobj.display_data[l]) listobj.selected_line = l self:wrap_closer(listobj.on_move(data_collection[l])) return data_collection[listobj.selected_line] end function ListViewCtrl:on_pagedown() local listobj = ListViewCtrl._viewctlobject if listobj.selected_line == nil then listobj.selected_line = 1 end local data_collection = listobj.data if listobj.filter_applied then data_collection = listobj.filtered_data end local disp_h = listobj.display_height if listobj.m_delegate.prompt == true then disp_h = disp_h - 1 end local l = listobj.display_start_at + disp_h trace('pagedown: ', listobj.selected_line, listobj.display_start_at, listobj.display_height, l, disp_h) if #data_collection == 0 then return {} end if l > #data_collection then listobj.m_delegate:set_pos(disp_h) listobj.on_move(data_collection[#data_collection]) log('next should show at: ', #listobj.data, 'set: ', disp_h, listobj.display_height) return end -- if l > listobj.display_start_at + disp_h - 1 then -- need to scroll next listobj.display_start_at = listobj.display_start_at + disp_h listobj.display_data = { unpack(data_collection, listobj.display_start_at, listobj.display_start_at + disp_h - 1), } trace('disp', listobj.display_data, disp_h, listobj.display_start_at) listobj.m_delegate:on_draw(listobj.display_data) listobj.m_delegate:set_pos(disp_h) -- log("next should show: ", listobj.display_data[l].text or listobj.display_data[l], listobj.display_start_at) listobj.selected_line = l self:wrap_closer(listobj.on_move(data_collection[l])) return data_collection[listobj.selected_line] end function ListViewCtrl:on_pageup() local listobj = ListViewCtrl._viewctlobject if listobj.selected_line == nil then listobj.selected_line = 1 end local data_collection = listobj.data if listobj.filter_applied then data_collection = listobj.filtered_data end local disp_h = listobj.display_height if listobj.m_delegate.prompt == true then disp_h = disp_h - 1 end local l = listobj.display_start_at - disp_h trace('pagedown: ', listobj.selected_line, listobj.display_start_at, listobj.display_height, l, disp_h) if l < 1 then listobj.m_delegate:set_pos(1) listobj.on_move(data_collection[1]) log('prev should show at: ', #listobj.data, 'set: ', disp_h, listobj.display_height) return end -- if l > listobj.display_start_at + disp_h - 1 then -- need to scroll next listobj.display_start_at = listobj.display_start_at - disp_h listobj.display_data = { unpack(data_collection, listobj.display_start_at, listobj.display_start_at + disp_h - 1), } trace('disp', listobj.display_data, disp_h, listobj.display_start_at) listobj.m_delegate:on_draw(listobj.display_data) listobj.m_delegate:set_pos(disp_h) -- log("next should show: ", listobj.display_data[l].text or listobj.display_data[l], listobj.display_start_at) listobj.selected_line = l self:wrap_closer(listobj.on_move(data_collection[l])) return data_collection[listobj.selected_line] end function ListViewCtrl:on_confirm(opts) local listobj = ListViewCtrl._viewctlobject local data_collection = listobj.data if listobj.filter_applied then data_collection = listobj.filtered_data end listobj.m_delegate:close() -- trace(listobj.m_delegate) if listobj.on_confirm == ListViewCtrl.on_confirm then return end listobj.on_confirm(data_collection[listobj.selected_line], opts) end function ListViewCtrl:on_search() -- local cursor = vim.api.nvim_win_get_cursor(0) trace(debug.traceback()) -- trace = log local listobj = ListViewCtrl._viewctlobject if listobj.m_delegate.prompt ~= true then return end local fzy = require('fzy').fzy if fzy == nil then print('[ERR] fzy not found') return end local listobj = ListViewCtrl._viewctlobject if listobj == nil then log('on search failed, no listviewCTRL') -- why on_search bind here? return end local buf = listobj.m_delegate.buf if not vim.api.nvim_buf_is_valid(buf) then return end local filter_input = vim.api.nvim_buf_get_lines(buf, -2, -1, false)[1] -- get string after prompt local filter_input_trim = string.sub(filter_input, 5, #filter_input) log('filter input:', filter_input_trim, 'input:', filter_input) if listobj.search_item == filter_input_trim then return -- same filter may caused by none-search field change end listobj.search_item = filter_input_trim if #filter_input_trim == 0 or #listobj.data == nil or #listobj.data == 0 then listobj.filter_applied = false listobj.filtered_data = vim.deepcopy(listobj.data) -- filter is not applied, clean up cache data listobj.display_data = { unpack(listobj.filtered_data, 1, listobj.display_height) } listobj.filter_applied = true listobj.display_start_at = 1 -- reset listobj:on_draw(listobj.display_data) vim.api.nvim_buf_clear_namespace(buf, _GH_SEARCH_NS, 0, -1) return else listobj.filtered_data = fzy(filter_input_trim, listobj.data) end trace('filtered data', listobj.filtered_data) listobj.display_data = { unpack(listobj.filtered_data, 1, listobj.display_height) } listobj.filter_applied = true listobj.display_start_at = 1 -- reset -- trace('filtered data', listobj.display_data) listobj:on_draw(listobj.display_data) listobj.selected_line = 1 listobj.m_delegate:set_pos(1) vim.api.nvim_buf_set_lines(buf, -2, -1, true, { filter_input }) -- log(cursor) -- vim.api.nvim_win_set_cursor(0, cursor) vim.cmd([[normal! A]]) vim.cmd('startinsert!') log('on search ends') end function ListViewCtrl:on_backspace(deleteword) local listobj = ListViewCtrl._viewctlobject local buf = listobj.m_delegate.buf local filter_input = vim.api.nvim_buf_get_lines(buf, -2, -1, false)[1] local filter_input_trim = string.sub(filter_input, 5, #filter_input) if #filter_input_trim == 0 then -- filter_input = string.sub(filter_input, 1, -2) return end vim.cmd([[stopi]]) if deleteword then vim.cmd([[normal! diw]]) else vim.cmd([[normal! cl]]) end vim.cmd([[normal! A]]) vim.cmd('startinsert!') -- log(filter_input) -- vim.api.nvim_buf_set_lines(buf, -2, -1, true, {filter_input}) -- log(filter_input) -- log("on search ends") end function ListViewCtrl:on_close() log('closer listview') -- , ListViewCtrl._viewctlobject.m_delegate) ListViewCtrl._viewctlobject.m_delegate.close() -- log("closer ", ListViewCtrl) ListViewCtrl._viewctlobject.m_delegate:on_close() ListViewCtrl:on_leave(true) ListViewCtrl._viewctlobject = nil end function ListViewCtrl:on_leave(force) log('closer background') -- , ListViewCtrl._viewctlobject.m_delegate) vim.defer_fn(function() -- return if ListViewCtrl._viewctlobject and ListViewCtrl._viewctlobject.m_delegate then if force then ListViewCtrl._viewctlobject.m_delegate.close() end if not on_preview() then ListViewCtrl._viewctlobject.m_delegate.close() end end end, 200) end function ListViewCtrl:on_data_update(data) local listobj = ListViewCtrl._viewctlobject listobj.data = data -- disable data end return ListViewCtrl
--Check Environment if GetConvar('txAdminServerMode', 'false') ~= 'true' then return end RegisterNetEvent('txAdmin:menu:drunkEffectPlayer', function(id) local src = source local allow = PlayerHasTxPermission(src, 'players.troll') if allow then TriggerClientEvent('txAdmin:menu:drunkEffect', id) end TriggerEvent('txaLogger:menuEvent', src, 'drunkEffect', allow, id) end) RegisterNetEvent('txAdmin:menu:setOnFire', function(id) local src = source local allow = PlayerHasTxPermission(src, 'players.troll') if allow then TriggerClientEvent('txAdmin:menu:setOnFire', id) end TriggerEvent('txaLogger:menuEvent', src, 'setOnFire', allow, id) end) RegisterNetEvent('txAdmin:menu:wildAttack', function(id) local src = source local allow = PlayerHasTxPermission(src, 'players.troll') if allow then TriggerClientEvent('txAdmin:menu:wildAttack', id) end TriggerEvent('txaLogger:menuEvent', src, 'wildAttack', allow, id) end)
---@class CS.UnityEngine.DrivenRectTransformTracker : CS.System.ValueType ---@type CS.UnityEngine.DrivenRectTransformTracker CS.UnityEngine.DrivenRectTransformTracker = { } function CS.UnityEngine.DrivenRectTransformTracker.StopRecordingUndo() end function CS.UnityEngine.DrivenRectTransformTracker.StartRecordingUndo() end ---@param driver CS.UnityEngine.Object ---@param rectTransform CS.UnityEngine.RectTransform ---@param drivenProperties number function CS.UnityEngine.DrivenRectTransformTracker:Add(driver, rectTransform, drivenProperties) end function CS.UnityEngine.DrivenRectTransformTracker:Clear() end return CS.UnityEngine.DrivenRectTransformTracker
object_mobile_dressed_sayromi_monk_06 = object_mobile_shared_dressed_sayromi_monk_06:new { } ObjectTemplates:addTemplate(object_mobile_dressed_sayromi_monk_06, "object/mobile/dressed_sayromi_monk_06.iff")
-- This is pretty scuffed code. I will rewrite it later local format, typev, string, concat = string.format, type, tostring, table.concat; local op = {}; for i,v in pairs(require("src/op")) do op[v] = i; end; local function Disassemble(chunk, id) local id = id or 0; local Instructions = chunk.code; local Constants = chunk.const; local out = format("Proto[%d]\n> #Stack: %d\n> #Params: %d\n> #Name: \"%s\"\n\nConstants[%d]\n", id, chunk.maxstacksize, chunk.numparams, chunk.name or "undefined", chunk.sizek - 1); for i,v in pairs(Constants) do out = out .. format("> [%d] (%s) \"%s\"\n", i - 1, typev(v), string(v)); end; out = out .. format("\nInstructions[%d]\n", chunk.sizecode - 1); for i,v in pairs(Instructions) do local Opcode = op[v.Opcode + 1] or string(v.Opcode); local Registers = v.Reg; local Code = v.Code; local B = Registers[2] + 1; local Deduct = ""; if Opcode == "LOP_GETIMPORT" then if Constants[B] then Deduct = format(" / R[2] = %s (%s)", string(Constants[B]), Constants[B - 1]); else Deduct = format(" / R[2] = Env[\"%s\"]", Constants[B - 1]); end; elseif Opcode == "LOP_LOADK" then Deduct = format(" / R[2] = \"%s\"", string(Constants[B])); end; out = out .. format("> [%d->%d] %s { %s }%s\n", i - 1, Code, Opcode, concat(Registers, ", "), Deduct); end; for i,v in pairs(chunk.p) do out = out .. "\n" .. Disassemble(v, i); end; return out; end; return Disassemble;
-- bitters -- -- lo-fi FM-capable mono/poly -- llllllll.co/t/bitters-norns -- -- @alanza -- v0.1 -- engine.name = "Bitters" function init() local needs_restart = false if not util.file_exists("/home/we/.local/share/SuperCollider/Extensions/TrianglePTR/TrianglePTR_scsynth.so") then util.os_capture("mkdir /home/we/.local/share/SuperCollider/Extensions/TrianglePTR") util.os_capture("cp /home/we/dust/code/bitters/bin/TrianglePTR/TrianglePTR_scsynth.so /home/we/.local/share/SuperCollider/Extensions/TrianglePTR/TrianglePTR_scsynth.so") print("installed TrianglePTR, please restart norns") needs_restart = true end if not util.file_exists("/home/we/.local/share/SuperCollider/Extensions/PulsePTR/PulsePTR_scsynth.so") then util.os_capture("mkdir /home/we/.local/share/SuperCollider/Extensions/PulsePTR") util.os_capture("cp /home/we/dust/code/bitters/bin/PulsePTR/PulsePTR_scsynth.so /home/we/.local/share/SuperCollider/Extensions/PulsePTR/PulsePTR_scsynth.so") print("installed PulsePTR, please restart norns") needs_restart = true end parameters = include("lib/parameters") parameters.init() notes = include("lib/notes") notes.init() page = include("lib/page") page:init(needs_restart) half_second = include("lib/halfsecond") half_second.init() screen_dirty = true params:bang() end function key(n,z) if n == 2 then page:left() elseif n == 3 then page:right() end screen_dirty = true end function enc(n,d) if n == 1 then if d < 0 then page:left() else page:right() end elseif n == 2 then page:scroll(d) elseif n == 3 then page:delta(d) end screen_dirty = true end function r() norns.script.load(norns.state.script) end
vim.api.nvim_exec([[ au FileType ledger nm <silent> <tab> :set ep=ledger\ -f\ -\ print<cr>= au FileType ledger xn <silent> <tab> :<c-u>set ep=ledger\ -f\ -\ print<cr>gv= au FileType ledger se commentstring=;\ %s ]], true)
local haslspconfig, lspconfig = pcall(require, 'lspconfig') if haslspconfig then local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true local on_attach = function(client, bufnr) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') -- require'completion'.on_attach() -- Mappings. local opts = { noremap=true, silent=true } buf_set_keymap('n', 'gD', '<Cmd>lua vim.lsp.buf.declaration()<CR>', opts) buf_set_keymap('n', 'gd', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts) buf_set_keymap('n', 'K', '<Cmd>lua vim.lsp.buf.hover()<CR>', opts) buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts) buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts) buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts) buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts) buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts) buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts) buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts) buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts) buf_set_keymap('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts) buf_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts) buf_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts) --buf_set_keymap('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts) -- Set some keybinds conditional on server capabilities if client.resolved_capabilities.document_formatting then buf_set_keymap("n", "<space>F", "<cmd>lua vim.lsp.buf.formatting()<CR>", opts) elseif client.resolved_capabilities.document_range_formatting then buf_set_keymap("n", "<space>f", "<cmd>lua vim.lsp.buf.range_formatting()<CR>", opts) end -- Set autocommands conditional on server_capabilities if client.resolved_capabilities.document_highlight then vim.api.nvim_exec([[ hi LspReferenceRead cterm=bold ctermbg=red guibg=LightYellow hi LspReferenceText cterm=bold ctermbg=red guibg=LightYellow hi LspReferenceWrite cterm=bold ctermbg=red guibg=LightYellow augroup lsp_document_highlight autocmd! " autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() " autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() augroup END ]], false) end end -- Use a loop to conveniently both setup defined servers -- and map buffer local keybindings when the language server attaches local servers = { -- "pyright", "rust_analyzer", "tsserver", "vimls", "intelephense", "pylsp", -- "pyright", "bashls", "julials", "clangd", "texlab", "html", "jsonls", "cssls", "vimls", "sqls", } for _, lsp in ipairs(servers) do lspconfig[lsp].setup { on_attach = on_attach, capabilities = capabilities, } end -- sumneko_lua local runtime_path = vim.split(package.path, ';') table.insert(runtime_path, "lua/?.lua") table.insert(runtime_path, "lua/?/init.lua") require'lspconfig'.sumneko_lua.setup { on_attach = on_attach, capabilities = capabilities, settings = { Lua = { runtime = { -- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim) version = 'LuaJIT', -- Setup your lua path path = runtime_path, }, diagnostics = { -- Get the language server to recognize the `vim` global globals = {'vim'}, }, workspace = { -- Make the server aware of Neovim runtime files library = vim.api.nvim_get_runtime_file("", true), }, -- Do not send telemetry data containing a randomized but unique identifier telemetry = { enable = false, }, }, }, } end -- if haslspconfig
-- decorateHelp - Release 1.1 - For tes3mp v0.6.1 -- Alter positions of items using a GUI --[[ INSTALLATION: 1) Save this file as "decorateHelp.lua" in mp-stuff/scripts 2) Add [ decorateHelp = require("decorateHelp") ] to the top of server.lua 3) Add the following to the elseif chain for commands in "OnPlayerSendMessage" inside server.lua [ elseif cmd[1] == "decorator" or cmd[1] == "decorate" or cmd[1] == "dh" then decorateHelp.OnCommand(pid) ] 4) Add the following to OnGUIAction in server.lua [ if decorateHelp.OnGUIAction(pid, idGui, data) then return end ] 5) Add the following to OnObjectPlace in server.lua [ decorateHelp.OnObjectPlace(pid, cellDescription) ] 6) Add the following to OnPlayerCellChange in server.lua [ decorateHelp.OnPlayerCellChange(pid) ] ]] ------ local config = {} config.MainId = 31360 config.PromptId = 31361 ------ local Methods = {} tableHelper = require("tableHelper") -- local playerSelectedObject = {} local playerCurrentMode = {} --Returns the object's data from a loaded cell. Doesn't need to load the cell because this assumes it'll always be called in a cell that's loaded. local function getObject(refIndex, cell) if refIndex == nil then return false end if LoadedCells[cell]:ContainsObject(refIndex) then return LoadedCells[cell].data.objectData[refIndex] else return false end end local function resendPlaceToAll(refIndex, cell) local object = getObject(refIndex, cell) if not object then return false end local refId = object.refId local count = object.count or 1 local charge = object.charge or -1 local posX, posY, posZ = object.location.posX, object.location.posY, object.location.posZ local rotX, rotY, rotZ = object.location.rotX, object.location.rotY, object.location.rotZ local refIndex = refIndex local inventory = object.inventory or nil local splitIndex = refIndex:split("-") for pid, pdata in pairs(Players) do if Players[pid]:IsLoggedIn() then --First, delete the original tes3mp.InitializeEvent(pid) tes3mp.SetEventCell(cell) tes3mp.SetObjectRefNumIndex(0) tes3mp.SetObjectMpNum(splitIndex[2]) tes3mp.AddWorldObject() --? tes3mp.SendObjectDelete() --Now remake it tes3mp.InitializeEvent(pid) tes3mp.SetEventCell(cell) tes3mp.SetObjectRefId(refId) tes3mp.SetObjectCount(count) tes3mp.SetObjectCharge(charge) tes3mp.SetObjectPosition(posX, posY, posZ) tes3mp.SetObjectRotation(rotX, rotY, rotZ) tes3mp.SetObjectRefNumIndex(0) tes3mp.SetObjectMpNum(splitIndex[2]) if inventory then for itemIndex, item in pairs(inventory) do tes3mp.SetContainerItemRefId(item.refId) tes3mp.SetContainerItemCount(item.count) tes3mp.SetContainerItemCharge(item.charge) tes3mp.AddContainerItem() end end tes3mp.AddWorldObject() tes3mp.SendObjectPlace() if inventory then tes3mp.SendContainer() end end end LoadedCells[cell]:Save() --Not needed, but it's nice to do anyways end local function showPromptGUI(pid) local message = "[" .. playerCurrentMode[tes3mp.GetName(pid)] .. "] - Enter a number to add/subtract." tes3mp.InputDialog(pid, config.PromptId, message) end local function onEnterPrompt(pid, data) local cell = tes3mp.GetCell(pid) local pname = tes3mp.GetName(pid) local mode = playerCurrentMode[pname] local data = tonumber(data) or 0 local object = getObject(playerSelectedObject[pname], cell) if not object then --The object no longer exists, so we should bail out now return false end if mode == "Rotate X" then local curDegrees = math.deg(object.location.rotX) local newDegrees = (curDegrees + data) % 360 object.location.rotX = math.rad(newDegrees) elseif mode == "Rotate Y" then local curDegrees = math.deg(object.location.rotY) local newDegrees = (curDegrees + data) % 360 object.location.rotY = math.rad(newDegrees) elseif mode == "Rotate Z" then local curDegrees = math.deg(object.location.rotZ) local newDegrees = (curDegrees + data) % 360 object.location.rotZ = math.rad(newDegrees) elseif mode == "Move North" then object.location.posY = object.location.posY + data elseif mode == "Move East" then object.location.posX = object.location.posX + data elseif mode == "Move Up" then object.location.posZ = object.location.posZ + data elseif mode == "Scale Up" then --Not sure how scale works atm. --TODO return end resendPlaceToAll(playerSelectedObject[pname], cell) end local function showMainGUI(pid) --Determine if the player has an item local currentItem = "None" --default local selected = playerSelectedObject[tes3mp.GetName(pid)] local object = getObject(selected, tes3mp.GetCell(pid)) if selected and object then --If they have an entry and it isn't gone currentItem = object.refId .. " (" .. selected .. ")" end local message = "Select an option. Your current item: " .. currentItem tes3mp.CustomMessageBox(pid, config.MainId, message, "Move North;Move East;Move Up;Rotate X;Rotate Y;Rotate Z;Scale Up;Grab;Close") end local function setSelectedObject(pid, refIndex) playerSelectedObject[tes3mp.GetName(pid)] = refIndex end Methods.SetSelectedObject = function(pid, refIndex) setSelectedObject(pid, refIndex) end Methods.OnObjectPlace = function(pid, cellDescription) --Get the last event, which should hopefully be the place packet tes3mp.ReadLastEvent() --Get the refIndex of the first item in the object place packet (in theory, there should only by one) local refIndex = tes3mp.GetObjectRefNumIndex(0) .. "-" .. tes3mp.GetObjectMpNum(0) --Record that item as the last one the player interacted with in this cell setSelectedObject(pid, refIndex) end Methods.OnGUIAction = function(pid, idGui, data) local pname = tes3mp.GetName(pid) if idGui == config.MainId then if tonumber(data) == 0 then --Move North playerCurrentMode[pname] = "Move North" showPromptGUI(pid) return true elseif tonumber(data) == 1 then --Move East playerCurrentMode[pname] = "Move East" showPromptGUI(pid) return true elseif tonumber(data) == 2 then --Move Up playerCurrentMode[pname] = "Move Up" showPromptGUI(pid) return true elseif tonumber(data) == 3 then --Rotate X playerCurrentMode[pname] = "Rotate X" showPromptGUI(pid) return true elseif tonumber(data) == 4 then --Rotate Y playerCurrentMode[pname] = "Rotate Y" showPromptGUI(pid) return true elseif tonumber(data) == 5 then --Rotate Z playerCurrentMode[pname] = "Rotate Z" showPromptGUI(pid) return true elseif tonumber(data) == 6 then --Scale Up --TODO tes3mp.MessageBox(pid, -1, "Not yet implemented, sorry.") return true elseif tonumber(data) == 7 then --Grab --TODO tes3mp.MessageBox(pid, -1, "Not yet implemented, sorry.") return true elseif tonumber(data) == 8 then --Close --Do nothing return true end elseif idGui == config.PromptId then if data ~= nil and data ~= "" and tonumber(data) then onEnterPrompt(pid, data) end playerCurrentMode[tes3mp.GetName(pid)] = nil return true, showMainGUI(pid) end end Methods.OnPlayerCellChange = function(pid) playerSelectedObject[tes3mp.GetName(pid)] = nil end Methods.OnCommand = function(pid) showMainGUI(pid) end return Methods
--[[ Copyright (C) 2020 Onset Roleplay Developers: * Logic_ Contributors: * Blue Mountains GmbH * Kuzkay (( for the undermap script )) ]]-- local MapTime = 5 * 1000 -- 5 seconds local MapTimer = 0 -- Functions local function PlayerUnderMapCheck() local x, y, z = GetPlayerLocation() local height = GetTerrainHeight(x, y, z) if z < 0 and height - 400 > z and not IsPlayerInVehicle() then CallRemoteEvent("OnPlayerUnderMap", height) end end -- Events AddEvent("OnPackageStart", function() Delay(MapTime, function () MapTimer = CreateTimer(PlayerUnderMapCheck, MapTime) end) end)
data:extend({ { type = 'tile', name = 'factory-floor', needs_correction = false, collision_mask = {'ground-tile'}, walking_speed_modifier = 1.4, layer = 61, decorative_removal_probability = 1.0, variants = { main = { { picture = '__base__/graphics/terrain/concrete/concrete1.png', count = 16, size = 1 }, { picture = '__base__/graphics/terrain/concrete/concrete2.png', count = 4, size = 2, probability = 0.39, }, { picture = '__base__/graphics/terrain/concrete/concrete4.png', count = 4, size = 4, probability = 1, }, }, inner_corner = { picture = '__base__/graphics/terrain/concrete/concrete-inner-corner.png', count = 8 }, outer_corner = { picture = '__base__/graphics/terrain/concrete/concrete-outer-corner.png', count = 8 }, side = { picture = '__base__/graphics/terrain/concrete/concrete-side.png', count = 8 }, u_transition = { picture = '__base__/graphics/terrain/concrete/concrete-u.png', count = 8 }, o_transition = { picture = '__base__/graphics/terrain/concrete/concrete-o.png', count = 1 } }, walking_sound = { { filename = '__base__/sound/walking/concrete-01.ogg', volume = 1.2 }, { filename = '__base__/sound/walking/concrete-02.ogg', volume = 1.2 }, { filename = '__base__/sound/walking/concrete-03.ogg', volume = 1.2 }, { filename = '__base__/sound/walking/concrete-04.ogg', volume = 1.2 } }, map_color= {r=100, g=100, b=100}, ageing=0, mineable_properties= { minable=false, }, can_be_part_of_blueprint=false, }, { type = 'tile', name = 'factory-wall', needs_correction = false, collision_mask = { 'ground-tile', 'water-tile', 'resource-layer', 'floor-layer', 'item-layer', 'object-layer', 'player-layer', 'doodad-layer' }, walking_speed_modifier = 1.4, layer = 61, decorative_removal_probability = 1.0, variants = { main = { { picture = '__base__/graphics/terrain/hazard-concrete-left/hazard-concrete-left1.png', count = 16, size = 1 }, { picture = '__base__/graphics/terrain/hazard-concrete-left/hazard-concrete-left2.png', count = 4, size = 2, probability = 0.39, }, { picture = '__base__/graphics/terrain/hazard-concrete-left/hazard-concrete-left4.png', count = 4, size = 4, probability = 1, }, }, inner_corner = { picture = '__base__/graphics/terrain/hazard-concrete-left/hazard-concrete-left-inner-corner.png', count = 8 }, outer_corner = { picture = '__base__/graphics/terrain/hazard-concrete-left/hazard-concrete-left-outer-corner.png', count = 8 }, side = { picture = '__base__/graphics/terrain/hazard-concrete-left/hazard-concrete-left-side.png', count = 8 }, u_transition = { picture = '__base__/graphics/terrain/hazard-concrete-left/hazard-concrete-left-u.png', count = 8 }, o_transition = { picture = '__base__/graphics/terrain/hazard-concrete-left/hazard-concrete-left-o.png', count = 1 } }, walking_sound = { { filename = '__base__/sound/walking/concrete-01.ogg', volume = 1.2 }, { filename = '__base__/sound/walking/concrete-02.ogg', volume = 1.2 }, { filename = '__base__/sound/walking/concrete-03.ogg', volume = 1.2 }, { filename = '__base__/sound/walking/concrete-04.ogg', volume = 1.2 } }, map_color= {r=0.5, g=0.5, b=0}, ageing=0, mineable_properties= { minable=false, }, can_be_part_of_blueprint=false, }, { type = 'tile', name = 'factory-entrance', needs_correction = false, collision_mask = { 'ground-tile', 'water-tile', 'resource-layer', 'floor-layer', 'item-layer', 'object-layer', 'doodad-layer' }, walking_speed_modifier = 1.4, layer = 61, decorative_removal_probability = 1.0, allowed_neighbors = {'factory-floor', 'factory-entrance', 'factory-wall'}, variants = { main = { { picture = '__base__/graphics/terrain/concrete/concrete1.png', count = 16, size = 1 }, { picture = '__base__/graphics/terrain/concrete/concrete2.png', count = 4, size = 2, probability = 0.39, }, { picture = '__base__/graphics/terrain/concrete/concrete4.png', count = 4, size = 4, probability = 1, }, }, inner_corner = { picture = '__base__/graphics/terrain/concrete/concrete-inner-corner.png', count = 8 }, outer_corner = { picture = '__base__/graphics/terrain/concrete/concrete-outer-corner.png', count = 8 }, side = { picture = '__base__/graphics/terrain/concrete/concrete-side.png', count = 8 }, u_transition = { picture = '__base__/graphics/terrain/concrete/concrete-u.png', count = 8 }, o_transition = { picture = '__base__/graphics/terrain/concrete/concrete-o.png', count = 1 } }, walking_sound = { { filename = '__base__/sound/walking/concrete-01.ogg', volume = 1.2 }, { filename = '__base__/sound/walking/concrete-02.ogg', volume = 1.2 }, { filename = '__base__/sound/walking/concrete-03.ogg', volume = 1.2 }, { filename = '__base__/sound/walking/concrete-04.ogg', volume = 1.2 } }, map_color= {r=100, g=100, b=100}, ageing=0, mineable_properties= { minable=false, }, can_be_part_of_blueprint=false, }, })
slot0 = class("ThirdAnniversaryJPPage", import("...base.BaseActivityPage")) slot0.OnInit = function (slot0) slot0:findUI() slot0:initData() end slot0.findUI = function (slot0) slot0.paintBackTF = slot0:findTF("Paints/PaintBack") slot0.paintFrontTF = slot0:findTF("Paints/PaintFront") slot0.skinShopBtn = slot0:findTF("BtnShop") slot0.btnContainer = slot0:findTF("BtnList/Viewport/Content") slot0.btnList1 = {} for slot5 = 0, slot0.btnContainer.childCount / 2 - 1, 1 do slot0.btnList1[slot5 + 1] = slot0.btnContainer:GetChild(slot5) end slot0.btnList2 = {} for slot5 = 5, 2 * slot1 - 1, 1 do slot0.btnList2[#slot0.btnList2 + 1] = slot0.btnContainer:GetChild(slot5) end slot0.gridLayoutGroupCom = GetComponent(slot0.btnContainer, "GridLayoutGroup") end slot0.initData = function (slot0) slot0.paintCount = 18 slot0.curPaintIndex = 1 slot0.paintSwitchTime = 1 slot0.paintStaticTime = 3.5 slot0.paintStaticCountValue = 0 slot0.paintPathPrefix = "thirdanniversaryjppage/" slot0.paintNamePrefix = "paint" slot0.btnCount = slot0.btnContainer.childCount / 2 slot0.btnSpeed = 50 slot0.btnSizeX = slot0.gridLayoutGroupCom.cellSize.x slot0.btnMarginX = slot0.gridLayoutGroupCom.spacing.x slot0.moveLength = slot0.btnCount * (slot0.btnSizeX + slot0.btnMarginX) slot0.startAnchoredPosX = slot0.btnContainer.anchoredPosition.x end slot0.switchNextPaint = function (slot0) slot0.frameTimer:Stop() setImageSprite(slot0.paintBackTF, LoadSprite(slot4, slot3)) LeanTween.value(go(slot0.paintFrontTF), 1, 0, slot0.paintSwitchTime):setOnUpdate(System.Action_float(function (slot0) setImageAlpha(slot0.paintFrontTF, slot0) setImageAlpha(slot0.paintBackTF, 1 - slot0) end)).setOnComplete(slot5, System.Action(function () setImageFromImage(slot0.paintFrontTF, slot0.paintBackTF) setImageAlpha(slot0.paintFrontTF, 1) setImageAlpha(slot0.paintBackTF, 0) setImageAlpha.curPaintIndex = slot0.paintBackTF setImageAlpha.frameTimer:Start() end)) end slot0.OnFirstFlush = function (slot0) slot0:initPaint() slot0:initBtnList(slot0.btnList1) slot0:initBtnList(slot0.btnList2) slot0:initTimer() end slot0.initPaint = function (slot0) setImageSprite(slot0.paintFrontTF, LoadSprite(slot0.paintPathPrefix .. slot3, slot0.paintNamePrefix .. slot1)) setImageSprite(slot0.paintBackTF, LoadSprite(slot0.paintPathPrefix .. slot3, slot0.paintNamePrefix .. slot2)) end slot0.initBtnList = function (slot0, slot1) onButton(slot0, slot1[1], function () slot0:emit(ActivityMediator.GO_PRAY_POOL) end, SFX_PANEL) onButton(slot0, slot1[2], function () slot0:emit(ActivityMediator.EVENT_GO_SCENE, SCENE.SKINSHOP) end, SFX_PANEL) onButton(slot0, slot1[3], function () slot0:emit(ActivityMediator.SELECT_ACTIVITY, getProxy(ActivityProxy):getActivityByType(ActivityConst.ACTIVITY_TYPE_RETURN_AWARD).id) end, SFX_PANEL) onButton(slot0, slot1[4], function () slot0:emit(ActivityMediator.EVENT_GO_SCENE, SCENE.THIRD_ANNIVERSARY_AKIBA) end, SFX_PANEL) onButton(slot0, slot1[5], function () slot0:emit(ActivityMediator.SELECT_ACTIVITY, pg.activity_const.JIUJIU_ADVENTURE_ID.act_id) end, SFX_PANEL) end slot0.initTimer = function (slot0) slot1 = 0.016666666666666666 slot0.paintStaticCountValue = 0 slot0.frameTimer = Timer.New(function () slot0.paintStaticCountValue = slot0.paintStaticCountValue + if slot0.paintStaticTime <= slot0.paintStaticCountValue then slot0.paintStaticCountValue = 0 slot0:switchNextPaint() end end, slot1, -1, false) slot0.frameTimer:Start() slot0.frameTimer2 = Timer.New(function () if slot0.moveLength <= slot0.startAnchoredPosX - (slot0.btnContainer.anchoredPosition.x - slot0.btnSpeed * ) then slot0 = slot0.btnContainer.anchoredPosition.x + slot0.moveLength end slot0.btnContainer.anchoredPosition = Vector3(slot0, 0, 0) end, slot1, -1, false) slot0.frameTimer2:Start() end slot0.OnDestroy = function (slot0) if slot0.frameTimer then slot0.frameTimer:Stop() slot0.frameTimer = nil end if slot0.frameTimer2 then slot0.frameTimer2:Stop() slot0.frameTimer2 = nil end end return slot0
local req_read_body = ngx.req.read_body local req_get_body_data = ngx.req.get_body_data local _M = {} function _M.get_body() req_read_body() local body = req_get_body_data() return body end return _M
--[[-------------------------------------------------------------------------- -- -- File: UAStarterFrag.State.RoundLoop.lua -- Copyright (c) Ubisoft Entertainment. All rights reserved. -- -- Project: Ubitoys.Tag -- Date: September 21, 2010 -- ------------------------------------------------------------------------------ -- -- Description: ... -- ----------------------------------------------------------------------------]] --[[ Dependencies ----------------------------------------------------------]] require "UTActivity.State.RoundLoop" require "UAStarterFrag.Ui.RoundLoop" --[[ Class -----------------------------------------------------------------]] UAStarterFrag.State.RoundLoop = UTClass(UTActivity.State.RoundLoop) -- defaults ------------------------------------------------------------------ UAStarterFrag.State.RoundLoop.uiClass = UAStarterFrag.Ui.RoundLoop -- __ctor -------------------------------------------------------------------- function UAStarterFrag.State.RoundLoop:__ctor(activity, ...) assert(activity) end -- Begin --------------------------------------------------------------------- function UAStarterFrag.State.RoundLoop:Begin() UTActivity.State.RoundLoop.Begin(self) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_13.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_14.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_15.wav"}, probas = {0.8, 0.1, 0.1}}) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_45.wav"},offset = activity.settings.playtime * 60 - 60,}) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_48.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_49.wav"}, offset = activity.settings.playtime * 60 - 57, priority = 2, proba = 0.333}) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_46.wav"}, offset = activity.settings.playtime * 60 - 30,}) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_48.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_49.wav"}, offset = activity.settings.playtime * 60 - 27,priority = 2, proba = 0.333}) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_47.wav"}, offset = activity.settings.playtime * 60 - 15,}) game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_48.wav", "base:audio/gamemaster/DLG_GM_GLOBAL_49.wav"}, offset = activity.settings.playtime * 60 - 12, priority = 2, proba = 0.333}) -- timer self.time = quartz.system.time.gettimemicroseconds() self.shootCount = 0 self.shootCountTime = self.time activity.timer = activity.settings.playtime * 60 * 1000000 end -- Message received from device ---------------------------------------------- function UAStarterFrag.State.RoundLoop:OnDispatchMessage(device, addressee, command, arg) -- base UTActivity.State.RoundLoop.OnDispatchMessage(self) if (0x95 == command) then -- decode this msg !! if (device.owner) then -------------------------------------------------------------------------------------- -- ammunitions and clip local ammunitions = (arg[4] * 256) + arg[5] if (ammunitions == 3) then if (game.settings.audio.gmtalkative == 1) then -- throw "We need Ammo! Now" sound game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_22.wav","base:audio/gamemaster/DLG_GM_GLOBAL_23.wav"},priority = 3,}) end end local clips = (arg[6] * 256) + arg[7] if (device.owner.data.heap.ammunitions < ammunitions and device.owner.data.heap.clips <= clips or device.owner.data.heap.clips < clips) then device.owner.data.heap.nbAmmoPack = device.owner.data.heap.nbAmmoPack + 1 activity.uiAFP:PushLine(device.owner.profile.name .. " " .. l"ingame006", UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Ammunition.tga") end if (device.owner.data.heap.ammunitions > ammunitions) then device.owner.data.heap.nbShot = device.owner.data.heap.nbShot + (device.owner.data.heap.ammunitions - ammunitions) device.owner.data.heap.hitLost = device.owner.data.heap.hitLost + 1 if (device.owner.data.heap.hitLost == 5) then if (game.settings.audio.gmtalkative == 1) then -- throw "T'es aveugle" sound game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_43.wav","base:audio/gamemaster/DLG_GM_GLOBAL_44.wav"},priority = 2,}) end device.owner.data.heap.hitLost = 0 end if (device.owner.data.heap.hitLost >= 2) then device.owner.data.nbHitLastPlayerShooted = 0 end end device.owner.data.heap.clips = clips device.owner.data.heap.ammunitions = ammunitions if (device.owner.data.heap.ammunitions == 20) then device.owner.data.heap.ammunitionsAndClips = "-/-" else device.owner.data.heap.ammunitionsAndClips = device.owner.data.heap.ammunitions .. "/" .. device.owner.data.heap.clips end -------------------------------------------------------------------------------------- -- nb hits local nbHit = (arg[2] * 256) + arg[3] -- check if I have been shot ... if (device.owner.data.heap.nbHit < nbHit) then if (self.shootCount) then self.shootCount = self.shootCount + 1 if (self.shootCount == 10) then local time = quartz.system.time.gettimemicroseconds() if (time - self.shootCountTime < 10 * 1000000) then if (game.settings.audio.gmtalkative == 1) then -- ouais jsuis a donf game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_24.wav","base:audio/gamemaster/DLG_GM_GLOBAL_25.wav","base:audio/gamemaster/DLG_GM_GLOBAL_121.wav","base:audio/gamemaster/DLG_GM_GLOBAL_133.wav","base:audio/gamemaster/DLG_GM_GLOBAL_134.wav",}, priority = 2, proba = 0.25}) end end self.shootCountTime = time self.shootCount = 0 end end local curIndex = math.max(0, nbHit - device.owner.data.heap.nbHit) while (curIndex > 0) do -- loose one life device.owner.data.heap.nbHit = device.owner.data.heap.nbHit + 1 -- get device that shot me local shooterDevice = engine.libraries.usb.proxy.devices.byRadioProtocolId[arg[math.min(12, curIndex + 7)]] curIndex = curIndex - 1 if (shooterDevice) then -- get shooter local shooter = shooterDevice.owner --!! give him point : DO this better if (shooter) then -- HIT ------------------------------------------------------ if (shooter.data.heap.lastPlayerShooted == device.owner) then shooter.data.heap.nbHitLastPlayerShooted = shooter.data.heap.nbHitLastPlayerShooted + 1 if (shooter.data.heap.nbHitLastPlayerShooted == 3) then if (game.settings.audio.gmtalkative == 1) then -- throw "Tireur d'�lite" sound game.gameMaster:RegisterSound({ paths = {"base:audio/gamemaster/DLG_GM_GLOBAL_26.wav","base:audio/gamemaster/DLG_GM_GLOBAL_122.wav","base:audio/gamemaster/DLG_GM_GLOBAL_123.wav","base:audio/gamemaster/DLG_GM_GLOBAL_124.wav",}, priority = 3, proba = 0.33}) end shooter.data.heap.nbHitLastPlayerShooted = 0 end else shooter.data.heap.nbHitLastPlayerShooted = 1 shooter.data.heap.lastPlayerShooted = device.owner end shooter.data.heap.hitLost = 0 shooter.data.heap.score = shooter.data.heap.score + 1 shooter.data.heap.hit = shooter.data.heap.hit + 1 activity.uiAFP:PushLine(shooter.profile.name .. " " .. l"ingame009" .. " " .. device.owner.profile.name, UIComponent.colors.gray, "base:texture/Ui/Icons/16x/Hit.tga") shooter.data.heap.hitByName[device.owner.nameId] = (shooter.data.heap.hitByName[device.owner.nameId] or 0) + 1 end end end end device.owner.data.heap.nbHit = nbHit end end end -- Update --------------------------------------------------------------------- function UAStarterFrag.State.RoundLoop:Update() UTActivity.State.RoundLoop.Update(self) -- end match if (activity.timer <= 0) then activity:PostStateChange("endround") end end
local server = require "nvim-lsp-installer.server" local Data = require "nvim-lsp-installer.data" local platform = require "nvim-lsp-installer.platform" local github = require "nvim-lsp-installer.core.managers.github" local process = require "nvim-lsp-installer.process" local path = require "nvim-lsp-installer.path" local coalesce, when = Data.coalesce, Data.when return function(name, root_dir) return server.Server:new { name = name, root_dir = root_dir, languages = { "codeql" }, async = true, installer = function() github.unzip_release_file({ repo = "github/codeql-cli-binaries", asset_file = coalesce( when(platform.is_mac, "codeql-osx64.zip"), when(platform.is_unix, "codeql-linux64.zip"), when(platform.is_win, "codeql-win64.zip") ), }).with_receipt() end, default_options = { cmd_env = { PATH = process.extend_path { path.concat { root_dir, "codeql" } }, }, }, } end
LinkLuaModifier("modifier_sai_rage_of_pain", "heroes/hero_sai/rage_of_pain.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_sai_rage_of_pain_mass_debuff", "heroes/hero_sai/rage_of_pain.lua", LUA_MODIFIER_MOTION_NONE) sai_rage_of_pain = class({ GetIntrinsicModifierName = function() return "modifier_sai_rage_of_pain" end, }) modifier_sai_rage_of_pain = class({}) function modifier_sai_rage_of_pain:DeclareFunctions() return { MODIFIER_PROPERTY_PREATTACK_CRITICALSTRIKE, MODIFIER_PROPERTY_BASEDAMAGEOUTGOING_PERCENTAGE } end if IsServer() then function modifier_sai_rage_of_pain:OnCreated() self:StartIntervalThink(0.1) self:OnIntervalThink() end end function modifier_sai_rage_of_pain:OnIntervalThink() local ability = self:GetAbility() local parent = self:GetParent() local health_per_stack_pct = ability:GetSpecialValueFor("health_per_stack_pct") self:SetStackCount(health_per_stack_pct - math.ceil(parent:GetHealth() / parent:GetMaxHealth() * health_per_stack_pct)) end function modifier_sai_rage_of_pain:GetModifierPreAttack_CriticalStrike(keys) local ability = self:GetAbility() local stacks = self:GetStackCount() local chance = ability:GetSpecialValueFor("crit_chance_pct") + ability:GetSpecialValueFor("crit_chance_per_stack_pct") * stacks if RollPercentage(chance) then return 100 + self:GetAbility():GetSpecialValueFor("crit_mult_pre_stack_pct") * stacks end end function modifier_sai_rage_of_pain:GetModifierBaseDamageOutgoing_Percentage(keys) local ability = self:GetAbility() return (ability:GetSpecialValueFor("damage_per_stack_pct") + self:GetParent():GetMaxMana() / ability:GetSpecialValueFor("mana_for_bonus_damage")) * self:GetStackCount() end
object_tangible_quest_som_crystal_marker_03 = object_tangible_quest_shared_som_crystal_marker_03:new { } ObjectTemplates:addTemplate(object_tangible_quest_som_crystal_marker_03, "object/tangible/quest/som_crystal_marker_03.iff")
local Prop = {} Prop.Name = "Nº24 Esquina da Gole de Skol" Prop.Cat = "House" Prop.Price = 340 Prop.Doors = { Vector(-1005.9299926758, 308.36401367188, -141.71899414063), Vector(-842, 87, 250), } GM.Property:Register( Prop )
local util = require("lspconfig.util") local bashls = {} bashls.root_dir = function(filename) return util.find_git_ancestor(filename) or util.path.dirname(filename) end return bashls
--[[ main.lua Copyright (c) 2017 andynines MIT License ]] local simulation = require("bugevo") local FIELD_X = simulation.FIELD_X local FIELD_Y = simulation.FIELD_Y local CODES = simulation.CODES local initialize = simulation.initialize local iterate = simulation.iterate local function rgb(r, g, b) return {r=r, g=g, b=b} end local WINDOW_TITLE = "BugEvo" local RUN_PROMPT = "Press [SPACE] to begin a new simulation" local WORD_WRAP = 500 local TEXT_COLOR = rgb(255, 255, 153) local BACKGROUND_COLOR = rgb(0, 0, 0) local BUG_COLOR = rgb(153, 255, 0) local BACTERIA_COLOR = rgb(76, 0, 153) --Keyboard control local RUN_CONTROL = " " local QUIT_CONTROL = "q" local STATES = {INITIAL=1, ACTIVE=2} --Stretch simulation space to fit display window local X_STRETCH = love.graphics.getWidth() / FIELD_X local Y_STRETCH = love.graphics.getHeight() / FIELD_Y --Initialize display window love.graphics.setCaption(WINDOW_TITLE) love.graphics.setBackgroundColor(BACKGROUND_COLOR.r, BACKGROUND_COLOR.g, BACKGROUND_COLOR.b) local state local function initial() --Wait for user input and initialize a new simulation love.graphics.setColor(TEXT_COLOR.r, TEXT_COLOR.g, TEXT_COLOR.b) love.graphics.printf(RUN_PROMPT, 0, 0, WORD_WRAP) if love.keyboard.isDown(RUN_CONTROL) then initialize() state = STATES.ACTIVE end end local function active() --Iterate over the current simulation local data = iterate() if not data then --Simulation returns nil when ended; return to start screen state = STATES.INITIAL else local field = data.field local iteration = data.iteration local population = data.population for x = 1, #field do for y = 1, #field[x] do if field[x][y] ~= CODES.EMPTY then if field[x][y] == CODES.BUG then love.graphics.setColor(BUG_COLOR.r, BUG_COLOR.g, BUG_COLOR.b) elseif field[x][y] == CODES.BACTERIA then love.graphics.setColor(BACTERIA_COLOR.r, BACTERIA_COLOR.g, BACTERIA_COLOR.b) end --[[Adjustments are made here to transition between "simulation" and "LOVE2D" space. 1. LOVE2D coordinates begin counting from 0; the simulation counts from 1 2. LOVE2D draws in the foruth quadrant of the cartesian plane; the simulation uses the first]] love.graphics.rectangle("fill", X_STRETCH * x - X_STRETCH, (FIELD_Y - y) * Y_STRETCH, X_STRETCH, Y_STRETCH) end end end love.graphics.setColor(TEXT_COLOR.r, TEXT_COLOR.g, TEXT_COLOR.b) love.graphics.printf("iter ".. iteration.. "\npop ".. population, 0, 0, WORD_WRAP) end end local STATE_FUNCTIONS = {initial, active} state = STATES.INITIAL function love.draw() --Check for quit command, else do according to the state of the program if love.keyboard.isDown(QUIT_CONTROL) then love.event.quit() end STATE_FUNCTIONS[state]() end
local ActionOptItem = class('ActionOptItem',OptionItem) function ActionOptItem:initialize(label,action) OptionItem:initialize(self) -- label is blank self.value = label self.invert_pointers = true if action then self.on_activate = action else self.on_activate = function() end end end -- Setting one or both of these true may cause arrows to be shown function ActionOptItem:atMin() return true -- indicates that option can go no lower end function ActionOptItem:atMax() return true -- indicates that option can go no higher end function ActionOptItem:clickedIn(xhit, yhit) -- Indicates a click received, relative to the center of the displayed value end function ActionOptItem:setAction(func) self.on_activate = func end function ActionOptItem:activate() self.on_activate() -- Happens when the user hits fire/space while this item is selected end return ActionOptItem
ESX = nil TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) -- GENERA PREZZI ATTUALI BORSA -- RegisterServerEvent('rdsk_borsa:GeneraPrezzi') AddEventHandler('rdsk_borsa:GeneraPrezzi', function() MySQL.Async.fetchAll('SELECT * FROM borsa', {}, function(result) for i=1, #result, 1 do local id = result[i].ID local nome = result[i].Nome local attuale = result[i].Attuale local min = result[i].Min local max = result[i].Max local med = result[i].Med local med = ((min + max) / 2) local rnd = math.random(min, max) MySQL.Async.execute('UPDATE borsa SET Attuale=@RND , Med=@MED WHERE ID=@ID', { ['@RND'] = rnd, ['@MED'] = med, ['@ID'] = id }) end end) end) ESX.RegisterServerCallback("rdsk_borsa:getPrezzo", function(source, nome, cb) local src = source local xPlayer = ESX.GetPlayerFromId(src) local Nome = nome MySQL.Async.fetchAll('SELECT * FROM borsa WHERE Nome=@Nome', {['@Nome'] = Nome}, function(result) local prezzo = result.Attuale cb(prezzo) end) end)
----------------------------------- -- Area: Port San d'Oria -- NPC: Festive Moogle -- Type: Event NPC -- !pos 70.641 -16.000 -118.589 232 ----------------------------------- require("scripts/globals/npc_util") ----------------------------------- function onTrade(player, npc, trade) --TODO: trade of pells for prize end function onTrigger(player, npc) local festiveItems = {getFestiveItems(player)} if festiveItems[1] then player:startEvent(773, unpack(festiveItems)) else player:startEvent(774) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) local festiveItems = {getFestiveItems(player)} if csid == 773 then npcUtil.giveItem(player, festiveItems[option]) end end function getFestiveItems(player) local festiveItemsAvailable = {} local stock = { 16119, -- Nomad Cap 16118, -- Moogle Cap 18401, -- Moogle Rod 320, -- Harpsichord 264, -- Stuffed Chocobo 11290, -- Tidal Talisman 11811, -- Destrier Beret 10293, -- Chocobo Shirt } local festiveItems = { [1] = player:getCharVar("festiveMoogleNomadCap"), [2] = player:getCharVar("festiveMoogleMoogleCap"), [3] = player:getCharVar("festiveMoogleMoogleRod"), [4] = player:getCharVar("festiveMoogleHarpsichord"), [5] = player:getCharVar("festiveMooglestuffedChocobo"), [6] = player:getCharVar("festiveMoogleTidalTalisman"), [7] = player:getCharVar("festiveMoogleDestrierBeret"), [8] = player:getCharVar("festiveMoogleChocoboShirt"), } for i = 1, #festiveItems, 1 do if festiveItems[i] == 1 then festiveItemsAvailable[i] = stock[i] end end return unpack(festiveItemsAvailable) end
-- -- Copyright (c) Jesse Freeman. All rights reserved. -- -- Licensed under the Microsoft Public License (MS-PL) License. -- See LICENSE file in the project root for full license information. -- -- Contributors -- -------------------------------------------------------- -- This is the official list of Pixel Vision 8 contributors: -- -- Jesse Freeman - @JesseFreeman -- Christer Kaitila - @McFunkypants -- Pedro Medeiros - @saint11 -- Shawn Rakowski - @shwany -- -- These values represent the shell's position, speed, animation -- time and frame. local shellAPos = {x = 0, y = 8*8} local shellBPos = {x = 8*22, y = 0} -- This 2D array stores sprite IDs for the turtle shell animations. -- Each shell is a made up of 4 sprites in a 2x2 grid. local shellSprites = {{0,1,6,7}, {2,3,8,9}} local speed = 100; local time = 0 local frame = 1 -- The Init() method is part of the game's lifecycle and called a game -- starts. We are going to use this method to configure the DisplayChip, -- ScreenBufferChip and also draw fonts into the background layer. function Init() -- Here we are starting by changing the background color and telling -- the DisplayChip to wrap. apiBridge:ChangeBackgroundColor(32) -- Here we are rebuilding the screen buffer so we can draw tile and -- fonts to it. This will cut down on our draw calls. apiBridge:RebuildScreenBuffer() -- With the ScreenBuffer ready, we can now draw fonts into it. Here -- we are creating two new labels to display under our demo sprites. apiBridge:DrawTileText("Sprite Test", 1, 1, "large-font", 0) apiBridge:DrawTileText("Position Wrap Test", 1, 6, "large-font", 0) end -- The Update() method is part of the game's life cycle. The engine -- calls Update() on every frame before the Draw() method. It accepts -- one argument, timeDelta, which is the difference in milliseconds -- since the last frame. We are going to keep track of time to sync -- up our sprite animation as well as move the sprites across the screen. function Update(timeDelta) -- We are going to move the sprite positions by calculating the speed by -- the timeDelata. We can then add this to the x or y position of our sprite -- vector. shellAPos.x = shellAPos.x + (speed * timeDelta) shellBPos.y = shellBPos.y + (speed * timeDelta) -- We are going to keep track of the time by adding timeDelta to our time -- field. We can then use this to tell if we should change our animation frame. time = time + timeDelta -- Here we'll determine when it's time to change the sprite frame. if(time > 0.09) then -- If time is past the frame we'll increase the frame number to advance the animation. frame = frame + 1 -- We need to reset the frame number if it is greater than the number of frames. if(frame > #shellSprites) then frame = 1 end -- Now we can reset time back to 0 to start tracking the next frame change. time = 0 end end -- The Draw() method is part of the game's life cycle. It is called after Update() and -- is where all of our draw calls should go. We'll be using this to render each of -- the sprites and font characters to the display. function Draw() -- It's important to clear the display on each frame. There are two ways to do this. Here -- we are going to use the DrawScreenBuffer() way to copy over the existing buffer and clear -- all of the previous pixel data. apiBridge:DrawScreenBuffer() -- Here we are going to draw the first example. The turtle shell is made up of 4 sprites. -- We'll draw each sprite out with a few pixels between them so you can see how they are -- put together. apiBridge:DrawSprite(0, 8, 24, false, false, true, 0) apiBridge:DrawSprite(1, 18, 24, false, false, true, 0) apiBridge:DrawSprite(6, 8, 34, false, false, true, 0) apiBridge:DrawSprite(7, 18, 34, false, false, true, 0) -- For the next two examples we'll use the DrawSprites() method which allows us to combine sprites together into -- a single draw request. Each sprite still counts as a draw call but this simplifies drawing -- larger sprites in your game. apiBridge:DrawSprites(shellSprites[1], 32, 24, 2, false, false, true, 0) apiBridge:DrawSprites(shellSprites[frame], 54, 24, 2, false, false, true, 0) -- Here we are drawing a turtle shell along the x and y axis. We'll take advantage of the Display's wrap -- setting so that the turtle will appear on the opposite side of the screen even when the x or y -- position is out of bounds. local x = math.ceil(shellAPos.x) local y = math.ceil(shellAPos.y) apiBridge:DrawSprites(shellSprites[frame], x, y, 2, false, false, true, 0) apiBridge:DrawSpriteText("("..x..","..y..")", x, y + 20, "large-font", 0) -- The last thing we are going to do is draw text below each of our moving turtles so we can see the -- x and y position as they wrap around the display. x = math.ceil(shellBPos.x) y = math.ceil(shellBPos.y) apiBridge:DrawSprites(shellSprites[frame], x, y, 2, false, false, true, 0) apiBridge:DrawSpriteText("("..x..","..y..")", x, y + 20, "large-font", 0) end
local executable = require('utils.files').executable if executable 'cmake' then RELOAD('filetypes.cmake').setup() end
require("deepcore/std/class") require("deepcore/std/Observable") ---@class DeepCoreState DeepCoreState = class() function DeepCoreState.with_empty_policy() return DeepCoreState { on_enter = function(self, state_context) end, on_update = function(self, state_context) end, on_exit = function(self, state_context) end } end ---@param state_policy DeepCoreStatePolicy function DeepCoreState:new(state_policy) ---@private ---@type table<string, any> self.state_context = {} ---@private ---@type DeepCoreStatePolicy self.state_policy = state_policy or {} self:add_missing_methods(self.state_policy) ---@public ---@type table<number, DeepCoreStateTransition> self.transitions = {} ---@public self.on_enter = Observable() ---@public self.on_exit = Observable() end ---@private function DeepCoreState:add_missing_methods(state_policy) if not state_policy.on_enter then state_policy.on_enter = function() end end if not state_policy.on_update then state_policy.on_update = function() end end if not state_policy.on_exit then state_policy.on_exit = function() end end end ---@param previous_state_context table<string, any> function DeepCoreState:initialise(previous_state_context) self.state_context = self.state_policy:on_enter(previous_state_context) or {} self.on_enter:notify(self.state_context) end function DeepCoreState:update() self.state_policy:on_update(self.state_context) self:try_transition_to_next_state() end function DeepCoreState:try_transition_to_next_state() ---@param transition DeepCoreStateTransition for i, transition in ipairs(self.transitions) do if transition:should_transition(self.state_context) then transition:transition(self.state_context) self.state_policy.on_exit(self.state_context) self.on_exit:notify(transition:get_next_state(), self.state_context) return end end end
package("named_type") set_kind("library", {headeronly = true}) set_homepage("https://github.com/joboccara/NamedType") set_description("Implementation of strong types in C++.") set_license("MIT") add_urls("https://github.com/joboccara/NamedType.git") add_versions("v1.1.0.20210209", "c119054eac4b8f3599233ff480ad1ce4309a52ad") on_install(function (package) os.cp("include/NamedType", package:installdir("include")) end) on_test(function (package) assert(package:has_cxxtypes("fluent::NamedType<int, struct TestTag>", {configs = {languages = "c++14"}, includes = "NamedType/named_type.hpp"})) end)
--[[ ## Space Station 8 `code.lua` This is the main `code.lua` file that runs the entire game. It's responsible for loading in all the game code, managing the game's state, and loading/saving the map. Learn more about making Pixel Vision 8 games at http://docs.pixelvision8.com ]]-- -- We use the `LoadScript()` API to load each Lua file inside of the `/Game/Src/` directory. We can use this API to break down game logic into smaller, self-contained files. require "scene-splash" require "scene-editor" require "scene-game" require "message-bar" require "utils" require "map-loader" mapLoader = MapLoader:Init() -- Pixel Vision 8 will ignore scripts it's can't fine in the `/Game/Src/` directory which is helpful if you are just sketching out a game and where you want to put the logic. -- These are the paths the game will need to use for loading maps and switching to the Settings Tool. USER_LEVEL_PATH = NewWorkspacePath("/User/Maps/") SETTINGS_TOOL_PATH = "/PixelVisionOS/Tools/Settings/" DEFAULT_EXTENSION = ".png" BASE_EXTENSION = ".spacestation8" FULL_EXTENSION = BASE_EXTENSION .. DEFAULT_EXTENSION -- The `NewWorkspacePath()` API allows us to create a path to the virtual filesystem Pixel Vision 8 sets up when it boots up. You can also add onto WorkspacePaths by calling `AppendFile()` or `AppendDirectory()` and it will return a new `WorkspacePath`. DEFAULT_MAP_PATH = NewWorkspacePath("/Game/map" .. FULL_EXTENSION) USER_MAP_PATH = NewWorkspacePath("/User/Maps/") --[[ Games can read files inside of their own directory. When a game is loaded into memory a virtual file system is created and mapped to the `/Game/` drive. This allows the game to read files from its own directory in a save way by constraining the file system to stay only in the `/Game/` directory. Once the game is loaded, you can access any file by using the `NewWorkspacePath()` API and passing in an absolute path to the file. ]]-- -- Since variable in Lua are global by default we can take advantage of this and create global constants to emulate an enum you'd find in other languages like C#. Here we define all of the game modes and set a int value to make it easier to switch between scenes by name instead of memorizing the Id. SPLASH, EDITOR, RUN, OVER = 1, 2, 3, 1 -- We can also share Ids between scenes this way as well. Since the Splash and Over scenes are the same, we will use the some Id, `1`, for both scenes. -- Here we set up several local variables to store the scenes, the active scene, and the active scene Id. local scenes = nil local activeScene = nil local activeSceneId = 1 -- Each Lua script has it's own scope so we can hide these values from other scripts we load up by making them local. local topMessageBar = MessageBar:Init(0, SpriteSize().Y-1, -1) local bottomMessageBar = MessageBar:Init(Display().Y - 9, 9, 0) -- The `Init()` function is part of the game's lifecycle and called a when a game starts. We'll use this function to configure the mask colors, background color, and scene instances. function Init() -- By default, Pixel Vision 8's mask color is `#FF00FF` but we use `#937AC5` so our map png's look exactly how they would in the game. -- Change the background to `#937AC5` which is Id `2` so it matches the color in the map png file. BackgroundColor(2) -- Now we are going to create a table for each scene instance by calling the scene's Init() function. scenes = { SplashScene:Init(), EditorScene:Init(), GameScene:Init(), } --[[ If you try to run the code before you have a scene before you create the code for it, you will get an error. You can create the following files in your `/Game/Src/` folder as a place holder while we get the rest of the game working: `scene-loader.lua`, `scene-splash.lua`, `scene-editor.lua`, and `scene-game.lua`. You can use the following template for each scene's code file, just replace the scene name with the scene you are creating. ```lua LoaderScene = {} LoaderScene.__index = LoaderScene function LoaderScene:Init() local _loader = { } setmetatable(_loader, LoaderScene) return _loader end ``` ]]-- -- Now that we have all of the scenes loaded into memory, we can call the `SwitchScene()` function and load the default scene. SwitchScene(SPLASH) -- The loader scene is responsible for reading and parsing map data. We usually call this scene before any others in order to configure the level correctly before we edit or play it. end -- We use this function to prepare a new scene and run through all of the steps required to make sure the new scene is correctly reset and ready to go. function SwitchScene(id) -- We want to save the active scene Id incase we need it later. activeSceneId = id -- Here we are saving the instance of the active scene so we can call `Update()` and `Draw()` on whichever scene is currently active. activeScene = scenes[activeSceneId] -- Finally, we need to reset the scene before it is loaded. activeScene:Reset() -- Since each scene is already instantiated, its `Init()` function won't be called again. We will use the `Reset()` function to restore the default values and state before loading it. end -- The `Update()` function is part of the game's life cycle. The engine calls `Update()` on every frame before drawing anything to the display. It accepts one argument, `timeDelta`, which is the difference in milliseconds since the last frame. You can use the `timeDelta` to sync animations and physics to the framerate incase it drops between frames. function Update(timeDelta) -- The game's `Update()` function is where you'll want to do all your physics calculations, capture input changes, and any other logic that does not require rendering. -- First, we want to check for the escape key to be released on every frame. if(Key(Keys.Escape, InputState.Released)) then -- Before we load up the settings tool, let's make sure we save the state of the game. SaveState() -- We can load the Settings Tool, which is just another PV8 game, by calling the `LoadGame()` API and passing it a path as a string. LoadGame("/PixelVisionOS/Tools/SettingsTool/") -- It's also important to exit out of the Update() function so the scene doesn't update after we exit. return end -- Next, we need to check to see if there is an active scene before trying to update it. If one exists, we'll call `Update()` on the active scene and pass in the timeDelta. if(activeScene ~= nil) then activeScene:Update(timeDelta) end -- Finally, we call the `UpdateMessageBar()` function and pass in the timeDelta value. -- UpdateMenu(timeDelta) topMessageBar:Update(timeDelta) bottomMessageBar:Update(timeDelta) end -- The `Draw()` function is part of the game's life cycle. It is called after `Update()` and is where all of our draw calls should go. function Draw() -- We can use the `RedrawDisplay()` method to clear the screen and copy the tilemap cache (which contains a pre-rendered tilemap) to the display. RedrawDisplay() -- Check to see if there is an active scene before trying to draw it. if(activeScene ~= nil) then -- Call the active scene's `Draw()` function. activeScene:Draw() end end function DisplayTitle(value, time, centered, onClearCallback) topMessageBar:DisplayMessage(value, time, centered, onClearCallback) end function ClearTitle() topMessageBar:ClearMessage() end function DisplayMessage(value, time, centered, onClearCallback) bottomMessageBar:DisplayMessage(value, time, centered, onClearCallback) end function ClearMessage() bottomMessageBar:ClearMessage() end -- The `OnLoad()` Function is responsible for loading a new map into memory. function OnLoadImage(value) if(activeSceneId == SPLASH) then -- TODO need to copy the image to the map folder then load it (This passes in the raw image but not the file name?) -- mapLoader.imagePath.Path = NewWorkspacePath(value) print("Load map", value) -- ewWorkspacePath(self.maps[id])) -- value.RemapColors({MaskColor(),Color(0), Color(1), Color(2), Color(3)}) -- scenes[LOADER].defaultMapImage = value SwitchScene(SPLASH) end end