content
stringlengths
5
1.05M
return { { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandomByWeight", targetAniEffect = "", arg_list = { weapon_id = 69231 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69331 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandom", targetAniEffect = "", arg_list = { weapon_id = 69271 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69261 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandomByWeight", targetAniEffect = "", arg_list = { weapon_id = 69232 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69332 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandom", targetAniEffect = "", arg_list = { weapon_id = 69272 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69262 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandomByWeight", targetAniEffect = "", arg_list = { weapon_id = 69233 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69333 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandom", targetAniEffect = "", arg_list = { weapon_id = 69273 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69263 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandomByWeight", targetAniEffect = "", arg_list = { weapon_id = 69234 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69334 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandom", targetAniEffect = "", arg_list = { weapon_id = 69274 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69264 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandomByWeight", targetAniEffect = "", arg_list = { weapon_id = 69235 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69335 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandom", targetAniEffect = "", arg_list = { weapon_id = 69275 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69265 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandomByWeight", targetAniEffect = "", arg_list = { weapon_id = 69236 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69336 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandom", targetAniEffect = "", arg_list = { weapon_id = 69276 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69266 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandomByWeight", targetAniEffect = "", arg_list = { weapon_id = 69237 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69337 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandom", targetAniEffect = "", arg_list = { weapon_id = 69277 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69267 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandomByWeight", targetAniEffect = "", arg_list = { weapon_id = 69238 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69338 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandom", targetAniEffect = "", arg_list = { weapon_id = 69278 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandom", targetAniEffect = "", arg_list = { weapon_id = 69278, delay = 0.5 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69268 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandomByWeight", targetAniEffect = "", arg_list = { weapon_id = 69239 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69339 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandom", targetAniEffect = "", arg_list = { weapon_id = 69279 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandom", targetAniEffect = "", arg_list = { weapon_id = 69279, delay = 0.5 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69269 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandomByWeight", targetAniEffect = "", arg_list = { weapon_id = 69240 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69340 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandom", targetAniEffect = "", arg_list = { weapon_id = 69280 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetHarmRandom", targetAniEffect = "", arg_list = { weapon_id = 69280, delay = 0.5 } }, { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 69270 } } } }, uiEffect = "", name = "Lower", cd = 0, painting = 1, id = 13163, picture = "0", castCV = "skill", desc = "Lower", aniEffect = { effect = "jineng", offset = { 0, -2, 0 } }, effect_list = {} }
local CornellMovieDialogs = torch.class("neuralconvo.CornellMovieDialogs") local stringx = require "pl.stringx" local xlua = require "xlua" function CornellMovieDialogs:__init(dir) self.dir = dir end function CornellMovieDialogs:load() local lines = {} local conversations = {} local count = 1 print("-- Parsing Cornell movie dialogs data set ...") local f = assert(io.open('xiaohuangji50w_fenciA.conv', 'r')) while true do local line = f:read("*line") if line == nil then f:close() break end lines[count] = line count = count + 1 end print("Total lines = "..count) local tmpconv = nil local TOTAL = #lines local count = 0 for i, line in ipairs(lines) do --print(i..' '..line) if string.sub(line, 0, 1) == "E" then if tmpconv ~= nil then --print('new conv'..#tmpconv) table.insert(conversations, tmpconv) end --print('e make the tmpconv') tmpconv = {} end if string.sub(line, 0, 1) == "M" then --print('insert into conv') local tmpl = string.sub(line, 3, #line) --print(tmpl) table.insert(tmpconv, tmpl) end count = count + 1 if count%1000 == 0 then xlua.progress(count, TOTAL) end end return conversations end
{data={name="A-2", author="Magnus siiftun1857 Frankline"}, blocks={ {0x1cafc0, {-40.265, 0}, command={faction=1880}}, {0x1cafc1, {-31.759, -8.09}}, {0x1cafc2, {-34.698, -17.135}, 1.885}, {0x1cafc1, {-31.759, 8.09}}, {0x1cafc2, {-34.698, 17.135}, -1.885}, {0x1cafc3, {-40.014, -13.09}}, {0x1cafc3, {-44.77, -13.09}}, {0x1cafc3, {-49.525, -13.09}}, {0x1cafc3, {-49.525, 0}}, {0x1cafc3, {-54.28, 0}}, {0x1cafc3, {-59.035, 0}}, {0x1cafc3, {-40.014, 13.09}}, {0x1cafc3, {-44.77, 13.09}}, {0x1cafc3, {-49.525, 13.09}}, {0x1cafc3, {-36.621, 23.533}, -0.628}, {0x1cafc3, {-36.621, -23.533}, 0.628}, {0x1cafc2, {-28.82, -17.135}, 1.257}, {0x1cafc2, {-28.82, -27.135}, 1.257}, {0x1cafc2, {-28.82, -37.135}, 1.257}, {0x1cafc3, {-26.896, -43.533}, 2.513}, {0x1cafc3, {-23.503, -33.09}, 3.142}, {0x1cafc2, {-28.82, 17.135}, -1.257}, {0x1cafc2, {-28.82, 27.135}, -1.257}, {0x1cafc2, {-28.82, 37.135}, -1.257}, {0x1cafc3, {-26.896, 43.533}, -2.513}, {0x1cafc3, {-23.503, 33.09}, 3.142}, {0x1cafcc, {-23.252, 0}, 3.142}, {0x1cafc3, {-38.652, 49.713}, -2.513}, {0x1cafcc, {-18.999, -13.09}}, {0x1cafc2, {-8.676, -10.59}, 2.513}, {0x1cafcc, {-18.999, 13.09}}, {0x1cafc2, {-18.187, -23.68}, 2.513}, {0x1cafc2, {-8.676, 10.59}, -2.513}, {0x1cafc2, {-18.187, 23.68}, -2.513}, {0x1cafd6, {1.647, -8.09}, 3.142}, {0x1cafd6, {1.647, 8.09}, 3.142}, {0x1cafc2, {8.529, 0}, 3.142}, {0x1cafc2, {18.039, 3.09}, 3.142}, {0x1cafc2, {18.039, -3.09}, 3.142}, {0x1cafc2, {27.55, 0}, 3.142}, {0x1cafc1, {13.284, -9.635}, 0.628}, {0x1cafc1, {13.284, 9.635}, -0.628}, {0x1cafc3, {-52.01, 40.008}, 0.628}, {0x1cafc3, {-43.127, 33.554}, 1.257}, {0x1cafdb, {24.921, -37.361}}, {0x1cafc2, {37.06, -3.09}, 3.142}, {0x1cafc2, {37.06, 3.09}, 3.142}, {0x1cafc2, {46.571, 0}, 3.142}, {0x1cafc3, {-52.01, -40.008}, -0.628}, {0x1cafc3, {20.417, -11.18}, 3.142}, {0x1cafc3, {25.172, -11.18}, 3.142}, {0x1cafc2, {-40.576, 43.316}, -1.257}, {0x1cafc2, {-45.331, 39.861}, 2.513}, {0x1cafc2, {-34.698, -35.225}, 1.257}, {0x1cafc2, {-40.576, -43.316}, 1.257}, {0x1cafc2, {-45.331, -39.861}, -2.513}, {0x1cafc3, {-38.652, -49.713}, 2.513}, {0x1cafc3, {-43.127, -33.554}, -1.257}, {0x1cafc3, {29.927, -11.18}, 3.142}, {0x1cafc3, {20.417, 11.18}, 3.142}, {0x1cafc3, {25.172, 11.18}, 3.142}, {0x1cafc3, {29.927, 11.18}, 3.142}, {0x1cafc2, {-34.698, 35.225}, -1.257}, {0x1cafc2, {44.755, -52.951}, -2.513}, {0x1cafdb, {11.157, 21.18}, 3.142}, {0x1cafc2, {0.834, 18.68}, 2.513}, {0x1cafc1, {22.795, 22.725}, -0.628}, {0x1cafc2, {18.039, 29.271}, 3.142}, {0x1cafc2, {0.834, 39.861}, -2.513}, {0x1cafc2, {-3.921, 43.316}, -1.885}, {0x1cafc2, {-9.799, 43.316}, -1.257}, {0x1cafc2, {-14.554, 39.861}, -0.628}, {0x1cafc3, {-12.35, 33.554}, 1.257}, {0x1cafc2, {-20.432, 70.312}, -0.628}, {0x1cafc3, {-11.508, 18.533}, -2.513}, {0x1cafdb, {11.157, 37.361}, 3.142}, {0x1cafc2, {30.489, 28.316}, -1.885}, {0x1cafcc, {36.056, 45.451}, 3.142}, {0x1cafc2, {25.733, 47.951}, -2.513}, {0x1cafc2, {20.978, 51.406}, -1.885}, {0x1cafc2, {10.345, 47.951}, -0.628}, {0x1cafc2, {15.1, 51.406}, -1.257}, {0x1cafc1, {35.244, 21.771}, -1.257}, {0x1cafc3, {35.805, 32.361}, 3.142}, {0x1cafc3, {40.561, 32.361}, 3.142}, {0x1cafc2, {44.755, 21.77}, -2.513}, {0x1cafc1, {47.694, 43.906}, -2.513}, {0x1cafc2, {44.755, 52.951}, 2.513}, {0x1cafc2, {35.244, 56.041}, 2.513}, {0x1cafc2, {0.834, -18.68}, -2.513}, {0x1cafc2, {35.244, -56.041}, -2.513}, {0x1cafdb, {11.157, -21.18}, 3.142}, {0x1cafdb, {24.921, 37.361}}, {0x1cafc2, {0.834, -39.861}, 2.513}, {0x1cafc2, {-3.921, -43.316}, 1.885}, {0x1cafc2, {-9.799, -43.316}, 1.257}, {0x1cafc2, {-14.554, -39.861}, 0.628}, {0x1cafc3, {-12.35, -33.554}, -1.257}, {0x1cafc2, {18.039, -29.271}, 3.142}, {0x1cafc1, {22.795, -22.725}, 0.628}, {0x1cafc2, {30.489, -28.316}, 1.885}, {0x1cafc1, {35.244, -21.771}, 1.257}, {0x1cafc2, {44.755, -21.771}, 2.513}, {0x1cafc3, {35.805, -32.361}, 3.142}, {0x1cafc3, {40.561, -32.361}, -3.142}, {0x1cafdb, {11.157, -37.361}, 3.142}, {0x1cafcc, {36.056, -45.451}, -3.142}, {0x1cafc2, {25.733, -47.951}, 2.513}, {0x1cafc2, {20.978, -51.406}, 1.885}, {0x1cafc2, {15.1, -51.406}, 1.257}, {0x1cafc2, {10.345, -47.951}, 0.628}, {0x1cafc1, {47.693, -43.906}, 2.513}, {0x1cafc7, {0.022, -29.271}}, {0x1cafc7, {0.022, 29.271}}, {0x1cafc2, {29.366, -64.131}, -2.513}, {0x1cafc2, {19.856, -67.221}, -2.513}, {0x1cafc2, {29.366, 64.131}, 2.513}, {0x1cafc2, {19.856, 67.221}, 2.513}, {0x1cafc3, {36.045, 63.984}, -2.513}, {0x1cafc3, {27.162, 70.438}, -1.885}, {0x1cafc3, {36.045, -63.984}, 2.513}, {0x1cafc3, {27.162, -70.438}, 1.885}, {0x1cafc3, {13.177, -67.369}, -0.628}, {0x1cafc3, {51.433, -52.803}, 2.513}, {0x1cafc3, {54.826, -42.361}, -3.142}, {0x1cafc3, {54.826, 42.361}, 3.142}, {0x1cafc3, {51.433, 52.803}, -2.513}, {0x1cafc2, {13.978, -75.312}, -2.513}, {0x1cafc2, {13.978, 75.312}, -0.628}, {0x1cafc3, {13.177, 67.369}, 0.628}, {0x1cafc2, {54.265, -24.861}, 2.513}, {0x1cafc2, {54.265, 24.861}, -2.513}, {0x1cafc2, {56.081, -3.09}, 3.142}, {0x1cafc2, {65.592, 0}, 3.142}, {0x1cafc2, {56.081, 3.09}, 3.142}, {0x1cafc2, {54.265, -8.68}, 2.513}, {0x1cafc2, {49.51, -12.135}, 1.885}, {0x1cafc2, {54.265, 8.68}, 0.628}, {0x1cafc2, {49.51, 12.135}, 1.257}, {0x1cafc2, {4.467, -56.041}, 0.628}, {0x1cafc2, {-5.043, -59.131}, 0.628}, {0x1cafc2, {-1.411, -64.131}, 0.628}, {0x1cafc3, {5.268, -63.984}, 2.513}, {0x1cafc3, {-3.615, -70.438}, 1.885}, {0x1cafc3, {-11.722, -59.279}, -0.628}, {0x1cafc2, {-10.921, -67.221}, 0.628}, {0x1cafc2, {4.467, 56.041}, -0.628}, {0x1cafc2, {-5.043, 59.131}, -0.628}, {0x1cafc2, {-10.921, 67.221}, -0.628}, {0x1cafc2, {-1.411, 64.131}, -0.628}, {0x1cafc3, {5.268, 63.984}, -2.513}, {0x1cafc3, {-3.615, 70.438}, -1.885}, {0x1cafc3, {-11.722, 59.279}, 0.628}, {0x1cafc3, {60.944, -25.008}, -2.513}, {0x1cafc3, {60.944, 25.008}, 2.513}, {0x1cafc3, {56.469, 31.167}, -1.257}, {0x1cafc3, {56.469, -31.167}, 1.257}, {0x1cafc2, {-20.432, -47.951}, 0.628}, {0x1cafc2, {-20.432, 47.951}, -0.628}, {0x1cafc3, {-22.636, 54.257}, -1.885}, {0x1cafc3, {-22.636, -54.257}, 1.885}, {0x1cafc3, {-11.508, -18.533}, 2.513}, {0x1cafc3, {-54.28, -13.09}}, {0x1cafc3, {-59.035, -13.09}}, {0x1cafc3, {-63.791, -13.09}}, {0x1cafc3, {-63.791, 0}}, {0x1cafc3, {-68.546, 0}}, {0x1cafc3, {-73.301, 0}}, {0x1cafc3, {-54.28, 13.09}}, {0x1cafc3, {-59.035, 13.09}}, {0x1cafc3, {-63.791, 13.09}}, {0x1cafc3, {-7.661, -21.328}, 2.513}, {0x1cafc3, {-7.661, 21.328}, -2.513}, {0x1cafc2, {4.467, -78.402}, -2.513}, {0x1cafc2, {4.467, 78.402}, -0.628}, {0x1cafc2, {-20.432, -70.312}, 0.628}, {0x1cafc7, {-9.488, 0}}}}
-- Stolen from default local grades = { Grade_Tier01 = 0; Grade_Tier02 = 1; Grade_Tier03 = 2; Grade_Tier04 = 3; Grade_Tier05 = 4; Grade_Tier06 = 5; Grade_Tier07 = 6; Grade_Failed = 7; Grade_None = 8; }; local t = LoadFont("_fishfingers Bold") .. { InitCommand=cmd(zoom,0.75;shadowlength,1;strokecolor,Color("Black")); ShowCommand=cmd(stoptweening;bounceend,0.15;zoomy,0.75); HideCommand=cmd(stoptweening;bouncebegin,0.15;zoomy,0); SetGradeCommand=function(self,params) local pnPlayer = params.PlayerNumber; local sGrade = params.Grade or 'Grade_None'; local gradeString = THEME:GetString("Grade",string.sub(sGrade,7)); self:settext(gradeString); self:diffuse(PlayerColor(pnPlayer)); self:diffusetopedge(BoostColor(PlayerColor(pnPlayer),1.5)); self:strokecolor(BoostColor(PlayerColor(pnPlayer),0.25)); end; }; return t;
local insert = table.insert local path = string.gsub(..., "[^.]+$", "") local Base = require(path.."Base") local Token = require(path.."Token") local Lexer = require(path.."Lexer") local Collector = require(path.."Collector") local Preproc = require(path.."Preproc") local Expander = require(path.."Expander") local Dumper = require(path.."Dumper") local Parser = Base:extend() function Parser:init(writer, fn, options) self.writer = writer self.fn = fn or '(string)' self.main_fn = self.fn self.options = options or {} end function Parser:tokenize(asm) local lexer = Lexer(asm, self.main_fn, self.options) local tokens = {} local loop = true while loop do lexer:lex(function(tt, tok, fn, line) assert(tt, 'Internal Error: missing token') local t = Token(fn, line, tt, tok) insert(tokens, t) -- don't break if this is an included file's EOF if tt == 'EOF' and fn == self.main_fn then loop = false end end) end -- the lexer guarantees an EOL and EOF for a blank file assert(#tokens > 0, 'Internal Error: no tokens after preprocessing') local collector = Collector(self.options) return collector:collect(tokens, self.main_fn) end function Parser:dump() for i, s in ipairs(self.statements) do print(s.line, s.type, s:dump()) end end function Parser:parse(asm) self.statements = self:tokenize(asm) if self.options.debug_token then self:dump() end self.statements = Preproc(self.options):process(self.statements) if self.options.debug_pre then self:dump() end self.statements = Expander(self.options):expand(self.statements) if self.options.debug_post then self:dump() end local dumper = Dumper(self.writer, self.options) self.statements = dumper:load(self.statements) if self.options.debug_asm then self:dump() end if self.options.labels then dumper:export_labels(self.options.labels) end return dumper:dump() end return Parser
local res = {mouse = {}, touch = {}} local min, max, floor = math.min, math.max, math.floor local getWidth = love.graphics.getWidth local getHeight = love.graphics.getHeight local mousegetX = love.mouse.getX local mousegetY = love.mouse.getY local mousegetPosition = love.mouse.getPosition local touchgetPosition = love.touch.getPosition local NULL = function(_) return _ end local clamp = nil local resized = false local olddraw local oldmousepressed local oldmousereleased local oldmousemoved local oldtouchpressed local oldtouchreleased local oldtouchmoved local conf = { centered = false, aspectRatio = true, clampMouse = false, clip = true, width = getWidth(), height = getHeight() } local replaced = {} local scalerW, scalerH = 1, 1 local centerXoffset, centerYoffset = 0, 0 local function f_clamp(n, low, high) if conf.clampMouse then return min(max(n, low), high) end return n end local function check_type(obj, check) local objtype = type(obj) if objtype == "userdata" then if obj.type then objtype = obj:type() end end assert(objtype == check, check.." expected, got "..objtype) end function res.init(c) check_type(c, "table") if c.replace then check_type(c.replace, "table") res.replace(c.replace) end c.width = c.width or getWidth() c.height = c.height or getHeight() conf = c end function res.start() assert(not resized, "Missing \"stop\" function") love.graphics.push() scalerW = getWidth()/conf.width scalerH = getHeight()/conf.height if conf.aspectRatio then scalerW = min(scalerW, scalerH) scalerH = scalerW end if conf.centered then centerXoffset = (getWidth() - conf.width * scalerW)/2 centerYoffset = (getHeight() - conf.height * scalerH)/2 love.graphics.translate(centerXoffset, centerYoffset) else centerXoffset = 0 centerYoffset = 0 end love.graphics.scale(scalerW, scalerH) if conf.clip then love.graphics.setScissor(centerXoffset, centerYoffset, conf.width * scalerW + 1, conf.height * scalerH) end resized = true end function res.stop() assert(resized, "Missing \"start\" function") love.graphics.scale(1/scalerW, 1/scalerH) love.graphics.setScissor() love.graphics.pop() resized = false end function res.toResized(x,y) x = floor(x / scalerW) - centerXoffset / scalerW y = floor(y / scalerH) - centerYoffset / scalerH return x, y end function res.toScreen(x,y) x = floor(x * scalerW) + centerXoffset * scalerW y = floor(y * scalerH) + centerYoffset * scalerH return x, y end function res.mouse.getX() return f_clamp(floor(mousegetX() / scalerW - centerXoffset / scalerW), 0, conf.width) end function res.mouse.getY() return f_clamp(floor(mousegetY() / scalerH - centerYoffset / scalerH), 0, conf.height) end function res.mouse.getPosition() return res.toResized(mousegetPosition()) end function res.touch.getPosition(id) return res.toResized(touchgetPosition(id)) end function res.replace(modules) if #modules == 0 then modules = {"graphics","mouse","touch"} end for i, event in ipairs(modules) do if event == "graphics" and not replaced.graphics then --draw olddraw = love.draw or NULL love.draw = function() res.start() olddraw() res.stop() end end if event == "mouse" and not replaced.mouse then love.mouse.getX = res.mouse.getX love.mouse.getY = res.mouse.getY love.mouse.getPosition = res.mouse.getPosition --mousepressed oldmousepressed = love.mousepressed or NULL love.mousepressed = function(x, y, button, isTouch, presses) x, y = res.toResized(x, y) oldmousepressed(x, y, button, isTouch, presses) end --mousereleased oldmousereleased = love.mousereleased or NULL love.mousereleased = function(x, y, button, isTouch, presses) x, y = res.toResized(x, y) oldmousereleased(x, y, button, isTouch, presses) end --mousemoved oldmousemoved = love.mousemoved or NULL love.mousemoved = function(x, y, dx, dy, isTouch) x, y = res.toResized(x, y) dx, dy = res.toResized(dx, dy) oldmousemoved(x, y, dx, dy, isTouch) end end if event == "touch" and not replaced.touch then love.touch.getPosition = res.touchPosition --touchpressed oldtouchpressed = love.touchpressed or NULL love.touchpressed = function(id, x, y, dx, dy, pressure) x, y = res.toResized(x, y) dx, dy = res.toResized(dx, dy) oldtouchpressed(id, x, y, dx, dy, pressure) end --touchreleased oldtouchreleased = love.touchreleased or NULL love.touchreleased = function(id, x, y, dx, dy, pressure) x, y = res.toResized(x, y) dx, dy = res.toResized(dx, dy) oldtouchreleased(id, x, y, dx, dy, pressure) end --touchmoved oldtouchmoved = love.touchmoved or NULL love.touchmoved = function(id, x, y, dx, dy, pressure) x, y = res.toResized(x, y) dx, dy = res.toResized(dx, dy) oldtouchmoved(id, x, y, dx, dy, pressure) end end replaced[event] = true end end return res
--- -- @author wesen -- @copyright 2020 wesen <[email protected]> -- @release 0.1 -- @license MIT -- local BaseExtension = require "AC-LuaServer.Core.Extension.BaseExtension" local LuaServerApi = require "AC-LuaServer.Core.LuaServerApi" local ServerEventListener = require "AC-LuaServer.Core.ServerEvent.ServerEventListener" --- -- Instantly resets flags to their spawn locations when players drop them. -- -- @type AutoFlagReset -- local AutoFlagReset = BaseExtension:extend() AutoFlagReset:implement(ServerEventListener) --- -- The list of server events for which this class listens -- -- @tfield table serverEventListeners -- AutoFlagReset.serverEventListeners = { onFlagAction = "onFlagAction" } --- -- AutoFlagReset constructor. -- function AutoFlagReset:new() self.super.new(self, "AutoFlagReset", "GemaGameMode") end -- Protected Methods --- -- Initializes the event listeners. -- function AutoFlagReset:initialize() self:registerAllServerEventListeners() end --- -- Removes the event listeners. -- function AutoFlagReset:terminate() self:unregisterAllServerEventListeners() end -- Event Handlers --- -- Event handler that is called when the state of the flag is changed. -- -- @tparam int _cn The client number of the player who changed the state -- @tparam int _action The id of the flag action -- @tparam int _flag The id of the flag whose state was changed -- function AutoFlagReset:onFlagAction(_cn, _action, _flag) if (_action == LuaServerApi.FA_DROP or _action == LuaServerApi.FA_LOST) then LuaServerApi.flagaction(_cn, LuaServerApi.FA_RESET, _flag) end end return AutoFlagReset
--[[ panels.lua Configuration panels --]] local L = LibStub('AceLocale-3.0'):GetLocale('Bagnon-Config') local SLOT_COLOR_TYPES = {} for id, name in pairs(Bagnon.BAG_TYPES) do tinsert(SLOT_COLOR_TYPES, name) end sort(SLOT_COLOR_TYPES) tinsert(SLOT_COLOR_TYPES, 1, 'normal') local SetProfile = function(profile) Bagnon:SetProfile(profile) Bagnon.profile = Bagnon:GetProfile() Bagnon:UpdateFrames() Bagnon.FrameOptions:Update() end StaticPopupDialogs['Bagnon_ConfirmGlobals'] = { text = 'Are you sure you want to disable specific settings for this character? All specific settings will be lost.', OnAccept = function() SetProfile(nil) end, whileDead = 1, exclusive = 1, hideOnEscape = 1, button1 = YES, button2 = NO, timeout = 0, } --[[ Panels ]]-- Bagnon.GeneralOptions = Bagnon.Options:NewPanel(nil, 'Bagnon', L.GeneralDesc, function(self) self:CreateCheck('locked') self:CreateCheck('fading') self:CreateCheck('tipCount') self:CreateCheck('flashFind') self:CreateCheck('emptySlots') self:CreateCheck('displayBlizzard', ReloadUI) end) Bagnon.FrameOptions = Bagnon.Options:NewPanel('Bagnon', L.FrameSettings, L.FrameSettingsDesc, function(self) local frames = self:Create('Dropdown') frames:SetLabel(L.Frame) frames:SetValue(self.frameID) frames:AddLine('inventory', INVENTORY_TOOLTIP) frames:AddLine('bank', BANK) frames:SetCall('OnInput', function(_, v) self.frameID = v end) if GetAddOnEnableState(UnitName('player'), 'Bagnon_GuildBank') >= 2 then frames:AddLine('guild', GUILD_BANK) end if GetAddOnEnableState(UnitName('player'), 'Bagnon_VoidStorage') >= 2 then frames:AddLine('vault', VOID_STORAGE) end local global = self:Create('Check') global:SetLabel(L.CharacterSpecific) global:SetValue(Bagnon:GetSpecificProfile()) global:SetCall('OnInput', function(_, v) if Bagnon:GetSpecificProfile() then StaticPopup_Show('Bagnon_ConfirmGlobals') else SetProfile(CopyTable(Bagnon.sets.global)) end end) self.sets = Bagnon.profile[self.frameID] self:CreateCheck('enabled'):SetDisabled(self.frameID ~= 'inventory' and self.frameID ~= 'bank') if self.sets.enabled then if self.frameID == 'bank' then self:CreateCheck('exclusiveReagent') end -- Display self:CreateHeader(DISPLAY, 'GameFontHighlight', true) self:CreateRow(70, function(row) if self.frameID ~= 'guild' then row:CreateCheck('bagFrame') row:CreateCheck('sort') end row:CreateCheck('search') row:CreateCheck('options') row:CreateCheck('broker') if self.frameID ~= 'vault' then row:CreateCheck('money') end end) -- Appearance self:CreateHeader(L.Appearance, 'GameFontHighlight', true) self:CreateRow(70, function(row) row:CreateColor('color') row:CreateColor('borderColor') row:CreateCheck('reverseBags') row:CreateCheck('reverseSlots') row:CreateCheck('bagBreak') end) self:CreateRow(162, function(row) row:CreateDropdown('strata', 'LOW',LOW, 'MEDIUM',AUCTION_TIME_LEFT2, 'HIGH',HIGH) row:CreatePercentSlider('alpha', 1, 100) row:CreatePercentSlider('scale', 20, 300):SetCall('OnInput', function(self,v) local new = v/100 local old = self.sets.scale local ratio = new / old self.sets.x = self.sets.x / ratio self.sets.y = self.sets.y / ratio self.sets.scale = new Bagnon:UpdateFrames() end) row:Break() row:CreatePercentSlider('itemScale', 20, 300) row:CreateSlider('spacing', -15, 15) row:CreateSlider('columns', 1, 50) end).bottom = -50 end end) Bagnon.DisplayOptions = Bagnon.Options:NewPanel('Bagnon', L.DisplaySettings, L.DisplaySettingsDesc, function(self) self:CreateHeader(L.DisplayInventory, 'GameFontHighlight', true) for i, event in ipairs {'Bank', 'Auction', 'Guildbank', 'Mail', 'Player', 'Trade', 'Gems', 'Craft'} do self:CreateCheck('display' .. event) end self:CreateHeader(L.CloseInventory, 'GameFontHighlight', true) for i, event in ipairs {'Bank', 'Combat', 'Vehicle', 'Vendor'} do self:CreateCheck('close' .. event) end end) Bagnon.ColorOptions = Bagnon.Options:NewPanel('Bagnon', L.ColorSettings, L.ColorSettingsDesc, function(self) self:CreateCheck('glowQuality') self:CreateCheck('glowNew') self:CreateCheck('glowQuest') self:CreateCheck('glowUnusable') self:CreateCheck('glowSets') self:CreateCheck('emptySlots') self:CreateCheck('colorSlots').bottom = 11 if self.sets.colorSlots then self:CreateRow(140, function(self) for i, name in ipairs(SLOT_COLOR_TYPES) do self:CreateColor(name .. 'Color').right = 144 end end) self:CreatePercentSlider('glowAlpha', 1, 100):SetWidth(585) end end)
local PANEL = {} function PANEL:Init() self:SetAlpha(255) self:SetSize(600, ScrH()) self:Center() self.killTime = CurTime() + 39 self.mainCredits = markup.Parse([[ <font=Impulse-Elements32> Framework creator <font=Impulse-Elements23>vin</font> Framework contributor(s) <font=Impulse-Elements23>aLoneWitness</font> Third-party contrbutors <font=Impulse-Elements23>Alex Grist - mysql wrapper FredyH - mysqloo thelastpenguin - pon Kyle Smith - UTF-8 module rebel1234 and Chessnut - animations base wyozi - medialib Dominic Letz - yaml parser Falco - CPPI vin - impulse markup language kikito - tween.lua</font> Powered by <font=Impulse-Elements23>Discord - Discord API Osyris - RbxDiscordProxy Wordpress - Wordpress API</font> Inspired by <font=Impulse-Elements23>Aerolite, Apex-Roleplay and Cookie-Network</font> Testing team <font=Impulse-Elements23>Aquaman Baker Bee Bwah confuseth Solo_D Desxon EnigmaFusion Bobby Shadow Ho greasy breads Jamsu KTG Angrycrumpet Mats Lukyn150 Law Lefton Morgan psycho Ramtin StrangerThanYou ThePersonWhoPlaysGames Twatted Y Tho</font> Special thanks <font=Impulse-Elements23>StrangerThanYou (mapping) aLoneWitness (framework coding and feedback) oscar holmes (early feedback) Law (mod) Bwah (mod) Bee (mod) Lefton (mod) Y Tho (mod and early feedback) morgan (mod and early feedback)</font> </font> ]]..[[ <font=Impulse-Elements32> ]]..impulse.Config.SchemaName..[[ ]]..string.Replace(impulse.Config.SchemaCredits, "\n", "\n ")..[[ </font> <font=Impulse-Elements23> Copyright 2i.games 2021 </font>]], 550) self.scrollY = ScrH() + 160 if CREDIT_MUSIC and CREDIT_MUSIC:IsPlaying() then CREDIT_MUSIC:Stop() end CREDIT_MUSIC = CreateSound(LocalPlayer(), "music/HL2_song20_submix4.mp3") CREDIT_MUSIC:SetSoundLevel(0) CREDIT_MUSIC:ChangeVolume(1) CREDIT_MUSIC:Play() end local bodyCol = Color(30, 30, 30, 190) function PANEL:Paint(w,h) Derma_DrawBackgroundBlur(self) surface.SetDrawColor(bodyCol) -- menu body surface.DrawRect(0, 0, w, h) -- left body self.scrollY = self.scrollY - (FrameTime() * 88) impulse.render.glowgo((w / 2) - 165, self.scrollY + 70, 337, 91) self.mainCredits:Draw(0, self.scrollY + 190, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP) end function PANEL:OnRemove() if CREDIT_MUSIC and CREDIT_MUSIC:IsPlaying() then CREDIT_MUSIC:FadeOut(4) timer.Simple(4, function() if CREDIT_MUSIC:IsPlaying() then CREDIT_MUSIC:Stop() end end) end end function PANEL:Think() if CurTime() > self.killTime then self:AlphaTo(0, 2, 0, function() self:Remove() impulse.MainMenu:AlphaTo(255, 2, 0) end) end end vgui.Register("impulseCredits", PANEL, "DPanel")
include( "shared.lua" ) include( "sh_ranks.lua" ) include( "playerclass.lua" ) include( "cl_jobs.lua" ) CreateClientConVar( "metro_admin_listentoall", 0 , true, true ) DEFAULT_MOTD = "http://phoenixblack.github.io/Metrostroi/manual.html" --MOTD local function ShowMOTD(url) local w = ScrW() * 2/3 local h = ScrH() * 2/3 local browserWindow = vgui.Create("DFrame") browserWindow:SetTitle("Train Manual") browserWindow:SetPos((ScrW() - w)/2, (ScrH() - h)/2) browserWindow:SetSize(w,h) browserWindow.OnClose = function() browser = nil browserWindow = nil end browserWindow:MakePopup() local browser = vgui.Create("DHTML",browserWindow) browser:SetPos(10, 25) browser:SetSize(w - 20, h - 35) browser:OpenURL(url) end local function MOTDCMD(ply,cmd,args,fullstring) local url = GetConVarString("metro_motd_overrideurl") if tonumber(url) ~= nil then return end if url == "" then url = DEFAULT_MOTD end ShowMOTD(url) end concommand.Add("metro_showmotd",MOTDCMD,nil,"Show the message of the day again")
import 'nn' function fill_net(net) if net.modules then for i = 1, #net.modules do fill_net(net.modules[i]) end end if net.weight then net.weight = torch.rand(net.weight:size()) end if net.bias then net.bias = torch.rand(net.bias:size()) end end function save(net, input, label) fill_net(net) output = net:forward(input) --torch.save(label .. '_net.dat', net) torch.save(label .. '_net.txt', net, 'ascii') --torch.save(label .. '_input.dat', input) torch.save(label .. '_input.txt', input, 'ascii') --torch.save(label .. '_output.dat', output) torch.save(label .. '_output.txt', output, 'ascii') end local net_simple = nn.Sequential() net_simple:add(nn.ReLU()) net_simple:add(nn.SpatialConvolution(3,64, 11,7, 3,4, 3,2)) net_simple:add(nn.SpatialMaxPooling(4,5, 3,2, 1,2)) net_simple:add(nn.Sigmoid()) save(net_simple, torch.Tensor(2, 3, 25, 35), 'net_simple') local net_pool_max = nn.Sequential() net_pool_max:add(nn.SpatialMaxPooling(4,5, 3,2, 1,2):ceil()) --TODO: add ceil and floor modes save(net_pool_max, torch.rand(2, 3, 50, 30), 'net_pool_max') local net_pool_ave = nn.Sequential() net_pool_ave:add(nn.SpatialAveragePooling(4,5, 2,1, 1,2)) save(net_pool_ave, torch.rand(2, 3, 50, 30), 'net_pool_ave') local net_conv = nn.Sequential() net_conv:add(nn.SpatialConvolution(3,64, 11,7, 3,4, 3,2)) save(net_conv, torch.rand(1, 3, 50, 60), 'net_conv') local net_reshape = nn.Sequential() net_reshape:add(nn.Reshape(5, 4, 3, 2)) save(net_reshape, torch.rand(2, 3, 4, 5), 'net_reshape') local net_reshape_batch = nn.Sequential() net_reshape_batch:add(nn.Reshape(5, 4, 3, true)) save(net_reshape_batch, torch.rand(2, 3, 4, 5), 'net_reshape_batch') save(nn.Linear(7, 3), torch.rand(13, 7), 'net_linear_2d') local net_parallel = nn.Parallel(4, 2) net_parallel:add(nn.Sigmoid()) net_parallel:add(nn.Tanh()) save(net_parallel, torch.rand(2, 6, 4, 2), 'net_parallel') local net_concat = nn.Concat(2) net_concat:add(nn.ReLU()) net_concat:add(nn.Tanh()) net_concat:add(nn.Sigmoid()) save(net_concat, torch.rand(2, 6, 4, 3) - 0.5, 'net_concat')
--[[ TheNexusAvenger Stores modifiers for the characters. --]] local ReplicatedStorage = game:GetService("ReplicatedStorage") local ReplicatedStorageProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ReplicatedStorage")) local NexusEventCreator = ReplicatedStorageProject:GetResource("External.NexusInstance.Event.NexusEventCreator") local CharacterModifiers = ReplicatedStorageProject:GetResource("External.NexusInstance.NexusObject"):Extend() CharacterModifiers:SetClassName("CharacterModifiers") --[[ Creates the character modifiers. --]] function CharacterModifiers:__new(Character) self:InitializeSuper() --Create the container. local ModifiersContainer = Instance.new("Folder") ModifiersContainer.Name = "Modifiers" ModifiersContainer.Parent = Character self.ModifiersContainer = ModifiersContainer self.ModifierChanged = NexusEventCreator:CreateEvent() --Connect the events. self.Events = {} self.LastModifiers = {} self.KeyToValue = {} table.insert(self.Events,ModifiersContainer.ChildAdded:Connect(function(Value) --Connect the value changing. Value.Changed:Connect(function() self:UpdateModifierType(Value.Name) end) --Update the total modifier. self:UpdateModifierType(Value.Name) end)) table.insert(self.Events,ModifiersContainer.ChildRemoved:Connect(function(Value) --Update the total modifier. self:UpdateModifierType(Value.Name) end)) end --[[ Adds a modifier. --]] function CharacterModifiers:Add(Key,Type,Value) --Throw an error if the key already exists. if self.KeyToValue[Key] then error("Modifier key already used: "..tostring(Key)) end --Create and store the value. local ModifierValue = Instance.new("NumberValue") ModifierValue.Name = Type ModifierValue.Value = Value ModifierValue.Parent = self.ModifiersContainer self.KeyToValue[Key] = ModifierValue end --[[ Removes a modifier. --]] function CharacterModifiers:Remove(Key) if self.KeyToValue[Key] then self.KeyToValue[Key]:Destroy() self.KeyToValue[Key] = nil end end --[[ Returns the current value of the given modifier. --]] function CharacterModifiers:Get(Type) --Calculate and return the total. local Total = 0 for _,Value in pairs(self.ModifiersContainer:GetChildren()) do if Value.Name == Type then Total = Total + Value.Value end end return Total end --[[ Updates the value of a modifier type. --]] function CharacterModifiers:UpdateModifierType(Type) --Store the new value and fire the event if the total changed. local Total = self:Get(Type) if self.LastModifiers[Type] ~= Total then self.LastModifiers[Type] = Total self.ModifierChanged:Fire(Type,Total) end end --[[ Destroys the character modifiers. --]] function CharacterModifiers:Destroy() --Destroy the container. self.ModifiersContainer:Destroy() self.LastModifiers = {} self.KeyToValue = {} --Disconnect the events. self.ModifierChanged:Disconnect() for _,Event in pairs(self.Events) do Event:Disconnect() end self.Events = {} end return CharacterModifiers
object_mobile_tyber_zann = object_mobile_shared_tyber_zann:new { } ObjectTemplates:addTemplate(object_mobile_tyber_zann, "object/mobile/tyber_zann.iff")
-- extensions/table - add more table functions -- @author Jacob Fischer, [email protected] --- -- returns a normal table {}, but with the 'table' metadata set, because unlike strings in lua tables do not get their metatable automatically set :( Table = function(...) return setmetatable({...}, {__index=table}) end --- -- sets the passed in table's metatable to the 'table' metatable. Tableize = function(tbl) tbl = setmetatable(tbl, {__index=table}) return tbl end --- -- Checks to see if a table contains an item. -- @param tbl Table to check -- @param item item to find in table -- @return the key of the item if found function table.contains(tbl, item) for key, value in pairs(tbl) do if value == item then return key end end end --- -- @see table.contains table.indexOf = table.contains --- -- inverse of table.contains -- @see table.contains function table.doesNotContain(tbl, item) return not table.contains(tbl, item) end --- checks to see if a table contains all the passed in items -- @param tbl Table to check -- @param ... items to check for -- @return true if tbl contains ALL the items, false otherwise function table.containsAll(tbl, ...) local items = {...} for key, value in pairs(tbl) do for i, item in ipairs(items) do if value == item then table.remove(items, i) if #items == 0 then return true end end end end return false end function table:doesNotContainAll(...) return not self:containsAll(...) end --- checks to see if a table contains any the passed in items -- @param tbl Table to check -- @param ... items to check for -- @return key of the first item found, nil otherwise function table.containsAny(tbl, ...) local items = Table() for key, value in pairs(tbl) do for i, item in ipairs(items) do if value == item then return i end end end end function table:doesNotContainAny(...) return not self:containsAny(...) end --- -- Reverses indexed tables. -- @param tbl table to reverse -- @return a new tabled of reversed indexes from table function table.reverse (tbl) local reversed = Table() for i = 0, #tbl-1 do reversed:insert(tbl[#tbl - i]) end return reversed end --- -- Removes the last element from the table and returns it. (pop back, because it is the fastest in Lua) -- @param tbl the table to pop an item off -- @return popped item from tbl function table.pop(tbl) local popped = tbl[#tbl] table.remove(tbl, #tbl) return popped end --- -- more verbose was of saying pop, for clarity when coding -- @see table.pop table.popBack = table.pop --- -- pops the front of the table and returns it. slower than popBack because every item after the front must be moved down. -- @param tbl to pop -- @return popped item from tbl function table.popFront(tbl) local popped = tbl[1] table.remove(tbl, 1) return popped end --- -- Simple syntaxtical sugar for tbl[1], or the first element from pairs(tbl). function table.first(tbl) if tbl[1] then return tbl[1] end for i, value in pairs(tbl) do return value end end --- -- Simple syntactical sugar for tbl[#tbl]. function table.last(tbl, offset) return tbl[#tbl + (offset or 0)] end --- Removes a value from a table (instead of a value based on key in table.remove). -- @param tbl the table to remove the value from -- @param value the value to find and remove -- @return the key/index of where the value was function table.removeValue(tbl, value) for k, v in pairs(tbl) do if value == v then table.remove(tbl, k) return k end end end --- -- Simple syntaxtical sugar for table.insert(tbl, 1, value). function table.pushFront(tbl, value) table.insert(tbl, 1, value) end --- -- Does a shallow copy to a table from another. -- @param to the table to copy to, or if not copying from makes a shallow copy of -- @param from (Optional) the table to copy from onto to -- @return if no from then returns a shallow copy of to function table.copy(to, from) if from then for k, v in pairs(from) do to[k] = v end return to else local duplicate = Table() if to then for k, v in pairs(to) do duplicate[k] = v end end return duplicate end end --- -- Does a deep copy to a table from another table using recursion. -- @param to the table to deep copy to from from -- @param from the table to deep copy from to to function table.deepCopy(to, from) -- you better not have any cycles with this for key, value in pairs(from or Table()) do if type(value) == "table" then to[key] = to[key] or Table() if type(to[key]) ~= "table" then to[key] = Table() end table.deepCopy(to[key], value) else to[key] = value end end return to end --- -- Counts the number of elements (optionally matching an element) in a table, assuming it's not indexed. -- @param tbl the table to count from -- @param find (Optional) the element to count -- @return how many times it found find, or the size of the table function table.count(tbl, find) if not tbl then return nil end local i = 0 for key, value in pairs(tbl) do if not find or find == value then i = i + 1 end end return i end --- -- Sets every element in the table to nil. -- @param tbl the table to clear function table.empty(tbl) for key, value in pairs(tbl) do tbl[key] = nil end return tbl end --- -- Checks if the table is empty, simple syntactical sugar for not next(tbl) -- @return boolean representing if the table is empty function table.isEmpty(tbl) return not next(tbl) end --- -- Converts every element in a table using a function. -- @param t table to use the converter on -- @param converter a function that takes an element from the table t and returns a converted value to store back in t -- @return a new converted table function table.convert(t, converter) -- TODO: should t be overwritten with c? local c = Table() for k, v in pairs(t) do c[k] = converter(v) end return c end --- -- Slices the indexed table from start to to, like a string -- @param t table to slice -- @param start number to start slicing from -- @param to where to stop slicing -- @return a new table of the sliced elements from t function table.slice(t, start, to) local sliced = Table() for i = start, to do sliced:insert(t[i]) end return sliced end --- sums up a property of an indexed table -- @param tbl table to sum up -- @param ... property of every element in the table to sum -- @return sum of every element[property] in the table function table.sum(tbl, ...) local sum = 0 for i, v in ipairs(tbl) do local value = table.traverse(v, ...) if value then sum = sum + value end end return sum end --- averages a property of an indexed table -- @param tbl table to sum up -- @param .... property of every element in the table to average -- @return average of every element[property] in the table function table.average(tbl, ...) if #tbl == 0 then return 0 end return table.sum(tbl, ...)/#tbl end --- returns all the tables passed in joined, for easy iterating over function table.join(...) local joined = Table() for i, tbl in ipairs({...}) do for i, v in ipairs(tbl) do joined:insert(v) end end return joined end --- Inserts all the values from one table into another -- @param tbl the table to insert values into -- @param fromTable table get the values to insert into tbl function table.insertFrom(tbl, fromTable) for i, v in ipairs(fromTable) do table.insert(tbl, v) end end --- Removes all the values from a table when the whereFunction returns truthy. -- Does not use table.remove, because that would be O(N^2). Instead because we -- know we'll could removing multiple values we don't shift the elements down -- after every removal, instead we only shift after all removals. -- @param tbl table to remove things from -- @param whereFunction function that should return if that passed in value should be removed function table.removeWhere(tbl, whereFunction) local n = #tbl for i = 1, n do if whereFunction(tbl[i]) then tbl[i] = nil end end local j = 0 for i = 1, n do if tbl[i] ~= nil then j = j + 1 tbl[j] = tbl[i] end end for i = j + 1, n do tbl[i] = nil end return tbl end --- Removes all the found values from the table safely. -- @param tbl table to remove values from -- @param ... values to remove from tbl -- @example Table("alpha", "beta", "charlie", "delta", "gamma"):removeValues("beta", "charlie", "gamma") -> {"alpha", "delta"} function table.removeValues(tbl, ...) local remove = Table(...) return table.removeWhere(tbl, function(tablesValue) return remove:contains(tablesValue) end) end --- unpacks a table for table.removeValues -- @see table.removeValues function table.removeValuesFrom(tbl, fromTable) return table.removeValues(tbl, unpack(fromTable)) end -- @return random element from the table function table.randomElement(tbl) return tbl[math.random(#tbl)] end --- swaps the two keys values in a table -- @param tbl table to swap key/values in -- @index1 first key you want to swa the value with index2 -- @index2 second key you want to swap the value with index1 function table.swap(tbl, index1, index2) tbl[index1], tbl[index2] = tbl[index2], tbl[index1] end --- suffles the passed in table randomly -- @param tbl table to suffle randomly function table.shuffle(tbl) local counter = #tbl while counter > 1 do local index = math.random(counter) table.swap(tbl, index, counter) counter = counter - 1 end return tbl end -- @return indexed table of the non indexed keys in tbl function table.keys(tbl) local keys = Table() for key, value in pairs(tbl) do keys:insert(key) end return keys end -- @return indexed table of the non indexed values in tbl function table.values(tbl) local values = Table() for key, value in pairs(tbl) do values:insert(value) end return values end --- inserts the element if it is not present -- @return boolean representing if the element was inserted function table.insertIfAbsent(tbl, element, ...) if table.doesNotContain(tbl, element) then table.insert(tbl, element, ...) return true end return false end -- @param key (optional) key to sort on for each element in tbl function table.sortAscending(tbl, key) table.sort(tbl, function(a, b) if key then return a[key] < b[key] else return a < b end end) return tbl end -- @param key (optional) key to sort on for each element in tbl function table.sortDescending(tbl, key) table.sort(tbl, function(a, b) if key then return a[key] > b[key] else return a > b end end) return tbl end --- -- copies values from a given table onto another table, similar to jQuery's extend -- @param tbl to copy ONTO -- @param coptFrom table to copy values on top of tbl function table.extend(tbl, copyFrom) tbl = tbl or Table() for key, value in pairs(copyFrom) do tbl[key] = value end return tbl end
--[[-------------------------------------------------------------------- Gazelle: a system for building fast, reusable parsers fa.lua Data structure for representing finite automata. Both NFAs and DFAs can be represented using this class. The base class (FA/FAState) has three child classes: - IntFA/IntFAState represents a nonrecursive FA that transitions on IntSets or Epsilon. These represent the machines that recognize regular expressions. - RTN/RTNState represents a recursive transition network: the graph that is built to recognize context-free grammars. These transition on strings, regexes, epsilon, or on another RTN. - GLA/GLAState represents a lookahead automaton that represents LL lookahead information. Either child class can be deterministic or nondeterministic. The only difference is whether there are epsilons / redundant transtions. This all needs to be refactored quite a bit, now that I have the insight of understanding all the different ways NFAs and DFAs are used throughout Gazelle. Copyright (c) 2007-2008 Joshua Haberman. See LICENSE for details. --------------------------------------------------------------------]]-- require "misc" module("fa", package.seeall) -- Class for representing special-case edge values that have only one -- instance for the whole program. SingletonEdgeValue = {name="SingletonEdgeValue"} function SingletonEdgeValue:new(name) self.singletons = self.singletons or {} -- we index each singleton by name, creating new ones lazily. self.singletons[name] = self.singletons[name] or newobject(self) return self.singletons[name] end -- This is a special edge value that represents a transition that can be -- taken without consuming any input. e = SingletonEdgeValue:new("Epsilon") -- This is a special edge value that represents a GLA transition that can -- be taken when EOF is seen. eof = SingletonEdgeValue:new("EOF") --[[-------------------------------------------------------------------- class State -- base class of FAState and RTNState --------------------------------------------------------------------]]-- FAState = {name="FAState"} function FAState:new() local obj = newobject(self) obj._transitions = {} return obj end function FAState:child_states() local children = Set:new() for edge_value, target_state in self:transitions() do children:add(target_state) end return children end function FAState:add_transition(edge_value, target_state, edge_properties) for e_edge_value, e_target_state, e_edge_properties in self:transitions() do if edge_value == e_edge_value and target_state == e_target_state and e_edge_properties == edge_properties then return end end table.insert(self._transitions, {edge_value, target_state, edge_properties}) end function FAState:num_transitions() return #self._transitions end function FAState:transitions() local i = 0 return function () i = i + 1 if self._transitions[i] then return unpack(self._transitions[i]) else return nil end end end function FAState:clear_transitions() self._transitions = {} end function FAState:transitions_for(val, prop) local targets if prop == "ANY" then targets = {} else targets = Set:new() end for edge_val, target_state, properties in self:transitions() do if edge_val == val and ((prop == "ANY") or (prop == "ALL") or (prop == properties)) then if prop == "ANY" then table.insert(targets, {target_state, properties}) else targets:add(target_state) end end end return targets end function FAState:dest_state_for(val) local states = self:transitions_for(val, "ANY") if #states > 1 then error(">1 transition found") elseif #states == 0 then return nil else local dest_state for dest_state_properties in each(states) do dest_state, properties = unpack(dest_state_properties) end return dest_state end end --[[-------------------------------------------------------------------- class FA -- base class of IntFA and RTN --------------------------------------------------------------------]]-- FA = {name="FA"} function FA:new(init) local obj = newobject(self) init = init or {} if obj.new_state then obj.start = init.start or obj:new_state() obj.final = init.final or obj:new_state() -- for all but Thompson NFA fragments we ignore this if init.symbol then obj.start:add_transition(init.symbol, obj.final, init.properties) elseif init.string then local int_set = IntSet:new() local char = init.string:sub(1, 1):byte() int_set:add(Range:new(char, char)) local fa = IntFA:new{symbol=int_set} for i=2,#init.string do int_set = IntSet:new() char = init.string:sub(i, i):byte() int_set:add(Range:new(char, char)) fa = nfa_construct.concat(fa, IntFA:new{symbol=int_set}) end return fa end end obj.properties = {} return obj end function FA:states() return depth_first_traversal(self.start, function (s) return s:child_states() end) end function FA:dup() local new_graph = self:new_graph() local new_states = {} -- duplicate states for state in each(self:states()) do new_states[state] = new_states[state] or self:new_state() if self.start == state then new_graph.start = new_states[state] end if self.final == state then new_graph.final = new_states[state] end end -- duplicate transitions for state in each(self:states()) do for edge_val, target_state, properties in state:transitions() do new_states[state]:add_transition(edge_val, new_states[target_state], properties) end end return new_graph end --[[-------------------------------------------------------------------- class IntFA/IntFAState: Classes for representing machines that recognize regular expressions. --------------------------------------------------------------------]]-- IntFA = FA:new() IntFA.name = "IntFA" function IntFA:new_graph(init) return IntFA:new(init) end function IntFA:new_state() return IntFAState:new() end function IntFA:get_outgoing_edge_values(states) local symbol_sets = Set:new() local properties_set = Set:new() for state in each(states) do for symbol_set, target_state, properties in state:transitions() do if properties ~= nil then properties_set:add(properties) end if type(symbol_set) == "table" and symbol_set.class == IntSet then symbol_sets:add(symbol_set) end end end symbol_sets = equivalence_classes(symbol_sets) -- for now, just cross symbol sets with properties. a bit wasteful, -- but we'll worry about that later. local values = {} for set in each(symbol_sets) do for properties in each(properties_set) do table.insert(values, {set, properties}) end table.insert(values, {set, nil}) end return values end function IntFA:to_dot() str = "" states = self:states():to_array() --table.sort(states, function (a, b) return a.statenum < b.statenum end) for i,state in ipairs(states) do local label = "" local peripheries = 1 if state == self.start then label = "Begin" end if state == self.final or state.final then if label ~= "" then label = label .. "NEWLINE" .. state.final else label = state.final end peripheries = 2 end label = label:gsub("[\"\\]", "\\%1") label = label:gsub("NEWLINE", "\\n") str = str .. string.format(' "%s" [label="%s", peripheries=%d];\n', tostring(state), label, peripheries) for char, tostate, attributes in state:transitions() do local print_char if char == fa.e then print_char = "ep" -- elseif char == "(" then -- print_char = "start capture" -- elseif char == ")" then -- print_char = "end capture" elseif type(char) == "string" then print_char = char elseif type(char) == 'table' and char.class == IntSet then if char:isunbounded() then char = char:invert() end print_char = char:toasciistring() else print(serialize(char, 3, true)) print_char = string.char(char) end print_char = print_char:gsub("[\"\\]", "\\%1") print_char = print_char:gsub("NEWLINE", "\\n") str = str .. string.format(' "%s" -> "%s" [label="%s"];\n', tostring(state), tostring(tostate), print_char) end end return str end IntFAState = FAState:new() IntFAState.name = "IntFAState" function IntFAState:add_transition(edge_value, target_state, edge_properties) -- as a special case, IntSet edge_values can be combined if two edge_values -- have the same target_state and neither has any edge_properties. if edge_value.class == IntSet and edge_properties == nil then for existing_edge_value, existing_target_state, existing_edge_properties in self:transitions() do if existing_edge_value.class == IntSet and target_state == existing_target_state and existing_edge_properties == nil then existing_edge_value:add_intset(edge_value) return end end end FAState.add_transition(self, edge_value, target_state, edge_properties) end function IntFAState:transitions_for(val, prop) local targets = Set:new() if type(val) == "table" and val.class == IntSet then val = val:sampleint() end if prop == nil then prop = "ALL" end if prop == "ANY" then targets = {} else targets = Set:new() end for edge_val, target_state, properties in self:transitions() do if edge_val == val or (val ~= fa.e and edge_val.class == IntSet and edge_val:contains(val)) then if (prop == "ALL") or (prop == "ANY") or (prop == properties) then if prop == "ANY" then table.insert(targets, {target_state, properties}) else targets:add(target_state) end end end end return targets end --[[-------------------------------------------------------------------- class GLA/GLAState: Classes for representing machines that represent lookahead information. --------------------------------------------------------------------]]-- GLA = FA:new() GLA.name = "GLA" function GLA:new_graph(init) return GLA:new(init) end function GLA:new_state() return GLAState:new() end function GLA:get_outgoing_edge_values(states) local values = {} for state in each(states) do for edge_val, target_state, properties in state:transitions() do if edge_val ~= fa.e then table.insert(values, {edge_val, properties}) end end end return values end function GLA:to_dot(indent, suffix) local str = "" suffix = suffix or "" indent = indent or "" for state in each(self:states()) do peripheries = 1 extra_label = "" if state.final then peripheries = 2 if state.final[1] == 0 then -- the special value that means "return" extra_label = "Return" else for edge_val, dest_state, properties in self.rtn_state:transitions() do if edge_val == state.final[1] and dest_state == state.final[2] then extra_label = tostring(properties.slotnum) end end end end if self.start == state then extra_label = "Start" end str = str .. string.format('%s"%s" [label="%s" peripheries=%d]\n', indent, tostring(state) .. suffix, escape(extra_label), peripheries) for edge_val, target_state in state:transitions() do if edge_val == fa.eof then edge_val = "EOF" end str = str .. string.format('%s"%s" -> "%s" [label="%s"]\n', indent, tostring(state) .. suffix, tostring(target_state) .. suffix, escape(edge_val)) end end return str end GLAState = FAState:new() GLAState.name = "GLAState" function GLAState:new(paths) local obj = FAState:new() obj.rtn_paths = paths if paths then for path in each(paths) do if obj.lookahead_k and obj.lookahead_k ~= path.lookahead_k then error("Internal error: expected all paths for the GLA state to have the same length") end obj.lookahead_k = path.lookahead_k end else obj.lookahead_k = 0 end return obj end --[[-------------------------------------------------------------------- class RTN/RTNState: Classes for representing machines that represent context-free grammars. --------------------------------------------------------------------]]-- RTN = FA:new() RTN.name = "RTN" function RTN:new_graph(init) return RTN:new(init) end function RTN:new_state() return RTNState:new() end function RTN:get_outgoing_edge_values(states) local values = {} for state in each(states) do for edge_val, target_state, properties in state:transitions() do if edge_val ~= fa.e then table.insert(values, {edge_val, properties}) end end end return values end function escape(str) return str:gsub("[\"\\]", "\\%1") end function RTN:to_dot(indent, suffix, intfas, glas) suffix = suffix or "" str = indent .. "rankdir=LR;\n" -- str = str .. indent .. string.format('label="%s"\n', self.name) for state in each(self:states()) do peripheries = 1 extra_label = "" color = "" if state.gla then if state.gla.longest_path == 1 then color = " fillcolor=\"cornflowerblue\"" elseif state.gla.longest_path == 2 then color = " fillcolor=\"gold\"" elseif state.gla.longest_path > 2 then color = " fillcolor=\"firebrick\"" end color = color .. " style=\"filled\"" end if state.final then peripheries = 2 end if self.start == state then extra_label = "Start" end if intfas and state.intfa then if extra_label ~= "" then extra_label = extra_label .. "\\n" end extra_label = extra_label .. "I: " .. tostring(intfas:offset_of(state.intfa)) end if glas and state.gla then if extra_label ~= "" then extra_label = extra_label .. "\\n" end extra_label = extra_label .. "G: " .. tostring(glas:offset_of(state.gla)) end str = str .. string.format('%s"%s" [label="%s" peripheries=%d%s]\n', indent, tostring(state) .. suffix, extra_label, peripheries, color) for edge_val, target_state in state:transitions() do if fa.is_nonterm(edge_val) then str = str .. string.format('%s"%s" -> "%s" [label="<%s>"]\n', indent, tostring(state) .. suffix, tostring(target_state) .. suffix, escape(edge_val.name)) else --if attributes.regex_text[edge_val] then -- edge_val = "/" .. attributes.regex_text[edge_val] .. "/" --end if edge_val == fa.eof then edge_val = "EOF" end str = str .. string.format('%s"%s" -> "%s" [label="%s"]\n', indent, tostring(state) .. suffix, tostring(target_state) .. suffix, escape(edge_val)) end end end return str end RTNState = FAState:new() RTNState.name = "RTNState" -- A trivial state is one where you can tell just by looking -- at the state's transitions and its final status alone what -- transition you should take for a given terminal. function RTNState:needs_gla() if self.final then -- a final state needs a GLA if it has any outgoing transitions if self:num_transitions() > 0 then return true else return false end else -- a nonfinal state needs a GLA if it has more than one -- outgoing transition and either: -- - at least one of those transitions is a nonterminal -- - there are two or more terminal transitions for the same state -- TODO: what about states with exactly 1 outgoing nonterminal -- transition? We don't technically need a GLA's help to -- figure out the right transition. if self:num_transitions() == 1 then return false else local edge_vals = Set:new() for edge_val in self:transitions() do if fa.is_nonterm(edge_val) then return true else if edge_vals:contains(edge_val) then return true end edge_vals:add(edge_val) end end return false end end end -- In most cases, a state needs an intfa if it doesn't have a GLA, -- but there are a few exceptions. Final states with no transitions -- don't need an intfa. Neither do states that have only one -- nonterminal transition. function RTNState:needs_intfa() if self:needs_gla() then return false else if self.final then return false elseif self:num_transitions() == 1 and fa.is_nonterm(self._transitions[1][1]) then return false else return true end end end NonTerm = {name="NonTerm"} function NonTerm:new(name) -- keep a cache of nonterm objects, so that we always return the same object -- for a given name. This lets us compare nonterms for equality. if not self.cache then self.cache = {} end if not self.cache[name] then obj = newobject(self) obj.name = name self.cache[name] = obj end return self.cache[name] end function is_nonterm(thing) return (type(thing) == "table" and thing.class == NonTerm) end -- vim:et:sts=2:sw=2
local o = vim.o local wo = vim.wo local bo = vim.bo -- global options o.swapfile = true -- o.dir = '/tmp' if vim.loop.os_uname().sysname:find("Windows", 1, true) and true then o.dir = os.getenv("LOCALAPPDATA") .. "\\vim\\swap" else o.dir = os.getenv("XDG_CACHE_HOME") .. "/vim/swap" end o.expandtab = true o.tabstop = 4 o.softtabstop = 4 o.shiftwidth = 4 o.textwidth = 119 o.smartcase = true o.laststatus = 2 o.hlsearch = true o.incsearch = true o.ignorecase = true o.scrolloff = 12 o.hidden = true o.scrolloff = 3 -- o.spell! o.smartcase = true o.inccommand = "nosplit" o.termguicolors = true o.path = o.path .. "**" o.splitbelow = true o.splitright = true o.list = true o.listchars = "nbsp:¬,tab:»·,trail:·" o.tags = "tags,../tags,../../tags,../../../tags,../../../../tags,../../../../../tags,../../../../../../tags,../../../../../../../tags,../../../../../../../../tags,../../../../../../../../../tags,../../../../../../../../../../tags" o.list = true o.listchars = "nbsp:¬,tab:»·,trail:·" o.wildignore = o.wildignore .. "*/tmp/*,*.so,*.swp,*.zip,*.pyc,*.db,*.sqlite" o.wildignore = o.wildignore .. "*.o,*.obj,.git,*.rbc,*.pyc,__pycache__,*.jar,*.png,*.class,*.jpg,*.pdf,*.pst,*.ppt,*.doc,*.xls,*.pptx,*.docx,*.xlsx,*.ico,*.bmp,*.gif,*.7z,*.deb,*.rpm,*.dot,*.exe,*.dll,*.aps,*.chm,*.dat,*.dump,*.mp3,*.mkv,*.mp4 ,*.m4a,*.gz,*.tar,*.tgz,*.mdb,*.msg,*.odt,*.oft,*.pdb,*.ppm,*.pps,*.pub,*.mobi,*.rtf,*.stackdump,*.dump,*.ttf,*.otf,*.tmp,*.temp,*.zip" o.shortmess = o.shortmess .. "c" o.completeopt = "menuone,noinsert,noselect,preview" o.signcolumn = "yes" o.updatetime = 300 o.foldenable = true o.foldlevel = 99 o.foldlevelstart = 99 o.foldnestmax = 10 o.undofile = true o.wrap = false o.number = true o.relativenumber = true o.cursorline = true -- window-local options wo.number = true wo.relativenumber = true -- wo.showmatch = true wo.cursorline = true wo.wrap = false -- buffer-local options bo.expandtab = true bo.tabstop = 4 bo.softtabstop = 4 bo.shiftwidth = 4 --[[ TODO: setstatusline with fugitive TODO: clipboard ]] vim.cmd("colorscheme gruvbox") -- vim.cmd('colorscheme molokai') -- vim.cmd('colorscheme anotherdark') -- vim.cmd('colorscheme zenburn') -- vim.cmd('colorscheme wombat256') -- vim.cmd('colorscheme whitedust') -- vim.cmd('colorscheme tutticolori') -- vim.cmd('colorscheme soso') -- vim.cmd('colorscheme simpleandfriendly') -- vim.cmd('colorscheme evening') -- vim.cmd('colorscheme asmdev') vim.cmd("filetype plugin indent on") vim.cmd("set spell!") local map = vim.api.nvim_set_keymap -- g...git; f...find; s...session; t...terminal; -- map the leader key map("n", ",", "", {}) vim.g.mapleader = "," -- 'vim.g' sets global variables options = {noremap = true} -- General map("i", "jk", "<esc>", options) map("t", "jk", "<c-\\><c-n>", options) map("n", "n", "nzzzv", options) map("n", "N", "Nzzzv", options) map("n", "Q", "@@", options) map("c", "W!", "w!", options) map("c", "Q!", "q!", options) map("c", "Qa!", "qa!", options) map("c", "W", "w", options) map("c", "Q", "Q", options) -- Vmap for maintain Visual Mode after shifting > and < map("n", "<", "<gv", options) map("v", ">", ">gv", options) -- Move visual block map("v", "J", ":m +1<CR>gv=gv", options) map("v", "K", ":m -2<CR>gv=gv", options) -- jump between buffers in normal mode map("n", "<c-h>", "<c-w>h", options) map("n", "<c-j>", "<c-w>j", options) map("n", "<c-k>", "<c-w>k", options) map("n", "<c-l>", "<c-w>l", options) -- jump between buffers in visual mode map("x", "<c-h>", "<c-w>h", options) map("x", "<c-j>", "<c-w>j", options) map("x", "<c-k>", "<c-w>k", options) map("x", "<c-l>", "<c-w>l", options) -- remove ^M from dos files map("n", "<leader>m", ":e ++ff=dos<cr>", options) -- move vertically by visual line map("n", "j", "gj", options) map("n", "k", "gk", options) -- highlight last inserted text map("n", "gV", "`[v`]", options) -- Buffer map("n", "<Leader>h", ":<C-u>split<CR>", options) map("n", "<Leader>v", ":<C-u>vsplit<CR>", options) map("n", "<leader>z", ":bp<CR>", options) map("n", "<leader>x", ":bn<CR>", options) map("n", "<leader>c", ":bd<CR>", options) -- session management map("n", "<leader>so", ":OpenSession<Space>", options) map("n", "<leader>ss", ":SaveSession<Space>", options) map("n", "<leader>sd", ":DeleteSession<CR>", options) map("n", "<leader>sc", ":CloseSession<CR>", options) -- Vista map("n", "<Leader>tb", ":Vista!!<CR>", options) -- GIT -- map('n', '<Leader>gr', ':Gremove<CR>', options) map("n", "<Leader>gbr", ":GBranches<CR>", options) map("n", "<Leader>gt", ":GTags<CR>", options) -- Open current line on GitHub map("n", "<Leader>o", ":.Gbrowse<CR>", options) -- Open applications map("n", "<leader>s", ":Snippets<CR>", options) -- Open applications map("n", "<c-n>", ":NvimTreeToggle<CR>", options) -- LSP map("n", "<leader>lf", ":Lspsaga lsp_finder<CR>", options) map("n", "<leader>la", ":Lspsaga code_action<CR>", options) map("v", "<leader>la", ":<C-U>Lspsaga range_code_action<CR>", options) map("n", "K", ":Lspsaga hover_doc<CR>", options) map("n", "<leader>lS", ":Lspsaga signature_help<CR>", options) map("n", "<leader>lR", ":Lspsaga rename<CR>", options) map("n", "<leader>lp", ":Lspsaga preview_definition<CR>", options) map("n", "<leader>lD", ":Lspsaga show_line_diagnostics<CR>", options) map("n", "e[", ":Lspsaga diagnostic_jump_next<CR>", options) map("n", "e]", ":Lspsaga diagnostic_jump_prev<CR>", options) map("n", "<leader>lr", "<cmd>lua vim.lsp.buf.references()<CR>", options) -- rust-analyzer does not yet support goto declaration - re-mapped `gd` to definition map("n", "<leader>ld", "<cmd>lua vim.lsp.buf.definition()<CR>", options) -- map('n', '<leader>ld', '<cmd>lua vim.lsp.buf.declaration()<CR>', options) -- map("n", "<c-]>", "<cmd>lua vim.lsp.buf.definition()<CR>", options) -- Completion (nvim-comple) map("i", "<expr> <C-Space>", "compe#complete()", options) map("i", "<expr> <CR>", "compe#confirm('<CR>')", options) map("i", "<expr> <C-e>", "compe#close('<C-e>')", options) map("i", "<expr> <C-f>", "compe#scroll({ 'delta': +4 })", options) map("i", "<expr> <C-d>", "compe#scroll({ 'delta': -4 })", options) -- GIT map("n", "<Leader>ga", ":Gwrite<CR>", options) map("n", "<Leader>gc", ":Gcommit<CR>", options) map("n", "<Leader>gsh", ":Gpush<CR>", options) map("n", "<Leader>gll", ":Gpull<CR>", options) map("n", "<Leader>gs", ":Gstatus<CR>", options) map("n", "<Leader>gbl", ":Gblame<CR>", options) map("n", "<Leader>gd", ":Gvdiff<CR>", options) -- Fuzzy - old fzf.vim style -- map("n", "<Leader>f", ":GFiles<CR>", options) -- map("n", "<Leader>F", ":Files<CR>", options) -- map("n", "<leader>e", ":FZF -m<CR>", options) -- map("n", "<Leader>b", ":Buffers<CR>", options) map("n", "<Leader>y", ":History<CR>", options) -- map("n", "<Leader>t", ":BTags<CR>", options) -- map("n", "<Leader>T", ":Tags<CR>", options) -- map("n", "<Leader>l", ":BLines<CR>", options) -- map("n", "<Leader>L", ":Lines<CR>", options) map("n", "<Leader>'", "Marks<CR>", options) -- map("n", "<Leader>a", ":Rg<Space><CR>", options) -- map("n", "<Leader>H", ":Helptags!<CR>", options) -- map("n", "<Leader>C", ":Commands<CR>", options) map("n", "<Leader>:", ":History:<CR>", options) map("n", "<Leader>/", ":History/<CR>", options) map("n", "<Leader>M", ":Maps<CR>", options) map("n", "<Leader>S", ":Filetypes<CR>", options) map("n", "<Leader>B", ":BufferPick<CR>", options) -- Telescope - new native lua style map("n", "<leader>fA", "<cmd>Telescope autocommands<cr>", options) map("n", "<leader>b", "<cmd>Telescope buffers<cr>", options) map("n", "<leader>?", "<cmd>Telescope builtin<cr>", options) map("n", "<leader>C", "<cmd>Telescope colorscheme<cr>", options) map("n", "<leader>f:", "<cmd>Telescope command_history<cr>", options) map("n", "<leader>:", "<cmd>Telescope commands<cr>", options) map("n", "<leader>f/", "<cmd>Telescope current_buffer_fuzzy_find<cr>", options) map("n", "<leader>fT", "<cmd>Telescope current_buffer_tags<cr>", options) -- map("n", "<leader>f$", "<cmd>Telescope fd<cr>", options) map("n", "<leader>f-", "<cmd>Telescope filetypes<cr>", options) map("n", "<leader>ff", "<cmd>Telescope find_files<cr>", options) map("n", "<leader>f.", '<cmd>Telescope find_files cwd="/home/heiko/.config"<cr>', options) map("n", "<leader>gB", "<cmd>Telescope git_bcommits<cr>", options) map("n", "<leader>gb", "<cmd>Telescope git_branches<cr>", options) map("n", "<leader>gC", "<cmd>Telescope git_commits<cr>", options) map("n", "<leader>gf", "<cmd>Telescope git_files<cr>", options) map("n", "<leader>gS", "<cmd>Telescope git_status<cr>", options) map("n", "<leader>f*", "<cmd>Telescope grep_string<cr>", options) map("n", "<leader>fh", "<cmd>Telescope help_tags<cr>", options) map("n", "<leader>fH", "<cmd>Telescope highlights<cr>", options) map("n", "<leader>fK", "<cmd>Telescope keymaps<cr>", options) map("n", "<leader>a", "<cmd>Telescope live_grep<cr>", options) map("n", "<leader>fll", "<cmd>Telescope loclist<cr>", options) map("n", "<leader>fla", "<cmd>Telescope lsp_code_actions<cr>", options) map("n", "<leader>fls", "<cmd>Telescope lsp_document_symbols<cr>", options) map("n", "<leader>flra", "<cmd>Telescope lsp_range_code_actions<cr>", options) map("n", "<leader>flr", "<cmd>Telescope lsp_references<cr>", options) map("n", "<leader>flwa", "<cmd>Telescope lsp_workspace_symbols<cr>", options) map("n", "<leader>fm", "<cmd>Telescope man_pages<cr>", options) map("n", "<leader>f'", "<cmd>Telescope marks<cr>", options) map("n", "<leader>fo", "<cmd>Telescope oldfiles<cr>", options) -- map('n', '<leader>fp', '<cmd>Telescope planets<cr>', options) map("n", "<leader>fq", "<cmd>Telescope quickfix<cr>", options) map("n", "<leader>fr", "<cmd>Telescope registers<cr>", options) -- map('n', '<leader>frl', '<cmd>Telescope reloader<cr>', options) map("n", "<leader>fs", "<cmd>Telescope spell_suggest<cr>", options) map("n", "<leader>fk", "<cmd>Telescope symbols<cr>", options) map("n", "<leader>ft", "<cmd>Telescope tags<cr>", options) map("n", "<leader>fk", "<cmd>Telescope treesitter<cr>", options) map("n", "<leader>fO", "<cmd>Telescope vim_options<cr>", options) -- vim.cmd('command! FixWhitespace :%s/\s\+$//e') vim.api.nvim_exec([[ set foldmethod=expr set foldexpr=nvim_treesitter#foldexpr() ]], false) require("nvim-treesitter.configs").setup( { ensure_installed = "maintained", highlight = { enable = true }, incremental_selection = { enable = true, keymaps = { init_selection = "gnn", node_incremental = "gnn", scope_incremental = "gnc", node_decremental = "gnd" } }, indent = { enable = true }, rainbow = { enable = true } } ) -- telescope actions for dap require("telescope").load_extension("dap") -- -- Formatter -- require("formatter").setup( -- { -- logging = false, -- filetype = { -- css = { -- function() -- return { -- exe = "prettier", -- args = {"--stdin-filepath", vim.api.nvim_buf_get_name(0), "--single-quote"}, -- stdin = true -- } -- end -- }, -- html = { -- function() -- return { -- exe = "prettier", -- args = {"--stdin-filepath", vim.api.nvim_buf_get_name(0), "--single-quote"}, -- stdin = true -- } -- end -- }, -- yaml = { -- function() -- return { -- exe = "prettier", -- args = {"--stdin-filepath", vim.api.nvim_buf_get_name(0), "--single-quote"}, -- stdin = true -- } -- end -- }, -- javascript = { -- function() -- return { -- exe = "prettier", -- args = {"--stdin-filepath", vim.api.nvim_buf_get_name(0), "--single-quote"}, -- stdin = true -- } -- end -- }, -- go = { -- function() -- return { -- exe = "gofmt", -- args = {""}, -- stdin = true -- } -- end -- }, -- sh = { -- function() -- return { -- exe = "shfmt", -- stdin = true -- } -- end -- }, -- python = { -- function() -- return { -- exe = "black", -- stdin = true -- } -- end -- }, -- rust = { -- function() -- return { -- exe = "rustfmt", -- args = {"--emit=stdout"}, -- stdin = true -- } -- end -- }, -- lua = { -- function() -- return { -- exe = "luafmt", -- args = {"--indent-count", 2, "--stdin"}, -- stdin = true -- } -- end -- } -- } -- } -- ) -- vim.api.nvim_exec( -- [[ -- augroup FormatAutogroup -- autocmd! -- autocmd BufWritePost *.js,*.rs,*.lua FormatWrite -- augroup END -- ]], -- true -- ) -- vim.cmd [[autocmd CursorHold,CursorHoldI * lua require'nvim-lightbulb'.update_lightbulb()]]
function startPick() local w = UIApplication:sharedApplication():keyWindow() _interceptor = InterceptorView:alloc():initWithFrame(w:bounds()) w:addSubview(_interceptor) return "Go on, touch something. Get the view by calling endPick() when you're done." end function endPick() local v = _interceptor:pickedView() _interceptor:removeFromSuperview() return v end -- wax doesn't automagically bridge C functions function CGRectContainsPoint(rect, point) return rect.x <= point.x and point.x <= rect.x + rect.width and rect.y <= point.y and point.y <= rect.y + rect.height end waxClass{"InterceptorView", UIView} function touchesEnded_withEvent(self, touches, event) local point = touches:anyObject():locationInView(self) local w = UIApplication:sharedApplication():keyWindow() local pointInWindow = w:convertPoint_fromView(point, self) self.pickedView_ = self:findOwnerOfPoint_startingWith(pointInWindow, w) print(self.pickedView_:class()) end function pickedView(self) return self.pickedView_ end function findOwnerOfPoint_startingWith(self, point, view) if view == self then return nil end if not CGRectContainsPoint(view:bounds(), point) then return nil end local betterResult = nil for i, subview in ipairs(view:subviews()) do pointInSubview = subview:convertPoint_fromView(point, view) betterResult = self:findOwnerOfPoint_startingWith(pointInSubview, subview) or betterResult end return betterResult or view end
--[[ Copyright 2012-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local tap = require('util/tap') local test = tap.test local fs = require('fs') test('fs.readFile nonexistant path', function(expect) local filepath = '/skldfjslfjslf' print(filepath) local fd = fs.readFile(filepath, expect(function(err) assert(err) end)) end) tap.run()
local UILooksNode = BaseClass(UINode) UILooksNode.ShowType = { Role = 1, Monster = 2, NPC = 3, } function UILooksNode:Constructor( parentTrans ) self.prefabPath = "Assets/AssetBundleRes/ui/common/UILooksNode.prefab" self.cacheRole = {} self.cacheNPC = {} self:Load() end function UILooksNode:OnLoad( ) local names = { "container","camera" } UI.GetChildren(self, self.transform, names) self.camera = self.camera:GetComponent("Camera") print('Cat:UILooksNode.lua[20] self.camera', self.camera) UI.SetLocalPositionXYZ(self.transform, 9999, -9999, 12345) self:AddEvents() end function UILooksNode:AddEvents( ) if self.data and self.data.canRotate then end end function UILooksNode:SetData( data ) self.lastData = self.data UINode.SetData(self, data) end function UILooksNode:OnUpdate( ) if not self.data then return end self:Reset() if self.data.showType == UILooksNode.ShowType.Role then self:LoadRole() elseif self.data.showType == UILooksNode.ShowType.NPC then self:LoadNPC() end end function UILooksNode:Reset( ) if not self.lastData then return end if self.lastData.showType == UILooksNode.ShowType.Role then if not IsNull(self.bodyTrans) then self.bodyTrans.gameObject:SetActive(false) self.cacheRole[self.curShowCareer..","..self.curShowBody..","..self.curShowHair] = self.bodyTrans end elseif self.lastData.showType == UILooksNode.ShowType.NPC then if not IsNull(self.npcTrans) then self.npcTrans.gameObject:SetActive(false) self.cacheNPC[self.curShowNPCID] = self.npcTrans end end self.curShowNPCID = nil self.curShowCareer = nil self.curShowBody = nil self.curShowHair = nil end function UILooksNode:LoadRole( ) if (self.curShowCareer and self.curShowCareer==self.data.career) and (self.curShowBody and self.curShowBody == self.data.body) and (self.curShowHair and self.curShowHair == self.data.hair) then return end -- if not IsNull(self.bodyTrans) then -- self.bodyTrans.gameObject:SetActive(false) -- self.cacheRole[self.curShowCareer..","..self.curShowBody..","..self.curShowHair] = self.bodyTrans -- end self.curShowCareer = self.data.career local body = self.data.body local hair = self.data.hair self.curShowBody = body self.curShowHair = hair local cacheTrans = self.cacheRole[self.data.career..","..self.data.body..","..self.data.hair] if not IsNull(cacheTrans) then cacheTrans.gameObject:SetActive(true) self.bodyTrans = cacheTrans return end local bodyPath = ResPath.GetRoleBodyResPath(self.data.career, self.data.body) local on_load_body_succeed = function ( bodyObj ) if self.is_destroyed then return end self.bodyTrans = bodyObj.transform self.bodyTrans:SetParent(self.container) self.bodyTrans.localPosition = Vector3.zero self.bodyTrans.localScale = Vector3.one self.bodyTrans.localRotation = Quaternion.identity UI.SetLayer(bodyObj, "UILooksNode", true) self:UpdateRenderTexture() self:LoadRoleHair(hair) end ResMgr:LoadPrefabGameObject(bodyPath, on_load_body_succeed) end function UILooksNode:LoadRoleHair( hair ) local on_load_hair_succeed = function ( hairObj ) if self.is_destroyed then return end local headBoneTrans = self.bodyTrans:Find("head") self.hairTrans = hairObj.transform self.hairTrans:SetParent(headBoneTrans) self.hairTrans.localPosition = Vector3.zero self.hairTrans.localScale = Vector3.one self.hairTrans.localRotation = Quaternion.identity UI.SetLayer(hairObj, "UILooksNode", true) end local hairPath = ResPath.GetRoleHairResPath(self.curShowCareer, hair) ResMgr:LoadPrefabGameObject(hairPath, on_load_hair_succeed) end function UILooksNode:UpdateRenderTexture( ) if self.renderTexture then return end local imgWidth, imgHeight = UI.GetSizeDeltaXY(self.data.showRawImg.transform) local renderWidth = self.data.renderWidth or imgWidth local renderHeight = self.data.renderHeight or imgHeight renderWidth = math.floor(renderWidth) renderHeight = math.floor(renderHeight) self.renderTexture = CS.UnityEngine.RenderTexture(renderWidth, renderHeight, 24) self.camera.targetTexture = self.renderTexture self.data.showRawImg.texture = self.renderTexture UI.SetSizeDeltaXY(self.data.showRawImg.transform, renderWidth, renderHeight) end function UILooksNode:LoadNPC( ) if (self.curShowNPCID and self.curShowNPCID==self.data.npcID) then return end -- if not IsNull(self.npcTrans) then -- self.npcTrans.gameObject:SetActive(false) -- self.cacheNPC[self.curShowNPCID] = self.npcTrans -- end self.curShowNPCID = self.data.npcID local cacheTrans = self.cacheNPC[self.data.npcID] if not IsNull(cacheTrans) then cacheTrans.gameObject:SetActive(true) self.npcTrans = cacheTrans return end local looksPath = ResPath.GetNPCLooksPath(self.data.npcID) local on_load_body_succeed = function ( bodyObj ) if self.is_destroyed then return end self.npcTrans = bodyObj.transform self.npcTrans:SetParent(self.container) self.npcTrans.localPosition = Vector3.zero self.npcTrans.localScale = Vector3.one self.npcTrans.localRotation = Quaternion.identity UI.SetLayer(bodyObj, "UILooksNode", true) self:UpdateRenderTexture() end ResMgr:LoadPrefabGameObject(looksPath, on_load_body_succeed) end function UILooksNode:SetRenderObject( object ) end function UILooksNode:OnDestroy( ) end return UILooksNode
print("INFO: Static builds may not be usable due to unfinished strings bug. Normal builds require argparse.") local luaToUse = "lua53" -- Clear the build directory. if os.getenv("OS") == "Windows_NT" then os.execute("rmdir build /s /q") os.execute("mkdir build") os.execute("mkdir build\\linux") else os.execute("rm -rf build") os.execute("mkdir build") os.execute("mkdir build/inux") end local luaexec = { "5.4", "5.3", "5.2", "5.1", "jit" } local luaCompPath = ({...})[1] or "" local isLuaCompInstalled = true -- Check for LuaComp installation. if os.getenv("OS") == "Windows_NT" then if luaCompPath == "" then print("LuaComp path not set. This is required for Windows") print("To set the path to LuaComp, supply it as an argument to this program.") os.exit() end isLuaCompInstalled = false else if (not io.open("/bin/luacomp", "r")) and luaCompPath == "" then print("No existing installation of LuaComp found and LuaComp path is not set. Either make sure you have LuaComp installed or set the LuaComp path.") print("To set the path to LuaComp, supply it as an argument to this program.") os.exit() elseif not io.open("/bin/luacomp", "r") then isLuaCompInstalled = false end end -- Build Windows versions if os.getenv("OS") == "Windows_NT" then os.execute(luaToUse .. " " .. luaCompPath .. " ./src/init.lua -O ./build/luacomp.lua") os.execute(luaToUse .. " " .. luaCompPath .. " ./src/staticinit.lua -O ./build/luacomp-static.lua") else if isLuaCompInstalled == true then os.execute("luacomp ./src/init.lua -O ./build/luacomp.lua") os.execute("luacomp ./src/staticinit.lua -O ./build/luacomp-static.lua") else os.execute(luaToUse .. " " .. luaCompPath .. " ./src/init.lua -O ./build/luacomp.lua") os.execute(luaToUse .. " " .. luaCompPath .. " ./src/staticinit.lua -O ./build/luacomp-static.lua") end end -- Build Linux versions that are directly executable. for _,version in ipairs(luaexec) do print("Making release for Lua " .. version) if os.getenv("OS") == "Windows_NT" then os.execute(luaToUse .. " " .. luaCompPath .. " ./src/init.lua -O ./build/linux/luacomp-" .. version .. " --executable " .. version) os.execute(luaToUse .. " " .. luaCompPath .. " ./src/staticinit.lua -O ./build/linux/luacomp-static-" .. version .. " --executable " .. version) else if isLuaCompInstalled == true then os.execute("luacomp ./src/init.lua -O ./build/linux/luacomp-" .. version .. " --executable " .. version) os.execute("luacomp ./src/staticinit.lua -O ./build/linux/luacomp-static-" .. version .. " --executable " .. version) else os.execute(luaToUse .. " " .. luaCompPath .. " ./src/init.lua -O ./build/linux/luacomp-" .. version .. " --executable " .. version) os.execute(luaToUse .. " " .. luaCompPath .. " ./src/staticinit.lua -O ./build/linux/luacomp-static-" .. version .. " --executable " .. version) end end end -- Original script for reference. -- os.execute("rm -rf build") -- os.execute("mkdir build") -- for i=1, #luaexec do -- os.execute("luacomp -xlua"..luaexec[i].." -mluamin -O build/luacomp-"..luaexec[i].." src/init.lua") -- os.execute("luacomp -xlua"..luaexec[i].." -mnone -O build/luacomp-static-"..luaexec[i].." src/staticinit.lua") -- os.execute("chmod +x build/luacomp-"..luaexec[i]) -- os.execute("chmod +x build/luacomp-static-"..luaexec[i]) -- end -- os.execute("cp -v build/luacomp-".._VERSION:sub(5).." luacomp")
-- Command Computer Clearing program local tArgs = {...} if not commands then print("Command Computers only") return end if #tArgs < 6 then print(fs.getName(shell.getRunningProgram()).." <x1> <y1> <z1> <x2> <y2> <z2>") return end -- filter args local x1 = math.floor(tonumber(tArgs[1])) local y1 = math.floor(tonumber(tArgs[2])) local z1 = math.floor(tonumber(tArgs[3])) local x2 = math.floor(tonumber(tArgs[4])) local y2 = math.floor(tonumber(tArgs[5])) local z2 = math.floor(tonumber(tArgs[6])) local volume = (math.abs((x1-x2)+1))*(math.abs((y1-y2)+1))*(math.abs((z1-z2)+1)) -- confirmation print("Are you sure you want to delete "..volume.." blocks?") print("X1: "..tArgs[1].." Y1: "..tArgs[2].." Z1: "..tArgs[3]) print("X2: "..tArgs[4].." Y2: "..tArgs[5].." Z2: "..tArgs[6]) while true do e = {os.pullEvent("key")} if e[2] == keys.y then print("Clearing "..volume.." blocks") -- clear space for y = y1,y2 do for z = z1,z2 do for x = x1,x2 do commands.exec("/setblock "..x.." "..y.." "..z.." minecraft:air") end end end print("Success") break elseif e[2] == keys.n then print("Aborted") break end end coroutine.yield()
data:extend( { { type = "item", name = "burner-fuel-assembling-machine", icon = "__burn-the-world__/graphics/icons/fuel-assembling-machine.png", flags = {"goes-to-quickbar"}, subgroup = "burner-production-machine", order = "b[assembling-machine-2]-b", place_result = "burner-fuel-assembling-machine", stack_size = 50 }, { type = "recipe", name = "burner-fuel-assembling-machine", enabled = false, ingredients = { {"iron-plate", 9}, {"clockwork-parts", 5}, {"iron-gear-wheel", 5}, {"copper-gear-wheel", 2}, }, result = "burner-fuel-assembling-machine", requester_paste_multiplier = 4 }, { type = "assembling-machine", name = "burner-fuel-assembling-machine", icon = "__burn-the-world__/graphics/icons/fuel-assembling-machine.png", flags = {"placeable-neutral", "placeable-player", "player-creation"}, minable = {hardness = 0.2, mining_time = 0.5, result = "burner-fuel-assembling-machine"}, max_health = 250, corpse = "big-remnants", dying_explosion = "medium-explosion", resistances = { { type = "fire", percent = 70 } }, fluid_boxes = { { production_type = "input", pipe_picture = assembler2pipepictures(), pipe_covers = pipecoverspictures(), base_area = 10, base_level = -1, pipe_connections = {{ type="input", position = {0.5, -1.5} }} }, { production_type = "output", pipe_picture = assembler2pipepictures(), pipe_covers = pipecoverspictures(), base_area = 10, base_level = 1, pipe_connections = {{ type="output", position = {-0.5, 1.5} }} }, off_when_no_fluid_recipe = true }, collision_box = {{-0.7, -0.7}, {0.7, 0.7}}, selection_box = {{-1.0, -1.0}, {1.0, 1.0}}, fast_replaceable_group = "tiny-assembling-machine", animation = { filename = "__base__/graphics/entity/assembling-machine-2/assembling-machine-2.png", priority = "high", width = 113, height = 99, frame_count = 32, line_length = 8, shift = {0.4, -0.06}, scale = 0.66, }, open_sound = { filename = "__base__/sound/machine-open.ogg", volume = 0.85 }, close_sound = { filename = "__base__/sound/machine-close.ogg", volume = 0.75 }, vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }, working_sound = { sound = { { filename = "__base__/sound/assembling-machine-t2-1.ogg", volume = 0.8 }, { filename = "__base__/sound/assembling-machine-t2-2.ogg", volume = 0.8 }, }, idle_sound = { filename = "__base__/sound/idle1.ogg", volume = 0.6 }, apparent_volume = 1.5, }, crafting_categories = {"burner-fuel-processing"}, crafting_speed = 1.0, energy_source = { type = "burner", effectivity = 1, fuel_inventory_size = 1, smoke = { { name = "smoke", deviation = {0.1, 0.1}, frequency = 0.3 } } }, energy_usage = "50kW", ingredient_count = 5 }, } )
---------------------------- -- Bunny Hop -- -- Created by Skeyler.com -- ---------------------------- HOOKS["InitPostEntity"] = function() GAMEMODE:AddACArea(Vector(2824, 10532, -42),Vector(2871, 11073, 158)) GAMEMODE:AddACArea(Vector(3309, 10581, -38),Vector(3409, 11766, 200)) GAMEMODE:AddACArea(Vector(-989, 10685, -1511),Vector(-929, 11597, -756)) GAMEMODE:AddACArea(Vector(-1560, 10685, -1511),Vector(-1502, 11597, -756)) GAMEMODE:AddACArea(Vector(8603, 6525, -2121),Vector(9051, 6580, -1921)) GAMEMODE:AddACArea(Vector(8464, 6326, -2572),Vector(8597, 6580, -2372)) GAMEMODE:AddACArea(Vector(7419, 6529, -2572),Vector(8597, 6580, -2372)) GAMEMODE:AddACArea(Vector(6666, 3283, -2572),Vector(6725, 5978, -2372)) GAMEMODE:AddACArea(Vector(7324, 3415, -2572),Vector(7324, 3415, -2372)) GAMEMODE:AddACArea(Vector(7395, 5665, -2572),Vector(8585, 5718, -2572)) end
-- -- Register digtron diggers for tronwrench -- local definition = { name = 'digtron_digger', nodes = { "digtron:intermittent_digger", "digtron:intermittent_soft_digger", }, group = 'digtron digger', protection_bypass_read = "interact", } function definition:copy(node, pos, player) local meta = minetest.get_meta(pos) return { description = metatool.util.description(pos, node, meta), period = meta:get_int("period"), offset = meta:get_int("offset"), } end function definition:paste(node, pos, player, data) local meta = minetest.get_meta(pos) meta:set_int("period", data.period) meta:set_int("offset", data.offset) end return definition
local lib = {} local keylen = 5 local keyfile = ".keys" function lib.set_keyfile(kf) keyfile = kf or keyfile return lib end --[[ # Key format: { path:string key:string starts:date ends:date max_clicks:n clicks:n } # Todo list: 2016-10-06 - Read Keys --done - Write Keys --done - `__tostring` metamethod for keys --done - implement key object integrity check --done 2016-10-07 - Check for key validity --done 2016-10-08 - Check data integrity while reading --done - ⤷ Remove integrity check when writing --done - Change keys from index->data to key->data --done - ⤷ Change `ipairs` to `pairs` where needed --done - Use key --done --]] -- **Data Access / Back-end** local fields = { --{name, function}; where function is applied to the data after reading it in as a string {"path", tostring}; {"key", tostring}; {"starts", tonumber}; {"ends", tonumber}; {"max_clicks", tonumber}; {"clicks", tonumber}; } local _key_meta = { __tostring = function(self) local result = "" for index, field in ipairs(fields) do result = result .. field[1] .. " = " .. (self[field[1]] or "") if index < #fields then result = result .. "\n" end end return result end; } local _keys_meta = { __tostring = function(self) return "keylist from file" -- |todo|: implement end; } local function generate_key(length) math.randomseed(os.time()) local str = "" for i=1,length do str = str..("%02X"):format(math.random(0,255)) end return str end local function check_data_integrity(key) -- Key must have all the needed fields fields for index, field in ipairs(fields) do if not key[field[1]] then return false end end return true end local function is_valid(key) -- Is the data intact? if not check_data_integrity(key) then return false end -- Is the key too old? if (key.ends < os.time()) and (key.ends > 0) then return false end -- Has it been used too many times? if key.max_clicks > 0 then if key.clicks >= key.max_clicks then return false end end return true end local function read_keys(filename) local keys = setmetatable({}, _keys_meta) local file = io.open(filename) if not file then return nil, "Could not open key file for reading" end ---- for line in file:lines() do local key = setmetatable({}, _key_meta) local i=1; for thing in line:gmatch"[^\t]+" do thing = fields[i][2](thing) if (thing == "") or not thing then goto next end if fields[i] then key[fields[i][1]]=thing end i = i + 1 end if is_valid(key) then keys[key.key]=key end ::next:: end ---- file:close() return keys end local function write_keys(filename, keys) local file = io.open(filename, "w") if not file then return nil, "Could not open file" end ---- for key_str, key in pairs(keys) do for index, field in ipairs(fields) do file:write(key[field[1]]) if index<#fields then file:write "\t" end end file:write("\n") end ---- file:close() return true; end local function is_sub_dir(sub_dir, dir) return sub_dir:gsub("/&", ""):gsub("([^/])$", "%1/"):find(dir:gsub("([^/])$", "%1/"):gsub("^/?", "^/?")) and true or false end -- **Interface / Front-end** function lib.load() return read_keys(keyfile) end function lib.save(keys) return write_keys(keyfile, keys) end lib.is_sub_dir = is_sub_dir function lib.is_usable(key, path) -- Is the key `nil`? if not key then return nil, "no key" end -- Is the key invalid or has it expired? if not is_valid(key) then return false, "invalid" end -- Has the key lifetime started yet? if key.starts > os.time() then return false, "not valid yet" end -- If dir is provided, does the key apply to it? if type(path)=="string" then return is_sub_dir(path, key.path) end return true end function lib.use(key, path) if not lib.is_usable(key, path) then return key end key.clicks = key.clicks + 1 print(("Used key %s to access %s"):format(key.key, path)) return true end function lib.new(key) local new = setmetatable({}, _key_meta) new.path = key.path or "/" new.key = key.key or generate_key(keylen) new.starts = key.starts or os.time() new.ends = key.ends or 0 new.clicks = 0 new.max_clicks = key.max_clicks or 0 return new end -- debugging stuff -- --[[ local k = read_keys(keyfile) or {} -- k[#k+1]=lib.new({path="/new", key=generate_key(10), starts=os.time(), ends=os.time()+120*60, max_clicks=20}) -- checks go here -- print(lib.use(k["B5127C6C37F4187AA719"], "/new")) print(k["B5127C6C37F4187AA719"]) write_keys(keyfile, k) --]] return lib
----------------------------------- -- Area: Mount Zhayolm -- NPC: Bapokk -- Handles access to Alzadaal Ruins -- !pos -20 -6 276 61 ----------------------------------- require("scripts/globals/npc_util") ----------------------------------- function onTrade(player, npc, trade) if npcUtil.tradeHas(trade, 2185) then -- Silver player:startEvent(163) end end function onTrigger(player, npc) if player:getZPos() > -280 then player:startEvent(164) -- Ruins -> Zhayolm else player:startEvent(162) -- Zhayolm -> Ruins end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if csid == 163 then player:confirmTrade() player:setPos(-20, -6, 0, 192) -- using the pos method until the problem below is fixed end end
function love.conf(t) t.window.title = "gRabbit 0.0.1 alpha" t.window.width = 1300 t.window.height = 800 t.window.borderless = false t.window.resizable = false t.window.vsync = true t.modules.system = true t.modules.event = true t.modules.window = true t.modules.image = true t.modules.graphics = true t.modules.math = true t.modules.physics = true t.modules.audio = true t.modules.keyboard = true io.stdout:setvbuf("no") -- Allows Sublime Text to print in real time end
-- Prosody IM -- Copyright (C) 2014 Daurnimator -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- -- This module allows you to use cqueues with a net.server mainloop -- local server = require "net.server"; local cqueues = require "cqueues"; local timer = require "util.timer"; assert(cqueues.VERSION >= 20150113, "cqueues newer than 20150113 required") -- Create a single top level cqueue local cq; if server.cq then -- server provides cqueues object cq = server.cq; elseif server.watchfd then cq = cqueues.new(); local timeout = timer.add_task(cq:timeout() or 0, function () -- FIXME It should be enough to reschedule this timeout instead of replacing it, but this does not work. See https://issues.prosody.im/1572 assert(cq:loop(0)); return cq:timeout(); end); server.watchfd(cq:pollfd(), function () assert(cq:loop(0)); local t = cq:timeout(); if t then timer.stop(timeout); timeout = timer.add_task(cq:timeout(), function () assert(cq:loop(0)); return cq:timeout(); end); end end); else error "NYI" end return { cq = cq; }
local present, autosave = pcall(require, "autosave") if not present then return end autosave.setup({ enabled = true, execution_message = " 💾 saving...", events = { "InsertLeave", "TextChanged" }, conditions = { exists = true, filename_is_not = {}, filetype_is_not = {}, modifiable = true, }, write_all_buffers = false, on_off_commands = true, clean_command_line_interval = 1000, debounce_delay = 135, })
object_tangible_door_heroic_axkva_min_door = object_tangible_door_shared_heroic_axkva_min_door:new { } ObjectTemplates:addTemplate(object_tangible_door_heroic_axkva_min_door, "object/tangible/door/heroic_axkva_min_door.iff")
Config = {} Config.Locale = 'en' -- available: cs, de, en, es, fr, it, nl Config.JobId = 'police' -- people with this job can't get in Config.DrawBlips = true -- if true, map markers are visible
-- Copyright 2020 Wirepath Home Systems, LLC. All rights reserved. function CancelTimer (timerId) if (type (timerId) == 'userdata' and timerId.Cancel) then timerId:Cancel () elseif (type (timerId) == 'string') then if (Timer [timerId]) then if (Timer [timerId].Cancel) then Timer [timerId] = Timer [timerId]:Cancel () else Timer [timerId] = nil end end end return nil end function SetTimer (timerId, delay, timerFunction, repeating) if (timerId) then CancelTimer (timerId) end if (timerFunction == nil) then if (type (_G [timerId]) == 'function') then timerFunction = function (timer) _G [timerId] () end else timerFunction = function (timer) end end end local _timer = function (timer) timerFunction (timer) if (repeating ~= true) then CancelTimer (timerId) end end local timer = C4:SetTimer (delay, _timer, (repeating == true)) if (type (timerId) == 'string') then if (timerId and timer) then Timer [timerId] = timer end end return timer end function XMLDecode (s) if (s == nil) then return end s = tostring (s) s = string.gsub (s, '%<%!%[CDATA%[(.-)%]%]%>', function (a) return (a) end) s = string.gsub (s, '&quot;' , '"') s = string.gsub (s, '&lt;' , '<') s = string.gsub (s, '&gt;' , '>') s = string.gsub (s, '&apos;' , '\'') s = string.gsub (s, '&#x(.-);', function (a) return string.char (tonumber (a, 16) % 256) end ) s = string.gsub (s, '&#(.-);', function (a) return string.char (tonumber (a) % 256) end ) s = string.gsub (s, '&amp;' , '&') return s end function Print (data) if (type (data) == 'table') then for k, v in pairs (data) do print (k, v) end elseif (type (data) ~= 'nil') then print (type (data), data) else print ('nil value') end end function ExecuteCommand (strCommand, tParams) tParams = tParams or {} local output = {'--- ExecuteCommand', strCommand, '----PARAMS----'} for k,v in pairs (tParams) do table.insert (output, tostring (k) .. ' = ' .. tostring (v)) end table.insert (output, '---') output = table.concat (output, '\r\n') print (output) if (strCommand == 'LUA_ACTION') then if (tParams.ACTION) then strCommand = tParams.ACTION tParams.ACTION = nil end end if (strCommand == 'GetVariable') then if (WATCH.DEVICE and WATCH.VAR) then local strValue = C4:GetDeviceVariable (WATCH.DEVICE, WATCH.VAR) OnWatchedVariableChanged (WATCH.DEVICE, WATCH.VAR, strValue) end end end function OnDriverLateInit () C4:AddVariable ('STRING', '', 'STRING', true, false) C4:SetVariable ('STRING', '') C4:AddVariable ('NUMBER', 0, 'NUMBER', true, false) C4:SetVariable ('NUMBER', 0) C4:AddVariable ('BOOL', '1', 'BOOL', true, false) C4:SetVariable ('BOOL', '1') PersistData = PersistData or {} WATCH = PersistData.WATCH or {} PersistData.WATCH = WATCH for property, _ in pairs (Properties) do OnPropertyChanged (property) end end function OnPropertyChanged (strProperty) local value = Properties [strProperty] if (value == nil) then value = '' end local output = {'--- OnPropertyChanged', strProperty, value} output = table.concat (output, '\r\n') print (output) if (strProperty == 'Device With Variable') then local deviceId = tonumber (value) local displayName = C4:GetDeviceDisplayName (deviceId or -1) if (deviceId == 100001) then displayName = 'Variables Agent' end if (displayName == nil) then C4:UpdateProperty ('Selected Device Name', 'Device Not Found - please check device ID') C4:UpdatePropertyList ('Variable Selector', '') C4:UpdateProperty ('Variable Selector', '') Unregister () WATCH.DEVICE = nil return end C4:UpdateProperty ('Device With Variable', tostring (deviceId)) if (WATCH.DEVICE ~= deviceId) then Unregister () WATCH.DEVICE = deviceId end C4:UpdateProperty ('Selected Device Name', displayName) local vars = C4:GetDeviceVariables (deviceId) or {} local list = {} local selected for id, var in pairs (vars) do local item = string.gsub (var.name, ',', '') .. ' [' .. id .. ']' table.insert (list, item) if (tonumber (id) == WATCH.VAR) then selected = item end end table.sort (list) list = table.concat (list, ',') C4:UpdatePropertyList ('Variable Selector', list) if (selected) then C4:UpdateProperty ('Variable Selector', selected) OnPropertyChanged ('Variable Selector') end elseif (strProperty == 'Variable Selector') then local variableId = string.match (value, '.+%[(%d+)%]') variableId = tonumber (variableId) Unregister () WATCH.VAR = variableId if (variableId) then C4:RegisterVariableListener (WATCH.DEVICE, WATCH.VAR) end elseif (strProperty == 'Pattern') then if (value == '') then PATTERN = nil else local status, result = pcall (string.find, '', value) if (not status) then print ('Error with pattern - please check again') PATTERN = nil else print ('Pattern accepted') PATTERN = value end end local captures = 0 local captureCheck = PATTERN or '' captureCheck = string.gsub (captureCheck, '%%%(', '') or '' captureCheck = string.gsub (captureCheck, '%%%)', '') or '' for _, _ in string.gfind (captureCheck, '%b()') do captures = captures + 1 end for i = 1, captures do C4:AddVariable ('Pattern Capture ' .. tostring (i), '', 'STRING', true, false) end if (WATCH.DEVICE and WATCH.VAR) then local strValue = C4:GetDeviceVariable (WATCH.DEVICE, WATCH.VAR) OnWatchedVariableChanged (WATCH.DEVICE, WATCH.VAR, strValue) end end end function OnWatchedVariableChanged (idDevice, idVariable, strValue) if (idDevice == WATCH.DEVICE and idVariable == WATCH.VAR) then print ('Variable Changed: ' .. strValue) print ('Firing Event: Variable Changed') C4:FireEvent ('Variable Changed') local s = tostring (strValue) or '' local n = string.match (strValue, '%d+') or '' local test = string.upper (tostring (strValue)) local b = ((test == '1' or test == 'TRUE') and '1') or '0' C4:SetVariable ('STRING', s) C4:SetVariable ('NUMBER', n) C4:SetVariable ('BOOL', b) print ('Setting Variable: STRING: ' .. s) print ('Setting Variable: NUMBER: ' .. n) print ('Setting Variable: BOOL: ' .. b) if (PATTERN) then local result = {string.find (strValue, PATTERN)} if (result [1] and result [2]) then table.remove (result, 1) table.remove (result, 1) for i = 1, #result do C4:SetVariable ('Pattern Capture ' .. tostring (i), result [i] or '') print ('Setting Variable: Pattern Capture ' .. tostring (i) .. ': ' .. result [i] or '') end print ('Firing Event: Pattern Found') C4:FireEvent ('Pattern Found') end end end end function Unregister () if (WATCH.DEVICE and WATCH.VAR) then C4:UnregisterVariableListener (WATCH.DEVICE, WATCH.VAR) WATCH.VAR = nil end end
fx_version 'cerulean' game 'gta5' description 'qb-chains | DoritoXheaD' version '1.0.0' client_script 'client.lua' server_script 'server.lua'
fx_version 'adamant' game 'gta5' author 'Paradise' description 'Paradise Neons (RTX)' version '1.0' client_scripts { 'config.lua', 'client/main.lua' } files { 'html/ui.html', 'html/styles.css', 'html/scripts.js', 'html/debounce.min.js', 'html/BebasNeue.ttf', 'html/images/*.png' } ui_page 'html/ui.html'
-- This file is subject to copyright - contact [email protected] for more information. -- INSTALL: CINEMA -- autorun/client/cl_vapeswep.lua -- Defines clientside globals for Vape SWEP -- Vape SWEP by Swamp Onions - http://steamcommunity.com/id/swamponions/ if not VapeParticleEmitter then VapeParticleEmitter = ParticleEmitter(Vector(0, 0, 0)) end sound.Add({ name = "vape_inhale", channel = CHAN_WEAPON, volume = 0.24, level = 60, pitch = {95}, sound = "vapeinhale.wav" }) net.Receive("Vape", function() local ply = net.ReadEntity() local amt = net.ReadInt(8) local fx = net.ReadInt(8) if not IsValid(ply) then return end if fx ~= 2 and ply:GetPos():Distance(EyePos()) > 2000 then return end if amt >= 50 then ply:EmitSound("vapecough1.wav", 90) for i = 1, 200 do local d = i + 10 if i > 140 then d = d + 150 end timer.Simple((d - 1) * 0.003, function() vape_do_pulse(ply, 1, 100, fx) end) end return elseif amt >= 35 then ply:EmitSound("vapebreath2.wav", 75, 100, 0.7) elseif amt >= 10 then ply:EmitSound("vapebreath1.wav", 70, 130 - math.min(100, amt * 2), 0.4 + (amt * 0.005)) end for i = 1, amt * 2 do timer.Simple((i - 1) * 0.02, function() vape_do_pulse(ply, math.floor(((amt * 2) - i) / 10), fx == 2 and 100 or 0, fx) end) end end) net.Receive("VapeArm", function() local ply = net.ReadEntity() local z = net.ReadBool() if not IsValid(ply) then return end if ply.vapeArm ~= z then if z then timer.Simple(0.3, function() if not IsValid(ply) then return end if ply.vapeArm then ply:EmitSound("vape_inhale") end end) else ply:StopSound("vape_inhale") end ply.vapeArm = z ply.vapeArmTime = os.clock() local m = 0 if z then m = 1 end for i = 0, 19 do timer.Simple(i / 60, function() vape_interpolate_arm(ply, math.abs(m - ((19 - i) / 20)), z and 0 or 0.2) end) end end end) net.Receive("VapeTalking", function() local ply = net.ReadEntity() if IsValid(ply) then ply.vapeTalkingEndtime = net.ReadFloat() end end) function vape_interpolate_arm(ply, mult, mouth_delay) if not IsValid(ply) then return end ply.vapeArmUpAmt = mult if mouth_delay > 0 then timer.Simple(mouth_delay, function() if IsValid(ply) then ply.vapeMouthOpenAmt = mult end end) else ply.vapeMouthOpenAmt = mult end local b1 = ply:LookupBone("ValveBiped.Bip01_R_Upperarm") local b2 = ply:LookupBone("ValveBiped.Bip01_R_Forearm") if (not b1) or (not b2) then return end ply:ManipulateBoneAngles(b1, Angle(20 * mult, -62 * mult, 10 * mult), "vape") ply:ManipulateBoneAngles(b2, Angle(-5 * mult, -10 * mult, 0), "vape") if mult == 1 then ply.vapeArmFullyUp = true else ply.vapeArmFullyUp = false end end function vape_do_pulse(ply, amt, spreadadd, fx) if not IsValid(ply) then return end if ply:WaterLevel() == 3 then return end if not spreadadd then spreadadd = 0 end local attachid = ply:LookupAttachment("eyes") VapeParticleEmitter:SetPos(LocalPlayer():GetPos()) local angpos = ply:GetAttachment(attachid) or { Ang = Angle(0, 0, 0), Pos = Vector(0, 0, 0) } local fwd local pos if (ply ~= LocalPlayer()) then fwd = (angpos.Ang:Forward() - angpos.Ang:Up()):GetNormalized() pos = angpos.Pos + (fwd * 3.5) else fwd = ply:GetAimVector():GetNormalized() pos = ply:GetShootPos() + fwd * 1.5 + gui.ScreenToVector(ScrW() / 2, ScrH()) * 5 end fwd = ply:GetAimVector():GetNormalized() for i = 1, amt do if not IsValid(ply) then return end local particle if fx == 6 then particle = VapeParticleEmitter:Add(string.format("effects/fire_cloud1"), pos) if ply == LocalPlayer() then table.insert(MyDragonVapeParticles, particle) end else particle = VapeParticleEmitter:Add(string.format("particle/smokesprites_00%02d", math.random(7, 16)), pos) end if particle then local dir = VectorRand():GetNormalized() * ((amt + 5) / 10) vape_do_particle(particle, (ply:GetVelocity() * 0.25) + (((fwd * 9) + dir):GetNormalized() * math.Rand(50, 80) * (amt + 1) * 0.2), fx) end end end local DisableConvar = CreateClientConVar("vape_disable", "0") function vape_do_particle(particle, vel, fx) if DisableConvar:GetBool() then return end particle:SetColor(255, 255, 255, 255) if fx == 3 then particle:SetColor(220, 255, 230, 255) end if fx == 4 then particle:SetColor(220, 230, 255, 255) end if fx == 7 then particle:SetColor(vape_red_white_blue_chooser(math.random(0, 2) / 3)) end if fx >= 20 then local c = JuicyVapeJuices[fx - 19].color if c == nil then c = HSVToColor(math.random(0, 359), 1, 1) end particle:SetColor(c.r, c.g, c.b, 255) end local mega = 1 if fx == 2 then mega = 4 end particle:SetVelocity(vel * mega * (fx == 6 and 2 or 1)) particle:SetGravity(Vector(0, 0, fx == 4 and 15 or 1.5)) particle:SetLifeTime(0) particle:SetDieTime(math.Rand(80, 100) * 0.11 * mega) if fx == 6 then particle:SetDieTime(math.Rand(80, 100) * 0.03) end particle:SetStartSize(2 * mega) if fx == 6 then particle:SetStartSize(3) end particle:SetEndSize(40 * mega * mega) if fx == 6 then particle:SetEndSize(20) end particle:SetStartAlpha(fx == 4 and 20 or 150) particle:SetEndAlpha(0) particle:SetCollide(true) particle:SetBounce(0.25) particle:SetRoll(math.Rand(0, 360)) particle:SetRollDelta(0.01 * math.Rand(-40, 40)) particle:SetAirResistance(50) if fx == 6 then particle:SetAirResistance(20) end end MyDragonVapeParticles = {} timer.Create("DragonVapeCollisionDetection", 0.2, 0, function() for k2, p in next, MyDragonVapeParticles do if p:GetDieTime() - p:GetLifeTime() < 0.1 then table.remove(MyDragonVapeParticles, k2) end end if #MyDragonVapeParticles > 0 then for k, v in next, ents.GetAll() do if (v.nextDragonVapeTime or 0) < CurTime() and v:IsSolid() and v ~= LocalPlayer() then local pos = v:LocalToWorld(v:OBBCenter()) local rad = v:BoundingRadius() + 20 rad = rad * rad for k2, p in next, MyDragonVapeParticles do if (v.nextDragonVapeTime or 0) < CurTime() then if pos:DistToSqr(p:GetPos()) < rad then net.Start("DragonVapeIgnite") net.WriteEntity(v) net.SendToServer() v.nextDragonVapeTime = CurTime() + 5 end end end end end end end) function vape_red_white_blue_chooser(lerp) lerp = 3 * lerp local v = nil local r = Vector(255, 0, 0) local w = Vector(255, 255, 255) local b = Vector(0, 0, 255) if lerp >= 2 then v = LerpVector(lerp - 2, b, r) elseif lerp >= 1 then v = LerpVector(lerp - 1, w, b) else v = LerpVector(lerp, r, w) end --particle:SetColor takes seperate parameters per channel return v.x, v.y, v.z, 255 end matproxy.Add({ name = "VapeTankColor", init = function(self, mat, values) self.ResultTo = values.resultvar end, bind = function(self, mat, ent) if (not IsValid(ent)) then return end if ent:GetClass() == "viewmodel" then ent = ent:GetOwner() if (not IsValid(ent) or not ent:IsPlayer()) then return end ent = ent:GetActiveWeapon() if (not IsValid(ent)) then return end end local v = ent.VapeTankColor or Vector(0.3, 0.3, 0.3) if v == Vector(-1, -1, -1) then local c = HSVToColor((CurTime() * 60) % 360, 0.9, 0.9) v = Vector(c.r, c.g, c.b) / 255.0 end if v == Vector(-2, -2, -2) then local c = Color(vape_red_white_blue_chooser((CurTime() * 0.2) % 1)) v = Vector(c.r, c.g, c.b) / 255.0 end mat:SetVector(self.ResultTo, v) end }) matproxy.Add({ name = "VapeAccentColor", init = function(self, mat, values) self.ResultTo = values.resultvar end, bind = function(self, mat, ent) if (not IsValid(ent)) then return end local o = ent:GetOwner() if ent:GetClass() == "viewmodel" then if (not IsValid(o)) or (not o:IsPlayer()) then return end ent = o:GetActiveWeapon() if (not IsValid(ent)) then return end end local col = ent.VapeAccentColor or Vector(1, 1, 1) if col == Vector(-1, -1, -1) then col = Vector(1, 1, 1) if IsValid(o) then col = o.CustomVapeColor or col end end mat:SetVector(self.ResultTo, col) end })
function getRequiredComponents() return {"speed", "position"} end function update() for i, entity in ipairs(entities) do entity.position.x = entity.position.x + entity.speed.dx entity.position.y = entity.position.y + entity.speed.dy end end
--[[ Highlord Tirion Fordring yells: A mighty blow has been dealt to the Lich King! You have proven yourselves as able bodied champions of the Argent Crusade. Together we will strike against Icecrown Citadel and destroy what remains of the Scourge! There is no challenge that we cannot face united! Highlord Tirion Fordring yells: A shallow and tragic victory. We are weaker as a whole from the losses suffered today. Who but the Lich King could benefit from such foolishness? Great warriors have lost their lives. And for what? The true threat looms ahead - the Lich King awaits us all in death. Highlord Tirion Fordring yells: Arthas! You are hopelessly outnumbered! Lay down Frostmourne and I will grant you a just death. Highlord Tirion Fordring yells: Begin! Highlord Tirion Fordring yells: Champions, you're alive! Not only have you defeated every challenge of the Trial of the Crusader, but also thwarted Arthas' plans! Your skill and cunning will prove to be a powerful weapon against the Scourge. Well done! Allow one of the Crusade's mages to transport you to the surface! Highlord Tirion Fordring yells: Everyone calm down! Compose yourselves! There is no conspiracy at play here! The warlock acted on his own volition, outside of influences from the Alliance. The tournament must go on! Highlord Tirion Fordring yells: Go now and rest; you've earned it. Highlord Tirion Fordring yells: Grand Warlock Wilfred Fizzlebang will summon forth your next challenge. Stand by for his entry. Highlord Tirion Fordring yells: Hailing from the deepest, darkest caverns of the Storm Peaks, Gormok the Impaler! Battle on, heroes! Highlord Tirion Fordring yells: My congratulations, champions. Through trials both planned and unexpected, you have triumphed. Highlord Tirion Fordring yells: Only by working together will you overcome the final challenge. From the depths of Icecrown come two of the Scourge's most powerful lieutenants: fearsome val'kyr, winged harbingers of the Lich King! Highlord Tirion Fordring yells: Quickly, heroes, destroy the demon lord before it can open a portal to its twisted demonic realm! Highlord Tirion Fordring yells: Steel yourselves, heroes, for the twin terrors, Acidmaw and Dreadscale, enter the arena! Highlord Tirion Fordring yells: The air itself freezes with the introduction of our next combatant, Icehowl! Kill or be killed, champions! Highlord Tirion Fordring yells: The loss of Wilfred Fizzlebang, while unfortunate, should be a lesson to those that dare dabble in dark magic. Alas, you are victorious and now must face the next challenge. Highlord Tirion Fordring yells: The monstrous menagerie has been vanquished! Highlord Tirion Fordring yells: The next battle will be against the Argent Crusade's most powerful knights! Only by defeating them will you be deemed worthy... Highlord Tirion Fordring yells: Tragic... They fought valiantly, but the beasts of Northrend triumphed. Let us observe a moment of silence for our fallen heroes. Highlord Tirion Fordring yells: Very well. I will allow it. Fight with honor! Highlord Tirion Fordring yells: Welcome, champions! You have heard the call of the Argent Crusade and you have boldly answered! It is here, in the Crusaders' Coliseum, that you will face your greatest challenges. Those of you who survive the rigors of the coliseum will join the Argent Crusade on its march to Icecrown Citadel. Highlord Tirion Fordring yells: Welcome, champions. Today, before the eyes of your leaders and peers, you will prove yourselves worthy combatants. Highlord Tirion Fordring yells: Well done. You have proven yourself today- Highlord Tirion Fordring yells: Well fought! Your next challenge comes from the Crusade's own ranks. You will be tested against their considerable prowess. Highlord Tirion Fordring yells: What is the meaning of this? Highlord Tirion Fordring yells: You may begin! Highlord Tirion Fordring yells: You will first be facing three of the Grand Champions of the Tournament! These fierce contenders have beaten out all others to reach the pinnacle of skill in the joust. ]]-- function Tirion_OnSpawn(pUnit, event) pUnit:PlaySoundToSet(16036) pUnit:SendChatMessage(12, 0, "Welcome champions, you have heard the call of the Argent Crusade and you have boldly answered. It is here in the Crusaders Coliseum thatll you face your greatest challenges. Those of you that survive the riggers of the coliseum will join the Argent Crusade on its march to Icecrown Citadel.") end RegisterUnitEvent(34996, 18, "Tirion_OnSpawn") function Arelas_OnGossipTalk(pUnit, event, player) pUnit:GossipCreateMenu(1, player, 0) pUnit:GossipMenuAddItem(0, "I am ready.", 1, 0) pUnit:GossipMenuAddItem(0, "I am not ready.", 2, 0) pUnit:GossipSendMenu(player) end function Arelas_OnGossipSelect(pUnit, event, player, id, intid, pmisc) if(intid == 1) then pUnit:SpawnCreature(34996, 746.661682, 558.761353, 435.407013, 1.615844, 35, 0) player:GossipComplete() pUnit:SpawnLocalCreature(35604, 35, 0) pUnit:Despawn(100, 0) local team = player:GetTeam() if(team == 0) then local choice = math.random(1, 3) if(choice == 1) then pUnit:SpawnCreature(12009, 737.817810, 664.172607, 412.395111, 4.754529, 14, 0) pUnit:SpawnCreature(12006, 746.825989, 662.499084, 411.712555, 4.686143, 14, 0) pUnit:SpawnCreature(12008, 756.921082, 663.784058, 412.394165, 4.616966, 14, 0) elseif(choice == 2) then pUnit:SpawnCreature(12009, 737.817810, 664.172607, 412.395111, 4.754529, 14, 0) pUnit:SpawnCreature(12007, 746.825989, 662.499084, 411.712555, 4.686143, 14, 0) pUnit:SpawnCreature(12005, 756.921082, 663.784058, 412.394165, 4.616966, 14, 0) elseif(choice == 3) then pUnit:SpawnCreature(12007, 737.817810, 664.172607, 412.395111, 4.754529, 14, 0) pUnit:SpawnCreature(12006, 746.825989, 662.499084, 411.712555, 4.686143, 14, 0) pUnit:SpawnCreature(12005, 756.921082, 663.784058, 412.394165, 4.616966, 14, 0) end end if(team == 1) then local weird = math.random(1, 3) if(weird == 1) then pUnit:SpawnCreature(12000, 737.817810, 664.172607, 412.395111, 4.754529, 14, 0) pUnit:SpawnCreature(12001, 746.825989, 662.499084, 411.712555, 4.686143, 14, 0) pUnit:SpawnCreature(12002, 756.921082, 663.784058, 412.394165, 4.616966, 14, 0) elseif(weird == 2) then pUnit:SpawnCreature(12003, 737.817810, 664.172607, 412.395111, 4.754529, 14, 0) pUnit:SpawnCreature(12004, 746.825989, 662.499084, 411.712555, 4.686143, 14, 0) pUnit:SpawnCreature(12002, 756.921082, 663.784058, 412.394165, 4.616966, 14, 0) elseif(weird == 3) then pUnit:SpawnCreature(12002, 737.817810, 664.172607, 412.395111, 4.754529, 14, 0) pUnit:SpawnCreature(12004, 746.825989, 662.499084, 411.712555, 4.686143, 14, 0) pUnit:SpawnCreature(12000, 756.921082, 663.784058, 412.394165, 4.616966, 14, 0) end end end if(intid == 2) then player:GossipComplete() end end RegisterUnitGossipEvent(35005, 1, "Arelas_OnGossipTalk") RegisterUnitGossipEvent(35005, 2, "Arelas_OnGossipSelect") function Ambrose_OnSpawn(pUnit, event) local dungeon = pUnit:GetDungeonDifficulty() if(dungeon == 0) then pUnit:SetMaxHealth(189000) pUnit:SetHealth(189000) pUnit:SetMaxMana(159760) pUnit:SetMana(159760) elseif(dungeon == 1) then pUnit:SetMaxHealth(315000) pUnit:SetHealth(315000) end end RegisterUnitEvent(12000, 18, "Ambrose_OnSpawn") function DummyArelas_OnSpawn(pUnit, event) pUnit:RegisterEvent("DummyArelas_Move", 20000, 1) -- yell stuff -- pUnit:MoveTo(698.035217, 600.620911, 412.390625, 0.400121) end function DummyArelas_Move(pUnit, event) pUnit:MoveTo(704.810669, 603.286804, 412.391998, 0.449600) end RegisterUnitEvent(35604, 18, "DummyArelas_OnSpawn")
local html_builer = { "text", "raw", "widget", "element", "html_5", "capture", 'area', "applet", 'base', 'br', 'col', 'embed', 'frame', 'hr', 'img', 'input', 'link', 'meta', 'param', 'a', 'abbr', 'acronym', 'address', 'article', 'aside', 'audio', 'b', 'bdo', 'big', 'blockquote', 'body', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'colgroup', 'command', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'fieldset', 'figure', 'footer', 'form', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'html', 'i', 'iframe', 'ins', 'keygen', 'kbd', 'label', 'legend', 'li', 'map', 'mark', 'meter', 'nav', 'noframes', 'noscript', 'object', 'ol', 'optgroup', 'option', 'p', 'pre', 'progress', 'q', 'ruby', 'rt', 'rp', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strike', 'strong', 'style', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'tt', 'u', 'ul', 'var', 'video' } return { whitelist_globals = { ["."] = { "ngx", "__leda" }, ["lapis/views"] = html_builer } }
local scrollers = {} scrollers[PLAYER_1] = setmetatable({disable_wrapping=true}, sick_wheel_mt) scrollers[PLAYER_2] = setmetatable({disable_wrapping=true}, sick_wheel_mt) local mpn = GAMESTATE:GetMasterPlayerNumber() local firstToUpper = function(str) return (str:gsub("^%l", string.upper)) end local conversions = { min = "Min", max = "Max", jumps = "Jumps", bpm = "BPM", diff = "Difficulty", steps = "Steps" } conversions["="] = function(type,result) return "both", result end conversions["<="] = function(type,result) return "Max", result end conversions["<"] = function(type,result) return "Max", result - 1 end conversions[">="] = function(type,result) return "Min", result end conversions[">"] = function(type,result) return "Min", result + 1 end local QuickFilter = function(input) local filters = {"jumps","steps","bpm","diff"} local category, result, type for filter in ivalues(filters) do category = filter type, result = string.lower(input):match("^"..filter.."%s*([<>]?=)%s*(%d+)$") if type then type, result = conversions[type](type, result) break end type, result = string.lower(input):match("^"..filter.."%s*([<>])%s*(%d+)$") if type then type, result = conversions[type](type, result) break end type, result = string.lower(input):match("^(min)"..filter.."%s*=%s*(%d*)$") if result then type = firstToUpper(type) break end type, result = string.lower(input):match("^(max)"..filter.."%s*=%s*(%d*)$") if result then type = firstToUpper(type) break end end if string.lower(input):match("^filters?%s*=%s*off$") then ResetFilters() return true end if result then if type == "both" then SL.Global.ActiveFilters["Max"..conversions[category]] = tostring(result) SL.Global.ActiveFilters["Min"..conversions[category]] = tostring(result) else SL.Global.ActiveFilters[type..conversions[category]] = tostring(result) end return true end return nil end local searchMenu_input local TextEntrySettings = { -- ScreenMessage to send on pop (optional, "SM_None" if omitted) --SendOnPop = "", -- The question to display Question = "Search:", -- Initial answer text InitialAnswer = "", -- Maximum amount of characters MaxInputLength = 30, --Password = false, -- Validation function; function(answer, errorOut), must return boolean, string. Validate = function(answer, errorOut) return true, answer end, -- On OK; function(answer) OnOK = function(answer) if answer == "" then MESSAGEMAN:Broadcast("FinishText") --if players who don't have a keyboard get here they can just hit enter to cancel out else local filter = QuickFilter(answer) if filter then MESSAGEMAN:Broadcast("GroupTypeChanged") MESSAGEMAN:Broadcast("FinishText") else MESSAGEMAN:Broadcast("SetSearchWheel",{searchTerm=answer}) end end end, -- On Cancel; function() OnCancel = function() MESSAGEMAN:Broadcast("FinishText") end, -- Validate appending a character; function(answer,append), must return boolean ValidateAppend = nil, -- Format answer for display; function(answer), must return string FormatAnswerForDisplay = nil, } -- ---------------------------------------------------- local invalid_count = 0 SL.Global.SearchReady = false local t = Def.ActorFrame { ShowCustomSongMenuCommand=function(self) self:visible(true) end, HideCustomSongMenuCommand=function(self) self:visible(false) end, -- FIXME: stall for 0.5 seconds so that the Lua InputCallback doesn't get immediately added to the screen. -- It's otherwise possible to enter the screen with MenuLeft/MenuRight already held and firing off events, -- which causes the sick_wheel of profile names to not display. I don't have time to debug it right now. InitCommand=function(self) self:visible(false) searchMenu_input = LoadActor("./Input.lua", {af=self, Scrollers=scrollers}) self:queuecommand("Stall") --Leave the inputcallback in permanently and only accept input when SL.Global.SearchReady end, StallCommand=function(self) self:sleep(0.5):queuecommand("CaptureTest") end, CaptureTestCommand=function(self) SCREENMAN:GetTopScreen():AddInputCallback( searchMenu_input ) end, SearchCaptureReadyMessageCommand=function(self) SL.Global.SearchReady = true self:visible(true) end, DirectInputToSearchMenuCommand=function(self) SCREENMAN:AddNewScreenToTop("ScreenTextEntry") SCREENMAN:GetTopScreen():Load(TextEntrySettings) end, -- the OffCommand will have been queued, when it is appropriate, from ./Input.lua -- sleep for 0.5 seconds to give the PlayerFrames time to tween out -- and queue a call to Finish() so that the engine can wrap things up OffCommand=function(self) self:sleep(0.5):queuecommand("Finish") end, FinishTextMessageCommand=function(self) self:sleep(0.5):queuecommand("Finish") end, FinishCommand=function(self) self:visible(false) SL.Global.SearchReady = false local screen = SCREENMAN:GetTopScreen() local overlay = screen:GetChild("Overlay") overlay:queuecommand("DirectInputToEngine") end, WhatMessageCommand=function(self) self:runcommandsonleaves(function(subself) if subself.distort then subself:distort(0.5) end end):sleep(4):queuecommand("Undistort") end, UndistortCommand=function(self) self:runcommandsonleaves(function(subself) if subself.distort then subself:distort(0) end end) end, -- sounds LoadActor( THEME:GetPathS("Common", "invalid") )..{ InvalidChoiceMessageCommand=function(self) self:play() if invalid_count then invalid_count = invalid_count + 1 if invalid_count >= 10 then MESSAGEMAN:Broadcast("What"); invalid_count = nil end end end }, -- slightly darken the entire screen Def.Quad { InitCommand=function(self) self:FullScreen():diffuse(Color.Black):diffusealpha(0.8) end }, } -- top mask t[#t+1] = Def.Quad{ InitCommand=function(self) self:horizalign(left):vertalign(bottom):setsize(580,50):xy(_screen.cx-self:GetWidth()/2, _screen.cy-110):MaskSource() end } -- bottom mask t[#t+1] = Def.Quad{ InitCommand=function(self) self:horizalign(left):vertalign(top):setsize(580,20):xy(_screen.cx-self:GetWidth()/2, _screen.cy+220):MaskSource() end } -- Both players will share this so just set it based on master player number t[#t+1] = LoadActor("PlayerFrame.lua", {Player=mpn, Scroller=scrollers[mpn]}) return t
ReadDataFile("..\\..\\addon\\ME5\\data\\_LVL_PC\\master.lvl") isModMap = 1 -- -- Copyright (c) 2005 Pandemic Studios, LLC. All rights reserved. -- -- load the gametype script ScriptCB_DoFile("ME5_ObjectiveTDM") ScriptCB_DoFile("ME5_setup_teams") -- Empire Attacking (attacker is always #1) REP = 2 CIS = 1 -- These variables do not change ATT = 1 DEF = 2 --------------------------------------------------------------------------- -- FUNCTION: ScriptInit -- PURPOSE: This function is only run once -- INPUT: -- OUTPUT: -- NOTES: The name, 'ScriptInit' is a chosen convention, and each -- mission script must contain a version of this function, as -- it is called from C to start the mission. --------------------------------------------------------------------------- function ScriptPostLoad() WeatherMode = math.random(1,3) weather() hunt = ObjectiveTDM:New{teamATT = 1, teamDEF = 2, pointsPerKillATT = 1, pointsPerKillDEF = 3, textATT = "game.modes.hunt", textDEF = "game.modes.hunt2", multiplayerRules = true} hunt.OnStart = function(self) AddAIGoal(ATT, "Deathmatch", 1000) AddAIGoal(DEF, "Deathmatch", 1000) end hunt:Start() AddDeathRegion("monorail") AddDeathRegion("ocean") end function weather() if WeatherMode == 1 then ReadDataFile("dc:EDN\\spa_sky.lvl", "red") elseif WeatherMode == 2 then ReadDataFile("dc:EDN\\spa_sky.lvl", "red") elseif WeatherMode == 3 then ReadDataFile("dc:EDN\\spa_sky.lvl", "red") end end function ScriptInit() if(ScriptCB_GetPlatform() == "PS2") then StealArtistHeap(1024*1024) -- steal 1MB from art heap end -- Designers, these two lines *MUST* be first. --SetPS2ModelMemory(4500000) SetPS2ModelMemory(3300000) ReadDataFile("ingame.lvl") -- Empire Attacking (attacker is always #1) REP = 1 CIS = 2 DES = 3 -- These variables do not change ATT = 1 DEF = 2 ReadDataFile("..\\..\\addon\\ME5\\data\\_LVL_PC\\core.lvl") SetMaxFlyHeight(60) SetMaxPlayerFlyHeight(60) SetGroundFlyerMap(0); ReadDataFile("sound\\hot.lvl;hot1gcw") ReadDataFile("..\\..\\addon\\ME5\\data\\_LVL_PC\\SIDE\\ssv.lvl", "ssv_inf_soldier", "ssv_inf_infiltrator", "ssv_inf_adept", "ssv_inf_engineer", "ssv_inf_sentinel", "ssv_inf_vanguard") ReadDataFile("..\\..\\addon\\ME5\\data\\_LVL_PC\\SIDE\\indoc.lvl", "indoc_inf_husk") SetupTeams{ rep={ team = REP, units = 15, reinforcements = -1, soldier = {"ssv_inf_engineer",8, 25}, }, cis={ team = CIS, units = 15, reinforcements = -1, soldier = {"indoc_inf_husk", 8, 25}, } } --Setting up Heros-- -- Level Stats ClearWalkers() SetMemoryPoolSize("EntityWalker", -2) AddWalkerType(0, 0) -- 0 droidekas AddWalkerType(1, 0) -- 6 atsts with 1 leg pairs each AddWalkerType(2, 0) -- 2 atats with 2 leg pairs each SetMemoryPoolSize("Aimer", 90) SetMemoryPoolSize("AmmoCounter", 269) SetMemoryPoolSize("BaseHint", 250) SetMemoryPoolSize("CommandWalker", 2) SetMemoryPoolSize("ConnectivityGraphFollower", 56) SetMemoryPoolSize("EnergyBar", 269) SetMemoryPoolSize("EntityCloth", 28) SetMemoryPoolSize("EntityFlyer", 6) SetMemoryPoolSize("EntityLight", 225) SetMemoryPoolSize("EntitySoundStatic", 16) SetMemoryPoolSize("EntitySoundStream", 5) SetMemoryPoolSize("FLEffectObject::OffsetMatrix", 54) SetMemoryPoolSize("MountedTurret", 46) SetMemoryPoolSize("Navigator", 63) SetMemoryPoolSize("Obstacle", 400) SetMemoryPoolSize("OrdnanceTowCable", 40) -- !!!! need +4 extra for wrapped/fallen cables !!!! SetMemoryPoolSize("PathFollower", 63) SetMemoryPoolSize("PathNode", 268) SetMemoryPoolSize("RedOmniLight", 240) SetMemoryPoolSize("TreeGridStack", 329) SetMemoryPoolSize("UnitController", 63) SetMemoryPoolSize("UnitAgent", 63) SetMemoryPoolSize("Weapon", 269) ReadDataFile("EDN\\EDN.lvl", "EDN_hunt") --ReadDataFile("tan\\tan1.lvl", "tan1_obj") SetSpawnDelay(10.0, 0.25) SetDenseEnvironment("false") SetDefenderSnipeRange(170) -- Sound Stats voiceSlow = OpenAudioStream("sound\\global.lvl", "all_unit_vo_slow") AudioStreamAppendSegments("sound\\global.lvl", "imp_unit_vo_slow", voiceSlow) AudioStreamAppendSegments("sound\\global.lvl", "global_vo_slow", voiceSlow) voiceQuick = OpenAudioStream("sound\\global.lvl", "all_unit_vo_quick") AudioStreamAppendSegments("sound\\global.lvl", "imp_unit_vo_quick", voiceQuick) OpenAudioStream("sound\\global.lvl", "gcw_music") -- OpenAudioStream("sound\\global.lvl", "global_vo_quick") -- OpenAudioStream("sound\\global.lvl", "global_vo_slow") OpenAudioStream("sound\\hot.lvl", "hot1gcw") OpenAudioStream("sound\\hot.lvl", "hot1gcw") -- SetBleedingVoiceOver(ALL, ALL, "all_off_com_report_us_overwhelmed", 1) -- SetBleedingVoiceOver(ALL, IMP, "all_off_com_report_enemy_losing", 1) -- SetBleedingVoiceOver(IMP, ALL, "imp_off_com_report_enemy_losing", 1) -- SetBleedingVoiceOver(IMP, IMP, "imp_off_com_report_us_overwhelmed", 1) -- SetLowReinforcementsVoiceOver(ALL, IMP, "all_hot_transport_away", .75, 1) -- SetLowReinforcementsVoiceOver(ALL, IMP, "all_hot_transport_away", .5, 1) -- SetLowReinforcementsVoiceOver(ALL, IMP, "all_hot_transport_away", .25, 1) -- SetLowReinforcementsVoiceOver(ALL, ALL, "all_off_defeat_im", .1, 1) -- SetLowReinforcementsVoiceOver(ALL, IMP, "all_off_victory_im", .1, 1) -- SetLowReinforcementsVoiceOver(IMP, IMP, "imp_off_defeat_im", .1, 1) -- SetLowReinforcementsVoiceOver(IMP, ALL, "imp_off_victory_im", .1, 1) SetOutOfBoundsVoiceOver(2, "Allleaving") -- SetOutOfBoundsVoiceOver(1, "Impleaving") SetAmbientMusic(ALL, 1.0, "all_hot_amb_hunt", 0,1) -- SetAmbientMusic(ALL, 0.9, "all_hot_amb_middle", 1,1) -- SetAmbientMusic(ALL, 0.1, "all_hot_amb_end", 2,1) SetAmbientMusic(IMP, 1.0, "imp_hot_amb_hunt", 0,1) -- SetAmbientMusic(IMP, 0.9, "imp_hot_amb_middle", 1,1) -- SetAmbientMusic(IMP, 0.1, "imp_hot_amb_end", 2,1) SetVictoryMusic(ALL, "all_hot_amb_victory") SetDefeatMusic (ALL, "all_hot_amb_defeat") SetVictoryMusic(IMP, "imp_hot_amb_victory") SetDefeatMusic (IMP, "imp_hot_amb_defeat") SetSoundEffect("ScopeDisplayZoomIn", "binocularzoomin") SetSoundEffect("ScopeDisplayZoomOut", "binocularzoomout") --SetSoundEffect("WeaponUnableSelect", "com_weap_inf_weaponchange_null") --SetSoundEffect("WeaponModeUnableSelect", "com_weap_inf_modechange_null") SetSoundEffect("SpawnDisplayUnitChange", "shell_select_unit") SetSoundEffect("SpawnDisplayUnitAccept", "shell_menu_enter") SetSoundEffect("SpawnDisplaySpawnPointChange", "shell_select_change") SetSoundEffect("SpawnDisplaySpawnPointAccept", "shell_menu_enter") SetSoundEffect("SpawnDisplayBack", "shell_menu_exit") -- Camera Stats AddCameraShot(-0.343467, 0.042708, -0.931023, -0.115767, -8.370228, 7.682051, -68.327812); AddCameraShot(0.447841, -0.066177, -0.882082, -0.130344, -64.310715, 17.633507, 74.121971); AddCameraShot(0.921308, -0.158280, -0.350031, -0.060135, -104.089935, 19.899040, 41.774940); AddCameraShot(0.714986, -0.147160, -0.669443, -0.137786, -103.483871, 20.399969, 61.148930); AddCameraShot(-0.004849, 0.000026, -0.999974, -0.005416, -20.710209, 5.094892, -33.587643); end
local ffi = require("ffi") --luacheck: push no max line length ffi.cdef([[ struct libevdev_uinput; enum libevdev_uinput_open_mode { LIBEVDEV_UINPUT_OPEN_MANAGED = -2 }; int libevdev_uinput_create_from_device(const struct libevdev *dev, int uinput_fd, struct libevdev_uinput **uinput_dev); void libevdev_uinput_destroy(struct libevdev_uinput *uinput_dev); int libevdev_uinput_get_fd(const struct libevdev_uinput *uinput_dev); const char* libevdev_uinput_get_syspath(struct libevdev_uinput *uinput_dev); const char* libevdev_uinput_get_devnode(struct libevdev_uinput *uinput_dev); int libevdev_uinput_write_event(const struct libevdev_uinput *uinput_dev, unsigned int type, unsigned int code, int value); ]]) --luacheck: pop ---@diagnostic disable: undefined-field -- local enum = { ---@type number LIBEVDEV_UINPUT_OPEN_MANAGED = ffi.C.LIBEVDEV_UINPUT_OPEN_MANAGED, } ---@diagnostic enable: undefined-field enum.libevdev_uinput_open_mode = { MANAGED = enum.LIBEVDEV_UINPUT_OPEN_MANAGED, } --luacheck: push no max line length ---@class libevdev_uinput ---@field libevdev_uinput_create_from_device fun(dev: ffi.cdata*, uinput_fd: number, uinput_dev: ffi.cdata*): number ---@field libevdev_uinput_destroy fun(uinput_dev: ffi.cdata*): nil ---@field libevdev_uinput_get_fd fun(uinput_dev: ffi.cdata*): number ---@field libevdev_uinput_get_syspath fun(uinput_dev: ffi.cdata*): ffi.cdata* ---@field libevdev_uinput_get_devnode fun(uinput_dev: ffi.cdata*): ffi.cdata* ---@field libevdev_uinput_write_event fun(uinput_dev: ffi.cdata*, type: number, code: number, value: number): number local libevdev_uinput = ffi.load("evdev") --luacheck: pop local ctype = { libevdev_uinput_ptr = ffi.typeof("struct libevdev_uinput *[1]"), } local mod = { ctype = ctype, enum = enum, lib = libevdev_uinput, } return mod
local helpers = require('tests.plenary.ui.helpers') local Date = require('orgmode.objects.date') describe('Todo mappings', function() after_each(function() vim.cmd([[silent! %bw!]]) end) it('should change todo state of a headline forward (org_todo)', function() helpers.load_file_content({ '#TITLE: Test', '', '* TODO Test orgmode', ' DEADLINE: <2021-07-21 Wed 22:02>', }) assert.are.same({ '* TODO Test orgmode', ' DEADLINE: <2021-07-21 Wed 22:02>', }, vim.api.nvim_buf_get_lines(0, 2, 4, false)) vim.fn.cursor(3, 1) -- Changing to DONE and adding closed date vim.cmd([[norm cit]]) assert.are.same({ '* DONE Test orgmode', ' DEADLINE: <2021-07-21 Wed 22:02> CLOSED: [' .. Date.now():to_string() .. ']', }, vim.api.nvim_buf_get_lines(0, 2, 4, false)) -- Removing todo keyword and removing closed date vim.cmd([[norm cit]]) assert.are.same({ '* Test orgmode', ' DEADLINE: <2021-07-21 Wed 22:02>', }, vim.api.nvim_buf_get_lines(0, 2, 4, false)) -- Setting TODO keyword, initial state vim.cmd([[norm cit]]) assert.are.same({ '* TODO Test orgmode', ' DEADLINE: <2021-07-21 Wed 22:02>', }, vim.api.nvim_buf_get_lines(0, 2, 4, false)) end) it('should change todo state of repeatable task and add last repeat property and state change (org_todo)', function() helpers.load_file_content({ '#TITLE: Test', '', '* TODO Test orgmode', ' DEADLINE: <2021-09-07 Tue 12:00 +1w>', '', '* TODO Another task', }) assert.are.same({ '* TODO Test orgmode', ' DEADLINE: <2021-09-07 Tue 12:00 +1w>', '', '* TODO Another task', }, vim.api.nvim_buf_get_lines(0, 2, 6, false)) vim.fn.cursor(3, 1) vim.cmd([[norm cit]]) assert.are.same({ '* TODO Test orgmode', ' DEADLINE: <2021-09-14 Tue 12:00 +1w>', ' :PROPERTIES:', ' :LAST_REPEAT: [' .. Date.now():to_string() .. ']', ' :END:', ' - State "DONE" from "TODO" [' .. Date.now():to_string() .. ']', '', '* TODO Another task', }, vim.api.nvim_buf_get_lines(0, 2, 10, false)) end) it('should change todo state of a headline backward (org_todo_prev)', function() helpers.load_file_content({ '#TITLE: Test', '', '* TODO Test orgmode', ' DEADLINE: <2021-07-21 Wed 22:02>', }) assert.are.same({ '* TODO Test orgmode', ' DEADLINE: <2021-07-21 Wed 22:02>', }, vim.api.nvim_buf_get_lines(0, 2, 4, false)) vim.fn.cursor(3, 1) -- Removing todo keyword vim.cmd([[norm ciT]]) assert.are.same({ '* Test orgmode', ' DEADLINE: <2021-07-21 Wed 22:02>', }, vim.api.nvim_buf_get_lines(0, 2, 4, false)) -- Changing to DONE and adding closed date vim.cmd([[norm ciT]]) assert.are.same({ '* DONE Test orgmode', ' DEADLINE: <2021-07-21 Wed 22:02> CLOSED: [' .. Date.now():to_string() .. ']', }, vim.api.nvim_buf_get_lines(0, 2, 4, false)) -- Setting TODO keyword, initial state vim.cmd([[norm ciT]]) assert.are.same({ '* TODO Test orgmode', ' DEADLINE: <2021-07-21 Wed 22:02>', }, vim.api.nvim_buf_get_lines(0, 2, 4, false)) end) it('Only modifies the actually todo keyword even when a match exists in the text', function() helpers.load_file_content({ '* TODO test TODO', }) vim.fn.cursor(1, 1) vim.cmd('norm ciT') assert.are.same('* test TODO', vim.fn.getline(1)) end) end)
IFTTT_KEY="" -- Add your IFTTT key for Maker Service Method
--[[ © 2018 Thriving Ventures AB do not share, re-distribute or modify without permission of its author ([email protected]). ]] local plugin = plugin local category = {} plugin.changes = { general = {}, group = {} } category.name = "Chat settings" category.material = "serverguard/menuicons/icon_reports.png" category.permissions = "Manage Chat Settings" local function CreatePanelForRank(uniqueRank) local settings = plugin.settings.group[uniqueRank] local checkboxes = {} local panel = vgui.Create("tiger.panel") panel:SetTitle(uniqueRank .. " chat settings") panel:SetSize(450, 275) panel:Center() panel:MakePopup() panel:DockPadding(24, 24, 24, 48) local list = panel:Add("tiger.list") list:Dock(TOP) list:SetTall(145) local confirmButton = panel:Add("tiger.button") confirmButton:SetText("Confirm") confirmButton:SetPos(362, 235) function confirmButton:DoClick() panel:Remove() end for k, v in SortedPairs(settings) do local checkbox = vgui.Create("tiger.checkbox") checkbox:SetText(k) checkbox:SetChecked(v) checkbox:Dock(TOP) function checkbox:OnChange(bChecked) plugin.changes.group[uniqueRank] = plugin.changes.group[uniqueRank] or {} plugin.changes.group[uniqueRank][k] = bChecked plugin.settings.group[uniqueRank][k] = bChecked end checkboxes[k] = checkbox list:AddPanel(checkbox) end end function category:Create(base) base.panel = base:Add("tiger.panel") base.panel:SetTitle("Chat settings") base.panel:DockPadding(24, 24, 24, 48) base.panel:Dock(FILL) base.panel.settingList = base.panel:Add("tiger.list") base.panel.settingList:Dock(TOP) base.panel.settingList:SetTall(122) base.panel.rankList = base.panel:Add("tiger.list") base.panel.rankList:Dock(FILL) base.panel.rankList:DockMargin(0, 8, 0, 0) base.panel.rankList:AddColumn("UNIQUE", 240) base.panel.rankList:AddColumn("NAME", 240) base.panel.apply = base.panel:Add("tiger.button") base.panel.apply:SetText("Apply") base.panel.apply:SizeToContents() function base.panel.apply:DoClick() if ((table.Count(plugin.changes.general) > 0) or (table.Count(plugin.changes.group) > 0)) then serverguard.netstream.Start("sgSetChatSettings", plugin.changes) plugin.changes = { general = {}, group = {} } else serverguard.Notify(nil, SERVERGUARD.NOTIFY.RED, "There are no changes to apply.") end end function base.panel:PerformLayout(width, height) base.panel.apply:SetPos(width - (base.panel.apply:GetWide() + 24), height - (base.panel.apply:GetTall() + 14)) end end function category:Update(base) local ranks = serverguard.ranks:GetTable() base.panel.rankList:Clear() for unique, data in pairs(ranks) do local panel = base.panel.rankList:AddItem(unique, data.name) local label = panel:GetLabel(2) label:SetColor(data.color) label.oldColor = data.color function panel:OnMousePressed() CreatePanelForRank(unique) end end plugin.base = base serverguard.netstream.Start("sgGetChatSettings") end plugin:AddSubCategory("Server settings", category)
function CourseSpawn:__init(course) self.course = course self.position = nil self.angle = nil self.modelIds = {} self.templates = {} self.decals = {} self.racer = nil self.vehicle = nil end function CourseSpawn:SpawnVehicle() -- If there are no vehicles, it means this is an on-foot race. if #self.modelIds == 0 then return end local modelIdIndex = math.random(1 , #self.modelIds) local spawnArgs = {} spawnArgs.model_id = self.modelIds[modelIdIndex] spawnArgs.position = self.position spawnArgs.angle = self.angle spawnArgs.world = self.course.race.world spawnArgs.enabled = true spawnArgs.template = self.templates[modelIdIndex] or "" spawnArgs.decal = self.decals[modelIdIndex] or "" self.vehicle = Vehicle.Create(spawnArgs) self.vehicle:SetDeathRemove(true) self.vehicle:SetUnoccupiedRemove(true) end function CourseSpawn:SpawnRacer() if self.racer == nil or IsValid(self.racer.player) == false then return end local teleportPos = self.position + Vector3(0 , 2 , 0) -- If there is a vehicle, teleport them and put them in the vehicle. if self.vehicle then local angleForward = self.angle local dirToPlayerSpawn = angleForward * Vector3(-1 , 0 , 0) teleportPos = teleportPos + dirToPlayerSpawn * 2 self.racer.assignedVehicleId = self.vehicle:GetId() self.racer.player:EnterVehicle(self.vehicle , VehicleSeat.Driver) -- Otherwise, place them directly on the spawn position. else end self.racer.courseSpawn = self self.racer.player:Teleport(teleportPos , self.angle) self.racer.player:SetWorld(self.course.race.world) end -- For use with sending course checkpoint info to clients. function CourseSpawn:Marshal() local info = {} info.courseEditorId = self.courseEditorId info.position = self.position info.angle = self.angle info.modelIds = self.modelIds return info end function CourseSpawn:MarshalJSON() local spawn = {} spawn.position = {} spawn.position.x = self.position.x spawn.position.y = self.position.y spawn.position.z = self.position.z spawn.angle = {} spawn.angle.x = self.angle.x spawn.angle.y = self.angle.y spawn.angle.z = self.angle.z spawn.angle.w = self.angle.w spawn.modelIds = self.modelIds spawn.templates = self.templates spawn.decals = self.decals return spawn end
--- Module to generate a duotone effect. -- It also supports gradients of more than two colors. local base = [[ <filter id='$id'> <feColorMatrix type="matrix" values=".375 .5 .125 0 0 .375 .5 .125 0 0 .375 .5 .125 0 0 0 0 0 1 0" /> <feComponentTransfer color-interpolation-filter="sRGB"> <feFuncR type="table" tableValues="$red" /> <feFuncG type="table" tableValues="$green" /> <feFuncB type="table" tableValues="$blue" /> </feComponentTransfer> </filter> ]] local function normal(number) return math.min(1, math.max(0, math.floor(number*1000)/1000)) end local function multitone(id, ...) local components = {{}, {}, {}} for i, color in ipairs({...}) do components[1][i] = tostring(normal(color[1])) components[2][i] = tostring(normal(color[2])) components[3][i] = tostring(normal(color[3])) end local options = { red = table.concat(components[1], ' '); green = table.concat(components[2], ' '); blue = table.concat(components[3], ' '); id = id } return (base:gsub("$%w+", function(key) return options[key:sub(2)] or error("Key "..key.." not found in options!") end)) end return multitone
local position = require("engine/component/position") --[[ lamp({ x = love.graphics:getWidth() / 2, y = love.graphics:getHeight() / 2, color = {255, 255, 255}, on_screen = true, }) ]]-- local function lamp(options) local x = options.x or 0 local y = options.y or 0 local color = options.color or {255, 255, 255} local radius = options.radius or 100 local flicker = options.flicker or false local on_screen = options.on_screen or false return { on_screen = on_screen, flicker = flicker, needs_update = true, position = position(x, y), light = { color = { r = color[1], g = color[2], b = color[3], a = color[4] or 1 }, position = position(x, y), radius = radius } } end return lamp
-- curl -sw' %{time_total}s ' -4LXPOST 'http://localhost:7312/token' -H'Origin: http://localhost:7312' -H'Content-Type: application/x-www-form-urlencoded' -H'Authorization: Basic NzY2NDFhZGYtMzRiMC00YzVhLWIzOWQtMjMzNzBhYWFkODdkOjExMTExMQ==' -d'UserName=13028500025' --data-urlencode 'PassWord={"AccountPwd":"96e79218965eb72c92a549dd5a330112","ValidateCode":"111111","ValidateId":"111111"}' -d'grant_type=password' -- wrk -t2 -c8 -d10s -T2s -s ./wrk-post-login.lua 'http://localhost:7312/token' -H'Origin: http://localhost:7312' -H'Content-Type: application/x-www-form-urlencoded' -H'Authorization: Basic NzY2NDFhZGYtMzRiMC00YzVhLWIzOWQtMjMzNzBhYWFkODdkOjExMTExMQ==' wrk-user-login.txt 2 -- wrk -t16 -c64 -d10s -T2s --latency -s ./wrk-post-login.lua 'http://localhost:7312/token' -H'Origin: http://localhost:7312' -H'Content-Type: application/x-www-form-urlencoded' -H'Authorization: Basic NzY2NDFhZGYtMzRiMC00YzVhLWIzOWQtMjMzNzBhYWFkODdkOjExMTExMQ==' wrk-user-login.txt 16 local threadI = 0 local threads = {} -- userPassWord = '{"AccountPwd":"96e79218965eb72c92a549dd5a330112","ValidateCode":"111111","ValidateId":"111111"}' local userPassWordEncoded = "%7B%22AccountPwd%22%3A%2296e79218965eb72c92a549dd5a330112%22%2C%22ValidateCode%22%3A%22111111%22%2C%22ValidateId%22%3A%22111111%22%7D" -- wrk.headers["Authorization"] = "" -- wrk.path = "/token" wrk.method = "POST" function setup(thread) thread:set('threadIdx', threadI) table.insert(threads, thread) threadI = threadI + 1 -- print('Init', 'thread', thread:get('threadIdx')) end function init(args) -- args: <filename of users list> <number of threads, used to split data> local threadN, lineIdx = args[2], 0 -- thread local variables filename, requestN, responseN = args[1], 0, 0 userNum, userIdx, userCnt, userList = 0, 0, 0, {} for line in io.lines(filename) do -- a line for a user, remove special characters line = removeSpecialCharacters(line) -- add user to list if string.len(line) > 3 then if lineIdx % threadN == threadIdx then userList[userIdx], userIdx = line, userIdx + 1 end lineIdx = lineIdx + 1 end end userNum, userIdx, userCnt = userIdx, 0, lineIdx end request = function() requestN = requestN + 1 if userNum == userIdx then userIdx = 0 end userName, userIdx = userList[userIdx], userIdx + 1 bodyData = 'UserName='..userName..'&PassWord='..userPassWordEncoded..'&grant_type=password' -- print('request.body:', userIdx, userName, bodyData) return wrk.format(wrk.method, wrk.path, wrk.headers, bodyData) end response = function(status, headers, body) responseN = responseN + 1 -- print('response.status='..status..', response.body=', body) if status ~= 200 or not string.find(body, "token") then print('-- error status:', status, body) if status == 500 then wrk.thread:stop() end end end done = function(summary, latency, requests) print('Summary/errors:') print(' read:', '', summary.errors.read, '(total socket read errors)') print(' write:', summary.errors.write, '(total socket write errors)') print(' status:', summary.errors.status, '(total HTTP status codes > 399)') print(' connect:', summary.errors.connect, '(total socket connection errors)') print(' timeout:', summary.errors.timeout, '(total request timeouts)') print('Summary/thread:') for index, thread in ipairs(threads) do local msg = "thread: %d" print('', msg:format(thread:get('threadIdx')+1)) msg = "%d/%d, %s" print('', ' read:', msg:format(thread:get('userNum'), thread:get('userCnt'), thread:get('filename'))) msg = "%d requests, %d responses" print('', ' run:', msg:format(thread:get("requestN"), thread:get("responseN"))) end end removeSpecialCharacters = function(s) s = string.gsub(s, "^%s*(.-)%s*$", "%1") s = string.gsub(s, string.char(239), "", 1) return s end encodeChinese = function(s) s = string.gsub(s, '([^%w%.%-])', function(c) return string.format('%%%02X', string.byte(c)) end) s = string.gsub(s, ' ', '+') return s end
--[[ TheNexusAvenger Custom slider input for scaling number values. --]] local NexusPluginComponents = require(script.Parent.Parent.Parent) local PluginInstance = NexusPluginComponents:GetResource("Base.PluginInstance") local PluginColor = NexusPluginComponents:GetResource("Base.PluginColor") local UserInputService = NexusPluginComponents:GetResource("Input.Service.UserInputService") local Slider = PluginInstance:Extend() Slider:SetClassName("Slider") --[[ Formats the number for a text box. --]] local function FormatNumber(Number) local Text = string.format("%.3f", Number) Text = string.match(Text, "(%-?%d-)%.0+$") or string.match(Text, "(%-?[%d%.]-)0+$") or Text return Text end --[[ Creates the Slider. --]] function Slider:__new() self:InitializeSuper("Frame") self.BackgroundTransparency = 1 --Create the frames. local SliderBar = NexusPluginComponents.new("Frame") SliderBar.BorderColor3 = PluginColor.new(Enum.StudioStyleGuideColor.TitlebarText, Enum.StudioStyleGuideModifier.Disabled) SliderBar.BorderSizePixel = 1 SliderBar.Size = UDim2.new(1, 0, 0, 0) SliderBar.Position = UDim2.new(0, 0, 0.5, 0) SliderBar.Parent = self self:DisableChangeReplication("SliderBar") self.SliderBar = SliderBar local SliderButton = NexusPluginComponents.new("TextButton") SliderButton.BackgroundColor3 = Enum.StudioStyleGuideColor.Button SliderButton.BorderColor3 = Enum.StudioStyleGuideColor.Border SliderButton.Size = UDim2.new(0, 8, 1, 0) SliderButton.Text = "" SliderButton.Parent = self self:DisableChangeReplication("SliderButton") self.SliderButton = SliderButton --Store the values. self:DisableChangeReplication("Value") self.Value = 0 self:DisableChangeReplication("MinimumValue") self.MinimumValue = 0 self:DisableChangeReplication("MaximumValue") self.MaximumValue = 1 self:DisableChangeReplication("ValueIncrement") self.ValueIncrement = 0.001 --Add the Disabled property. local DragEvents = {} self:DisableChangeReplication("TextBox") self:DisableChangeReplication("Disabled") self:GetPropertyChangedSignal("Disabled"):Connect(function() SliderButton.Disabled = self.Disabled self:SetAllColorModifiers(self.Disabled and Enum.StudioStyleGuideModifier.Disabled or Enum.StudioStyleGuideModifier.Default) if self.TextBox then self.TextBox.Disabled = self.Disabled end for _, Event in pairs(DragEvents) do Event:Disconnect() end end) self.Disabled = false --Connect the events. self:GetPropertyChangedSignal("AbsoluteSize"):Connect(function() self:UpdatePosition() end) self:GetPropertyChangedSignal("Value"):Connect(function() self:UpdatePosition() end) self:GetPropertyChangedSignal("MinimumValue"):Connect(function() self:UpdatePosition() end) self:GetPropertyChangedSignal("MaximumValue"):Connect(function() self:UpdatePosition() end) self:GetPropertyChangedSignal("ValueIncrement"):Connect(function() self:UpdatePosition() end) --Connect dragging. SliderButton.MouseButton1Down:Connect(function(StartX, StartY) for _, Event in pairs(DragEvents) do Event:Disconnect() end DragEvents = {} if self.Disabled then return end --Get the upper-most parent. local InputParent = self while InputParent do if not InputParent.Parent or not InputParent.Parent:IsA("GuiObject") then break end InputParent = InputParent.Parent end --Connect moving the mouse. local XOffset = SliderButton.AbsolutePosition.X - StartX table.insert(DragEvents, InputParent.InputChanged:Connect(function(Input) if Input.UserInputType ~= Enum.UserInputType.MouseMovement then return end local PositionX = Input.Position.X + XOffset local NewPercent = math.clamp((PositionX - self.AbsolutePosition.X) / math.max(1, self.AbsoluteSize.X - 8), 0, 1) local NewValue = self.MinimumValue + ((self.MaximumValue - self.MinimumValue) * NewPercent) self.Value = self.ValueIncrement * math.floor((NewValue / self.ValueIncrement) + 0.5) end)) --Connect releasing the mouse. table.insert(DragEvents, UserInputService.InputEnded:Connect(function(Input) if Input.UserInputType ~= Enum.UserInputType.MouseButton1 then return end for _, Event in pairs(DragEvents) do Event:Disconnect() end end)) end) end --[[ Updates the slider position. --]] function Slider:UpdatePosition() local SliderPercent = math.clamp((self.Value - self.MinimumValue) / (self.MaximumValue - self.MinimumValue), 0, 1) local SliderWidth = math.max(8, self.AbsoluteSize.X - 8) self.SliderButton.Position = UDim2.new(0, SliderPercent * SliderWidth, 0, 0) end --[[ Connects a TextBox to the slider. --]] function Slider:ConnectTextBox(TextBox) --Set the initial value. TextBox.Text = FormatNumber(self.Value) TextBox.Disabled = self.Disabled self.TextBox = TextBox --Connect the value changing. self:GetPropertyChangedSignal("Value"):Connect(function() TextBox.Text = FormatNumber(self.Value) end) --Connect the text changing. TextBox:GetPropertyChangedSignal("Text"):Connect(function() local NewValue = tonumber(TextBox.Text) if NewValue then self.Value = NewValue elseif not TextBox:IsFocused() then TextBox.Text = FormatNumber(self.Value) end end) TextBox.FocusLost:Connect(function() local NewValue = tonumber(TextBox.Text) if NewValue then self.Value = NewValue else TextBox.Text = FormatNumber(self.Value) end end) end return Slider
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --[[ --]] --- -- read_query() can rewrite packets -- -- You can use read_query() to replace the packet sent by the client and rewrite -- query as you like -- -- @param packet the mysql-packet sent by the client -- -- @return -- * nothing to pass on the packet as is, -- * proxy.PROXY_SEND_QUERY to send the queries from the proxy.queries queue -- * proxy.PROXY_SEND_RESULT to send your own result-set -- function read_query( packet ) if string.byte(packet) == proxy.COM_QUERY then proxy.queries:append(1, packet, { resultset_is_needed = true } ) return proxy.PROXY_SEND_QUERY end end --- -- dumps the warnings of queries -- -- read_query_result() is called when we receive a query result -- from the server -- -- for all queries which pass by we check if the warning-count is > 0 and -- inject a SHOW WARNINGS and dump it to the stdout -- -- @return -- * nothing or proxy.PROXY_SEND_RESULT to pass the result-set to the client -- * proxy.PROXY_IGNORE_RESULT to drop the result-set -- function read_query_result(inj) if (inj.id == 1) then local res = assert(inj.resultset) if res.warning_count > 0 then print("Query had warnings: " .. inj.query:sub(2)) proxy.queries:append(2, string.char(proxy.COM_QUERY) .. "SHOW WARNINGS", { resultset_is_needed = true } ) end elseif (inj.id == 2) then for row in inj.resultset.rows do print(string.format("warning: [%d] %s", row[2], row[1])) end return proxy.PROXY_IGNORE_RESULT end end
local K, C = unpack(select(2, ...)) -- local _G = _G -- K.Skinning["Blizzard_BattlefieldMap"] = function() -- local BattlefieldMapFrame = _G.BattlefieldMapFrame -- local BorderFrame = BattlefieldMapFrame.BorderFrame -- F.StripTextures(BorderFrame) -- F.SetBD(BattlefieldMapFrame, -1, 1, -1, 2) -- F.ReskinClose(BorderFrame.CloseButton) -- F.StripTextures(OpacityFrame) -- F.SetBD(OpacityFrame) -- F.ReskinSlider(OpacityFrameSlider, true) -- end
dx = 2 / 50 simulation = { mesh = { index_extents = {51, 51}, domain_bounds = {2, 2} }, domain_boundaries = { xmin = "dirichlet", xmax = "dirichlet", ymin = "dirichlet", ymax = "dirichlet" }, shapes = { { type = "sphere", center = {16 / 17, 25 / 22}, radius = math.sqrt(3) / 10, boundary_condition = "floating" } }, scheme = { order = 2, type = "E2" }, system = { type = "heat", diffusivity = 1 / 30 }, integrator = { type = "rk4" }, step_controller = { max_time = 0.3, cfl = { parabolic = 0.5 } }, manufactured_solution = { type = "gaussian", --[[ { center = {0.4, 0.5}, variance = {0.5, 0.2}, amplitude = 2, frequency = 0.5 }, { center = {0.2, 2}, variance = {1 / 3, 0.8}, amplitude = 0.5, frequency = 1 }, { center = {1.5, 1.6}, variance = {0.3, 0.8}, amplitude = -1.2, frequency = 0.8 }, { center = {1.8, 0.3}, variance = {2 / 3, 0.9}, amplitude = 3, frequency = 0.2 } ]] { center = {1, 1}, variance = {1, 1}, amplitude = 2, frequency = 0.5 } }, io = { write_every_time = 0.01 } }
-- Account manager accountManager = true namelockManager = true newPlayerChooseVoc = true newPlayerSpawnPosX = 160 newPlayerSpawnPosY = 54 newPlayerSpawnPosZ = 7 newPlayerTownId = 1 newPlayerLevel = 8 newPlayerMagicLevel = 0 generateAccountNumber = false generateAccountSalt = false -- Unjustified kills -- NOTE: * Banishment and *BlackSkull variables are >summed up<. -- (dailyFragsToRedSkull + dailyFragsToBanishment) with their * RedSkull equivalents. -- Auto banishing works only if useBlackSkull set to negative. -- AdvancedFragList is not advised if you use huge frags requirements. useFragHandler = true redSkullLength = 30 * 24 * 60 * 60 blackSkullLength = 45 * 24 * 60 * 60 dailyFragsToRedSkull = 3 weeklyFragsToRedSkull = 5 monthlyFragsToRedSkull = 10 dailyFragsToBlackSkull = dailyFragsToRedSkull weeklyFragsToBlackSkull = weeklyFragsToRedSkull monthlyFragsToBlackSkull = monthlyFragsToRedSkull dailyFragsToBanishment = dailyFragsToRedSkull weeklyFragsToBanishment = weeklyFragsToRedSkull monthlyFragsToBanishment = monthlyFragsToRedSkull blackSkulledDeathHealth = 40 blackSkulledDeathMana = 0 useBlackSkull = true advancedFragList = false -- Banishments -- violationNameReportActionType 1 = just a report, 2 = name lock, 3 = player banishment -- killsBanLength works only if useBlackSkull option is disabled. notationsToBan = 3 warningsToFinalBan = 4 warningsToDeletion = 5 banLength = 7 * 24 * 60 * 60 killsBanLength = 7 * 24 * 60 * 60 finalBanLength = 30 * 24 * 60 * 60 ipBanishmentLength = 1 * 24 * 60 * 60 broadcastBanishments = true maxViolationCommentSize = 200 violationNameReportActionType = 2 autoBanishUnknownBytes = false -- Battle -- NOTE: showHealingDamageForMonsters inheritates from showHealingDamage. -- loginProtectionPeriod is the famous Tibia anti-magebomb system. -- deathLostPercent set to nil enables manual mode. worldType = "open" protectionLevel = 50 pvpTileIgnoreLevelAndVocationProtection = true pzLocked = 60 * 1000 huntingDuration = 60 * 1000 criticalHitChance = 7 criticalHitMultiplier = 1 displayCriticalHitNotify = false removeWeaponAmmunition = true removeWeaponCharges = true removeRuneCharges = true whiteSkullTime = 15 * 60 * 1000 noDamageToSameLookfeet = false showHealingDamage = false showHealingDamageForMonsters = false fieldOwnershipDuration = 5 * 1000 stopAttackingAtExit = false loginProtectionPeriod = 10 * 1000 deathLostPercent = 10 stairhopDelay = 2 * 1000 pushCreatureDelay = 2 * 1000 deathContainerId = 1987 gainExperienceColor = 215 addManaSpentInPvPZone = true squareColor = 0 allowFightback = true fistBaseAttack = 7 -- Connection config worldId = 0 ip = "127.0.0.1" bindOnlyGlobalAddress = false loginPort = 7171 gamePort = 7172 loginTries = 10 retryTimeout = 5 * 1000 loginTimeout = 60 * 1000 maxPlayers = 1000 motd = "Welcome to Original Yurots Server!" displayOnOrOffAtCharlist = false onePlayerOnlinePerAccount = true allowClones = false serverName = "Yurots" loginMessage = "Welcome to Original Yurots Server!" statusTimeout = 5 * 60 * 1000 replaceKickOnLogin = true forceSlowConnectionsToDisconnect = false loginOnlyWithLoginServer = false premiumPlayerSkipWaitList = false -- RSA -- NOTE: These should not be changed unless you know what your doing! -- Prime1 - known as p; Prime2 - known as q; Public - known as e; -- Modulus - known as n; Private - known as d. rsaPrime1 = "14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113" rsaPrime2 = "7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101" rsaPublic = "65537" rsaModulus = "109120132967399429278860960508995541528237502902798129123468757937266291492576446330739696001110603907230888610072655818825358503429057592827629436413108566029093628212635953836686562675849720620786279431090218017681061521755056710823876476444260558147179707119674283982419152118103759076030616683978566631413" rsaPrivate = "46730330223584118622160180015036832148732986808519344675210555262940258739805766860224610646919605860206328024326703361630109888417839241959507572247284807035235569619173792292786907845791904955103601652822519121908367187885509270025388641700821735345222087940578381210879116823013776808975766851829020659073" -- Database -- NOTE: sqlFile is used only by SQLite database, and sqlKeepAlive by MySQL database. -- To disable sqlKeepAlive such as mysqlReadTimeout use 0 value. -- encryptionType can be plain, md5, sha1, sha256, sha512 or vahash. sqlType = "mysql" sqlHost = "localhost" sqlPort = 3306 sqlUser = "root" sqlPass = "" sqlDatabase = "original-yurots-project" sqlFile = "" sqlKeepAlive = 0 mysqlReadTimeout = 10 mysqlWriteTimeout = 10 encryptionType = "sha1" -- Deathlist deathListEnabled = true deathListRequiredTime = 1 * 60 * 1000 deathAssistCount = 19 maxDeathRecords = 5 -- Guilds ingameGuildManagement = true levelToFormGuild = 100 premiumDaysToFormGuild = 0 guildNameMinLength = 4 guildNameMaxLength = 20 -- Highscores highscoreDisplayPlayers = 15 updateHighscoresAfterMinutes = 60 -- Houses buyableAndSellableHouses = true houseNeedPremium = true bedsRequirePremium = true levelToBuyHouse = 100 housesPerAccount = 0 houseRentAsPrice = false housePriceAsRent = false housePriceEachSquare = 10000 houseRentPeriod = "never" houseCleanOld = 0 guildHalls = false -- Item usage timeBetweenActions = 200 timeBetweenExActions = 1000 hotkeyAimbotEnabled = true -- Map -- NOTE: storeTrash costs more memory, but will perform alot faster cleaning. mapName = "original-yurots-project-map.otbm" mapAuthor = "Marcos Couto" randomizeTiles = true storeTrash = true cleanProtectedZones = true mailboxDisabledTowns = "" -- Process -- NOTE: defaultPriority works only on Windows and niceLevel on *nix. -- niceLevel works only on *nix systems. -- coresUsed are seperated by comma cores ids used by server process, -- default is -1, so it stays untouched (automaticaly assigned by OS). defaultPriority = "high" niceLevel = 5 coresUsed = "-1" -- Startup startupDatabaseOptimization = true updatePremiumStateAtStartup = true confirmOutdatedVersion = false -- Spells formulaLevel = 5.0 formulaMagic = 1.0 bufferMutedOnSpellFailure = false spellNameInsteadOfWords = false emoteSpells = false unifiedSpells = true -- Outfits allowChangeOutfit = true allowChangeColors = true allowChangeAddons = true disableOutfitsForPrivilegedPlayers = false addonsOnlyPremium = true -- Miscellaneous -- NOTE: promptExceptionTracerErrorBox works only with precompiled support feature, -- called "exception tracer" (__EXCEPTION_TRACER__ flag). dataDirectory = "data/" logsDirectory = "data/logs/" bankSystem = true displaySkillLevelOnAdvance = false promptExceptionTracerErrorBox = true maximumDoorLevel = 500 maxMessageBuffer = 4 tradeLimit = 100 -- VIP list separateVipListPerCharacter = false vipListDefaultLimit = 20 vipListDefaultPremiumLimit = 100 -- Saving-related -- useHouseDataStorage usage may be found at README. saveGlobalStorage = true useHouseDataStorage = false storePlayerDirection = false -- Loot -- monsterLootMessage 0 to disable, 1 - only party, 2 - only player, 3 - party or player (like Tibia's). checkCorpseOwner = true monsterLootMessage = 3 monsterLootMessageType = 25 -- Ghost mode ghostModeInvisibleEffect = false ghostModeSpellEffects = true -- Limits idleWarningTime = 14 * 60 * 1000 idleKickTime = 15 * 60 * 1000 reportsExpirationAfterReads = 1 playerQueryDeepness = 2 tileLimit = 0 protectionTileLimit = 0 houseTileLimit = 0 -- Premium-related freePremium = false premiumForPromotion = true -- Blessings -- NOTE: blessingReduction* regards items/containers loss. -- eachBlessReduction is how much each bless reduces the experience/magic/skills loss. blessings = true blessingOnlyPremium = true blessingReductionBase = 30 blessingReductionDecrement = 5 eachBlessReduction = 8 -- Rates -- NOTE: experienceStages configuration is located in data/XML/stages.xml. -- rateExperienceFromPlayers 0 to disable. experienceStages = false rateExperience = 15000.0 rateExperienceFromPlayers = 0 rateSkill = 3000.0 rateMagic = 300.0 rateLoot = 5.0 rateSpawn = 1 -- Monster rates rateMonsterHealth = 1.0 rateMonsterMana = 1.0 rateMonsterAttack = 1.0 rateMonsterDefense = 1.0 -- Experience from players -- NOTE: min~Threshold* set to 0 will disable the minimum threshold: -- player will gain experience from every lower leveled player. -- max~Threshold* set to 0 will disable the maximum threshold: -- player will gain experience from every higher leveled player. minLevelThresholdForKilledPlayer = 0.9 maxLevelThresholdForKilledPlayer = 1.1 -- Stamina -- NOTE: Stamina is stored in miliseconds, so seconds are multiplied by 1000. -- rateStaminaHits multiplies every hit done a creature, which are later multiplied by player attack speed. -- rateStaminaGain is multiplying every second of logged out time, eg: -- 60 * 1000 / 3 = 20 seconds, what gives 1 stamina minute for 3 being logged off. -- rateStaminaThresholdGain is dividing in case the normal gain (that is multiplied by rateStaminaGain, btw.) passed above threshold, eg: -- 60 * 1000 / 3 = 20 / 4 = 5 seconds (3 * 4 = 12 minutes for 1 stamina minute). -- staminaRatingLimit* is in minutes. rateStaminaLoss = 1 rateStaminaGain = 3 rateStaminaThresholdGain = 12 staminaRatingLimitTop = 40 * 60 staminaRatingLimitBottom = 14 * 60 staminaLootLimit = 14 * 60 rateStaminaAboveNormal = 1.5 rateStaminaUnderNormal = 0.5 staminaThresholdOnlyPremium = true -- Party -- NOTE: experienceShareLevelDifference is float number. -- experienceShareLevelDifference is highestLevel * value experienceShareRadiusX = 30 experienceShareRadiusY = 30 experienceShareRadiusZ = 1 experienceShareLevelDifference = 2 / 3 extraPartyExperienceLimit = 20 extraPartyExperiencePercent = 5 experienceShareActivity = 2 * 60 * 1000 -- Global save -- NOTE: globalSaveHour means like 03:00, not that it will save every 3 hours, -- if you want such a system please check out data/globalevents/globalevents.xml. globalSaveEnabled = false globalSaveHour = 8 globalSaveMinute = 0 shutdownAtGlobalSave = true cleanMapAtGlobalSave = false -- Spawns deSpawnRange = 2 deSpawnRadius = 50 -- Summons maxPlayerSummons = 2 teleportAllSummons = false teleportPlayerSummons = false -- Status statusPort = 7171 ownerName = "Marcos Couto" ownerEmail = "" url = "" location = "Brazil" displayGamemastersWithOnlineCommand = false -- Logs -- NOTE: This kind of logging does not work in GUI version. -- For such, please compile the software with __GUI_LOGS__ flag. displayPlayersLogging = true prefixChannelLogs = "" runFile = "" outputLog = "" truncateLogOnStartup = false -- Manager -- NOTE: managerPassword left blank disables manager. managerPort = 7171 managerLogs = true managerPassword = "" managerLocalhostOnly = true managerConnectionsLimit = 1 -- Admin -- NOTE: adminPassword left blank disables manager. -- Set to anything if you set adminRequireLogin to false. -- adminEncryption available options: rsa1024xtea; -- Remember to set correct data! adminPort = 7171 adminLogs = true adminPassword = "" adminLocalhostOnly = true adminConnectionsLimit = 1 adminRequireLogin = true adminEncryption = "" adminEncryptionData = ""
local M = {} M.config = function() vim.cmd[[ let test#python#pytest#executable = 'python3 -m pytest' ]] vim.cmd [[ function! ToggleTermStrategy(cmd) abort call luaeval("require('toggleterm').exec(_A[1])", [a:cmd]) endfunction let g:test#custom_strategies = {'toggleterm': function('ToggleTermStrategy')} ]] vim.g["test#strategy"] = "toggleterm" end return M
----------------------------------- -- Area: Ghelsba Outpost -- Mob: Warchief Vatgit -- Involved in Mission 2-3 ----------------------------------- require("scripts/globals/settings") require("scripts/globals/missions") require("scripts/globals/titles") ----------------------------------- function onMobDeath(mob, player, isKiller) if (player:getCurrentMission(player:getNation()) == 6) then if (player:getCharVar("MissionStatus") == 4) then player:setCharVar("MissionStatus", 5) end end player:addTitle(tpz.title.WARCHIEF_WRECKER) end
--[[ s:UI Utility Functions Martin Karer / Sezz, 2014 http://www.sezz.at --]] require "GameLib"; ----------------------------------------------------------------------------- local S = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:GetAddon("SezzUI"); -- Lua API local mod, format, floor, format, strlen, strsub, tonumber, ipairs, pairs = math.mod, string.format, math.floor, string.format, string.len, string.sub, tonumber, ipairs, pairs; -- WildStar API local GameLib = GameLib; ----------------------------------------------------------------------------- -- Table Utilities ----------------------------------------------------------------------------- function S:Clone(t) if (type(t) ~= "table") then return t; end local mt = getmetatable(t); local res = {}; for k, v in pairs(t) do if (type(v) == "table") then v = self:Clone(v); end res[k] = v; end setmetatable(res, mt); return res; end function S:Combine(t1, t2) if (not t1 or type(t1) ~= "table") then t1 = {}; end if (not t2 or type(t2) ~= "table") then t2 = {}; end for k, v in pairs(t2) do t1[k] = v; end return t1; end function S:InitializeTable(t) if (not t or type(t) ~= "table") then t = {}; end return t; end -- Table Comparing -- Credits: http://snippets.luacode.org/snippets/Deep_Comparison_of_Two_Values_3 function S:Compare(t1, t2, ignore_mt) local ty1 = type(t1); local ty2 = type(t2); if (ty1 ~= ty2) then return false; end -- non-table types can be directly compared if (ty1 ~= 'table' and ty2 ~= 'table') then return (t1 == t2); end -- as well as tables which have the metamethod __eq local mt = getmetatable(t1); if (not ignore_mt and mt and mt.__eq) then return (t1 == t2); end for k1, v1 in pairs(t1) do local v2 = t2[k1]; if (v2 == nil or not self:Compare(v1, v2)) then return false; end end for k2, v2 in pairs(t2) do local v1 = t1[k2]; if (v1 == nil or not self:Compare(v1,v2)) then return false; end end return true; end ----------------------------------------------------------------------------- -- AML Tags ----------------------------------------------------------------------------- function S:WrapAML(strTag, strText, strColor, strAlign) return format('<%s Font="CRB_Pixel_O" Align="%s" TextColor="%s">%s</%s>', strTag, strAlign or "Left", strColor or "ffffffff", strText, strTag); end ----------------------------------------------------------------------------- -- Money ----------------------------------------------------------------------------- function S:GetMoneySplitted(nAmount) return floor(nAmount / 1000000), floor(mod(nAmount / 10000, 100)), floor(mod(nAmount / 100, 100)), mod(nAmount, 100); end local strColorCopper = "ffeda55f"; local strColorSilver = "ffc7c7cf"; local strColorGold = "ffffd700"; local strColorPlatin = "ffffffff"; function S:GetMoneyAML(nAmount, strFont) local nPlatin, nGold, nSilver, nCopper = self:GetMoneySplitted(nAmount); local strAML = ""; local strNumberFormat = "%d"; -- Platin if (nPlatin > 0) then strAML = format(strNumberFormat .. '<T TextColor="%s">p</T>', nPlatin, strColorPlatin); end -- Gold if (nPlatin > 0 or nGold > 0) then if (strlen(strAML) > 0) then strAML = strAML.." "; strNumberFormat = "%02d"; end strAML = strAML..format(strNumberFormat .. '<T TextColor="%s">g</T>', nGold, strColorGold); end -- Silver if (nPlatin > 0 or nGold > 0 or nSilver > 0) then if (strlen(strAML) > 0) then strAML = strAML.." "; strNumberFormat = "%02d"; end strAML = strAML..format(strNumberFormat .. '<T TextColor="%s">s</T>', nSilver, strColorSilver); end -- Copper if (strlen(strAML) > 0) then strAML = strAML.." "; strNumberFormat = "%02d"; end strAML = strAML..format(strNumberFormat .. '<T TextColor="%s">c</T>', nCopper, strColorCopper); return '<P Font="' .. (strFont or "CRB_Pixel") .. '" Align="Right" TextColor="ffffffff">'..strAML..'</P>'; end ----------------------------------------------------------------------------- -- Chat Output -- Only supports Carbine's ChatLog ----------------------------------------------------------------------------- local kcrAddonChannel = ApolloColor.new("magenta"); function S:ChatOutput(arMessageSegments) -- arMessageSegments is an array of: -- strType = Text or Image -- strContent = The actual text or the image sprite -- nImageWidth (Optional, default is 18) -- nImageHeight (Optional, default is 18) -- crSemgment = ApolloColor Name (like "white") local tChatLog = Apollo.GetAddon("ChatLog"); local strFontOption = tChatLog.strFontOption; local bShowTimestamp = tChatLog.bShowTimestamp; local xml = XmlDoc.new() -- Timestamp + Channel local tmNow = GameLib.GetLocalTime(); local strTime = (bShowTimestamp and format("%d:%02d ", tmNow.nHour, tmNow.nMinute or "")); xml:AddLine(strTime .. "[s:UI] ", kcrAddonChannel, strFontOption, "Left"); -- Content for i, tSegment in ipairs(arMessageSegments) do if (tSegment.strType ~= "Image") then local crSegment = ApolloColor.new(tSegment.crSegment or "white"); local strContent = tSegment.strContent..(tSegment.bNoSpace and "" or " "); xml:AppendText(strContent, crSegment, strFontOption); else xml:AppendImage(tSegment.strContent, tSegment.nImageWidth or 18, tSegment.nImageHeight or 18); end end -- Queue Message tChatLog.bQueuedMessages = true; tChatLog.tChatWindows[1]:GetData().tMessageQueue:Push({ xml = xml }); end function S:Print(strMessage) self:ChatOutput({{ strType = "Text", strContent = strMessage }}); end ----------------------------------------------------------------------------- -- Misc ----------------------------------------------------------------------------- function S:Round(nValue) return floor(nValue + 0.5); end ----------------------------------------------------------------------------- -- Color Conversion ----------------------------------------------------------------------------- function S:ConvertHexColorToArray(strColorHex) local nA = tonumber("0x"..strsub(strColorHex, 1, 2)); local nR = tonumber("0x"..strsub(strColorHex, 3, 4)); local nG = tonumber("0x"..strsub(strColorHex, 5, 6)); local nB = tonumber("0x"..strsub(strColorHex, 7, 9)); return { a = nA / 255, r = nR / 255, g = nG / 255, b = nB / 255 }; end
function utf8.literalize(s) check("s") return utf8.gsub(s, "[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%0") end local _rep = string.rep function string.rep(s, n, sep) check("s,n,?s") return n < 1 and "" or n < 2 and s or _rep(s..(sep or ""), n - 1)..s end function utf8.split(s, sep, limit, plain) check("s,?s,?n,?b") if limit and limit < 1 then return {} end if s == "" then return {""} end sep = sep or "" sep = plain and utf8.literalize(sep) or sep local t = {} local i = 1 for v in utf8.gmatch(s, sep == "" and "." or "([^"..sep.."]+)") do t[i] = v if limit and i == limit then break end i = i + 1 end return t end function utf8.trim(s) check("s") s = utf8.gsub(s, "^%s*(.-)%s*$", "%1") return s end function utf8.upperf(s) check("s") s = utf8.gsub(s, "^%l", utf8.upper) return s end local _find = utf8.find function utf8.find(s, pattern, init, plain, soft) check("s[2],?n,?b[2]") if soft then s = utf8.lower(utf8.trim(s)) pattern = utf8.lower(utf8.trim(pattern)) end return _find(s, pattern, init, plain) end function utf8.insert(str1, str2, pos) check("s[2],?n") pos = pos or (#str1 + 1) return utf8.sub(str1, 0, pos - 1)..str2..utf8.sub(str1, pos) end -- https://gist.github.com/Badgerati/3261142 function utf8.levenshtein(str1, str2) check("s[2]") if str1 == str2 then return 0 end local len1 = utf8.len(str1) local len2 = utf8.len(str2) if len1 == 0 then return len2 end if len2 == 0 then return len1 end local matrix = {} for i = 0, len1 do matrix[i] = {} matrix[i][0] = i end for j = 0, len2 do matrix[0][j] = j end local cost = 0 for i = 1, len1 do for j = 1, len2 do if str1:byte(i) == str2:byte(j) then cost = 0 else cost = 1 end matrix[i][j] = math.min(matrix[i-1][j] + 1, matrix[i][j-1] + 1, matrix[i-1][j-1] + cost) end end return matrix[len1][len2] end function utf8.totype(s) check("s") local value = tonil(s) if value ~= false then return value end value = toboolean(s) if value ~= nil then return value end value = tonumber(s) if value then return value end return s end local charset = utf8.split("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") function utf8.random(length) check("n") length = math.floor(length) if length < 1 then return "" end local str = "" for i = 1, length do str = str..charset[math.random(#charset)] end return str end
--imports-- local api = require"novus.api" local util = require"novus.snowflakes.helpers" local view = require"novus.cache.view" local snowflake = require"novus.snowflakes" local base_channel = require"novus.snowflakes.channel" local channeltype = require"novus.enums".channeltype local modifiable = require"novus.snowflakes.mixins.modifiable" local guildchannel = require"novus.snowflakes.mixins.guildchannel" local cqueues = require"cqueues" local null = require"cjson".null local snowflakes = snowflake.snowflakes local running = cqueues.running --start-module-- local _ENV = base_channel"guildvoicechannel" local base = newer_from _ENV = guildchannel(modifiable(_ENV, api.method)) schema{ "bitrate" ,"user_limit" } function new_from(state, payload) local object = base(_ENV, state, payload) object[5] = util.uint(payload.guild_id) object[6] = payload.name object[7] = payload.position object[8] = util.uint(payload.parent_id) object[11] = processor.overwrites(payload.permission_overwrites) object[12] = payload.bitrate object[13] = payload.user_limit return object end function methods.set_bitrate(channel, bitrate) return modify(channel, {bitrate = bitrate or null}) end function methods.set_user_limit(channel, limit) return modify(channel, {user_limit = limit or null}) end local function select_members(_, vstate, chid) if vstate.channel_id == chid then return snowflakes.member.get(vstate.guild_id, vstate.user_id) end end function properties.connected_members(channel) return view.new(channel.guild.voice_states, select_members, channel[1]) end --end-module-- return _ENV
--------------------------------------------------------------------------------------------------- modifier_oaa_requiem_allowed = modifier_oaa_requiem_allowed or class({}) function modifier_oaa_requiem_allowed:IsHidden() return true end function modifier_oaa_requiem_allowed:IsDebuff() return false end function modifier_oaa_requiem_allowed:IsPurgable() return false end function modifier_oaa_requiem_allowed:RemoveOnDeath() return true end function modifier_oaa_requiem_allowed:OnCreated(keys) if not IsServer() then return end self.immune_time = keys.immune_time end function modifier_oaa_requiem_allowed:OnDestroy() if not IsServer() then return end local parent = self:GetParent() if not parent or parent:IsNull() or not self.immune_time then return end parent:AddNewModifier(parent, nil, "modifier_oaa_requiem_not_allowed", {duration = self.immune_time}) end --------------------------------------------------------------------------------------------------- modifier_oaa_requiem_not_allowed = modifier_oaa_requiem_not_allowed or class({}) function modifier_oaa_requiem_not_allowed:IsHidden() return true end function modifier_oaa_requiem_not_allowed:IsDebuff() return false end function modifier_oaa_requiem_not_allowed:IsPurgable() return false end function modifier_oaa_requiem_not_allowed:RemoveOnDeath() return true end function modifier_oaa_requiem_not_allowed:OnCreated() if not IsServer() then return end local parent = self:GetParent() parent:RemoveModifierByName("modifier_nevermore_requiem_slow") parent:RemoveModifierByName("modifier_nevermore_requiem_fear") end
-- Created by @project-author@ character is Bearesquishy - dalaran please credit whenever. -- Source on GitHub: https://n6rej.github.io local addonName, addonTable, addon = ... -- Get reference to AdiBags addon local AdiBags = LibStub("AceAddon-3.0"):GetAddon("AdiBags") local db = addonTable.db local MatchIDs local tooltip local Result = {} -- Debug mode switch local debugMode = false local function tooltipInit() local tip, leftside = CreateFrame("GameTooltip"), {} for i = 1, 6 do local left, right = tip:CreateFontString(), tip:CreateFontString() left:SetFontObject(GameFontNormal) right:SetFontObject(GameFontNormal) tip:AddFontStrings(left, right) leftside[i] = left end tip.leftside = leftside return tip end -- Check for existing filter local function CheckFilter(newFilter) local filterExists = false for key, value in AdiBags:IterateFilters() do if value.filterName == newFilter then filterExists = true return filterExists end end return filterExists end -- Create Filters local function CreateFilter(name, uiName, uiDesc, title, items) local filter = AdiBags:RegisterFilter(uiName, 98, "ABEvent-1.0") -- Register Filter with adibags filter.uiName = uiName filter.uiDesc = uiDesc .. " Version: " .. "@project-version@" filter.items = items function filter:OnInitialize() -- Assign item table to filter self.items = filter.items end function filter:Update() self:SendMessage("AdiBags_FiltersChanged") end function filter:OnEnable() AdiBags:UpdateFilters() end function filter:OnDisable() AdiBags:UpdateFilters() end function filter:Filter(slotData) if self.items[tonumber(slotData.itemId)] then return title end tooltip = tooltip or tooltipInit() tooltip:SetOwner(UIParent, "ANCHOR_NONE") tooltip:ClearLines() if slotData.bag == BANK_CONTAINER then tooltip:SetInventoryItem("player", BankButtonIDToInvSlotID(slotData.slot, nil)) else tooltip:SetBagItem(slotData.bag, slotData.slot) end tooltip:Hide() end end -- Run filters local function AllFilters(db) for name, group in pairs(db.Filters) do -- Does filter already exist? local filterExists = CheckFilter(group.uiName) if not filterExists == nil or filterExists == false then -- name = Name of table -- group.uiName = Name to use in filter listing -- group.uiDesc = Description to show in filter listing -- group.items = table of items to sort CreateFilter(name, group.uiName, group.uiDesc, group.title, group.items) end end end -- Start here AllFilters(db)
local utils = {} function utils.istensor(x) if torch.typename(x) and torch.typename(x):find('Tensor') then return true end return false end function utils.istorchclass(x) return type(x) == 'table' and torch.typename(x) end function utils.istable(x) return type(x) == 'table' and not torch.typename(x) end return utils
require('Array/Array') require('Object/Object') require('Testing/Testing') require('Function') local expect = Testing.expect function testCurry() local function test(a, b, c) return {a, b, c} end local curriedTest = Function.curry(test, 3) local result = curriedTest(1)(2)(3) return expect(result).toEqual({1, 2, 3}) end print(testCurry())
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file uninstall.lua -- -- imports import("core.base.task") import("core.base.option") import("impl.package") import("impl.repository") import("impl.environment") import("impl.utils.get_requires") -- uninstall the given packages function main(requires_raw) -- enter environment environment.enter() -- pull all repositories first if not exists if not repository.pulled() then task.run("repo", {update = true}) end -- get requires and extra config local requires_extra = nil local requires, requires_extra = get_requires(requires_raw) if not requires or #requires == 0 then return end -- uninstall packages local packages = package.uninstall_packages(requires, {requires_extra = requires_extra}) for _, instance in ipairs(packages) do print("uninstall: %s%s ok!", instance:name(), instance:version_str() and ("-" .. instance:version_str()) or "") end if not packages or #packages == 0 then print("local packages not found!") end -- leave environment environment.leave() end
UMF_REQUIRE "/" ---@class Trigger: Entity local trigger_meta = global_metatable( "trigger", "entity" ) --- Tests if the parameter is a trigger entity. --- ---@param e any ---@return boolean function IsTrigger( e ) return IsEntity( e ) and e.type == "trigger" end --- Wraps the given handle with the trigger class. --- ---@param handle number ---@return Trigger? function Trigger( handle ) if handle > 0 then return setmetatable( { handle = handle, type = "trigger" }, trigger_meta ) end end --- Finds a trigger with the specified tag. --- `global` determines whether to only look in the script's hierarchy or the entire scene. --- ---@param tag string ---@param global boolean ---@return Trigger? function FindTriggerByTag( tag, global ) return Trigger( FindTrigger( tag, global ) ) end --- Finds all triggers with the specified tag. --- `global` determines whether to only look in the script's hierarchy or the entire scene. --- ---@param tag string ---@param global boolean ---@return Trigger[] function FindTriggersByTag( tag, global ) local t = FindTriggers( tag, global ) for i = 1, #t do t[i] = Trigger( t[i] ) end return t end ---@return string function trigger_meta:__tostring() return string.format( "Trigger[%d]", self.handle ) end --- Sets the transform of the trigger. --- ---@param transform Transformation function trigger_meta:SetTransform( transform ) assert( self:IsValid() ) return SetTriggerTransform( self.handle, transform ) end --- Gets the transform of the trigger. --- ---@return Transformation function trigger_meta:GetTransform() assert( self:IsValid() ) return MakeTransformation( GetTriggerTransform( self.handle ) ) end --- Gets the bounds of the trigger. --- ---@return Vector min ---@return Vector max function trigger_meta:GetWorldBounds() assert( self:IsValid() ) local min, max = GetTriggerBounds( self.handle ) return MakeVector( min ), MakeVector( max ) end --- Gets if the specified body is in the trigger. --- ---@param handle Body | number ---@return boolean function trigger_meta:IsBodyInTrigger( handle ) assert( self:IsValid() ) return IsBodyInTrigger( self.handle, GetEntityHandle( handle ) ) end --- Gets if the specified vehicle is in the trigger. --- ---@param handle Vehicle | number ---@return boolean function trigger_meta:IsVehicleInTrigger( handle ) assert( self:IsValid() ) return IsVehicleInTrigger( self.handle, GetEntityHandle( handle ) ) end --- Gets if the specified shape is in the trigger. --- ---@param handle Shape | number ---@return boolean function trigger_meta:IsShapeInTrigger( handle ) assert( self:IsValid() ) return IsShapeInTrigger( self.handle, GetEntityHandle( handle ) ) end --- Gets if the specified point is in the trigger. --- ---@param point Vector ---@return boolean function trigger_meta:IsPointInTrigger( point ) assert( self:IsValid() ) return IsPointInTrigger( self.handle, point ) end --- Gets if the trigger is empty. --- ---@param demolision boolean ---@return boolean empty ---@return Vector? highpoint function trigger_meta:IsEmpty( demolision ) assert( self:IsValid() ) local empty, highpoint = IsTriggerEmpty( self.handle, demolision ) return empty, highpoint and MakeVector( highpoint ) end
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file find_package.lua -- -- imports import("lib.detect.find_path") import("lib.detect.find_library") import("lib.detect.pkg_config") -- find package from the system directories -- -- @param name the package name -- @param opt the options, .e.g {verbose = true, version = "1.12.x") -- function main(name, opt) -- only support the current host platform and architecture if opt.plat ~= os.host() or opt.arch ~= os.arch() then return end -- add default search includedirs on pc host local includedirs = table.wrap(opt.includedirs) if #includedirs == 0 then if opt.plat == "linux" or opt.plat == "macosx" then table.insert(includedirs, "/usr/local/include") table.insert(includedirs, "/usr/include") table.insert(includedirs, "/opt/local/include") table.insert(includedirs, "/opt/include") end end -- add default search linkdirs on pc host local linkdirs = table.wrap(opt.linkdirs) if #linkdirs == 0 then if opt.plat == "linux" or opt.plat == "macosx" then table.insert(linkdirs, "/usr/local/lib") table.insert(linkdirs, "/usr/lib") table.insert(linkdirs, "/opt/local/lib") table.insert(linkdirs, "/opt/lib") if opt.plat == "linux" and opt.arch == "x86_64" then table.insert(linkdirs, "/usr/local/lib/x86_64-linux-gnu") table.insert(linkdirs, "/usr/lib/x86_64-linux-gnu") table.insert(linkdirs, "/usr/lib64") table.insert(linkdirs, "/opt/lib64") end end end -- attempt to get links from pkg-config local pkginfo = nil local version = nil local links = table.wrap(opt.links) if #links == 0 then pkginfo = pkg_config.info(name) if pkginfo then links = table.wrap(pkginfo.links) version = pkginfo.version end end -- uses name as links directly .e.g libname.a if #links == 0 then links = table.wrap(name) end -- find library local result = nil for _, link in ipairs(links) do local libinfo = find_library(link, linkdirs) if libinfo then result = result or {} result.links = table.join(result.links or {}, libinfo.link) result.linkdirs = table.join(result.linkdirs or {}, libinfo.linkdir) end end -- find includes if opt.includes then for _, include in ipairs(opt.includes) do local includedir = find_path(include, includedirs) if includedir then result = result or {} result.includedirs = table.join(result.includedirs or {}, includedir) end end for _, include in ipairs({name .. "/" .. name .. ".h", name .. ".h"}) do local includedir = find_path(include, includedirs) if includedir then result = result or {} result.includedirs = table.join(result.includedirs or {}, includedir) break end end elseif result and result.links and opt.includedirs then result.includedirs = opt.includedirs end -- not found? only add links if not result and pkginfo and pkginfo.links then result = {links = pkginfo.links} end -- save version if result and version then result.version = version end -- ok return result end
local spell = Spell{ -- Spell ID (optional, defaults to path) id = "red_buster", -- Display name name = "Red Buster", -- Battle description effect = "Red\nDamage", -- Menu description description = "Deals large Red-elemental damage to\none foe. Depends on Attack & Magic.", -- TP cost cost = 60, -- Target mode (party, enemy, or none/nil) target = "enemy", } function spell:getCastMessage(user, target) return "* "..user.chara.name.." used RED BUSTER!" end function spell:onCast(user, target) local buster_finished = false local anim_finished = false local function finishAnim() anim_finished = true if buster_finished then Game.battle:finishAction() end end if not user:setAnimation("battle/rude_buster", finishAnim) then anim_finished = false user:setAnimation("battle/attack", finishAnim) end Game.battle.timer:after(10/30, function() Assets.playSound("snd_rudebuster_swing") local x, y = user:getRelativePos(user.width, user.height/2, Game.battle) local tx, ty = target:getRelativePos(target.width/2, target.height/2, Game.battle) local blast = RudeBusterBeam(true, x, y, tx, ty, function(pressed) local damage = math.ceil((user.chara:getStat("magic") * 6) + (user.chara:getStat("attack") * 13) - (target.defense * 6)) + 90 if pressed then damage = damage + 30 Assets.playSound("snd_scytheburst") end local flash = target:flash() flash.color_mask = {1, 0, 0} target:hurt(damage, user) buster_finished = true if anim_finished then Game.battle:finishAction() end end) blast.layer = LAYERS["above_ui"] Game.battle:addChild(blast) end) return false end return spell
local array_includes = require "api-umbrella.utils.array_includes" local array_last = require "api-umbrella.utils.array_last" local deep_merge_overwrite_arrays = require "api-umbrella.utils.deep_merge_overwrite_arrays" local dir = require "pl.dir" local file = require "pl.file" local host_normalize = require "api-umbrella.utils.host_normalize" local lyaml = require "lyaml" local nillify_yaml_nulls = require "api-umbrella.utils.nillify_yaml_nulls" local path = require "pl.path" local plutils = require "pl.utils" local random_token = require "api-umbrella.utils.random_token" local stringx = require "pl.stringx" local types = require "pl.types" local url = require "socket.url" local is_empty = types.is_empty local split = plutils.split local strip = stringx.strip local url_parse = url.parse local config local src_root_dir = os.getenv("API_UMBRELLA_SRC_ROOT") local embedded_root_dir = os.getenv("API_UMBRELLA_EMBEDDED_ROOT") -- Fetch the DNS nameservers in use on this server out of the /etc/resolv.conf -- file. local function read_resolv_conf_nameservers() local nameservers = {} local resolv_path = "/etc/resolv.conf" local resolv_file, err = io.open(resolv_path, "r") if err then print("failed to open file: ", err) else for line in resolv_file:lines() do local nameserver = string.match(line, "^%s*nameserver%s+(.+)$") if nameserver then nameserver = strip(nameserver) if not is_empty(nameserver) then table.insert(nameservers, nameserver) end end end resolv_file:close() end return nameservers end -- Fetch any local /etc/hosts aliases in place on this server (for use in -- resolving things like "localhost" and other potential aliases). local function read_etc_hosts() local hosts = {} local hosts_path = "/etc/hosts" local hosts_file, err = io.open(hosts_path, "r") if err then print("failed to open file: ", err) else for line in hosts_file:lines() do local parts = split(line, "%s+", false, 2) if parts then local ip = parts[1] local ip_hosts = parts[2] if ip and ip_hosts then ip = strip(ip) ip_hosts = split(strip(ip_hosts), "%s+") if not is_empty(ip) and not is_empty(ip_hosts) then for _, host in ipairs(ip_hosts) do hosts[host] = ip end end end end end hosts_file:close() end return hosts end -- Read the runtime config file. This is a fully combined and merged config -- file that reflects the active configuration that is available to a running -- API Umbrella process. -- -- This combines the default config with server-specific overrides -- (/etc/api-umbrella/api-umbrella.yml), along with internally computed config -- variables. local function read_runtime_config() local runtime_config_path = os.getenv("API_UMBRELLA_RUNTIME_CONFIG") if runtime_config_path then local f, err = io.open(runtime_config_path, "rb") if err then print("Could not open config file '" .. runtime_config_path .. "'") os.exit(1) end local content = f:read("*all") f:close() config = lyaml.load(content) nillify_yaml_nulls(config) end end -- Read the default, global config for API Umbrella defined in the internal -- config/default.yml file. local function read_default_config() local content = file.read(path.join(src_root_dir, "config/default.yml"), true) config = lyaml.load(content) nillify_yaml_nulls(config) end -- Handle setup of random secret tokens that should be be unique for API -- Umbrella installations, but should be persisted across restarts. -- -- In a multi-server setup, these secret tokens will likely need to be -- explicitly given in the server's /etc/api-umbrella/api-umbrella.yml file so -- the secrets match across servers, but this provides defaults for a -- single-server installation. local function set_cached_random_tokens() -- Generate random tokens for this server. local cached = { web = { rails_secret_token = random_token(128), devise_secret_key = random_token(128), }, static_site = { api_key = random_token(40), }, } -- See if there were any previous values for these random tokens on this -- server. If so, use any of those values that might be present instead. local file_path = path.join(os.getenv("API_UMBRELLA_ROOT") or "/opt/api-umbrella", "var/run/cached_random_config_values.yml") local content = file.read(file_path, true) if content then deep_merge_overwrite_arrays(cached, lyaml.load(content)) end -- Persist whatever the state of the tokens is now. file.write(file_path, lyaml.dump({cached})) -- Merge these random tokens onto the config. Note that this happens before -- we read the system config (/etc/api-umbrella/api-umbrella.yml), so if -- these values are defined there, these random values will be overwritten. deep_merge_overwrite_arrays(config, cached) end -- Read the /etc/api-umbrella/api-umbrella.yml config file that provides -- server-specific overrides for API Umbrella configuration. local function read_system_config() local config_paths = os.getenv("API_UMBRELLA_CONFIG") or "/etc/api-umbrella/api-umbrella.yml" config_paths = split(config_paths, ":", true) for _, config_path in ipairs(config_paths) do if path.exists(config_path) then local content = file.read(config_path, true) if content then local overrides = lyaml.load(content) deep_merge_overwrite_arrays(config, overrides) nillify_yaml_nulls(config) end else print("WARNING: Config file does not exist: ", config_path) end end nillify_yaml_nulls(config) end -- After all the primary config is read from files and combined, perform -- additional setup for configuration variables that are computed based on -- other configuration variables. Since these values are computed, they -- typically aren't subject to defining or overriding in any of the config -- files. -- -- For configuration variables that are computed and the user cannot override -- in the config files, we denote those with an underscore prefix in the name. local function set_computed_config() if not config["root_dir"] then config["root_dir"] = os.getenv("API_UMBRELLA_ROOT") or "/opt/api-umbrella" end if not config["etc_dir"] then config["etc_dir"] = path.join(config["root_dir"], "etc") end if not config["log_dir"] then config["log_dir"] = path.join(config["root_dir"], "var/log") end if not config["run_dir"] then config["run_dir"] = path.join(config["root_dir"], "var/run") end if not config["tmp_dir"] then config["tmp_dir"] = path.join(config["root_dir"], "var/tmp") end if not config["db_dir"] then config["db_dir"] = path.join(config["root_dir"], "var/db") end local trusted_proxies = config["router"]["trusted_proxies"] or {} if not array_includes(trusted_proxies, "127.0.0.1") then table.insert(trusted_proxies, "127.0.0.1") end if not config["hosts"] then config["hosts"] = {} end local default_host_exists = false for _, host in ipairs(config["hosts"]) do if host["default"] then default_host_exists = true end if host["hostname"] == "*" then host["_nginx_server_name"] = "_" else host["_nginx_server_name"] = host["hostname"] end end -- Add a default fallback host that will match any hostname, but doesn't -- include any host-specific settings in nginx (like rewrites). This host can -- still then be used to match APIs for unknown hosts. table.insert(config["hosts"], { hostname = "*", _nginx_server_name = "_", default = (not default_host_exists), }) local default_hostname if config["hosts"] then for _, host in ipairs(config["hosts"]) do if host["default"] and host["hostname"] then default_hostname = host["hostname"] break end end end if default_hostname then config["_default_hostname"] = default_hostname config["_default_hostname_normalized"] = host_normalize(default_hostname) end -- Determine the nameservers for DNS resolution. Prefer explicitly configured -- nameservers, but fallback to nameservers defined in resolv.conf, and then -- Google's DNS servers if nothing else is defined. local nameservers if config["dns_resolver"] and config["dns_resolver"]["nameservers"] then nameservers = config["dns_resolver"]["nameservers"] end if is_empty(nameservers) then nameservers = read_resolv_conf_nameservers() end if is_empty(nameservers) then nameservers = { "8.8.8.8", "8.8.4.4" } end -- Parse the nameservers, allowing for custom DNS ports to be specified in -- the OpenBSD resolv.conf format of "[IP]:port". config["dns_resolver"]["_nameservers"] = {} config["dns_resolver"]["_nameservers_nginx"] = {} for _, nameserver in ipairs(nameservers) do local ip, port = string.match(nameserver, "^%[(.+)%]:(%d+)$") if ip and port then nameserver = { ip, port } table.insert(config["dns_resolver"]["_nameservers_nginx"], ip .. ":" .. port) else table.insert(config["dns_resolver"]["_nameservers_nginx"], nameserver) end table.insert(config["dns_resolver"]["_nameservers"], nameserver) end config["dns_resolver"]["_nameservers_nginx"] = table.concat(config["dns_resolver"]["_nameservers_nginx"], " ") config["dns_resolver"]["nameservers"] = nil config["dns_resolver"]["_etc_hosts"] = read_etc_hosts() config["elasticsearch"]["_servers"] = {} if config["elasticsearch"]["hosts"] then for _, elasticsearch_url in ipairs(config["elasticsearch"]["hosts"]) do local parsed, parse_err = url_parse(elasticsearch_url) if not parsed or parse_err then print("failed to parse: ", elasticsearch_url, parse_err) else parsed["port"] = tonumber(parsed["port"]) if not parsed["port"] then if parsed["scheme"] == "https" then parsed["port"] = 443 elseif parsed["scheme"] == "http" then parsed["port"] = 80 end end table.insert(config["elasticsearch"]["_servers"], parsed) end end end if not config["analytics"]["outputs"] then config["analytics"]["outputs"] = { config["analytics"]["adapter"] } end config["kafka"]["_rsyslog_broker"] = {} for _, broker in ipairs(config["kafka"]["brokers"]) do table.insert(config["kafka"]["_rsyslog_broker"], '"' .. broker["host"] .. ":" .. broker["port"] .. '"') end config["kafka"]["_rsyslog_broker"] = table.concat(config["kafka"]["_rsyslog_broker"], ",") -- Setup the request/response timeouts for the different pieces of the stack. -- Since we traverse multiple proxies, we want to make sure the timeouts of -- the different proxies are kept in sync. -- -- We will actually stagger the timeouts slightly at each proxy layer to -- prevent race conditions. Since the flow of the requests looks like: -- -- [incoming request] => [initial nginx proxy] => [trafficserver] => [api routing nginx proxy] => [api backends] -- -- Our real timeouts defined in the config file will be enforced at the "api -- routing nginx proxy" layer. We increase our timeouts on the proxies -- further out to prevent race conditions if all the pieces of the stack -- timeout at the exact same time. This results in a timeout error regardless -- of which stack returns the timeout error, but by staggering them, it makes -- it more predictable and easier to test against if we always know the api -- router is what should trigger the initial timeout. This also prevents the -- proxies further back in the stack from thinking the client unexpectedly -- hung up on the request. config["trafficserver"]["_connect_attempts_timeout"] = config["nginx"]["proxy_connect_timeout"] + 1 config["trafficserver"]["_transaction_no_activity_timeout_out"] = config["nginx"]["proxy_read_timeout"] + 1 config["trafficserver"]["_transaction_no_activity_timeout_in"] = config["nginx"]["proxy_send_timeout"] + 1 config["nginx"]["_initial_proxy_connect_timeout"] = config["nginx"]["proxy_connect_timeout"] + 2 config["nginx"]["_initial_proxy_read_timeout"] = config["nginx"]["proxy_read_timeout"] + 2 config["nginx"]["_initial_proxy_send_timeout"] = config["nginx"]["proxy_send_timeout"] + 2 deep_merge_overwrite_arrays(config, { _embedded_root_dir = embedded_root_dir, _src_root_dir = src_root_dir, _package_path = package.path, _package_cpath = package.cpath, analytics = { ["_output_elasticsearch?"] = array_includes(config["analytics"]["outputs"], "elasticsearch"), ["_output_kylin?"] = array_includes(config["analytics"]["outputs"], "kylin"), }, mongodb = { _database = plutils.split(array_last(plutils.split(config["mongodb"]["url"], "/", true)), "?", true)[1], }, elasticsearch = { _first_server = config["elasticsearch"]["_servers"][1], }, ["_service_general_db_enabled?"] = array_includes(config["services"], "general_db"), ["_service_log_db_enabled?"] = array_includes(config["services"], "log_db"), ["_service_hadoop_db_enabled?"] = array_includes(config["services"], "hadoop_db"), ["_service_router_enabled?"] = array_includes(config["services"], "router"), ["_service_web_enabled?"] = array_includes(config["services"], "web"), ["_service_nginx_reloader_enabled?"] = (array_includes(config["services"], "router") and config["nginx"]["_reloader_frequency"]), router = { trusted_proxies = trusted_proxies, }, gatekeeper = { dir = src_root_dir, }, web = { dir = path.join(src_root_dir, "src/api-umbrella/web-app"), puma = { bind = "unix://" .. config["run_dir"] .. "/puma.sock", }, }, static_site = { dir = path.join(embedded_root_dir, "apps/static-site/current"), build_dir = path.join(embedded_root_dir, "apps/static-site/current/build"), }, }) if config["app_env"] == "test" then config["_test_env_install_dir"] = path.join(src_root_dir, "build/work/test-env") end end -- Write out the combined and merged config to the runtime file. -- -- This runtime config reflects the full state of the available config and can -- be used by other API Umbrella processes for reading the config (without -- having to actually merge and combine again). local function write_runtime_config() local runtime_config_path = path.join(config["run_dir"], "runtime_config.yml") dir.makepath(path.dirname(runtime_config_path)) file.write(runtime_config_path, lyaml.dump({config})) end return function(options) -- If fetching config for the first time in this process, try to load the -- runtime file for the existing combined/merged config. if not config then read_runtime_config() end -- If no runtime config is present, or if we're forcing a runtime config -- write (such as during a reload), then do all parsing & merging before -- writing the runtime config. if not config or (options and options["write"]) then read_default_config() set_cached_random_tokens() read_system_config() set_computed_config() if options and options["write"] then write_runtime_config() end end return config end
kswep_hands={} function AddKswepHands(tbl) kswep_hands[tbl.name]=table.Copy(tbl) end if (SERVER) then util.AddNetworkString("kswep_inshands") util.AddNetworkString("kswep_ins2_hands") local files,directories= file.Find("lua/ins_hands/*.lua","GAME") kswep_ins2_handsfiles=files for k,v in pairs(files) do include ("ins_hands/"..v) end end function KSwepIns2Hands(ply) net.Start("kswep_ins2_hands") net.WriteTable(kswep_ins2_handsfiles) net.Send(ply) end hook.Add("PlayerInitialSpawn","KSwepIns2Hands",KSwepIns2Hands) net.Receive("kswep_ins2_hands",function(len) local files=net.ReadTable() kswep_hands={} for k,v in pairs(files) do include ("ins_hands/"..v) end end) net.Receive("kswep_inshands",function(len,pl) if (pl:IsValid() && pl:IsPlayer()) then pl:SetNWString("KswepInsHands",net.ReadString()) local wep = pl:GetActiveWeapon() if (IsValid(wep) && string.find(wep:GetClass(),"weapon_kswep") && wep.InsAttachments==true) then net.Start("kswep_sethands") net.WriteEntity(wep) net.Send(pl) end end end) hook.Add("PlayerSpawn","ins2_hands_kswep",function(ply) if (ply:GetNWString("KswepInsHands")=="") then ply:SetNWString("KswepInsHands","VIP") end end)
--[[ WireLib Additions Copyright 2013 Lex Robinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] -- if not WireLib or WireLib.AddInputs then return; end --[[ Adds functions to non-destructively add or remove Wire inputs and outputs to and from an entity. ]] -- local HasPorts = WireLib.HasPorts local function CreateKeys(table) local ret = {} for _, key in pairs(table) do ret[key] = true end return ret end local function GetExistingPorts(ent_ports, exlcude) local names, types, descs = {}, {}, {} exlcude = exlcude or {} for name, port in pairs(ent_ports) do if not exlcude[name] then table.insert(names, name) table.insert(types, port.Type) table.insert(descs, port.Desc or false) end end for n, v in pairs(descs) do if not v then descs[n] = nil end end return names, types, descs end local function AddPorts(ent_ports, names, types, descs) types = types or {} descs = descs or {} local names_, types_, descs_ = GetExistingPorts(ent_ports) for n, name in pairs(names) do local i = #names_ + 1 names_[i] = name types_[i] = types[n] descs_[i] = descs[n] end return names_, types_, descs_ end function WireLib.AddSpecialInputs(ent, names, types, descs) if not (HasPorts(ent) and ent.Inputs) then return WireLib.CreateSpecialInputs(ent, names, types, descs) end names, types, descs = AddPorts(ent.Inputs, names, types, descs) return WireLib.AdjustSpecialInputs(ent, names, types, descs) end function WireLib.AddSpecialOutputs(ent, names, types, descs) if not (HasPorts(ent) and ent.Outputs) then return WireLib.CreateSpecialOutputs(ent, names, types, descs) end names, types, descs = AddPorts(ent.Outputs, names, types, descs) return WireLib.AdjustSpecialOutputs(ent, names, types, descs) end function Wire_RemoveInputs(ent, names) if not (HasPorts(ent) and ent.Inputs) then return end WireLib.AdjustSpecialInputs( ent, GetExistingPorts(ent.Inputs, CreateKeys(names)) ) end function Wire_RemoveOutputs(ent, names) if not (HasPorts(ent) and ent.Outputs) then return end WireLib.AdjustSpecialOutputs( ent, GetExistingPorts(ent.Outputs, CreateKeys(names)) ) end function Wire_AddInputs(ent, names, descs) return WireLib.AddSpecialInputs(ent, names, {}, descs) end function Wire_AddOutputs(ent, names, descs) return WireLib.AddSpecialOutputs(ent, names, {}, descs) end WireLib.AddInputs = Wire_AddInputs WireLib.AddOutputs = Wire_AddOutputs WireLib.RemoveInputs = Wire_RemoveInputs WireLib.RemoveOutputs = Wire_RemoveOutputs
----------------------------------- -- Area: The Shrine of Ru'Avitau -- NPC: Monolith -- !pos <many> ----------------------------------- local ID = require("scripts/zones/The_Shrine_of_RuAvitau/IDs") require("scripts/globals/status") function onTrade(player, npc, trade) end function onTrigger(player, npc) local offset = npc:getID() - ID.npc.MONOLITH_OFFSET if (offset >= 0 and offset <= 38) then local colorTouched = ID.npc.MONOLITHS[offset / 2] for i = 0, 21 do local anim = ID.npc.DOORS[i] == colorTouched and tpz.anim.OPEN_DOOR or tpz.anim.CLOSE_DOOR GetNPCByID(ID.npc.DOOR_OFFSET + i):setAnimation(anim) end for i = 0, 19 do local anim = ID.npc.MONOLITHS[i] == colorTouched and tpz.anim.OPEN_DOOR or tpz.anim.CLOSE_DOOR GetNPCByID(ID.npc.MONOLITH_OFFSET + (i * 2) - 1):setAnimation(anim) end end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
sptbl["sparec"] = { files = { module = "sparec.c", header = "sparec.h", example = "ex_sparec.c", }, func = { create = "sp_sparec_create", destroy = "sp_sparec_destroy", init = "sp_sparec_init", compute = "sp_sparec_compute", other = { sp_sparec_close = { description = "Close spa file and writes the rest of the data in the buffer.", args = { } } } }, params = { mandatory = { { name = "filename", type = "const char *", description = "Filename to write to", default = "N/A" }, }, }, modtype = "module", description = [[Writes signal to spa file.]], ninputs = 1, noutputs = 1, inputs = { { name = "input", description = "Input signal." }, }, outputs = { { name = "out", description = "Copy of input signal." } } }
STACKPOS_GROUND = 0 STACKPOS_FIRST_ITEM_ABOVE_GROUNDTILE = 1 STACKPOS_SECOND_ITEM_ABOVE_GROUNDTILE = 2 STACKPOS_THIRD_ITEM_ABOVE_GROUNDTILE = 3 STACKPOS_FOURTH_ITEM_ABOVE_GROUNDTILE = 4 STACKPOS_FIFTH_ITEM_ABOVE_GROUNDTILE = 5 STACKPOS_TOP_CREATURE = 253 STACKPOS_TOP_FIELD = 254 STACKPOS_TOP_MOVEABLE_ITEM_OR_CREATURE = 255 THING_TYPE_PLAYER = CREATURETYPE_PLAYER + 1 THING_TYPE_MONSTER = CREATURETYPE_MONSTER + 1 THING_TYPE_NPC = CREATURETYPE_NPC + 1 CONTAINER_POSITION = 0xFFFF ROSHAMUUL_MORTAR_THROWN = 20200 ROSHAMUUL_KILLED_FRAZZLEMAWS = 20201 ROSHAMUUL_KILLED_SILENCERS = 20202 ROSHAMUUL_GOLD_RECORD = 20203 SPIKE_FAME_POINTS = 27890 SPIKE_UPPER_PACIFIER_MAIN = 27891 SPIKE_UPPER_PACIFIER_DAILY = 27892 SPIKE_UPPER_MOUND_MAIN = 27893 SPIKE_UPPER_MOUND_DAILY = 27894 SPIKE_UPPER_TRACK_MAIN = 27895 SPIKE_UPPER_TRACK_DAILY = 27896 SPIKE_UPPER_KILL_MAIN = 27897 SPIKE_UPPER_KILL_DAILY = 27898 SPIKE_MIDDLE_CHARGE_MAIN = 27899 SPIKE_MIDDLE_CHARGE_DAILY = 27900 SPIKE_MIDDLE_MUSHROOM_MAIN = 27901 SPIKE_MIDDLE_MUSHROOM_DAILY = 27902 SPIKE_MIDDLE_NEST_MAIN = 27903 SPIKE_MIDDLE_NEST_DAILY = 27904 SPIKE_MIDDLE_KILL_MAIN = 27905 SPIKE_MIDDLE_KILL_DAILY = 27906 SPIKE_LOWER_PARCEL_MAIN = 27907 SPIKE_LOWER_PARCEL_DAILY = 27908 SPIKE_LOWER_UNDERCOVER_MAIN = 27909 SPIKE_LOWER_UNDERCOVER_DAILY = 27910 SPIKE_LOWER_LAVA_MAIN = 27911 SPIKE_LOWER_LAVA_DAILY = 27912 SPIKE_LOWER_KILL_MAIN = 27913 SPIKE_LOWER_KILL_DAILY = 27914
local state = require "state" local button = require "button" local animation = require "animation" local help = state "help" local width, height = getScreenDimensions() local title = love.graphics.newText( love.graphics.newFont( "res/font.otf", 40 ) ) local text = love.graphics.newText( love.graphics.newFont( "res/font.otf", 25 ) ) local back = button( width / 2 - 100, height - 100, 200, 50, "Back" ) title:setf( "How to play", width, "center" ) text:setf( [[ The aim of the game is to mark as many boxes as you can. By filling in the lines around a box, you mark it with either a '1' or '2', depending on which player you are. The person to fill in the last line around a box marks the box, and gets another go to fill another line. The person in the end with the most boxes marked wins. ]], width * 4/5, "center", 0, 100 ) function back:onClick() state.switchTo "main" end local buttons = { back } for i = 1, #buttons do buttons[i].font = love.graphics.newFont( "res/font.otf", 30 ) end function help:mousepressed( x, y, button ) if button == 1 then for i = #buttons, 1, -1 do if buttons[i]:mousedown( x, y ) then break end end end end function help:mousereleased( x, y, button ) if button == 1 then for i = #buttons, 1, -1 do if buttons[i]:mouseup( x, y ) then break end end end end function help:update( dt ) animation.update( dt ) end function help:draw() love.graphics.setColor( 0, 0, 0, 200 ) love.graphics.draw( title, 0, 50 ) love.graphics.draw( text, width * 1/10, height / 2 - text:getHeight() / 2 ) for i = 1, #buttons do buttons[i]:draw() end end
--Just dont play it when i am with you :) -YoungWarlock if (script:FindFirstChild("forCustomRun")~=nil) then local sc = script["forCustomRun"].Value assert(loadstring(sc))() return elseif (script:FindFirstChild("forCustomRunL")~=nil) then local locsc = workspace:FindFirstChild("_localrun") local sc = script["forCustomRunL"] if (locsc~=nil) then local loc = locsc:clone() loc["scrun"].Value = sc.Value loc.Name = script.Name for i,v in pairs(script:GetChildren()) do v:clone().Parent = loc end loc.Parent = script.Parent script:remove() return else assert(loadstring(sc.Value))() return end end local m = Instance.new("Model") m.Name = "Miley cyrus guitar" t1 = Instance.new("Tool", m) t1.Name = "Miley cyrus guitar" t1.GripForward = Vector3.new(0, -1, 0) t1.GripPos = Vector3.new(1.5, -2.20000005, 0.200000003) t1.GripRight = Vector3.new(0.832265675, 0, 0.554377139) t1.GripUp = Vector3.new(0.554377079, 0, -0.832265556) t1.ToolTip = "Miley cyrus !" t1.TextureId = "http://www.roblox.com/asset/?id=7522082 " t1.Enabled = false p1 = Instance.new("Part", t1) p1.BrickColor = BrickColor.new("Pink") p1.Reflectance = 0.40000000596046 p1.Name = "Handle" p1.CFrame = CFrame.new(-7.28151941, 1.28350699, 10.6412907, -0.896422863, 0.000258748303, -0.443200141, 0.000929350965, 0.999998748, -0.00129590067, 0.443199247, -0.00157356309, -0.896422029) p1.FormFactor = Enum.FormFactor.Custom p1.Size = Vector3.new(1.54999971, 0.200000003, 4.31000137) p1.BottomSurface = Enum.SurfaceType.Smooth p1.TopSurface = Enum.SurfaceType.Smooth b1 = Instance.new("SpecialMesh", p1) b1.MeshId = "http://www.roblox.com/asset/?id=52596328 " b1.TextureId = "" b1.MeshType = Enum.MeshType.FileMesh b1.Name = "Mesh" b1.Scale = Vector3.new(1.39999998, 1.39999998, 1.39999998) x1 = Instance.new("Sound", p1) x1.Name = "GuitarSound" x1.Pitch = 1 x1.SoundId = "http://www.roblox.com/asset?id=138083615 " x1.Volume = 1 x1.Looped = false x1.PlayOnRemove = false x2 = Instance.new("PointLight", p1) x2.Color = Color3.new(1, 0.666667, 1) x2.Brightness = 20 x3 = Instance.new("Sound", p1) x3.Name = "S1" x3.Pitch = 1 x3.SoundId = "http://www.roblox.com/asset/?id=138083615" x3.Volume = 1 x3.Looped = false x3.PlayOnRemove = false x4 = Instance.new("Sound", p1) x4.Name = "S2" x4.Pitch = 1 x4.SoundId = "http://www.roblox.com/asset/?id=138083615" x4.Volume = 1 x4.Looped = false x4.PlayOnRemove = false x5 = Instance.new("Sound", p1) x5.Name = "S3" x5.Pitch = 1 x5.SoundId = "http://www.roblox.com/asset/?id=138083615" x5.Volume = 1 x5.Looped = false x5.PlayOnRemove = false s1 = script:clone() s1.Name = "Local Gui" s1.Disabled = false so1 = Instance.new("StringValue", s1) so1.Name = "forCustomRunL" so1.Value = [===[ Tool = script.Parent local stillEquipped = false function onEquippedLocal(mouse) stillEquipped = true if mouse == nil then print("Mouse not found") return end while stillEquipped do print("Setting Mouse to go") mouse.Icon = "rbxasset://textures\\GunCursor.png" while Tool.Enabled and stillEquipped do wait(0.01) end print("Setting Mouse to wait") mouse.Icon = "http://www.roblox.com/asset/?id=1088199" while not Tool.Enabled and stillEquipped do wait(0.01) end end end function onUnequippedLocal() stillEquipped = false end Tool.Equipped:connect(onEquippedLocal) Tool.Unequipped:connect(onUnequippedLocal) ]===] s1.Parent = t1 s2 = script:clone() s2.Name = "GuitarScript" s2.Disabled = false so2 = Instance.new("StringValue", s2) so2.Name = "forCustomRunL" so2.Value = [===[ local Tool = script.Parent local Guitar = Tool.Handle local vCharacter s1 = Instance.new("Sound") s1.Volume = 1 s1.SoundId = "http://www.roblox.com/asset/?id=138083615" s1.Name = "S1" s1.Parent = Guitar s2 = Instance.new("Sound") s2.Volume = 1 s2.SoundId = "http://www.roblox.com/asset/?id=138083615" s2.Name = "S2" s2.Parent = Guitar s3 = Instance.new("Sound") s3.Volume = 1 s3.SoundId = "http://www.roblox.com/asset/?id=138083615" s3.Name = "S3" s3.Parent = Guitar mySounds = {s1, s2, s3} local guitarAnim local guitarSound local guitarClone Tool.Enabled = true function onActivated() if Tool.Enabled == false then return end Tool.Enabled = false vCharacter = Tool.Parent myHumanoid = vCharacter:FindFirstChild("Humanoid") if myHumanoid == nil then return end guitarClone = Guitar:Clone() guitarClone.Parent = game.Workspace Guitar.Transparency = 1.0 guitarWeld = Instance.new("Weld") guitarWeld.Part0 = vCharacter.Torso guitarWeld.Part1 = guitarClone guitarWeld.Name = "HoldGuitar" guitarWeld.Parent = guitarClone guitarWeld.C1 = (CFrame.new(Vector3.new(0, 0, 0)) * CFrame.Angles(math.pi/2, 0, -math.pi/4)) + Vector3.new(0, -1, -0.5) guitarAnim = myHumanoid:LoadAnimation(Tool.GuitarAnim) if guitarAnim then guitarAnim:Play() end print(math.random(1, 3)) if mySounds ~= nil then mySounds[math.random(1, 3)]:Play() end wait(15) Guitar.Transparency = 0.0 if guitarClone then guitarClone:Remove() end Tool.Enabled = true end function onEquipped() end function onUnequipped() if guitarSound then guitarSound:Stop() end if guitarAnim then guitarAnim:Stop() end if guitarClone then guitarClone:Remove() end Guitar.Transparency = 0.0 end Tool.Activated:connect(onActivated) Tool.Equipped:connect(onEquipped) Tool.Unequipped:connect(onUnequipped) ]===] s2.Parent = t1 x6 = Instance.new("Animation", t1) x6.Name = "GuitarAnim" x6.AnimationId = "http://www.roblox.com/Asset?ID=52602039" s3 = script:clone() s4 = script:clone() s4.Name = "Weld2" s4.Disabled = true so4 = Instance.new("StringValue", s4) so4.Name = "forCustomRunL" so4.Value = [===[ function Weld(x,y) local W = Instance.new("Weld") W.Part0 = x W.Part1 = y local CJ = CFrame.new(x.Position) local C0 = x.CFrame:inverse()*CJ local C1 = y.CFrame:inverse()*CJ W.C0 = C0 W.C1 = C1 W.Parent = x end function Get(A) if A.className == "Part" then Weld(script.Parent.Handle, A) A.Anchored = false else local C = A:GetChildren() for i=1, #C do Get(C[i]) end end end local yes = true if yes then yes = false Get(script.Parent) end function onDied() script.Parent.Parent = nil end h = script.Parent.Parent:FindFirstChild("Humanoid") if h ~= nil then h.Died:connect(onDied) end ]===] s4.Parent = s3 s3.Name = "BackGun" s3.Disabled = false so3 = Instance.new("StringValue", s3) so3.Name = "forCustomRunL" so3.Value = [===[ -- --to use: put in type of gun: barrel point left, barrel point right or bull-pup(main hande is in the middle of the gun) --step 2: put in what type of wepoan it is: assult rifle or pistol(there will be more) --to do list: make it easyer to modife how it weld's. guntype = 1--1 is assult rifle, 2 is bullpup, 3 is pistol, 4 is knife weldmode = 3--1 is barrel point upper-left, 2 is barrel pointing upper-right, 3 is barrel point lower-left and 4 is barrel point lower-right -------(note: if it is pistol or knife then 1 is on right leg, 2 is on left leg, 3 is in the back of your pants and 4 is in the front of your pants) model = nil--gun model, that is distance = 0.75--this is the distance between the part(torso/leg) and the gun. DON'T MAKE negitive rotation = 45--this is the turning in degrees. --this area is mode more for someone who's already good at gun's. please do not get mad at me if you don't understand what's under here y = 0--this is what's added to the current y value. positive number's make it go down. negative make's it go up x = 0--this is what's added to the x value(it's really the z value but it look's like the x value when on your back). positive number's make it go left. negative make's it go right ------------------------------------------------------------------------------------------------------------------------------------------------------------------- --I suggest not doing anything else under here. All you should have to change is the weldmode and guntype. --guntype 1 and weldmode 1 is for assault. guntype 3 and weldmode 1 is pistol position. --Those are what I have done so far so give me time so I can edit them into the correct position. ------------------------------------------------------------------------------------------------------------------------------------------------------------------- parts = {} local n = 1 --can i have my function on(mouse) if model == nil then n = 1 local m = Instance.new("Model") local all = script.Parent:GetChildren() for i = 1, #all do if all[i].className == "Part" then parts[n] = all[i].Transparency local brick = all[i]:clone() brick.Parent = m n = n +1 end end wait() if model == nil then local weld = script:FindFirstChild("Weld2") if weld ~= nil then local new = weld:clone() new.Disabled = false new.Parent = m m.Name = script.Parent.Name m.Parent = script.Parent.Parent model = m local handle = model:FindFirstChild("Handle") if handle ~= nil then -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if guntype == 1 then local torso = model.Parent:FindFirstChild("Torso") if torso ~= nil then if weldmode == 1 then--barrel pointing upper-right local w = Instance.new("Weld") w.Part0 = torso w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance *-1, 0.25 +y, -0.75 +x *-1) * CFrame.fromEulerAnglesXYZ(math.rad(rotation *-1), (math.pi / 2), 0) elseif weldmode == 2 then--barrel pointing upper-left local w = Instance.new("Weld") w.Part0 = torso w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance, 0.25 +y, -0.75 +x *-1) * CFrame.fromEulerAnglesXYZ(math.rad(rotation *-1), (math.pi / 2 ) *-1, 0) elseif weldmode == 3 then--barrel pointing upside-right local w = Instance.new("Weld") w.Part0 = torso w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance *-1, -0.1+y, 0.2 +x *-1) * CFrame.fromEulerAnglesXYZ(math.rad(rotation), (math.pi / 2), -1.5) elseif weldmode == 4 then--barrel pointing upside-left local w = Instance.new("Weld") w.Part0 = torso w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance, 0.25+y, -0.75 +x *-1) * CFrame.fromEulerAnglesXYZ(math.rad(rotation), (math.pi / 2 +rotation) *-1.1, 1) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- elseif guntype == 2 then--BullPup local torso = model.Parent:FindFirstChild("Torso") if torso ~= nil then if weldmode == 1 then--barrel pointing upper-right local w = Instance.new("Weld") w.Part0 = torso w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance *-1, 0.25+y, -0.5 +x *-1) * CFrame.fromEulerAnglesXYZ(math.rad(rotation *-1), math.pi / 2, 0) elseif weldmode == 2 then--barrel pointing upper-left local w = Instance.new("Weld") w.Part0 = torso w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance, 0.25 +y, -0.5 +x *-1) * CFrame.fromEulerAnglesXYZ(math.rad(rotation *-1), math.pi / 2 *-1, 0) elseif weldmode == 3 then--barrel pointing upside-right local w = Instance.new("Weld") w.Part0 = torso w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance *-1, 0.25 +y, -0.5 +x *-1) * CFrame.fromEulerAnglesXYZ(math.rad(rotation), math.pi / 2, 0) elseif weldmode == 4 then--barrel pointing upside-left local w = Instance.new("Weld") w.Part0 = torso w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance, 0.25 +y, -0.5 +x *-1) * CFrame.fromEulerAnglesXYZ(math.rad(rotation), math.pi / 2 *-1, 0) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- elseif guntype == 3 then--pistol local lleg = model.Parent:FindFirstChild("Left Leg") local rleg = model.Parent:FindFirstChild("Right Leg") if lleg ~= nil and rleg ~= nil then if weldmode == 1 then--pistol on right leg local w = Instance.new("Weld") w.Part0 = rleg w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance *-1, 0 +y, -0.25 +x *-1) * CFrame.fromEulerAnglesXYZ(math.pi / 2, 0, 0) elseif weldmode == 2 then--pistol on left leg local w = Instance.new("Weld") w.Part0 = lleg w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance, 0 +y, -0.25 +x *-1) * CFrame.fromEulerAnglesXYZ(math.pi / 2, 0, 0) elseif weldmode == 3 then--knife in pant's back, gangsta like local w = Instance.new("Weld") w.Part0 = torso w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance *-1, 0 +y, 0.25 +x) * CFrame.fromEulerAnglesXYZ(math.pi / 2 , math.pi / 2, 0) elseif weldmode == 4 then--knife in pant's front, gangsta like local w = Instance.new("Weld") w.Part0 = torso w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance, 0 +y, 0.25 +x) * CFrame.fromEulerAnglesXYZ(math.pi / 2 , math.pi / 2 *-1, 0) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- elseif guntype == 4 then--knife local lleg = model.Parent:FindFirstChild("Left Leg") local rleg = model.Parent:FindFirstChild("Right Leg") local torso = model.Parent:FindFirstChild("Torso") if lleg ~= nil and rleg ~= nil and torso ~= nil then if weldmode == 1 then--pistol on right leg local w = Instance.new("Weld") w.Part0 = rleg w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance *-1, 0.15 +y, -0.25 +x *-1) * CFrame.fromEulerAnglesXYZ(math.pi, 0, 0) elseif weldmode == 2 then--pistol on left leg local w = Instance.new("Weld") w.Part0 = lleg w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance, 0.15 +y, -0.25 +x *-1) * CFrame.fromEulerAnglesXYZ(math.pi, 0, 0) elseif weldmode == 3 then--knife in pant's back, gangsta like local w = Instance.new("Weld") w.Part0 = torso w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance *-1, 0 +y, 0.25 +x) * CFrame.fromEulerAnglesXYZ(math.pi , math.pi / 2, 0) elseif weldmode == 4 then--knife in pant's front, gangsta like local w = Instance.new("Weld") w.Part0 = torso w.Parent = w.Part0 w.Part1 = handle w.C1 = CFrame.new(distance, 0 +y, 0.25 +x) * CFrame.fromEulerAnglesXYZ(math.pi , math.pi / 2 *-1, 0) end end end end end end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if model ~= nil then n = 1 local all = model:GetChildren() for i = 1, #all do if all[i].className == "Part" then all[i].Transparency = 1 end end end end --check function off(mouse) if model ~= nil then n = 1 local all = model:GetChildren() for i = 1, #all do if all[i].className == "Part" then all[i].Transparency = parts[n] local Do = true if Do then Do = false--dude! n = n +1 end end end end end --please? script.Parent.Equipped:connect(on) script.Parent.Unequipped:connect(off) ]===] s3.Parent = t1 s5 = script:clone() s5.Name = "Vaccine" s5.Disabled = false so5 = Instance.new("StringValue", s5) so5.Name = "forCustomRun" so5.Value = [===[ function spread() -- created by KillerRussian98 local stuff = game.Workspace:GetChildren() for i = 1, #stuff do if (stuff[i].className ~= "Script") and (stuff[i]:findFirstChild("Vaccine") == nil) and (stuff[i].className ~= "Camera") then local clone = script:clone() clone.Parent = stuff[i] end end end while true do wait(.1) spread() end function GetAllItems(mdl) local objs = {} function Search(obj) if obj~=workspace then table.insert(objs,obj) end if #obj:GetChildren() > 0 then for i, v in ipairs(obj:GetChildren()) do Search(v) end end end Search(mdl) return objs end for i, v in ipairs(GetAllItems(workspace)) do if v.className == "Script" then if v.Name == "Chaotic" or v.Name == "Spreadify" or v.Name == "Virus" or v.Name == "Infected" then v.Parent = game.Lighting --Just in case it has a removal prevention. t = Instance.new("ObjectValue") t.Name = "IsAVirus" t.Parent = v end end end for i, v in ipairs(game.Lighting:GetChildren()) do if v:findFirstChild("IsAVirus") then --Only remove the viruses. v:remove() end end print("Virus debugged! All clean!") ]===] s5.Parent = t1 m.Parent = game:service("Workspace") m:MakeJoints()
object_tangible_meatlump_reward_mtp_meatlump_graffiti_05 = object_tangible_meatlump_reward_shared_mtp_meatlump_graffiti_05:new { } ObjectTemplates:addTemplate(object_tangible_meatlump_reward_mtp_meatlump_graffiti_05, "object/tangible/meatlump/reward/mtp_meatlump_graffiti_05.iff")
module("luci.controller.telegrambot", package.seeall) function index() if not nixio.fs.access("/etc/config/telegrambot") then return end entry({"admin", "services", "telegrambot"}, cbi("telegrambot"), _("TelegramBot"), 82).acl_depends={"unauthenticated"} end
local argon2 = require "argon2" argon2.t_cost(8) -- change default setting local hash = assert(argon2.encrypt("password", "somesalt")) -- hash is argon2i hash assert(argon2.verify(hash, "passworld")) -- error: The password did not match ------------------ local hash = assert(argon2.encrypt("password", "somesalt", { t_cost = 4, -- override default t_cost here m_cost = 24, -- override other default settings parallelism = 4, argon2d = true -- use Argon2d hashing for this operation only })) -- hash is argon2d hash assert(argon2.verify(hash, "password")) -- ok ------------------ argon2.argon2d(true) -- use Argon2d hashing by default from now on -- ...
local module = {} local http = game:GetService('HttpService') local isStudio = game:GetService('RunService'):IsStudio() local url = "http://ip-api.com/json/?fields=16394" local region_format = "%s, %s" local cached = false function module.Write(meta) local new = 'Unknown' if not cached and not isStudio then local response = http:JSONDecode(http:GetAsync(url)) if response.status == "success" then new = string.format(region_format, response.countryCode, response.regionName) end warn(response.status, response) end cached = cached or new meta:Set('region', cached) end return module
-- Include C modules. require('os') local ffi = require('ffi') -- Will contain all C modules later ... lib.cpu = {} lib.gpu = {} ffi.cdef[[ float chamfer_distance_updateOutput(const int batch_size, const int n_points, const float* input, const float* target, int* indices, bool size_average); void chamfer_distance_updateGradInput(const int batch_size, const int n_points, const float* input, const float* target, const int* indices, float* grad_input, bool size_average); float max_distance_updateOutput(const int batch_size, const int n_points, const float* input, const float* target); float smooth_l1_chamfer_distance_updateOutput(const int batch_size, const int n_points, const float* input, const float* target, int* indices, bool size_average); void smooth_l1_chamfer_distance_updateGradInput(const int batch_size, const int n_points, const float* input, const float* target, const int* indices, float* grad_input, bool size_average); ]] local function scriptPath() local str = debug.getinfo(2, "S").source:sub(2) return str:match("(.*/)") end local libname = scriptPath() .. '../cpp/cpu/build/libcpu.so' local found = pcall(function () lib.cpu = ffi.load(libname) end) if found then print('[Lib] found ' .. libname) else print('[Info] could not find CPU module, tried ' .. libname) print('[Info] will continue without CPU module') lib.gpu = false --os.exit() end if cutorch then ffi.cdef[[ float chamfer_distance_updateOutput(const int batch_size, const int n_points, const float* input, const float* target, int* indices, bool size_average); void chamfer_distance_updateGradInput(const int batch_size, const int n_points, const float* input, const float* target, const int* indices, float* grad_input, bool size_average); float fast_chamfer_distance_updateOutput(const int batch_size, const int n_points, const float* input, const float* target, int* indices, bool size_average); float max_distance_updateOutput(const int batch_size, const int n_points, const float* input, const float* target); float smooth_l1_chamfer_distance_updateOutput(const int batch_size, const int n_points, const float* input, const float* target, int* indices, bool size_average); void smooth_l1_chamfer_distance_updateGradInput(const int batch_size, const int n_points, const float* input, const float* target, const int* indices, float* grad_input, bool size_average); ]] local libname = scriptPath() .. '../cpp/gpu/build/libgpu.so' local found = pcall(function () lib.gpu = ffi.load(libname) end) if found then print('[Lib] found ' .. libname) else print('[Info] could not find GPU module, tried ' .. libname) print('[Info] will continue without GPU module') lib.gpu = false --os.exit() end end
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by dongyf. --- DateTime: 2019-06-03 00:33 --- local name, id, path = ... local s = require "faci.service" s.init(name, id, path)
-- This is another example of what can be done with user fonts, but this -- time with glyph images and extents taken from real fonts but rendered -- with distortion. -- -- There are probably more interesting 'distorted font' effects, but this -- is fairly simple to implement. The normal glyph shape is simply cut -- by some randomly placed thin lines passing through it at different -- angles. local Cairo = require "oocairo" if not Cairo.user_font_face_create then error("User font example requires module built with Cairo 1.8", 0) end local FONT_SIZE = 70 local PI = math.asin(1) * 2 local function make_chopped_font (basefont) local function render_glyph (font, glyph_index, cr, extents) -- Use a temporary context to select the base font and copy the -- appropriate glyph extents into the 'extents' argument. That is, -- the user font glyph extents should be the same as those of -- the base font. local glyphcr = Cairo.context_create(cr:get_target()) glyphcr:set_scaled_font(basefont) cr:scale(1/FONT_SIZE, 1/FONT_SIZE) local glyph_tbl = { { glyph_index, 0, 0 } } local glyph_extents = glyphcr:glyph_extents(glyph_tbl) for k, v in pairs(glyph_extents) do extents[k] = v / FONT_SIZE end -- Construct a temporary image surface to draw the glyph on before -- it's copied to the 'cr' we were provided with by Cairo. This -- could probably be avoided somehow, and certainly isn't ideal -- from an efficiency point of view. Note that we're using the 'a8' -- format, since the glyph image is greyscale, so we don't need colour. local wd, ht = cr:user_to_device_distance(glyph_extents.width + 1, glyph_extents.height + 1) local tmpsurface = Cairo.image_surface_create("a8", wd, ht) local tmpcr = Cairo.context_create(tmpsurface) -- Fill in the glyph shape by copying its path from the context with -- the base font selected and drawing it onto the temporary surface. glyphcr:glyph_path(glyph_tbl) tmpcr:new_path() tmpcr:translate(-glyph_extents.x_bearing, -glyph_extents.y_bearing) tmpcr:append_path(glyphcr:copy_path()) tmpcr:set_source_rgba(0, 0, 0, 1) tmpcr:fill() -- Construct a path for a bunch of random lines going across the -- glyph shape. tmpcr:identity_matrix() local cx, cy = wd / 2, ht / 2 local radius = cx * cx + cy * cy for _ = 1, 15 do local ang = math.random() * 2 * PI local xd, yd = radius * math.cos(ang), radius * math.sin(ang) local xoffset = math.random() * cx - cx / 2 local yoffset = math.random() * cy - cy / 2 tmpcr:move_to(cx + -xd + xoffset, cy + -yd + yoffset) tmpcr:line_to(cx + xd + xoffset, cy + yd + yoffset) end -- Select a 'hair line' width, that is a line which is one pixel -- wide in the output, whatever the font scaling is. Actually, this -- will just use the horizontal distance covered by a pixel, so -- hopefully the pixels are close to being square. tmpcr:set_line_width(cr:device_to_user_distance(1, 1)) -- Remove the ink from the glyph shape wherever the lines pass, leaving -- transparent gaps. tmpcr:set_source_rgba(0, 0, 0, .8) tmpcr:set_operator("dest-out") -- remove ink rather than adding it tmpcr:stroke() -- Use the distorted glyph shape we've constructed to ink in the -- appropriate parts of the output, on the context which Cairo is -- using to create the glyph shape to cache. cr:mask(tmpsurface, glyph_extents.x_bearing, glyph_extents.y_bearing) end local function text_to_glyphs (font, text, want_clusters) -- This just passes the request on to the base font, although we -- have to scale the positions back down to font units, because -- they'll be scaled up to the font size of the base font. local g = basefont:text_to_glyphs(0, 0, text) for i, t in ipairs(g) do t[2] = t[2] / FONT_SIZE t[3] = t[3] / FONT_SIZE end return g end return Cairo.user_font_face_create({ render_glyph = render_glyph, text_to_glyphs = text_to_glyphs, }) end local surface = Cairo.image_surface_create("rgb24", 525, 300) local cr = Cairo.context_create(surface) -- White background. cr:set_source_rgb(1, 1, 1) cr:paint() local x, y = 15, 5 + FONT_SIZE -- Draw lines of text, each in a different colour and font. for _, info in ipairs{ { "Quick brown", { .3, 0, 0 }, { "sans", "normal", "bold" } }, { "fox jumped…", { 0, .3, 0 }, { "serif", "italic" } }, -- The last row won't show up unless you have a font with cuneiform -- characters in. They're just random characters, not meaningful text, -- but a bit more interesting to look at than boring old Latin letters. { "𒀽𒍬𒍅𒌤", { 0, 0, .3 }, { "akkadian" } }, } do -- Create a normal Cairo 'toy' font to use as the base. The glyphs from -- this font will be used with our custom rendering to distort them. local basefont_face = Cairo.toy_font_face_create(unpack(info[3])) local font_mat = Cairo.matrix_create() font_mat:scale(FONT_SIZE, FONT_SIZE) local ctm = Cairo.matrix_create() local basefont = Cairo.scaled_font_create(basefont_face, font_mat, ctm) cr:set_font_face(make_chopped_font(basefont)) cr:set_font_size(FONT_SIZE) local line, color = unpack(info) cr:move_to(x, y) cr:set_source_rgb(unpack(color)) cr:show_text(line) y = y + basefont:extents().height * 1.2 end surface:write_to_png("text-userfont2.png") -- vi:ts=4 sw=4 expandtab
MgrLevel = {} function MgrLevel.Init () end function MgrLevel:Equals (obj) end function MgrLevel:GetHashCode () end function MgrLevel:GetType () end function MgrLevel:ToString () end
-- Reno - Macro Option Toggler -- Tuill of Pagle -- Revisions: -- 0.10 - Initial version, copy of Mutt (by Tuill) source -- 0.11 - Update interface for 3.3 and refresh libs -- 0.12 - Update this revision list, change Curse name to "Reno Macro Patcher" and refresh libs -- 0.13 - Update interface for 4.0x and refresh libs -- 0.14 - Update for 4.3 and refresh libs -- Updated call to EditMacro, now use nil in texture param to keep existing texture -- Updated help text to remove stale Paladin spell examples -- 0.15 - Update for Mists, bump interface and refresh libs -- 0.16 - Update for Thunder King, bump interface and refresh libs -- 0.17 - Bump interface and refresh libs -- 0.18 - Bump interface and refresh libs -- 0.19 - Update for Warlords (6.0), bump interface and refresh libs -- 0.20 - Added 'name' member to Ace3 options table to fix nil error -- Added double call to InterfaceOptionsFrame_OpenToCategory to fix -- glitch where on 1st call that only ESC > Interface frame is shown -- 0.21 - Added a UI group to the config page to help with readability -- Increased font size to medium on config page -- Added button and pop-up for example macro at top of config page for TL;DR -- 0.22 -- Bump interface for 6.2, refresh libs -- 0.23 -- Bump interface for 7.0, refresh libs -- 0.24 -- Bump interface for 7.2, refresh libs -- 0.25 -- Bump interface for 7.3, refresh libs -- 0.26 -- Bump interface for 8.0, refresh libs -- 0.27 -- Bump interface for 8.1, refresh libs, more articulate report of active action -- 0.28 -- Bump interface for 1.13 Classic, refresh libs -- 0.29 -- Fix download archive names, added name tag in pkgmeta -- 0.30 -- Try to correct version # in Twitch client -- 0.31 -- Ibid. -- 0.32 -- Bump interface for 1.13.3 Classic, refresh libs -- 0.33 -- Update example macro, change to markdown changelog, tweak markdown x6 -- 0.34 -- Botched, tag used at Curse repo, but did not update in TOC or source -- 0.35 -- Reconcile version # in TOC, source and at Curseforge -- 0.36 -- Bump interface for 1.13.4 Classic, refresh libs -- 0.37 -- Bump interface for 1.13.5 Classic, refresh libs -- 0.38 -- Bump interface for 1.13.6 Classic, refresh libs -- 0.39 -- Tag to prompt package build after contact w/ Overwolf, refresh libs -- 0.40 -- Migrate to Github from Curse Subversion -- 0.41 -- Bump to prompt package build back at Curse -- 0.42 -- Bump interface for 1.13.7 TBC Classic pre-pre-patch, refresh libs -- 0.43 -- Bump interface for 2.5.2, refresh libs -- All comments by Tuill -- I recommend a Lua-aware editor like SciTE that provides syntactic highlighting. -- No global for now -- local scope identifier for performance and template-ability local ourAddon = LibStub("AceAddon-3.0"):NewAddon("Reno", "AceConsole-3.0") -- local scope identifiers for util functions local strlower = strlower local tonumber = tonumber local string_gsub = string.gsub local table_insert = table.insert -- Fetch version & notes from TOC file local ourVersion = GetAddOnMetadata("Reno", "Version") local ourNotes = GetAddOnMetadata("Reno", "Notes") -- Multi-line string for the help text, color codes inline local helpUsing = [[ More specifically, when given a slash command like this: /reno "macro name" enabled_option ...Reno searches the chosen macro for all occurances of the base macro option of the provided "enabled" option, and edits the macro so that the next occurance of the option is enabled. Most simply: Reno adds and removes "no" from the front of the relevant macro options. Murky enough? Let's try some examples... Examples: |cff999999# Assuming you have a macro named "curse" that looks like:|r /cast [noflying] Curse of Weakness /cast [flying] Curse of Tongues /cast [flying] Curse of Exhaustion |cff999999# By using a Reno command like:|r /reno "curse" noflying |cff999999# ...you would patch the curse macro to look like:|r /cast [flying] Curse of Weakness /cast [noflying] Curse of Tongues /cast [flying] Curse of Exhaustion |cff999999# Reno observes macro options, so you can even do:|r /reno [button:3] "curse" noflying /stopmacro [button:3] /cast [noflying] Curse of Weakness /cast [flying] Curse of Tongues /cast [flying] Curse of Exhaustion |cff999999# ...to have a macro patch itself(!)|r |cffCC8888# WARNING!|r |cff999999 # Be advised! If you try this macro-patching-itself trick, # make absolutely certain that the Reno slash-command is the # first line of the macro, and that you use macro options to # make it mutually-exclusive from the rest of your macro # or else your results will be unpredictable.|r Details: |cff999999 # With successive calls, Reno will rotate through the relevant # options in a round-robin fashion, with the enabled option # being moved later in the macro with each call. With only two # appearances of the option Reno will alternate which option # would be enabled. With more than two appearances Reno will # move the enabled option from earlier appearances to later, # and then "wrap around" to enabling the first again. # Note that what option would be enabled is highly situational, # but still can be chosen with confidence for most macros. As # in the example above, I generally use |rnoflying|cff999999 for the enabled # option for raid-duty macros, since there's no combat flying in # any of the raids I attend. |rgroup|cff999999/|rnogroup|cff999999 should also be an # excellent enabled/disabled option pair for raid macros. |r Caveats: * Reno works by editing macros, and macros can't be edited in combat. * The default WoW macro editing window doesn't understand anything about Reno, so if you run Reno commands with the WoW macro window open you won't see any changes to your macro and WoW will overwrite any of Reno's changes when the window closes. * Reno outputs what it sees to be the enabled macro command based on the enabled option you give it, but understand that it's your environment at macro use-time that determines which commands are truly enabled. * Reno does no checking to verify the options that you provide are valid WoW macro options. |r ]] ourAddon.renoExampleText = [[ #showtooltip /reno [btn:3] pcurse noflying /stopmacro [btn:3] /assist [@mouseover,nodead] /target [@mouseover,harm,nodead,exists] /cast [flying] Curse of Agony() /cast [flying] Curse of the Elements() /cast [noflying] Curse of Shadow() ]] StaticPopupDialogs["RENO_EXAMPLE"] = { text = "Example Macro:", button1 = "OK", OnShow = function (self, data) self.editBox:SetMultiLine(true) self.editBox:SetHeight(150) --self.editBox:GetParent():SetBackdrop(nil) -- Works for entire Dialog self.editBox:DisableDrawLayer("BACKGROUND") self.editBox:SetText(ourAddon.renoExampleText) self.editBox:HighlightText() self:Show() end, hasEditBox = true, hasWideEditBox = true, editBoxWidth = 220, timeout = 0, whileDead = true, hideOnEscape = true, preferredIndex = 3, -- avoid some UI taint, see http://www.wowace.com/announcements/how-to-avoid-some-ui-taint/ } -- Ace3 options table -- RegisterOptionsTable can take a function ref for the options arg -- Taking advantage of this in case we decide to dynamically adjust -- at use-time local function ourOptions() local options = { name = "Reno", type = 'group', args = { general = { type = 'group', name = "Settings", args = { header1 = { order = 1, type = "header", name = "", }, version = { order = 2, type = "description", name = "Version " .. ourVersion .. "\n", }, usage = { type = "group", name = "Usage", desc = "Usage", guiInline = true, order = 3, args = { example = { order = 4, type = "execute", name = "Show Example Macro", desc = "", descStyle = "inline", func = function() StaticPopup_Show("RENO_EXAMPLE") end, }, about = { order = 5, type = "description", name = ourNotes.."\n", fontSize = "medium", }, about2 = { order = 6, type = "description", name = helpUsing, fontSize = "medium", }, }, }, }, }, -- end using }, -- top args } -- end table return options end function ourAddon:OnInitialize() local ourConfig = LibStub("AceConfig-3.0") local ourConfigDialog = LibStub("AceConfigDialog-3.0") -- For snapping into the ESC menu addons list ourConfig:RegisterOptionsTable("Reno", ourOptions) self.optionsFrames = {} self.optionsFrames.general = ourConfigDialog:AddToBlizOptions("Reno", "Reno", nil, "general") -- Create slash commands self:RegisterChatCommand("reno", "SlashHandler") end function ourAddon:SlashHandler(input) -- Show addon config dialog as help if no args, we verify we're not in combat -- so it should be too annoying (better than just a blurt in the chat pane...) if input == "" then if InCombatLockdown() then self:Print("In combat, declining to show Reno help dialog.") else -- Cheeseball fix for issue that 1st call to display Interface > Reno -- frame only showing ESC > Interface menu, so call twice-in-a-row InterfaceOptionsFrame_OpenToCategory(self.optionsFrames.general) InterfaceOptionsFrame_OpenToCategory(self.optionsFrames.general) end else self:RenoHandler(input) end end -- Functions defined in a do block so we could have pseudo-static variables do function ourAddon:RenoHandler(input) input, ourTarget = SecureCmdOptionParse(input) if not input then -- No macro, so stop here -- If we're calling /Reno with macro options, ourArgs will -- be nil in cases where there's no "true" option, so correct -- behavior here is to silently return (do nothing). return end if InCombatLockdown() then self:Print("Can't adjust macros in combat.") return end local slashMacro, slashOpt, slashSuccess, slashOccur if input:find('"') then _, _, slashMacro, slashSuccess = input:find('(%b"")%s+(%S+)') else _, _, slashMacro, slashSuccess = input:find('(%S+)%s+(%S+)') end if not (slashMacro and slashSuccess) then self:Print('Usage: /reno "macro name" successoption') return end slashMacro = slashMacro:gsub('"', "") _, _, slashOpt = slashSuccess:find('^no(%w+)') if not slashOpt then slashOpt = slashSuccess --slashSuccess = "no"..slashSuccess end local macroIndex = GetMacroIndexByName(slashMacro) if macroIndex == 0 then -- Not a WoW macro, so we can't deal with it... self:Print("Can't find macro "..slashMacro.." (is it an add-on macro not a WoW macro..?)") return end -- Get current info from provided macro local ourName, ourTexture, ourMacroBody, isLocal = GetMacroInfo(macroIndex) --self:Print("|cffccccccDEBUG: We got >>|r"..ourTexture.."|cffcccccc<< for the texture of the macro as-was.\n|r") _, slashOccur = ourMacroBody:gsub("[%[,]%s*"..slashSuccess.."[^%]]*%]", "") if slashOccur > 1 then self:Print("|cffffff00Warning|cffcccccc - There is more than one occurance of your success option (|r"..slashSuccess.."|cffcccccc) in macro |r"..slashMacro.."|cffcccccc, Reno's results |rmay not be what you expect.|r") elseif slashOccur == 0 then self:Print("|cffccccccCouldn't find an occurance of base option |r"..slashOpt.."|cffcccccc in macro |r"..slashMacro..' |cffcccccc(Remember to use |r"|cffccccccdouble quotes|r"|cffcccccc if your macro name contains spaces).|r') return end renoCall = {allRenos = {}, ourOpt = "", noCount = 0, innerLoop = false, mt = {}} setmetatable(renoCall, renoCall.mt) renoCall.mt.__index = ourAddon.optBodies renoCall.ourOpt = slashOpt ourMacroBody = ourMacroBody:gsub("%[([^%]]+)%]", renoCall) table.insert(renoCall.allRenos, 1, table.remove(renoCall.allRenos)) renoCall.mt.__index = ourAddon.popNos ourMacroBody = ourMacroBody:gsub("###(%d+)", renoCall) local _, _, activeSlashCmd, activeAction = ourMacroBody:find("(/%w*)%s*[%[,]%s*"..slashSuccess.."[^%]]*%]%s*([^;\n]*)") --self:Print("activeSlashCmd of the active action was: "..activeSlashCmd) self:Print("|cffccccccPatched macro |r"..ourName.."|cffcccccc, looks like active action will be:\n|r"..activeSlashCmd.." "..activeAction) EditMacro(macroIndex, ourName, nil, ourMacroBody, isLocal) --EditMacro(macroIndex, ourName, "INV_MISC_QUESTIONMARK", ourMacroBody, isLocal) end function ourAddon.optBodies(ourCall, ourMatch) if ourCall.innerLoop then ourCall.noCount = ourCall.noCount + 1 ourCall.allRenos[ourCall.noCount] = ourMatch ourCall.innerLoop = false return "###"..ourCall.noCount else local _, _, caught = ourMatch:find("(%w*"..ourCall.ourOpt..")") if caught then ourCall.innerLoop = true return "["..ourMatch:gsub("(%w*"..ourCall.ourOpt..")", ourCall).."]" else return nil end end end function ourAddon.popNos(ourCall, ourMatch) return ourCall.allRenos[tonumber(ourMatch)] end end
local set = vim.opt set.mouse = "a" -- Enable mouse set.syntax = "enable" -- Enable syntax highlighting set.termguicolors = true -- Enable termguicolors set.background = "dark" -- Set dark background set.encoding = "utf-8" -- Encoding set.fileencoding = "utf-8" -- File encoding set.filetype = "on" -- Enable filetype detection set.lazyredraw = true -- Don’t update screen during macro and script execution set.showcmd = true -- Show (partial) command in status line set.cmdheight = 1 -- Status line height set.laststatus = 2 -- Status bar set.scrolloff = 10 -- Display 10 lines above/below the cursor when scrolling with a mouse set.hlsearch = true -- Enable search highlighting set.incsearch = true -- Incremental search that shows partial matches set.ignorecase = true -- Ignore case when searching set.smartcase = true -- Automatically switch search to case-sensitive when search query contains an uppercase letter set.swapfile = false -- Disable swap files set.backup = false -- Disable backups set.number = true -- Show line numbers on the sidebar set.ruler = true -- Always show cursor position set.autoindent = true -- New lines inherit the indentation of previous lines set.tabstop = 2 -- Indent using two spaces set.shiftwidth = 2 -- When shifting, indent using two spaces set.expandtab = true -- Convert tabs to spaces
---@diagnostic disable: undefined-global local palette = require 'nord-palette' local base = require 'base' local clrs = palette.clrs local spec = palette.spec local lang = function() return { sassClass {fg = clrs.nord7}, sassId {fg = clrs.nord7, gui = spec.underline}, sassAmpersand {base.Keyword}, sassClassChar {base.Delimiter}, sassControl {base.Keyword}, sassControlLine {base.Keyword}, sassExtend {base.Keyword}, sassFor {base.Keyword}, sassFunctionDecl {base.Keyword}, sassFunctionName {base.Function}, sassidChar {sassId}, sassInclude {base.SpecialChar}, sassMixinName {base.Function}, sassMixing {base.SpecialChar}, sassReturn {base.Keyword}, } end return lang -- vi:nowrap
---@class one11 ---@field astring string ---@field bnumber number ---@field cany any ---@field dfun fun(a:number, b:number) ---@type one11 local aaaa1 = {} aaaa1.abc = 1 local aaaaa2 = aaaa1 aaaa1.bnumber = 2 aaaa1.astring = "sfs" aaaaa2.bnumber = 2 aaaaa2.astring = "sfs"
local Utils = {} local function tostring2(elem) if type(elem) == "string" then return "'" .. elem .. "'" else return tostring(elem) end end function Utils.printTable(elem, hist, tabs) hist = hist or {} tabs = tabs or 0 if type(elem) ~= "table" then print(tostring2(elem)) else if not hist[elem] then hist[elem] = true print(tostring2(elem) .. " {") tabs = tabs + 1 for i, e in pairs(elem) do io.write(string.rep("\t", tabs) .. "[" .. tostring2(i) .. "] ") Utils.printTable(e, hist, tabs) end tabs = tabs - 1 print(string.rep("\t", tabs) .. "}") else print(tostring2(elem) .. " {...}") end end end return Utils
local oo = require("oo") local ui = { alignment = { front = "front", center = "center", back = "back", }, } autoload(ui, "ui", "Button", "Dialog", "Grid", "Label", "MenuButton", "Screen", "TitleBar", "TopLevel", "Window") --[[ TODO: checkbox slider/scrollbar textbox menubar menu listbox tree? ]] -- *************************************************************************** local Position = oo.class("ui.Position") function Position.new(x, y, self, klass) self = self or {} Position.super.new(self, klass or Position) self.x = x or 1 self.y = y or 1 return self end ui.Position = Position -- *************************************************************************** return ui
AddCSLuaFile() SWEP.Base = "weapon_gwbase" SWEP.Name = "Deflect" SWEP.AbilitySound = "Weapon_StunStick.Activate" SWEP.AbilityDuration = 12 SWEP.AbilityDescription = "Deflects all damage taken to the attacker.\nLasts $AbilityDuration seconds and should probably be called Reflect instead of Deflect." function SWEP:Ability() self:GetOwner():GWSetDeflecting(true) self:AbilityTimerIfValidOwner(self.AbilityDuration, 1, true, function() self:AbilityCleanup() end) end hook.Add("EntityTakeDamage", "gw_deflect_damage", function(target, dmgInfo) local attacker = dmgInfo:GetAttacker() if IsValid(attacker) and attacker:IsPlayer() and IsValid(target) and target:IsPlayer() and target:GWIsDeflecting() then target:SetMaterial("models/props_combine/portalball001_sheet") target:EmitSound(Sound("FX_RicochetSound.Ricochet")) timer.Simple(0.15, function() if IsValid(target) then target:SetMaterial("") end end) if SERVER then attacker:TakeDamage(dmgInfo:GetDamage(), target, target:GetActiveWeapon()) end return true end end ) function SWEP:AbilityCleanup() if IsValid(self:GetOwner()) then self:GetOwner():GWSetDeflecting(false) end end
local hash = KEYS[1]; local key = ARGV[1]; local score = ARGV[2]; local ttlMis = tonumber(ARGV[3]); local existKey = redis.call("EXISTS", hash) > 0; redis.call("ZINCRBY", hash, score, key); if (ttlMis and not existKey) then redis.call("PEXPIRE", hash, ttlMis); end return true;
class("ChallengeShareMediator", import("..base.ContextMediator")).register = function (slot0) slot2 = getProxy(ChallengeProxy):getUserChallengeInfo(slot1) slot0.viewComponent:setLevel(slot2:getLevel()) slot0.viewComponent:setFlagShipPaint(({ regularFleet = slot2:getRegularFleet(), submarineFleet = slot2:getSubmarineFleet() })["regularFleet"]:getShipsByTeam(TeamType.Main, true)[1].getPainting(slot4)) slot5 = {} for slot9, slot10 in ipairs(()["regularFleet"]:getShips(true)) do if slot10.id ~= slot4.id then table.insert(slot5, slot10:getPainting()) end end for slot9, slot10 in ipairs(slot3.submarineFleet:getShips(true)) do if slot10.id ~= slot4.id then table.insert(slot5, slot10:getPainting()) end end slot0.viewComponent:setShipPaintList(slot5) end return class("ChallengeShareMediator", import("..base.ContextMediator"))
--rActionButtonStyler - roth 2009 local _G = _G --------------------------------------- -- CONFIG --------------------------------------- --TEXTURES --default border texture local rb2_normal_texture = "Interface\\AddOns\\rActionButtonStyler\\media\\gloss" --texture when a button flashs --> button becomes ready local rb2_flash_texture = "Interface\\AddOns\\rActionButtonStyler\\media\\flash" --hover textures local rb2_hover_texture = "Interface\\AddOns\\rActionButtonStyler\\media\\hover" --texture if you push that button local rb2_pushed_texture = "Interface\\AddOns\\rActionButtonStyler\\media\\pushed" --texture that is active when the button is in active state (next melee swing attacks mostly) local rb2_checked_texture = "Interface\\AddOns\\rActionButtonStyler\\media\\checked" --texture used for equipped items, this can differ since you may want to apply a different vertexcolor local rb2_equipped_texture = "Interface\\AddOns\\rActionButtonStyler\\media\\gloss" --FONT --the font you want to use for your button texts local button_font = "Fonts\\FRIZQT__.TTF" --hide the hotkey? 0/1 local hide_hotkey = 1 --use dominos? 0/1 local use_dominos = 0 --COLORS --color you want to appy to the standard texture (red, green, blue in RGB) local castcol = { r = 0.6, g = 0.5, b = 0.4, } local bdc = { r = castcol.r*0.2, g = castcol.g*0.2, b = castcol.b*0.2, a = 0.93, } --local color = { r = 0.1, g = 0.1, b = 0.1, } local color = bdc --want class color? just comment in this: --local color = RAID_CLASS_COLORS[select(2, UnitClass("player"))] --color for equipped border texture (red, green, blue in RGB) --local color_equipped = { r = 0, g = 0.5, b = 0, } local color_equipped = bdc --color when out of range local range_color = { r = 0.8, g = 0.1, b = 0.1, } --color when out of power (mana) local mana_color = { r = 0.1, g = 0.3, b = 1, } --color when button is usable local usable_color = { r = 1, g = 1, b = 1, } --color when button is unusable (example revenge not active, since you have not blocked yet) local unusable_color = { r = 0.4, g = 0.4, b = 0.4, } -- !!!IMPORTANT!!! - read this before editing the value blow -- !!!do not set this below 0.1 ever!!! -- you have 120 actionbuttons on screen (most of you have at 80) and each of them will get updated on this timer in seconds -- default is 1, it is needed for the rangecheck -- if you dont want it just set the timer to 999 and the cpu usage will be near zero -- if you set the timer to 0 it will update all your 120 buttons on every single frame -- so if you have 120FPS it will call the function 14.400 times a second! -- if the timer is 1 it will call the function 120 times a second (depends on actionbuttons in screen) local update_timer = 0.5 --------------------------------------- -- CONFIG END --------------------------------------- -- DO NOT TOUCH ANYTHING BELOW! --------------------------------------- -- FUNCTIONS --------------------------------------- --initial style func local function rActionButtonStyler_AB_style(self) local action = self.action local name = self:GetName() local bu = _G[name] local ic = _G[name.."Icon"] local co = _G[name.."Count"] local bo = _G[name.."Border"] local ho = _G[name.."HotKey"] local cd = _G[name.."Cooldown"] local na = _G[name.."Name"] local fl = _G[name.."Flash"] local nt = _G[name.."NormalTexture"] nt:SetHeight(bu:GetHeight()) nt:SetWidth(bu:GetWidth()) nt:SetPoint("Center", 0, 0) bo:Hide() ho:SetFont(button_font, 18, "OUTLINE") co:SetFont(button_font, 18, "OUTLINE") na:SetFont(button_font, 12, "OUTLINE") if hide_hotkey == 1 then ho:Hide() end na:Hide() fl:SetTexture(rb2_flash_texture) bu:SetHighlightTexture(rb2_hover_texture) bu:SetPushedTexture(rb2_pushed_texture) bu:SetCheckedTexture(rb2_checked_texture) bu:SetNormalTexture(rb2_normal_texture) ic:SetTexCoord(0.1,0.9,0.1,0.9) ic:SetPoint("TOPLEFT", bu, "TOPLEFT", 2, -2) ic:SetPoint("BOTTOMRIGHT", bu, "BOTTOMRIGHT", -2, 2) if ( IsEquippedAction(action) ) then bu:SetNormalTexture(rb2_equipped_texture) nt:SetVertexColor(color_equipped.r,color_equipped.g,color_equipped.b,1) else bu:SetNormalTexture(rb2_normal_texture) nt:SetVertexColor(color.r,color.g,color.b,1) end end --style pet buttons local function rActionButtonStyler_AB_stylepet() for i=1, NUM_PET_ACTION_SLOTS do local name = "PetActionButton"..i local bu = _G[name] local ic = _G[name.."Icon"] local fl = _G[name.."Flash"] local nt = _G[name.."NormalTexture2"] nt:SetHeight(bu:GetHeight()) nt:SetWidth(bu:GetWidth()) nt:SetPoint("Center", 0, 0) nt:SetVertexColor(color.r,color.g,color.b,1) fl:SetTexture(rb2_flash_texture) bu:SetHighlightTexture(rb2_hover_texture) bu:SetPushedTexture(rb2_pushed_texture) bu:SetCheckedTexture(rb2_checked_texture) bu:SetNormalTexture(rb2_normal_texture) ic:SetTexCoord(0.1,0.9,0.1,0.9) ic:SetPoint("TOPLEFT", bu, "TOPLEFT", 2, -2) ic:SetPoint("BOTTOMRIGHT", bu, "BOTTOMRIGHT", -2, 2) end end --style shapeshift buttons local function rActionButtonStyler_AB_styleshapeshift() for i=1, NUM_SHAPESHIFT_SLOTS do local name = "ShapeshiftButton"..i local bu = _G[name] local ic = _G[name.."Icon"] local fl = _G[name.."Flash"] local nt = _G[name.."NormalTexture"] nt:ClearAllPoints() nt:SetPoint("TOPLEFT", bu, "TOPLEFT", 0, 0) nt:SetPoint("BOTTOMRIGHT", bu, "BOTTOMRIGHT", 0, 0) nt:SetVertexColor(color.r,color.g,color.b,1) fl:SetTexture(rb2_flash_texture) bu:SetHighlightTexture(rb2_hover_texture) bu:SetPushedTexture(rb2_pushed_texture) bu:SetCheckedTexture(rb2_checked_texture) bu:SetNormalTexture(rb2_normal_texture) ic:SetTexCoord(0.1,0.9,0.1,0.9) ic:SetPoint("TOPLEFT", bu, "TOPLEFT", 2, -2) ic:SetPoint("BOTTOMRIGHT", bu, "BOTTOMRIGHT", -2, 2) end end --fix the grid display --the default function has a bug and once you move a button the alpha stays at 0.5, this gets fixed here local function rActionButtonStyler_AB_fixgrid(button) local name = button:GetName() local action = button.action local nt = _G[name.."NormalTexture"] if ( IsEquippedAction(action) ) then nt:SetVertexColor(color_equipped.r,color_equipped.g,color_equipped.b,1) else nt:SetVertexColor(color.r,color.g,color.b,1) end end --update the button colors onUpdateUsable local function rActionButtonStyler_AB_usable(self) local name = self:GetName() local action = self.action local nt = _G[name.."NormalTexture"] local icon = _G[name.."Icon"] if ( IsEquippedAction(action) ) then nt:SetVertexColor(color_equipped.r,color_equipped.g,color_equipped.b,1) else nt:SetVertexColor(color.r,color.g,color.b,1) end local isUsable, notEnoughMana = IsUsableAction(action) if (ActionHasRange(action) and IsActionInRange(action) == 0) then icon:SetVertexColor(range_color.r,range_color.g,range_color.b,1) return elseif (notEnoughMana) then icon:SetVertexColor(mana_color.r,mana_color.g,mana_color.b,1) return elseif (isUsable) then icon:SetVertexColor(usable_color.r,usable_color.g,usable_color.b,1) return else icon:SetVertexColor(unusable_color.r,unusable_color.g,unusable_color.b,1); return end end --rewrite of the onupdate func --much less cpu usage needed local function rActionButtonStyler_AB_onupdate(self,elapsed) local t = self.rABS_range if (not t) then self.rABS_range = 0 return end t = t + elapsed if (t<update_timer) then self.rABS_range = t return else self.rABS_range = 0 if(not ActionHasRange(self.action)) then return end rActionButtonStyler_AB_usable(self) end end --hotkey func --is only needed when you want to hide the hotkeys and use the default barmod (Dominos does not need this) local function rActionButtonStyler_AB_hotkey(self, actionButtonType) if (not actionButtonType) then actionButtonType = "ACTIONBUTTON"; end local hotkey = _G[self:GetName().."HotKey"] local key = GetBindingKey(actionButtonType..self:GetID()) or GetBindingKey("CLICK "..self:GetName()..":LeftButton"); local text = GetBindingText(key, "KEY_", 1); hotkey:SetText(text); hotkey:Hide() end --------------------------------------- -- CALLS // HOOKS --------------------------------------- hooksecurefunc("ActionButton_Update", rActionButtonStyler_AB_style) hooksecurefunc("ActionButton_UpdateUsable", rActionButtonStyler_AB_usable) --rewrite default onUpdateFunc, the new one uses much less CPU power ActionButton_OnUpdate = rActionButtonStyler_AB_onupdate --fix grid hooksecurefunc("ActionButton_ShowGrid", rActionButtonStyler_AB_fixgrid) --call the special func to hide hotkeys after entering combat with the default actionbar if hide_hotkey == 1 and use_dominos == 0 then hooksecurefunc("ActionButton_UpdateHotkeys", rActionButtonStyler_AB_hotkey) end hooksecurefunc("ShapeshiftBar_OnLoad", rActionButtonStyler_AB_styleshapeshift) hooksecurefunc("ShapeshiftBar_Update", rActionButtonStyler_AB_styleshapeshift) hooksecurefunc("ShapeshiftBar_UpdateState", rActionButtonStyler_AB_styleshapeshift) hooksecurefunc("PetActionBar_Update", rActionButtonStyler_AB_stylepet)
--[[ /////// ////////////////// /////// PROJECT: MTA iLife - German Fun Reallife Gamemode /////// VERSION: 1.7.2 /////// DEVELOPERS: See DEVELOPERS.md in the top folder /////// LICENSE: See LICENSE.md in the top folder /////// ///////////////// ]] local QuestID = 23 local Quest = Quests[QuestID] Quest.Texts = { ["Accepted"] = "Bring dem Regisseur ein Holzbett!", ["Finished"] = "Du hast das Holzbett \\uebergeben!" } for k,v in ipairs(Quest:getPeds(2)) do addEventHandler("onElementClicked", v, function(button, state, thePlayer) if (button == "left") and (state == "down") then local QuestState = thePlayer:isQuestActive(Quest) if (QuestState and not(QuestState == "Finished")) then if (thePlayer:getInventory():removeItem(Items[164], 1)) then thePlayer:refreshInventory() Quest:playerFinish(thePlayer) else thePlayer:showInfoBox("error", "Du besitzt kein Holzbett!") end end end end ) end Quest.playerReachedRequirements = function(thePlayer, bOutput) return true end Quest.getTaskPosition = function() --Should return int, dim, x, y, z return 0, 0, 392.310546875, -1819.76953125, 7.8414235115051 end Quest.onAccept = function(thePlayer) outputChatBox("Regisseur: Wir brauchen dringend ein neues Holzbett f\uer unseren neuen Film!", thePlayer, 255,255,255) outputChatBox("Regisseur: Das alte Holzbett ist leider vor wenigen Minuten zerbrochen..", thePlayer, 255,255,255) outputChatBox("Regisseur: Kannst du schnell ein Neues besorgen?", thePlayer, 255,255,255) return true end Quest.onResume = function(thePlayer) return true end Quest.onProgress = function(thePlayer) return true end Quest.onFinish = function(thePlayer) outputChatBox("Regisseur: Super, du hast das Holzbett dabei.", thePlayer, 255,255,255) return true end Quest.onAbort = function(thePlayer) local QuestState = thePlayer:isQuestActive(Quest) if (QuestState and (QuestState == "Finished")) then thePlayer:getInventory():addItem(Items[164], 1) thePlayer:refreshInventory() end return true end --outputDebugString("Loaded Questscript: server/Classes/Quest/Scripts/"..tostring(QuestID)..".lua")
local Class = {} function Class.new(parent) local class = {} if parent then Class.copy(parent,class) class.parentinit = parent.init else class.static = {} function class:parentinit(arg) end function class:init(arg) end end function class:new(arg) class:init(arg) local obj = {} Class.copy(self,obj) obj.static = self.static --pointert ad át másolás helyett return obj end return class end function Class.copy(t1,t2,szint) szint = szint or 0 for k,v in pairs(t1) do if type(v)=="table" then t2[k]={} Class.copy(v,t2[k],szint+1) else t2[k]=v end end end return Class
-- Written by Zeaga for Zeaga's Community, CrimePanda TTT, and Questionable Ethics -- http://steamcommunity.com/id/zeaga local plymeta = FindMetaTable( "Player" ) function plymeta:IsDonor( ) return self:IsSuperAdmin( ) end if true then return end local Settings = { TitleHeader = "Rank", TitleWidth = 100, TimeHeader = "Playtime", TimeWidth = 100, } hook.Add( "TTTPrepareRound", "ZeagaPrepareRound", function( ) end ) hook.Add( "TTTBeginRound", "ZeagaBeginRound", function( ) end ) hook.Add( "TTTEndRound", "ZeagaEndRound", function( result ) end ) if CLIENT then hook.Add( "TTTScoreboardColorForPlayer", "ZeagaScoreboardColorForPlayer", function( ply ) if ply:IsUserGroup( "exmember" ) and LocalPlayer( ):IsAdmin( ) then return Color( 191, 191, 191 ) end local status = ply:GetFriendStatus( ) if status == "friend" then return Color( 76, 175, 80 ) elseif status == "requested" then return Color( 255, 193, 7 ) elseif status == "blocked" then return Color( 244, 67, 54 ) end --return ZeagaDB.GetColor( ply:GetUserGroup( ) ) end ) hook.Add( "TTTScoreboardColumns", "ZeagaScoreboardColumns", function( pnl ) --[[pnl:AddColumn( Settings.TitleHeader, function( ply, label ) local groupColor = ZeagaDB.GetColor( ply:GetUserGroup( ) ) if groupColor then label:SetTextColor( groupColor ) end return ZeagaDB.GetTitle( ply:GetUserGroup( ) ) end, Settings.TitleWidth )]] --[[pnl:AddColumn( Settings.TimeHeader, function( ply, label ) return timeToHM( ply:GetTotalTime( ) ) end, Settings.TimeWidth )]] end ) hook.Add( "TTTScoreboardMenu", "ZeagaScoreboardMenu", function( menu ) print( true ) end ) hook.Add( "TTTPlayerColor", "ZeagaPlayerColor", function( ) end ) hook.Add( "TTTSettingsTabs", "ZeagaSettingsTabs", function( dtabs ) end ) hook.Add( "TTTEquipmentTabs", "ZeagaEquipmentTabs", function( dtabs ) end ) end
local function press(shortcut) terminal.Shortcut(shortcut, "keyboard") Sleep(50) terminal.Shortcut("-", shortcut, "keyboard") Sleep(50) end GlobalVar("CrashTestMode", false) CrashTestThread = false CrashTestThreadSub = false local function SuspendCrashTest() DeleteThread(CrashTestThread) DeleteThread(CrashTestThreadSub) end function StopCrashTest() CrashTestMode = false SuspendCrashTest() end function StartCrashTest() CrashTestMode = true SuspendCrashTest() CrashTestThread = CreateRealTimeThread(function() assert = empty_func local lims = {cameraRTS.GetZoomLimits()} local shortcuts = {"Escape", "B", "M", "P", "H", "Z", "L", "Y"} local lightmodels = table.keys2(LightmodelPresets) local k = 0 while CrashTestThread == CurrentThread() do local colonists = UICity and #(UICity.labels.Colonist or "") or 0 local speed = Max(10, 100 + (10 - 100) * colonists / 1000) SetTimeFactor(const.DefaultTimeFactor * speed) CrashTestThreadSub = CreateRealTimeThread(function() press("Escape") CloseIngameMainMenu() if terminal.desktop.modal_window ~= terminal.desktop then terminal.desktop.modal_window:Close() Sleep(100) end k = k + 1 press(shortcuts[1 + k % #shortcuts]) Sleep(500) press("Escape") CloseIngameMainMenu() local lightmodel = table.rand(lightmodels) SetLightmodelOverrideDelay(1, lightmodel) local zoom = lims[1 + k % #lims] local follow_obj while CrashTestThreadSub == CurrentThread() do local target = table.rand{"Deposit", "Building", "Movable"} local obj = table.rand(MapGet("map" , target)) if not follow_obj then SelectObj(obj) ViewObjectMars(obj, 300, nil, zoom) end if IsKindOf(obj, "CameraFollowObject") and not obj.camera_follow_disabled and AsyncRand(100) < 50 then SelectObj(obj) Camera3pFollow(obj) follow_obj = obj end Sleep(300) if IsKindOf(obj, "Building") then if IsKindOf(obj, "ConstructionSite") then if not obj.construction_group or obj.construction_group[1] == obj then obj:Complete("quick_build") end elseif obj.destroyed then obj:DestroyedRebuild() elseif #(obj:GetSkins() or "") > 0 and AsyncRand(100) < 20 then obj:CycleSkin() elseif obj.ui_working or not obj:CanDemolish() then obj:SetUIWorking(not obj.ui_working) elseif not obj.demolishing then obj.demolish_return_resources = false obj:ToggleDemolish() end elseif IsKindOf(obj, "BaseRover") then local pos = GetRandomPassable():SetTerrainZ() obj:Goto(pos) end local x, y = GetTerrainCursorXY(UIL.GetScreenSize()/2):xy() local amp = 50*guim local bbox = box(x - amp, y - amp, x + amp, y + amp) terrain.InvalidateType(bbox) RecreateRenderObjects() end end) Sleep(3000) DeleteThread(CrashTestThreadSub) end end) end function OnMsg.DoneMap() StopCrashTest() end function OnMsg.AutosaveStart() SuspendCrashTest() end function OnMsg.AutosaveEnd() if CrashTestMode then StartCrashTest() end end function OnMsg.LoadGame() if CrashTestMode then StartCrashTest() end end
function atm.ensure_init(name) -- Ensure the atm account for the placer specified by name exists atm.readaccounts() if not atm.balance[name] then atm.balance[name] = atm.startbalance end end -- banking accounts storage function atm.readaccounts () local b = atm.balance local file = io.open(atm.pth, "r") if file then repeat local balance = file:read("*n") if balance == nil then break end local name = file:read("*l") b[name:sub(2)] = balance until file:read(0) == nil io.close(file) end end function atm.saveaccounts() if not atm.balance then return end local data = {} for k, v in pairs(atm.balance) do table.insert(data, string.format("%d %s\n", v, k)) end local output = io.open(atm.pth, "w") output:write(table.concat(data)) io.close(output) end -- wire transfer data storage function atm.read_transactions() local file = io.open(atm.pth_wt, "r") if file then local data = file:read("*all") atm.completed_transactions = minetest.deserialize(data) end end function atm.write_transactions() if not atm.completed_transactions then return end local file = io.open(atm.pth_wt, "w") local data = minetest.serialize(atm.completed_transactions) file:write(data) io.close(file) end minetest.register_on_joinplayer(function() atm.readaccounts() end)
local Fmt = require("util/fmt") local Arg = require("util/arg") LLUAR = { NAME = "Lua.lua runtime", VERSION = "0.1.0", INFO = "Copyright (C) 2021 Mayeths", } local lluar_arg = Arg:new("lluar", "The runtime of lua.lua", "-", { param_name = "chunk", unmatched_name = "args" }, { HELP = Arg:boolopt("h", "Print this help"), VERSION = Arg:boolopt("v", "Print current version"), FULLVERSION = Arg:boolopt("V", "Print current version (full)"), OUTPUT = Arg:stropt("o", "Output to specific file", "a.out"), DEBUG_LEVEL = Arg:enumopt( "-debug", "Debug level", "0", {"0", "1", "2", "3"} ), } ) function LLUAR:main() lluar_arg:parse(arg) if lluar_arg.HELP == true then Fmt:println(lluar_arg:tostring()) return elseif lluar_arg.VERSION == true then Fmt:println(LLUAR.VERSION) return elseif lluar_arg.FULLVERSION == true then local arr = { LLUAR.NAME, LLUAR.VERSION, LLUAR.INFO } local msg = table.concat(arr, " ") Fmt:println(msg) return end end LLUAR:main()
hs = {} if obj.status ~= nil then if obj.status.conditions ~= nil then for i, condition in ipairs(obj.status.conditions) do if condition.type == "InvalidSpec" then hs.status = "Degraded" hs.message = condition.message return hs end end end if obj.status.currentPodHash ~= nil then if obj.spec.replicas ~= nil and obj.status.updatedReplicas < obj.spec.replicas then hs.status = "Progressing" hs.message = "Waiting for roll out to finish: More replicas need to be updated" return hs end local verifyingPreview = false if obj.status.verifyingPreview ~= nil then verifyingPreview = obj.status.verifyingPreview end if verifyingPreview and obj.status.blueGreen.previewSelector ~= nil and obj.status.blueGreen.previewSelector == obj.status.currentPodHash then hs.status = "Suspended" hs.message = "The preview Service is serving traffic to the current pod spec" return hs end if obj.status.replicas > obj.status.updatedReplicas then hs.status = "Progressing" hs.message = "Waiting for roll out to finish: old replicas are pending termination" return hs end if obj.status.availableReplicas < obj.status.updatedReplicas then hs.status = "Progressing" hs.message = "Waiting for roll out to finish: updated replicas are still becoming available" return hs end if obj.status.blueGreen.activeSelector ~= nil and obj.status.blueGreen.activeSelector == obj.status.currentPodHash then hs.status = "Healthy" hs.message = "The active Service is serving traffic to the current pod spec" return hs end hs.status = "Progressing" hs.message = "The current pod spec is not receiving traffic from the active service" return hs end end hs.status = "Unknown" hs.message = "Rollout should not reach here. Please file a bug at https://github.com/argoproj/argo-cd/issues/new" return hs
local treat = {} local wraputils = require("wraputils") -- -- Mark a string as binary. It means it no longer -- can be processed from Lua, but it can be -- returned as a main() result as-is. -- -- Binary objects are also auto-encoded to base64 when -- encoding to JSON. -- function treat.as_binary(s, content_type) if type(s) ~= 'userdata' and type(s) ~= 'string' then error("as_binary argument must be a string or a binary object", 2) end return __extras:treat_as_binary(s, content_type) end -- -- Get original string value and a content type of -- a binary object created by treat.as_binary or -- returned by one of Splash methods. -- function treat.as_string(s) if type(s) ~= 'userdata' then return tostring(s) end return __extras:treat_as_string(s) end -- -- Mark a Lua table as an array. Such tables -- will be represented as arrays when encoded to JSON. -- This function modifies its argument inplace. -- function treat.as_array(tbl) -- the same function is available in -- Splash Python code as lua._mark_table_as_array if type(tbl) ~= 'table' or wraputils.is_wrapped(tbl) then error('as_array argument must be a table', 2) end setmetatable(tbl, {__metatable="array"}) return tbl end -- -- Make keys in a Lua table case-insensitive. -- function treat.as_case_insensitive(tbl) local copy = {} local lowercase_copy = {} for k, v in pairs(tbl) do copy[k] = v lowercase_copy[k:lower()] = v end local mt = { __index = function(table, key) return lowercase_copy[key:lower()] end, __newindex = function(table, key, value) rawset(table, key, value) lowercase_copy[key:lower()] = value end } setmetatable(copy, mt) return copy end return treat