content
stringlengths
5
1.05M
local _ = require 'moses' local RecGRU, parent = torch.class('nn.RecGRU', 'nn.AbstractRecurrent') function RecGRU:__init(inputsize, outputsize) local stepmodule = nn.StepGRU(inputsize, outputsize) parent.__init(self, stepmodule) self.inputsize = inputsize self.outputsize = outputsize self.zeroOutput = torch.Tensor() end function RecGRU:maskZero(v1) assert(torch.isTypeOf(self.modules[1], 'nn.StepGRU')) for i,stepmodule in pairs(self.sharedClones) do stepmodule:maskZero(v1) end self.modules[1]:maskZero(v1) return self end ------------------------- forward backward ----------------------------- function RecGRU:_updateOutput(input) assert(input:dim() == 2, "RecGRU expecting batchsize x inputsize tensor (Only supports batchmode)") local prevOutput = self:getHiddenState(self.step-1, input) -- output(t) = gru{input(t), output(t-1)} local output if self.train ~= false then local stepmodule = self:getStepModule(self.step) output = stepmodule:updateOutput({input, prevOutput}) else self._prevOutput = self._prevOutput or prevOutput.new() self._prevOutput:resizeAs(prevOutput):copy(prevOutput) output = self.modules[1]:updateOutput({input, self._prevOutput}) end return output end function RecGRU:_updateGradInput(input, gradOutput) assert(self.step > 1, "expecting at least one updateOutput") local step = self.updateGradInputStep - 1 assert(step >= 1) -- set the output/gradOutput states of current Module local stepmodule = self:getStepModule(step) -- backward propagate through this step local _gradOutput = assert(self:getGradHiddenState(step, input)) self._gradOutputs[step] = self._gradOutputs[step] or _gradOutput.new() self._gradOutputs[step]:resizeAs(_gradOutput) self._gradOutputs[step]:add(_gradOutput, gradOutput) gradOutput = self._gradOutputs[step] local inputTable = {input, self:getHiddenState(step-1)} local gradInputTable = stepmodule:updateGradInput(inputTable, gradOutput) self:setGradHiddenState(step-1, gradInputTable[2]) return gradInputTable[1] end function RecGRU:_accGradParameters(input, gradOutput, scale) local step = self.accGradParametersStep - 1 assert(step >= 1) -- set the output/gradOutput states of current Module local stepmodule = self:getStepModule(step) -- backward propagate through this step local inputTable = {input, self:getHiddenState(step-1)} local gradOutput = self._gradOutputs[step] or self:getGradHiddenState(step) stepmodule:accGradParameters(inputTable, gradOutput, scale) end function RecGRU:clearState() self.startState = nil self.zeroOutput:set() return parent.clearState(self) end function RecGRU:type(type, ...) if type then self:forget() self:clearState() end return parent.type(self, type, ...) end function RecGRU:initZeroTensor(input) if input then if input:dim() == 2 then self.zeroOutput:resize(input:size(1), self.outputsize):zero() else self.zeroOutput:resize(self.outputsize):zero() end end end function RecGRU:getHiddenState(step, input) step = step == nil and (self.step - 1) or (step < 0) and (self.step - step - 1) or step local prevOutput if step == 0 then if self.startState then prevOutput = self.startState if input and input:dim() == 2 then assert(prevOutput:size(2) == self.outputsize) assert(prevOutput:size(1) == input:size(1)) end else prevOutput = self.zeroOutput self:initZeroTensor(input) end else -- previous output of this module prevOutput = self.outputs[step] end return prevOutput end function RecGRU:setHiddenState(step, hiddenState) step = step == nil and (self.step - 1) or (step < 0) and (self.step - step - 1) or step assert(torch.isTensor(hiddenState)) if step == 0 then -- this hack bipasses the fact that Sequencer calls forget when remember is false -- which makes it impossible to use self.outputs to set the h[0] (it is forgotten) self:setStartState(hiddenState) else -- previous output of this module self.outputs[step] = hiddenState end end function RecGRU:getGradHiddenState(step, input) self.gradOutputs = self.gradOutputs or {} local _step = self.updateGradInputStep or self.step step = step == nil and (_step - 1) or (step < 0) and (_step - step - 1) or step local gradOutput if step == self.step-1 then if self.startState and not self.gradOutputs[step] then self:initZeroTensor(input) end gradOutput = self.gradOutputs[step] or self.zeroOutput else gradOutput = self.gradOutputs[step] end return gradOutput end function RecGRU:setGradHiddenState(step, gradHiddenState) local _step = self.updateGradInputStep or self.step step = step == nil and (_step - 1) or (step < 0) and (_step - step - 1) or step assert(torch.isTensor(gradHiddenState)) self.gradOutputs[step] = gradHiddenState end function RecGRU:__tostring__() if self.weightO then return self.__typename .. string.format("(%d -> %d -> %d)", self.inputsize, self.hiddensize, self.outputsize) else return self.__typename .. string.format("(%d -> %d)", self.inputsize, self.outputsize) end end
dependencies = { 'libs/Context.lua', 'libs/backend/HPMSFacade.lua', 'libs/gui/InputText2D.lua', 'libs/utils/DebugConsole.lua', 'libs/utils/Utils.lua', 'libs/managers/SceneManager.lua' }
WireGPU_Monitors = {} function WireGPU_AddMonitor(name, model, tof, tou, tor, trs, x1, x2, y1, y2, rot, translucent) if not rot then rot = Angle(0, 90, 90) elseif not isangle(rot) then rot = Angle(0, 90, 0) end local RatioX = (y2 - y1) / (x2 - x1) local monitor = { Name = name, offset = Vector(tof, -tor, tou), RS = trs, RatioX = RatioX, x1 = x1, x2 = x2, y1 = y1, y2 = y2, z = tof, rot = rot, translucent = translucent } WireGPU_Monitors[model] = monitor end local function mindimension(vec) -- add a bias to make the screen appear on the front face of a cube if vec.x - 0.002 < vec.y then -- x < y -- another bit of bias, otherwise it'd appear on the left face. if vec.x - 0.002 < vec.z then -- x < y, x < z return Vector(1, 0, 0) else -- x < y, z<=x -> z < y return Vector(0, 0, 1) end else -- y <= x if vec.y < vec.z then -- y <= x, y < z return Vector(0, 1, 0) else -- y <= x, z <= y -> z <= x return Vector(0, 0, 1) end end end local function maxdimension(vec) -- add a small bias, so squared screens draw text in the correct orientation (y+/down = forward axis) if vec.x - 0.002 > vec.y then -- x > y if vec.x > vec.z then -- x > y, x > z return Vector(1, 0, 0) else -- x > y, z>=x -> z > y return Vector(0, 0, 1) end else -- y >= x -- more bias, this time to give the front face the correct orientation if vec.y + 0.002 > vec.z then -- y >= x, y > z return Vector(0, 1, 0) else -- y >= x, z >= y -> z >= x return Vector(0, 0, 1) end end end function WireGPU_FromBox(name, model, boxmin, boxmax, translucent) local dim = boxmax - boxmin local mindim, maxdim = mindimension(dim), maxdimension(dim) -- get an angle with up=mindim local rot = mindim:Angle() + Angle(90, 0, 0) -- make sure forward=maxdim if math.abs(maxdim:Dot(rot:Forward())) < 0.01 then rot:RotateAroundAxis(mindim, 90) end -- unrotate boxmin/max local box1 = WorldToLocal(boxmin, Angle(0, 0, 0), Vector(0, 0, 0), rot) local box2 = WorldToLocal(boxmax, Angle(0, 0, 0), Vector(0, 0, 0), rot) -- sort boxmin/max local boxmin = Vector(math.min(box1.x, box2.x), math.min(box1.y, box2.y), math.min(box1.z, box2.z)) local boxmax = Vector(math.max(box1.x, box2.x), math.max(box1.y, box2.y), math.max(box1.z, box2.z)) -- make a new gpu screen return WireGPU_FromBox_Helper(name, model, boxmin, boxmax, rot, translucent) end -- boxmin/boxmax have to be already rotated function WireGPU_FromBox_Helper(name, model, boxmin, boxmax, rot, translucent) local boxcenter = (boxmin + boxmax) * 0.5 local offset = Vector(boxcenter.x, boxcenter.y, boxmax.z + 0.2) boxmin = boxmin - offset boxmax = boxmax - offset local x1, y1 = boxmin.x, boxmin.y local x2, y2 = boxmax.x, boxmax.y offset:Rotate(rot) local monitor = { Name = name, offset = offset, RS = (y2 - y1) / 512, RatioX = (y2 - y1) / (x2 - x1), x1 = x1, x2 = x2, y1 = y1, y2 = y2, z = offset.z, rot = rot, translucent = translucent } WireGPU_Monitors[model] = monitor return monitor end function WireGPU_FromRotatedBox(name, model, box1, box2, box3, box4, rot, translucent) if isvector(rot) then rot = Vector:Angle() end --local boxvectors = { box1, box2, box3, box4 } local box1 = WorldToLocal(box1, Angle(0, 0, 0), Vector(0, 0, 0), rot) local box2 = WorldToLocal(box2, Angle(0, 0, 0), Vector(0, 0, 0), rot) local box3 = WorldToLocal(box3, Angle(0, 0, 0), Vector(0, 0, 0), rot) local box4 = WorldToLocal(box4, Angle(0, 0, 0), Vector(0, 0, 0), rot) local boxmin = Vector(math.min(box1.x, box2.x, box3.x, box4.x), math.min(box1.y, box2.y, box3.y, box4.y), math.min(box1.z, box2.z, box3.z, box4.z)) local boxmax = Vector(math.max(box1.x, box2.x, box3.x, box4.x), math.max(box1.y, box2.y, box3.y, box4.y), math.max(box1.z, box2.z, box3.z, box4.z)) print(boxmin, boxmax, rot) return WireGPU_FromBox_Helper(name, model, boxmin, boxmax, rot, translucent) end WireGPU_FromBox_Helper("Workspace 002", "models/props_lab/workspace002.mdl", Vector(-20, 49, -34), Vector(16.2, 84, -30.5), Angle(0, 133.34, 59.683)) -- Offset front, offset up, offset right, resolution/scale OF OU OR SCALE LOWX HIGHX LOWY HIGHY ROTATE90 WireGPU_AddMonitor("Small TV", "models/props_lab/monitor01b.mdl", 6.53, 0.45, 1.0, 0.0185, -5.535, 3.5, -4.1, 5.091) WireGPU_AddMonitor("Monitor Small", "models/kobilica/wiremonitorsmall.mdl", 0.3, 5.0, 0, 0.0175, -4.4, 4.5, 0.6, 9.5) WireGPU_AddMonitor("LCD Monitor (4:3)", "models/props/cs_office/computer_monitor.mdl", 3.3, 16.7, 0, 0.031, -10.5, 10.5, 8.6, 24.7) WireGPU_AddMonitor("Monitor Big", "models/kobilica/wiremonitorbig.mdl", 0.2, 13, 0, 0.045, -11.5, 11.6, 1.6, 24.5) WireGPU_AddMonitor("Plasma TV (4:3)", "models/blacknecro/tv_plasma_4_3.mdl", 0.1, -0.5, 0, 0.082, -27.87, 27.87, -20.93, 20.93) WireGPU_AddMonitor("Plasma TV (16:10)", "models/props/cs_office/tv_plasma.mdl", 6.1, 18.93, 0, 0.065, -28.5, 28.5, 2, 36) WireGPU_AddMonitor("Billboard", "models/props/cs_assault/billboard.mdl", 1, 0, 0, 0.23, -110.512, 110.512, -57.647, 57.647) WireGPU_AddMonitor("Cube 1x1x1", "models/hunter/blocks/cube1x1x1.mdl", 24, 0, 0, 0.09, -48, 48, -48, 48) WireGPU_AddMonitor("Panel 1x1", "models/hunter/plates/plate1x1.mdl", 0, 1.7, 0, 0.09, -48, 48, -48, 48, true) WireGPU_AddMonitor("Panel 2x2", "models/hunter/plates/plate2x2.mdl", 0, 1.7, 0, 0.182, -48, 48, -48, 48, true) WireGPU_AddMonitor("Panel 0.5x0.5", "models/hunter/plates/plate05x05.mdl", 0, 1.7, 0, 0.045, -48, 48, -48, 48, true) WireGPU_AddMonitor("Tray", "models/props/cs_militia/reload_bullet_tray.mdl", 0, 0.8, 0, 0.009, 0, 100, 0, 60, true) -- Offset front, offset up, offset right, resolution/scale OF OU OR SCALE LOWX HIGHX LOWY HIGHY ROTATE90 --WireGPU_AddMonitor("LED Board (1:1)", "models/blacknecro/ledboard60.mdl", 6.1, 18.5 , 11 , 0.065 , -60 , 60 , -60 , 60 ) -- broken WireGPU_FromBox("TF2 Red billboard", "models/props_mining/billboard001.mdl", Vector(0, -168, 0), Vector(3, 168, 192), false) WireGPU_FromBox("TF2 Red vs Blue billboard", "models/props_mining/billboard002.mdl", Vector(0, -306, 96), Vector(3, 306, 288), false) -- transparent screens WireGPU_AddMonitor("Window", "models/props_phx/construct/windows/window1x1.mdl", 0, 1.7, 0, 0.07, -46, 46, -46, 46, true, true) --[[ models/props_c17/tv_monitor01.mdl models/props_wasteland/controlroom_monitor001b.mdl models/props/cs_militia/television_console01.mdl models/props/cs_militia/tv_console.mdl models/props_silo/silo_launchroom_monitor.mdl models/props_bts/glados_screenborder_curve.mdl models/props_spytech/tv001.mdl models/props_lab/monitor02.mdl models/props_lab/monitor01a.mdl workspaces: models/props_lab/workspace003.mdl models/props_lab/securitybank.mdl too curvy? models/props_spytech/computer_screen_bank.mdl ]] local function fallback(self, model) local ent local entities = ents.GetAll() -- tried to use FindByModel, but it didn't work - don't know why for i = 1, #entities do local e = entities[i] if e:GetModel() == model and e:GetClass() ~= "class C_BaseFlex" and e:GetClass() ~= "gmod_ghost" then -- don't include adv dupe 2 ghosts -- don't include adv dupe 1 ghosts ent = e break end end if not ent then return nil end local gap = Vector(0.25, 0.25, 0.25) local boxmin = ent:OBBMins() + gap local boxmax = ent:OBBMaxs() - gap return WireGPU_FromBox("Auto: " .. model:match("([^/]*)$"), model, boxmin, boxmax, false) end setmetatable(WireGPU_Monitors, { __index = fallback })
local util = require 'lspconfig.util' return { default_config = { cmd = { 'quick-lint-js', '--lsp-server' }, filetypes = { 'javascript' }, root_dir = util.root_pattern('package.json', 'jsconfig.json', '.git'), }, docs = { description = [[ https://quick-lint-js.com/ quick-lint-js finds bugs in JavaScript programs. See installation [instructions](https://quick-lint-js.com/install/) ]], }, }
function OnTargetSelected(user, target) if (user:IsPlayer() == true and user:IsMyPartyMember() == false and target:IsMe() == true) then local TargetersFile = io.open(GetDir() .. "_targeters\\" .. GetMe():GetName() .. ".txt", "a") TargetersFile:write(os.date("%Y-%m-%d %H:%M:%S") .. " | " .. user:GetName() .. "\n"); TargetersFile:close(); end; end;
local MIXTURE = {} MIXTURE.ID = 11; MIXTURE.Results = "weapon_fiveseven"; MIXTURE.Ingredients = {'item_chunk_metal', 'item_chunk_metal', 'item_paint', 'item_paint', 'item_chunk_plastic'}; MIXTURE.Requires = { {GENE_INTELLIGENCE, 3}, {GENE_DEXTERITY, 3}, {SKILL_CRAFTINESS, 3}, }; MIXTURE.Free = false; MIXTURE.RequiresHeatSource = false; MIXTURE.RequiresWaterSource = false; MIXTURE.RequiresSawHorse = false; function MIXTURE.CanMix ( player, pos ) player:UnlockMixture(5); return true; end GM:RegisterMixture(MIXTURE);
-- Copyright 2020, Michael Adler <[email protected]> local log = require("log") local List = require("pl.List") local Map = require("pl.Map") local Set = require("pl.Set") local M = {} local function parse_line(line) local directions = List({}) local i = 1 local n = #line while i <= n do local x = line:sub(i, i + 1) if x == "se" or x == "sw" or x == "nw" or x == "ne" then directions:append(x) i = i + 2 else x = line:sub(i, i) directions:append(x) i = i + 1 end end assert(i == n + 1) return directions end M.parse_line = parse_line local function read_input(fname) local f = io.open(fname, "r") local directions = List({}) for line in f:lines() do directions:append(parse_line(line)) end f:close() return directions end M.read_input = read_input local function calc_coords(directions) -- “odd-r” horizontal layout shoves odd rows right -- see https://www.redblobgames.com/grids/hexagons/ local x, y = 0, 0 -- reference tile log.debug("Processing:", directions) for c in directions:iter() do if c == "e" then log.debug("going east") x = x + 1 elseif c == "w" then log.debug("going west") x = x - 1 elseif c == "se" then log.debug("going south-east") if y % 2 == 1 then x = x + 1 end y = y + 1 elseif c == "sw" then log.debug("going south-west") if y % 2 == 0 then x = x - 1 end y = y + 1 elseif c == "nw" then log.debug("going north-west") if y % 2 == 0 then x = x - 1 end y = y - 1 elseif c == "ne" then log.debug("going north-east") if y % 2 == 1 then x = x + 1 end y = y - 1 else log.error("Missing case:", c) assert(false, c) end log.debug("x:", x, "y:", y) end return x, y end M.calc_coords = calc_coords local function count_black_tiles(colors) local result = 0 for _, v in colors:iter() do if v == true then result = result + 1 end end return result end local function hash_point(x, y) return string.format("%d\0%d", x, y) end local _cache = {} local function unhash_point(s) local val = _cache[s] if not val then local x, y = s:match("(%-?%d+)%z(%-?%d+)") val = { tonumber(x), tonumber(y) } _cache[s] = val end return val[1], val[2] end local function build_map(input) local colors = Map({}) -- black: true, nil or false: white for directions in input:iter() do local x, y = calc_coords(directions) local key = hash_point(x, y) colors[key] = not colors[key] end return colors end local function part1(fname) local input = read_input(fname) local colors = build_map(input) return count_black_tiles(colors) end M.part1 = part1 local function neighbors(x, y) return coroutine.wrap(function() -- e coroutine.yield(x + 1, y) -- w coroutine.yield(x - 1, y) -- se local my_x = x if y % 2 == 1 then my_x = my_x + 1 end coroutine.yield(my_x, y + 1) -- sw my_x = x if y % 2 == 0 then my_x = my_x - 1 end coroutine.yield(my_x, y + 1) -- nw my_x = x if y % 2 == 0 then my_x = my_x - 1 end coroutine.yield(my_x, y - 1) -- ne my_x = x if y % 2 == 1 then my_x = my_x + 1 end coroutine.yield(my_x, y - 1) end) end M.neighbors = neighbors local function part2(fname) local steps = 100 local input = read_input(fname) local colors = build_map(input) for _ = 1, steps do local changes = Map({}) local white_candidates = Set({}) for k, is_black in colors:iter() do local x, y = unhash_point(k) if is_black then local black_count = 0 for nb_x, nb_y in neighbors(x, y) do local nb_key = hash_point(nb_x, nb_y) if colors[nb_key] == true then black_count = black_count + 1 else white_candidates = white_candidates + nb_key end end -- Any black tile with zero or more than 2 black tiles immediately adjacent to it is flipped to white. if black_count == 0 or black_count > 2 then log.debug( "(", x, ",", y, ") is a black tile with", black_count, "black neighbors => changing to white" ) changes[k] = false end end end for k in Set.values(white_candidates):iter() do local x, y = unhash_point(k) local black_count = 0 for nb_x, nb_y in neighbors(x, y) do local nb_key = hash_point(nb_x, nb_y) if colors[nb_key] == true then black_count = black_count + 1 if black_count > 2 then break end end end -- Any white tile with exactly 2 black tiles immediately adjacent to it is flipped to black. if black_count == 2 then log.debug("(", x, ",", y, ") is a white tile with", black_count, "black neighbors => changing to black") changes[k] = true end end -- apply changes for k, v in pairs(changes) do colors[k] = v end end return count_black_tiles(colors) end M.part2 = part2 return M
local turbo = require("turbo") local middleclass = require("turbo.3rdparty.middleclass") local ffi = require("ffi") local yield = coroutine.yield local task = turbo.async.task local COMMANDS = require("turboredis.commands") local util = require("turboredis.util") local resp = {} -- Convert a table of command+arguments to redis format. function resp.pack(t) local out = "*" .. tostring(#t) .. "\r\n" for _, v in ipairs(t) do out = out .. "$" .. tostring(string.len(v)) .. "\r\n" .. v .. "\r\n" end return out end -- Read a Redis reply -- -- Parameters: -- -- - stream[IOStream]: The IOStream object to use -- - wrap[bool]: Wether or not to wrap the result in a table (if the reply -- is not an error or 'simple string' reply. -- function resp.read_resp_reply (stream, wrap, callback, callback_arg) turbo.ioloop.instance():add_callback(function () local part local first local len local data local is_ss = false -- Read the first line of the reply to figure out -- reply type and length. part = yield(task(stream.read_until, stream, "\r\n")) first = part:sub(1,1) -- Handle a 'simple string' or error reply. if first == "+" or first == "-" then is_ss = true res = {first == "+", part:sub(2, part:len()-2)} -- Handle a 'bulk string' reply. elseif first == "$" then len = tonumber(part:sub(2, part:len()-2)) if len == -1 then res = nil else data = yield(task(stream.read_bytes, stream, len+2)) res = data:sub(1, data:len()-2) end -- Handle an array reply, we call resp.read_resp_array_reply -- if the length is not -1 (nil) elseif first == "*" then len = tonumber(part:sub(2, part:len()-2)) if len == -1 then res = nil else res = yield(task(resp.read_resp_array_reply, stream, len)) end -- Handle an integer reply elseif first == ":" then res = tonumber(part:sub(2, part:len()-2)) else -- Should never get here, but if we do, we fail in -- the same way as with an error reply. res = {false, "turboredis: Error in reply from redis"} end if (not is_ss) and wrap then -- Wrap result in a table if not a 'simple string' or 'error' reply res = {res} end if callback_arg then callback(callback_arg, res) else callback(res) end end) end -- Read a redis array reply. -- Calls resp.read_resp_reply() on each element. -- -- Parameters: -- -- - stream[IOStream]: The IOStream object to use -- - n[int]: Number of elements in the array reply. -- function resp.read_resp_array_reply(stream, n, callback, callback_arg) stream.io_loop:add_callback(function () local out = {} local i = 0 while i < n do out[#out+1] = yield(task(resp.read_resp_reply, stream, false)) i = i + 1 end if callback_arg then callback(callback_arg, out) else callback(out) end end) end return resp
-- -*- lua -*- conflict("openmpi") whatis("Name: OpenMPI") whatis("Version: "..myModuleVersion()) whatis("Description: Open source MPI implementation that is developed and maintained by a consortium of academic, research, and industry partners.") local version = {} local key=1 for num in string.gmatch(myModuleVersion(), "(%d+)") do version[key]=num key = key + 1 end local major=version[1] local minor=version[2] local patch=version[3] local version=major.."."..minor.."."..patch local prefix=pathJoin("/opt/HPC/MPIs", os.getenv("COMPILER_TYPE"), os.getenv("COMPILER_VERSION"), myModuleName(), myModuleVersion()) setenv("MPI", myModuleName()) setenv("MPI_VER", myModuleVersion()) setenv("MPI_HOME", prefix) setenv("MPICH_HOME", prefix) setenv("MPI_ARCH_PATH", prefix) setenv("MPI_BUFFER_SIZE", "2000000") prepend_path("PATH", pathJoin(prefix, "bin")) prepend_path("LD_LIBRARY_PATH", pathJoin(prefix, "lib")) append_path("MANPATH", pathJoin(prefix, "share/man"))
-- -*- mode: lua; tab-width: 2; indent-tabs-mode: 1; st-rulers: [70] -*- -- vim: ts=4 sw=4 ft=lua noet ---------------------------------------------------------------------- -- @author Daniel Barney <[email protected]> -- @copyright 2015, Pagoda Box, Inc. -- @doc -- -- @end -- Created : 15 May 2015 by Daniel Barney <[email protected]> ---------------------------------------------------------------------- local Object = require('core').Object local Pid = require('./pid') local Link = require('./link') local Mailbox = require('./mailbox') local Timer = require('./timer') local Name = require('./name') local Ref = require('./ref') local Wrap = require('./wrap') local Group = require('./group') local Reactor = require('./reactor') local RunQueue = require('./run_queue') local Process = Object:extend() -- we only want to return a pid when we create a new process function Process:new(...) local pid = Object.new(self,...) return pid._pid,pid._parent_link end function Process:initialize(start,opts) -- a function or a string that maps to a member function on the -- current object can be passed in to start the process if type(start) ~= 'function' and type(self[start]) ~= 'function' then error('unable to spawn pid without a starting function') end -- set some defaults if not opts then opts = {link = true,args = {}} elseif type(opts) ~= 'table' then error('bad options specified') end if not opts.args then opts.args = {} end -- normal is a pid exiting. this is the default self._crash_reason = 'normal' -- check if a pid is available. throws an error if one is not Pid.available() -- if there is a name for this process, see if the name is taken. if opts.register_name and opts.name and Name.lookup(opts.name) ~= nil then error('name is already taken') end -- Nothing should fail from here on out. -- create a new mailbox, for some reason require doesn't work. -- probably because of require dependancies. self._mailbox = Mailbox:new() self._names = {} self._links = {} self._groups = {} self._inverse_links = {} -- create the coroutine that is the process local process = self if type(start) == 'function' then self._routine = coroutine.create(function() -- we do this to preserve send,recv,exit functions. start(process,unpack(opts.args)) error('normal',0) end) else self._routine = coroutine.create(function() self[start](self,unpack(opts.args)) error('normal',0) end) end -- track how long this process has been on CPU self._run_time = 0 -- assign a pid to the new process self._pid = Pid.next() Pid.enter(self._pid,self) -- link the new process to the current process if opts.link and Reactor.current() then self._parent_link = Link.link(self._pid,Reactor.current()) end -- set up the name for this process if opts.register_name and opts.name then Name.register(self._pid,opts.name) end -- should the next two really happen here? -- or should it be somewhere else? -- we add the pid to the run_queue RunQueue:enter(self) -- and we pause this pid if we need to. local current = Reactor.current() if current ~= nil then self:yield() end end function Process:destroy() local pid = self._pid Name.clean(pid) local sent = Link.clean(pid,self._crash_reason) Pid.remove(pid) Group.clean(pid) -- we need to get this working correctly. if self._pid == Reactor.current() then self:exit() end return sent end function Process:exit(pid,err) if not err and pid then err = pid pid = nil end if not err then err = 'exit' end local current = Reactor.current() if current == nil then self._crash_reason = err -- and now I need to end the coroutine coroutine.resume(self._routine,err) elseif pid == nil or pid == current then error(err) else -- I need to terminate a different process self:send(pid,'$exit') end end -- send a message to a process after time has passed function Process:send_after(pid,time,...) return self:send_interval(pid,0,time,...) end -- send a message to a process after time has passed function Process:send_interval(pid,interval,time,...) if type(time) ~= "number" or time < 0 or type(interval) ~= "number" or time < 0 then error("invalid interval") end -- pid could be a lot of things local kind = type(pid) local is_pid = kind == "number" local is_name = kind == "string" local is_group = kind == "table" and pid[1] == 'group' local is_remote = kind == "table" and pid[1] == 'remote' assert(is_pid or is_name or is_group or is_remote, 'invalid pid') if self and not self._mailbox then self = Pid.lookup(Reactor.current()) end -- I still need to check if the msg being sent is nil return self._mailbox:yield("send",{pid,interval,time,...}) end -- cancel the sending of a message that may have been sent function Process:cancel_timer(timer) if timer then Timer.cancel(timer) end end -- send a message to a process function Process:send(pid,...) self:send_interval(pid,0,0,...) end -- receive a message from the mailbox function Process:recv(...) return self._mailbox:recv(...) end function Process:yield() self._mailbox:yield('yield') end function Process:current() return Reactor.current() end -- we wrap an async function to be used inside of this coroutine function Process:wrap(fun,...) return unpack(self._mailbox:yield('wrap',{fun,...})) end function Process:close(ref) Wrap.close(ref) end return Process
local spell, super = Class(Spell, "pacify") function spell:init() super:init(self) -- Display name self.name = "Pacify" -- Name displayed when cast (optional) self.cast_name = nil -- Battle description self.effect = "Spare\nTIRED foe" -- Menu description self.description = "SPARE a tired enemy by putting them to sleep." -- TP cost self.cost = 16 -- Target mode (ally, party, enemy, enemies, or none) self.target = "enemy" -- Tags that apply to this spell self.tags = {"spare_tired"} end function spell:getCastMessage(user, target) local message = super:getCastMessage(self, user, target) if target.tired then return message elseif target.mercy < 100 then return message.."\n[wait:0.25s]* But the enemy wasn't [color:blue]TIRED[color:reset]..." else return message.."\n[wait:0.25s]* But the foe wasn't [color:blue]TIRED[color:reset]... try\n[color:yellow]SPARING[color:reset]!" end end function spell:onCast(user, target) if target.tired then Assets.playSound("spell_pacify") target:spare(true) local pacify_x, pacify_y = target:getRelativePos(target.width/2, target.height/2) local z_count = 0 local z_parent = target.parent Game.battle.timer:every(1/15, function() z_count = z_count + 1 local z = SpareZ(z_count * -40, pacify_x, pacify_y) z.layer = target.layer + 0.002 z_parent:addChild(z) end, 8) else local recolor = target:addFX(RecolorFX()) Game.battle.timer:during(8/30, function() recolor.color = Utils.lerp(recolor.color, {0, 0, 1}, 0.12 * DTMULT) end, function() Game.battle.timer:during(8/30, function() recolor.color = Utils.lerp(recolor.color, {1, 1, 1}, 0.16 * DTMULT) end, function() target:removeFX(recolor) end) end) end end return spell
require("util/util") require("util/set") require("ift/mask") Item = Class() function Item.new(noun, adjectives, components, children, parent) local self = { parent = parent, noun = noun, adjectives = adjectives and Set.new():addAll(adjectives) or Set.new(), components = components and Set.new():addAll(components) or Set.new(), children = children, } setmetatable(self, Item) return self end function Item:destroy() self.parent = nil self.noun = nil self.adjectives = nil self.children = nil end --[[-- For sentences like "(Put) (the 6 brown cats) (on the 6 green tables)" ]] ActionSentence = Class() function ActionSentence.new(verb, subject, preposition) local self = { verb = verb, subject = subject, preposition = preposition, } setmetatable(self, ActionSentence) return self end --[[-- For sentences like "(Are) (the 6 cats) (on the tables) (brown)" ]] QualitySentence = Class() function QualitySentence.new(verb, subject, preposition, quality) local self = { verb = verb, subject = subject, preposition = preposition, quality = quality } setmetatable(self, QualitySentence) return self end function QualitySentence:eval(scene) local matches -- get subject local subject = Mask.fromSubject(self.subject, scene) if self.preposition ~= nil then -- get location local location = Mask.fromSubject(self.preposition.subject, scene) location:selectChildren() -- all x on y matches = subject:AND(location) else matches = subject end -- whether all items must satisfy condition local distinct = self.subject.distinct local countMatch = 0 for i, v in ipairs(matches:addToList({})) do if qualifies(v, self.quality) then countMatch = countMatch + 1 end end if distinct then return countMatch == matches:count() else return countMatch > 0 end end function qualifies(item, quality) if quality.component then return item.components[quality.component] else return item.adjectives[quality.adjective] end end
local M = {} local function serialize(obj) local lua = "" local t = type(obj) if t == "number" then lua = lua .. obj elseif t == "boolean" then lua = lua .. tostring(obj) elseif t == "string" then lua = lua .. string.format("%q", obj) elseif t == "table" then lua = lua .. "{" for k, v in pairs(obj) do lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. "," end local metatable = getmetatable(obj) if metatable ~= nil and type(metatable.__index) == "table" then for k, v in pairs(metatable.__index) do lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. "," end end lua = lua .. "}" elseif t == "nil" then return "nil" elseif t == "userdata" then return "userdata" elseif t == "function" then return "function" elseif t == "thread" then return "thread" else error("can not serialize a " .. t .. " type.") end return lua end M.table_2_str = serialize function M.print(o) print(serialize(o)) end function M.get_card_str(i) if i <= 9 then return i.."万" end end return M
-- Developed by MAHN.quifi, 2010 local print = print local pairs = pairs local tostring = tostring local type = type local setmetatable = setmetatable local getmetatable = getmetatable local stdout = io.stdout local stringrep = string.rep local setfenv = setfenv local assert = assert local rawget = rawget local pcall = pcall local load = load local loadfile = loadfile local tableconcat = table.concat local tableremove = table.remove local luad = luad local ioopen = io.open local error = error local select = select local _VERSION = _VERSION local is_5_1 = (_VERSION == "Lua 5.1") local _ENV = nil local malut = {} -- -- printTable relative -- local tableToString_tablelist = nil local tableToString_strBuilder = nil local function tableToString_write (...) local n = select("#", ...) for i = 1, n do tableToString_strBuilder[#tableToString_strBuilder +1] = select(i, ...) end end local tableToString_ -- function tableToString_ (t, level, maxLevel, name) local function tableToString_keyValue (k, v, level, maxLevel, name) tableToString_write(stringrep(' ',level*2)) -- key local typeK = type(k) if typeK == "number" then tableToString_write("#", k) else tableToString_write(tostring(k)) end -- = tableToString_write(" = ") -- value local typeV = type(v) if typeV=="table" then if tableToString_tablelist[v] then tableToString_write(tostring(v), " (", tableToString_tablelist[v], ")" ) elseif maxLevel and level+1 >= maxLevel then tableToString_write(tostring(v), " (...)" ) else tableToString_write(tostring(v), "\n") return tableToString_(v, level + 1, maxLevel, name.."."..tostring(k)) --convert to tail call end else if typeV == "string" then tableToString_write('"', v, '"') else tableToString_write(tostring(v)) end end tableToString_write("\n") end --local function tableToString_ (t, level, maxLevel, name) tableToString_tablelist[t] = name local size = #t -- array part for i = 1, size do local v = t[i] if v ~= nil then tableToString_keyValue(i, v, level, maxLevel, name) end end -- map part for k,v in pairs(t) do if type(k) == "number" and k >= 1 and k <= size then -- already printed else tableToString_keyValue(k, v, level, maxLevel, name) end end end function malut.tableToString (t, maxLevel, name) tableToString_tablelist = {} tableToString_strBuilder = {} if name then tableToString_write(name, " =\n") end if type(t) == "table" then tableToString_write( "[", tostring(t), "]\n" ) tableToString_( t, 0, maxLevel, type(name)=="string" and name or "t" ) else if type(t)=="string" then tableToString_write( '"', t, '"' ) else tableToString_write(tostring(t)) end tableToString_write("\n") end local ret = table.concat(tableToString_strBuilder) tableToString_tablelist = nil tableToString_strBuilder = nil return ret end --@param t value to be printed, could be any value --@param maxLevel max recursion level, nil mean no limit --@name name of t function malut.printTable( t, maxLevel, name ) local str = malut.tableToString(t, maxLevel, name) print(str:sub(1, -2)) end -- --[[ function copy first check src.__copy, if it is a function, use it else if it is a table, if __copy[key] == true then copy src[key] if src[key].__copytype == "all", copy it --]] local emptyTable = {} local function copy (dst, src) local __copy = rawget(src, "__copy") if type(__copy) == "function" then return __copy( dst, src ) end if type(__copy) ~= "table" then __copy = emptyTable end for k,v in pairs(src) do local copyFlag = __copy[k] --true: copy table, false: copy none, nil: copy ref if copyFlag ~= false then if type(v) == "table" and v.__copytype ~= "ref" then if copyFlag == true or v.__copytype == "all" then local newT = {} local metaT = getmetatable(v) if metaT ~= nil then if metaT == src then setmetatable(newT, newT) else setmetatable(newT, metaT) end end dst[k] = copy( newT, v ) else dst[k] = v end else dst[k] = v end end end return dst end malut.copy = copy -- function clone, copy and add meta table local function clone (t) local newT = {} local metaT = getmetatable(t) if metaT ~= nil then if metaT == src then setmetatable(newT, newT) else setmetatable(newT, metaT) end end return copy( newT, t ) end malut.clone = clone -- copy without overwrite local emptyTable = {} local function copynew (dst, src) local retFlag = true local __copy = rawget(src, "__copy") if type(__copy) ~= "table" then __copy = emptyTable end for k,v in pairs(src) do local copyFlag = __copy[k] --true: copy table, false: copy none, nil: copy ref if copyFlag ~= false then if type(v) == "table" and v.__copytype ~= "ref" then local dstV = dst[k] if dstV == nil then if copyFlag == true or v.__copytype == "all" then local newT = {} local metaT = getmetatable(v) if metaT ~= nil then if metaT == src then setmetatable(newT, newT) else setmetatable(newT, metaT) end end dst[k] = copy( newT, v ) else dst[k] = v end elseif type(dstV)=="table" and (copyFlag == true or v.__copytype == "all") then local ret = copynew( dstV, v ) retFlag = retFlag and ret end elseif dst[k] == nil then dst[k] = v else retFlag = false end end end return retFlag end malut.copynew = copynew -- -- function toCode, convert table to code, return codeStr, errMsg -- no guarantee for float value precision -- local toCode_codes -- = {} -- initialized in function toCode() local toCode_tables -- = {} local toCode_ -- function toCode_ (t, level, subfix) local function toCode_printKeyValue (k, v, level) local indentInner = (' '):rep((level+1)*2) toCode_codes[#toCode_codes+1] = indentInner local typeK = type(k) if typeK == "number" or typeK == "boolean" then toCode_codes[#toCode_codes+1] = "[" toCode_codes[#toCode_codes+1] = tostring(k) toCode_codes[#toCode_codes+1] = "] = " elseif typeK == "string" then if k:match("^[%a_][%w_]*$") then -- valid variable name toCode_codes[#toCode_codes+1] = k.." = " else toCode_codes[#toCode_codes+1] = ("[%q] = "):format(k) end else error( "unsupported key type: "..typeK..", for "..tostring(k), 4+2*level ) end local typeV = type(v) if typeV == "number" or typeV == "boolean" then toCode_codes[#toCode_codes+1] = tostring(v) toCode_codes[#toCode_codes+1] = ";\n" elseif typeV == "string" then toCode_codes[#toCode_codes+1] = ("%q;\n"):format(v) elseif typeV == "table" then if toCode_tables[v] then error( "table has ring: "..tostring(v), 3 ) end toCode_codes[#toCode_codes+1] = "\n" return toCode_(v, level + 1, ";\n") -- convert to tail call else error( "unsupported value type: "..typeV..", for "..tostring(v), 4+2*level ) end end --local function toCode_ (t, level, subfix) -- recursion function toCode_tables[t] = true local indent = (' '):rep(level*2) local indentInner = (' '):rep((level+1)*2) toCode_codes[#toCode_codes+1] = indent toCode_codes[#toCode_codes+1] = "{\n" local size = #t -- array part for i = 1, size do local v = t[i] if v ~= nil then toCode_printKeyValue(i, v, level) end end -- map part for k,v in pairs(t) do if type(k) == "number" and k >= 1 and k <= size then -- already printed else toCode_printKeyValue(k, v, level) end end toCode_codes[#toCode_codes+1] = indent toCode_codes[#toCode_codes+1] = "}" toCode_codes[#toCode_codes+1] = subfix return true end local function toCode (t) local typeT = type(t) if typeT == "table" then toCode_codes = {} toCode_tables = {} toCode_(t, 0, "") local result = tableconcat(toCode_codes) toCode_codes = nil toCode_tables = nil return result elseif typeT == "number" or typeT == "boolean" then return tostring(t) elseif typeT == "string" then return ("%q"):format(t) else error( "unsupported value type: "..typeT, 2) end end malut.toCode = toCode function malut.toCodeToFile (t, fileName) local fout, err = ioopen(fileName, "w") if fout then fout:write("return\n", toCode(t)) fout:close() return true else return nil, err end end if is_5_1 then function malut.fromCode (str) local func, err = loadstring(str) if func then local s, ret = pcall( setfenv( func, {} ) ) if s then return ret else return nil, ret end else return nil, err end end else function malut.fromCode (str) local func, err = load(str, nil, nil, {}) if func then local s, ret = pcall(func) if s then return ret else return nil, ret end else return nil, err end end end if is_5_1 then function malut.fromCodeInFile (fileName) local func, err = loadfile(fileName) if func then local s, ret = pcall( setfenv( func, {} ) ) if s then return ret else return nil, ret end else return nil, err end end else function malut.fromCodeInFile (fileName) local func, err = loadfile(fileName, nil, {}) if func then local s, ret = pcall(func) if s then return ret else return nil, ret end else return nil, err end end end return malut
local function _updateRepo(destination, url, name, branch) local current = os.getcwd() if os.isdir(destination) then printf(" - Updating '%s'", name) os.chdir(destination) if branch then os.executef("git checkout %s", branch) else os.execute("git checkout .") end if url and branch then os.executef("git pull %s %s", url, branch) else os.execute("git pull") end os.chdir(current) else printf(" - Creating '%s'", name) if branch then os.executef("git clone -v -b %s --recurse --depth 1 --progress \"%s\" \"%s\"", branch, url, destination) else os.executef("git clone -v --recurse --depth 1 --progress \"%s\" \"%s\"", url, destination) end end end newaction { trigger = "update-bootstrap", shortname = "Update module loader", description = "Updates the module loader bootstrapping process", execute = function() local destination = path.join(CMD, BOOTSTRAP_DIR) _updateRepo(destination, BOOTSTRAP_REPO, "bootstrap loader", BOOTSTRAP_BRANCH) end } newaction { trigger = "update-zpm", shortname = "Update zpm", description = "Updates the zpm module", execute = function() local destination = path.join(CMD, ZPM_DIR) _updateRepo(destination, ZPM_REPO, "zpm", ZPM_BRANCH) end } newaction { trigger = "update-registry", shortname = "Update the registry", description = "Updates the zpm library definitions", execute = function() local destination = path.join(CMD, REGISTRY_DIR) _updateRepo(destination, REGISTRY_REPO, "registry", REGISTRY_BRANCH) end } newaction { trigger = "repair", shortname = "Repairs ZPM", description = "Repairs the current installation", execute = function() premake.action.call("update-bootstrap") premake.action.call("update-zpm") premake.action.call("update-registry") end } if not (_ACTION and (_ACTION:contains("update-") or _ACTION == "repair")) then if not zpm or (zpm and not zpm.__isLoaded) then bootstrap = dofile(path.join(_PREMAKE_DIR, "../bootstrap/bootstrap.lua")) zpm = dofile(path.join(_PREMAKE_DIR, "../zpm/zpm.lua")) zpm.onLoad() zpm.__isLoaded = true end else if zpm then zpm.util.disableMainScript() end end
local snownet = require "snownet" local debugchannel = require "snownet.debugchannel" local CMD = {} local channel function CMD.start(address, fd) assert(channel == nil, "start more than once") snownet.error(string.format("Attach to :%08x", address)) local handle channel, handle = debugchannel.create() local ok, err = pcall(snownet.call, address, "debug", "REMOTEDEBUG", fd, handle) if not ok then snownet.ret(snownet.pack(false, "Debugger attach failed")) else -- todo hook snownet.ret(snownet.pack(true)) end snownet.exit() end function CMD.cmd(cmdline) channel:write(cmdline) end function CMD.ping() snownet.ret() end snownet.start(function() snownet.dispatch("lua", function(_,_,cmd,...) local f = CMD[cmd] f(...) end) end)
local utils = require 'mp.utils' local msg = require 'mp.msg' local options = require 'mp.options' local lib = mp.find_config_file('scripts/lib.disable') if not lib then return end -- lib can be nil if the folder does not exist or we're in --no-config mode package.path = package.path .. ';' .. lib .. '/?.lua;' require 'gallery' ON_WINDOWS = (package.config:sub(1,1) ~= "/") -- global path = "" path_hash = "" duration = 0 did_pause = false time_pos = 0 with_chapters = false bindings = {} bindings_repeat = {} compute_geometry = function(ww, wh) end ass_changed = false ass = "" geometry_changed = false pending_selection = nil thumbs_dir = "" gallery = gallery_new() gallery.config.accurate = true gallery.config.align_text = false gallery.config.always_show_placeholders = false opts = { thumbs_dir = ON_WINDOWS and "%APPDATA%\\mpv\\gallery-thumbs-dir" or "~/.mpv_thumbs_dir/", generate_thumbnails_with_mpv = ON_WINDOWS, --gallery_position = "{30, 30}", --gallery_size = "{tw + 4*sw, wh - 2*gy }", --min_spacing = "{15, 15}", --thumbnail_size = "(ww * wh <= 1280 * 720) and {192, 108} or (ww * wh <= 1920 * 1080) and {288, 162} or {384, 216}", -- basic centered grid --gallery_position = "{ ww/20, wh/20 }", --gallery_size = "{ww - 2*gx, wh - 2*gy}", --min_spacing = "{15, 15}", --thumbnail_size = "(ww * wh <= 1280 * 720) and {192, 108} or (ww * wh <= 1920 * 1080) and {288, 162} or {384, 216}", -- grid with minimum margins gallery_position = "{ (ww - gw) / 2, (wh - gh) / 2}", gallery_size = "{ 9 * ww / 10, 9 * wh / 10 }", min_spacing = "{ 15, 15 }", thumbnail_size = "(ww * wh <= 1366 * 768) and {192, 108} or {288, 162}", max_thumbnails = 64, seek_on_toggle_off = false, close_on_seek = true, pause_on_start = true, resume_on_stop = "only-if-did-pause", time_distance = "2%", chapter_mode = false, chapter_mode_time_offset = 2, chapter_mode_fallback_to_time_steps = true, show_text = "selection", show_millisecond_precision = true, text_size = 28, background_color = "333333", background_opacity = "33", normal_border_color = "BBBBBB", normal_border_size = 1, selected_border_color = "E5E4E5", selected_border_size = 6, highlight_previous = true, previous_border_color = "EBC5A7", previous_border_size = 4, placeholder_color = "222222", command_on_open = "", command_on_close = "", mouse_support = true, UP = "UP", DOWN = "DOWN", LEFT = "LEFT", RIGHT = "RIGHT", PAGE_UP = "PGUP", PAGE_DOWN = "PGDWN", FIRST = "HOME", LAST = "END", RANDOM = "r", ACCEPT = "ENTER", CANCEL = "ESC", } function reload_config() gallery.config.generate_thumbnails_with_mpv = opts.generate_thumbnails_with_mpv gallery.config.placeholder_color = opts.placeholder_color gallery.config.background_color = opts.background_color gallery.config.background_opacity = opts.background_opacity gallery.config.max_thumbnails = math.min(opts.max_thumbnails, 64) gallery.config.text_size = opts.text_size if ON_WINDOWS then thumbs_dir = string.gsub(opts.thumbs_dir, "^%%APPDATA%%", os.getenv("APPDATA") or "%APPDATA%") else thumbs_dir = string.gsub(opts.thumbs_dir, "^~", os.getenv("HOME") or "~") end local res = utils.file_info(thumbs_dir) if not res or not res.is_dir then msg.error(string.format("Thumbnail directory \"%s\" does not exist", thumbs_dir)) end compute_geometry = get_geometry_function() reload_bindings() if gallery.active then local ww, wh = mp.get_osd_size() compute_geometry(ww, wh) gallery:ass_refresh(true, true, true, true) reload_items() end end options.read_options(opts, mp.get_script_name(), reload_config) local sha256 --[[ minified code below is a combination of: -sha256 implementation from http://lua-users.org/wiki/SecureHashAlgorithm -lua implementation of bit32 (used as fallback on lua5.1) from https://www.snpedia.com/extensions/Scribunto/engines/LuaCommon/lualib/bit32.lua both are licensed under the MIT below: 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. --]] do local b,c,d,e,f;if bit32 then b,c,d,e,f=bit32.band,bit32.rrotate,bit32.bxor,bit32.rshift,bit32.bnot else f=function(g)g=math.floor(tonumber(g))%0x100000000;return(-g-1)%0x100000000 end;local h={[0]={[0]=0,0,0,0},[1]={[0]=0,1,0,1},[2]={[0]=0,0,2,2},[3]={[0]=0,1,2,3}}local i={[0]={[0]=0,1,2,3},[1]={[0]=1,0,3,2},[2]={[0]=2,3,0,1},[3]={[0]=3,2,1,0}}local function j(k,l,m,n,o)for p=1,m do l[p]=math.floor(tonumber(l[p]))%0x100000000 end;local q=1;local r=0;for s=0,31,2 do local t=n;for p=1,m do t=o[t][l[p]%4]l[p]=math.floor(l[p]/4)end;r=r+t*q;q=q*4 end;return r end;b=function(...)return j('band',{...},select('#',...),3,h)end;d=function(...)return j('bxor',{...},select('#',...),0,i)end;e=function(g,u)g=math.floor(tonumber(g))%0x100000000;u=math.floor(tonumber(u))u=math.min(math.max(-32,u),32)return math.floor(g/2^u)%0x100000000 end;c=function(g,u)g=math.floor(tonumber(g))%0x100000000;u=-math.floor(tonumber(u))%32;local g=g*2^u;return g%0x100000000+math.floor(g/0x100000000)end end;local v={0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2}local function w(n)return string.gsub(n,".",function(t)return string.format("%02x",string.byte(t))end)end;local function x(y,z)local n=""for p=1,z do local A=y%256;n=string.char(A)..n;y=(y-A)/256 end;return n end;local function B(n,p)local z=0;for p=p,p+3 do z=z*256+string.byte(n,p)end;return z end;local function C(D,E)local F=-(E+1+8)%64;E=x(8*E,8)D=D.."\128"..string.rep("\0",F)..E;return D end;local function G(H)H[1]=0x6a09e667;H[2]=0xbb67ae85;H[3]=0x3c6ef372;H[4]=0xa54ff53a;H[5]=0x510e527f;H[6]=0x9b05688c;H[7]=0x1f83d9ab;H[8]=0x5be0cd19;return H end;local function I(D,p,H)local J={}for K=1,16 do J[K]=B(D,p+(K-1)*4)end;for K=17,64 do local L=J[K-15]local M=d(c(L,7),c(L,18),e(L,3))L=J[K-2]local N=d(c(L,17),c(L,19),e(L,10))J[K]=J[K-16]+M+J[K-7]+N end;local O,s,t,P,Q,R,S,T=H[1],H[2],H[3],H[4],H[5],H[6],H[7],H[8]for p=1,64 do local M=d(c(O,2),c(O,13),c(O,22))local U=d(b(O,s),b(O,t),b(s,t))local V=M+U;local N=d(c(Q,6),c(Q,11),c(Q,25))local W=d(b(Q,R),b(f(Q),S))local X=T+N+W+v[p]+J[p]T=S;S=R;R=Q;Q=P+X;P=t;t=s;s=O;O=X+V end;H[1]=b(H[1]+O)H[2]=b(H[2]+s)H[3]=b(H[3]+t)H[4]=b(H[4]+P)H[5]=b(H[5]+Q)H[6]=b(H[6]+R)H[7]=b(H[7]+S)H[8]=b(H[8]+T)end;local function Y(H)return w(x(H[1],4)..x(H[2],4)..x(H[3],4)..x(H[4],4)..x(H[5],4)..x(H[6],4)..x(H[7],4)..x(H[8],4))end;local Z={}sha256=function(D)D=C(D,#D)local H=G(Z)for p=1,#D,64 do I(D,p,H)end;return Y(H)end end -- end of sha code gallery.ass_show = function(new_ass) ass_changed = true ass = new_ass end function item_to_time(item, with_offset) if not with_chapters then return item end if not with_offset then return item.time end local time_with_offset = item.time + opts.chapter_mode_time_offset if time_with_offset < duration then return time_with_offset else return item.time; end end gallery.item_to_overlay_path = function(index, item) local thumb_filename = string.format("%s_%u_%d_%d", path_hash, item_to_time(item, true) * 100, gallery.geometry.thumbnail_size[1], gallery.geometry.thumbnail_size[2]) return utils.join_path(thumbs_dir, thumb_filename) end gallery.item_to_thumbnail_params = function(index, item) return path, item_to_time(item, true) end function blend_colors(colors) if #colors == 1 then return colors[1] end local comp1 = 0 local comp2 = 0 local comp3 = 0 for _, val in ipairs(colors) do comp1 = comp1 + tonumber(string.sub(val, 1, 2), 16) comp2 = comp2 + tonumber(string.sub(val, 3, 4), 16) comp3 = comp3 + tonumber(string.sub(val, 5, 6), 16) end return string.format("%02x%02x%02x", comp1 / #colors, comp2 / #colors, comp3 / #colors) end gallery.item_to_border = function(index, item) local size = 0 colors = {} if index == gallery.selection then colors[#colors + 1] = opts.selected_border_color size = math.max(size, opts.selected_border_size) end if opts.highlight_previous and time_pos and item_to_time(item, false) <= (time_pos + 0.01) and (index == #gallery.items or item_to_time(gallery.items[index + 1], false) > (time_pos + 0.01)) then colors[#colors + 1] = opts.previous_border_color size = math.max(size, opts.previous_border_size) end if #colors == 0 then return opts.normal_border_size, opts.normal_border_color else return size, blend_colors(colors) end end gallery.item_to_text = function(index, item) if opts.show_text == "everywhere" or (opts.show_text == "selection" and index == gallery.selection) then if with_chapters and item.title ~= "" and item.title ~= "(unnamed)" then return item.title else local str local time = item_to_time(item, false) if duration > 3600 then str = string.format("%d:%02d:%02d", time / 3600, (time / 60) % 60, time % 60) else str = string.format("%02d:%02d", (time / 60) % 60, time % 60) end if opts.show_millisecond_precision then str = string.format("%s.%03d", str, math.floor(time * 1000 % 1000)) end return str end else return "" end end function setup_ui_handlers() for key, func in pairs(bindings_repeat) do mp.add_forced_key_binding(key, "playlist-view-"..key, func, {repeatable = true}) end for key, func in pairs(bindings) do mp.add_forced_key_binding(key, "playlist-view-"..key, func) end end function teardown_ui_handlers() for key, _ in pairs(bindings_repeat) do mp.remove_key_binding("playlist-view-"..key) end for key, _ in pairs(bindings) do mp.remove_key_binding("playlist-view-"..key) end end function reload_bindings() if gallery.active then teardown_ui_handlers() end bindings = {} bindings_repeat = {} local increment_func = function(increment, clamp) local new = (pending_selection or gallery.selection) + increment if new <= 0 or new > #gallery.items then if not clamp then return end new = math.max(1, math.min(new, #gallery.items)) end pending_selection = new end bindings[opts.FIRST] = function() pending_selection = 1 end bindings[opts.LAST] = function() pending_selection = #gallery.items end bindings[opts.ACCEPT] = function() seek_to_selection() if opts.close_on_seek then stop() end end bindings[opts.CANCEL] = function() stop() end if opts.mouse_support then bindings["MBTN_LEFT"] = function() local index = gallery:index_at(mp.get_mouse_pos()) if not index then return end if index == gallery.selection then seek_to_selection() if opts.close_on_seek then stop() end else pending_selection = index end end bindings["WHEEL_UP"] = function() increment_func(- gallery.geometry.columns, false) end bindings["WHEEL_DOWN"] = function() increment_func( gallery.geometry.columns, false) end end bindings_repeat[opts.UP] = function() increment_func(- gallery.geometry.columns, false) end bindings_repeat[opts.DOWN] = function() increment_func( gallery.geometry.columns, false) end bindings_repeat[opts.LEFT] = function() increment_func(- 1, false) end bindings_repeat[opts.RIGHT] = function() increment_func( 1, false) end bindings_repeat[opts.PAGE_UP] = function() increment_func(- gallery.geometry.columns * gallery.geometry.rows, true) end bindings_repeat[opts.PAGE_DOWN] = function() increment_func( gallery.geometry.columns * gallery.geometry.rows, true) end bindings_repeat[opts.RANDOM] = function() pending_selection = math.random(1, #gallery.items) end if gallery.active then setup_ui_handlers() end end -- the purpose of this highly-convoluted code is to handle the geometries of the gallery -- dynamically, while computing the different properties in the correct order -- so that they can reference one another (barring cyclical dependencies) function get_geometry_function() local geometry_functions = loadstring(string.format([[ return { function(ww, wh, gx, gy, gw, gh, sw, sh, tw, th) return %s end, function(ww, wh, gx, gy, gw, gh, sw, sh, tw, th) return %s end, function(ww, wh, gx, gy, gw, gh, sw, sh, tw, th) return %s end, function(ww, wh, gx, gy, gw, gh, sw, sh, tw, th) return %s end }]], opts.gallery_position, opts.gallery_size, opts.min_spacing, opts.thumbnail_size))() local names = { "gallery_position", "gallery_size", "min_spacing", "thumbnail_size" } local order = {} -- the order in which the 4 properties should be computed, based on inter-dependencies -- build the dependency matrix local patterns = { "g[xy]", "g[wh]", "s[wh]", "t[wh]" } local deps = {} for i = 1,4 do for j = 1,4 do local i_depends_on_j = (string.find(opts[names[i]], patterns[j]) ~= nil) if i == j and i_depends_on_j then msg.error(names[i] .. " depends on itself") return end deps[i * 4 + j] = i_depends_on_j end end local has_deps = function(index) for j = 1,4 do if deps[index * 4 + j] then return true end end return false end local num_resolved = 0 local resolved = { false, false, false, false } while true do local resolved_one = false for i = 1, 4 do if resolved[i] then -- nothing to do elseif not has_deps(i) then order[#order + 1] = i -- since i has no deps, anything that depends on it might as well not for j = 1, 4 do deps[j * 4 + i] = false end resolved[i] = true resolved_one = true num_resolved = num_resolved + 1 end end if num_resolved == 4 then break elseif not resolved_one then local str = "" for index, resolved in ipairs(resolved) do if not resolved then str = (str == "" and "" or (str .. ", ")) .. names[index] end end msg.error("Circular dependency between " .. str) return end end return function(window_width, window_height) local new_geom = { gallery_position = {}, gallery_size = {}, min_spacing = {}, thumbnail_size = {}, } local show_text = (opts.show_text == "selection" or opts.show_text == "everywhere") for _, index in ipairs(order) do new_geom[names[index]] = geometry_functions[index]( window_width, window_height, new_geom.gallery_position[1], new_geom.gallery_position[2], new_geom.gallery_size[1], new_geom.gallery_size[2], new_geom.min_spacing[1], new_geom.min_spacing[2], new_geom.thumbnail_size[1], new_geom.thumbnail_size[2] ) if show_text and names[index] == "min_spacing" then new_geom.min_spacing[2] = math.max(opts.text_size, new_geom.min_spacing[2]) elseif names[index] == "thumbnail_size" then new_geom.thumbnail_size[1] = math.floor(new_geom.thumbnail_size[1]) new_geom.thumbnail_size[2] = math.floor(new_geom.thumbnail_size[2]) end end gallery:set_geometry( new_geom.gallery_position[1], new_geom.gallery_position[2], new_geom.gallery_size[1], new_geom.gallery_size[2], new_geom.min_spacing[1], new_geom.min_spacing[2], new_geom.thumbnail_size[1], new_geom.thumbnail_size[2] ) end end function normalize_path(path) if string.find(path, "://") then return path end path = utils.join_path(utils.getcwd(), path) if ON_WINDOWS then path = string.gsub(path, "\\", "/") end path = string.gsub(path, "/%./", "/") local n repeat path, n = string.gsub(path, "/[^/]*/%.%./", "/", 1) until n == 0 return path end function time_pos_changed(_, val) time_pos = val if opts.highlight_previous then gallery:ass_refresh(true, false, false, false) end end function idle() if pending_selection then gallery:set_selection(pending_selection) pending_selection = nil end if ass_changed or geometry_changed then local ww, wh = mp.get_osd_size() if geometry_changed then geometry_changed = false compute_geometry(ww, wh) end if ass_changed then ass_changed = false mp.set_osd_ass(ww, wh, ass) end end end function mark_geometry_stale() geometry_changed = true end function reload_items() with_chapters = false if opts.chapter_mode then local chap_list = mp.get_property_native("chapter-list") if #chap_list > 0 then with_chapters = true gallery.items = chap_list elseif opts.chapter_mode_fallback_to_time_steps then -- empty else return end end if not with_chapters then local effective_time_distance if string.sub(opts.time_distance, -1) == "%" then effective_time_distance = tonumber(string.sub(opts.time_distance, 1, -2)) / 100 * duration else effective_time_distance = tonumber(opts.time_distance) end local time = 0 local times = {} while time < duration do times[#times + 1] = time time = time + effective_time_distance end gallery.items = times end local selection = #gallery.items for index, value in ipairs(gallery.items) do if item_to_time(value, false) > time_pos + 0.01 then selection = math.max(index - 1, 1) break end end gallery:items_changed(selection) end function start() if gallery.active then return end if not mp.get_property_bool("seekable") then msg.error("Video is not seekable") return end path = mp.get_property("path") path_hash = string.sub(sha256(normalize_path(path)), 1, 12) duration = mp.get_property_number("duration") if not duration or duration == 0 then return end duration = duration - (1 / mp.get_property_number("container-fps", 30)) if duration == 0 then return end time_pos = mp.get_property_number("time-pos") reload_items() local ww, wh = mp.get_osd_size() compute_geometry(ww, wh) if not gallery:activate() then return end if opts.command_on_open ~= "" then mp.command(opts.command_on_open) end did_pause = false if opts.pause_on_start and not mp.get_property_bool("pause", false) then mp.set_property_bool("pause", true) did_pause = true end mp.observe_property("time-pos", "number", time_pos_changed) mp.observe_property("osd-width", "native", mark_geometry_stale) mp.observe_property("osd-height", "native", mark_geometry_stale) mp.register_idle(idle) mp.register_event("end-file", stop) idle() setup_ui_handlers() end function seek_to_selection() if not gallery.active then return end local time = item_to_time(gallery.items[gallery.selection], false) if not time then return end mp.commandv("seek", time, "absolute") end function stop() if not gallery.active then return end mp.unregister_event(stop) if opts.resume_on_stop == "yes" or (opts.resume_on_stop == "only-if-did-pause" and did_pause) then mp.set_property_bool("pause", false) end if opts.command_on_close ~= "" then mp.command(opts.command_on_close) end mp.unobserve_property(time_pos_changed) mp.unobserve_property(mark_geometry_stale) mp.unregister_idle(idle) gallery:deactivate() teardown_ui_handlers() idle() end function toggle() if not gallery.active then start() else if opts.seek_on_toggle_off then seek_to_selection() end stop() end end reload_config() mp.register_script_message("thumbnail-generated", function(thumb_path) gallery:thumbnail_generated(thumb_path) end) mp.register_script_message("thumbnails-generator-broadcast", function(generator_name) gallery:add_generator(generator_name) end) mp.add_key_binding(nil, "contact-sheet-open", start) mp.add_key_binding(nil, "contact-sheet-close", stop) mp.add_key_binding('c', "contact-sheet-toggle", toggle) mp.add_key_binding(nil, "contact-sheet-seek", seek_to_selection)
YF = 1.70710678118654752440 XF = 0.70710678118654752440 RYF = 0.58578643762690495119 RXF = 1.41421356237309504880 maxx = XF * pi maxy = YF * tan(0.5*pi/2) max_fov = 360 max_vfov = 180 lens_width = maxx*2 lens_height = maxy*2 onload = "f_contain" function lens_forward(x,y,z) if abs(x) > maxx or abs(y) > maxy then return nil end local lat,lon = ray_to_latlon(x,y,z) local x = XF * lon local y = YF * tan(0.5 * lat) return x,y end function lens_inverse(x,y) local lon = RXF * x local lat = 2 * atan(y * RYF) return latlon_to_ray(lat,lon) end
-- Inventory-related methods local Inventory = {} -- TODO: Consider the Cursor Inventory too (otherwise items can be lost during transition) -- TODO: Consider Filters (otherwise they are lost during transition) -- Whether a Player's Inventory is vulnerable to going missing due to lack of a body function Inventory.ShouldPersist(controller) return controller ~= defines.controllers.character end -- Ensure a Player's Inventory isn't full function Inventory.Prune(player) local inventory = player.get_main_inventory() if not inventory then return end if inventory.count_empty_stacks() == 0 then player.print("Your inventory is almost full. Please throw some items away.") player.surface.spill_item_stack(player.position, inventory[#inventory]) inventory[#inventory].clear() end end -- Persist one Inventory into another mod-created one function Inventory.Persist(from, to) if not from then return nil end if not to then to = game.create_inventory(#from) else to.resize(#from) end for i = 1, #from do to[i].set_stack(from[i]) end return to end -- Restore one Inventory into another function Inventory.Restore(from, to) if not from or not to then return end local transition = math.min(#from, #to) for i = 1, transition do to[i].set_stack(from[i]) end if transition < #to then for i = transition + 1, #to do to[i].set_stack() end end end return Inventory
--spawnpoint of Libria_main spawnpoint 'a_m_y_runner_01' { x = -1477.14, y = -538.7499, z = 55.5264 } --
--[[ Mojang Authentication API No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) OpenAPI spec version: 2020-06-05 Generated by: https://openapi-generator.tech ]] -- reduced_user_data class local reduced_user_data = {} local reduced_user_data_mt = { __name = "reduced_user_data"; __index = reduced_user_data; } local function cast_reduced_user_data(t) return setmetatable(t, reduced_user_data_mt) end local function new_reduced_user_data(id, properties) return cast_reduced_user_data({ ["id"] = id; ["properties"] = properties; }) end return { cast = cast_reduced_user_data; new = new_reduced_user_data; }
local function writebytes(x) local b2=string.char(x%256) x=(x-x%256)/256 local b1=string.char(x%256) x=(x-x%256)/256 return b2,b1 end function bytes(x) local b2=x%256 x=(x-x%256)/256 local b1=x%256 x=(x-x%256)/256 return string.char(b1,b2) end function write_int(x) local b4=x%256 x=(x-x%256)/256 local b3=x%256 x=(x-x%256)/256 local b2=x%256 x=(x-x%256)/256 local b1=x%256 x=(x-x%256)/256 return string.char(b1,b2,b3,b4) end local function on_click_save(self, mouse) local function on_save( path) local size_map = Map.size_map local output = assert(io.open(PATH_MAPS .. path .. ".map", "wb")) local max_x = #Tiles.fields[1] output:write(bytes(size_map[1])) output:write(bytes(size_map[2])) for y=1, #Tiles.fields do for x=1, max_x do local num = Tiles.get_element(x,y) output:write(string.char(num)) end end output:close() MpR.save(path) end local save = GUI.make_input_frame("SAVE", 70,"txt",on_save) GUI.compose_object(self.parrent.parrent, save) GUI.send_event(self.parrent.parrent, "on_activate", save) GUI.send_event(self.parrent.parrent, "on_click_save") GUI.add_event(save,"on_click",function (self) GUI.send_event(self.parrent,"on_activate", save) end) GUI.add_event(save, "on_activate", function (self) GUI.send_event(self.parrent,"on_activate", save) end) end local function on_click_load(self, mouse) local function on_load(path) local result = path -- result = string.match(path,"%w+") result = path Map.load(result, true) Map.render(0,0) -- mini_map = Mini_map.make() GUI.send_event(self.parrent.parrent,"on_change_map") end local fB = GUI.make_file_browser(PATH_MAPS,on_load) GUI.compose_object(self.parrent.parrent, fB) end local Menu = {} function Menu.make() local menu_bar = make_layout_buttons({{"SAVE", on_click_save}, {"LOAD", on_click_load}}) return menu_bar end return Menu
local function Y(x) return (function (f) return f(f) end)(function(y) return x(function(z) return y(y)(z) end) end) end return Y(function(fibs) return function(n) return n < 2 and 1 or fibs(n - 1) + fibs(n - 2) end end)
Config = {} Config.DrawDistance = 100.0 --language currently available EN and SV Config.Locale = 'sv' Config.Zones = { PoliceDuty = { Pos = { x = 439.825, y = -975.693, z = 29.691 }, Size = { x = 2.5, y = 2.5, z = 1.5 }, Color = { r = 0, g = 255, b = 0 }, Type = 27, }, AmbulanceDuty = { Pos = { x = 264.45, y = -1356.84, z = 23.56 }, Size = { x = 2.5, y = 2.5, z = 1.5 }, Color = { r = 0, g = 255, b = 0 }, Type = 27, }, }
Talk(79, "我说老五啊,天气这么冷,喝这烈酒虽能驱寒,但如能再配上热腾腾的兔肉,那才真是够味呢.", "talkname79", 0); Talk(79, "四哥,在这寒天雪地中,上那找兔肉去?", "talkname79", 4); Talk(79, "谁说没有兔子,只是我们功夫不济,抓不到罢了.我曾听人家说,在极北之地有一个很厉害的猎户,轻功极高,在这雪地上猎兔,犹如猎鹰般的快,狠,准.", "talkname79", 0); Talk(79, "那还等什么,我们这就上他 家去要点兔肉来吃.", "talkname79", 4); Talk(79, "你想上他家?我看要等到下辈子了.你知道他住那吗?他住的地方叫”云鹤崖”,轻功不到家的人根本就上不去.", "talkname79", 0); Talk(79, "云鹤崖?他该不会是....", "talkname79", 4); Talk(79, "没错,四大恶人之一的云中鹤.", "talkname79", 0); Talk(79, "那...那我们还是喝酒就好了.", "talkname79", 4); do return end;
-- in millisecond, used for both CursorHold and CursorHoldI, -- use updatetime instead if not defined vim.g.cursorhold_updatetime = 100
local Var = require "lattice.var" local Element = require "lattice.element" local Cell = {} function Cell:InitWithScope(scope) local vars = {} local newCell = {_vars = vars} for _, varName in pairs(scope) do vars[varName] = Var:InitWithName(varName) end setmetatable(newCell, self) self.__index = self return newCell end function Cell:getVar(name) local var = self._vars[name] if not var then -- Means it's an upvalue not assigned -- to before. var = Var:InitWithName(name) var:setBottom() return var else return var end end function Cell:addVar(name) self._vars[name] = Var:InitWithName(name) end function Cell:setElementToVar(name, element) local var = self:getVar(name) var:setElement(element) end -- Returns if there's some change function Cell:updateWithInEdges(edges) local cells = {} for _,edge in ipairs(edges) do if edge:isExecutable() then table.insert(cells, edge:getFromNode().outCell) end end local changed = false local vars = self._vars for name, var in pairs(vars) do for _,cell in ipairs(cells) do local otherVar = cell:getVar(name) changed = var:meet(otherVar) or changed end end return changed end function Cell:compareWithCell(cell) for name,var in pairs(self._vars)do local otherVar = cell:getVar(name) if not var:equal(otherVar) then return false end end return true end function Cell:copy() local vars = {} local newCell = {_vars = vars} for name, var in pairs(self._vars) do vars[name] = var:copy() end setmetatable(newCell, getmetatable(self)) return newCell end function Cell:bottomAllVars() for _,var in ipairs(self._vars) do var:setElement(Element:InitWithBottom()) end end return Cell
local modname = ... local theme = {} package.loaded[modname] = theme local imageSuffix = display.imageSuffix or "" local sheetFile = "theme/editField.png" local sheetData = "theme.editField" theme.editField = { sheet = sheetFile, data = sheetData, topLeftFrame = "editField_topLeft", middleLeftFrame = "editField_middleLeft", bottomLeftFrame = "editField_bottomLeft", topMiddleFrame = "editField_topMiddle", middleFrame = "editField_middle", bottomMiddleFrame = "editField_bottomMiddle", topRightFrame = "editField_topRight", middleRightFrame = "editField_middleRight", bottomRightFrame = "editField_bottomRight", textFieldWidth = 150, textFieldHeight = 29, } return theme
local has_devicons, devicons = pcall(require, 'nvim-web-devicons') local conf = require('telescope.config').values local entry_display = require('telescope.pickers.entry_display') local path = require('telescope.path') local utils = require('telescope.utils') local get_default = utils.get_default local make_entry = {} local transform_devicons if has_devicons then if not devicons.has_loaded() then devicons.setup() end transform_devicons = function(filename, display, disable_devicons) if disable_devicons or not filename then return display end local icon, icon_highlight = devicons.get_icon(filename, string.match(filename, '%a+$'), { default = true }) local icon_display = (icon or ' ') .. ' ' .. display if conf.color_devicons then return icon_display, icon_highlight else return icon_display end end else transform_devicons = function(_, display, _) return display end end do local lookup_keys = { display = 1, ordinal = 1, value = 1, } local mt_string_entry = { __index = function(t, k) return rawget(t, rawget(lookup_keys, k)) end } function make_entry.gen_from_string() return function(line) return setmetatable({ line, }, mt_string_entry) end end end do local lookup_keys = { ordinal = 1, value = 1, filename = 1, cwd = 2, } function make_entry.gen_from_file(opts) opts = opts or {} local cwd = vim.fn.expand(opts.cwd or vim.fn.getcwd()) local disable_devicons = opts.disable_devicons local shorten_path = opts.shorten_path local mt_file_entry = {} mt_file_entry.cwd = cwd mt_file_entry.display = function(entry) local display, hl_group = entry.value if shorten_path then display = utils.path_shorten(display) end display, hl_group = transform_devicons(entry.value, display, disable_devicons) if hl_group then return display, { { {1, 3}, hl_group } } else return display end end mt_file_entry.__index = function(t, k) local raw = rawget(mt_file_entry, k) if raw then return raw end if k == "path" then return t.cwd .. path.separator .. t.value end return rawget(t, rawget(lookup_keys, k)) end return function(line) return setmetatable({line}, mt_file_entry) end end end do local lookup_keys = { value = 1, ordinal = 1, } -- Gets called only once to parse everything out for the vimgrep, after that looks up directly. local parse = function(t) local _, _, filename, lnum, col, text = string.find(t.value, [[([^:]+):(%d+):(%d+):(.*)]]) local ok ok, lnum = pcall(tonumber, lnum) if not ok then lnum = nil end ok, col = pcall(tonumber, col) if not ok then col = nil end t.filename = filename t.lnum = lnum t.col = col t.text = text return {filename, lnum, col, text} end local execute_keys = { path = function(t) return t.cwd .. path.separator .. t.filename, false end, filename = function(t) return parse(t)[1], true end, lnum = function(t) return parse(t)[2], true end, col = function(t) return parse(t)[3], true end, text = function(t) return parse(t)[4], true end, } function make_entry.gen_from_vimgrep(opts) opts = opts or {} local shorten_path = opts.shorten_path local disable_coordinates = opts.disable_coordinates local disable_devicons = opts.disable_devicons local display_string = "%s:%s%s" local mt_vimgrep_entry = {} mt_vimgrep_entry.cwd = vim.fn.expand(opts.cwd or vim.fn.getcwd()) mt_vimgrep_entry.display = function(entry) local display_filename if shorten_path then display_filename = utils.path_shorten(entry.filename) else display_filename = entry.filename end local coordinates = "" if not disable_coordinates then coordinates = string.format("%s:%s:", entry.lnum, entry.col) end local display, hl_group = transform_devicons( entry.filename, string.format(display_string, display_filename, coordinates, entry.text), disable_devicons ) if hl_group then return display, { { {1, 3}, hl_group } } else return display end end mt_vimgrep_entry.__index = function(t, k) local raw = rawget(mt_vimgrep_entry, k) if raw then return raw end local executor = rawget(execute_keys, k) if executor then local val, save = executor(t) if save then rawset(t, k, val) end return val end return rawget(t, rawget(lookup_keys, k)) end return function(line) return setmetatable({line}, mt_vimgrep_entry) end end end function make_entry.gen_from_git_commits() return function(entry) if entry == "" then return nil end local sha, msg = string.match(entry, '([^ ]+) (.+)') return { value = sha, ordinal = sha .. ' ' .. msg, display = sha .. ' ' .. msg, } end end function make_entry.gen_from_quickfix(opts) opts = opts or {} opts.tail_path = get_default(opts.tail_path, true) local make_display = function(entry) local to_concat = {} if not opts.hide_filename then local filename = entry.filename if opts.tail_path then filename = utils.path_tail(filename) elseif opts.shorten_path then filename = utils.path_shorten(filename) end table.insert(to_concat, filename) table.insert(to_concat, ":") end table.insert(to_concat, entry.text) return table.concat(to_concat, "") end return function(entry) local filename = entry.filename or vim.api.nvim_buf_get_name(entry.bufnr) return { valid = true, value = entry, ordinal = ( not opts.ignore_filename and filename or '' ) .. ' ' .. entry.text, display = make_display, filename = filename, lnum = entry.lnum, col = entry.col, text = entry.text, start = entry.start, finish = entry.finish, } end end function make_entry.gen_from_buffer(opts) opts = opts or {} local displayer = entry_display.create { separator = " ", items = { { width = opts.bufnr_width }, { width = 4 }, { remaining = true }, }, } local cwd = vim.fn.expand(opts.cwd or vim.fn.getcwd()) local make_display = function(entry) local display_bufname if opts.shorten_path then display_bufname = path.shorten(entry.filename) else display_bufname = entry.filename end return displayer { entry.bufnr, entry.indicator, display_bufname .. ":" .. entry.lnum, } end return function(entry) local bufname = entry.info.name ~= "" and entry.info.name or '[No Name]' -- if bufname is inside the cwd, trim that part of the string bufname = path.normalize(bufname, cwd) local hidden = entry.info.hidden == 1 and 'h' or 'a' local readonly = vim.api.nvim_buf_get_option(entry.bufnr, 'readonly') and '=' or ' ' local changed = entry.info.changed == 1 and '+' or ' ' local indicator = entry.flag .. hidden .. readonly .. changed return { valid = true, value = bufname, ordinal = entry.bufnr .. " : " .. bufname, display = make_display, bufnr = entry.bufnr, filename = bufname, lnum = entry.info.lnum ~= 0 and entry.info.lnum or 1, indicator = indicator, } end end function make_entry.gen_from_treesitter(opts) opts = opts or {} local bufnr = opts.bufnr or vim.api.nvim_get_current_buf() local make_display = function(entry) if opts.show_line then if not tonumber(opts.show_line) then opts.show_line = 30 end local spacing = string.rep(" ", opts.show_line - #entry.ordinal) return entry.ordinal .. spacing .. ": " .. (vim.api.nvim_buf_get_lines( bufnr, entry.lnum - 1, entry.lnum, false )[1] or '') else return entry.ordinal end end return function(entry) local ts_utils = require('nvim-treesitter.ts_utils') local start_row, start_col, end_row, _ = ts_utils.get_node_range(entry.node) local node_text = ts_utils.get_node_text(entry.node)[1] return { valid = true, value = entry.node, ordinal = string.format("%s [%s]", node_text, entry.kind), display = make_display, node_text = node_text, filename = vim.api.nvim_buf_get_name(bufnr), -- need to add one since the previewer substacts one lnum = start_row + 1, col = start_col, text = node_text, start = start_row, finish = end_row } end end function make_entry.gen_from_taglist(_) local delim = string.char(9) return function(line) local entry = {} local tag = (line..delim):match("(.-)" .. delim) entry.valid = tag ~= "" entry.display = tag entry.value = tag entry.ordinal = tag return entry end end function make_entry.gen_from_packages(opts) opts = opts or {} local make_display = function(module_name) local p_path = package.searchpath(module_name, package.path) or "" local display = string.format("%-" .. opts.column_len .. "s : %s", module_name, vim.fn.fnamemodify(p_path, ":~:.")) return display end return function(module_name) local entry = { valid = module_name ~= "", value = module_name, ordinal = module_name, } entry.display = make_display(module_name) return entry end end function make_entry.gen_from_apropos() return function(line) local cmd, _, desc = line:match("^(.*)%s+%((.*)%)%s+%-%s(.*)$") return { value = cmd, ordinal = cmd, display = string.format("%-30s : %s", cmd, desc) } end end function make_entry.gen_from_marks(_) return function(line) local split_value = utils.max_split(line, "%s+", 4) local mark_value = split_value[1] local cursor_position = vim.fn.getpos("'" .. mark_value) return { value = line, ordinal = line, display = line, lnum = cursor_position[2], col = cursor_position[3], start = cursor_position[2], filename = vim.api.nvim_buf_get_name(cursor_position[1]) } end end function make_entry.gen_from_registers(_) local displayer = entry_display.create { separator = ":", items = { { width = 4 }, { remaining = true }, }, } local make_display = function(entry) return displayer { string.format("[%s]", entry.value), entry.content } end return function(entry) return { valid = true, value = entry, ordinal = entry, content = vim.fn.getreg(entry), display = make_display } end end function make_entry.gen_from_highlights() local make_display = function(entry) local display = entry.value return display, { { { 0, #display }, display } } end local preview_command = function(entry, bufnr) local hl = entry.value vim.api.nvim_buf_set_option(bufnr, 'filetype', 'vim') local output = vim.split(vim.fn.execute('hi ' .. hl), '\n') local start = string.find(output[2], 'xxx', 1, true) vim.api.nvim_buf_set_lines(bufnr, 0, -1, true, output) vim.api.nvim_buf_add_highlight(bufnr, -1, hl, 1, start - 1, start + 2) end return function(entry) return { value = entry, display = make_display, ordinal = entry, preview_command = preview_command } end end function make_entry.gen_from_vimoptions() local process_one_opt = function(o) local ok, value_origin local option = { name = "", description = "", current_value = "", default_value = "", value_type = "", set_by_user = false, last_set_from = "", } local is_global = false for _, v in ipairs(o.scope) do if v == "global" then is_global = true end end if not is_global then return end if is_global then option.name = o.full_name ok, option.current_value = pcall(vim.api.nvim_get_option, o.full_name) if not ok then return end local str_funcname = o.short_desc() option.description = assert(loadstring("return " .. str_funcname))() -- if #option.description > opts.desc_col_length then -- opts.desc_col_length = #option.description -- end if o.defaults ~= nil then option.default_value = o.defaults.if_true.vim or o.defaults.if_true.vi end if type(option.default_value) == "function" then option.default_value = "Macro: " .. option.default_value() end option.value_type = (type(option.current_value) == "boolean" and "bool" or type(option.current_value)) if option.current_value ~= option.default_value then option.set_by_user = true value_origin = vim.fn.execute("verbose set " .. o.full_name .. "?") if string.match(value_origin, "Last set from") then -- TODO: parse file and line number as separate items option.last_set_from = value_origin:gsub("^.*Last set from ", "") end end return option end end local displayer = entry_display.create { separator = "│", items = { { width = 25 }, { width = 50 }, { remaining = true }, }, } local make_display = function(entry) return displayer { entry.name, string.format( "[%s] %s", entry.value_type, utils.display_termcodes(tostring(entry.current_value))), entry.description, } end return function(line) local entry = process_one_opt(line) if not entry then return end entry.valid = true entry.display = make_display entry.value = line entry.ordinal = line.full_name -- entry.raw_value = d.raw_value -- entry.last_set_from = d.last_set_from return entry end end function make_entry.gen_from_ctags(opts) opts = opts or {} local cwd = vim.fn.expand(opts.cwd or vim.fn.getcwd()) local current_file = path.normalize(vim.fn.expand('%'), cwd) local display_items = { { width = 30 }, { remaining = true }, } if opts.show_line then table.insert(display_items, 2, { width = 30 }) end local displayer = entry_display.create { separator = " │ ", items = display_items, } local make_display = function(entry) local filename if not opts.hide_filename then if opts.shorten_path then filename = path.shorten(entry.filename) else filename = entry.filename end end local scode if opts.show_line then scode = entry.scode end return displayer { filename, entry.tag, scode, } end return function(line) if line == '' or line:sub(1, 1) == '!' then return nil end local tag, file, scode = string.match(line, '([^\t]+)\t([^\t]+)\t/^\t?(.*)/;"\t+.*') if opts.only_current_file and file ~= current_file then return nil end return { valid = true, ordinal = file .. ': ' .. tag, display = make_display, scode = scode, tag = tag, filename = file, col = 1, lnum = 1, } end end function make_entry.gen_from_autocommands(_) local displayer = entry_display.create { separator = "▏", items = { { width = 14 }, { width = 18 }, { width = 16 }, { remaining = true }, }, } local make_display = function(entry) return displayer { entry.event, entry.group, entry.ft_pattern, entry.command } end -- TODO: <action> dump current filtered items to buffer return function(entry) return { event = entry.event, group = entry.group, ft_pattern = entry.ft_pattern, command = entry.command, value = string.format("+%d %s", entry.source_lnum, entry.source_file), source_file = entry.source_file, source_lnum = entry.source_lnum, -- valid = true, ordinal = entry.event .. " " .. entry.group .. " " .. entry.ft_pattern .. " " .. entry.command, display = make_display, } end end return make_entry
--The room "object" file --Load required files and such local achievement = require("achievement") local entity = require("entity") local resource = require("resource") local event = require("event") local sprite = require("sprite") local transform = require("transform") --Create the module local M = {} --Room information component local infoComponent = function (id, info, pos) --Create a new component to store information in, --then store the info table into it. local component = entity.newComponent(info) component.occupied = 0 component.reservations = 0 component.assigned = 0 component.messy = false if info.cleaningSupplies then component.stock = info.stock end if info.integrity then component.integrity = info.integrity end local check = function (t) if math.ceil(t.floorNum) == pos.floorNum and t.roomNum >= pos.roomNum - 0.5 and t.roomNum <= pos.roomNum - 0.5 + info.width then t.callback(id, info.type) end end local getRooms = function (callback) callback(id, info.type) end local unoccupied = function (callback) if info.type ~= "elevator" and component.occupied == 0 and not component.messy then callback(id, info.type) end end local dirtyRooms = function (callback) if component.occupied == 0 and component.messy then callback(id, info.type) end end local isDirty = function (callback) callback(component.messy) end local setDirty = function (value) component.messy = value if value then event.notify("sprite.play", id, "dirty") else event.notify("sprite.play", id, "clean") end end local checkOccupied = function (callback) callback(component.occupied) end local getStock = function (callback) callback(component.stock) end local setStock = function (stock) component.stock = stock event.notify("sprite.play", id, "stocked" .. stock) if stock == 0 then local snd = resource.get("snd/empty.wav") snd:seek(0) love.audio.play(snd) end end local assign = function (e) component.assigned = component.assigned + 1 end local unassign = function (e) component.assigned = component.assigned - 1 end local checkAssigned = function (callback) callback(component.assigned) end local setReservations = function (r) if component.reservations ~= r then component.reservations = r event.notify("room.reservationChange", 0, { type = info.id, pos = pos, id = id, reservations = r, }) end end local reserve = function (e) setReservations(component.reservations + 1) end local release = function (e) setReservations(component.reservations - 1) end local propagate_res if info.id == "elevator" then propagate_res = function (e) if e.pos.roomNum == pos.roomNum and (e.pos.floorNum == pos.floorNum - 1 or e.pos.floorNum == pos.floorNum + 1) and e.reservations ~= component.reservations and e.type == "elevator" then setReservations(e.reservations) end end event.subscribe("room.reservationChange", 0, propagate_res) end local checkReservations = function (callback) callback(component.reservations) end local enter = function () component.occupied = component.occupied + 1 end local exit = function () if component.occupied > 0 then component.occupied = component.occupied - 1 end end local occupy = function (e) if component.occupied < 1 then component.occupied = component.occupied + 1 e.callback(true) else e.callback(false) end end local depart = function (e) if component.occupied > 0 then component.occupied = component.occupied - 1 end if component.occupied <= 0 then component.occupied = 0 end end local isBroken = function (callback) if info.integrity then callback(component.integrity <= 0) else callback(false) end end local setIntegrity = function (integrity) if integrity ~= component.integrity then if component.integrity <= 0 and integrity > 0 then event.notify("room.fixed", id, { type = info.id, id = id, pos = pos, }) event.notify("room.fixed", 0, { type = info.id, id = id, pos = pos, }) if info.stock ~= nil then event.notify("sprite.play", id, "stocked" .. component.stock) elseif info.id == "elevator" then event.notify("sprite.play", id, "closed") elseif info.id == "spa" then event.notify("sprite.play", id, "idle") end elseif component.integrity > 0 and integrity <= 0 then event.notify("sprite.play", id, "broken") event.notify("room.broken", id, { type = info.id, id = id, pos = pos, }) event.notify("room.broken", 0, { type = info.id, id = id, pos = pos, }) local snd = resource.get("snd/break.wav") snd:seek(0) love.audio.play(snd) end component.integrity = integrity event.notify("room.integrityChange", 0, { type = info.id, id = id, pos = pos, integrity = component.integrity, }) event.notify("room.integrityChange", id, { type = info.id, id = id, pos = pos, integrity = component.integrity, }) end end local use = function () if component.stock then setStock(component.stock - 1) end if info.integrity then setIntegrity(component.integrity - 1) end end local fix = function (t) if info.integrity then setIntegrity(t.integrity) end end local propagate if info.id == "elevator" then propagate = function (e) if e.pos.roomNum == pos.roomNum and (e.pos.floorNum == pos.floorNum - 1 or e.pos.floorNum == pos.floorNum + 1) and e.integrity ~= component.integrity and e.type == "elevator" then setIntegrity(e.integrity) end end event.subscribe("room.integrityChange", 0, propagate) end local function delete () event.unsubscribe("room.check", 0, check) event.unsubscribe("room.all", 0, getRooms) event.unsubscribe("room.unoccupied", 0, unoccupied) event.unsubscribe("room.dirty", 0, dirtyRooms) event.unsubscribe("room.isDirty", id, isDirty) event.unsubscribe("room.setDirty", id, setDirty) event.unsubscribe("room.occupation", id, checkOccupied) event.unsubscribe("room.reservations", id, checkReservations) event.unsubscribe("room.getStock", id, getStock) event.unsubscribe("room.setStock", id, setStock) event.unsubscribe("room.assign", id, assign) event.unsubscribe("room.unassign", id, unassign) event.unsubscribe("room.assigned", id, checkAssigned) event.unsubscribe("room.reserve", id, reserve) event.unsubscribe("room.release", id, release) event.unsubscribe("room.enter", id, enter) event.unsubscribe("room.exit", id, exit) event.unsubscribe("room.occupy", id, occupy) event.unsubscribe("room.depart", id, depart) event.unsubscribe("room.isBroken", id, isBroken) event.unsubscribe("room.use", id, use) event.unsubscribe("room.fix", id, fix) event.unsubscribe("room.integrityChange", 0, propagate) event.unsubscribe("room.reservationChange", 0, propagate_res) event.unsubscribe("delete", id, delete) end event.subscribe("room.check", 0, check) event.subscribe("room.all", 0, getRooms) event.subscribe("room.unoccupied", 0, unoccupied) event.subscribe("room.dirty", 0, dirtyRooms) event.subscribe("room.isDirty", id, isDirty) event.subscribe("room.setDirty", id, setDirty) event.subscribe("room.occupation", id, checkOccupied) event.subscribe("room.reservations", id, checkReservations) event.subscribe("room.getStock", id, getStock) event.subscribe("room.setStock", id, setStock) event.subscribe("room.assign", id, assign) event.subscribe("room.unassign", id, unassign) event.subscribe("room.assigned", id, checkAssigned) event.subscribe("room.reserve", id, reserve) event.subscribe("room.release", id, release) event.subscribe("room.enter", id, enter) event.subscribe("room.exit", id, exit) event.subscribe("room.occupy", id, occupy) event.subscribe("room.depart", id, depart) event.subscribe("room.isBroken", id, isBroken) event.subscribe("room.use", id, use) event.subscribe("room.fix", id, fix) event.subscribe("delete", id, delete) --Return the room info table. return component end local roomInfo = {} --Room constructor M.new = function (state, roomType, pos) --Create an entity and get the id for the new room local roomId = entity.new(state) local roomType = string.lower(roomType) local room = resource.get("scr/rooms/" .. roomType .. ".lua") roomInfo[roomId] = room room.type = roomType local roomWidth = room.width*32 local roomHeight = 32 local prefix = "img/rooms/" .. room.id .. "_" --Add sprite components for _,s in pairs(room.sprites) do entity.addComponent(roomId, sprite.new(roomId, { image = resource.get(prefix .. s.name .. ".png"), width = roomWidth, height = roomHeight, animations = s.animations, playing = s.playing, })) end --Add cleaning sign sprite components if room.dirtyable then entity.addComponent(roomId, sprite.new(roomId, { image = resource.get("img/rooms/cleaning.png"), width = 32, height = 32, originX = -(roomWidth/2), animations = { cleaning = { first = 1, last = 1, speed = 1, }, cleanless = { first = 0, last = 0, speed = 1, }, }, playing = "cleanless", })) end --Add love heart sprite components if room.visitable then entity.addComponent(roomId, sprite.new(roomId, { image = resource.get("img/rooms/love_hearts.png"), width = 32, height = 32, originX = 16 - (roomWidth/2), animations = { hearts = { first = 1, last = 8, speed = 0.1, }, heartless = { first = 0, last = 0, speed = 1, }, }, playing = "heartless", })) end --Add position component entity.addComponent(roomId, transform.new(roomId, pos, {x = 0, y = 0})) --Add info component entity.addComponent(roomId, infoComponent(roomId, room, pos)) -- Update room counts for achievement if gCounts.rooms[roomType] then gCounts.rooms[roomType] = gCounts.rooms[roomType] + 1 else gCounts.rooms[roomType] = 1 end -- Check if achievement triggered if gCounts.rooms["missionary"] and gCounts.rooms["spoon"] and gCounts.rooms["balloon"] and gCounts.rooms["moustache"] and gCounts.rooms["heaven"] and gCounts.rooms["tropical"] and gCounts.rooms["banana"] then achievement.achieve(achievement.SUITES) end -- Cleanup rooms counts when room deleted local onDelete onDelete = function () event.unsubscribe("delete", roomId, onDelete) if gCounts.rooms[roomType] then gCounts.rooms[roomType] = gCounts.rooms[roomType] - 1 if gCounts.rooms[roomType] <= 0 then gCounts.rooms[roomType] = nil end end end event.subscribe("delete", roomId, onDelete) --Function returns the rooms id return roomId end M.all = function () local rooms = {} event.notify("room.all", 0, function (id, type) table.insert(rooms, id) end) return rooms end M.getCount = function (type) return (gCounts.rooms[type] or 0) end M.getInfo = function (id) return roomInfo[id] end M.getPos = function (id) pos = transform.getPos(id) width = M.getInfo(id).width return { roomNum = pos.roomNum + width/2 - 0.5, floorNum = pos.floorNum, } end M.getNearest = function (com, roomNum, floorNum, filter) local rooms = M.all() local nearest = nil local distance = 2^52 -- maximum integer for _,room in ipairs(rooms) do local pos = M.getPos(room) local d if pos.floorNum == floorNum then d = math.abs(pos.roomNum - roomNum) else -- d = dist to elevator + floor dist + dist to room d = math.abs(pos.floorNum - floorNum) + 14 - (roomNum + pos.roomNum) end if d < distance and (filter == nil or filter(com, room)) then nearest = room distance = d end end return nearest end M.isDirty = function (id) local info = M.getInfo(id) local dirty = false if info.dirtyable then event.notify("room.isDirty", id, function (e) dirty = dirty or e end) end return dirty end M.setDirty = function (id, value) local info = M.getInfo(id) if info.dirtyable then event.notify("room.setDirty", id, value) end end M.enter = function (id) event.notify("room.enter", id, nil) end M.exit = function (id) event.notify("room.exit", id, nil) end M.occupation = function (id) local occupation = nil event.notify("room.occupation", id, function (e) occupation = e end) return occupation end M.assign = function (id) event.notify("room.assign", id, nil) end M.unassign = function (id) event.notify("room.unassign", id, nil) end M.assigned = function (id) local assigned = nil event.notify("room.assigned", id, function (e) assigned = e end) return assigned end M.reserve = function (id) if id ~= nil then event.notify("room.reserve", id, nil) end end M.release = function (id) if id ~= nil then event.notify("room.release", id, nil) end end M.reservations = function (id) local reservations = nil event.notify("room.reservations", id, function (e) reservations = e end) return reservations end local heightUp heightUp = function (roomNum, floorNum, cType) local id, type event.notify("room.check", 0, { roomNum = roomNum, floorNum = floorNum, callback = function (_id, _type) id = _id type = _type end, }) if cType ~= type then return 0 end return 1 + heightUp(roomNum, floorNum + 1, cType) end local heightDown heightDown = function (roomNum, floorNum, cType) local id, type event.notify("room.check", 0, { roomNum = roomNum, floorNum = floorNum, callback = function (_id, _type) id = _id type = _type end, }) if cType ~= type then return 0 end return 1 + heightDown(roomNum, floorNum - 1, cType) end M.height = function (id) local info = M.getInfo(id) local type = info.id local pos = M.getPos(id) return (1 + heightUp(pos.roomNum, pos.floorNum + 1, type) + heightDown(pos.roomNum, pos.floorNum - 1, type)) end M.getStock = function (id) local stock = nil event.notify("room.getStock", id, function (e) stock = e end) return stock end M.setStock = function (id, stock) event.notify("room.setStock", id, stock) end M.isBroken = function (id) local broken = false event.notify("room.isBroken", id, function (e) broken = e end) return broken end M.use = function (id) event.notify("room.use", id, nil) end M.fix = function (id, newIntegrity) event.notify("room.fix", id, {integrity = newIntegrity}) end --Return the module return M
CreateClientConVar("zm_preference", "0", true, true, "What is your Zombie Master preference? (0 = Survivor, 1 = Zombie Master)") CreateClientConVar("zm_nopreferredmenu", "0", true, false, "Toggles the preference menu to appear or not.") CreateClientConVar("zm_scrollwheelsensativity", "20", true, false, "How sensitive the mouse scroll is when moving with ZM.") local function ZM_Open_Preferred_Menu(ply) if not IsValid(ply) then return end GAMEMODE:MakePreferredMenu() end concommand.Add("zm_open_preferred_menu", ZM_Open_Preferred_Menu, nil, "Opens the preference menu.") local function ZM_Power_PhysExplode(ply) if (not IsValid(ply)) or (IsValid(ply) and not ply:IsZM()) then return end ply:PrintTranslatedMessage(HUD_PRINTTALK, "enter_explosion_mode") GAMEMODE:SetPlacingShockwave(true) end concommand.Add("zm_power_physexplode", ZM_Power_PhysExplode, nil, "Creates a physics explosion at a chosen location") local function ZM_Power_SpotCreate(ply) if (not IsValid(ply)) or (IsValid(ply) and not ply:IsZM()) then return end ply:PrintTranslatedMessage(HUD_PRINTTALK, "enter_hidden_mode") GAMEMODE:SetPlacingSpotZombie(true) end concommand.Add("zm_power_spotcreate", ZM_Power_SpotCreate, nil, "Creates a Shambler at target location, if it is unseen to players") local function ZM_Power_NightVision(ply) if ply:IsZM() then GAMEMODE.nightVision = not GAMEMODE.nightVision ply:PrintTranslatedMessage(HUD_PRINTTALK, "toggled_nightvision") if not GAMEMODE.nightVision then GAMEMODE.nightVisionCur = 0.5 end end end concommand.Add("zm_power_nightvision", ZM_Power_NightVision, nil, "Enables night vision")
return { tag = 'callbacks', summary = 'Called when restarting.', description = [[ This callback is called when a restart from `lovr.event.restart` is happening. A value can be returned to send it to the next LÖVR instance, available as the `restart` key in the argument table passed to `lovr.load`. Object instances can not be used as the restart value, since they are destroyed as part of the cleanup process. ]], arguments = {}, returns = { { type = '*', name = 'cookie', description = 'The value to send to the next `lovr.load`.' } }, notes = [[ Only nil, booleans, numbers, and strings are supported types for the return value. ]], example = [[ function lovr.restart() return currentLevel:getName() end ]], related = { 'lovr.event.restart', 'lovr.load', 'lovr.quit' } }
local _, addon = ...; -- https://onlinetexttools.com/split-text?input=&split-by-char=false&char=%20&split-by-regex=false&regex=%2F%5Cs%2B%2F&split-by-length=true&length=110&separator=%2C%5Cn&symbol-before-chunk=%22&symbol-after-chunk=%22 table.insert(addon.officialCourses, table.concat({ "!WOP:2!0x49726C82!vIvFWXvvvClLkTBhW(vAvJ25MoWqdKus28rtkIpAtA7lniMMK2sD0P5UV3D3929TV7Z79(YYshLPzK2r0bRvge1IuJ1P", "vgGXrGXQaIvquAv8j4hvWyR9deyGI0rBXzGbp37(2nztFnVX)jtY(E793VZVZ587CUzA3tklMpxq27hT9DBXY75qKe7Sj9P2hC6Z(jnnELz9l2", "2c3(rnno((ESBDHl4XplMZPdJDSPcj21ImJDBHDCsHTYjAFKYFycEEQlnp2lr)fyCh7eJ6r4c4Hexz2GlBOxWYHG5LF7A6xsLoeEFmQRe18QsZ", "bEmNnP(IiwAuFyEoGIEZtFuWHUfQfZDlc6TrQXBUHanHpRFlo(2kouWmhAvzHd0R9bX5iizwc6tZtPoWb5yxHdZclPmxKKPFMK5PEM6xfEuozz", "ThCjzdMEjr407Q(R5D)Ppiic762l4p)pBWLoJGz0EWhmrWLLiyMjcMLkOcsutWSddIKbxEWve8HQjyo1emxfvcMN3IxlrIyUHa1TVixbkahhnW", "fG3PENEp5zg4hb4TT1T5d9D(6XIxlrGxYnZ8ryobLX31fJCjeB0AioO(9fzryxB0ADO2QahLbigqKjXHJpYV(1(pVoWHXULDC(z)6XYHwJGdn1", "nZpLdbTv)8EAmRqajRaubikP9zPcKN6qQMb7RUh(5FwFGbByS76ql5oILbTfbd2060qZz(a6kWYsDCGFblraOPiYceIlQOsQ0VqfMG6JZsHt5u", "SKYbYKVGuH)vt056STEFIPBAm26f37dS3BmwI2EeeTHEKcqNesegLIkv1iyugDkYMviSofyNWJnjz6kE66EIp(6nn(tVHX5(JT(gXI(YJa9v1l", "H4HKC8WehQBge2Hb)uPxwuzrubOhxGkaAxPCP6vydd1Uv6xevXPt812XV5lVpQPXlE2NE0)9bjXYPoIGtF4bvXlTunsAQl2zYTMJzA8Q9N8Wh7", "7DetJN7(p1Sg6AhjwK6mcK6zaPk7RCdaOyG)qgiWzCxcVbvTXvxDxewGY7BLf6zOzYkv)PhtiOqHEvu7F(8BCRVO1Umn(dl4oUQZ)GR5ItTrcT", "(AkcUTFTkWCjio5Z7RuAKhNyrfkZlDnlf8aZSSeBKaSoTpuFsKCcuFpElw5IADZoM6IeS8ee5wH8Dyq0GkYDNy7jkVY2eke1QpPq4RxuFKkBSW", "Z1bltZ45RkYFLUFo0JC1VQPXV)NS79)uFX3k(iV5iI8RCDQUHkuQu92ub7P)B)GDp)n0HPXrEM2E)T)yBnEyJYNwo446Lw51kaNbnKkdB9FLHR", "Cnstj8IilEryoMZ4pKue6gqAYlbnuusTl32iYrv9sH2U(EtY5fcJtTGwV7Tu7TaL0B8WZ7U)QVz8Hru2)lAI5YOCybKoz37H9j47W043oTL8dN", ")bUP4rkktERlUG5cfnLNWM1pZuiCtq00dlMc95etdVZJD5lX04fU3T(2NzPtX0XYSoYbddoX6OY2mcmKQWLJMMBfLYxwXxqpTwOCKd3uiIOPkM", "E8J8bsD4RF)Mghn1R9Z(DFJZgptJAYW3QIdGY(xQDNusLAUMfhCEkXfSNI4006HzfikllMQGdusNj4UvjI1ZaLtk11GoG1NGAozASEyjm9mtPD", "g0NemkfecA1JHoUZ39sFO9CqtJ)YbE5EUQ7)NhFSg1COBO6Aj98WueGVqwbLhI1IOuCQnujHtbgcObHiQBc2gnGfMxfFo2dD77j5)6ba(89h7O", "pv9TfpFIAguDAzUS(gM2NipQgZUgAhp(1xRPXl1XxzT1CZNmEmJAAuVW0OILtxLM8gcSAwCd6(IqdycSQqMYdS0DC(cvopY1uow635z)mh6Hnn", "E5V0q)3h5J8lJLDjJAEKyIvJso1khifelSA7ifHGn7hg88ulEMcwYohnCpIHPKcHn42LwkCCdQWcSj81ViEwQ6SCl((E0)8Ndw26A35DD(ZofR", "wuokIy2c)Mzi1LdQ6GLVvTRBEndjVdS(RzM5(2XFWrn94gl1xkGJx1Ym(Qb62Njh54sJx1rzrDcS6yD438C3z9BZ04VEO1(UnK(jJNsrnj4g6R", "Y(cGIMJuSUQVhqMY3dqrfTJDK8b8Z(hT(f2)JUVVj8l1EN52(79mXZNOMxuR6IqHW5GfHWDHODIt)2l8Ew8WMg)9ZXLDU5DgpAv85bOaa1O9j)", ")kHmL7xCYm)Q9EFJDayc9AEP3R3pvlXtO2JGq10fSAnhdB7RSzZJTvBzv3p2MiS4up1Ds9od4aWLvDBaFz5bpdqDGnHYZG0zxA)aOi6cUnzIe9", "VHBA1dSIeqHEANIQMWLUYsfBW(I6ZXsTKivz5R(E62z3kVm46WkaR6c7kUAanH62aBIXGv)WUflGlkQprIb7PpaGUj5bMy67kHxt32dRNMonCI", "2OLgQ1flV7QDP5lECL3nqJcC4GRFjuBVRS1oTtHjD0AJTJ7mzJT2ANPASJojT1OvtT1slDIBj9YtL0BoQ6L8mBkmZ12gljEZTPwUUMx(1LSzy7", "5v0YYxrZjhjprIHNHB3BHwzXCSfWSvBtLqC1L()1XL49XQ8aXMazR0hVsXkTK0HjjgLk6k8Ffs2rbSstT8DKfxLjS7BWS9w0KYait9k0IrlWkO", "0kqt7VZL10YAJRLyg3Br9GDbtoS6Qvnoi1klZ1Mt9f)Vp" }))
--[[ © 2018 Thriving Ventures AB do not share, re-distribute or modify without permission of its author ([email protected]). ]] local plugin = plugin plugin:IncludeFile("shared.lua", SERVERGUARD.STATE.CLIENT) plugin:IncludeFile("sh_commands.lua", SERVERGUARD.STATE.CLIENT) plugin:IncludeFile("cl_panel.lua", SERVERGUARD.STATE.CLIENT) plugin:IncludeFile("cl_settings.lua", SERVERGUARD.STATE.CLIENT) serverguard.netstream.Hook("sgStartReport", function(data) local menu = vgui.Create("tiger.panel") menu:SetTitle("Write a report") menu:SetSize(580, 440) menu:Center() menu:MakePopup() menu:DockPadding(24, 24, 24, 48) local entry = menu:Add("DTextEntry") entry:SetMultiline(true) entry:Dock(FILL) entry:SetSkin("serverguard") local complete = menu:Add("tiger.button") complete:SetPos(4, 4) complete:SetText("Complete") complete:SizeToContents() function complete:DoClick() serverguard.SetMenuStay(false) local text = entry:GetValue() if (text ~= "") then serverguard.netstream.Start("sgSendReport", text) end menu:Remove() end local cancel = menu:Add("tiger.button") cancel:SetPos(4, 4) cancel:SetText("Cancel") cancel:SizeToContents() function cancel:DoClick() serverguard.SetMenuStay(false) menu:Remove() end function menu:PerformLayout() local w, h = self:GetSize() complete:SetPos(w - (complete:GetWide() + 24), h - (complete:GetTall() + 14)) cancel:SetPos(0, h - (cancel:GetTall() + 14)) cancel:MoveLeftOf(complete, 14) end end)
local ipairs = ipairs local ngx = ngx local string_helpers = require "trustbuilder-gateway.helpers.string" local gw_conf = require "trustbuilder-gateway.configuration" local authentication = require "trustbuilder-gateway.authentication" local ngx_exit = ngx.exit local conf, conf_err = gw_conf:new() if not conf then ngx.log(ngx.ERR, conf_err) ngx_exit(500) end local function is_allowed_contenttype(headerval) local allowed_types = { "text/html", "text/xml", "text/plain", "application/json", "application/soap", "application/xml" } for _, val in ipairs(allowed_types) do if string_helpers.starts(headerval, val) then return true end end return nil end local function validate_authentication_request() ngx.log(ngx.DEBUG, "Validating Authentication Interface") if ngx.status >= 200 and ngx.status < 300 then ngx.log(ngx.DEBUG, "HTTP-Status: " .. ngx.status .. " // Checking Content-Type") if ngx.header["content-type"] and is_allowed_contenttype(ngx.header["content-type"]) then ngx.log(ngx.DEBUG, "Content-Type valid") return true end elseif ngx.status >= 300 and ngx.status < 400 then ngx.log(ngx.DEBUG, "redirect status found: " .. ngx.status) return true else ngx.log(ngx.DEBUG, "No valid HTTP status found for authentication_interface") end return nil end local function clear_auth_headers() ngx.header["X-TB-AUTH"] = nil ngx.header["X-TB-SESSION"] = nil ngx.header["X-TB-EXPIRES-IN"] = nil ngx.header["X-TB-CREDENTIAL-TTL"] = nil ngx.header["X-TB-CREDENTIAL-ID"] = nil ngx.header["X-TB-OAUTH-SCOPES"] = nil end local function authentication_interface() if not validate_authentication_request() then clear_auth_headers() ngx.log(ngx.DEBUG, "Ignoring Authentication Interface, Not a valid request") return end ngx.log(ngx.DEBUG, "Start Authentication flow") local sessionId = ngx.ctx.sessionId or authentication.getSessionCookieValue() local sessionIdHeader = ngx.header["X-TB-SESSION"] if not sessionId then if not sessionIdHeader then authentication.generateSessionCookie() else sessionId = sessionIdHeader end end local auth_hdr = ngx.header["X-TB-AUTH"] local existing_cred = ngx.header["X-TB-CREDENTIAL-ID"] local session_expire = ngx.header["X-TB-EXPIRES-IN"] local credential_expire = ngx.header["X-TB-CREDENTIAL-TTL"] local logout_hdr = ngx.header["X-TB-LOGOUT"] local ssl_session_id = ngx.var.ssl_session_id local opts = { credentialIndex = existing_cred, sessionTtl = session_expire, credentialTtl = credential_expire, sslSessionId = ssl_session_id } if ngx.header["X-TB-CREDENTIAL-ID"] then ngx.log(ngx.DEBUG, "Existing Credential : " .. ngx.header["X-TB-CREDENTIAL-ID"]) end if auth_hdr and not logout_hdr then ngx.log(ngx.DEBUG, "Starting Authentication phase with X-TB-AUTH") authentication.saveSessionInCookie(auth_hdr, opts); end if logout_hdr then ngx.log(ngx.DEBUG, "Removing Credential index") if logout_hdr == ngx.ctx.principalSessionId then ngx.timer.at(0,authentication.removeSession, conf, ngx.ctx.session, ngx.ctx.sessionId) end end clear_auth_headers() end return authentication_interface
return { { effect_list = { { type = "BattleBuffCount", trigger = { "onTorpedoWeaponFire" }, arg_list = { countTarget = 4, countType = 14680 } }, { type = "BattleBuffCastSkill", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, target = "TargetSelf", skill_id = 14680, countType = 14680 } }, { type = "BattleBuffCancelBuff", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, countType = 14680 } } } }, { effect_list = { { type = "BattleBuffCount", trigger = { "onTorpedoWeaponFire" }, arg_list = { countTarget = 4, countType = 14680 } }, { type = "BattleBuffCastSkill", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, target = "TargetSelf", skill_id = 14680, countType = 14680 } }, { type = "BattleBuffCancelBuff", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, countType = 14680 } } } }, { effect_list = { { type = "BattleBuffCount", trigger = { "onTorpedoWeaponFire" }, arg_list = { countTarget = 4, countType = 14680 } }, { type = "BattleBuffCastSkill", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, target = "TargetSelf", skill_id = 14680, countType = 14680 } }, { type = "BattleBuffCancelBuff", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, countType = 14680 } } } }, { effect_list = { { type = "BattleBuffCount", trigger = { "onTorpedoWeaponFire" }, arg_list = { countTarget = 4, countType = 14680 } }, { type = "BattleBuffCastSkill", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, target = "TargetSelf", skill_id = 14680, countType = 14680 } }, { type = "BattleBuffCancelBuff", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, countType = 14680 } } } }, { effect_list = { { type = "BattleBuffCount", trigger = { "onTorpedoWeaponFire" }, arg_list = { countTarget = 4, countType = 14680 } }, { type = "BattleBuffCastSkill", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, target = "TargetSelf", skill_id = 14680, countType = 14680 } }, { type = "BattleBuffCancelBuff", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, countType = 14680 } } } }, { effect_list = { { type = "BattleBuffCount", trigger = { "onTorpedoWeaponFire" }, arg_list = { countTarget = 4, countType = 14680 } }, { type = "BattleBuffCastSkill", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, target = "TargetSelf", skill_id = 14680, countType = 14680 } }, { type = "BattleBuffCancelBuff", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, countType = 14680 } } } }, { effect_list = { { type = "BattleBuffCount", trigger = { "onTorpedoWeaponFire" }, arg_list = { countTarget = 4, countType = 14680 } }, { type = "BattleBuffCastSkill", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, target = "TargetSelf", skill_id = 14680, countType = 14680 } }, { type = "BattleBuffCancelBuff", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, countType = 14680 } } } }, { effect_list = { { type = "BattleBuffCount", trigger = { "onTorpedoWeaponFire" }, arg_list = { countTarget = 4, countType = 14680 } }, { type = "BattleBuffCastSkill", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, target = "TargetSelf", skill_id = 14680, countType = 14680 } }, { type = "BattleBuffCancelBuff", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, countType = 14680 } } } }, { effect_list = { { type = "BattleBuffCount", trigger = { "onTorpedoWeaponFire" }, arg_list = { countTarget = 4, countType = 14680 } }, { type = "BattleBuffCastSkill", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, target = "TargetSelf", skill_id = 14680, countType = 14680 } }, { type = "BattleBuffCancelBuff", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, countType = 14680 } } } }, { effect_list = { { type = "BattleBuffCount", trigger = { "onTorpedoWeaponFire" }, arg_list = { countTarget = 4, countType = 14680 } }, { type = "BattleBuffCastSkill", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, target = "TargetSelf", skill_id = 14680, countType = 14680 } }, { type = "BattleBuffCancelBuff", trigger = { "onBattleBuffCount" }, arg_list = { count = 1, countType = 14680 } } } }, time = 0, name = "回血", init_effect = "jinengchufared", color = "blue", picture = "", desc = "鱼雷计数", stack = 1, id = 14681, icon = 14680, last_effect = "", blink = { 1, 0, 0, 0.3, 0.3 }, effect_list = {} }
local Color3 = import("../types/Color3") local Font = import("../Enum/Font") local GuiButton = import("./GuiButton") local InstanceProperty = import("../InstanceProperty") local TextButton = GuiButton:extend("TextButton", { creatable = true, }) TextButton.properties.Font = InstanceProperty.enum(Font, { getDefault = function() return Font.Legacy end, }) TextButton.properties.Text = InstanceProperty.typed("string", { getDefault = function() return "Button" end, }) TextButton.properties.TextColor3 = InstanceProperty.typed("Color3", { getDefault = function() return Color3.new(27, 42, 53) end, }) TextButton.properties.TextSize = InstanceProperty.typed("number", { getDefault = function() return 14 end, }) return TextButton
PLUGIN.name = "Armour" PLUGIN.author = "Zadkiel" PLUGIN.desc = "Armour addon"
function DrawBrowseScreen() love.graphics.clear(unpack(colors.black)) love.graphics.setColor(0, 0, 0, 100) love.graphics.rectangle("fill", 0, 0, love.graphics.getWidth(), love.graphics.getHeight()) local blackImage = love.graphics.newImage(settings.black_screen_path) local blackImageScale = 2*dimensions.window_width/1920 * 2 local jorytrialImage = love.graphics.newImage(settings.court_path) local jorytrialImageScale = 2*dimensions.window_width/1920 * 2.5 local posttrialImage = love.graphics.newImage(settings.lobby_path) local posttrialImageScale = 2*dimensions.window_width/1920 * 2.5 local backW = (dimensions.window_width * 1/5) local backX = (dimensions.window_width * 1/6 - backW/2) local backY = blackImage:getHeight()*blackImageScale + 150 local backH = 60 local jorytrialW = (dimensions.window_width * 1/3.75) local jorytrialX = (dimensions.window_width * 3/6 - jorytrialW/2) local jorytrialY = blackImage:getHeight()*blackImageScale + 150 local jorytrialH = 60 local posttrialW = (dimensions.window_width * 1/3.75) local posttrialX = (dimensions.window_width * 5/6 - posttrialW/2) local posttrialY = blackImage:getHeight()*blackImageScale + 150 local posttrialH = 60 local dx = 8 local dy = 8 if TitleSelection == "Jory's Trial" then love.graphics.setColor(0.44,0.56,0.89) love.graphics.draw( jorytrialImage, dimensions.window_width/2 - (jorytrialImage:getWidth() * jorytrialImageScale)/2 + 20, 0, 0, jorytrialImageScale, jorytrialImageScale ) love.graphics.rectangle("fill", jorytrialX-dx, jorytrialY-dy, jorytrialW+2*dx, jorytrialH+2*dy) elseif TitleSelection == "Post-Trial" then love.graphics.setColor(0.44,0.56,0.89) love.graphics.draw( posttrialImage, dimensions.window_width/2 - (posttrialImage:getWidth() * posttrialImageScale)/2 + 20, 0, 0, posttrialImageScale, posttrialImageScale ) love.graphics.rectangle("fill", posttrialX-dx, posttrialY-dy, posttrialW+2*dx, posttrialH+2*dy) else love.graphics.setColor(0.44,0.56,0.89) love.graphics.draw( blackImage, dimensions.window_width/2 - (blackImage:getWidth() * blackImageScale)/2 + 20, 0, 0, blackImageScale, blackImageScale ) love.graphics.rectangle("fill", backX-dx, backY-dy, backW+2*dx, backH+2*dy) end love.graphics.setColor(222, 0, 0) love.graphics.rectangle("fill", backX, backY, backW, backH) love.graphics.setColor(0.3,0.3,0.3) love.graphics.rectangle("fill", jorytrialX, jorytrialY, jorytrialW, jorytrialH) love.graphics.setColor(0.3,0.3,0.3) love.graphics.rectangle("fill", posttrialX, posttrialY, posttrialW, posttrialH) love.graphics.setColor(1,1,1) local textScale = 3 local backText = love.graphics.newText(GameFont, "Back") love.graphics.draw( backText, backX + backW/2-(backText:getWidth() * textScale)/2, backY + backH/2-(backText:getHeight() * textScale)/2, 0, textScale, textScale ) local jorytrialText = love.graphics.newText(GameFont, "Jory's Trial") love.graphics.draw( jorytrialText, jorytrialX + jorytrialW/2-(jorytrialText:getWidth() * textScale)/2, jorytrialY + jorytrialH/2-(jorytrialText:getHeight() * textScale)/2, 0, textScale, textScale ) local posttrialText = love.graphics.newText(GameFont, "Post-Trial") love.graphics.draw( posttrialText, posttrialX + posttrialW/2-(posttrialText:getWidth() * textScale)/2, posttrialY + posttrialH/2-(posttrialText:getHeight() * textScale)/2, 0, textScale, textScale ) return self end browseSceneSelections = {} browseSceneSelections[0] = "Back"; browseSceneSelections[1] = "Jory's Trial"; browseSceneSelections[2] = "Post-Trial"; TitleSelection = "Back"; SelectionIndex = 0; blip2 = love.audio.newSource("sounds/selectblip2.wav", "static") jingle = love.audio.newSource("sounds/selectjingle.wav", "static") blip2:setVolume(settings.sfx_volume / 100 / 2); jingle:setVolume(settings.sfx_volume / 100 / 2); BrowseScreenConfig = { displayed = false; onKeyPressed = function(key) if key == controls.start_button then love.graphics.clear(0,0,0); if TitleSelection == "Back" then blip2:play() screens.title.displayed = true; DrawTitleScreen(); screens.browsescenes.displayed = false; SelectionIndex = 1; TitleSelection = "Case Select"; elseif TitleSelection == "Jory's Trial" then blip2:play() screens.jorytrial.displayed = true; DrawJoryTrialScreen(); screens.browsescenes.displayed = false; SelectionIndexX = 0; SelectionIndexY = 0; elseif TitleSelection == "Post-Trial" then jingle:play() Episode = NewEpisode(settings.posttrial_path) Episode:begin() CurrentScene.penalties = 5; screens.browsescenes.displayed = false; end elseif key == controls.press_right then blip2:play() SelectionIndex = SelectionIndex + 1 if (SelectionIndex > 2) then SelectionIndex = 0; end TitleSelection = browseSceneSelections[SelectionIndex] elseif key == controls.press_left then blip2:play() SelectionIndex = SelectionIndex - 1 if (SelectionIndex < 0) then SelectionIndex = 2; end TitleSelection = browseSceneSelections[SelectionIndex] end end; onDisplay = function() screens.browsescenes.displayed = true screens.pause.displayed = false screens.courtRecords.displayed = false screens.jorytrial.displayed = false screens.options.displayed = false screens.title.displayed = false screens.volume.displayed = false TitleSelection = "Back"; SelectionIndex = 0; end; draw = function() if screens.browsescenes.displayed == true then DrawBrowseScreen() blip2:setVolume(settings.sfx_volume / 100 / 2) jingle:setVolume(settings.sfx_volume / 100 / 2) end end }
local ffi = require("ffi") local require("ovsdb_command_common") ffi.cdef[[ struct vsctl_context { /* Read-only. */ int argc; char **argv; struct shash options; /* Modifiable state. */ struct ds output; struct table *table; struct ovsdb_idl *idl; struct ovsdb_idl_txn *txn; struct ovsdb_symbol_table *symtab; const struct ovsrec_open_vswitch *ovs; bool verified_ports; /* A cache of the contents of the database. * * A command that needs to use any of this information must first call * vsctl_context_populate_cache(). A command that changes anything that * could invalidate the cache must either call * vsctl_context_invalidate_cache() or manually update the cache to * maintain its correctness. */ bool cache_valid; struct shash bridges; /* Maps from bridge name to struct vsctl_bridge. */ struct shash ports; /* Maps from port name to struct vsctl_port. */ struct shash ifaces; /* Maps from port name to struct vsctl_iface. */ /* A command may set this member to true if some prerequisite is not met * and the caller should wait for something to change and then retry. */ bool try_again; }; ]]
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ========== PlaceObj('XTemplate', { group = "InGame", id = "Milestones", PlaceObj('XTemplateTemplate', { '__template', "OverlayDlg", 'MaxWidth', 800, }, { PlaceObj('XTemplateWindow', { '__class', "XLabel", 'Dock', "top", 'HAlign', "right", 'TextFont', "PGModTitle", 'TextColor', RGBA(119, 198, 255, 255), 'Translate', true, 'Text', T{433085262825, --[[XTemplate Milestones Text]] "MILESTONES"}, }), PlaceObj('XTemplateWindow', { '__class', "XFrame", 'Margins', box(-80, 6, -155, -100), 'Dock', "top", 'VAlign', "top", 'Image', "UI/Common/bm_pad_small.tga", 'FrameBox', box(170, 0, 165, 0), 'SqueezeY', false, }), PlaceObj('XTemplateWindow', { '__context', function (parent, context) return {rating = CalcChallengeRating()} end, '__class', "XText", 'Dock', "top", 'HAlign', "right", 'TextFont', "PGModAuthorDate", 'TextColor', RGBA(119, 198, 255, 255), 'RolloverTextColor', RGBA(119, 198, 255, 255), 'Translate', true, 'Text', T{700087753666, --[[XTemplate Milestones Text]] "DIFFICULTY BONUS <white><percent(rating)>"}, }), PlaceObj('XTemplateWindow', { '__context', function (parent, context) return Presets.Milestone.Default end, '__class', "XText", 'Dock', "top", 'HAlign', "right", 'TextFont', "PGModAuthorDate", 'TextColor', RGBA(119, 198, 255, 255), 'RolloverTextColor', RGBA(119, 198, 255, 255), 'Translate', true, 'Text', T{841674688207, --[[XTemplate Milestones Text]] "SCORE <white><sum(0, 'ChallengeScore')>"}, }), PlaceObj('XTemplateAction', { 'ActionId', "close", 'ActionName', T{4523, --[[XTemplate Milestones ActionName]] "CLOSE"}, 'ActionToolbar', "ActionBar", 'ActionShortcut', "Escape", 'ActionGamepad', "ButtonB", 'OnActionEffect', "close", }), PlaceObj('XTemplateWindow', { '__class', "XList", 'Id', "idList", 'Margins', box(0, 10, 0, 10), 'BorderWidth', 0, 'LayoutVSpacing', 12, 'Clip', false, 'Background', RGBA(0, 0, 0, 0), 'FocusedBackground', RGBA(0, 0, 0, 0), 'VScroll', "idScroll", 'ShowPartialItems', false, 'MouseScroll', false, }, { PlaceObj('XTemplateCode', { 'run', function (self, parent, context) ForEachPreset("Milestone", function(preset, group, self, parent) self:EvalChildren(parent, preset) end, self, parent) end, }, { PlaceObj('XTemplateWindow', { 'comment', "milestone item", 'IdNode', true, 'RolloverZoom', 1050, }, { PlaceObj('XTemplateWindow', { '__class', "XImage", 'Dock', "left", 'Image', "UI/Common/mission_yes.tga", }, { PlaceObj('XTemplateCode', { 'run', function (self, parent, context) local sol = context:CompleteSol() if sol == false then parent:SetImage("UI/Common/milestone_no.tga") end parent:SetVisible(sol ~= nil) end, }), }), PlaceObj('XTemplateWindow', { '__class', "XLabel", 'Margins', box(6, 0, 0, 0), 'MinWidth', 200, 'TextFont', "PGModAuthorDate", 'TextColor', RGBA(221, 215, 170, 255), 'Translate', true, 'Text', T{611518845262, --[[XTemplate Milestones Text]] "<CompleteText>"}, }), PlaceObj('XTemplateWindow', { 'Dock', "right", 'MinWidth', 120, }, { PlaceObj('XTemplateWindow', { '__class', "XLabel", 'HAlign', "right", 'TextFont', "PGModAuthorDate", 'TextColor', RGBA(221, 215, 170, 255), 'Translate', true, 'Text', T{940959765296, --[[XTemplate Milestones Text]] "<def(ChallengeScore,'')>"}, }), }), }), }), }), PlaceObj('XTemplateWindow', { '__class', "XPageScroll", 'Id', "idScroll", 'Dock', "bottom", 'Target', "idList", }), }), })
package("cglm") set_homepage("https://github.com/recp/cglm") set_description("Highly optimized 2D|3D math library, also known as OpenGL Mathematics (glm) for `C`. cglm provides lot of utils to help math operations to be fast and quick to write.") set_urls("https://github.com/recp/cglm/archive/v$(version).tar.gz") add_versions("0.8.3", "3a3f935f9f2ed5a8cb6337e421bf6f3a699a72d8cfe26fde1bbb8fde5c1c8aaf") add_deps("cmake") on_install(function (package) import("package.tools.cmake").install(package, {"-Dxxx=ON"}) end) on_test(function (package) assert(package:has_cfuncs("glm_vec2", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_copy", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_zero", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_one", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_dot", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_cross", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_norm2", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_norm", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_add", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_adds", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_sub", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_subs", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_mul", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_scale", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_scale_as", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_div", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_divs", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_addadd", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_subadd", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_muladd", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_muladds", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_maxadd", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_minadd", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_negate", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_negate_to", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_normalize", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_normalize_to", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_rotate", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_distance2", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_distance", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_maxv", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_minv", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_clamp", {includes = "cglm/cglm.h"})) assert(package:has_cfuncs("glm_vec2_lerp", {includes = "cglm/cglm.h"})) end)
--[[ File NAME: DocTitanPlugin.lua DESC: This file contains documentation of Titan to assist a developer. :DESC --]] --[[ API NAME: Titan API overview for developers DESC: Updated Dec 2011 This documentation is intended for addon developers that wish to create a Titan plugin. Terms: Throughout the documentation and naming of routines and variables there are some terms that are used interchangably. - Plugin / button / frame - Character / player / toon - Plugin ID / plugin name Over time we desire to consolidate terms but it may take time. Plugin Types: Titan allows two types of plugins: - Titan native - LDB enabled addons See http://code.google.com/p/titanpanel/downloads/list to download examples. Titan Plugin Recognition: Titan native plugins must use one of the Titan templates found in TitanPanelTemplates.xml. LDB Plugin Recognition: LDB enabled addons only need to adhere to the LDB (Lib Data Broker) 1.1 spec. Titan uses the callback feature ("LibDataBroker_DataObjectCreated") to recognize LDB addons. At player_login Titan registers the call back. It then loops through the LDB objects using :DataObjectIterator(). When any LDB object is found Titan will attempt to create a Titan native plugin for display. Registration Steps: Titan attempts to register each plugin it recognizes. Registration for Titan is a two step process. Step one: On the creation of a Titan plugin frame place the plugin in a holding table until the "Player Entering World" (PEW) event is fired. Step two: Once Titan is initialized it will take each plugin from this table and attempt to register it for display. The attempt uses a protected call (pcall) to protect the Titan core and (hopefully) prevents Titan from crashing. Registration Attempts: Each plugin attempt is placed in an 'attempted' table along with the results of the registration. This attempted table is accessible to the user in the Titan "Attempted" options. The developer can see what happened and users can report issues using that data. Registry Table of Each Plugin: Each plugin must contain a table called "registry". self.registry = {} The registry table must have a unique id across all Titan plugins that are loaded. self.registry = {id = "MyPlugin"} This is all that is required for successful registration. It will register but will be a rather dull plugin. It is strongly recommended that you download the TitanStarter plugin example(see the link above). The example explains all the elements of the registry that Titan uses. The example is based on TitanBags so you can play with the code and compare it to a supported plugin. Titan API: The functions that Titan offers to the plugin developer are in a separate document. Within the Titan files you can recognize an API routine by the comment just before the function declaration. The comment block will have "API" as part of the starting block. :DESC --]]
if ( SERVER ) then AddCSLuaFile( "shared.lua" ) SWEP.BackHolster = false; end if ( CLIENT ) then SWEP.PrintName = "Service Pistol" SWEP.Author = "Counter-Strike" SWEP.Slot = 3 SWEP.SlotPos = 1 SWEP.IconLetter = "u" end SWEP.HoldType = "pistol"; SWEP.HoldTypeNorm = "normal"; SWEP.Base = "weapon_perp_base" SWEP.Category = "Counter-Strike" SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.ViewModel = "models/weapons/v_pist_fiveseven.mdl" SWEP.WorldModel = "models/weapons/w_pist_fiveseven.mdl" SWEP.Weight = 5 SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false SWEP.AnimPrefix = "rpg" SWEP.Primary.Sound = Sound( "Weapon_FiveSeven.Single" ) SWEP.Primary.Recoil = 1.2 SWEP.Primary.Damage = 18 SWEP.Primary.NumShots = 1 SWEP.Primary.Cone = 0.02 SWEP.Primary.ClipSize = 14 SWEP.Primary.Delay = 0.05 SWEP.Primary.DefaultClip = 14 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "pistol" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" SWEP.IronSightsPos = Vector (4.5198, -2.9805, 3.3317) SWEP.IronSightsAng = Vector (0, 0, 0) SWEP.NormalPos = Vector( 0, 0, 3 ) SWEP.NormalAng = Vector( -20, 0, 0 ); SWEP.MaxPenetration = PENETRATION_PISTOL;
---@meta ---@class cc.EaseRateAction :cc.ActionEase local EaseRateAction={ } cc.EaseRateAction=EaseRateAction ---* brief Set the rate value for the ease rate action.<br> ---* param rate The value will be set. ---@param rate float ---@return self function EaseRateAction:setRate (rate) end ---* brief Initializes the action with the inner action and the rate parameter.<br> ---* param pAction The pointer of the inner action.<br> ---* param fRate The value of the rate parameter.<br> ---* return Return true when the initialization success, otherwise return false. ---@param pAction cc.ActionInterval ---@param fRate float ---@return boolean function EaseRateAction:initWithAction (pAction,fRate) end ---* brief Get the rate value of the ease rate action.<br> ---* return Return the rate value of the ease rate action. ---@return float function EaseRateAction:getRate () end ---* ---@param action cc.ActionInterval ---@param rate float ---@return self function EaseRateAction:create (action,rate) end
local hijack = {} function hijack.load(libName, methodName, override) if (not hijack) then return nil, "no hijack" end if (not hijack[libName]) then local lib, reason = require(libName); if (not lib) then return nil, reason end hijack[libName] = {} hijack[libName].lib = lib hijack[libName].originals = {}; end -- safeguard original if not yet set if (not hijack[libName].originals[methodName]) then -- if the lib doesn't know about this method, error out now if (not hijack[libName].lib[methodName] or type(hijack[libName].lib[methodName]) ~= "function") then return nil, libName .. "." .. methodName .. " does not exist or is not a function"; end hijack[libName].originals[methodName] = hijack[libName].lib[methodName]; end local original = hijack[libName].originals[methodName]; local redirect = function(...) return override(original, ...) end hijack[libName].lib[methodName] = redirect; return hijack[libName].lib; end function hijack.unload(libName, methodName) if (not hijack or not hijack[libName] or not hijack[libName].lib or not hijack[libName].originals[methodName]) then return false, libName .. "." .. methodName .. " was not hijacked" end hijack[libName].lib[methodName] = hijack[libName].originals[methodName]; hijack[libName].originals[methodName] = nil; -- allow for override again end return hijack
-- ===================================================================== -- -- nvim-telescope.lua - -- -- Created by liubang on 2020/12/13 13:38 -- Last Modified: 2020/12/13 13:38 -- -- ===================================================================== local actions = require 'telescope.actions' local telescope = require 'telescope' local themes = require 'telescope.themes' telescope.setup { defaults = themes.get_dropdown { file_ignore_patterns = { '.git/*' }, prompt_prefix = '  ', path_display = { 'absolute' }, winblend = 0, mappings = { i = { ['<C-x>'] = false, ['<C-u>'] = false, ['<C-d>'] = false, ['<C-c>'] = actions.close, ['<C-s>'] = actions.select_horizontal, ['<C-v>'] = actions.select_vertical, ['<C-/>'] = 'which_key', }, n = { ['<esc>'] = actions.close }, }, }, pickers = { find_files = { follow = true, }, buffers = { sort_mru = true, }, lsp_code_actions = themes.get_cursor(), lsp_range_code_actions = themes.get_cursor(), }, extensions = { fzf = { fuzzy = true, -- false will only do exact matching override_generic_sorter = true, -- override the generic sorter override_file_sorter = true, -- override the file sorter case_mode = 'smart_case', -- or "ignore_case" or "respect_case" }, project = { hidden_files = true, }, ['ui-select'] = { require('telescope.themes').get_dropdown { -- even more opts }, }, }, } telescope.load_extension 'fzf' -- telescope.load_extension 'dap' telescope.load_extension 'bazel' telescope.load_extension 'tasks' telescope.load_extension 'project' telescope.load_extension 'ui-select'
----------------------------------------------------------------------------- --- --- --- Under Migration to CorePackages --- --- --- --- Please put your changes in AppTempCommon. --- --- NOTE: You will have to rebuild for changes to kick in --- ----------------------------------------------------------------------------- local lastId = 0 return function() lastId = lastId + 1 return tostring(lastId) end
local map = require('core.utils').map -- DEFAULT MAP -- ----------- vim.g.mapleader = ' ' -- Disable SPC key -- Note: `which-key` already implemented this -- map('n', '<Space>', '<Nop>') map('n', '<TAB>', '<Cmd>bn<CR>') map('n', '<S-TAB>', '<Cmd>bp<CR>') -- Break lines in normmal mode map('n', 'o', 'o<ESC>', { noremap = false }) map('n', 'O', 'O<ESC>', { noremap = false }) -- SEE: https://dev.to/snawaz/comment/pa71 -- map('n', 'o', ':<C-u>call append(line("."), repeat([""], v:count1))<CR>', {noremap = false}) -- map('n', 'O', ':<C-u>call append(line(".")-1, repeat([""], v:count1))<CR>', {noremap = false}) -- Remove search highlights map('n', '<F2>', '<Cmd>noh<CR>') -- Vim map map('n', 'Y', 'y$', { noremap = false }) map('n', '<C-h>', '<C-w>h', { noremap = false }) map('n', '<C-l>', '<C-w>l', { noremap = false }) map('n', '<C-j>', '<C-w>j', { noremap = false }) map('n', '<C-k>', '<C-w>k', { noremap = false }) map('n', '<A-[>', '<Cmd>vertical resize -5<CR>', { noremap = false }) map('n', '<A-]>', '<Cmd>vertical resize +5<CR>', { noremap = false }) -- Insert map('i', '<C-w>', '<C-[>diwa') map('i', '<C-h>', '<BS>') map('i', '<C-d>', '<Del>') map('i', '<C-u>', '<C-G>u<C-U>') map('i', '<C-b>', '<Left>') map('i', '<C-f>', '<Right>') map('i', '<C-a>', '<ESC>^i') map('i', '<C-j>', '<Esc>o') map('i', '<C-k>', '<Esc>O') map('i', '<C-s>', '<Cmd>w<CR>') map('i', '<C-q>', '<Cmd>wq<CR>') -- map('i', '<C-e>', [[pumvisible() ? '<C-e>' : '<End>']], { expr = true, silent = false }) -- Command line map('c', '<C-b>', '<Left>') map('c', '<C-f>', '<Right>') map('c', '<C-a>', '<Home>') map('c', '<C-e>', '<End>') map('c', '<C-d>', '<Del>') map('c', '<C-h>', '<BS>') map('c', '<C-t>', [[<C-r>=expand('%:p:h') . '/' <CR>]]) -- Term map('t', '<Esc><Esc>', [[<C-\><C-n>]]) map('t', '<C-j>', [[<C-\><C-n><C-w>j]]) map('t', '<C-h>', [[<C-\><C-n><C-w>h]]) map('t', '<C-k>', [[<C-\><C-n><C-w>k]]) map('t', '<C-l>', [[<C-\><C-n><C-w>l]]) -- ------------------------ -- Quit -- ------------------------ map('n', '<Leader>qq', ':<C-u>confirm qa<CR>', { noremap = false }) map('n', '<Leader>qQ', ':<C-u>qa!<CR>', { noremap = false }) map('n', '<Leader>qs', ':<C-u>wq<CR>', { noremap = false }) -- ------------------------ -- FILE & BUFFER NAVIGATION -- ------------------------ -- Save map('n', '<Leader>fs', ':<C-u>w<CR>') map('n', '<Leader>bs', ':<C-u>w<CR>') -- Save all map('n', '<Leader>fS', ':<C-u>wa<CR>') map('n', '<Leader>bS', ':<C-u>wa<CR>') -- Close -- Smart way to close buffers without losing split windows -- SEE: http://bit.ly/2heyMZ8 map('n', '<Leader>fd', '<Cmd>bp|bd #<CR>') map('n', '<Leader>fc', '<Cmd>bp|bd #<CR>') map('n', '<Leader>bd', '<Cmd>bp|bd #<CR>') map('n', '<Leader>bc', '<Cmd>bp|bd #<CR>') -- Create new file under current dir map('n', '<Leader>fo', ':<C-u>e <C-r>=expand("%:p:h") . "/"<CR>', { silent = false }) map('n', '<Leader>bo', ':<C-u>e <C-r>=expand("%:p:h") . "/"<CR>', { silent = false }) -- Rename map('n', '<Leader>fr', ':<C-u>Rename ', { silent = false }) map('n', '<Leader>br', ':<C-u>Rename ', { silent = false }) -- Move map('n', '<Leader>fm', ':<C-u>Move ', { silent = false }) map('n', '<Leader>bm', ':<C-u>Move ', { silent = false }) -- Delete map('n', '<Leader>fD', ':<C-u>Delete!<CR>') map('n', '<Leader>bD', ':<C-u>Delete!<CR>') map('n', '<Leader>bn', '<Cmd>bn<CR>') map('n', '<Leader>bp', '<Cmd>bp<CR>') map('n', '<Leader>fn', '<Cmd>bn<CR>') map('n', '<Leader>fp', '<Cmd>bp<CR>') -- ------------------------ -- HELP -- ------------------------ -- Packer map('n', '<Leader>hpu', '<Cmd>PackerUpdate<CR>', { nowait = true }) map('n', '<Leader>hpi', '<Cmd>PackerInstall<CR>', { nowait = true }) map('n', '<Leader>hpc', '<Cmd>PackerCompile<CR>', { nowait = true }) map('n', '<Leader>hps', '<Cmd>PackerSync<CR>', { nowait = true }) map('n', '<Leader>hpp', '<Cmd>PackerProfile<CR>', { nowait = true }) -- ------------------------ -- Project -- ------------------------ -- map('n', '<Leader>pp', '<Cmd>lua require("session-lens").search_session()<CR>') -- map('n', '<Leader>ps', '<Cmd>SaveSessiocope<CR>') -- map('n', '<Leader>pd', '<Cmd>DeleteSession<CR>') -- map('n', '<Leader>pr', '<Cmd>RestoreSession<CR>') -- ------------------------ -- WINDOWS NAVIGATION -- ------------------------ map('n', '<Leader>wj', '<C-w>j') map('n', '<Leader>wk', '<C-w>k') map('n', '<Leader>wh', '<C-w>h') map('n', '<Leader>wl', '<C-w>l') map('n', '<Leader>wJ', '<C-w>J') map('n', '<Leader>wK', '<C-w>K') map('n', '<Leader>wH', '<C-w>H') map('n', '<Leader>wL', '<C-w>L') map('n', '<Leader>wc', '<C-w>c') map('n', '<Leader>ww', '<C-w>w') map('n', '<Leader>w=', '<C-w>=') map('n', '<Leader>ws', '<Cmd>sp<CR>') map('n', '<Leader>wv', '<Cmd>vsplit<CR>') -- Plugin vim-operator-surround -- map('n', '<leader>xsa', '<Cmd><Plug>(operator-surround-append)<CR>', {noremap = false}) -- map('n', '<leader>xsd', '<Cmd><Plug>(operator-surround-delete)<CR>', {noremap = false}) -- map('n', '<leader>xsr', '<Cmd><Plug>(operator-surround-replace)<CR>', {noremap = false}) -- Plugin vim_niceblock -- map('x', 'I', 'v:lua.enhance_nice_block("I")', {noremap = false, expr = true}) -- map('x', 'gI', 'v:lua.enhance_nice_block("gI")', {noremap = false, expr = true}) -- map('x', 'A', 'v:lua.enhance_nice_block("A")', {noremap = false, expr = true})
-- Entry.lua -- Util bootstrap, do not use require here local SnowyStream = System.SnowyStream function require(name) local mod = package.loaded[name] if mod then return mod end local path = name .. ".lua" local content = SnowyStream.FetchFileData(path) if content then local chunk, errMsg = load(content, name, "t", _ENV) if chunk then mod = chunk(name) else print("Load module " .. name .. " failed!") print("Error: " .. errMsg) end else print("Module not exist or empty: " .. name) end package.loaded[name] = mod return mod end -- TODO: Remove this line in release build EnableTL = false print("Loading Entry ...") local Bootstrap = require("Engine/Boot/Bootstrap") -- Assure latest script -- local Builder = require("Build") -- Enable Debug Console MakeConsole() local args = { ... } if args[1] and args[1]:sub(1, 1) == "!" then print("Starting custom " .. args[1]) local scriptEntry = args[1]:sub(2) local App = require(scriptEntry) local co = coroutine.create(App.Main) coroutine.resume(co, table.unpack(args, 2)) else print("Starting Main ...") local App = require("Script/Main") local co = coroutine.create(App.Main) coroutine.resume(co, ...) end
-- simple global session data storage function build(directory, config, parameters, level, seed) local ds = getmetatable ''["stardustlib:gdata"] if not ds then ds = { } getmetatable ''["stardustlib:gdata"] = ds end if type(parameters.dataRequest) == "table" then parameters.dataReturn = { } for k in pairs(parameters.dataRequest) do parameters.dataReturn[k] = ds[k] end parameters.dataRequest = nil end if type(parameters.dataInsert) == "table" then for k, v in pairs(parameters.dataInsert) do ds[k] = v end parameters.dataInsert = nil end return config, parameters end
local test = require('tap/test') local t = test.new() t:plan(4) local lazy = t:requireOK('lazy') or t:bailOut("Can't load program-options") t:subtest( 'lazy.require()', function () t:plan(2) -- We want to unload some libraries and try loading it through -- lazy.require(). But it would be too rude to do that on something -- not under our control. So we unload the very 'lazy'. package.loaded.lazy = nil local llazy = lazy.require('lazy') -- Metamethods don't seem to be able to fool pairs(). local function isEmpty(mod) -- luacheck: ignore for _ in pairs(mod) do return false end return true end t:ok(isEmpty(llazy), "Lazily loaded module is initially empty") t:is(type(llazy.require), "function", "Observing its member actually loads it") end) t:subtest( 'delay and force', function () t:plan(5) local evaluated = false local delayed = lazy.delay( function () evaluated = true return 42 end) t:ok(not evaluated, "Delayed values are initially not evaluated") t:is(lazy.force(delayed), 42, "The computed value is correct") t:is(delayed(), 42, "Delayed values can also be forced by calling them as functions") evaluated = false lazy.force(delayed) t:ok(not evaluated, "force()'ing the same value doesn't evaluate it again") local wrapped = lazy.wrap(42) t:is(wrapped(), 42, "wrap") end) t:subtest( 'map', function () t:plan(2) local evaluated = false local foo = lazy.delay( function () evaluated = true return 42 end) local bar = foo:map( function (x) return x+1 end) t:ok(not evaluated, "Delayed values won't be forced simply because they are mapped") t:is(bar(), 43, ":map() transforms a delayed value with a function") end)
local brackets = require('bracket-push') describe('bracket-push', function() it('should accept an empty string', function() assert.is_true(brackets.valid('')) end) it('should accept a matched pair of braces', function() assert.is_true(brackets.valid('{}')) end) it('should reject an opening brace without a closing brace', function() assert.is_false(brackets.valid('{')) end) it('should reject a closing brace without an opening brace', function() assert.is_false(brackets.valid('}{')) end) it('should accept a matched pair of parens', function() assert.is_true(brackets.valid('()')) end) it('should reject an opening paren without a closing paren', function() assert.is_false(brackets.valid('(')) end) it('should reject a closing paren without an opening paren', function() assert.is_false(brackets.valid(')(')) end) it('should accept a matched pair of square brackets', function() assert.is_true(brackets.valid('[]')) end) it('should reject an opening square bracket without a closing square bracket', function() assert.is_false(brackets.valid('[')) end) it('should reject a closing square bracket without an opening square bracket', function() assert.is_false(brackets.valid('][')) end) it('should accept more than one pair of brackets', function() assert.is_true(brackets.valid('[]{}()')) end) it('should accept nested brackets', function() assert.is_true(brackets.valid('[{}]')) end) it('should reject properly balanced but improperly nested brackets', function() assert.is_false(brackets.valid('[{]}')) end) it('should allow deep nesting of brackets', function() assert.is_true(brackets.valid('[{(([{}]))}]')) end) it('should accept complicated brackets that are balanced and properly nested', function() assert.is_true(brackets.valid('{[]([()])}')) end) it('should reject complicated brackets that are not balanced', function() assert.is_false(brackets.valid('{[]([()]}')) end) it('should reject complicated brackets that are not properly nested', function() assert.is_false(brackets.valid('{[]([()]})')) end) it('should ignore non-bracket characters', function() assert.is_true(brackets.valid('{hello[]([a()])b}c')) end) end)
local global = require 'domain.global' local server = {} local vim = vim -- gopls configuration template use daemon server.go = { cmd = {"gopls","--remote=auto"}; filetypes = {'go','gomod'}; root_patterns = {'go.mod','.git'}; -- https://github.com/golang/tools/blob/master/gopls/doc/settings.md#settings init_options = { usePlaceholders=true; completeUnimported=true; }; } server.lua = { cmd = { global.home.."/lua-language-server/bin/macOS/lua-language-server", "-E", global.home.."/lua-language-server/main.lua"}; filetypes = {'lua'}; root_patterns = {'.git'}; settings = { Lua = { diagnostics = { enable = true, globals = {"vim"} }, runtime = {version = "LuaJIT"}, workspace = { library = vim.list_extend({[vim.fn.expand("$VIMRUNTIME/lua")] = true},{}), }, }, } } server.rust = { cmd = { "rust-analyzer" }; filetypes = {"rust"}; root_patterns = {"Cargo.toml", "rust-project.json"} } server.zig = { cmd = { "zls" }; filetypes = {"zig"}; root_patterns = {".git"} } server.sh = { cmd = { "bash-language-server", "start" }; filetypes = { "sh" }; root_patterns = {".git"} } server.Dockerfile = { cmd = { "docker-langserver", "--stdio" }; filetypes = { "Dockerfile", "dockerfile" }; root_patterns = {"Dockerfile"}; } server.tsserver = { cmd = {"typescript-language-server","--stdio"}; filetypes = {"javascript", "javascriptreact", "typescript", "typescriptreact"}; root_patterns = {"package.json", "tsconfig.json", ".git"} } server.cssls = { cmd = {'css-languageserver','--stdio'}; filetypes = {"css", "scss", "less"}; } local lsp_intall_scripts = [=[ # Install gopls cd $HOME go get golang.org/x/tools/gopls@latest # clone lua lsp and build it git clone https://github.com/sumneko/lua-language-server cd lua-language-server git submodule update --init --recursive cd 3rd/luamake ninja -f ninja/macos.ninja cd ../.. ./3rd/luamake/luamake rebuild # Install dockerfile lsp server npm install -g dockerfile-language-server-nodejs # Install bash lsp server npm i -g bash-language-server # Install rust-analyzer RUSTANALYZER=/tmp/rust-analyzer curl -L https://github.com/rust-analyzer/rust-analyzer/releases/latest/download/rust-analyzer-mac -o $RUSTANALYZER chmod +x $RUSTANALYZER mv $RUSTANALYZER /usr/local/bin/ ]=] -- TODO: check install scripts and design a better install function function server.lsp_install_server() os.execute("sh -c"..lsp_intall_scripts) end function server.install_command() vim.api.nvim_command("command! -nargs=0 -bar LspInstall lua require'lspconf'.lsp_install_server()") end return server
require("bindings.global.key") require("bindings.global.mouse") require("bindings.client.key") require("bindings.client.mouse") root.keys(globalkeys)
AddCSLuaFile() AddCSLuaFile("client/cop_client.lua") stalker_cop = stalker_cop or {} stalker_cop.CrosshairEnabled = CreateConVar("cop_crosshair_enabled", 1, {FCVAR_REPLICATED, FCVAR_ARCHIVE}) game.AddParticles("particles/cop_particles_gauss.pcf") game.AddParticles("particles/cop_particles_explosion.pcf") PrecacheParticleSystem("cop_gauss_rail") PrecacheParticleSystem("cop_rgd_explosion") COP_WEPSTATE_NONE = 0 COP_WEPSTATE_AIMING = 1 COP_WEPSTATE_RELOADING = 2 COP_WEPSTATE_HOLSTERING = 3 COP_WEPSTATE_THROWING = 4 stalker_cop.Addons = { ["scope_pso"] = { name = "PSO-1 Scope", type = "scope" }, ["scope_susat"] = { name = "SUSAT Scope", type = "scope" }, ["silencer"] = { name = "Silencer", type = "silencer" } } for k, v in pairs(stalker_cop.Addons) do v.cvar = CreateConVar("cop_upgrade_" .. k, 1, true, false) if CLIENT then language.Add("COP_ADDON_" .. string.upper(k), v.name) end end if CLIENT then stalker_cop.HandType = CreateClientConVar("cop_hands", 0, true, true) stalker_cop.HandTex = CreateClientConVar("cop_handtex", 1, true, true) stalker_cop.DynamicCrosshair = CreateClientConVar("cop_crosshair_dynamic", 1, true, true) stalker_cop.ModelManager = {} stalker_cop.ModelManager.ActiveModels = {} function stalker_cop.ModelManager:CreateModel(modelname, ent) local model = ClientsideModel(modelname, RENDERGROUP_VIEWMODEL_TRANSLUCENT) if model then model:SetNoDraw(true) model.entParent = ent table.insert(self.ActiveModels, model) return model end end function stalker_cop.ModelManager:Validate() local i = 1 while i <= #self.ActiveModels do local model = self.ActiveModels[i] if not IsValid(model.entParent) then SafeRemoveEntity(model) table.remove(self.ActiveModels, i) else i = i + 1 end end end timer.Create("stalker_cop.ModelManager", 5, 0, function() stalker_cop.ModelManager:Validate() end) local hands = { "models/weapons/wick/stcopwep/wpn_black_gloves_hands.mdl", "models/weapons/stalker_cop/v_hands_exo.mdl" } function stalker_cop.UpdatePlayerHands() local ply = LocalPlayer() local t = stalker_cop.HandType:GetInt() local tex = stalker_cop.HandTex:GetInt() if IsValid(ply) then local handmodel = hands[math.Clamp(t, 1, #hands)] if handmodel then if ply.COP_Hands then SafeRemoveEntity(ply.COP_Hands) end ply.COP_Hands = stalker_cop.ModelManager:CreateModel(handmodel, ply) if IsValid(ply.COP_Hands) then local skinCount = ply.COP_Hands:SkinCount() ply.COP_Hands:SetSkin(math.Clamp(tex, 0, skinCount - 1)) end end end end cvars.AddChangeCallback("cop_hands", function(cvar, old, new) stalker_cop.UpdatePlayerHands() end, "stalker_cop.cop_hands") cvars.AddChangeCallback("cop_handtex", function(cvar, old, new) stalker_cop.UpdatePlayerHands() end, "stalker_cop.cop_handtex") local td = {} function stalker_cop.DrawAmmoInfo() local ply = LocalPlayer() if IsValid(ply) and ply:Alive() then if ply:KeyDown(IN_USE) then local _ents = ents.FindInSphere(ply:GetPos(), 320) surface.SetFont("TargetID") surface.SetTextColor(255, 255, 255, 255) for i = 1, #_ents do local ent = _ents[i] if IsValid(ent) and ent.IsCOPEntity then td.start = ply:EyePos() td.endpos = td.start + (ent:GetPos() - td.start):GetNormal() * 1024 td.filter = ply local tr = util.TraceLine(td) if not tr.Hit or (tr.Entity == ent) then local pos = ent:GetPos() pos.z = pos.z + 20 local screen = pos:ToScreen() if screen.visible then local w, h = surface.GetTextSize(ent.PrintName) surface.SetTextPos(screen.x - w * 0.5, screen.y - h * 0.5) surface.DrawText(ent.PrintName) end end end end end end end hook.Add("HUDPaint", "stalker_cop.DrawAmmoInfo", stalker_cop.DrawAmmoInfo) end local function AddSound(id, name) if istable(name) then for i = 1, #name do name[i] = "weapons/stalker_cop/" .. name[i] .. ".wav" end else name = "weapons/stalker_cop/" .. name .. ".wav" end sound.Add { name = id, channel = CHAN_STATIC, volume = 1, level = 80, pitch = { 96, 104 }, sound = name } end local function AddAmmoType(id, name, give_amount) game.AddAmmoType{ name = id, dmgtype = DMG_BULLET } if CLIENT then language.Add(id .. "_ammo", name) end local ENT = {} ENT.PrintName = name ENT.Base = "cop_ammo_base" ENT.Category = "Call of Pripyat - Ammo" ENT.Spawnable = true ENT.AmmoType = id ENT.GiveAmount = give_amount or 20 local classname = string.lower(id) .. "_ammo" scripted_ents.Register(ENT, classname) end AddAmmoType("COP_545", "5.45x39mm Ammo", 30) AddAmmoType("COP_556", "5.56x45mm Ammo", 30) AddAmmoType("COP_9x19MM", "9x19mm Ammo", 20) AddAmmoType("COP_9x18MM", "9x18mm Ammo", 20) AddAmmoType("COP_9x39MM", "9x39mm Ammo", 20) AddAmmoType("COP_12x70BUCK", "12x70 Buckshot", 12) AddAmmoType("COP_762x54PP", "7.62x54mm PP Ammo", 20) AddAmmoType("COP_762x42MMR", "7.62x54mmR Ammo", 20) AddAmmoType("COP_45ACP", ".45 ACP Ammo", 20) AddAmmoType("COP_RGD5", "RGD-5 Grenades", 3) AddAmmoType("COP_F1", "F1 Grenades", 3) AddAmmoType("COP_VOG25", "VOG-25 Grenades", 10) AddAmmoType("COP_BATTERY", "Batteries", 10) AddAmmoType("COP_PG7VL", "PG-7VL Warheads", 3) AddSound("COP_Addon.Attach", "addon_attach") AddSound("COP_Addon.Detach", "addon_detach") AddSound("COP_Knife.Swing", {"knife_1", "knife_2", "knife_3"}) AddSound("COP_Knife.Hurt", {"knife_hurt1", "knife_hurt2"}) AddSound("COP_Knife.Hit", "knife_hit") AddSound("COP_Generic.Draw", "generic_draw_stcop") AddSound("COP_Generic.Empty", "generic_empty") AddSound("COP_Generic.Reload", "") AddSound("COP_Generic.Holster", "generic_holster_stcop") AddSound("COP_Pistol.Empty", "pistol_empty") AddSound("COP_AK74.Draw", "ak74_draw") AddSound("COP_AK74.Fire", "n_ak74_shot") AddSound("COP_AK74.Bore", "ak74_bore") AddSound("COP_AK74.Sil", "w_ak74_shot1") AddSound("COP_AK74u.Fire", "n_ak74u_shot") AddSound("COP_Bino.Draw", "bino_draw") AddSound("COP_Bino.Holster", "bino_holster") AddSound("COP_Gauss.Fire", "gauss_shoot") AddSound("COP_Gauss.Reload", "gauss_reload") AddSound("COP_PM.FireAPS", "aps_shoot") AddSound("COP_PB.FireAPS", "aps_shot_sil") AddSound("COP_Pistol.ReloadAPS", "aps_reload") AddSound("COPSNPER.FireSVDSTCOP", "svd_shoot") AddSound("COPSNPER.FireSVDSTCOPSILENS", "svd_shot_sil") AddSound("COPSNPER.SVDDRAWSTCOP", "svd_draw") AddSound("COPSNPER.SVDRELOADSTCOP", "svd_reload") AddSound("COPMP5.SHOOTSTCOP", "mp5_shoot") AddSound("COPMP5.SHOOTSILSTCOP", "mp5_shot_sil") AddSound("COPMP5.RELOADSTCOP", "mp5_reload") AddSound("COPMP5.EMPTSTCOP", "mp5_empty") AddSound("COPMP5.DELPOY", "mp5_draw") AddSound("COPGROZA.groza_draw", "groza_draw") AddSound("COPGROZA.groza_reload", "groza_reload") AddSound("COPGROZA.groza_shoot", "groza_shoot") AddSound("COPGROZA.groza_shot_sil", "groza_shot_sil") AddSound("COPBIZON.SHOOTSTCOP", "bizon_shoot") AddSound("COPBIZON.SHOOTSILSTCOP", "bizon_shot_sil") AddSound("COPBIZON.RELOADSTCOP", "bizon_reload") AddSound("COPFN2000.fn2000_draw", "fn2000_draw") AddSound("COPFN2000.fn2000_empty", "fn2000_empty") AddSound("COPFN2000.fn2000_reload", "fn2000_reload") AddSound("COPFN2000.fn2000_shoot", "fn2000_shoot") AddSound("COPFN2000.fn2000_shot_sil", "fn2000_shot_sil") AddSound("COPP99.walther_draw", "walther_draw") AddSound("COPP99.walther_empty", "walther_empty") AddSound("COPP99.walther_reload", "walther_reload") AddSound("COPP99.walther_shoot", "walther_shoot") AddSound("COPP99.walther_shot_sil", "walther_shot_sil") AddSound("COPPKM.pkm_draw", "pkm_draw") AddSound("COPPKM.pkm_empty", "pkm_empty") AddSound("COPPKM.pkm_holster", "pkm_holster") AddSound("COPPKM.pkm_reload", "pkm_reload") AddSound("COPPKM.pkm_shoot", "pkm_shoot") AddSound("COPDEAGLE.de_draw", "de_draw") AddSound("COPDEAGLE.de_empty", "de_empty") AddSound("COPDEAGLE.de_reload", "de_reload") AddSound("COPDEAGLE.de_shoot", "de_shoot") AddSound("COPDEAGLE.de_shot_sil", "de_shot_sil") AddSound("COPCOLT.colt_draw", "colt_draw") AddSound("COPCOLT.colt_empty", "colt_empty") AddSound("COPCOLT.de_reload", "de_reload") AddSound("COPCOLT.colt_shot_sil", "colt_shot_sil") AddSound("COPCOLT.colt_shoot", "colt_shoot") AddSound("COPUSP.usp_draw", "usp_draw") AddSound("COPUSP.usp_empty", "usp_empty") AddSound("COPUSP.usp_reload", "usp_reload") AddSound("COPUSP.usp_shoot", "usp_shoot") AddSound("COPUSP.usp_shot_sil", "usp_shot_sil") AddSound("COPLR300.lr300_draw", "lr300_draw") AddSound("COPLR300.lr300_empty", "lr300_empty") AddSound("COPLR300.lr300_reload", "lr300_reload") AddSound("COPLR300.lr300_shoot", "lr300_shoot") AddSound("COPLR300.lr300_shot_sil", "lr300_shot_sil") AddSound("COPHK416STCOP.hk416_reload", "hk416_reload") AddSound("COPSPAS.spas12_reload_end", "spas12_reload_end") AddSound("COPSPAS.spas12_holster", "spas12_holster") AddSound("COPSPAS.spas12_draw", "spas12_draw") AddSound("COPSPAS.spas12_empty", "spas12_empty") AddSound("COPSPAS.spas12_load", "spas12_load") AddSound("COPSPAS.spas12_open", "spas12_open") AddSound("COPSPAS.spas12_shoot", "spas12_shoot") AddSound("COPPROTECTA.protecta_draw", "protecta_draw") AddSound("COPPROTECTA.protecta_empty", "protecta_empty") AddSound("COPPROTECTA.protecta_load", "protecta_load") AddSound("COPPROTECTA.protecta_open", "protecta_open") AddSound("COPPROTECTA.protecta_shoot", "protecta_shoot") AddSound("COPPROTECTA.protecta_close", "protecta_close") AddSound("COPPROTECTA.protecta_open", "protecta_open") AddSound("COPRPGSTCOP.rpg7_shoot", "rpg7_shoot") AddSound("COPRPGSTCOP.rpg7_reload", "rpg7_reload") AddSound("COPRPGSTCOP.rpg7_explode", "rpg7_explode") AddSound("COPRPGSTCOP.rpg7_shot", "rpg7_shot") AddSound("COPRPGSTCOP.rpg7_draw", "rpg7_draw") AddSound("COPRPGSTCOP.rpg7_empty", "rpg7_empty") AddSound("COPRG6.rg6_close", "rg6_close") AddSound("COPRG6.rg6_draw", "rg6_draw") AddSound("COPRG6.rg6_empty", "rg6_empty") AddSound("COPRG6.rg6_shoot", "rg6_shoot") AddSound("COPRG6.rg6_reload", "rg6_reload") AddSound("COPRG6.rg6_open", "rg6_open") AddSound("COPPM.pm_close", "pm_close") AddSound("COPPM.pm_draw", "pm_draw") AddSound("COPPM.pm_empty", "pm_empty") AddSound("COPPM.pm_reload", "pm_reload") AddSound("COPPM.pm_shoot", "pm_shoot") AddSound("COPPM.pm_shot_sil", "pm_shot_sil") AddSound("COPSG550.sig550_draw", "sig550_draw") AddSound("COPSG550.sig550_empty", "sig550_empty") AddSound("COPSG550.sig550_reload", "sig550_reload") AddSound("COPSG550.sig550_shoot", "sig550_shoot") AddSound("COPSG550.sig550_shot_sil", "sig550_shot_sil") AddSound("COPLR85.l85_reload", "l85_reload") AddSound("COPLR85.l85_draw", "l85_draw") AddSound("COPLR85.l85_empty", "l85_empty") AddSound("COPLR85.l85_shot_sil", "l85_shot_sil") AddSound("COPLR85.l85_shoot", "l85_shoot") AddSound("COPAEK.aek971_reload", "aek971_reload") AddSound("COPAEK.aek971_shoot", "aek971_shoot") AddSound("COPAK74.ak74_shot_sil", "ak74_shot_sil") AddSound("COPAK74.ak_draw", "ak_draw") AddSound("COPSAIGA.saiga_reload", "saiga_reload") AddSound("COPSAIGA.saiga_shoot", "saiga_shoot") AddSound("COPSAIGA.saiga_shot_sil", "saiga_shot_sil") AddSound("COPBERETASTCOP.beretta_shot_sil", "beretta_shot_sil") AddSound("COPBERETASTCOP.beretta_reload", "beretta_reload") AddSound("COPBERETASTCOP.beretta_shoot", "beretta_shoot") AddSound("COPBERETASTCOP.beretta_draw", "beretta_draw") AddSound("COPBERETASTCOP.beretta_empty", "beretta_empty") AddSound("COPVSSSTCOP.vintorez_draw", "vintorez_draw") AddSound("COPVSSSTCOP.vintorez_empty", "vintorez_empty") AddSound("COPVSSSTCOP.vintorez_reload", "vintorez_reload") AddSound("COPVSSSTCOP.vintorez_shoot", "vintorez_shoot") AddSound("COPSCARSTCOP.scar_reload", "scar_reload") AddSound("COPSCARSTCOP.scar_shoot", "scar_shoot") AddSound("COPSCARSTCOP.scar_shot_sil", "scar_shot_sil") AddSound("COPFNPSTCOP.fnp45_draw", "fnp45_draw") AddSound("COPFNPSTCOP.fnp45_reload", "fnp45_reload") AddSound("COPFNPSTCOP.fnp45_shoot", "fnp45_shoot") AddSound("COPFNPSTCOP.fnp45_shot_sil", "fnp45_shot_sil") AddSound("COPMOSINSTCOP.mosin_reload1", "mosin_reload1") AddSound("COPMOSINSTCOP.mosin_shoot_sound", "mosin_shoot_conv") AddSound("COPGLOCKSTCOP.glock_reload", "glock_reload") AddSound("COPGLOCKSTCOP.glock_shoot", "glock_shoot") AddSound("COPGLOCKSTCOP.glock_shot_sil", "glock_shot_sil") AddSound("COPSV98STCOP.sv98_draw", "sv98_draw") AddSound("COPSV98STCOP.sv98_reload", "sv98_reload") AddSound("COPSV98STCOP.sv98_empty", "sv98_empty") AddSound("COPSV98STCOP.sv98_shoot", "sv98_shoot") AddSound("COPL96STCOP.l96a1_reload", "l96a1_reload") AddSound("COPL96STCOP.l96a1_shoot", "l96a1_shoot") AddSound("COPVALSTCOP.val_draw", "val_draw") AddSound("COPVALSTCOP.val_empty", "val_empty") AddSound("COPVALSTCOP.val_reload", "val_reload") AddSound("COPVALSTCOP.val_shoot", "val_shoot") AddSound("COPG36SCOP.g36_draw", "g36_draw") AddSound("COPG36SCOP.g36_empty", "g36_empty") AddSound("COPG36SCOP.g36_holster", "g36_holster") AddSound("COPG36SCOP.g36_reload_stcop", "g36_reload_stcop") AddSound("COPG36SCOP.g36_shoot", "g36_shoot") AddSound("COPG36SCOP.g36_shot_sil", "g36_shot_sil") AddSound("COPAK_74SCOP.ak74_draw_stcop", "ak74_draw_stcop") AddSound("COPAK_74SCOP.ak74_holster", "ak74_holster") AddSound("COPAK_74SCOP.ak74_reload", "ak74_reload") AddSound("COPAK_74SCOP.ak74_shoot", "ak74_shoot") AddSound("COPAK_74SCOP.ak74_shot_sil_stcop", "ak74_shot_sil_stcop") AddSound("COPFORTSCOP.fort_draw", "fort_draw") AddSound("COPFORTSCOP.fort_empty", "fort_empty") AddSound("COPFORTSCOP.fort_reload", "fort_reload") AddSound("COPFORTSCOP.fort_shoot", "fort_shoot") AddSound("COPFORTSCOP.fort_shot_sil", "fort_shot_sil") AddSound("COPBINOSCOP.bino_draw_stcop", "bino_draw_stcop") AddSound("COPBINOSCOP.bino_holster", "bino_holster") AddSound("COPBROWINGSCOP.hpsa_shot_sil", "hpsa_shot_sil") AddSound("COPBROWINGSCOP.hpsa_draw", "hpsa_draw") AddSound("COPBROWINGSCOP.hpsa_empty", "hpsa_empty") AddSound("COPBROWINGSCOP.hpsa_reload", "hpsa_reload") AddSound("COPBROWINGSCOP.hpsa_shoot", "hpsa_shoot") AddSound("COPRPKSCOP.rpk74_reload", "rpk74_reload") AddSound("COPRPKSCOP.rpk74_shoot", "rpk74_shoot") AddSound("COPSVUSCOP.svu_draw", "svu_draw") AddSound("COPSVUSCOP.svu_reload_stcop", "svu_reload_stcop") AddSound("COPSVUSCOP.svu_shoot", "svu_shoot") AddSound("COPBM16SCOP.bm16_draw", "bm16_draw") AddSound("COPBM16SCOP.bm16_empty", "bm16_empty") AddSound("COPBM16SCOP.bm16_reload_l_stcop", "bm16_reload_l_stcop") AddSound("COPBM16SCOP.bm16_reload_lr_stcop", "bm16_reload_lr_stcop") AddSound("COPBM16SCOP.bm16_shoot", "bm16_shoot") AddSound("COPBM16SCOP.bm16_shoot_both", "bm16_shoot_both") AddSound("COPABAKANSCOP.abakan_draw", "abakan_draw") AddSound("COPABAKANSCOP.abakan_empty", "abakan_empty") AddSound("COPABAKANSCOP.abakan_reload", "abakan_reload_cut") AddSound("COPABAKANSCOP.abakan_shoot", "abakan_shoot") AddSound("COPABAKANSCOP.abakan_shot_sil", "abakan_shot_sil") AddSound("COPAKMSCOP.akm_shoot", "akm_shoot") AddSound("COPSKSSCOP.sks_draw", "sks_draw") AddSound("COPSKSSCOP.sks_reload", "sks_reload") AddSound("COPSKSSCOP.sks_shoot", "sks_shoot") AddSound("COPTOZ34COP.toz34_draw", "toz34_draw") AddSound("COPTOZ34COP.toz34_empty", "toz34_empty") AddSound("COPTOZ34COP.toz34_reload_l", "toz34_reload_l") AddSound("COPTOZ34COP.toz34_reload_lr", "toz34_reload_lr") AddSound("COPTOZ34COP.toz34_shoot", "toz34_shoot") AddSound("COPKARYAKCOP.kar98k_pump", "kar98k_pump") AddSound("COPKARYAKCOP.kar98k_reload", "kar98k_reload") AddSound("COPKARYAKCOP.kar98k_reload_end", "kar98k_reload_end") AddSound("COPKARYAKCOP.kar98k_reload_start", "kar98k_reload_start") AddSound("COPKARYAKCOP.kar98k_shoot", "kar98_shoot_conv") AddSound("COPKARYAKCOP.kar98k_shoot_sil", "kar98k_shoot_sil") AddSound("COPFLASHLIGHT.flashlight_draw", "flashlight_draw") AddSound("COPFLASHLIGHT.flashlight_holster", "flashlight_holster") AddSound("COPAKSUSTCOP.aks74u_draw", "aks74u_draw") AddSound("COPAKSUSTCOP.aks74u_reload", "aks74u_reload") AddSound("COPAKSUSTCOP.aks74u_shoot", "aks74u_shoot") AddSound("COPAKSUSTCOP.aks74u_shot_sil", "aks74u_shot_sil") AddSound("COPMP153STCOP.mp153_draw", "mp153_draw") AddSound("COPMP153STCOP.mp153_insertshell", "mp153_insertshell") AddSound("COPMP153STCOP.mp153_shoot", "mp153_shoot") AddSound("gauss_shot", "gauss_shot") AddSound("gauss_reload", "gauss_reload") AddSound("gauss_holster", "gauss_holster") AddSound("gauss_empty", "gauss_empty") AddSound("gauss_draw", "gauss_draw") AddSound("m60_reload", "m60_reload") AddSound("m60_shoot", "m60_shoot")
return function () local uv = require('uv') local core = require('core')() if #args < 2 then core.installDeps(uv.cwd()) else local list = {} for i = 2, #args do list[#list + 1] = args[i] end core.installList(uv.cwd(), list) end end
local class = require 'lib.middleclass' local Entity = require 'source.entities.entity' local anim8 = require 'lib.anim8' local Timer = require 'lib.timer' local Dust = class ("Dust", Entity) local img = love.graphics.newImage("assets/sprites/player/landingdust.png") local w = 16 local h = 16 function Dust:initialize(map, world, x, y) Entity.initialize(self, map, world, x, y, w, h) self.map = map self.x = x self.y = y self.properties = {passable = true} self.timer = Timer() local grid = anim8.newGrid(16, 16, img:getWidth(), img:getHeight()) self.anim = anim8.newAnimation(grid('1-8', 1), 0.05, "pauseAtEnd") self.timer:after(0.5, function() self:destroy() end) end function Dust:update(dt) self.timer:update(dt) self.anim:update(dt) end function Dust:draw(debug) self.anim:draw(img, self.x, self.y, 0, 1, 1, w/2, 5) end return Dust
-- _ _____ ___ _ __ ___________ ________ __ -- | | | ___|/ _ \ | | / /| ___| _ \ | ___ \ \ / / -- | | | |__ / /_\ \| |/ / | |__ | | | | | |_/ /\ V / -- | | | __|| _ || \ | __|| | | | | ___ \ \ / -- | |____| |___| | | || |\ \| |___| |/ / | |_/ / | | -- \_____/\____/\_| |_/\_| \_/\____/|___/ \____/ \_/ -- ___ .__ __. ______ .__ __. ____ ____ .___ ___. ______ __ __ _______. __ _______ ___ __ ___ .______ -- / \ | \ | | / __ \ | \ | | \ \ / / | \/ | / __ \ | | | | / | | | | ____| / \ | |/ / | _ \ -- / ^ \ | \| | | | | | | \| | \ \/ / | \ / | | | | | | | | | | (----` | | | |__ / ^ \ | ' / | |_) | -- / /_\ \ | . ` | | | | | | . ` | \_ _/ | |\/| | | | | | | | | | \ \ | | | __| / /_\ \ | < | / -- / _____ \ | |\ | | `--' | | |\ | | | | | | | | `--' | | `--' | .----) | | `----.| |____ / _____ \ | . \ | |\ \----. -- /__/ \__\ |__| \__| \______/ |__| \__| |__| |__| |__| \______/ \______/ |_______/ |_______||_______/__/ \__\ |__|\__\ | _| `._____| Vliss = Vliss or {} Vliss.Messages = Vliss.Messages or {} if Vliss.Core.WorkshopEnabled then resource.AddWorkshop( "524266848" ) end if Vliss.Core.ResourcesEnabled then resource.AddFile( "resource/fonts/adventpro_light.ttf" ) resource.AddFile( "resource/fonts/oswald_light.ttf" ) resource.AddFile( "resource/fonts/teko_light.ttf" ) resource.AddFile( "materials/vliss/vliss_btn_cleanup.png" ) resource.AddFile( "materials/vliss/vliss_btn_close.png" ) resource.AddFile( "materials/vliss/vliss_btn_copy.png" ) resource.AddFile( "materials/vliss/vliss_btn_decals.png" ) resource.AddFile( "materials/vliss/vliss_btn_disconnect.png" ) resource.AddFile( "materials/vliss/vliss_btn_donate.png" ) resource.AddFile( "materials/vliss/vliss_btn_group.png" ) resource.AddFile( "materials/vliss/vliss_btn_home.png" ) resource.AddFile( "materials/vliss/vliss_btn_ipaddress.png" ) resource.AddFile( "materials/vliss/vliss_btn_leftpanel_actions.png" ) resource.AddFile( "materials/vliss/vliss_btn_leftpanel_controls.png" ) resource.AddFile( "materials/vliss/vliss_btn_leftpanel_home.png" ) resource.AddFile( "materials/vliss/vliss_btn_leftpanel_news.png" ) resource.AddFile( "materials/vliss/vliss_btn_limits.png" ) resource.AddFile( "materials/vliss/vliss_btn_mainmenu.png" ) resource.AddFile( "materials/vliss/vliss_btn_motd.png" ) resource.AddFile( "materials/vliss/vliss_btn_player_actions.png" ) resource.AddFile( "materials/vliss/vliss_btn_rcon.png" ) resource.AddFile( "materials/vliss/vliss_btn_resume.png" ) resource.AddFile( "materials/vliss/vliss_btn_server.png" ) resource.AddFile( "materials/vliss/vliss_btn_speakenabled.png" ) resource.AddFile( "materials/vliss/vliss_btn_speakmute.png" ) resource.AddFile( "materials/vliss/vliss_btn_staff.png" ) resource.AddFile( "materials/vliss/vliss_btn_steam.png" ) resource.AddFile( "materials/vliss/vliss_btn_stopsound.png" ) resource.AddFile( "materials/vliss/vliss_btn_switch_off.png" ) resource.AddFile( "materials/vliss/vliss_btn_switch_on.png" ) resource.AddFile( "materials/vliss/vliss_btn_unban.png" ) resource.AddFile( "materials/vliss/vliss_btn_weap.png" ) resource.AddFile( "materials/vliss/vliss_btn_website.png" ) resource.AddFile( "materials/vliss/vliss_btn_workshop.png" ) resource.AddFile( "materials/vliss/vliss_plystatus_dead.png" ) resource.AddFile( "materials/vliss/vliss_status_dead.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_1.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_2.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_3.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_4.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_5.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_6.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_7.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_8.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_9.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_10.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_11.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_12.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_13.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_14.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_15.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_16.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_17.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_18.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_19.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_20.png" ) resource.AddFile( "materials/vliss/avatars/vliss_avatar_21.png" ) end ----------------------------------------------------------------- -- [ ADDITIONALS ] ----------------------------------------------------------------- AddCSLuaFile( "vliss/cl/cl_override.lua" ) ----------------------------------------------------------------- -- [ NETWORK STRINGS ] ----------------------------------------------------------------- util.AddNetworkString("VlissMessageSet") util.AddNetworkString("VlissPlayerIP") util.AddNetworkString("VlissActionPlayerXfer") ----------------------------------------------------------------- -- [ SERVER SETTINGS ] ----------------------------------------------------------------- function Vliss:SettingsSetup() if not file.Exists( "vliss", "DATA" ) then file.CreateDir( "vliss" ) end if not file.Exists( "vliss/settings", "DATA" ) then file.CreateDir( "vliss/settings" ) end if not file.Exists( "vliss/settings/config.txt", "DATA" ) then file.Write( "vliss/settings/config.txt", "" ) end end Vliss:SettingsSetup() ----------------------------------------------------------------- -- [ MESSAGE / BROADCAST FEATURE ] ----------------------------------------------------------------- local Player = FindMetaTable( "Player" ) function Vliss:Broadcast(...) local args = {...} net.Start( "VlissMessageSet" ) net.WriteTable( args ) net.Broadcast() end function Player:PlayerMsg(...) local args = {...} net.Start( "VlissMessageSet" ) net.WriteTable( args ) net.Send( self ) end ----------------------------------------------------------------- -- [ JOIN TEAM ] -- -- Controls the buttons on Vlisss which allow you to join -- whichever team you want. ----------------------------------------------------------------- concommand.Add("vliss_jointeam", function (ply, com, args) if #args < 1 then return end if ( ply.timerLastChanged or 0 ) > CurTime() then ply:PlayerMsg( Vliss.Messages.BCColorType or Color( 255, 255, 0 ), "[PRIVATE] ", Vliss.Messages.BCColorMsg or Color( 255, 255, 255 ), "You must wait ", Vliss.Messages.BCColorValue2 or Color(45, 147, 181), math.Round(ply.timerLastChanged - CurTime()) .." more seconds", Vliss.Messages.BCColorMsg or Color( 255, 255, 255 ), " before changing teams again.") return end local curTeam = ply:Team() local newTeam = tonumber(args[1] or "") or 0 if newTeam != curTeam then ply:SetTeam(newTeam) ply:KillSilent() Vliss:Broadcast( Vliss.Messages.BCColorType or Color( 255, 255, 0 ), "[SERVER] ", Vliss.Messages.BCColorValue or Color( 255, 0, 0 ), ply:Nick(), Vliss.Messages.BCColorMsg or Color( 255, 255, 255 ), " has switched teams.") ply.timerLastChanged = CurTime() + ( Vliss.PropHunt.ForceTeamCooldown or 5 ) end end) ----------------------------------------------------------------- -- [ FORCE TEAM SWITCH ] -- -- This will allow an admin to force a teamswitch on another -- player via the scoreboard. ----------------------------------------------------------------- concommand.Add("vliss_forcemovetoteam", function (ply, com, args) if #args < 1 then return end if not Vliss.PropHunt.AccessMovePlayer[string.lower(ply:GetUserGroup())] then ply:PlayerMsg( Vliss.Messages.BCColorType or Color( 255, 255, 0 ), "[PRIVATE] ", Vliss.Messages.BCColorMsg or Color( 255, 255, 255 ), "You don't have permission to do this.") return end local ent = Entity(tonumber(args[1]) or -1) if !IsValid(ent) || !ent:IsPlayer() then return end if ( ply.timerLastChanged or 0 ) > CurTime() then ply:PlayerMsg( Vliss.Messages.BCColorType or Color( 255, 255, 0 ), "[PRIVATE] ", Vliss.Messages.BCColorMsg or Color( 255, 255, 255 ), "You must wait ", Vliss.Messages.BCColorValue2 or Color(45, 147, 181), math.Round(ply.timerLastChanged - CurTime()) .." more seconds", Vliss.Messages.BCColorMsg or Color( 255, 255, 255 ), " before doing this.") return end local curTeam = ent:Team() local newTeam = tonumber(args[2] or "") or 0 if newTeam != curTeam then ent:SetTeam(newTeam) ent:KillSilent() Vliss:Broadcast( Vliss.Messages.BCColorType or Color( 255, 255, 0 ), "[SERVER] ", Vliss.Messages.BCColorValue or Color( 255, 0, 0 ), ply:Nick(), Vliss.Messages.BCColorMsg or Color( 255, 255, 255 ), " forced team-switch on player ", Vliss.Messages.BCColorValue2 or Color(45, 147, 181), ent:Nick()) ply.timerLastChanged = CurTime() + ( Vliss.PropHunt.ForceTeamCooldown or 5 ) end end) net.Receive("VlissActionPlayerXfer", function( len, ply ) if not (Vliss.Core.StaffGroups[string.lower(ply:GetUserGroup())] and Vliss.Core.AccessXferPlayer[string.lower(ply:GetUserGroup())]) then ply:PlayerMsg( Vliss.Messages.BCColorType or Color( 255, 255, 0 ), "[PRIVATE] ", Vliss.Messages.BCColorMsg or Color( 255, 255, 255 ), "You don't have permission to do this.") return end local targetPlayer = net.ReadEntity() local destIP = net.ReadString() local destHostname = net.ReadString() if !IsValid( targetPlayer ) then ply:PlayerMsg( Vliss.Messages.BCColorType or Color( 255, 255, 0 ), "[PRIVATE] ", Vliss.Messages.BCColorMsg or Color( 255, 255, 255 ), "You supplied an invalid player to transfer.") return end if not destIP then ply:PlayerMsg( Vliss.Messages.BCColorType or Color( 255, 255, 0 ), "[PRIVATE] ", Vliss.Messages.BCColorMsg or Color( 255, 255, 255 ), "You did not specify a server to transfer this player to.") return end targetPlayer:SendLua("LocalPlayer():ConCommand('connect " .. destIP .. "')") Vliss:Broadcast( Vliss.Messages.BCColorServer or Color( 255, 255, 0 ), "[SERVER] ", Vliss.Messages.BCColorName or Color( 77, 145, 255 ), ply:Nick(), Vliss.Messages.BCColorMsg or Color( 255, 255, 255 ), " has transferred player ", Color( 255, 50, 0 ), targetPlayer:Nick(), Vliss.Messages.BCColorMsg or Color( 255, 255, 255 ), " to server", Vliss.Messages.BCColorValue or Color(45, 147, 181), " " .. destHostname .. " ", Vliss.Messages.BCColorValue2 or Color(45, 147, 181), "(" .. destIP .. ")" ) end) -- This is disabled to stop DRM bellow, remove if you want but I have commented it out by putting -- in front of the line. ----hook.Add("Think", "GetVlissUpdate", function() -- VlissFetchHashAuth(1661, "e8aa296d178cd57b8c13a88d39c70ba9d20e4dc1ceefc083", "sv_init", Vliss.Script.Build, nil, game.GetIP()) -- hook.Remove("Think", "GetVlissUpdate") --end)
local settings = ModDLCSettings.throwable_spears local base_string = "scripts/mods/throwables/DLCSettings/throwable_spears/" settings.item_master_list_file_names = { base_string .. "item_master_list_we_throwing_spears" } settings.weapon_skins_file_names = { base_string .. "weapon_skins_we_throwing_spears" } settings.weapon_template_file_names = { base_string .. "we_throwing_spears", } settings.default_items = { we_throwing_spears = { inventory_icon = "icon_wpn_we_spear_01", description = "description_default_wood_elf_ww_spear", display_name = "display_name_default_wood_elf_ww_throwing_spears" }, } settings.inventory_package_list = {} settings.damage_profile_template_files_names = { base_string .. "damage_profile_templates_dlc_we_throwing_spears" } settings.power_level_template_files_names = { base_string .. "power_level_templates_dlc_we_throwing_spears" } settings.attack_template_files_names = { base_string .. "attack_templates_dlc_we_throwing_spears" } settings.projectile_gravity_settings = { throwing_spears = -9.82 } settings.projectile_units = { we_throwing_spears_skin_01 = { dummy_linker_unit_name = "units/weapons/player/wpn_we_spear_01/wpn_we_spear_01_3p", projectile_unit_name = "units/weapons/player/wpn_we_spear_01/wpn_we_spear_01_3p" }, we_throwing_spears_skin_02 = { dummy_linker_unit_name = "units/weapons/player/wpn_we_spear_02/wpn_we_spear_02_3p", projectile_unit_name = "units/weapons/player/wpn_we_spear_02/wpn_we_spear_02_3p" }, we_throwing_spears_skin_03 = { dummy_linker_unit_name = "units/weapons/player/wpn_we_spear_03/wpn_we_spear_03_3p", projectile_unit_name = "units/weapons/player/wpn_we_spear_03/wpn_we_spear_03_3p" }, we_throwing_spears_skin_03_runed_01 = { dummy_linker_unit_name = "units/weapons/player/wpn_we_spear_03/wpn_we_spear_03_runed_01_3p", projectile_unit_name = "units/weapons/player/wpn_we_spear_03/wpn_we_spear_03_runed_01_3p" }, we_throwing_spears_skin_03_runed_02 = { dummy_linker_unit_name = "units/weapons/player/wpn_we_spear_03/wpn_we_spear_03_runed_01", projectile_unit_name = "units/weapons/player/wpn_we_spear_03/wpn_we_spear_03_runed_01", material_settings = WeaponMaterialSettingsTemplates.purple_glow }, we_throwing_spears_skin_04 = { dummy_linker_unit_name = "units/weapons/player/wpn_we_spear_04/wpn_we_spear_04_3p", projectile_unit_name = "units/weapons/player/wpn_we_spear_04/wpn_we_spear_04_3p" }, we_throwing_spears_skin_04_runed_01 = { dummy_linker_unit_name = "units/weapons/player/wpn_we_spear_04/wpn_we_spear_04_runed_01_3p", projectile_unit_name = "units/weapons/player/wpn_we_spear_04/wpn_we_spear_04_runed_01_3p" }, we_throwing_spears_skin_05 = { dummy_linker_unit_name = "units/weapons/player/wpn_we_spear_05/wpn_we_spear_05_3p", projectile_unit_name = "units/weapons/player/wpn_we_spear_05/wpn_we_spear_05_3p" }, } settings.projectiles = { throwing_spears = { rotation_speed = 30, rotation_max = 75, static_impact_type = "raycast", impact_type = "sphere_sweep", trajectory_template_name = "throw_trajectory", radius = 0.075, --linear_dampening = 0.691, indexed = true, use_weapon_skin = true, gravity_settings = "throwing_spears", bounce_angular_velocity = { 0, 0, 0 }, --scale = 50, } } settings.spread_templates = { throwing_spears = { continuous = { still = { max_yaw = 0.25, max_pitch = 0.25 }, moving = { max_yaw = 0.25, max_pitch = 0.25 }, crouch_still = { max_yaw = 0.25, max_pitch = 0.25 }, crouch_moving = { max_yaw = 0.25, max_pitch = 0.25 }, zoomed_still = { max_yaw = 0.25, max_pitch = 0.25 }, zoomed_moving = { max_yaw = 0.25, max_pitch = 0.25 }, zoomed_crouch_still = { max_yaw = 0.25, max_pitch = 0.25 }, zoomed_crouch_moving = { max_yaw = 0.25, max_pitch = 0.25 } }, immediate = { being_hit = { immediate_pitch = 1.4, immediate_yaw = 1.4 }, shooting = { immediate_pitch = 0.5, immediate_yaw = 0.5 } } } } return
local carpetItems = { [22737] = 22736, [22736] = 22737,-- Rift carpet [23537] = 23536, [23536] = 23537,-- Void carpet [23431] = 23453, [23453] = 23431,-- Yalaharian carpet [23432] = 23454, [23454] = 23432,-- White fur carpet [23433] = 23455, [23455] = 23433,-- Bamboo mat carpet [23715] = 23707, [23707] = 23715,-- Crimson carpet [23710] = 23716, [23716] = 23710,-- Azure carpet [23711] = 23717, [23717] = 23711,-- Emerald carpet [23712] = 23718, [23718] = 23712,-- Light parquet carpet [23713] = 23719, [23719] = 23713,-- Dark parquet carpet [23714] = 23720, [23720] = 23714,-- Marble floor [24416] = 24424, [24424] = 24416,-- Flowery carpet [24417] = 24425, [24425] = 24417,-- Colourful Carpet [24418] = 24426, [24426] = 24418,-- Striped carpet [24419] = 24427, [24427] = 24419,-- Fur carpet [24420] = 24428, [24428] = 24420,-- Diamond carpet [24421] = 24429, [24429] = 24421,-- Patterned carpet [24422] = 24430, [24430] = 24422,-- Night sky carpet [24423] = 24431, [24431] = 24423,-- Star carpet [26114] = 26115, [26115] = 26114,-- Verdant carpet [26116] = 26117, [26117] = 26116,-- Shaggy carpet [26118] = 26119, [26119] = 26118,-- Mystic carpet [26120] = 26121, [26121] = 26120,-- Stone tile [26123] = 26122, [26122] = 26123,-- Wooden plank [26151] = 26150, [26150] = 26151,-- Wheat carpet [26152] = 26153, [26153] = 26152,-- Crested carpet [26154] = 26155, [26155] = 26154 -- Decorated carpet } local carpets = Action() function carpets.onUse(player, item, fromPosition, target, toPosition, isHotkey) local carpet = carpetItems[item.itemid] if not carpet then return false end local tile = Tile(item:getPosition()) local carpetStack = 0 for _, carpetId in pairs(carpetItems) do carpetStack = carpetStack + tile:getItemCountById(carpetId) end if fromPosition.x == CONTAINER_POSITION then player:sendTextMessage(MESSAGE_FAILURE, "Put the item on the floor first.") return true elseif not tile or not tile:getHouse() then player:sendTextMessage(MESSAGE_FAILURE, "You may use this only inside a house.") return true elseif carpetStack > 1 then player:sendCancelMessage(RETURNVALUE_NOTPOSSIBLE) return true end item:transform(carpet) return true end for index, value in pairs(carpetItems) do carpets:id(index) end carpets:register()
local ffi = require("ffi") ffi.cdef[[ int mapnik_register_datasources(const char* path); // Opaque class structure typedef struct _mapnik_map_t mapnik_map_t; mapnik_map_t * mapnik_map( unsigned int width, unsigned int height ); void mapnik_map_free(mapnik_map_t * m); const char * mapnik_map_get_srs(mapnik_map_t * m); int mapnik_map_set_srs(mapnik_map_t * m, const char* srs); int mapnik_map_load(mapnik_map_t * m, const char* stylesheet); int mapnik_map_zoom_all(mapnik_map_t * m); int mapnik_map_render_to_file(mapnik_map_t * m, const char* filepath); ]] local clib = ffi.load("./libmapnik_c.dylib") clib.mapnik_register_datasources("/usr/local/lib/mapnik/input") local map = clib.mapnik_map(256,256) clib.mapnik_map_load(map,"./sample/stylesheet.xml") clib.mapnik_map_zoom_all(map) clib.mapnik_map_render_to_file(map,"lua-test.png") clib.mapnik_map_free(map)
local ProgressBar = class "ProgressBar" local Tween = require "libs.tween" local util = require "util.util" local progressBarAnimationSpeed = 3 function ProgressBar:init(imageName, x, y, scale, initialValue, anchorSide, offsetLeft, offsetRight, fadeIn) self.positionX, self.positionY = x or 0, y or 0 self.value = 0 self.image = love.graphics.newImage("sprites/" .. imageName .. ".png") self.fillImage = love.graphics.newImage("sprites/" .. imageName .. "_fill.png") self.scale = scale or 1.0 self.drawContext = "ui" self.anchorSide = anchorSide or "left" self.offsetLeft = offsetLeft or 0 self.offsetRight = offsetRight or 0 self.fillOffsetX = 0 self.isAnimating = false if fadeIn then self:animateToValue(initialValue) else self:setValue(initialValue) end self.targetValue = self.value end function ProgressBar:setPosition(x, y) self.positionX, self.positionY = x or 0, y or 0 end function ProgressBar:setScale(scale) self.scale = scale end function ProgressBar:animateToValue(targetValue, tweenFunction) if targetValue == self.targetValue then return end tweenFunction = tweenFunction or "outQuint" self.isAnimating = true self.targetValue = util.fract(targetValue) self.valueTween = Tween.new(progressBarAnimationSpeed, self, {value = util.fract(targetValue)}, tweenFunction) end -- @param [Float] value in interval [0, 1] function ProgressBar:setValue(value, isAnimation) value = value or self.value if value < 0.0 then value = 0.0 end if value > 1.0 then value = 1.0 end self.value = value if not isAnimation then self.isAnimating = false end local width, height = self.fillImage:getDimensions() width = width - self.offsetLeft - self.offsetRight local widthOffset = 0 if self.anchorSide == "right" then self.fillOffsetX = math.floor(width * (1.0 - value)) + self.offsetLeft widthOffset = self.offsetRight else widthOffset = self.offsetLeft end local quadWidth = math.floor(width * util.fract(value)) + widthOffset self.quad = love.graphics.newQuad(self.fillOffsetX, 0, quadWidth, height, self.fillImage:getDimensions()) end function ProgressBar:update(dt) if not self.isAnimating then return false end local previousValue = self.value local isFinished = self.valueTween:update(dt) if isFinished then self.isAnimating = false end if previousValue ~= self.value then self:setValue(self.value, true) end end function ProgressBar:draw() local positionX, positionY = self.positionX, self.positionY if self.anchorSide == "right" then positionX = love.graphics.getWidth() - self.scale * self.image:getWidth() - positionX end love.graphics.setColor(255, 255, 255) love.graphics.draw(self.fillImage, self.quad, positionX + self.fillOffsetX, positionY, 0, self.scale) love.graphics.draw(self.image, positionX, positionY, 0, self.scale) end return ProgressBar
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local voices = { {text = 'Passages to Thais, Darashia, Edron, Venore, Ankrahmun, Liberty Bay and Yalahar.'} } npcHandler:addModule(VoiceModule:new(voices)) -- Travel local function addTravelKeyword(keyword, cost, destination) local travelKeyword = keywordHandler:addKeyword({keyword}, StdModule.say, {npcHandler = npcHandler, text = 'Do you seek a passage to ' .. keyword:titleCase() .. ' for |TRAVELCOST|?', cost = cost, discount = 'postman'}) travelKeyword:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = true, cost = cost, discount = 'postman', destination = destination}) travelKeyword:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, text = 'We would like to serve you some time.', reset = true}) end addTravelKeyword('edron', 150, Position(33173, 31764, 6)) addTravelKeyword('venore', 160, Position(32954, 32022, 6)) addTravelKeyword('yalahar', 260, Position(32816, 31272, 6)) addTravelKeyword('ankrahmun', 110, Position(33092, 32883, 6)) addTravelKeyword('darashia', 180, Position(33289, 32480, 6)) addTravelKeyword('thais', 160, Position(32310, 32210, 6)) addTravelKeyword('liberty bay', 50, Position(32285, 32892, 6)) -- Kick keywordHandler:addKeyword({'kick'}, StdModule.kick, {npcHandler = npcHandler, destination = Position(32536, 32791, 6)}) -- Basic keywordHandler:addKeyword({'sail'}, StdModule.say, {npcHandler = npcHandler, text = 'Where do you want to go - {Thais}, {Darashia}, {Venore}, {Liberty Bay}, {Ankrahmun}, {Yalahar} or {Edron?}'}) keywordHandler:addKeyword({'passage'}, StdModule.say, {npcHandler = npcHandler, text = 'Where do you want to go - {Thais}, {Darashia}, {Venore}, {Liberty Bay}, {Ankrahmun}, {Yalahar} or {Edron?}'}) keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, text = 'Im the captain of the Poodle, the proudest ship on all oceans.'}) keywordHandler:addKeyword({'captain'}, StdModule.say, {npcHandler = npcHandler, text = 'I am the captain of this ship.'}) keywordHandler:addKeyword({'port hope'}, StdModule.say, {npcHandler = npcHandler, text = "That's where we are."}) keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, text = 'It\'s Charles.'}) keywordHandler:addKeyword({'svargrond'}, StdModule.say, {npcHandler = npcHandler, text = 'I\'m sorry, but we don\'t serve the routes to the Ice Islands.'}) npcHandler:setMessage(MESSAGE_GREET, "Ahoy. Where can I sail you today?") npcHandler:setMessage(MESSAGE_FAREWELL, "Bye.") npcHandler:setMessage(MESSAGE_WALKAWAY, "Bye.") npcHandler:addModule(FocusModule:new())
document = require "document" json = require "json" local Set = {} Set.__index = Set setmetatable(Set, { __call = function(set, id, options) local self = {} self.__index = self self._id = id return setmetatable(self, { __index = Set }) end }) function Set.config(options) box.cfg(options) end -- Server function Set.server(options) local router = require "http.router".new() local server = require "http.server".new(options.host or "localhost", options.port or 2608, { log_requests = options.log and options.log.requests or true, log_errors = options.log and options.log.errors or true, display_errors = false, }) for _, module in next, options.modules do require(module):init(router) end server:set_router(router) server:start() end function Set.error(code, text) return {status = code, body = text} end function Set.json(data) return { status = 200, headers = { ["content-type"] = "application/json;charset=utf8" }, body = json.encode(data) } end -- Document function Set.remove(set, data) return document.delete(box.space[set], data) end function Set.insert(set, data) return document.insert(box.space[set], data) end function Set.get(set, data) return document.get(box.space[set], data) end function Set.select(set, data) return document.select(box.space[set], data) end -- Schema function Set:init(router) box.once(("schema.%s"):format(self._id), function() if not self._schema then return end for id, schema in next, self._schema do repeat if not schema or not schema.options then break end if schema.sequence then box.schema.sequence.create(id, schema.sequence) end local space = box.schema.space.create(id, schema.options) if schema.index then for _, index in next, schema.index do document.create_index(space, index.type, index.options) end end until true end end, self) box.once(("default.%s"):format(self._id), function() if not self._default then return end for _, callback in next, self._default do repeat if type(callback) ~= "function" then break end for set, values in next, callback(self) do for _, value in next, values do document.insert(box.space[set], value) end end until true end end, self) if router and self._routes then for path, route in next, self._routes do router:route(route.options, route.callback) end end end function Set:schema(id, options) if not id or not options then return end self._schema = self._schema or {} self._schema[id] = options end function Set:default(callback) if not callback then return end self._default = self._default or {} table.insert(self._default, callback) end function Set:next() return box.sequence[self._id]:next() end -- Router function Set:call(callback, ...) local status, result = pcall(callback, self, ...) if status then return self.json(result) end return self.error( result.code or result[1] or 500, result.text or result[2] or "server.internal_error" ) end function Set:create(callback) self:router("post", ("/%s"):format(self._id), function(http) local data = http:json() if not data then return self.error(400, "http.bad_request") end return self:call(callback, data) end) end function Set:read(callback) self:router("get", ("/%s/:id"):format(self._id), function(http) local id = tonumber(http:stash("id")) if not id then return self.error(400, "http.bad_request") end return self:call(callback, id) end) end function Set:update(callback) self:router("patch", ("/%s/:id"):format(self._id), function(http) local id = tonumber(http:stash("id")) if not id then return self.error(400, "http.bad_request") end local data = http:json() if not data then return self.error(400, "http.bad_request") end return self:call(callback, id, data) end) end function Set:delete(callback) self:router("delete", ("/%s/:id"):format(self._id), function(http) local id = tonumber(http:stash("id")) if not id then return self.error(400, "http.bad_request") end return self:call(callback, id) end) end function Set:route(method, path, callback, options) self:router(method, path, function(http) return self:call(callback, http:param()) end) end function Set:router(method, path, callback, options) self._routes = self._routes or {} local route = {} route.callback = callback route.options = options or {} route.options.method = method route.options.path = path table.insert(self._routes, route) end return Set
--[[ Listener is an extension to deal with triggers which is designed by Observer Model. Require: subject Member: _object_ - object using the listener _registry_ - record what event is registered. Function: new() - create a new instance object() - return the object of a listener addBroadcast(name, arg, callback) - add a broadcast to the event source. name - event name arg - event arg whose type is string callback - callback function addEvent(name, callback) - add an event to the listener. name - event name callback - callback function onTick(name, ...) - call all callback functions of the event we assigned. name - event name ... - args you want to put. --]] local require, xpcall, select = require, xpcall, select local cls = require 'std.class'("Listener") local error = function() return false end local subject = select(2, xpcall(require, error, 'framework.listener.subject')) local template = select(2, xpcall(require, error, "framework.listener.template")) function cls:_new(obj) local this = { _event_ = {}, _object_ = obj, _registry_ = {}, -- 記錄有沒有重複對主題註冊事件 } if subject then subject.addListener(this) end return this end function cls:object() return self._object_ end function cls:isRegistered(name) return self._registry_[name] end function cls:add(name, arg, callback) local type = type if not(type(name) == 'string' or type(name) == 'table') then return self end local event -- NOTE: 解析只有名字或是一個事件的情況 if not (arg or callback) then if type(name) == 'table' then event = name name = name.name elseif template and template[name] then event = template[name] else return self end else event = {name=name, arg=arg, callback=callback} end if not self._event_[name] then self._event_[name] = {} end self._event_[name][#self._event_[name] + 1] = event if not self._registry_[name] and subject and subject.add(self, name, arg) then self._registry_[name] = true end return self end function cls:onTick(name, ...) if not self._event_[name] then return false end -- 把 self 加入到參數列裡 local arg = {...} arg[#arg+1] = self local unpack = table.unpack for _, event in ipairs(self._event_[name]) do event.callback(unpack(arg)) end return self end function cls:iterator(name) if not self._event_[name] then return function() return nil end -- 防止for iterator報錯 end local i = 1 return function() if i > #self._event_[name] then return end local arg, callback = self._event_[name][i].arg or "", self._event_[name][i].callback i = i + 1 return arg, callback end end return cls
big_gothic = love.graphics.newFont("gothic_pixel.ttf", 30) -- *keep these* titleFont = love.graphics.newFont("gothic_pixel.ttf", 86) -- *keep these* thin = love.graphics.newFont("thintel.ttf", 16) blokk = love.graphics.newFont("BLOKKRegular.ttf", 10) dialogueBox = { x = 350, y = 0, w = 450, h = 100, backgroundDraw = false } --[[patientSayings = { "Wowee, I am sick doc!", "Please fix my head, it hurts!", "I got eggs in my skin! Is there no cure? I tried everything!" }--]] patientSayings = {} local buttonTimerMax = 0.2 local buttonTimer = 0 function loadSayings() --load all sayings from patient and store in patient sayings to be displayed patientSayings = getDialogue() end local i = 1 function updateDialogue(dt) -- if mouse clicks dialogueBox if love.mouse.getX() > dialogueBox.x and love.mouse.getX() < dialogueBox.x + dialogueBox.w and love.mouse.getY() > dialogueBox.y and love.mouse.getY() < dialogueBox.y + dialogueBox.h and love.mouse.isDown(1) and buttonTimer <= 0 then buttonTimer = buttonTimerMax dialogueBox.backgroundDraw = true -- set background draw to true if i < table.getn(patientSayings) then i = i + 1 elseif i >= table.getn(patientSayings) then i = 1 end end if buttonTimer <= 0 then -- if button timer runs out dialogueBox.backgroundDraw = false end -- decrement button Timer if buttonTimer > 0 then buttonTimer = buttonTimer - (1 * dt) end end function drawDialogue() if dialogueBox.backgroundDraw then -- if clicked draw background love.graphics.setColor(255, 0, 0, 150) -- set color to red love.graphics.rectangle("fill", 350, 0, 450, 100) love.graphics.setColor(255, 255, 255, 255) end love.graphics.setFont(big_gothic) love.graphics.printf(patientSayings[i], 360, 5, 440) love.graphics.setFont(thin) love.graphics.printf(i, 770, 80, 50) love.graphics.printf("/", 775, 80, 50) love.graphics.printf(table.getn(patientSayings), 780, 80, 50) end
includeFile("custom_content/tangible/holiday/life_day/rewards_09/lifeday_costume.lua") includeFile("custom_content/tangible/holiday/life_day/rewards_09/lifeday_decor_cookie.lua") includeFile("custom_content/tangible/holiday/life_day/rewards_09/lifeday_decor_fruitcake.lua") includeFile("custom_content/tangible/holiday/life_day/rewards_09/lifeday_decor_hoth_chocolate.lua") includeFile("custom_content/tangible/holiday/life_day/rewards_09/lifeday_decor_varactyl_nog.lua") includeFile("custom_content/tangible/holiday/life_day/rewards_09/lifeday_fireplace_01.lua") includeFile("custom_content/tangible/holiday/life_day/rewards_09/lifeday_fireplace_02.lua") includeFile("custom_content/tangible/holiday/life_day/rewards_09/lifeday_lamp_01.lua") includeFile("custom_content/tangible/holiday/life_day/rewards_09/lifeday_lamp_02.lua") includeFile("custom_content/tangible/holiday/life_day/rewards_09/lifeday_ornament.lua") includeFile("custom_content/tangible/holiday/life_day/rewards_09/lifeday_painting.lua")
local url_to_slack_channel = "https://hooks.slack.com/services/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" --local url_to_slack_channel = "https://httpbin.org/post" function slack(msg) http.post(url_to_slack_channel, 'Content-Type: text/xml\r\n', '{"text": "Its works. Message from agent '..msg..'" }', slack_cb) end local function slack_cb(code, data) if (code < 0) then print("HTTP request failed") else print(code, data) end end return { slack = slack, }
-- Natural Selection 2 Competitive Mod -- Source located at - https://github.com/xToken/CompMod -- lua\CompMod\TechMaps\AlienTechMap\replace.lua -- - Dragon local function CheckHasTech(techId) local techTree = GetTechTree() return techTree ~= nil and techTree:GetHasTech(techId) end local function SetShellIcon(icon) if CheckHasTech(kTechId.ThreeShells) then icon:SetTexturePixelCoordinates(GUIUnpackCoords(GetTextureCoordinatesForIcon(kTechId.ThreeShells))) elseif CheckHasTech(kTechId.TwoShells) then icon:SetTexturePixelCoordinates(GUIUnpackCoords(GetTextureCoordinatesForIcon(kTechId.TwoShells))) else icon:SetTexturePixelCoordinates(GUIUnpackCoords(GetTextureCoordinatesForIcon(kTechId.Shell))) end end local function SetVeilIcon(icon) if CheckHasTech(kTechId.ThreeVeils) then icon:SetTexturePixelCoordinates(GUIUnpackCoords(GetTextureCoordinatesForIcon(kTechId.ThreeVeils))) elseif CheckHasTech(kTechId.TwoVeils) then icon:SetTexturePixelCoordinates(GUIUnpackCoords(GetTextureCoordinatesForIcon(kTechId.TwoVeils))) else icon:SetTexturePixelCoordinates(GUIUnpackCoords(GetTextureCoordinatesForIcon(kTechId.Veil))) end end local function SetSpurIcon(icon) if CheckHasTech(kTechId.ThreeSpurs) then icon:SetTexturePixelCoordinates(GUIUnpackCoords(GetTextureCoordinatesForIcon(kTechId.ThreeSpurs))) elseif CheckHasTech(kTechId.TwoSpurs) then icon:SetTexturePixelCoordinates(GUIUnpackCoords(GetTextureCoordinatesForIcon(kTechId.TwoSpurs))) else icon:SetTexturePixelCoordinates(GUIUnpackCoords(GetTextureCoordinatesForIcon(kTechId.Spur))) end end kAlienTechMapYStart = 0 kAlienTechMapIconSize = Vector(60, 60, 0) kAlienTechMapSize = 16 kAlienTechMap = { { {kTechId.Whip}, {kTechId.WhipBombard}, {}, {kTechId.Shift}, {kTechId.ShiftEnergize}, {}, {kTechId.Shade}, {kTechId.ShadeInk}, {}, {kTechId.Crag}, {kTechId.HealWave}, {}, {kTechId.Harvester} }, { {kTechId.Veil, SetVeilIcon}, {}, {kTechId.OffensiveTraits, nil, "Offense Traits" }, {}, {}, {}, {kTechId.DefensiveTraits, nil, "Defense Traits" }, {}, {kTechId.Shell, SetShellIcon} }, { {kTechId.Crush}, {}, {kTechId.Aura}, {}, {}, {}, {}, {}, {kTechId.Carapace}, {}, {kTechId.Regeneration} }, { {kTechId.Spur, SetSpurIcon}, {}, {kTechId.MovementTraits, nil, "Movement Traits" }, {}, {}, {}, {kTechId.AdditionalTraitSlot1, nil, "2nd Trait Slot"}, {}, {kTechId.AdditionalTraitSlot2, nil, "3rd Trait Slot"}, {}, {}, {} }, { {kTechId.Celerity}, {}, {kTechId.Adrenaline}, {}, {}, {}, {}, {kTechId.NutrientMist, nil, "Nutrient Mist" }, {}, {}, {}, {kTechId.StructureMenu, nil, "Build Structures"}, {kTechId.EnzymeCloud}, {kTechId.ParasiteCloud, nil, "Parasite Cloud" } }, { {}, {}, {}, {}, {}, {}, {kTechId.Hive}, {}, {}, {}, {}, {}, {kTechId.Drifter} }, { {}, {kTechId.GorgeTunnelTech}, {}, {kTechId.BileBomb}, {}, {kTechId.HealingRoost}, {}, {kTechId.MetabolizeEnergy}, {}, { kTechId.Charge}, {}, {kTechId.AdvancedStructureMenu, nil, "Build Adv Structures"}, {kTechId.Hallucinate}, {kTechId.TeleportStructure, nil, "Echo" } }, { {}, {}, {}, {}, {}, {}, {kTechId.TwoHives, nil, "Two Hives" }, {}, {}, {}, {}, {} }, { {}, {}, {}, {kTechId.Leap}, {}, {kTechId.Umbra}, {}, {kTechId.MetabolizeHealth}, {}, {kTechId.BoneShield} }, { {}, {}, {}, {}, {}, {}, {kTechId.ThreeHives, nil, "Three Hives" } }, { {}, {}, {}, {kTechId.Xenocide}, {}, {kTechId.Spores}, {}, {kTechId.Stab}, {}, {kTechId.Stomp} } } kAlienLines = { GetLinePositionForTechMap(kAlienTechMap, kTechId.Whip, kTechId.WhipBombard), GetLinePositionForTechMap(kAlienTechMap, kTechId.Shift, kTechId.ShiftEnergize), GetLinePositionForTechMap(kAlienTechMap, kTechId.Shade, kTechId.ShadeInk), GetLinePositionForTechMap(kAlienTechMap, kTechId.Crag, kTechId.HealWave), GetLinePositionForTechMap(kAlienTechMap, kTechId.Drifter, kTechId.TeleportStructure), GetLinePositionForTechMap(kAlienTechMap, kTechId.Drifter, kTechId.EnzymeCloud), GetLinePositionForTechMap(kAlienTechMap, kTechId.Drifter, kTechId.ParasiteCloud), GetLinePositionForTechMap(kAlienTechMap, kTechId.Drifter, kTechId.Hallucinate), GetLinePositionForTechMap(kAlienTechMap, kTechId.Drifter, kTechId.StructureMenu), GetLinePositionForTechMap(kAlienTechMap, kTechId.Drifter, kTechId.AdvancedStructureMenu), GetLinePositionForTechMap(kAlienTechMap, kTechId.Hive, kTechId.NutrientMist), GetLinePositionForTechMap(kAlienTechMap, kTechId.Hive, kTechId.Drifter), GetLinePositionForTechMap(kAlienTechMap, kTechId.Hive, kTechId.DefensiveTraits), GetLinePositionForTechMap(kAlienTechMap, kTechId.Hive, kTechId.OffensiveTraits), GetLinePositionForTechMap(kAlienTechMap, kTechId.Hive, kTechId.MovementTraits), GetLinePositionForTechMap(kAlienTechMap, kTechId.Hive, kTechId.AdditionalTraitSlot1), GetLinePositionForTechMap(kAlienTechMap, kTechId.AdditionalTraitSlot1, kTechId.AdditionalTraitSlot2), GetLinePositionForTechMap(kAlienTechMap, kTechId.DefensiveTraits, kTechId.Shell), GetLinePositionForTechMap(kAlienTechMap, kTechId.OffensiveTraits, kTechId.Veil), GetLinePositionForTechMap(kAlienTechMap, kTechId.MovementTraits, kTechId.Spur), GetLinePositionForTechMap(kAlienTechMap, kTechId.Shell, kTechId.Carapace), GetLinePositionForTechMap(kAlienTechMap, kTechId.Shell, kTechId.Regeneration), GetLinePositionForTechMap(kAlienTechMap, kTechId.Veil, kTechId.Crush), GetLinePositionForTechMap(kAlienTechMap, kTechId.Veil, kTechId.Aura), GetLinePositionForTechMap(kAlienTechMap, kTechId.Spur, kTechId.Celerity), GetLinePositionForTechMap(kAlienTechMap, kTechId.Spur, kTechId.Adrenaline), GetLinePositionForTechMap(kAlienTechMap, kTechId.Hive, kTechId.GorgeTunnelTech), GetLinePositionForTechMap(kAlienTechMap, kTechId.Hive, kTechId.BileBomb), GetLinePositionForTechMap(kAlienTechMap, kTechId.Hive, kTechId.HealingRoost), GetLinePositionForTechMap(kAlienTechMap, kTechId.Hive, kTechId.MetabolizeEnergy), GetLinePositionForTechMap(kAlienTechMap, kTechId.Hive, kTechId.Charge), GetLinePositionForTechMap(kAlienTechMap, kTechId.Hive, kTechId.TwoHives), GetLinePositionForTechMap(kAlienTechMap, kTechId.TwoHives, kTechId.Leap), GetLinePositionForTechMap(kAlienTechMap, kTechId.TwoHives, kTechId.Umbra), GetLinePositionForTechMap(kAlienTechMap, kTechId.TwoHives, kTechId.MetabolizeHealth), GetLinePositionForTechMap(kAlienTechMap, kTechId.TwoHives, kTechId.BoneShield), GetLinePositionForTechMap(kAlienTechMap, kTechId.TwoHives, kTechId.ThreeHives), GetLinePositionForTechMap(kAlienTechMap, kTechId.ThreeHives, kTechId.Xenocide), GetLinePositionForTechMap(kAlienTechMap, kTechId.ThreeHives, kTechId.Spores), GetLinePositionForTechMap(kAlienTechMap, kTechId.ThreeHives, kTechId.Stab), GetLinePositionForTechMap(kAlienTechMap, kTechId.ThreeHives, kTechId.Stomp), }
local widget = require 'ui_widget' local oop = require 'minioop' local button = oop.class() oop.extend(button, widget) local function hex_to_rgb(hex) hex = hex:gsub("#", "") return tonumber(hex:sub(1,2), 16), tonumber(hex:sub(3,4), 16), tonumber(hex:sub(5,6), 16), #hex > 7 and tonumber(hex:sub(7,8) or 255) or 255 end function button:new(ox, oy, width, height, text) local obj = widget:new(ox, oy, width, height) -- _tc == _text_conf obj._tc = {} obj._tc.text = text or '' obj._tc.color = '#000000' obj._tc.size = 12 obj._tc.font = love.graphics.newFont(obj._tc.size) obj._cb = false obj._is_pressed = false return oop.object(self, obj) end function button:set_callback() end function button:set_text_size(size) self._tc.size = size end function button:set_text_color(hex_color) self._tc.color = hex_color end function button:on_mousepressed(x, y, button) if not self._is_pressed and self:check_collision(x, y) and button == 1 then self._is_pressed = true return true end end function button:on_mousereleased(x, y, button) if self._is_pressed and self:check_collision(x, y) then if self._cb then self._cb() end self._is_pressed = false return true end end function button:on_mousemoved(x, y, dx, dy) if self._is_pressed and not self:check_collision(x, y) then self._is_pressed = false return true end end function button:draw() if self._is_pressed then self._style.button_pressed:draw_back(self._pos.ox, self._pos.oy, self._w, self._h) -- love.graphics.setColor(0, 255, 0) else self._style.button_normal:draw_back(self._pos.ox, self._pos.oy, self._w, self._h) -- love.graphics.setColor(255, 0, 0) end -- love.graphics.line(self._pos.ox, self._pos.oy, self._pos.x, self._pos.oy) -- love.graphics.line(self._pos.x, self._pos.oy, self._pos.x, self._pos.y) -- love.graphics.line(self._pos.x, self._pos.y, self._pos.ox, self._pos.y) -- love.graphics.line(self._pos.ox, self._pos.y, self._pos.ox, self._pos.oy) end return button
return {'kodak','kodde','koddebeier','koddig','koddigheid','kodde','kodaks','koddebeiers','kodden','koddige','koddiger','koddigst','koddigste','koddigheden'}
AuctionatorShoppingListTabMixin = {} local ListDeleted = Auctionator.ShoppingLists.Events.ListDeleted local ListSelected = Auctionator.ShoppingLists.Events.ListSelected local ListItemSelected = Auctionator.ShoppingLists.Events.ListItemSelected local EditListItem = Auctionator.ShoppingLists.Events.EditListItem local DialogOpened = Auctionator.ShoppingLists.Events.DialogOpened local DialogClosed = Auctionator.ShoppingLists.Events.DialogClosed function AuctionatorShoppingListTabMixin:OnLoad() Auctionator.Debug.Message("AuctionatorShoppingListTabMixin:OnLoad()") Auctionator.ShoppingLists.InitializeDialogs() self:SetUpEvents() self:SetUpAddItemDialog() self:SetUpEditItemDialog() self:SetUpExportDialog() self:SetUpImportDialog() -- Add Item button starts in the default state until a list is selected self.AddItem:Disable() self.ResultsListing:Init(self.DataProvider) end function AuctionatorShoppingListTabMixin:SetUpEvents() -- System Events self:RegisterEvent("AUCTION_HOUSE_CLOSED") -- Auctionator Events Auctionator.EventBus:RegisterSource(self, "Auctionator Shopping List Tab") Auctionator.EventBus:Register(self, { ListSelected, ListDeleted, ListItemSelected, EditListItem, DialogOpened, DialogClosed }) end function AuctionatorShoppingListTabMixin:SetUpAddItemDialog() self.addItemDialog = CreateFrame("Frame", "AuctionatorAddItemFrame", self, "AuctionatorShoppingItemTemplate") self.addItemDialog:Init(AUCTIONATOR_L_LIST_ADD_ITEM_HEADER, AUCTIONATOR_L_ADD_ITEM) self.addItemDialog:SetPoint("CENTER") self.addItemDialog:SetOnFinishedClicked(function(newItemString) self:AddItemToList(newItemString) end) end function AuctionatorShoppingListTabMixin:SetUpEditItemDialog() self.editItemDialog = CreateFrame("Frame", "AuctionatorEditItemFrame", self, "AuctionatorShoppingItemTemplate") self.editItemDialog:Init(AUCTIONATOR_L_LIST_EDIT_ITEM_HEADER, AUCTIONATOR_L_EDIT_ITEM) self.editItemDialog:SetPoint("CENTER") self.editItemDialog:SetOnFinishedClicked(function(newItemString) self:ReplaceItemInList(newItemString) end) end function AuctionatorShoppingListTabMixin:SetUpExportDialog() self.exportDialog = CreateFrame("Frame", "AuctionatorExportListFrame", self, "AuctionatorExportListTemplate") self.exportDialog:SetPoint("CENTER") end function AuctionatorShoppingListTabMixin:SetUpImportDialog() self.importDialog = CreateFrame("Frame", "AuctionatorImportListFrame", self, "AuctionatorImportListTemplate") self.importDialog:SetPoint("CENTER") end function AuctionatorShoppingListTabMixin:OnShow() if self.selectedList ~= nil then self.AddItem:Enable() end end function AuctionatorShoppingListTabMixin:OnEvent(event, ...) self.addItemDialog:ResetAll() self.addItemDialog:Hide() end function AuctionatorShoppingListTabMixin:ReceiveEvent(eventName, eventData) if eventName == ListSelected then self.selectedList = eventData self.AddItem:Enable() elseif eventName == ListDeleted and #Auctionator.ShoppingLists.Lists == 0 then -- If no more lists, need to clean up the UI self.Rename:Disable() self.AddItem:Disable() self.ManualSearch:Disable() elseif eventName == DialogOpened then self.AddItem:Disable() self.Export:Disable() self.Import:Disable() elseif eventName == DialogClosed then self.AddItem:Enable() self.Export:Enable() self.Import:Enable() elseif eventName == EditListItem then self.editingItemIndex = eventData self:EditItemClicked() end end function AuctionatorShoppingListTabMixin:AddItemToList(newItemString) if self.selectedList == nil then Auctionator.Utilities.Message( Auctionator.Locales.Apply("LIST_ADD_ERROR") ) return end table.insert(self.selectedList.items, newItemString) Auctionator.EventBus:Fire(self, Auctionator.ShoppingLists.Events.ListItemAdded, self.selectedList) end function AuctionatorShoppingListTabMixin:ReplaceItemInList(newItemString) if self.selectedList == nil then Auctionator.Utilities.Message( Auctionator.Locales.Apply("LIST_ADD_ERROR") ) return end self.selectedList.items[self.editingItemIndex] = newItemString Auctionator.EventBus:Fire(self, Auctionator.ShoppingLists.Events.ListItemReplaced, self.selectedList) end function AuctionatorShoppingListTabMixin:AddItemClicked() self.addItemDialog:Show() end function AuctionatorShoppingListTabMixin:EditItemClicked() self.editItemDialog:Show() self.editItemDialog:SetItemString(self.selectedList.items[self.editingItemIndex]) end function AuctionatorShoppingListTabMixin:ImportListsClicked() self.importDialog:Show() end function AuctionatorShoppingListTabMixin:ExportListsClicked() self.exportDialog:Show() end
-- Test if ":options" throws any exception. The options window seems to mess -- other tests, so restart nvim in the teardown hook local helpers = require('test.functional.helpers') local command, clear = helpers.command, helpers.clear describe('options', function() setup(clear) it('is working', function() command('options') end) end)
local premake = require('premake') local vstudio = require('vstudio') local vcxproj = vstudio.vcxproj local VsVcxItemDefinitionsGroupTests = test.declare('VsVcxItemDefinitionsGroupTests', 'vcxproj', 'vstudio') function VsVcxItemDefinitionsGroupTests.setup() vstudio.setTargetVersion(2015) end local function _execute(fn) workspace('MyWorkspace', function () fn() project('MyProject', function () end) end) local prj = vcxproj.prepare(vstudio.fetch(2015).workspaces['MyWorkspace'].projects['MyProject']) vcxproj.itemDefinitionGroup(prj) end --- -- Sanity check the overall structure with minimal settings; the handling of the -- individual child elements is tested elsewhere. --- function VsVcxItemDefinitionsGroupTests.sanityTest() _execute(function () configurations { 'Debug', 'Release' } end) test.capture [[ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <DebugInformationFormat>EditAndContinue</DebugInformationFormat> <Optimization>Disabled</Optimization> </ClCompile> <Link> <SubSystem>Console</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <WarningLevel>Level3</WarningLevel> <Optimization>MinSpace</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <MinimalRebuild>false</MinimalRebuild> <StringPooling>true</StringPooling> </ClCompile> <Link> <SubSystem>Console</SubSystem> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> </Link> </ItemDefinitionGroup> ]] end
local iec_104 = require('ckit.lib') libsocket = require "socket" libunix = require "socket.unix" socket = assert(libunix()) SOCKET_FILE = "/tmp/socket" os.remove(SOCKET_FILE) assert(socket:bind(SOCKET_FILE)) assert(socket:listen()) iec_104.fetch("meter1.example.com", 2404, SOCKET_FILE, true); iec_104.fetch("meter2.example.com", 2404, SOCKET_FILE, true); while true do conn = assert(socket:accept()) data=conn:receive("*a") -- receive all data from socket, until connection is closed if (data ~= nil) then print("Got data: " .. data) else print("Got no data!") end end
--[[ TheNexusAvenger Tests the ServerAuthorization class. --]] local NexusUnitTesting = require("NexusUnitTesting") local ServerAuthorizationUnitTest = NexusUnitTesting.UnitTest:Extend() local ServerAuthorization = require(game:GetService("ServerScriptService"):WaitForChild("MainModule"):WaitForChild("NexusAdmin"):WaitForChild("Server"):WaitForChild("ServerAuthorization")) local Configuration = require(game:GetService("ServerScriptService"):WaitForChild("MainModule"):WaitForChild("NexusAdmin"):WaitForChild("Common"):WaitForChild("Configuration")) --[[ Sets up the unit test. --]] function ServerAuthorizationUnitTest:Setup() --Create the component under testing. self.CuT = ServerAuthorization.new(Configuration.new({ Admins = { [2] = 3, [4] = 2, [5] = 2, }, GroupAdminLevels = { [11] = { [20] = 1, [40] = 2, [60] = 3, } }, })) --Set the game id and creator id. self.CuT.GameId = 1 self.CuT.CreatorId = 7 --Create the mock players. self.MockPlayers = { {UserId=1}, {UserId=2}, {UserId=3}, {UserId=4}, {UserId=5}, {UserId=6}, {UserId=25691148}, {UserId=7}, } --Mock the GroupService. self.CuT.GroupService = { GetGroupsAsync = function(self,Id) if Id == 3 then return { { Id = 12, Rank = 70, }, } elseif Id == 4 then return { { Id = 11, Rank = 70, }, } elseif Id == 5 then return { { Id = 11, Rank = 70, }, } elseif Id == 6 then return { { Id = 11, Rank = 40, }, } else return {} end end } --Add the players. for _,MockPlayer in pairs(self.MockPlayers) do self.CuT:InitializePlayer(MockPlayer) end end --[[ Tests the GetAdminLevel method. --]] NexusUnitTesting:RegisterUnitTest(ServerAuthorizationUnitTest.new("GetAdminLevel"):SetRun(function(self) --Assert that the admin levels are correct. self:AssertEquals(self.CuT:GetAdminLevel(self.MockPlayers[1]),-1) self:AssertEquals(self.CuT:GetAdminLevel(self.MockPlayers[2]),3) self:AssertEquals(self.CuT:GetAdminLevel(self.MockPlayers[3]),-1) self:AssertEquals(self.CuT:GetAdminLevel(self.MockPlayers[4]),3) self:AssertEquals(self.CuT:GetAdminLevel(self.MockPlayers[5]),3) self:AssertEquals(self.CuT:GetAdminLevel(self.MockPlayers[6]),2) self:AssertEquals(self.CuT:GetAdminLevel(self.MockPlayers[7]),0) self:AssertEquals(self.CuT:GetAdminLevel(self.MockPlayers[8]),5) --Set an admin level and assert that it is correct. self.CuT:SetAdminLevel(self.MockPlayers[2],5) self:AssertEquals(self.CuT:GetAdminLevel(self.MockPlayers[2]),5) end)) return true
-- todo -- 24x7 -- Fuel Stations -- Ammunation -- Medical supplies -- other various stores
-- File: Axe.lua -- Author: EroicaCpp (https://github.com/Eroica-cpp/dota2scripts) -- Version: 1.0 -- Release Date: 2017/6/26 local Utility = require("Utility") local Axe = {} Axe.optionAutoItem = Menu.AddOption({"Hero Specific", "Axe"}, "Auto Use Items", "Auto use items like blademail, lotus when calling") Axe.optionAutoBattleHunger = Menu.AddOption({"Hero Specific", "Axe"}, "Auto Battle Hunger", "Auto cast battle hunger to the enemy that you are attacking") Axe.optionBlinkHelper = Menu.AddOption({"Hero Specific", "Axe"}, "Blink Helper", "Auto blink to best position when calling") Axe.optionAutoInitiate = Menu.AddOption({"Hero Specific", "Axe"}, "Auto Initiate", "Auto initiate once see enemy heroes (can be turn on/off by key)") Axe.key = Menu.AddKeyOption({"Hero Specific", "Axe"}, "Auto Initiate Key", Enum.ButtonCode.KEY_E) Axe.font = Renderer.LoadFont("Tahoma", 24, Enum.FontWeight.EXTRABOLD) local shouldAutoInitiate = false -- blink to best position before call function Axe.OnPrepareUnitOrders(orders) if not orders then return true end local myHero = Heroes.GetLocal() if not myHero then return true end if (not Entity.IsAlive(myHero)) or NPC.IsStunned(myHero) then return true end if Menu.IsEnabled(Axe.optionAutoBattleHunger) then Axe.AutoBattleHunger(myHero, orders) end if Menu.IsEnabled(Axe.optionBlinkHelper) then Axe.BlinkHelper(myHero, orders) end return true end function Axe.AutoBattleHunger(myHero, orders) if not myHero or not orders then return end if orders.order ~= Enum.UnitOrder.DOTA_UNIT_ORDER_ATTACK_MOVE and orders.order ~= Enum.UnitOrder.DOTA_UNIT_ORDER_ATTACK_TARGET then return end if NPC.IsSilenced(myHero) or NPC.IsStunned(myHero) or not Entity.IsAlive(myHero) then return end if NPC.HasState(myHero, Enum.ModifierState.MODIFIER_STATE_INVISIBLE) then return end if NPC.HasModifier(myHero, "modifier_teleporting") then return end if NPC.IsChannellingAbility(myHero) then return end local battle_hunger = NPC.GetAbility(myHero, "axe_battle_hunger") if not battle_hunger or not Ability.IsCastable(battle_hunger, NPC.GetMana(myHero)) then return end if not orders.target or not NPC.IsHero(orders.target) or Entity.IsSameTeam(myHero, orders.target) then return end if NPC.HasModifier(orders.target, "modifier_axe_battle_hunger") then return end if NPC.HasState(orders.target, Enum.ModifierState.MODIFIER_STATE_MAGIC_IMMUNE) then return end if NPC.HasState(orders.target, Enum.ModifierState.MODIFIER_STATE_INVULNERABLE) then return end local range = 750 if not NPC.IsEntityInRange(myHero, orders.target, range) then return end Ability.CastTarget(battle_hunger, orders.target) end function Axe.BlinkHelper(myHero, orders) if not myHero or not orders then return end if orders.order == Enum.UnitOrder.DOTA_UNIT_ORDER_TRAIN_ABILITY then return end if not orders.ability or not Entity.IsAbility(orders.ability) then return end if Ability.GetName(orders.ability) ~= "axe_berserkers_call" then return end if not NPC.HasItem(myHero, "item_blink", true) then return end local blink = NPC.GetItem(myHero, "item_blink", true) if not blink or not Ability.IsCastable(blink, 0) then return end local call_radius = 300 local blink_radius = 1200 local enemyHeroes = NPC.GetHeroesInRadius(myHero, blink_radius, Enum.TeamType.TEAM_ENEMY) if not enemyHeroes or #enemyHeroes <= 0 then return end local pos = Utility.BestPosition(enemyHeroes, call_radius) if pos then Ability.CastPosition(blink, pos) end end -- auto use items when calling enemy heroes (blademail, lotus, etc) function Axe.OnUpdate() if not Menu.IsEnabled(Axe.optionAutoItem) then return end local myHero = Heroes.GetLocal() if not myHero or not NPC.HasModifier(myHero, "modifier_axe_berserkers_call_armor") then return end if (not Entity.IsAlive(myHero)) or NPC.IsStunned(myHero) then return end -- local mod = NPC.GetModifier(myHero, "modifier_axe_berserkers_call_armor") -- if mod and GameRules.GetGameTime() - Modifier.GetCreationTime(mod) > 0.1 then return end local call_radius = 300 local enemyHeroes = NPC.GetHeroesInRadius(myHero, call_radius, Enum.TeamType.TEAM_ENEMY) if #enemyHeroes > 0 then Utility.PopDefensiveItems(myHero) end end -- auto initiate when enemy heroes are near -- (this mode can be turn on/off by pressing key) function Axe.OnDraw() if not Menu.IsEnabled(Axe.optionAutoInitiate) then return end local myHero = Heroes.GetLocal() if not myHero or NPC.GetUnitName(myHero) ~= "npc_dota_hero_axe" then return end if (not Entity.IsAlive(myHero)) or NPC.IsStunned(myHero) or NPC.IsSilenced(myHero) then return end if Menu.IsKeyDownOnce(Axe.key) then shouldAutoInitiate = not shouldAutoInitiate end if not shouldAutoInitiate then return end -- draw text when auto initiate key is up local pos = Entity.GetAbsOrigin(myHero) local x, y, visible = Renderer.WorldToScreen(pos) Renderer.SetDrawColor(0, 255, 0, 255) Renderer.DrawTextCentered(Axe.font, x, y, "Auto", 1) if not NPC.HasItem(myHero, "item_blink", true) then return end local blink = NPC.GetItem(myHero, "item_blink", true) if not blink or not Ability.IsCastable(blink, 0) then return end local call = NPC.GetAbilityByIndex(myHero, 0) if not call or not Ability.IsCastable(call, NPC.GetMana(myHero)) then return end local call_radius = 300 local blink_radius = 1200 local enemyHeroes = NPC.GetHeroesInRadius(myHero, blink_radius, Enum.TeamType.TEAM_ENEMY) if not enemyHeroes or #enemyHeroes <= 0 then return end local pos = Utility.BestPosition(enemyHeroes, call_radius) if pos then Ability.CastPosition(blink, pos) end Ability.CastNoTarget(call) end return Axe
--rpc_server.lua local next = next local pairs = pairs local tunpack = table.unpack local log_err = logger.err local log_info = logger.info local qxpcall = quanta.xpcall local signalquit = signal.quit local FlagMask = enum("FlagMask") local KernCode = enum("KernCode") local NetwkTime = enum("NetwkTime") local SUCCESS = KernCode.SUCCESS local event_mgr = quanta.get("event_mgr") local thread_mgr = quanta.get("thread_mgr") local socket_mgr = quanta.get("socket_mgr") local statis_mgr = quanta.get("statis_mgr") local perfeval_mgr = quanta.get("perfeval_mgr") local RpcServer = singleton() local prop = property(RpcServer) prop:reader("ip", "") --监听ip prop:reader("port", 0) --监听端口 prop:reader("clients", {}) prop:reader("listener", nil) function RpcServer:__init() end --初始化 --induce:根据index推导port function RpcServer:setup(ip, port, induce) if not ip or not port then log_err("[RpcServer][setup] ip:%s or port:%s is nil", ip, port) signalquit() end local real_port = induce and (port + quanta.index - 1) or port self.listener = socket_mgr.listen(ip, real_port) if not self.listener then log_err("[RpcServer][setup] now listen %s:%s failed", ip, real_port) signalquit() end self.ip, self.port = ip, real_port log_info("[RpcServer][setup] now listen %s:%s success!", ip, real_port) self.listener.on_accept = function(client) qxpcall(self.on_socket_accept, "on_socket_accept: %s", self, client) end event_mgr:add_listener(self, "rpc_heartbeat") end --rpc事件 function RpcServer:on_socket_rpc(client, rpc, session_id, rpc_flag, source, ...) client.alive_time = quanta.now if session_id == 0 or rpc_flag == FlagMask.REQ then local function dispatch_rpc_message(...) local eval = perfeval_mgr:begin_eval("rpc." .. rpc) local rpc_datas = event_mgr:notify_listener(rpc, client, ...) if session_id > 0 then client.call_rpc(session_id, FlagMask.RES, rpc, tunpack(rpc_datas)) end perfeval_mgr:end_eval(eval) end thread_mgr:fork(dispatch_rpc_message, ...) return end thread_mgr:response(session_id, ...) end --连接关闭 function RpcServer:on_socket_error(token, err) local client = self.clients[token] if client then self.clients[token] = nil event_mgr:notify_listener("on_socket_error", client, token, err) end end --accept事件 function RpcServer:on_socket_accept(client) client.set_timeout(NetwkTime.ROUTER_TIMEOUT) self.clients[client.token] = client client.call_rpc = function(session_id, rpc_flag, rpc, ...) local send_len = client.call(session_id, rpc_flag, 0, rpc, ...) if send_len < 0 then statis_mgr:statis_notify("on_rpc_send", rpc, send_len) log_err("[RpcServer][call_rpc] call failed! code:%s", send_len) return false end return true, SUCCESS end client.on_call = function(recv_len, session_id, rpc_flag, source, rpc, ...) statis_mgr:statis_notify("on_rpc_recv", rpc, recv_len) qxpcall(self.on_socket_rpc, "on_socket_rpc: %s", self, client, rpc, session_id, rpc_flag, source, ...) end client.on_error = function(token, err) qxpcall(self.on_socket_error, "on_socket_error: %s", self, token, err) end --通知收到新client event_mgr:notify_listener("on_socket_accept", client) end --send接口 function RpcServer:call(client, rpc, ...) local session_id = thread_mgr:build_session_id() if client.call_rpc(session_id, FlagMask.REQ, rpc, ...) then return thread_mgr:yield(session_id, rpc, NetwkTime.RPC_CALL_TIMEOUT) end return false, "rpc server send failed" end --send接口 function RpcServer:send(client, rpc, ...) return client.call_rpc(0, FlagMask.REQ, rpc, ...) end --broadcast接口 function RpcServer:broadcast(rpc, ...) for _, client in pairs(self.clients) do client.call_rpc(0, FlagMask.REQ, rpc, ...) end end --获取client function RpcServer:get_client(token) return self.clients[token] end --获取client function RpcServer:get_client_by_id(quanta_id) for token, client in pairs(self.client) do if client.id == quanta_id then return client end end end --迭代器 function RpcServer:iterator() local token = nil local clients = self.clients local function iter() token = next(clients, token) if token then return token, clients[token] end end return iter end --rpc回执 ----------------------------------------------------------------------------- --服务器心跳协议 function RpcServer:rpc_heartbeat(client, node_info) self:send(client, "on_heartbeat", quanta.id) if node_info then client.id = node_info.id client.service_id = node_info.service_id event_mgr:notify_listener("on_socket_info", client, node_info) end end return RpcServer
local kLeapVerticalForce = 10.8 local kLeapTime = 0.2 local kLeapForce = 7.6 Skulk.kMaxSneakOffset = 0.55 --0.55 was the original number. Return of the sneaky skulks! function Skulk:GetThirdPersonOffset() local z = -1.5 - self:GetVelocityLength() / self:GetMaxSpeed(true) * 0.4 return Vector(0, 0.9, z) end function Skulk:GetFirstPersonFov() return kSkulkFov end -- Tilt the camera based on the wall the Skulk is attached to. function Skulk:PlayerCameraCoordsAdjustment(cameraCoords) local viewModelTiltAngles = Angles() viewModelTiltAngles:BuildFromCoords(Alien.PlayerCameraCoordsAdjustment(self, cameraCoords)) if self.currentCameraRoll then viewModelTiltAngles.roll = viewModelTiltAngles.roll + self.currentCameraRoll end local viewModelTiltCoords = viewModelTiltAngles:GetCoords() viewModelTiltCoords.origin = cameraCoords.origin return viewModelTiltCoords end -- fix leaping into ground (more of a problem now that we are third person) local originalOnLeap = Skulk.OnLeap function Skulk:OnLeap() local velocity = self:GetVelocity() * 0.5 local forwardVec = self:GetViewAngles():GetCoords().zAxis -- don't jump into the ground, ya dummy if not self:GetCanWallJump() and forwardVec.y < 0 then forwardVec.y = 0 end local newVelocity = velocity + GetNormalizedVectorXZ(forwardVec) * kLeapForce local forwardY = forwardVec.y -- Add in vertical component. newVelocity.y = kLeapVerticalForce * forwardY + kLeapVerticalForce * 0.5 + ConditionalValue(velocity.y < 0, velocity.y, 0) self:SetVelocity(newVelocity) self.leaping = true self.wallWalking = false self:DisableGroundMove(0.2) self.timeOfLeap = Shared.GetTime() end
-- Copyright (C) 2019-2021 Igara Studio S.A. -- -- This file is released under the terms of the MIT license. -- Read LICENSE.txt for more information. dofile('./test_utils.lua') -- this tests and ensures that the alpha-ness of a background -- layer is maintained when sprite conversion takes place from -- Indexed to RGB do local sprite = Sprite(2, 2, ColorMode.INDEXED) local pal = sprite.palettes[1] assert(sprite.layers[1].isTransparent) assert(sprite.colorMode == ColorMode.INDEXED) assert(#pal == 256) local color = pal:getColor(3) color.alpha = 200 pal:setColor(3, color) local image = sprite.cels[1].image image:drawPixel(0, 0, pal:getColor(2)) image:drawPixel(0, 1, pal:getColor(3)) image:drawPixel(1, 0, pal:getColor(4)) image:drawPixel(1, 1, pal:getColor(5)) app.command.BackgroundFromLayer() local layer = sprite.layers[1] assert(layer.isTransparent == false) assert(layer.name == "Background") -- change color mode from Indexed to RGB app.command.ChangePixelFormat { format="rgb" } assert(sprite.colorMode == ColorMode.RGB) image = sprite.cels[1].image for x=0, 1, 1 do for y=0, 1, 1 do local pixel = image:getPixel(x, y) assert(app.pixelColor.rgbaA(pixel) == 255) end end end
local ConfigHelper = Object:extend() local FileSystem = require("fs") local Path = require("path") local Json = require("json") function ConfigHelper:initialize(ConfigPath) self.ConfigPath = ConfigPath self.Settings = {} self.Order = {} end function ConfigHelper:AddSetting(Key, Value) self.Settings[Key] = Value table.insert(self.Order, Key) end function ConfigHelper:ReadFile() if not FileSystem.existsSync(self.ConfigPath) then FileSystem.writeFileSync(self.ConfigPath, "{}") end return Json.decode(FileSystem.readFileSync(self.ConfigPath)) end function ConfigHelper:ResetFile(ConfigData) return FileSystem.writeFileSync( self.ConfigPath, Json.encode( ConfigData, { indent = true, keyorder = self.Order, } ) ) end function ConfigHelper:ParseConfig() local ConfigData = self:ReadFile() local Reset = false for SettingsKey, SettingsValue in pairs(self.Settings) do if ConfigData[SettingsKey] == nil then ConfigData[SettingsKey] = SettingsValue Reset = true end end for Key, Value in pairs(ConfigData) do if self.Settings[Key] == nil then ConfigData[Key] = nil Reset = true end end if Reset then self:ResetFile(ConfigData) return false end return true end return ConfigHelper
do function run(msg, matches) local answers = {'It is certain','It is decidedly so','Without a doubt', 'Yes definitely','You may rely on it','As I see it, yes', 'Most likely','Outlook good','Yes','Signs point to yes', 'Reply hazy try again','Ask again later', 'Better not tell you now','Cannot predict now', 'Concentrate and ask again','Don\'t count on it', 'My reply is no','My sources say no','Outlook not so good', 'Very doubtful'} return answers[math.random(#answers)] end return { description = "Magic 8Ball", usage = "!magic8ball", patterns = {"^!magic8ball"}, run = run } end
local ffi = require('ffi') local cdt = ffi.load(package.searchpath('c-dt', package.cpath), true) ffi.cdef [[ // dt_config.h enum { /* Chronological Julian Date, January 1, 4713 BC, Monday #define DT_EPOCH_OFFSET 1721425 */ /* Network Time Protocol (NTP), January 1, 1900, Monday #define DT_EPOCH_OFFSET -693596 */ /* Unix, January 1, 1970, Thursday #define DT_EPOCH_OFFSET -719163 */ /* Rata Die, January 1, 0001, Monday (as Day 1) */ DT_EPOCH_OFFSET = 0 }; typedef int dt_t; // dt_core.h typedef enum { DT_MON = 1, DT_MONDAY = 1, DT_TUE = 2, DT_TUESDAY = 2, DT_WED = 3, DT_WEDNESDAY = 3, DT_THU = 4, DT_THURSDAY = 4, DT_FRI = 5, DT_FRIDAY = 5, DT_SAT = 6, DT_SATURDAY = 6, DT_SUN = 7, DT_SUNDAY = 7, } dt_dow_t; dt_t dt_from_rdn (int n); dt_t dt_from_yd (int y, int d); dt_t dt_from_ymd (int y, int m, int d); dt_t dt_from_yqd (int y, int q, int d); dt_t dt_from_ywd (int y, int w, int d); void dt_to_yd (dt_t dt, int *y, int *d); void dt_to_ymd (dt_t dt, int *y, int *m, int *d); void dt_to_yqd (dt_t dt, int *y, int *q, int *d); void dt_to_ywd (dt_t dt, int *y, int *w, int *d); int dt_rdn (dt_t dt); dt_dow_t dt_dow (dt_t dt); // dt_parse_iso.h size_t dt_parse_iso_date (const char *str, size_t len, dt_t *dt); size_t dt_parse_iso_time (const char *str, size_t len, int *sod, int *nsec); size_t dt_parse_iso_time_basic (const char *str, size_t len, int *sod, int *nsec); size_t dt_parse_iso_time_extended (const char *str, size_t len, int *sod, int *nsec); size_t dt_parse_iso_zone (const char *str, size_t len, int *offset); size_t dt_parse_iso_zone_basic (const char *str, size_t len, int *offset); size_t dt_parse_iso_zone_extended (const char *str, size_t len, int *offset); size_t dt_parse_iso_zone_lenient (const char *str, size_t len, int *offset); // dt_tm.h dt_t dt_from_struct_tm (const struct tm *tm); void dt_to_struct_tm (dt_t dt, struct tm *tm); // datetime with timezone struct t_datetime_tz { int secs; int nsec; int offset; }; struct t_datetime_duration { int secs; int nsec; }; // <asm-generic/posix_types.h> typedef long __kernel_long_t; typedef unsigned long __kernel_ulong_t; // /usr/include/x86_64-linux-gnu/bits/types/time_t.h typedef long time_t; // <time.h> typedef __kernel_long_t __kernel_time_t; typedef __kernel_long_t __kernel_suseconds_t; struct timespec { __kernel_time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; struct timeval { __kernel_time_t tv_sec; /* seconds */ __kernel_suseconds_t tv_usec; /* microseconds */ }; struct timezone { int tz_minuteswest; /* minutes west of Greenwich */ int tz_dsttime; /* type of dst correction */ }; // /usr/include/x86_64-linux-gnu/sys/time.h typedef struct timezone * __timezone_ptr_t; /* Get the current time of day and timezone information, putting it into *TV and *TZ. If TZ is NULL, *TZ is not filled. Returns 0 on success, -1 on errors. NOTE: This form of timezone information is obsolete. Use the functions and variables declared in <time.h> instead. */ int gettimeofday (struct timeval *__tv, struct timezone * __tz); // /usr/include/x86_64-linux-gnu/bits/types/struct_tm.h /* ISO C `broken-down time' structure. */ struct tm { int tm_sec; /* Seconds. [0-60] (1 leap second) */ int tm_min; /* Minutes. [0-59] */ int tm_hour; /* Hours. [0-23] */ int tm_mday; /* Day. [1-31] */ int tm_mon; /* Month. [0-11] */ int tm_year; /* Year - 1900. */ int tm_wday; /* Day of week. [0-6] */ int tm_yday; /* Days in year.[0-365] */ int tm_isdst; /* DST. [-1/0/1]*/ long int tm_gmtoff; /* Seconds east of UTC. */ const char *tm_zone;/* Timezone abbreviation. */ }; // <time.h> /* Format TP into S according to FORMAT. Write no more than MAXSIZE characters and return the number of characters written, or 0 if it would exceed MAXSIZE. */ size_t strftime (char * __s, size_t __maxsize, const char * __format, const struct tm * __tp); /* Parse S according to FORMAT and store binary time information in TP. The return value is a pointer to the first unparsed character in S. */ char *strptime (const char * __s, const char * __fmt, struct tm *__tp); /* Return the `struct tm' representation of *TIMER in UTC, using *TP to store the result. */ struct tm *gmtime_r (const time_t * __timer, struct tm * __tp); /* Return the `struct tm' representation of *TIMER in local time, using *TP to store the result. */ struct tm *localtime_r (const time_t * __timer, struct tm * __tp); /* Return a string of the form "Day Mon dd hh:mm:ss yyyy\n" that is the representation of TP in this format. */ char *asctime (const struct tm *__tp); /* Equivalent to `asctime (localtime (timer))'. */ char *ctime (const time_t *__timer); ]] local native = ffi.C local SECS_PER_DAY = 86400 local NANOS_PER_SEC = 1000000000 local datetime_t = ffi.typeof('struct t_datetime_tz') local duration_t = ffi.typeof('struct t_datetime_duration') local function duration_new() local delta = ffi.new(duration_t) return delta end local function adjusted_secs(dt) return dt.secs - dt.offset * 60 end local function datetime_sub(lhs, rhs) local s1 = adjusted_secs(lhs) local s2 = adjusted_secs(rhs) local d = duration_new() d.secs = s2 - s1 d.nsec = rhs.nsec - lhs.nsec if d.nsec < 0 then d.secs = d.secs - 1 d.nsec = d.nsec + NANOS_PER_SEC end return d end local function datetime_add(lhs, rhs) local s1 = adjusted_secs(lhs) local s2 = adjusted_secs(rhs) local d = duration_new() d.secs = s2 + s1 d.nsec = rhs.nsec + lhs.nsec if d.nsec >= NANOS_PER_SEC then d.secs = d.secs + 1 d.nsec = d.nsec - NANOS_PER_SEC end return d end local function datetime_eq(lhs, rhs) -- we usually don't need to check nullness -- but tarantool console will call is checking for equality to nil if rhs == nil then return false end -- FIXME - timezone? return (lhs.secs == rhs.secs) and (lhs.nsec == rhs.nsec) end local function datetime_lt(lhs, rhs) -- FIXME - timezone? return (lhs.secs < rhs.secs) or (lhs.secs == rhs.secs and lhs.nsec < rhs.nsec) end local function datetime_le(lhs, rhs) -- FIXME - timezone? return (lhs.secs <= rhs.secs) or (lhs.secs == rhs.secs and lhs.nsec <= rhs.nsec) end --[[ local function datetime_tostring(self) return string.format('DateTime:{secs: %d. nsec: %d, offset:%d}', self.secs, self.nsec, self.offset) end ]] local function datetime_serialize(self) -- Allow YAML, MsgPack and JSON to dump objects with sockets return { secs = self.secs, nsec = self.nsec, tz = self.offset } end --[[ local function duration_tostring(self) return string.format('Duration:{secs: %d. nsec: %d}', self.secs, self.nsec) end ]] local function duration_serialize(self) -- Allow YAML and JSON to dump objects with sockets return { secs = self.secs, nsec = self.nsec } end local datetime_mt = { -- __tostring = datetime_tostring, __serialize = datetime_serialize, __eq = datetime_eq, __lt = datetime_lt, __le = datetime_le, __sub = datetime_sub, __add = datetime_add, } local duration_mt = { -- __tostring = duration_tostring, __serialize = duration_serialize, __eq = datetime_eq, __lt = datetime_lt, __le = datetime_le, } local function datetime_new_raw(secs, nsec, offset) local dt_obj = ffi.new(datetime_t) dt_obj.secs = secs dt_obj.nsec = nsec dt_obj.offset = offset return dt_obj end local function local_rd(secs) return secs / SECS_PER_DAY end local function local_dt(secs) return cdt.dt_from_rdn(local_rd(secs)) end local function mk_timestamp(dt, sp, fp, offset) local dtV = dt ~= nil and (cdt.dt_rdn(dt) - 719163) * SECS_PER_DAY or 0 local spV = sp ~= nil and sp or 0 local fpV = fp ~= nil and fp or 0 local ofsV = offset ~= nil and offset or 0 return datetime_new_raw (dtV + spV - ofsV * 60, fpV, ofsV) end -- create @datetime_t given object @o fields local function datetime_new(o) if o == nil then return datetime_new_raw(0, 0, 0) end local secs = 0 local nsec = 0 local offset = 0 local easy_way = false local y, M, d, ymd y, M, d, ymd = 0, 0, 0, false local h, m, s, frac, hms h, m, s, frac, hms = 0, 0, 0, 0, false local dt = 0 for key, value in pairs(o) do local handlers = { secs = function(v) secs = v easy_way = true end, nsec = function(v) nsec = v easy_way = true end, offset = function (v) offset = v easy_way = true end, year = function(v) assert(v > 0 and v < 10000) y = v ymd = true end, month = function(v) assert(v > 0 and v < 12 ) M = v ymd = true end, day = function(v) assert(v > 0 and v < 32) d = v ymd = true end, hour = function(v) assert(v >= 0 and v < 24) h = v hms = true end, minute = function(v) assert(v >= 0 and v < 60) m = v hms = true end, second = function(v) assert(v >= 0 and v < 61) frac = v % 1 if frac then s = v - (v % 1) else s = v end hms = true end, -- tz offset in minutes tz = function(v) assert(v >= 0 and v <= 720) offset = v end } handlers[key](value) end -- .sec, .nsec, .offset if easy_way then return datetime_new_raw(secs, nsec, offset) end -- .year, .month, .day if ymd then dt = dt + cdt.dt_from_ymd(y, M, d) end -- .hour, .minute, .second if hms then secs = h * 3600 + m * 60 + s end return mk_timestamp(dt, secs, frac, offset) end -- simple parse functions: -- parse_date/parse_time/parse_zone --[[ Basic Extended 20121224 2012-12-24 Calendar date (ISO 8601) 2012359 2012-359 Ordinal date (ISO 8601) 2012W521 2012-W52-1 Week date (ISO 8601) 2012Q485 2012-Q4-85 Quarter date ]] local function parse_date(str) local dt = ffi.new('dt_t[1]') local rc = cdt.dt_parse_iso_date(str, #str, dt) assert(rc > 0) return mk_timestamp(dt[0]) end --[[ Basic Extended T12 N/A T1230 T12:30 T123045 T12:30:45 T123045.123456789 T12:30:45.123456789 T123045,123456789 T12:30:45,123456789 The time designator [T] may be omitted. ]] local function parse_time(str) local sp = ffi.new('int[1]') local fp = ffi.new('int[1]') local rc = cdt.dt_parse_iso_time(str, #str, sp, fp) assert(rc > 0) return mk_timestamp(nil, sp[0], fp[0]) end --[[ Basic Extended Z N/A ±hh N/A ±hhmm ±hh:mm ]] local function parse_zone(str) local offset = ffi.new('int[1]') local rc = cdt.dt_parse_iso_zone(str, #str, offset) assert(rc > 0) return mk_timestamp(nil, nil, nil, offset[0]) end --[[ aggregated parse functions assumes to deal with date T time time_zone at once date [T] time [ ] time_zone ]] local function parse_str(str) local dt = ffi.new('dt_t[1]') local len = #str local n = cdt.dt_parse_iso_date(str, len, dt) local dt_ = dt[0] if n == 0 or len == n then return mk_timestamp(dt_) end str = str:sub(tonumber(n) + 1) local ch = str:sub(1,1) if ch ~= 't' and ch ~= 'T' and ch ~= ' ' then return mk_timestamp(dt_) end str = str:sub(2) len = #str local sp = ffi.new('int[1]') local fp = ffi.new('int[1]') local n = cdt.dt_parse_iso_time(str, len, sp, fp) if n == 0 then return mk_timestamp(dt_) end local sp_ = sp[0] local fp_ = fp[0] if len == n then return mk_timestamp(dt_, sp_, fp_) end str = str:sub(tonumber(n) + 1) if str:sub(1,1) == ' ' then str = str:sub(2) end len = #str local offset = ffi.new('int[1]') n = cdt.dt_parse_iso_zone(str, len, offset) if n == 0 then return mk_timestamp(dt_, sp_, fp_) end return mk_timestamp(dt_, sp_, fp_, offset[0]) end local function datetime_from(o) if o == nil or type(o) == 'table' then return datetime_new(o) elseif type(o) == 'string' then return parse_str(o) end end local function local_now() local p_tv = ffi.new ' struct timeval [1] ' local rc = native.gettimeofday(p_tv, nil) assert(rc == 0) local secs = p_tv[0].tv_sec local nsec = p_tv[0].tv_usec * 1000 local p_time = ffi.new 'time_t[1]' local p_tm = ffi.new 'struct tm[1]' native.localtime_r(p_time, p_tm); local dt = cdt.dt_from_struct_tm(p_tm) local ofs = p_tm[0].tm_gmtoff / 60 -- convert seconds to minutes return mk_timestamp(dt, secs, nsec, ofs) end local function asctime(o) assert(ffi.typeof(o) == datetime_t) local p_tm = ffi.new 'struct tm[1]' cdt.dt_to_struct_tm(local_dt(o.secs), p_tm) return ffi.string(native.asctime(p_tm)) end local function ctime(o) assert(ffi.typeof(o) == datetime_t) local p_time = ffi.new 'time_t[1]' p_time[0] = o.secs return ffi.string(native.ctime(p_time)) end local function strftime(fmt, o) assert(ffi.typeof(o) == datetime_t) local sz = 50 local buff = ffi.new('char[?]', sz) local p_tm = ffi.new 'struct tm[1]' cdt.dt_to_struct_tm(local_dt(o.secs), p_tm) native.strftime(buff, sz, fmt, p_tm) return ffi.string(buff) end -- strftime may be redirected to datetime:fmt("format") local function datetime_fmt() end ffi.metatype(duration_t, duration_mt) ffi.metatype(datetime_t, datetime_mt) return setmetatable( { datetime = datetime_new, delta = duration_new, parse = parse_str, parse_date = parse_date, parse_time = parse_time, parse_zone = parse_zone, fmt = datetime_fmt, now = local_now, -- strptime = strptime; strftime = strftime, asctime = asctime, ctime = ctime, }, { __call = function(self, ...) return datetime_from(...) end } ) -- vim: ts=4 sts=4 sw=4 et
-- =================================================================== -- This file contains Global functions -- that can be called from bash scripts -- =================================================================== local weekly_review = require('config.workflows.weekly-review') -- =================================================================== -- Weekly Review -- =================================================================== function Start_Weekly_Review() weekly_review.start() end function Finish_Weekly_Review() weekly_review.finish() end -- =================================================================== -- [[placeholder]] -- ===================================================================
bh_force_sensitive_crypt_crawler = Creature:new { objectName = "@mob/creature_names:force_sensitive_crypt_crawler", randomNameType = NAME_GENERIC, randomNameTag = true, socialGroup = "kun", faction = "", level = 250, chanceHit = 0.9, damageMin = 685, damageMax = 1080, baseXp = 19057, baseHAM = 116000, baseHAMmax = 119000, armor = 2, resists = {75,75,40,40,40,40,40,40,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = PACK + KILLER, optionsBitmask = AIENABLED, diet = HERBIVORE, templates = {"object/mobile/dressed_force_sensitive_crypt_crawler.iff"}, lootGroups = { { groups = { {group = "tierone", chance = 2500000}, {group = "tiertwo", chance = 500000}, {group = "tierthree", chance = 500000}, {group = "color_crystals", chance = 500000}, {group = "power_crystals", chance = 1000000}, {group = "wearables_all", chance = 1000000}, {group = "weapons_all", chance = 1000000}, {group = "armor_all", chance = 1000000}, {group = "clothing_attachments", chance = 1000000}, {group = "armor_attachments", chance = 1000000} }, lootChance = 10000000 }, { groups = { {group = "tierone", chance = 2500000}, {group = "tiertwo", chance = 500000}, {group = "tierthree", chance = 500000}, {group = "color_crystals", chance = 500000}, {group = "power_crystals", chance = 1000000}, {group = "wearables_all", chance = 1000000}, {group = "weapons_all", chance = 1000000}, {group = "armor_all", chance = 1000000}, {group = "clothing_attachments", chance = 1000000}, {group = "armor_attachments", chance = 1000000} }, lootChance = 8000000 }, { groups = { {group = "tierone", chance = 2500000}, {group = "tiertwo", chance = 500000}, {group = "tierthree", chance = 500000}, {group = "color_crystals", chance = 500000}, {group = "power_crystals", chance = 500000}, {group = "power_crystals", chance = 500000}, {group = "wearables_all", chance = 1000000}, {group = "weapons_all", chance = 1000000}, {group = "armor_all", chance = 1000000}, {group = "clothing_attachments", chance = 1000000}, {group = "armor_attachments", chance = 1000000} }, lootChance = 7500000 }, }, weapons = {"mixed_force_weapons"}, conversationTemplate = "", attacks = merge(pikemanmaster,brawlermaster) } CreatureTemplates:addCreatureTemplate(bh_force_sensitive_crypt_crawler, "bh_force_sensitive_crypt_crawler")
---------------------------------------------------------------------- -- hessian.lua: this file appends extra methods to modules in nn, -- to estimate diagonal elements of the Hessian. This is useful -- to condition learning rates individually. ---------------------------------------------------------------------- nn.hessian = {} ---------------------------------------------------------------------- -- Hessian code is still experimental, -- and deactivated by default ---------------------------------------------------------------------- function nn.hessian.enable() local function accDiagHessianParameters(module, input, diagHessianOutput, gw, hw) if #gw ~= #hw then error('Number of gradients is nto equal to number of hessians') end module.inputSq = module.inputSq or input.new() module.inputSq:resizeAs(input) torch.cmul(module.inputSq, input, input) -- replace gradients with hessian for i=1,#gw do local gwname = gw[i] local hwname = hw[i] local gwval = module[gwname] local hwval = module[hwname] if hwval == nil then module[hwname] = gwval.new():resizeAs(gwval) hwval = module[hwname] end module[gwname] = hwval module[hwname] = gwval end module.accGradParameters(module, module.inputSq, diagHessianOutput, 1) -- put back gradients for i=1,#gw do local gwname = gw[i] local hwname = hw[i] local gwval = module[gwname] local hwval = module[hwname] module[gwname] = hwval module[hwname] = gwval end end nn.hessian.accDiagHessianParameters = accDiagHessianParameters local function updateDiagHessianInput(module, input, diagHessianOutput, w, wsq) if #w ~= #wsq then error('Number of weights is not equal to number of weights squares') end module.diagHessianInput = module.diagHessianInput or input.new() module.diagHessianInput:resizeAs(input) local gi = module.gradInput module.gradInput = module.diagHessianInput for i=1,#w do local wname = w[i] local wsqname = wsq[i] local wval = module[wname] local wsqval = module[wsqname] if wsqval == nil then module[wsqname] = wval.new() wsqval = module[wsqname] end wsqval:resizeAs(wval) torch.cmul(wsqval, wval, wval) module[wsqname] = wval module[wname] = wsqval end module.updateGradInput(module,input,diagHessianOutput) for i=1,#w do local wname = w[i] local wsqname = wsq[i] local wval = module[wname] local wsqval = module[wsqname] module[wname] = wsqval module[wsqname] = wval end module.gradInput = gi return module.diagHessianInput end nn.hessian.updateDiagHessianInput = updateDiagHessianInput local function updateDiagHessianInputPointWise(module, input, diagHessianOutput) local tdh = diagHessianOutput.new():resizeAs(diagHessianOutput):fill(1) updateDiagHessianInput(module,input,tdh,{},{}) module.diagHessianInput:cmul(module.diagHessianInput) module.diagHessianInput:cmul(diagHessianOutput) return module.diagHessianInput end nn.hessian.updateDiagHessianInputPointWise = updateDiagHessianInputPointWise local function initDiagHessianParameters(module,gw,hw) module.diagHessianInput = module.diagHessianInput or module.gradInput.new(); for i=1,#gw do module[hw[i]] = module[hw[i]] or module[gw[i]].new():resizeAs(module[gw[i]]) end end nn.hessian.initDiagHessianParameters = initDiagHessianParameters ---------------------------------------------------------------------- -- Module ---------------------------------------------------------------------- function nn.Module.updateDiagHessianInput(self, input, diagHessianOutput) error(torch.typename(self) .. ':updateDiagHessianInput() is undefined') end function nn.Module.accDiagHessianParameters(self, input, diagHessianOutput) end function nn.Module.initDiagHessianParameters() end ---------------------------------------------------------------------- -- Sequential ---------------------------------------------------------------------- function nn.Sequential.initDiagHessianParameters(self) for i=1,#self.modules do self.modules[i]:initDiagHessianParameters() end end function nn.Sequential.updateDiagHessianInput(self, input, diagHessianOutput) local currentDiagHessianOutput = diagHessianOutput local currentModule = self.modules[#self.modules] for i=#self.modules-1,1,-1 do local previousModule = self.modules[i] currentDiagHessianOutput = currentModule:updateDiagHessianInput(previousModule.output, currentDiagHessianOutput) currentModule = previousModule end currentDiagHessianOutput = currentModule:updateDiagHessianInput(input, currentDiagHessianOutput) self.diagHessianInput = currentDiagHessianOutput return currentDiagHessianOutput end function nn.Sequential.accDiagHessianParameters(self, input, diagHessianOutput) local currentDiagHessianOutput = diagHessianOutput local currentModule = self.modules[#self.modules] for i=#self.modules-1,1,-1 do local previousModule = self.modules[i] currentModule:accDiagHessianParameters(previousModule.output, currentDiagHessianOutput) currentDiagHessianOutput = currentModule.diagHessianInput currentModule = previousModule end currentModule:accDiagHessianParameters(input, currentDiagHessianOutput) end ---------------------------------------------------------------------- -- Concat (NEW) ---------------------------------------------------------------------- function nn.Concat.initDiagHessianParameters(self) self.diagHessianInput = self.diagHessianInput or self.gradInput.new(); for i=1,#self.modules do self.modules[i]:initDiagHessianParameters() end end function nn.Concat.updateDiagHessianInput(self, input, diagHessianOutput) self.diagHessianInput:resizeAs(input) local offset = 1 for i,module in ipairs(self.modules) do local currentOutput = module.output local currentDiagHessianInput = module:updateDiagHessianInput(input, diagHessianOutput:narrow(self.dimension, offset, currentOutput:size(self.dimension))) if i==1 then self.diagHessianInput:copy(currentDiagHessianInput) else self.diagHessianInput:add(currentDiagHessianInput) end offset = offset + currentOutput:size(self.dimension) end return self.diagHessianInput end function nn.Concat.accDiagHessianParameters(self,input, diagHessianOutput) local offset = 1 for i,module in ipairs(self.modules) do local currentOutput = module.output local currentDiagHessianInput = module:accDiagHessianParameters(input, diagHessianOutput:narrow(self.dimension, offset, currentOutput:size(self.dimension))) offset = offset + currentOutput:size(self.dimension) end end ---------------------------------------------------------------------- -- Criterion ---------------------------------------------------------------------- function nn.Criterion.updateDiagHessianInput(self, input, diagHessianOutput) error(torch.typename(self) .. ':updateDiagHessianInput() is undefined') end ---------------------------------------------------------------------- -- MSECriterion ---------------------------------------------------------------------- function nn.MSECriterion.updateDiagHessianInput(self, input, target) self.diagHessianInput = self.diagHessianInput or input.new() local val = 2 if self.sizeAverage then val = val / input:nElement() end self.diagHessianInput:resizeAs(input):fill(val) return self.diagHessianInput end ---------------------------------------------------------------------- -- Linear ---------------------------------------------------------------------- function nn.Linear.updateDiagHessianInput(self, input, diagHessianOutput) updateDiagHessianInput(self, input, diagHessianOutput, {'weight'}, {'weightSq'}) return self.diagHessianInput end function nn.Linear.accDiagHessianParameters(self, input, diagHessianOutput) accDiagHessianParameters(self,input, diagHessianOutput, {'gradWeight','gradBias'}, {'diagHessianWeight','diagHessianBias'}) end function nn.Linear.initDiagHessianParameters(self) initDiagHessianParameters(self,{'gradWeight','gradBias'},{'diagHessianWeight','diagHessianBias'}) end ---------------------------------------------------------------------- -- SpatialConvolution (BUG: why are the biases ignored here?) ---------------------------------------------------------------------- function nn.SpatialConvolution.updateDiagHessianInput(self, input, diagHessianOutput) updateDiagHessianInput(self, input, diagHessianOutput, {'weight'}, {'weightSq'}) return self.diagHessianInput end function nn.SpatialConvolution.accDiagHessianParameters(self, input, diagHessianOutput) accDiagHessianParameters(self,input, diagHessianOutput, {'gradWeight'}, {'diagHessianWeight'}) end function nn.SpatialConvolution.initDiagHessianParameters(self) initDiagHessianParameters(self,{'gradWeight'},{'diagHessianWeight'}) end ---------------------------------------------------------------------- -- TemporalConvolution (NEW) ---------------------------------------------------------------------- function nn.TemporalConvolution.updateDiagHessianInput(self, input, diagHessianOutput) updateDiagHessianInput(self, input, diagHessianOutput, {'weight','bias'}, {'weightSq','biasSq'}) return self.diagHessianInput end function nn.TemporalConvolution.accDiagHessianParameters(self, input, diagHessianOutput) accDiagHessianParameters(self,input, diagHessianOutput, {'gradWeight','gradBias'}, {'diagHessianWeight','diagHessianBias'}) end function nn.TemporalConvolution.initDiagHessianParameters(self) initDiagHessianParameters(self,{'gradWeight','gradBias'},{'diagHessianWeight','diagHessianBias'}) end ---------------------------------------------------------------------- -- SpatialSubtractiveNormalization (NEW, VERIFY) ---------------------------------------------------------------------- function nn.SpatialSubtractiveNormalization.initDiagHessianParameters(self) self.diagHessianInput = self.diagHessianInput or self.gradInput.new() self.subtractor:initDiagHessianParameters() self.divider:initDiagHessianParameters() self.meanestimator:initDiagHessianParameters() end function nn.SpatialSubtractiveNormalization.updateDiagHessianInput(self, input, diagHessianOutput) self.diagHessianInput:resizeAs(input):zero() -- backprop through all modules local hsub = self.subtractor:updateDiagHessianInput({input, self.adjustedsums}, diagHessianOutput) local hdiv = self.divider:updateDiagHessianInput({self.localsums, self.coef}, hsub[2]) self.diagHessianInput:add(self.meanestimator:updateDiagHessianInput(input, hdiv[1])) self.diagHessianInput:add(hsub[1]) return self.diagHessianInput end ---------------------------------------------------------------------- -- SpatialZeroPadding (NEW, VERIFY) ---------------------------------------------------------------------- function nn.SpatialZeroPadding.initDiagHessianParameters(self) self.diagHessianInput = torch.Tensor() end function nn.SpatialZeroPadding.updateDiagHessianInput(self, input, diagHessianOutput) if input:dim() ~= 3 then error('input must be 3-dimensional') end self.diagHessianInput:resizeAs(input):zero() -- crop diagHessianInput if necessary local cg_input = self.diagHessianInput if self.pad_t < 0 then cg_input = cg_input:narrow(2, 1 - self.pad_t, cg_input:size(2) + self.pad_t) end if self.pad_b < 0 then cg_input = cg_input:narrow(2, 1, cg_input:size(2) + self.pad_b) end if self.pad_l < 0 then cg_input = cg_input:narrow(3, 1 - self.pad_l, cg_input:size(3) + self.pad_l) end if self.pad_r < 0 then cg_input = cg_input:narrow(3, 1, cg_input:size(3) + self.pad_r) end -- crop diagHessianOutput if necessary local cg_output = diagHessianOutput if self.pad_t > 0 then cg_output = cg_output:narrow(2, 1 + self.pad_t, cg_output:size(2) - self.pad_t) end if self.pad_b > 0 then cg_output = cg_output:narrow(2, 1, cg_output:size(2) - self.pad_b) end if self.pad_l > 0 then cg_output = cg_output:narrow(3, 1 + self.pad_l, cg_output:size(3) - self.pad_l) end if self.pad_r > 0 then cg_output = cg_output:narrow(3, 1, cg_output:size(3) - self.pad_r) end -- copy diagHessianOutput to diagHessianInput cg_input:copy(cg_output) return self.diagHessianInput end ---------------------------------------------------------------------- -- Sum (NEW, VERIFY) ---------------------------------------------------------------------- function nn.Sum.initDiagHessianParameters(self) self.diagHessianInput = torch.Tensor() end function nn.Sum.updateDiagHessianInput(self, input, diagHessianOutput) local size = diagHessianOutput:size():totable() local stride = diagHessianOutput:stride():totable() table.insert(size, self.dimension, input:size(self.dimension)) table.insert(stride, self.dimension, 0) self.diagHessianInput:set(diagHessianOutput:storage(), 1, torch.LongStorage(size), torch.LongStorage(stride)) return self.diagHessianInput end ---------------------------------------------------------------------- -- CSubTable (NEW, VERIFY) ---------------------------------------------------------------------- function nn.CSubTable.initDiagHessianParameters(self) self.diagHessianInput = {} end function nn.CSubTable.updateDiagHessianInput(self, input, diagHessianOutput) self.diagHessianInput[1] = self.diagHessianInput[1] or torch.Tensor() self.diagHessianInput[2] = self.diagHessianInput[2] or torch.Tensor() self.diagHessianInput[1]:resizeAs(input[1]):copy(diagHessianOutput) self.diagHessianInput[2]:resizeAs(input[1]):copy(diagHessianOutput):mul(-1) return self.diagHessianInput end ---------------------------------------------------------------------- -- CDivTable (NEW, VERIFY) ---------------------------------------------------------------------- function nn.CDivTable.initDiagHessianParameters(self) self.diagHessianInput = {} end function nn.CDivTable.updateDiagHessianInput(self, input, diagHessianOutput) self.diagHessianInput[1] = self.diagHessianInput[1] or torch.Tensor() self.diagHessianInput[2] = self.diagHessianInput[2] or torch.Tensor() self.diagHessianInput[1]:resizeAs(input[1]):copy(diagHessianOutput):cdiv(input[2]) self.diagHessianInput[2]:resizeAs(input[2]):zero():addcdiv(-1,self.diagHessianInput[1],input[2]):cmul(input[1]) return self.diagHessianInput end ---------------------------------------------------------------------- -- Replicate (NEW, VERIFY) ---------------------------------------------------------------------- function nn.Replicate.initDiagHessianParameters(self) self.diagHessianInput = self.diagHessianInput or self.gradInput.new() end function nn.Replicate.updateDiagHessianInput(self, input, diagHessianOutput) self.diagHessianInput:resizeAs(input):zero() for k = 1,diagHessianOutput:size(1) do self.diagHessianInput:add(diagHessianOutput[k]) end return self.diagHessianInput end ---------------------------------------------------------------------- -- SpatialSubSampling (NEW) ---------------------------------------------------------------------- function nn.SpatialSubSampling.updateDiagHessianInput(self, input, diagHessianOutput) updateDiagHessianInput(self, input, diagHessianOutput, {'weight','bias'}, {'weightSq','biasSq'}) return self.diagHessianInput end function nn.SpatialSubSampling.accDiagHessianParameters(self, input, diagHessianOutput) accDiagHessianParameters(self,input, diagHessianOutput, {'gradWeight','gradBias'}, {'diagHessianWeight','diagHessianBias'}) end function nn.SpatialSubSampling.initDiagHessianParameters(self) initDiagHessianParameters(self,{'gradWeight','gradBias'},{'diagHessianWeight','diagHessianBias'}) end ---------------------------------------------------------------------- -- SpatialConvolutionMap ---------------------------------------------------------------------- function nn.SpatialConvolutionMap.updateDiagHessianInput(self, input, diagHessianOutput) updateDiagHessianInput(self, input, diagHessianOutput, {'weight','bias'}, {'weightSq','biasSq'}) return self.diagHessianInput end function nn.SpatialConvolutionMap.accDiagHessianParameters(self, input, diagHessianOutput) accDiagHessianParameters(self,input, diagHessianOutput, {'gradWeight','gradBias'}, {'diagHessianWeight','diagHessianBias'}) end function nn.SpatialConvolutionMap.initDiagHessianParameters(self) initDiagHessianParameters(self,{'gradWeight','gradBias'},{'diagHessianWeight','diagHessianBias'}) end ---------------------------------------------------------------------- -- Tanh ---------------------------------------------------------------------- function nn.Tanh.updateDiagHessianInput(self, input, diagHessianOutput) updateDiagHessianInputPointWise(self, input, diagHessianOutput) return self.diagHessianInput end ---------------------------------------------------------------------- -- Square ---------------------------------------------------------------------- function nn.Square.updateDiagHessianInput(self, input, diagHessianOutput) updateDiagHessianInputPointWise(self, input, diagHessianOutput) return self.diagHessianInput end ---------------------------------------------------------------------- -- Sqrt ---------------------------------------------------------------------- function nn.Sqrt.updateDiagHessianInput(self, input, diagHessianOutput) updateDiagHessianInputPointWise(self, input, diagHessianOutput) return self.diagHessianInput end ---------------------------------------------------------------------- -- Mul (NEW) ---------------------------------------------------------------------- function nn.Mul.updateDiagHessianInput(self, input, diagHessianOutput) updateDiagHessianInput(self, input, diagHessianOutput, {'weight'}, {'weightSq'}) return self.diagHessianInput end function nn.Mul.accDiagHessianParameters(self, input, diagHessianOutput) accDiagHessianParameters(self,input, diagHessianOutput, {'gradWeight'}, {'diagHessianWeight'}) end function nn.Mul.initDiagHessianParameters(self) initDiagHessianParameters(self,{'gradWeight'},{'diagHessianWeight'}) end ---------------------------------------------------------------------- -- Abs (NEW) ---------------------------------------------------------------------- function nn.Abs.updateDiagHessianInput(self, input, diagHessianOutput) updateDiagHessianInputPointWise(self, input, diagHessianOutput) return self.diagHessianInput end ---------------------------------------------------------------------- -- Reshape ---------------------------------------------------------------------- function nn.Reshape.updateDiagHessianInput(self, input, diagHessianOutput) self.diagHessianInput = self.diagHessianInput or input.new() diagHessianOutput = diagHessianOutput:contiguous() self.diagHessianInput:set(diagHessianOutput):resizeAs(input) return self.diagHessianInput end ---------------------------------------------------------------------- -- Parameters manipulation: -- we modify these functions such that they return hessian coefficients ---------------------------------------------------------------------- function nn.Module.parameters(self) if self.weight and self.bias then return {self.weight, self.bias}, {self.gradWeight, self.gradBias}, {self.diagHessianWeight, self.diagHessianBias} elseif self.weight then return {self.weight}, {self.gradWeight}, {self.diagHessianWeight} elseif self.bias then return {self.bias}, {self.gradBias}, {self.diagHessianBias} else return end end function nn.Module.getParameters(self) -- get parameters local parameters,gradParameters,hessianParameters = self:parameters() -- this function flattens arbitrary lists of parameters, -- even complex shared ones local function flatten(parameters) -- already flat ? local flat = true for k = 2,#parameters do if parameters[k]:storage() ~= parameters[k-1]:storage() then flat = false break end end if flat then local nParameters = 0 for k,param in ipairs(parameters) do nParameters = nParameters + param:nElement() end local flatParameters = parameters[1].new(parameters[1]:storage()) if nParameters ~= flatParameters:nElement() then error('flattenParameters(): weird parameters') end return flatParameters end -- compute offsets of each parameter local offsets = {} local sizes = {} local strides = {} local elements = {} local storageOffsets = {} local params = {} local nParameters = 0 for k,param in ipairs(parameters) do table.insert(offsets, nParameters+1) table.insert(sizes, param:size()) table.insert(strides, param:stride()) table.insert(elements, param:nElement()) table.insert(storageOffsets, param:storageOffset()) local isView = false for i = 1,k-1 do if param:storage() == parameters[i]:storage() then offsets[k] = offsets[i] if storageOffsets[k] ~= storageOffsets[i] or elements[k] ~= elements[i] then error('flattenParameters(): cannot flatten shared weights with different structures') end isView = true break end end if not isView then nParameters = nParameters + param:nElement() end end -- create flat vector local flatParameters = parameters[1].new(nParameters) local storage = flatParameters:storage() -- reallocate all parameters in flat vector for i = 1,#parameters do local data = parameters[i]:clone() parameters[i]:set(storage, offsets[i], elements[i]):resize(sizes[i],strides[i]):copy(data) data = nil collectgarbage() end -- cleanup collectgarbage() -- return flat param return flatParameters end -- flatten parameters and gradients local flatParameters = flatten(parameters) local flatGradParameters = flatten(gradParameters) local flatHessianParameters if hessianParameters[1] then flatHessianParameters = flatten(hessianParameters) end -- return new flat vector that contains all discrete parameters return flatParameters, flatGradParameters, flatHessianParameters end local function tinsert(to, from) if type(from) == 'table' then for i=1,#from do tinsert(to,from[i]) end else table.insert(to,from) end end function nn.Sequential.parameters(self) local w = {} local gw = {} local ggw = {} for i=1,#self.modules do local mw,mgw,mggw = self.modules[i]:parameters() if mw then tinsert(w,mw) tinsert(gw,mgw) tinsert(ggw,mggw) end end return w,gw,ggw end function nn.Concat.parameters(self) local w = {} local gw = {} local ggw = {} for i=1,#self.modules do local mw,mgw,mggw = self.modules[i]:parameters() if mw then tinsert(w,mw) tinsert(gw,mgw) tinsert(ggw,mggw) end end return w,gw,ggw end ---------------------------------------------------------------------- -- Avoid multiple calls to enable() ---------------------------------------------------------------------- function nn.hessian.enable() end end
local API = {} function API.RegisterDialogueId(dialogId) if not _G.APIDialogsLibrary then _G.APIDialogsLibrary = {} end if not _G.APIDialogsLibrary[dialogId] then _G.APIDialogsLibrary[dialogId] = {} else error("Can't register the same dialog id twice.") end end function API.SetCondition(dialogId, conditionResource, targetDialogId1, targetDialogId2) if not _G.APIDialogsLibrary or not _G.APIDialogsLibrary[dialogId] then warn("No registered "..dialogId.." found.") return end _G.APIDialogsLibrary[dialogId].condition = { conditionResource = conditionResource, targetDialogId1 = targetDialogId1, targetDialogId2 = targetDialogId2 } end function API.AddText(dialogId, text, animation, rewardTable) if not _G.APIDialogsLibrary or not _G.APIDialogsLibrary[dialogId] then warn("No registered "..dialogId.." found.") return end if not _G.APIDialogsLibrary[dialogId].texts then _G.APIDialogsLibrary[dialogId].texts = {} end if text ~= nil then table.insert(_G.APIDialogsLibrary[dialogId].texts, { text = text, animation = animation, rewardTable = rewardTable }) end end function API.AddOption(dialogId, optionName, targetDialogId, eventName) if not _G.APIDialogsLibrary or not _G.APIDialogsLibrary[dialogId] then warn("No registered "..dialogId.." found.") return end if not _G.APIDialogsLibrary[dialogId].options then _G.APIDialogsLibrary[dialogId].options = {} end table.insert(_G.APIDialogsLibrary[dialogId].options, { optionName = optionName, dialogId = targetDialogId, eventName = eventName }) end function API.GetDialogLibrary() if not _G.APIDialogsLibrary then warn("No registered dialogs library found.") return nil end return _G.APIDialogsLibrary end function API.GetDialogTable(dialogId) if not _G.APIDialogsLibrary or not _G.APIDialogsLibrary[dialogId] then warn("No registered "..dialogId.." found.") return nil end return _G.APIDialogsLibrary[dialogId] end return API
local common = require('common') local wikiEncodeURL = { -- https://www.w3schools.com/tags/ref_urlencode.asp enc = { ["Windows-1252"] = { "%01", "%02", "%03", "%04", "%05", "%06", "%07", "%08", "%09", "%0A", "%0B", "%0C", "%0D", "%0E", "%0F", "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17", "%18", "%19", "%1A", "%1B", "%1C", "%1D", "%1E", "%1F", "%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27", "%28", "%29", "%2A", "%2B", "%2C", "%2D", "%2E", "%2F", "%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37", "%38", "%39", "%3A", "%3B", "%3C", "%3D", "%3E", "%3F", "%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47", "%48", "%49", "%4A", "%4B", "%4C", "%4D", "%4E", "%4F", "%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57", "%58", "%59", "%5A", "%5B", "%5C", "%5D", "%5E", "%5F", "%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67", "%68", "%69", "%6A", "%6B", "%6C", "%6D", "%6E", "%6F", "%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77", "%78", "%79", "%7A", "%7B", "%7C", "%7D", "%7E", "%7F", "%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87", "%88", "%89", "%8A", "%8B", "%8C", "%8D", "%8E", "%8F", "%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97", "%98", "%99", "%9A", "%9B", "%9C", "%9D", "%9E", "%9F", "%A0", "%A1", "%A2", "%A3", "%A4", "%A5", "%A6", "%A7", "%A8", "%A9", "%AA", "%AB", "%AC", "%AD", "%AE", "%AF", "%B0", "%B1", "%B2", "%B3", "%B4", "%B5", "%B6", "%B7", "%B8", "%B9", "%BA", "%BB", "%BC", "%BD", "%BE", "%BF", "%C0", "%C1", "%C2", "%C3", "%C4", "%C5", "%C6", "%C7", "%C8", "%C9", "%CA", "%CB", "%CC", "%CD", "%CE", "%CF", "%D0", "%D1", "%D2", "%D3", "%D4", "%D5", "%D6", "%D7", "%D8", "%D9", "%DA", "%DB", "%DC", "%DD", "%DE", "%DF", "%E0", "%E1", "%E2", "%E3", "%E4", "%E5", "%E6", "%E7", "%E8", "%E9", "%EA", "%EB", "%EC", "%ED", "%EE", "%EF", "%F0", "%F1", "%F2", "%F3", "%F4", "%F5", "%F6", "%F7", "%F8", "%F9", "%FA", "%FB", "%FC", "%FD", "%FE", "%FF" }, ["UTF-8"] = { "%01", "%02", "%03", "%04", "%05", "%06", "%07", "%08", "%09", "%0A", "%0B", "%0C", "%0D", "%0E", "%0F", "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17", "%18", "%19", "%1A", "%1B", "%1C", "%1D", "%1E", "%1F", "%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27", "%28", "%29", "%2A", "%2B", "%2C", "%2D", "%2E", "%2F", "%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37", "%38", "%39", "%3A", "%3B", "%3C", "%3D", "%3E", "%3F", "%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47", "%48", "%49", "%4A", "%4B", "%4C", "%4D", "%4E", "%4F", "%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57", "%58", "%59", "%5A", "%5B", "%5C", "%5D", "%5E", "%5F", "%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67", "%68", "%69", "%6A", "%6B", "%6C", "%6D", "%6E", "%6F", "%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77", "%78", "%79", "%7A", "%7B", "%7C", "%7D", "%7E", "%7F", "%E2%82%AC", "%81", "%E2%80%9A", "%C6%92", "%E2%80%9E", "%E2%80%A6", "%E2%80%A0", "%E2%80%A1", "%CB%86", "%E2%80%B0", "%C5%A0", "%E2%80%B9", "%C5%92", "%C5%8D", "%C5%BD", "%8F", "%C2%90", "%E2%80%98", "%E2%80%99", "%E2%80%9C", "%E2%80%9D", "%E2%80%A2", "%E2%80%93", "%E2%80%94", "%CB%9C", "%E2%84", "%C5%A1", "%E2%80", "%C5%93", "%9D", "%C5%BE", "%C5%B8", "%C2%A0", "%C2%A1", "%C2%A2", "%C2%A3", "%C2%A4", "%C2%A5", "%C2%A6", "%C2%A7", "%C2%A8", "%C2%A9", "%C2%AA", "%C2%AB", "%C2%AC", "%C2%AD", "%C2%AE", "%C2%AF", "%C2%B0", "%C2%B1", "%C2%B2", "%C2%B3", "%C2%B4", "%C2%B5", "%C2%B6", "%C2%B7", "%C2%B8", "%C2%B9", "%C2%BA", "%C2%BB", "%C2%BC", "%C2%BD", "%C2%BE", "%C2%BF", "%C3%80", "%C3%81", "%C3%82", "%C3%83", "%C3%84", "%C3%85", "%C3%86", "%C3%87", "%C3%88", "%C3%89", "%C3%8A", "%C3%8B", "%C3%8C", "%C3%8D", "%C3%8E", "%C3%8F", "%C3%90", "%C3%91", "%C3%92", "%C3%93", "%C3%94", "%C3%95", "%C3%96", "%C3%97", "%C3%98", "%C3%99", "%C3%9A", "%C3%9B", "%C3%9C", "%C3%9D", "%C3%9E", "%C3%9F", "%C3%A0", "%C3%A1", "%C3%A2", "%C3%A3", "%C3%A4", "%C3%A5", "%C3%A6", "%C3%A7", "%C3%A8", "%C3%A9", "%C3%AA", "%C3%AB", "%C3%AC", "%C3%AD", "%C3%AE", "%C3%AF", "%C3%B0", "%C3%B1", "%C3%B2", "%C3%B3", "%C3%B4", "%C3%B5", "%C3%B6", "%C3%B7", "%C3%B8", "%C3%B9", "%C3%BA", "%C3%BB", "%C3%BC", "%C3%BD", "%C3%BE", "%C3%BF" } }, dec = {}, mod = "Windows-1252" } for k, v in pairs(wikiEncodeURL.enc) do wikiEncodeURL.dec[k] = {} for iD = 1, #v do local c = v[iD] wikiEncodeURL.dec[k][c] = iD end end return wikiEncodeURL
return { id = 3, s1 = "", s2 = {key='',text=""}, }
--MoveCurve --B_30101/curve_RushB curve_RushB return { filePath = "B_30101/curve_RushB", startTime = Fixed64(0) --[[0]], startRealTime = Fixed64(0) --[[0]], endTime = Fixed64(104857600) --[[100]], endRealTime = Fixed64(629146) --[[0.6]], isZoom = false, isCompensate = false, curve = { [1] = { time = 0 --[[0]], value = 0 --[[0]], inTangent = 2097152 --[[2]], outTangent = 2097152 --[[2]], }, [2] = { time = 116194 --[[0.1108118]], value = 1578816 --[[1.505677]], inTangent = 9546483 --[[9.104236]], outTangent = 9546483 --[[9.104236]], }, [3] = { time = 274459 --[[0.261744]], value = 3581279 --[[3.415373]], inTangent = 7330656 --[[6.991058]], outTangent = 7330656 --[[6.991058]], }, [4] = { time = 1048576 --[[1]], value = 6291456 --[[6]], inTangent = 0 --[[0]], outTangent = 0 --[[0]], }, }, }
Dataset = require('datasets/dataset') local MbDataset, parent = torch.class('MbDataset', 'Dataset') function MbDataset:__init(self, opt) parent.__init(parent, self, opt) self.name='mb' end local function createDataset(opt) return MbDataset:new(opt) end function MbDataset:setParams(opt) --parameters for training self.true1 = 0.5 self.false1 = 1.5 self.false2 = 6 -- parameters for image transformations self.hflip = 0 self.vflip= 0 self.rotate = 28 self.hscale = 0.8 self.scale = 0.8 self.trans = 0 self.hshear = 0.1 self.brightness = 1.3 self.contrast = 1.1 self.d_vtrans = 1 self.d_rotate = 3 self.d_hscale = 0.9 self.d_hshear = 0.3 self.d_brightness = 0.7 self.d_contrast = 1.1 self.d_light=0.2 self.d_exp=0.2 --parameters for the network self.rect = opt.rect self.n_colors = opt.color == 'rgb' and 3 or 1 self.color = opt.color self.height = 1500 self.width = 1000 self.disp_max = 200 self.err_at = 1 end function MbDataset:load(opt) local data_dir = ('%s/data.mb.%s_%s'):format(opt.storage, self.rect, self.color) self.te = fromfile(('%s/te.bin'):format(data_dir)) self.metadata = fromfile(('%s/meta.bin'):format(data_dir)) self.nnz_tr = fromfile(('%s/nnz_tr.bin'):format(data_dir)) self.nnz_te = fromfile(('%s/nnz_te.bin'):format(data_dir)) self.fname_submit = {} for line in io.open(('%s/fname_submit.txt'):format(data_dir), 'r'):lines() do table.insert(self.fname_submit, line) end self.X = {} self.dispnoc = {} local fname = "" for n = 1,self.metadata:size(1) do local XX = {} local light = 1 while true do fname = ('%s/x_%d_%d.bin'):format(data_dir, n, light) if not paths.filep(fname) then break end table.insert(XX, fromfile(fname)) light = light + 1 if opt.a == 'test_te' or opt.a == 'submit' then break -- we don't need to load training data end end table.insert(self.X, XX) fname = ('%s/dispnoc%d.bin'):format(data_dir, n) if paths.filep(fname) then table.insert(self.dispnoc, fromfile(fname)) end end end function MbDataset:subset(ds,tr, subset) local tr_2014 = Dataset.sample(torch.range(11, 23):long(), subset) local tr_2006 = Dataset.sample(torch.range(24, 44):long(), subset) local tr_2005 = Dataset.sample(torch.range(45, 50):long(), subset) local tr_2003 = Dataset.sample(torch.range(51, 52):long(), subset) local tr_2001 = Dataset.sample(torch.range(53, 60):long(), subset) local tr_subset = torch.cat(tr_2014, tr_2006) tr_subset = torch.cat(tr_subset, tr_2005) tr_subset = torch.cat(tr_subset, tr_2003) tr_subset = torch.cat(tr_subset, tr_2001) local nnz_tr_output = torch.FloatTensor(ds:size()):zero() local t = adcensus.subset_dataset(tr_subset, ds, nnz_tr_output); return nnz_tr_output[{{1,t}}] end function MbDataset:getSubmissionRange() local examples = {} -- for i = #X - 14, #X do for i = #self.X - 29, #self.X do table.insert(examples, {i, 2}) end return examples end function MbDataset:getTestTange() local examples = {} for i = 1,self.te:nElement() do table.insert(examples, {self.te[i], 2}) end table.insert(examples, {5, 3}) table.insert(examples, {5, 4}) return examples end function MbDataset:getTestSample(i) local img = {} local i, right = table.unpack(i) img.id = ('%d_%d'):format(i, right) img.disp_max = self.metadata[{i,3}] local x0 = self.X[i][1][{{1}}] local x1 = self.X[i][1][{{right}}] img.x_batch = torch.CudaTensor(2, self.n_colors, self.height, self.width) img.x_batch:resize(2, self.n_colors, x0:size(3), x0:size(4)) --print(img.x_batch:size(), x0:size()) img.x_batch[1]:copy(x0) img.x_batch[2]:copy(x1) img.dispnoc = self.dispnoc[i]:cuda() return img end function MbDataset:prepareTrainingData(subset, action, all) -- subset training dataset if subset < 1 then self.nnz = self:subset(self.nnz_tr, self.tr, subset) elseif all then self.nnz = torch.cat(self.nnz_tr, self.nnz_te, 1) else self.nnz = self.nnz_tr end self.disp = self.nnz self.nnz_disp = self.nnz_tr end function MbDataset:getLR(img) local x0, x1 local light = (torch.random() % (#self.X[img] - 1)) + 2 local exp = (torch.random() % self.X[img][light]:size(1)) + 1 local light_ = light local exp_ = exp if torch.uniform() < self.d_exp then exp_ = (torch.random() % self.X[img][light]:size(1)) + 1 end if torch.uniform() < self.d_light then light_ = math.max(2, light - 1) end x0 = self.X[img][light][{exp,1}] x1 = self.X[img][light_][{exp_,2}] return x0, x1 end function fromfile(fname) -- initialize a tensor of the proper type and dimensions from the file fname local file = io.open(fname .. '.dim') local dim = {} for line in file:lines() do table.insert(dim, tonumber(line)) end if #dim == 1 and dim[1] == 0 then return torch.Tensor() end local file = io.open(fname .. '.type') local type = file:read('*all') local x if type == 'float32' then x = torch.FloatTensor(torch.FloatStorage(fname)) elseif type == 'int32' then x = torch.IntTensor(torch.IntStorage(fname)) elseif type == 'int64' then x = torch.LongTensor(torch.LongStorage(fname)) else print(fname, type) assert(false) end x = x:reshape(torch.LongStorage(dim)) return x end return createDataset
object_mobile_rebel_specforce_hum_m = object_mobile_shared_rebel_specforce_hum_m:new { } ObjectTemplates:addTemplate(object_mobile_rebel_specforce_hum_m, "object/mobile/rebel_specforce_hum_m.iff")
local obj = {} obj.__index = obj -- Metadata obj.name = "weather" obj.version = "1.0" obj.author = "Pavel Makhov" obj.homepage = "https://fork-my-spoons.github.io/" obj.license = "MIT - https://opensource.org/licenses/MIT" obj.indicator = nil obj.timer = nil obj.api_key = nil obj.lat = nil obj.lon = nil obj.iconPath = hs.spoons.resourcePath("icons") local wind_icon = hs.styledtext.new(' ', { font = {name = 'feather', size = 12 }}) local humidity_icon = hs.styledtext.new(' ', { font = {name = 'feather', size = 12 }}) local sunrise_icon = hs.styledtext.new(' ', { font = {name = 'feather', size = 16 }}) local sunset_icon = hs.styledtext.new(' ', { font = {name = 'feather', size = 16 }}) local sun_icon = hs.styledtext.new(' ', { font = {name = 'feather', size = 16 }, color = {hex = '#F4A71D'}}) local moon_icon = hs.styledtext.new(' ', { font = {name = 'feather', size = 16 }, color = {hex = '#72B8D4'}}) local icon_map = { ["01d"] = "clear", ["02d"] = "mostlysunny", ["03d"] = "partlycloudy", ["04d"] = "partlycloudy", ["09d"] = "chancerain", ["10d"] = "rain", ["11d"] = "tstorm", ["13d"] = "snow", ["50d"] = "fog", ["01n"] = "nt_clear", ["02n"] = "nt_mostlysunny", ["03n"] = "nt_partlycloudy", ["04n"] = "nt_partlycloudy", ["09n"] = "nt_chancerain", ["10n"] = "nt_rain", ["11n"] = "nt_tstorm", ["13n"] = "nt_snow", ["50n"] = "nt_fog" } local function updateMenu() local query if obj.lat ~= nil and obj.lon ~= nil then query = string.format('lat=%s&lon=%s', obj.lat, obj.lon) else query = 'q=' .. obj.city end local url = string.format('http://api.openweathermap.org/data/2.5/weather?%s&appid=%s&units=%s', query, obj.app_id, obj.units) hs.http.asyncGet(url, nil, function(status, body) local weather = hs.json.decode(body) obj.indicator:setTitle(math.floor(weather.main.temp + 0.5)) obj.indicator:setIcon(hs.image.imageFromPath(obj.iconPath .. '/white/png/32x32/' .. icon_map[weather.weather[1].icon] .. '.png'):setSize({w=16,h=16}), false) local menu = {} table.insert(menu, { image = hs.image.imageFromPath(obj.iconPath .. '/white/png/128x128/' .. icon_map[weather.weather[1].icon] .. '.png'):setSize({w=64,h=64}), title = hs.styledtext.new('Feels like ' .. math.floor(weather.main.feels_like) .. '\n') .. hs.styledtext.new(weather.weather[1].description .. '\n') .. wind_icon .. hs.styledtext.new(weather.wind.speed .. ' m/s\n') .. humidity_icon .. hs.styledtext.new(weather.main.humidity .. ' %') }) local sunrise = weather.sys.sunrise local sunset = weather.sys.sunset local now = weather.dt local is_night = now > sunset if is_night then s = sunset e = sunrise + 86400 else s = sunrise e = sunset end local pct = (weather.dt - s) / (e - s) local c = math.floor(40 * pct) table.insert(menu, {title = '-'}) table.insert(menu, { title = (is_night and sunset_icon or sunrise_icon) .. hs.styledtext.new(string.rep(' ', c)) .. (is_night and moon_icon or sun_icon) .. hs.styledtext.new(string.rep(' ', 40 - c)) .. (is_night and sunrise_icon or sunset_icon) .. hs.styledtext.new('\n') .. hs.styledtext.new(os.date("%H:%M", s)) .. hs.styledtext.new(string.rep(' ', 38)) .. hs.styledtext.new(os.date("%H:%M", e), {color = {hex = '#ffffff'}}) }) obj.indicator:setMenu(menu) end) end function obj:init() self.indicator = hs.menubar.new() self.timer = hs.timer.new(300, updateMenu) end function obj:setup(args) self.app_id = args.app_id self.lat = args.lat self.lon = args.lon self.city = args.city if (args.units == 'f' or args.units == 'F') then self.units = 'imperial' else self.units = 'metric' end end function obj:start() self.timer:fire() self.timer:start() end return obj
-- Wiebel instability Pi = Lucee.Pi log = Lucee.logInfo -- physical parameters (two electron streams: "ions" are really electrons!) gasGamma = 5./3. elcCharge = -1.0 ionCharge = -1.0 ionMass = 1.0 elcMass = 1.0 lightSpeed = 1.0 epsilon0 = 1.0 mu0 = 1.0 mgnErrorSpeedFactor = 1.0 -- simulation parameters udrift1 = 0.3 udrift2 = -0.3 k0 = 1.6 -- wave number elcTemp = 0.01 Lx = 1.0 Ly = 2*Lucee.Pi/k0 n0 = 0.5 -- resolution and time-stepping NX = 1 NY = 1024 cfl = 0.9 tStart = 0.0 tEnd = 150.0 nFrames = 75 ------------------------------------------------ -- COMPUTATIONAL DOMAIN, DATA STRUCTURE, ETC. -- ------------------------------------------------ -- decomposition object decomp = DecompRegionCalc2D.CartGeneral {} -- computational domain grid = Grid.RectCart2D { lower = {0.0, 0.0}, upper = {1.0, Ly}, cells = {NX, NY}, decomposition = decomp, periodicDirs = {0, 1}, } -- solution q = DataStruct.Field2D { onGrid = grid, numComponents = 18, ghost = {2, 2}, } -- solution after update along X (ds algorithm) qX = DataStruct.Field2D { onGrid = grid, numComponents = 18, ghost = {2, 2}, } -- final updated solution qNew = DataStruct.Field2D { onGrid = grid, numComponents = 18, ghost = {2, 2}, } -- duplicate copy in case we need to take the step again qDup = DataStruct.Field2D { onGrid = grid, numComponents = 18, ghost = {2, 2}, } qNewDup = DataStruct.Field2D { onGrid = grid, numComponents = 18, ghost = {2, 2}, } -- aliases to various sub-systems elcFluid = q:alias(0, 5) ionFluid = q:alias(5, 10) emField = q:alias(10, 18) elcFluidX = qX:alias(0, 5) ionFluidX = qX:alias(5, 10) emFieldX = qX:alias(10, 18) elcFluidNew = qNew:alias(0, 5) ionFluidNew = qNew:alias(5, 10) emFieldNew = qNew:alias(10, 18) ----------------------- -- INITIAL CONDITION -- ----------------------- -- initial conditions function init(x,y,z) local rho = elcMass*n0 local pr0 = n0*elcTemp local Bz = 1e-3*math.sin(k0*y) local u1 = udrift1 local Er1 = pr0/(gasGamma-1) + 0.5*rho*u1^2 local u2 = udrift2 local Er2 = pr0/(gasGamma-1) + 0.5*rho*u2^2 return rho, rho*u1, 0.0, 0.0, Er1, rho, rho*u2, 0.0, 0.0, Er2, 0.0, 0.0, 0.0, 0.0, 0.0, Bz, 0.0, 0.0 end ------------------------ -- Boundary Condition -- ------------------------ -- boundary applicator objects for fluids and fields -- function to apply boundary conditions to specified field function applyBc(fld, tCurr, myDt) for i,bc in ipairs({}) do bc:setOut( {fld} ) bc:advance(tCurr+myDt) end -- copy BCs in Y fld:applyCopyBc(1, "lower") fld:applyCopyBc(1, "upper") -- sync ghost cells fld:sync() end ---------------------- -- EQUATION SOLVERS -- ---------------------- -- regular Euler equations elcEulerEqn = HyperEquation.Euler { gasGamma = gasGamma, } ionEulerEqn = HyperEquation.Euler { gasGamma = gasGamma, } -- (Lax equations are used to fix negative pressure/density) elcEulerLaxEqn = HyperEquation.Euler { gasGamma = gasGamma, numericalFlux = "lax", } ionEulerLaxEqn = HyperEquation.Euler { gasGamma = gasGamma, numericalFlux = "lax", } maxwellEqn = HyperEquation.PhMaxwell { lightSpeed = lightSpeed, elcErrorSpeedFactor = 0.0, mgnErrorSpeedFactor = mgnErrorSpeedFactor } -- ds solvers for regular Euler equations along X elcFluidSlvrDir0 = Updater.WavePropagation2D { onGrid = grid, equation = elcEulerEqn, limiter = "van-leer", cfl = cfl, cflm = 1.1*cfl, updateDirections = {0} -- directions to update } ionFluidSlvrDir0 = Updater.WavePropagation2D { onGrid = grid, equation = ionEulerEqn, limiter = "van-leer", cfl = cfl, cflm = 1.1*cfl, updateDirections = {0} } maxSlvrDir0 = Updater.WavePropagation2D { onGrid = grid, equation = maxwellEqn, limiter = "van-leer", cfl = cfl, cflm = 1.1*cfl, updateDirections = {0} } -- ds solvers for regular Euler equations along Y elcFluidSlvrDir1 = Updater.WavePropagation2D { onGrid = grid, equation = elcEulerEqn, limiter = "van-leer", cfl = cfl, cflm = 1.1*cfl, updateDirections = {1} } ionFluidSlvrDir1 = Updater.WavePropagation2D { onGrid = grid, equation = ionEulerEqn, limiter = "van-leer", cfl = cfl, cflm = 1.1*cfl, updateDirections = {1} } maxSlvrDir1 = Updater.WavePropagation2D { onGrid = grid, equation = maxwellEqn, limiter = "van-leer", cfl = cfl, cflm = 1.1*cfl, updateDirections = {1} } -- ds solvers for Lax Euler equations along X elcLaxSlvrDir0 = Updater.WavePropagation2D { onGrid = grid, equation = elcEulerLaxEqn, limiter = "zero", cfl = cfl, cflm = 1.1*cfl, updateDirections = {0} } ionLaxSlvrDir0 = Updater.WavePropagation2D { onGrid = grid, equation = ionEulerLaxEqn, limiter = "zero", cfl = cfl, cflm = 1.1*cfl, updateDirections = {0} } maxLaxSlvrDir0 = Updater.WavePropagation2D { onGrid = grid, equation = maxwellEqn, limiter = "zero", cfl = cfl, cflm = 1.1*cfl, updateDirections = {0} } -- ds solvers for Lax Euler equations along Y elcLaxSlvrDir1 = Updater.WavePropagation2D { onGrid = grid, equation = elcEulerLaxEqn, limiter = "zero", cfl = cfl, cflm = 1.1*cfl, updateDirections = {1} } ionLaxSlvrDir1 = Updater.WavePropagation2D { onGrid = grid, equation = ionEulerLaxEqn, limiter = "zero", cfl = cfl, cflm = 1.1*cfl, updateDirections = {1} } maxLaxSlvrDir1 = Updater.WavePropagation2D { onGrid = grid, equation = maxwellEqn, limiter = "zero", cfl = cfl, cflm = 1.1*cfl, updateDirections = {1} } -- updater for source terms sourceSlvr = Updater.ImplicitFiveMomentSrc2D { onGrid = grid, numFluids = 2, charge = {elcCharge, ionCharge}, mass = {elcMass, ionMass}, epsilon0 = epsilon0, -- linear solver to use: one of partialPivLu or colPivHouseholderQr linearSolver = "partialPivLu", hasStaticField = false, } elcIonMomRelax = Updater.TwoFluidMomentumRelaxation2D { onGrid = grid, electronIonCollisionFrequency = 0.0, frictionFactor = 0.5 } -- function to update source terms function updateSource(elcIn, ionIn, emIn, tCurr, t) sourceSlvr:setOut( {elcIn, ionIn, emIn} ) sourceSlvr:setCurrTime(tCurr) sourceSlvr:advance(t) end -- function to update the fluid and field using dimensional splitting function updateFluidsAndField(tCurr, t) local myStatus = true local myDtSuggested = 1e3*math.abs(t-tCurr) local useLaxSolver = False -- X-direction updates for i,slvr in ipairs({elcFluidSlvrDir0, ionFluidSlvrDir0, maxSlvrDir0}) do slvr:setCurrTime(tCurr) local status, dtSuggested = slvr:advance(t) myStatus = status and myStatus myDtSuggested = math.min(myDtSuggested, dtSuggested) end if ((elcEulerEqn:checkInvariantDomain(elcFluidX) == false) or (ionEulerEqn:checkInvariantDomain(ionFluidX) == false)) then useLaxSolver = true end if ((myStatus == false) or (useLaxSolver == true)) then return myStatus, myDtSuggested, useLaxSolver end -- apply BCs to intermediate update after X sweep applyBc(qX, tCurr, t-tCurr) -- Y-direction updates for i,slvr in ipairs({elcFluidSlvrDir1, ionFluidSlvrDir1, maxSlvrDir1}) do slvr:setCurrTime(tCurr) local status, dtSuggested = slvr:advance(t) myStatus = status and myStatus myDtSuggested = math.min(myDtSuggested, dtSuggested) end if ((elcEulerEqn:checkInvariantDomain(elcFluidNew) == false) or (ionEulerEqn:checkInvariantDomain(ionFluidNew) == false)) then useLaxSolver = true end return myStatus, myDtSuggested, useLaxSolver end -- function to take one time-step with Euler solver function solveTwoFluidSystem(tCurr, t) local dthalf = 0.5*(t-tCurr) -- update source terms updateSource(elcFluid, ionFluid, emField, tCurr, tCurr+dthalf) applyBc(q, tCurr, t-tCurr) -- update fluids and fields local status, dtSuggested, useLaxSolver = updateFluidsAndField(tCurr, t) -- update source terms updateSource(elcFluidNew, ionFluidNew, emFieldNew, tCurr, tCurr+dthalf) applyBc(qNew, tCurr, t-tCurr) return status, dtSuggested,useLaxSolver end -- function to update the fluid and field using dimensional splitting Lax scheme function updateFluidsAndFieldLax(tCurr, t) local myStatus = true local myDtSuggested = 1e3*math.abs(t-tCurr) for i,slvr in ipairs({elcLaxSlvrDir0, ionLaxSlvrDir0, maxLaxSlvrDir0}) do slvr:setCurrTime(tCurr) local status, dtSuggested = slvr:advance(t) myStatus = status and myStatus myDtSuggested = math.min(myDtSuggested, dtSuggested) end applyBc(qX, tCurr, t-tCurr) -- Y-direction updates for i,slvr in ipairs({elcLaxSlvrDir1, ionLaxSlvrDir1, maxLaxSlvrDir1}) do slvr:setCurrTime(tCurr) local status, dtSuggested = slvr:advance(t) myStatus = status and myStatus myDtSuggested = math.min(myDtSuggested, dtSuggested) end return myStatus, myDtSuggested end -- function to take one time-step with Lax Euler solver function solveTwoFluidLaxSystem(tCurr, t) local dthalf = 0.5*(t-tCurr) -- update source terms updateSource(elcFluid, ionFluid, emField, tCurr, tCurr+dthalf) applyBc(q, tCurr, t-tCurr) -- update fluids and fields local status, dtSuggested = updateFluidsAndFieldLax(tCurr, t) -- update source terms updateSource(elcFluidNew, ionFluidNew, emFieldNew, tCurr, tCurr+dthalf) applyBc(qNew, tCurr, t-tCurr) return status, dtSuggested end ---------------------------- -- DIAGNOSIS AND DATA I/O -- ---------------------------- -- dynvector to store integrated flux -- dynvector to store magnetic energy bz2 = DataStruct.DynVector { numComponents = 1 } bz2Calc = Updater.IntegrateField2D { onGrid = grid, -- index of cell to record integrand = function (ex, ey, ez, bx, by, bz, e1, e2) return bz^2 end, } bz2Calc:setIn( {emField} ) bz2Calc:setOut( {bz2} ) -- compute diagnostic function calcDiagnostics(tCurr, myDt) for i,diag in ipairs({bz2Calc}) do diag:setCurrTime(tCurr) diag:advance(tCurr+myDt) end end -- write data to H5 files function writeFields(frame, t) qNew:write( string.format("q_%d.h5", frame), t ) bz2:write( string.format("bz2_%d.h5", frame) ) end ---------------------------- -- TIME-STEPPING FUNCTION -- ---------------------------- function runSimulation(tStart, tEnd, nFrames, initDt) local frame = 1 local tFrame = (tEnd-tStart)/nFrames local nextIOt = tFrame local step = 1 local tCurr = tStart local myDt = initDt local status, dtSuggested local useLaxSolver = false -- the grand loop while true do -- copy q and qNew in case we need to take this step again qDup:copy(q) qNewDup:copy(qNew) -- if needed adjust dt to hit tEnd exactly if (tCurr+myDt > tEnd) then myDt = tEnd-tCurr end -- advance fluids and fields if (useLaxSolver) then -- call Lax solver if positivity violated log (string.format(" Taking step %5d at time %6g with dt %g (using Lax solvers)", step, tCurr, myDt)) status, dtSuggested = solveTwoFluidLaxSystem(tCurr, tCurr+myDt) useLaxSolver = false else log (string.format(" Taking step %5d at time %6g with dt %g", step, tCurr, myDt)) status, dtSuggested, useLaxSolver = solveTwoFluidSystem(tCurr, tCurr+myDt) end if (status == false) then -- time-step too large log (string.format(" ** Time step %g too large! Will retake with dt %g", myDt, dtSuggested)) myDt = dtSuggested qNew:copy(qNewDup) q:copy(qDup) elseif (useLaxSolver == true) then -- negative density/pressure occured log (string.format(" ** Negative pressure or density at %8g! Will retake step with Lax fluxes", tCurr+myDt)) q:copy(qDup) qNew:copy(qNewDup) else -- check if a nan occured if (qNew:hasNan()) then log (string.format(" ** NaN occured at %g! Stopping simulation", tCurr)) break end -- compute diagnostics calcDiagnostics(tCurr, myDt) -- copy updated solution back q:copy(qNew) -- write out data if (tCurr+myDt > nextIOt or tCurr+myDt >= tEnd) then log (string.format(" Writing data at time %g (frame %d) ...\n", tCurr+myDt, frame)) writeFields(frame, tCurr+myDt) frame = frame + 1 nextIOt = nextIOt + tFrame step = 0 end tCurr = tCurr + myDt myDt = dtSuggested step = step + 1 -- check if done if (tCurr >= tEnd) then break end end end -- end of time-step loop return dtSuggested end ---------------------------- -- RUNNING THE SIMULATION -- ---------------------------- -- setup initial condition q:set(init) q:sync() qNew:copy(q) -- set input/output arrays for various solvers elcFluidSlvrDir0:setIn( {elcFluid} ) elcFluidSlvrDir0:setOut( {elcFluidX} ) ionFluidSlvrDir0:setIn( {ionFluid} ) ionFluidSlvrDir0:setOut( {ionFluidX} ) maxSlvrDir0:setIn( {emField} ) maxSlvrDir0:setOut( {emFieldX} ) elcFluidSlvrDir1:setIn( {elcFluidX} ) elcFluidSlvrDir1:setOut( {elcFluidNew} ) ionFluidSlvrDir1:setIn( {ionFluidX} ) ionFluidSlvrDir1:setOut( {ionFluidNew} ) maxSlvrDir1:setIn( {emFieldX} ) maxSlvrDir1:setOut( {emFieldNew} ) elcLaxSlvrDir0:setIn( {elcFluid} ) elcLaxSlvrDir0:setOut( {elcFluidX} ) ionLaxSlvrDir0:setIn( {ionFluid} ) ionLaxSlvrDir0:setOut( {ionFluidX} ) maxLaxSlvrDir0:setIn( {emField} ) maxLaxSlvrDir0:setOut( {emFieldX} ) elcLaxSlvrDir1:setIn( {elcFluidX} ) elcLaxSlvrDir1:setOut( {elcFluidNew} ) ionLaxSlvrDir1:setIn( {ionFluidX} ) ionLaxSlvrDir1:setOut( {ionFluidNew} ) maxLaxSlvrDir1:setIn( {emFieldX} ) maxLaxSlvrDir1:setOut( {emFieldNew} ) -- apply BCs on initial conditions applyBc(q, 0.0, 0.0) applyBc(qNew, 0.0, 0.0) -- write initial conditions calcDiagnostics(0.0, 0.0) writeFields(0, 0.0) initDt = 100.0 runSimulation(tStart, tEnd, nFrames, initDt)
------------------------------------------------------------------------ --[[FineCoarseCriterion ]]-- -- Lin Sun 2016@Stanford ------------------------------------------------------------------------ require 'nn' require 'rnn' local FineCoarseCriterion, parent = torch.class('nn.FineCoarseCriterion2_bc2', 'nn.Criterion') function FineCoarseCriterion:__init(criterion, fm, bm) parent.__init(self) self.criterion_f = criterion self.criterion_c = criterion self.fm = fm self.bm = bm print(#fm, #bm) if torch.isTypeOf(criterion, 'nn.ModuleCriterion') then error("SequencerCriterion shouldn't decorate a ModuleCriterion. ".. "Instead, try the other way around : ".. "ModuleCriterion decorates a SequencerCriterion. ".. "Its modules can also be similarly decorated with a Sequencer.") end self.clones_f = {} self.clones_c = {} self.gradInput = {} print('[INFO] using nn.FineCoarseCriterion2') end function FineCoarseCriterion:getStepCriterion(step) assert(step, "expecting step at arg 1") local criterion_f = self.clones_f[step] local criterion_c = self.clones_c[step] if not criterion_f or not criterion_c then criterion_f = self.criterion_f:clone() self.clones_f[step] = criterion_f criterion_c = self.criterion_c:clone() self.clones_c[step] = criterion_c end return criterion_f, criterion_c end function FineCoarseCriterion:updateOutput(input, target_both) self.output = 0 local target = target_both.f local ctarget = target_both.c local nStep if torch.isTensor(input) then assert(torch.isTensor(target), "expecting target Tensor since input is a Tensor") assert(target:size(1) == input:size(1), "target should have as many elements as input") nStep = input:size(1) else assert(torch.type(target) == 'table', "expecting target table") assert(#target == #input, "target should have as many elements as input") nStep = #input end for i=1,nStep do local criterion_f, criterion_c = self:getStepCriterion(i) ii = i num = ii -- ii = i - 1 -- num = ii * 2 temp = input[i]:clone() cinput = nn.Log():forward(nn.Exp():forward(temp:float()) * self.fm:float()) if true then self.output = self.output + (num/nStep)*0.5*criterion_f:forward(input[i], target[i]) + (1.0-num/nStep)*0.5*criterion_c:forward(cinput:cuda(), ctarget[i]) -- self.output = self.output + criterion_f:forward(input[i], target[i]) + criterion_c:forward(cinput:cuda(), ctarget[i]) else self.output = self.output + criterion_f:forward(input[i], target[i]) + 0*criterion_c:forward(cinput:cuda(), ctarget[i]) end -- print("forward") -- print(criterion_f.output) -- print(criterion_c.output) end return self.output end function FineCoarseCriterion:updateGradInput(input, target_both) local target = target_both.f local ctarget = target_both.c self.gradInput = {} if torch.isTensor(input) then assert(torch.isTensor(target), "expecting target Tensor since input is a Tensor") assert(target:size(1) == input:size(1), "target should have as many elements as input") nStep = input:size(1) else assert(torch.type(target) == 'table', "expecting gradOutput table") assert(#target == #input, "target should have as many elements as input") nStep = #input end local fineGradInput = {} local coarseGradInput = {} local tableGradInput = {} for i=1,nStep do ii = i num = ii -- ii = i - i -- num = ii * 2 local criterion_f, criterion_c = self:getStepCriterion(i) fineGradInput[i] = criterion_f:backward(input[i], target[i]) --print('input') --print(torch.sum(input[i])) temp = input[i]:clone() exp = nn.Exp() middle1 = exp:forward(temp:float()) middle2 = middle1 * self.fm:float() cinput = nn.Log():forward(middle2) d_loss= criterion_c:backward(cinput:cuda(),ctarget[i]):float() --print('values') --print(torch.sum(loss)) --print(torch.sum(value)) --print(torch.sum(middle)) d_cinput = nn.Log():backward(middle2, d_loss) d_middle1 = d_cinput * self.bm:float() d_temp = exp:backward(temp, d_middle1) coarseGradInput[i] = d_temp:cuda() -- print('max') print ('Iter', i) print('coarseGradInput_min:', torch.min(coarseGradInput[i])) print('fineGradInput_min: ', torch.min(fineGradInput[i])) print('coarseGradInput_sum:', torch.sum(fineGradInput[i])) print('fineGradInput_sum: ', torch.sum(coarseGradInput[i])) -- print (coarseGradInput[i]) if torch.min(coarseGradInput[i]) > -0.005 then -- tableGradInput[i] = (num/nStep)*fineGradInput[i] + (1.0-num/nStep)*coarseGradInput[i] tableGradInput[i] = (num/nStep)*0.5*fineGradInput[i] + (1.0-num/nStep)*0.5*coarseGradInput[i] else -- tableGradInput[i] = 0*fineGradInput[i] + (1.0-num/nStep)*0.5*coarseGradInput[i] tableGradInput[i] = (num/nStep)*0.5*fineGradInput[i] + 0*coarseGradInput[i] end end if torch.isTensor(input) then self.gradInput = tableGradInput[1].new() self.gradInput:resize(nStep, unpack(tableGradInput[1]:size():totable())) for step=1,nStep do self.gradInput[step]:copy(tableGradInput[step]) end else self.gradInput = tableGradInput end return self.gradInput end
---- -- Tests for the xlsxwriter.lua styles class. -- -- Copyright 2014, John McNamara, [email protected] -- require "Test.More" require "Test.LongString" plan(1) ---- -- Tests setup. -- local expected local got local caption local Styles = require "xlsxwriter.styles" local Workbook = require "xlsxwriter.workbook" local styles local workbook -- Remove extra whitespace in the formatted XML strings. function _clean_xml_string(s) return (string.gsub(s, ">%s+<", "><")) end ---- -- Test the _write_styles() method. -- caption = " \tStyles: Styles: _assemble_xml_file()" expected = _clean_xml_string([[ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"> <fonts count="1"> <font> <sz val="11"/> <color theme="1"/> <name val="Calibri"/> <family val="2"/> <scheme val="minor"/> </font> </fonts> <fills count="2"> <fill> <patternFill patternType="none"/> </fill> <fill> <patternFill patternType="gray125"/> </fill> </fills> <borders count="14"> <border> <left/> <right/> <top/> <bottom/> <diagonal/> </border> <border> <left/> <right/> <top style="hair"> <color auto="1"/> </top> <bottom/> <diagonal/> </border> <border> <left/> <right/> <top style="dotted"> <color auto="1"/> </top> <bottom/> <diagonal/> </border> <border> <left/> <right/> <top style="dashDotDot"> <color auto="1"/> </top> <bottom/> <diagonal/> </border> <border> <left/> <right/> <top style="dashDot"> <color auto="1"/> </top> <bottom/> <diagonal/> </border> <border> <left/> <right/> <top style="dashed"> <color auto="1"/> </top> <bottom/> <diagonal/> </border> <border> <left/> <right/> <top style="thin"> <color auto="1"/> </top> <bottom/> <diagonal/> </border> <border> <left/> <right/> <top style="mediumDashDotDot"> <color auto="1"/> </top> <bottom/> <diagonal/> </border> <border> <left/> <right/> <top style="slantDashDot"> <color auto="1"/> </top> <bottom/> <diagonal/> </border> <border> <left/> <right/> <top style="mediumDashDot"> <color auto="1"/> </top> <bottom/> <diagonal/> </border> <border> <left/> <right/> <top style="mediumDashed"> <color auto="1"/> </top> <bottom/> <diagonal/> </border> <border> <left/> <right/> <top style="medium"> <color auto="1"/> </top> <bottom/> <diagonal/> </border> <border> <left/> <right/> <top style="thick"> <color auto="1"/> </top> <bottom/> <diagonal/> </border> <border> <left/> <right/> <top style="double"> <color auto="1"/> </top> <bottom/> <diagonal/> </border> </borders> <cellStyleXfs count="1"> <xf numFmtId="0" fontId="0" fillId="0" borderId="0"/> </cellStyleXfs> <cellXfs count="14"> <xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/> <xf numFmtId="0" fontId="0" fillId="0" borderId="1" xfId="0" applyBorder="1"/> <xf numFmtId="0" fontId="0" fillId="0" borderId="2" xfId="0" applyBorder="1"/> <xf numFmtId="0" fontId="0" fillId="0" borderId="3" xfId="0" applyBorder="1"/> <xf numFmtId="0" fontId="0" fillId="0" borderId="4" xfId="0" applyBorder="1"/> <xf numFmtId="0" fontId="0" fillId="0" borderId="5" xfId="0" applyBorder="1"/> <xf numFmtId="0" fontId="0" fillId="0" borderId="6" xfId="0" applyBorder="1"/> <xf numFmtId="0" fontId="0" fillId="0" borderId="7" xfId="0" applyBorder="1"/> <xf numFmtId="0" fontId="0" fillId="0" borderId="8" xfId="0" applyBorder="1"/> <xf numFmtId="0" fontId="0" fillId="0" borderId="9" xfId="0" applyBorder="1"/> <xf numFmtId="0" fontId="0" fillId="0" borderId="10" xfId="0" applyBorder="1"/> <xf numFmtId="0" fontId="0" fillId="0" borderId="11" xfId="0" applyBorder="1"/> <xf numFmtId="0" fontId="0" fillId="0" borderId="12" xfId="0" applyBorder="1"/> <xf numFmtId="0" fontId="0" fillId="0" borderId="13" xfId="0" applyBorder="1"/> </cellXfs> <cellStyles count="1"> <cellStyle name="Normal" xfId="0" builtinId="0"/> </cellStyles> <dxfs count="0"/> <tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleLight16"/> </styleSheet>]]) styles = Styles:new() workbook = Workbook:new("test.xlsx") workbook:add_format{top = 7 } workbook:add_format{top = 4 } workbook:add_format{top = 11} workbook:add_format{top = 9 } workbook:add_format{top = 3 } workbook:add_format{top = 1 } workbook:add_format{top = 12} workbook:add_format{top = 13} workbook:add_format{top = 10} workbook:add_format{top = 8 } workbook:add_format{top = 2 } workbook:add_format{top = 5 } workbook:add_format{top = 6 } workbook:_set_default_xf_indices() workbook:_prepare_format_properties() local properties = {} properties["xf_formats"] = workbook.xf_formats properties["palette"] = workbook.palette properties["font_count"] = workbook.font_count properties["num_format_count"] = workbook.num_format_count properties["border_count"] = workbook.border_count properties["fill_count"] = workbook.fill_count properties["custom_colors"] = workbook.custom_colors properties["dxf_formats"] = workbook.dxf_formats styles:_set_style_properties(properties) styles:_set_filehandle(io.tmpfile()) styles:_assemble_xml_file() got = _clean_xml_string(styles:_get_data()) is_string(got, expected, caption)
local SymbolCache = {} function SymbolCache.new() return setmetatable({ __tostring = function (self) return self.Key end, }, SymbolCache) end function SymbolCache:__index(index) local value = setmetatable({ Key = index }, self) rawset(self, index, value) -- cache the value so future lookups are cheaper return value end return SymbolCache
require( "iuplua" ) text_field = iup.multiline { expand = "Yes" } button = iup.button { title = "Push" } function button:action() iup.Message( "o.O", "Button pushed" ) return iup.DEFAULT end box = iup.vbox { text_field, button } dialog = iup.dialog { box; title = "Multi-element dialog", size = "HalfxHalf" } dialog:show() iup.MainLoop()