content
stringlengths
5
1.05M
Queue = { attempts = {}, banned = {}, bans = {}, connecting = {}, whitelist = {}, } --[[ Functions ]]-- function Queue:Init() self.banned.tokens = {} -- Cache bans. local bans = exports.GHMattiMySQL:QueryResult("SELECT * FROM `bans` WHERE `unbanned`=0") for index, row in ipairs(bans) do self:AddBan(row) end -- Cache users. local users = exports.GHMattiMySQL:QueryResult("SELECT * FROM `users` WHERE `priority`>-128") for index, row in ipairs(users) do if row.steam then self.whitelist[row.steam] = true end end -- Final init. self.init = true end function Queue:AddBan(info) local index = #self.bans + 1 -- Update identifiers. for __, key in ipairs(Server.Identifiers) do local value = info[key] if value ~= nil then if self.banned[key] == nil then self.banned[key] = {} end self.banned[key][value] = index end end -- Update tokens. local tokens = info.tokens if tokens ~= nil then tokens = json.decode(tokens) for _, token in ipairs(tokens) do self.banned.tokens[token] = index end end -- Get end time. local endTime = (info.duration == 0 and 0) or (info.start_time / 1000.0 + info.duration * 3600.0) info.endTime = endTime -- Cache ban. self.bans[index] = info end function Queue:RemoveBan(info) for key, value in pairs(info) do local banned = self.banned[key] if banned then local index = banned[value] if index then self.bans[index] = nil self.banned[key][value] = nil end end end end function Queue:Connect(source, name, setKickReason, deferrals) -- Update deferral. deferrals.update("Connecting...") deferrals.defer() Citizen.Wait(0) -- Get endpoint. local endpoint = GetPlayerEndpoint(source) if not endpoint then print(("no endpoint for [%s]"):format(source)) return end -- Check tries. local tries = self.attempts[endpoint] or 0 if tries > Server.MaxTries then deferrals.done(Server.Deferrals.Blocked) return false end -- Update tries. tries = tries + 1 self.attempts[endpoint] = tries -- Basic log. print(("Checking %s"):format(endpoint)) -- Get data. local data = Main:GetData(source) -- Check bans. local banTime, banReason = self:GetBanned(data.identifiers, data.tokens) if banTime == 0 then deferrals.done(Server.Deferrals.BannedForever:format(banReason or "No reason specified")) return false elseif banTime then deferrals.done(Server.Deferrals.Banned:format(banReason or "No reason specified", math.floor(banTime / 3600.0), math.floor(banTime / 3600.0 % 1.0 * 60.0))) return false end -- Check identifiers. for key, text in pairs(Server.Deferrals.Licenses) do if data.identifiers[key] == nil then deferrals.done(text) return false end end -- Check whitelist. if Server.EnableWhitelist then if not self.whitelist[data.identifiers.steam] then deferrals.done(Server.Deferrals.Whitelist) return false end end -- Check name. if name:gsub("[\128-\255]", "") ~= name then deferrals.done(Server.Deferrals.InvalidName) return false end -- Create user. local user = User:Create(data) if not user then deferrals.done(Server.Deferrals.UserFailed) return false end -- Set deferral. user.deferrals = deferrals -- Add to queue. local waitingCount = #self.connecting local position = waitingCount + 1 local priority = self.priority or 0 for k, queued in ipairs(self.connecting) do if priority > (queued.priority or -1) then position = k end end print(("Queue: %s@steam:%s@ip:%s joined - position %s/%s"):format(data.identifiers.name or "?", data.identifiers.steam or "?", data.identifiers.endpoint or "?", position, waitingCount + 1)) table.insert(self.connecting, position, user) -- Finish. deferrals.update("Waiting for queue...") end function Queue:Update() local waitingCount = #self.connecting -- Get random emoji. math.randomseed(math.floor(os.clock() * 1000)) local emoji = Server.Emoji[math.random(1, #Server.Emoji)] -- Update queue. for position = #self.connecting, 1, -1 do local user = self.connecting[position] local lastMsg = GetPlayerLastMsg(user.source) if lastMsg > 60000 then table.remove(self.connecting, position) print(("Queue: steam:%s removed - position %s/%s"):format(user.identifiers.steam, position, waitingCount)) user.deferrals.done(Server.Deferrals.Timeout) else user.deferrals.update(("Your position in queue: %s/%s — %s"):format(position, waitingCount, emoji)) end end -- Get first user. local user = self.connecting[1] if user == nil then return end -- Check players. local playerCount = GetNumPlayerIndices() local maxPlayers = GetConvarInt("sv_maxClients", 1) if playerCount >= maxPlayers then return end -- Let user in. user.deferrals.done() print(("Queue: %s@steam:%s@ip:%s connected"):format(user.identifiers.name or "?", user.identifiers.steam or "?", user.identifiers.endpoint or "?")) table.remove(self.connecting, 1) end function Queue:Count() return #self.connecting end function Queue:CheckBan(index) local banned = self.bans[index or false] if banned ~= nil and (banned.endTime == 0 or (banned.endTime or 0) > os.time()) then return (banned.endTime == 0 and 0) or (banned.endTime - os.time()), banned.reason end end function Queue:GetBanned(identifiers, tokens) -- Check identifiers. for _, key in ipairs(Server.Identifiers) do local value = identifiers[key] if value ~= nil and self.banned[key] ~= nil then local timeLeft, reason = self:CheckBan(self.banned[key][value]) if timeLeft ~= nil then return timeLeft, reason end end end -- Check tokens. for _, token in ipairs(tokens) do local timeLeft, reason = self:CheckBan(self.banned.tokens[token]) if timeLeft ~= nil then return timeLeft, reason end end -- Not banned. return false end --[[ Events ]]-- AddEventHandler(Main.event.."start", function() Queue:Init() end) AddEventHandler("playerConnecting", function(name, setKickReason, deferrals) local source = source Queue:Connect(source, name, setKickReason, deferrals) end) --[[ Threads ]]-- Citizen.CreateThread(function() while true do Queue:Update() Citizen.Wait(2000) end end) --[[ Commands ]]-- RegisterCommand("togglequeue", function(source, args, rawcommand) if source ~= 0 then return end Server.EnableWhitelist = not Server.EnableWhitelist print("Queue "..(Server.EnableWhitelist and "enabled" or "disabled").."!") end, true)
-- Imugi Show Hide Window With Command -- William R. Good 03-22-19 if not SUPPORTS_FLOATING_WINDOWS then -- to make sure the script doesn't stop old FlyWithLua versions logMsg("imgui not supported by your FlyWithLua version") return end function ishwwc_on_build(ishwwc_wnd, x, y) imgui.TextUnformatted("This is a test window") end ishwwc_wnd = nil function ishwwc_show_wnd() ishwwc_wnd = float_wnd_create(640, 480, 1, true) float_wnd_set_title(ishwwc_wnd, "Imgui Show Hide Window With Command") float_wnd_set_imgui_builder(ishwwc_wnd, "ishwwc_on_build") end function ishwwc_hide_wnd() if ishwwc_wnd then float_wnd_destroy(ishwwc_wnd) end end ishwwc_show_only_once = 0 ishwwc_hide_only_once = 0 function toggle_imgui_show_hide_window_with_command() ishwwc_show_window = not ishwwc_show_window if ishwwc_show_window then if ishwwc_show_only_once == 0 then ishwwc_show_wnd() ishwwc_show_only_once = 1 ishwwc_hide_only_once = 0 end else if ishwwc_hide_only_once == 0 then ishwwc_hide_wnd() ishwwc_hide_only_once = 1 ishwwc_show_only_once = 0 end end end add_macro("Imgui Show Hide Window With Command: open/close", "ishwwc_show_wnd()", "ishwwc_hide_wnd()", "deactivate") create_command("FlyWithLua/imgui-show-hide-window-with-command/show_toggle", "open/close umgui show hide window", "toggle_imgui_show_hide_window_with_command()", "", "")
-- *************************************************************** -- -- Copyright 2017 by Sean Conner. All Rights Reserved. -- -- This library is free software; you can redistribute it and/or modify it -- under the terms of the GNU Lesser General Public License as published by -- the Free Software Foundation; either version 3 of the License, or (at your -- option) any later version. -- -- This library 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 Lesser General Public -- License for more details. -- -- You should have received a copy of the GNU Lesser General Public License -- along with this library; if not, see <http://www.gnu.org/licenses/>. -- -- Comments, questions and criticisms can be sent to: sean@conman.org -- -- ******************************************************************** -- luacheck: globals null -- luacheck: ignore 611 local lpeg = require "lpeg" local utf8 if _VERSION < "Lua 5.3" then local char = require "string".char local floor = require "math".floor local select = select utf8 = { char = function(...) local function onechar(n) if n < 0x80 then return char(n) elseif n < 0x800 then return char( floor(n / 2^6) + 0xC0, (n % 0x40) + 0x80 ) else return char( (floor(n / 2^12) + 0xE0), (floor(n / 2^ 6) % 0x40) + 0x80, (n % 0x40) + 0x80 ) end end local res = "" for i = 1 , select('#',...) do local c = select(i,...) res = res .. onechar(c,16) end return res end } else utf8 = require "utf8" end -- ******************************************************************** local jsonS do local Cc = lpeg.Cc local Cp = lpeg.Cp local Cs = lpeg.Cs local Ct = lpeg.Ct local P = lpeg.P local R = lpeg.R local S = lpeg.S local int = P"0" + R"19" * R"09"^0 local frac = P"." * R"09"^1 local exp = S"Ee" * S"+-"^-1 * R"09"^1 local number = (P"-"^-1 * int * frac^-1 * exp^-1) / tonumber local unescaped = R(" !","#[","]~","\128\255") local char = unescaped + P[[\"]] / [["]] + P[[\\]] / [[\]] + P[[\b]] / "\b" + P[[\f]] / "\f" + P[[\n]] / "\n" + P[[\r]] / "\r" + P[[\t]] / "\t" + P[[\/]] / "/" + P[[\u]] * ( R("09","AF","af") * R("09","AF","af") * R("09","AF","af") * R("09","AF","af") ) / function(c) return utf8.char(tonumber(c:sub(3,-1),16)) end local string = P'"' * Cs(char^0) * P'"' local ws = S"\t\r\n "^0 local array = ws * P"[" * ws * #P(1) local object = ws * P"{" * ws * #P(1) local NAME = ws * P":" * ws * #P(1) local VALUE = ws * P"," * ws * #P(1) local ARRAY = ws * P"]" * ws local OBJECT = ws * P"}" * ws jsonS = Cc('string') * string * Cp() + Cc('number') * number * Cp() * #(VALUE + ARRAY + OBJECT) + P'false' * Cc('boolean') * Cc(false) * Cp() + P'true' * Cc('boolean') * Cc(true) * Cp() + P'null' * Cc('null') * Cc(null) * Cp() + array * Cc('array') * Ct("") * Cp() + object * Cc('object') * Ct("") * Cp() + ARRAY * Cc('ARRAY') * Cc(nil) * Cp() + OBJECT * Cc('OBJECT') * Cc(nil) * Cp() + NAME * Cc('NAME') * Cc(nil) * Cp() + VALUE * Cc('VALUE') * Cc(nil) * Cp() end -- ********************************************************************** -- Usage: json = jsonS:match(fundat) -- Desc: Return a Lua table populated from JSON data. This uses -- a streaming method that is more resource lean than my -- other JSON decoder. -- Input: fundat(string function) if a string, JSON encoded data. -- | if a function, it should return the next chunk -- | to parse; otherwise it should return nil or an -- | empty string to indicate no more data. -- Return: json (table) JSON data parsed as Lua data. -- -- Note: The JSON "null" value will be returned as a Lua nil. If -- you want a custom null value, define a global variable -- named "null" with the sentinel value you want. -- -- Always returning a single character from fundat() will -- cause issues with parsing. -- ********************************************************************** local function match(_,fundat) -- ----------------------------------------------------------------------- -- To be a drop-in replacement for my original JSON decoder, the fundat -- parameter can be a string. If it is, then replace it with a function -- that just returns said string. Otherwise, we have a function that will -- return the next chunk of data to read. -- ----------------------------------------------------------------------- if type(fundat) == 'string' then local data = fundat fundat = function() local d = data data = nil return d end end local data local pos local result local okay local array -- forward function reference local object -- forward function reference -- ----------------------------------------------------------------------- local function next_token(list) local token,val,newpos = jsonS:match(data,pos) if not token then local new = fundat() if new == nil or new == "" then error "parse" end data = data:sub(pos,-1) .. new pos = 1 return next_token(list) else for _,isthis in ipairs(list) do if isthis == token then return token,val,newpos end end error "parse" end end -- ----------------------------------------------------------------------- -- JSON arrays and objects are mapped to Lua tables. During processing, -- the current array/object is stored in result. To help keep track of -- things, the following are temporarily stored during processing: -- -- result[false] -> parent node -- result[true] -> function to call for processing next token -- -- They are removed once an array/object is finished processing. -- ----------------------------------------------------------------------- local function insert_list(token,key,value,resume) result[key] = value result[true] = resume if token == 'array' then value[false] = result value[true] = array result = value elseif token == 'object' then value[false] = result value[true] = object result = value end return result[true]() end -- ----------------------------------------------------------------------- local end_list do -- --------------------------------------------------------- -- Sigh---the things I do to follow the letter of the spec. -- --------------------------------------------------------- local SPACE = lpeg.S"\t\r\n "^0 * lpeg.P(-1) local function drain(d) local extra = fundat() if not extra or extra == "" then return d else return drain(d .. extra) end end end_list = function() local parent = result[false] result[true] = nil result[false] = nil result = parent or result if not parent then if pos > #data then local extra = drain("") if SPACE:match(extra) then return result end end return nil else return result[true]() end end end -- ----------------------------------------------------------------------- local token local value local function array_value() token,value,pos = next_token { 'ARRAY' , 'VALUE' } if token == 'ARRAY' then return end_list() else assert(token == 'VALUE') token,value,pos = next_token { 'string' , 'number' , 'boolean' , 'null' , 'array' , 'object' } return insert_list(token,#result + 1,value,array_value) end end array = function() token,value,pos = next_token { 'string' , 'number' , 'boolean' , 'null' , 'array' , 'object' , 'ARRAY' } if token == 'ARRAY' then return end_list() end return insert_list(token,#result + 1,value,array_value) end -- ----------------------------------------------------------------------- local function object_value() token,value,pos = next_token { 'VALUE','OBJECT'} if token == 'OBJECT' then return end_list() else assert(token == 'VALUE') token,value,pos = next_token { 'string' } local name = value token,value,pos = next_token { 'NAME' } token,value,pos = next_token { 'string' , 'number' , 'boolean' , 'null' , 'array' , 'object' } return insert_list(token,name,value,object_value) end end object = function() token,value,pos = next_token { 'string' , 'OBJECT' } if token == 'OBJECT' then return end_list() end local name = value token,value,pos = next_token { 'NAME' } token,value,pos = next_token { 'string' , 'number' , 'boolean' , 'null' , 'array' , 'object' } return insert_list(token,name,value,object_value) end -- ------------------------------------------------------------------ okay,result = pcall(function() data = fundat() pos = 1 if data == nil or data == "" then return nil end token,result,pos = next_token { 'array' , 'object' } if token == 'array' then return array() elseif token == 'object' then return object() end end) return okay and result or nil end -- ********************************************************************** return { match = match }
local eventName = "garageBreakVehicles" local function CreateEvent() local function StartTouch(ent, chance) if not ent:IsVehicle() or CGM13.Vehicle:IsBroken(ent) then return end if math.random(1, 100) <= chance then timer.Simple(math.random(2, 6), function() if not ent:IsValid() then return end CGM13.Vehicle:Break(ent, true) if math.random(1, 100) <= 50 then local explo = ents.Create("env_explosion") explo:SetPos(ent:GetPos()) explo:Spawn() explo:Fire("Explode") explo:SetKeyValue("IMagnitude", 20) ent:Ignite(15, 30) end end) end end local breakVehiclesGarage = ents.Create("gm13_trigger") breakVehiclesGarage:Setup(eventName, "breakVehiclesGarage", Vector(-2809.4, -1064.7, 207.9), Vector(-1056.9, -1919, -143.9)) local breakVehiclesDarkroom = ents.Create("gm13_trigger") breakVehiclesDarkroom:Setup(eventName, "breakVehiclesDarkroom", Vector(-5252.1, -2571.6, 138.1), Vector(-3263.6, -1071.8, -102.9)) function breakVehiclesGarage:StartTouch(ent) StartTouch(ent, 40) end function breakVehiclesDarkroom:StartTouch(ent) StartTouch(ent, 75) end return true end GM13.Event:SetCall(eventName, CreateEvent)
local F, C, L = unpack(select(2, ...)) local module = F:GetModule("Misc") local menuFrame = CreateFrame("Frame", "aSettingsMarkingFrame", UIParent, "UIDropDownMenuTemplate") local menuList = { {text = "Clear", func = function() SetRaidTarget("target", 0) end}, {text = "Skull", func = function() SetRaidTarget("target", 8) end}, {text = "|cffff0000Cross|r", func = function() SetRaidTarget("target", 7) end}, {text = "|cff00ffffSquare|r", func = function() SetRaidTarget("target", 6) end}, {text = "|cffC7C7C7Moon|r", func = function() SetRaidTarget("target", 5) end}, {text = "|cff00ff00Triangle|r", func = function() SetRaidTarget("target", 4) end}, {text = "|cff912CEEDiamond|r", func = function() SetRaidTarget("target", 3) end}, {text = "|cffFF8000Circle|r", func = function() SetRaidTarget("target", 2) end}, {text = "|cffffff00Star|r", func = function() SetRaidTarget("target", 1) end}, } function module:Marker() if not C.general.marker then return end WorldFrame:HookScript("OnMouseDown", function(self, button) if button == "LeftButton" and IsAltKeyDown() and UnitExists("mouseover") then local inRaid = IsInRaid() if (inRaid and (UnitIsGroupLeader("player") or UnitIsGroupAssistant("player"))) or not inRaid then EasyMenu(menuList, menuFrame, "cursor", 0, 0, "MENU", 1) end end end) end
local class = require "utils.class" local OrderQueue = class({}) -- table.unpack = table.unpack or unpack; -- table.pack = table.pack or function(...) return {...} end function OrderQueue:_init_() self.queue = {} self.notify = {} end function OrderQueue:Pop(order) local o = self.queue[1]; if o and o.order <= order then table.remove(self.queue, 1) -- print("%d %s", o.tick, o.event); return o.order, o.event, o.data; end end function OrderQueue:Append(order, event, data) local o = {order = order, event = event, data = data } self:Add(o); end function OrderQueue:Add(o) local n = #self.queue; for i = n, 1, -1 do local v = self.queue[i]; if v.order <= o.order then return self:insert(i+1, o) end end self:insert(1, o) end function OrderQueue:insert(k, o) table.insert(self.queue, k, o) end return OrderQueue;
return { name = "james2doyle/rndm", version = "0.0.2", description = "random string generator", tags = { "rndm", "random", "string", "generator" }, license = "MIT", author = { name = "james2doyle", email = "james2doyle@gmail.com" }, homepage = "https://github.com/james2doyle/lit-rndm", dependencies = { "luvit/buffer@1.0.1-3" }, files = { "**.lua", "!test.lua" } }
-- prints to stdout file ready to be `require`d in your game local file = arg[1] if not file then print("usage: lua " .. arg[0] .. " ./tiles_list") os.exit() end local data = {} local fmt = ' %s = { x=%d, y=%d, w=%d, h=%d, animLen=%d, isAnim=%s },' local tn = tonumber local fp, err = io.open(arg[1], 'r') if not fp then print(err) os.exit() end local pattern = '([a-z_]+)' .. (' ([0-9]+)'):rep(4) .. ' *([0-9+]?)' for line in fp:lines() do --local name, x, y, w, h, anim_len = line:match('([a-z_]+)') local name, x, y, w, h, animLen = line:match(pattern) if name then data[#data+1] = fmt:format( name, tn(x), tn(y), tn(w), tn(h), tn(animLen == '' and 1 or animLen), animLen ~= '') end end fp:close() table.sort(data) io.write('return {\n', table.concat(data, '\n'), '\n}\n')
--[[Author: Pizzalol Date: 11.01.2015. Checks if it is night time to see if it should apply the night modifier If it is day then it removes it if the caster has the night modifier]] function HunterInTheNight( keys ) local caster = keys.caster local ability = keys.ability local modifier = keys.modifier if not GameRules:IsDaytime() then ability:ApplyDataDrivenModifier(caster, caster, modifier, {}) else if caster:HasModifier(modifier) then caster:RemoveModifierByName(modifier) end end end
Zones = { { Coords = vector3(229.4284, -418.1848, 48.09515), Radius = 0.8, }, { Coords = vector3(236.0107, -420.9793, 48.09515), Radius = 0.8, }, { Coords = vector3(1843.076, 2585.989, 46.01429), Radius = 1.0, }, { Coords = vector3(1834.164, 2594.318, 46.0143), Radius = 1.0, }, }
require("config") require("framework.init") -- define global module game = {} function game.startup() game.showDemoScene() end function game.exit() --cc.Director:getInstance():endToLua() os.exit() end function game.showDemoScene() display.replaceScene(require("MainScene").new(), "fade", 0.6, display.COLOR_WHITE) end
-- Safe Data Store -- Crazyman32 -- February 3, 2017 --[[ Works exactly like the real DataStore. safeDataStore.Failed(method, key, errorMessage) --]] local SafeDataStore = {} SafeDataStore.__index = SafeDataStore local MAX_ATTEMPTS = 5 local ATTEMPT_INTERVAL = 2 local dataStoreService = game:GetService("DataStoreService") if (game.PlaceId == 0) then dataStoreService = require(script.Parent:WaitForChild("MockDataStoreService")) end local modulesFolder = game:GetService("ReplicatedStorage"):WaitForChild("Aero"):WaitForChild("Modules") local Aero = require(modulesFolder:WaitForChild("Aero")) -- Map DataStoreService methods to associated RequestTypes: local requestTypes = { GetAsync = Enum.DataStoreRequestType.GetAsync; SetAsync = Enum.DataStoreRequestType.SetIncrementAsync; RemoveAsync = Enum.DataStoreRequestType.SetIncrementAsync; OnUpdate = Enum.DataStoreRequestType.OnUpdate; IncrementAsync = Enum.DataStoreRequestType.SetIncrementAsync; } local function GetBudget(method) return dataStoreService:GetRequestBudgetForRequestType(requestTypes[method]) end function SafeDataStore.new(name, scope) local self = setmetatable({ DataStore = dataStoreService:GetDataStore(name, scope); }, SafeDataStore) self.Failed = Aero.Event.new() return self end function SafeDataStore:Try(method, k, v) local budget = GetBudget(method) if (budget == 0) then -- Do something in later implementation end local value = nil for i = 1,MAX_ATTEMPTS do local success success, v = pcall(function() return self.DataStore[method](self.DataStore, k, v) end) if (success) then value = v break elseif (i == MAX_ATTEMPTS) then warn("DataStore " .. method .. " failed: " .. tostring(v)) self.Failed:Fire(method, k, tostring(v)) else wait(ATTEMPT_INTERVAL) end end return value end function SafeDataStore:OnUpdate(key, callback) return self.DataStore:OnUpdate(key, callback) end function SafeDataStore:GetAsync(key) return self:Try("GetAsync", key) end function SafeDataStore:IncrementAsync(key, delta) return self:Try("IncrementAsync", key, delta) end function SafeDataStore:SetAsync(key, value) return self:Try("SetAsync", key, value) end function SafeDataStore:RemoveAsync(key) return self:Try("RemoveAsync", key) end function SafeDataStore:UpdateAsync(key, transformFunction) return self:Try("UpdateAsync", key, transformFunction) end return SafeDataStore
if not matches[2] then dx.mining:showConfigs() return end local val = matches[4] if val == "true" or val == "yes" or val == "on" then val = true end if val == "false" or val == "no" or val == "off" then val = false end local numberVal = tonumber(val) val = numberVal and numberVal or val dx.mining:toggle(matches[3], val)
--[[local spam = {} function antiSpam() if (spam[source]) then spam[source] = 1 elseif (spam[source] >= 5) then cancelEvent() exports.UDCdx:new(source, "Refrain from command spamming, please") else spam[source] = spam[source] + 1 end end addEventHandler("onPlayerCommand", root, antiSpam) function clearAntiSpam() spam = {} end setTimer(clearAntiSpam, 1000, 0) --]]
-- ======================================================================================= -- Plugin: fileFinder.lua -- Programmer: Cooper Santillan -- Last Modified: October 18, 2021 10:10am -- ======================================================================================= -- Description: Find files in determined path (and ALL subfolders) in search for all -- files with certain extension. Only works for onPC systems. -- ======================================================================================= -- ======================================================================================= -- ==== MAIN: fileFinder ================================================================= -- ======================================================================================= -- https://stackoverflow.com/questions/1426954/split-string-in-lua local function mysplit (inputstr, sep) if sep == nil then sep = "%s" end local t={} for str in string.gmatch(inputstr, "([^"..sep.."]+)") do table.insert(t, str) end return t end -- https://stackoverflow.com/questions/1410862/concatenation-of-tables-in-lua local function TableConcat(t1,t2) for i=1,#t2 do t1[#t1+1] = t2[i] end return t1 end local function tableCat(t1, t2) if t1 == nil then return t2 end for k,v in pairs(t2) do t1[k] = v end return t1 end -- purpose: append the path to a batch of files in table local function tableAppend(t1, descript) local t2 = {} for i=1, #t1 do t2[t1[i]] = descript end return t2 end local function fileFinder(path, ext) local aFiles = {} local luas = io.popen("dir \"" ..path .."\\*." ..ext .."\" /b") --finds all files with this extension in folder if luas then aFiles = luas:read("*a") aFiles = mysplit(aFiles) if (aFiles ~= nil) then aFiles = tableAppend(aFiles, path) end local newDir = io.popen("dir \"" ..path .."\" /b /ad") --finds all folders in the directory if newDir then local newDirRead = newDir:read("*a") if newDirRead ~= "" then local dirTable = mysplit(newDirRead) for i=1, #dirTable do aFiles = tableCat(aFiles, fileFinder(path .."\\"..dirTable[i], ext)) end end end end return aFiles end local caller = select(2,...):gsub("%d+$", "") -- label of the plugin local callerNumber = select(2,...):match("%d+$") -- number of the plugin local function foo() local pluginPath = gma.show.getvar("PLUGINPATH") local githubFolder = "gma2-maker" local f = fileFinder(pluginPath .."\\" ..githubFolder, "lua") -- returns a table of all lua files local c = callerNumber + 1 -- gma2 doesn't want to use this command :/ -- for k, v in pairs(f) do -- gma.cmd("Import \"" ..k .."\" At Plugin " ..c .." /nc /p=\"" ..v .."\"") -- c = c + 1 -- end end return foo -- ======================================================================================= -- ==== END OF fileFinder ================================================================ -- =======================================================================================
local Popup = require("nui.popup") local Text = require("nui.text") local defaults = require("nui.utils").defaults local is_type = require("nui.utils").is_type local event = require("nui.utils.autocmd").event local function init(class, popup_options, options) popup_options.enter = true popup_options.buf_options = defaults(popup_options.buf_options, {}) popup_options.buf_options.buftype = "prompt" if not is_type("table", popup_options.size) then popup_options.size = { width = popup_options.size, } end popup_options.size.height = 1 local self = class.super.init(class, popup_options) local props = { default_value = defaults(options.default_value, ""), prompt = Text(defaults(options.prompt, "")), } self.input_props = props props.on_submit = function(value) local prompt_normal_mode = vim.fn.mode() == "n" self:unmount() vim.schedule(function() if prompt_normal_mode then -- NOTE: on prompt-buffer normal mode <CR> causes neovim to enter insert mode. -- ref: https://github.com/neovim/neovim/blob/d8f5f4d09078/src/nvim/normal.c#L5327-L5333 vim.api.nvim_command("stopinsert") end if options.on_submit then options.on_submit(value) end end) end props.on_close = function() self:unmount() vim.schedule(function() if vim.fn.mode() == "i" then vim.api.nvim_command("stopinsert") end if options.on_close then options.on_close() end end) end if options.on_change then props.on_change = function() local value_with_prompt = vim.api.nvim_buf_get_lines(self.bufnr, 0, 1, false)[1] local value = string.sub(value_with_prompt, props.prompt:length() + 1) options.on_change(value) end end return self end local Input = setmetatable({ name = "Input", super = Popup, }, { __index = Popup.__index, }) function Input:init(popup_options, options) return init(self, popup_options, options) end function Input:mount() local props = self.input_props self.super.mount(self) if props.on_change then vim.api.nvim_buf_attach(self.bufnr, false, { on_lines = props.on_change, }) end if #props.default_value then self:on(event.InsertEnter, function() vim.api.nvim_feedkeys(props.default_value, "n", false) end, { once = true }) end vim.fn.prompt_setprompt(self.bufnr, props.prompt:content()) if props.prompt:length() > 0 then vim.schedule(function() props.prompt:highlight(self.bufnr, self.ns_id, 1, 0) end) end vim.fn.prompt_setcallback(self.bufnr, props.on_submit) vim.fn.prompt_setinterrupt(self.bufnr, props.on_close) vim.api.nvim_command("startinsert!") end local InputClass = setmetatable({ __index = Input, }, { __call = init, __index = Input, }) return InputClass
mg.write("HTTP/1.0 200 OK\r\n") mg.write("Content-Type: text/html\r\n") mg.write("\r\n") mg.write([[<html><body> <p>This is Lua script example 2, served by the <a href="https://github.com/civetweb/civetweb">CivetWeb web server</a>, version ]] .. mg.version .. [[. </p><p> The following features are available: <ul> ]]) demo_data_for_xml = {} demo_data_for_json = {} function print_if_available(tab, name) if tab then mg.write("<li>" .. name .. " available</li>\n") if type(tab)=="table" then demo_data_for_xml[name] = {} demo_data_for_xml[name][0] = name demo_data_for_json[name] = {} for nname,nval in pairs(tab) do demo_data_for_xml[name][nname] = type(nval) demo_data_for_json[name][nname] = type(nval) end else demo_data_for_xml[name] = type(tab) demo_data_for_json[name] = type(tab) end else mg.write("<li>" .. name .. " not available</li>\n") end end function recurse(tab, excl) excl = excl or {} mg.write("<ul>\n") for k,v in pairs(tab) do if type(v) == "table" then mg.write("<li>" .. tostring(k) .. ":</li>\n") if excl[v] then -- cyclic else excl[v] = true recurse(v, excl) excl[v] = false end else mg.write("<li>" .. tostring(k) .. " = " .. tostring(v) .. "</li>\n") end end mg.write("</ul>\n") end -- Print Lua version and available libraries mg.write("<li>" .. _VERSION .. " with the following standard libraries</li>\n") mg.write("<ul>\n") libs = {"string", "math", "table", "io", "os", "bit32", "utf8", "package", "coroutine", "debug"}; for _,n in ipairs(libs) do print_if_available(_G[n], n); end mg.write("</ul>\n") print_if_available(sqlite3, "SQLite3 binding (sqlite3)") print_if_available(lfs, "LuaFileSystem (lfs)") print_if_available(json, "JSON binding (json)") print_if_available(xml, "LuaXML (xml)") print_if_available(shared, "Lua shared data (shared)") --recurse(_G) -- Print mg library libname = "mg" print_if_available(_G[libname], libname .. " library") recurse(_G[libname]) -- Print connect function print_if_available(connect, "connect function") -- Get all server options mg.write("<li>server options</li>\n") recurse(mg.get_option()) -- Print some data from random generators if mg.uuid then mg.write("<li>random data</li>\n") local t = {GUID = mg.uuid(), random = mg.random()} recurse(t) end -- Print loaded packages known to Lua if package and (type(package.loaded)=="table") then if #package.loaded > 0 then mg.write("<li>loaded packages</li>\n") recurse(package.loaded) else mg.write("<li>loaded packages: none</li>\n") end end -- Load path mg.write("<li>Package search path: " .. package.path .. "</li>\n"); -- End of list mg.write("</ul></p>\n"); -- Current date/time mg.write("\n<hr/>\n") mg.write("<p>Today is " .. os.date("%A") .. "</p>\n"); -- Request content mg.write("\n<hr/>\n") l = mg.request_info.content_length if l then mg.write("<p>Content-Length = "..l..":<br>\n<pre>\n") mg.write(mg.read()) mg.write("\n</pre>\n</p>\n") else mg.write("<p>no request content available for " .. mg.request_info.request_method .. " method</p>\n") end -- Directory listing mg.write("\n<hr/>\n") mg.write("<p>\n"); if not lfs then mg.write("lfs not available\n") else mg.write("Files in " .. lfs.currentdir()) mg.write("\n<ul>\n") local cnt = 0 for f in lfs.dir(".") do cnt = cnt + 1 if (cnt < 6) then local mime = mg.get_mime_type(f) mg.write("<li>" .. f .. " (" .. mime .. ")</li>\n") local at = lfs.attributes(f); recurse(at) end end mg.write("</ul>\n") mg.write(string.format("<ul>%u files total</ul>\n", cnt)) end mg.write("</p>\n") function htmlEsc(txt) s = txt:gsub("%&", "&amp;") s = s:gsub("%<", "&lt;") s = s:gsub("%>", "&gt;") return (s) end function printTable(tab, indent) indent = indent or 0 for k,v in pairs(tab) do if (type(v)=="table") then mg.write(string.rep(" ", indent) .. tostring(k) .. ":\n") printTable(v, indent + 1) else mg.write(string.rep(" ", indent) .. tostring(k) .. "\t" .. tostring(v) .. "\n") end end end -- xml test if (xml) then mg.write("\n<hr/>\n") mg.write("<p>xml2lua:<br>\n<pre>\n"); xmlstr = [[<obj attr="a"><sub1 attr="suba">sub1val</sub1><sub2 attr="suba2" /><sub3></sub3><sub4><subsub>subsubval</subsub></sub4></obj>]] xmlev = xml.eval(xmlstr) mg.write(htmlEsc(xmlstr)) mg.write("\n-->\n") mg.write(type(xmlev) .. ":\n") mg.write(printTable(xmlev, 1)) mg.write("</pre>\n</p>\n") mg.write("<p>lua2xml:<br>\n<pre>\n"); mg.write(htmlEsc(xml.str(xmlev, 1, "xml"))) mg.write("</pre>\n</p>\n") mg.write("<p>lua2xml:<br>\n<pre>\n"); mg.write(htmlEsc(xml.str(demo_data_for_xml, 1, "xml"))) mg.write("</pre>\n</p>\n") end -- json test current_script_path = mg.script_name:match("(.*[%/%\\]).*%.lua") script_search_path = current_script_path .. "?.lua" package.path = script_search_path .. ";" .. package.path json = require "json" mg.write("\n<hr/>\n") mg.write("<p>json2lua:<br>\n<pre>\n"); -- JSON example from https://en.wikipedia.org/wiki/JSON#Example jsonstr = [[{ "firstName": "John", "lastName": "Smith", "isAlive": true, "age": 27, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021-3100" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" }, { "type": "mobile", "number": "123 456-7890" } ], "children": [], "spouse": null }]] jsonev = json.decode(jsonstr) mg.write(htmlEsc(jsonstr)) mg.write("\n-->\n") mg.write(type(jsonev) .. ":\n") mg.write(printTable(jsonev, 1)) mg.write("</pre>\n</p>\n") mg.write("<p>lua2json:<br>\n<pre>\n"); mg.write(htmlEsc(json.encode(jsonev))) mg.write("</pre>\n</p>\n") mg.write("<p>lua2json:<br>\n<pre>\n"); mg.write(htmlEsc(json.encode(demo_data_for_json))) mg.write("</pre>\n</p>\n") -- Next section ... mg.write("\n<hr/>\n") mg.write([[ </body></html> ]])
local colors = { bg = "#202328", fg = "#bbc2cf", aqua = "#3affdb", beige = "#f5c06f", blue = "#51afef", brown = "#905532", cyan = "#008080", darkblue = "#081633", darkorange = "#f16529", green = "#98be65", grey = "#8c979a", lightblue = "#5fd7ff", lightgreen = "#31b53e", magenta = "#c678dd", orange = "#d4843e", pink = "#cb6f6f", purple = "#834f79", red = "#ae403f", salmon = "#ee6e73", violet = "#a9a1e1", white = "#eff0f1", yellow = "#f09f17", black = "#202328" } local icons = { -- system icons linux = " ", macos = " ", windows = " ", -- diagnostic icons error = " ", warning = " ", info = " ", hint = " ", -- lsp = " ", lsp = " ", line = "☰", -- git icons git = "", -- git = "", unstaged = "●", staged = "✓", unmerged = "", renamed = "➜", untracked = "★", deleted = "", ignored = "◌", -- file icons arrow_open = "", arrow_closed = "", default = "", open = "", empty = "", empty_open = "", symlink = "", symlink_open = "", file = "", symlink = "" } return { colors = colors, icons = icons }
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Extended Bus" ENT.WireDebugName = "Extended Bus" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS) self:SetMoveType( MOVETYPE_VPHYSICS) self:SetSolid( SOLID_VPHYSICS) self:SetUseType( SIMPLE_USE) self.Outputs = Wire_CreateOutputs(self, {"Memory"}) self.Inputs = Wire_CreateInputs(self,{"Memory1","Memory2","Memory3","Memory4","Memory5","Memory6","Memory7","Memory8"}) self.DataRate = 0 self.DataBytes = 0 self.PerformRecursiveScan = 1 self.ControlDataSize = 32 self.ControlData = {} self.Memory = {} self.MemStart = {} self.MemEnd = {} for i = 1,8 do self.Memory[i] = nil self.MemStart[i] = 0 self.MemEnd[i] = 0 end self:SetOverlayText("Data rate: 0 bps") end function ENT:Think() BaseClass.Think(self) self.DataRate = self.DataBytes self.DataBytes = 0 Wire_TriggerOutput(self, "Memory", self.DataRate) self:SetOverlayText("Data rate: "..math.floor(self.DataRate*2).." bps") self:NextThink(CurTime()+0.5) end function ENT:ReadCell(Address) Address = math.floor(Address) if (Address >= 0) and (Address < self.ControlDataSize) then if Address < 16 then if Address % 2 == 0 then return self.MemStart[Address/2+1] else return self.MemEnd[(Address-1)/2+1] end elseif Address == 16 then return self.ControlDataSize elseif Address == 18 then return self.DataRate elseif Address == 20 then return self.PerformRecursiveScan elseif Address >= 32 then return self.ControlData[Address-31] or 0 end return 0 else for i = 1,8 do if (Address-self.ControlDataSize >= self.MemStart[i]) and (Address-self.ControlDataSize <= self.MemEnd[i]) then if self.Memory[i] then if self.Memory[i].ReadCell then self.DataBytes = self.DataBytes + 1 local val = self.Memory[i]:ReadCell(Address-self.ControlDataSize-self.MemStart[i]) return val or 0 end else return 0 end end end end return nil end local recursiveCounter = 0 function ENT:GetDeviceInfo(deviceEnt) local deviceType = CPULib.GetDeviceType(deviceEnt:GetClass()) if deviceEnt.Socket then if deviceEnt.Socket.Inputs.Memory.Src then self:GetDeviceInfo(deviceEnt.Socket.Inputs.Memory.Src) else table.insert(self.ControlData,14) end return elseif deviceEnt.Plug then if deviceEnt.Plug.Inputs.Memory.Src then self:GetDeviceInfo(deviceEnt.Plug.Inputs.Memory.Src) else table.insert(self.ControlData,13) end return end table.insert(self.ControlData,deviceType) if self.PerformRecursiveScan >= 1 then recursiveCounter = recursiveCounter + 1 if recursiveCounter < 256 then if (deviceEnt:GetClass() == "gmod_wire_addressbus") or (deviceEnt:GetClass() == "gmod_wire_extbus") then for i = 1,8 do if deviceEnt.Memory[i] then self:GetDeviceInfo(deviceEnt.Memory[i]) else table.insert(self.ControlData,0) end end end end end end function ENT:WriteCell(Address, Value) Address = math.floor(Address) if (Address >= 0) and (Address < self.ControlDataSize) then -- [0..15] Address bus settings -- [16] Control data area size -- [17] Write to request device info -- [18] Data transfer rate -- [19] Override returned device type (0: no override) -- [20] Perform recursive scan -- [32..] Device types if Address < 16 then if Address % 2 == 0 then self.MemStart[Address/2+1] = math.floor(Value) else self.MemEnd[(Address-1)/2+1] = math.floor(Value) end elseif Address == 16 then self.ControlDataSize = math.max(32,math.floor(Value)) elseif Address == 17 then recursiveCounter = 0 self.ControlData = {} for i = 1,8 do if self.Memory[i] then self:GetDeviceInfo(self.Memory[i]) else table.insert(self.ControlData,0) end end elseif Address == 20 then self.PerformRecursiveScan = Value end return true else local res = false for i = 1,8 do if (Address-self.ControlDataSize >= self.MemStart[i]) and (Address-self.ControlDataSize <= self.MemEnd[i]) then if self.Memory[i] then if self.Memory[i].WriteCell then self.Memory[i]:WriteCell(Address-self.ControlDataSize-self.MemStart[i], Value) end end self.DataBytes = self.DataBytes + 1 res = true end end return res end end function ENT:TriggerInput(iname, value) for i = 1,8 do if iname == "Memory"..i then self.Memory[i] = self.Inputs["Memory"..i].Src end end end duplicator.RegisterEntityClass("gmod_wire_extbus", WireLib.MakeWireEnt, "Data")
local match_signup_tips= { name="match_signup_tips",type=0,typeName="View",time=0,report=0,x=0,y=0,width=1280,height=720,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignCenter, { name="background",type=1,typeName="Image",time=72841520,report=0,x=0,y=0,width=1280,height=720,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignCenter,file="isolater/bg_shiled.png" }, { name="tipsBg",type=1,typeName="Image",time=72841572,report=0,x=0,y=0,width=810,height=480,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="isolater/popupWindow/popupWindow_bg_55_55_55_55.png",gridLeft=55,gridRight=55,gridTop=55,gridBottom=55, { name="titleBg",type=1,typeName="Image",time=72841802,report=0,x=0,y=-55,width=617,height=190,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTop,file="isolater/popupWindow/popupWindow_title.png", { name="txtTitle",type=4,typeName="Text",time=72841867,report=0,x=0,y=-8,width=200,height=50,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=36,textAlign=kAlignCenter,colorRed=255,colorGreen=245,colorBlue=204,string=[[报名须知]] } }, { name="btnClose",type=2,typeName="Button",time=72848740,report=0,x=-15,y=-15,width=60,height=60,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopRight,file="isolater/popupWindow/popupWindow_close.png" }, { name="startView",type=0,typeName="View",time=0,x=0,y=10,width=800,height=390,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom, { name="contentView",type=0,typeName="View",time=0,x=5,y=44,width=789,height=111,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft }, { name="timeStr",type=4,typeName="Text",time=0,x=-61,y=185,width=160,height=38,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom,fontSize=32,textAlign=kAlignRight,colorRed=143,colorGreen=92,colorBlue=31,string=[[距离开赛]],colorA=1 }, { name="timeVal",type=4,typeName="Text",time=0,x=88,y=185,width=120,height=32,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom,fontSize=32,textAlign=kAlignLeft,colorRed=219,colorGreen=135,colorBlue=25,colorA=1 }, { name="btnOK",type=2,typeName="Button",time=72842325,report=0,x=0,y=66,width=295,height=90,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom,file="isolater/btns/btn_green_164x89_l25_r25_t25_b25.png",gridLeft=30,gridRight=30,gridTop=30,gridBottom=30, { name="text",type=4,typeName="Text",time=72842394,report=0,x=1,y=0,width=295,height=90,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignCenter,fontSize=34,textAlign=kAlignCenter,colorRed=255,colorGreen=245,colorBlue=204,string=[[现在进入]],colorA=1 } } }, { name="tipsView",type=0,typeName="View",time=0,x=0,y=10,width=800,height=390,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom, { name="txtTips",type=5,typeName="TextView",time=72863226,report=0,x=0,y=-55,width=650,height=200,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,fontSize=34,textAlign=kAlignLeft,colorRed=157,colorGreen=92,colorBlue=22,colorA=1 }, { name="notNow",type=2,typeName="Button",time=72842325,report=0,x=80,y=38,width=250,height=82,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottomLeft,file="isolater/btns/btn_green_164x89_l25_r25_t25_b25.png",gridLeft=30,gridRight=30,gridTop=30,gridBottom=30, { name="text",type=4,typeName="Text",time=72842394,report=0,x=1,y=0,width=250,height=82,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignCenter,fontSize=34,textAlign=kAlignCenter,colorRed=255,colorGreen=245,colorBlue=204,string=[[暂不报名]],colorA=1 } }, { name="continue",type=2,typeName="Button",time=72842325,report=0,x=80,y=38,width=250,height=82,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottomRight,file="isolater/btns/btn_green_164x89_l25_r25_t25_b25.png",gridLeft=30,gridRight=30,gridTop=30,gridBottom=30, { name="text",type=4,typeName="Text",time=72842394,report=0,x=1,y=0,width=250,height=82,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignCenter,fontSize=34,textAlign=kAlignCenter,colorRed=255,colorGreen=245,colorBlue=204,string=[[继续报名]] } }, { name="btnOK",type=2,typeName="Button",time=72842325,report=0,x=0,y=38,width=250,height=82,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom,file="isolater/btns/btn_green_164x89_l25_r25_t25_b25.png",gridLeft=30,gridRight=30,gridTop=30,gridBottom=30, { name="text",type=4,typeName="Text",time=72842394,report=0,x=1,y=0,width=250,height=82,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignCenter,fontSize=34,textAlign=kAlignCenter,colorRed=255,colorGreen=245,colorBlue=204,string=[[确定]],colorA=1 } } }, { name="successView",type=0,typeName="View",time=0,x=0,y=10,width=800,height=390,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom, { name="timeStr",type=4,typeName="Text",time=0,x=180,y=73,width=210,height=49,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft,fontSize=42,textAlign=kAlignLeft,colorRed=143,colorGreen=92,colorBlue=31,string=[[比赛时间:]],colorA=1 }, { name="timeVal",type=4,typeName="Text",time=0,x=378,y=70,width=240,height=48,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft,fontSize=48,textAlign=kAlignLeft,colorRed=249,colorGreen=96,colorBlue=13,colorA=1 }, { name="tips",type=5,typeName="TextView",time=0,x=0,y=190,width=760,height=60,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom,fontSize=28,textAlign=kAlignCenter,colorRed=143,colorGreen=92,colorBlue=31,colorA=1 }, { name="tips2",type=4,typeName="Text",time=0,x=0,y=150,width=760,height=30,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom,fontSize=24,textAlign=kAlignCenter,colorRed=138,colorGreen=118,colorBlue=94,string=[[【报名成功的比赛在已报名比赛列表查看】]],colorA=1 }, { name="btnOK",type=2,typeName="Button",time=72842325,report=0,x=0,y=38,width=250,height=82,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignBottom,file="isolater/btns/btn_green_164x89_l25_r25_t25_b25.png",gridLeft=30,gridRight=30,gridTop=30,gridBottom=30, { name="text",type=4,typeName="Text",time=72842394,report=0,x=1,y=0,width=250,height=82,visible=1,fillParentWidth=1,fillParentHeight=1,nodeAlign=kAlignCenter,fontSize=34,textAlign=kAlignCenter,colorRed=255,colorGreen=245,colorBlue=204,string=[[知道了]],colorA=1 } } } } } return match_signup_tips;
local family = "Courier New" local size = 10 if platform == "mac" then family = "Menlo" size = 12 elseif platform == "win" then family = "Consolas" elseif platform == "x11" then family = "Monospace" end return { font = { family = family, size = size }, indent = { tabs = true, width = 4, tabwidth = 4 }, blame = { heatmap = true } }
local u = require("utils") local lsp = vim.lsp local M = {} M.format_async = function(err, _, result, _, bufnr) if err ~= nil or result == nil then return end if not vim.api.nvim_buf_get_option(bufnr, "modified") then local view = vim.fn.winsaveview() lsp.util.apply_text_edits(result, bufnr) vim.fn.winrestview(view) if bufnr == vim.api.nvim_get_current_buf() then vim.api.nvim_command("noautocmd :update") end end end M.set_highlights = function() u.exec([[ function! LspHighlights() abort hi def link LspDiagnosticsDefaultError ErrorMsg hi def link LspDiagnosticsDefaultWarning WarningMsg hi def link LspDiagnosticsDefaultInformation Title hi def linkLspDiagnosticsDefaultHint EndOfBuffer hi def link LspDiagnosticsUnderlineError ErrorMsg hi def link LspDiagnosticsUnderlineWarning WarningMsg hi def link LspDiagnosticsUnderlineInformation Title hi def link LspDiagnosticsUnderlineHint EndOfBuffer endfunction augroup LspHighlights autocmd! autocmd ColorScheme * call LspHighlights() augroup END ]]) end return M
local npairs = require('nvim-autopairs') local utils = require('../utils') local lsp = require('lspconfig') function completion_confirm() if vim.fn.pumvisible() ~= 0 then if vim.fn.complete_info()['selected'] ~= -1 then return vim.fn['compe#confirm'](npairs.esc('<cr>')) else return npairs.esc('<cr>') end else return npairs.autopairs_cr() end end -- diagnostic local filetypes = { typescript = "eslint", typescriptreact = "eslint", } local linters = { eslint = { sourceName = "eslint", command = "eslint_d", rootPatterns = {".eslintrc.js", "package.json"}, debounce = 100, args = {"-stdin", "stdin-filename", "%filepath", "--format", "json"}, parseJson = { errorsRoot = "[0].messages", line = "line", column = "column", endLine = "endLine", endColumn = "endColumn", message = "${message} [${ruleId}]", security = "severity" }, securities = {[2] = "error", [1] = "warning"} } } local formatters = { prettier = {command = "prettier", args = {"--stdin-filepath", "%filepath"}} } local formatFileTypes = { typescript = "prettier", typescriptreact = "prettier", } local noremap = { noremap = true, silent = true, } local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true capabilities.textDocument.completion.completionItem.resolveSupport = { properties = { "documentation", "detail", "additionalTextEdits", }, } local noremap_expr = vim.tbl_extend('force', noremap, {expr = true}) utils.set_globals { completion_matching_strategy_list = {'exact', 'substring', 'fuzzy', 'all'}, } local on_attach = function (client, bufnr) vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc') if client.resolved_capabilities.document_formatting then utils.remap { n = {{'<leader>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', noremap}} } end if client.resolved_capabilities.document_range_formatting then utils.remap { v = {{'<leader>f', '<cmd>lua vim.lsp.buf.range_formatting()<CR>', noremap}} } end if client.resolved_capabilities.document_highlight then vim.cmd[[ augroup lsp_document_highlight autocmd! * <buffer> autocmd CursorHold <buffer> Lspsaga show_cursor_diagnostics autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() augroup END ]] end end local servers = { 'cmake', 'vimls', 'gopls', 'jsonls', 'texlab', 'clangd', 'tsserver', 'elixirls', 'rust_analyzer', 'java_language_server', } local servers_settings = { rust_analyzer = { updates = { channel = "nightly" }, }, elixirls = { projectDir = ".", }, sumneko_lua = { Lua = { runtime = { version = 'LuaJIT', path = vim.split(package.path, ';'), }, diagnostics = { globals = {'vim', 'use', 'use_rocks'}, }, workspace = { library = { [vim.fn.expand('$VIMRUNTIME/lua')] = true, [vim.fn.expand('$VIMRUNTIME/lua/vim/lsp')] = true, } }, telemetry = { enable = false, } } }, texlab = { bibtex = { formatting = { lineLength = 80, }, }, texlab = { build = { args = { "-xelatex", "-synctex=1", "-shell-escape", "-interaction=nonstopmode", "-output-directory=build", "%f" }, onSave = true, outputDirectory = "build", }, lint = { onChange = true, }, rootDirectory = ".", } }, gopls = { analyses = { unusedparams = true, }, staticcheck = true, }, diagnosticls = { filetypes = vim.tbl_keys(filetypes), init_options = { filetypes = filetypes, linters = linters, formatters = formatters, formatFileTypes = formatFileTypes } } } local commands = { elixirls = { '/usr/local/bin/elixir-ls/language_server.sh' }, java_language_server = { '/Users/iago/Projects/java/java-language-server/dist/lang_server_mac.sh' }, gopls = {vim.fn.expand('~/go/bin/gopls'), 'serve'}, } for _, server in pairs(servers) do lsp[server].setup { on_attach = on_attach, settings = servers_settings[server], capabilities = capabilities, cmd = commands[server], } end utils.remap { n = { {'<F2>', '<cmd>lua vim.lsp.buf.rename()<CR>', noremap}, {'<leader>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', noremap}, {'<leader>sd', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', noremap}, {'K', '<cmd>lua vim.lsp.buf.hover()<CR>', noremap}, {'[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', noremap}, {']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', noremap}, {'g0', '<cmd>lua vim.lsp.buf.document_symbol()<CR>', noremap}, {'gW', '<cmd>lua vim.lsp.buf.workspace_symbol()<CR>', noremap}, {'gd', '<cmd>lua vim.lsp.buf.declaration()<CR>', noremap}, {'gd', '<cmd>lua vim.lsp.buf.declaration()<CR>', noremap}, {'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', noremap}, {'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', noremap}, {'gr', '<cmd>lua vim.lsp.buf.references()<CR>', noremap}, {'gs', '<cmd>lua vim.lsp.buf.signature_help()<CR>', noremap}, {'gy', '<cmd>lua vim.lsp.buf.type_definition()<CR>', noremap}, {'<leader>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', noremap}, {'<leader>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', noremap}, {'<leader>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', noremap}, }, i = { {'<cr>', 'v:lua.completion_confirm()', noremap_expr}, {'<tab>', 'pumvisible() ? "<C-n>" : "<tab>"', noremap_expr}, {'<S-tab>', 'pumvisible() ? "<C-p>" : "<S-tab>"', noremap_expr}, } }
local M = {} local u = require("util") function M.config() local ok, dap = pcall(function() return require("dap") end) if not ok then return end -- Configurations dap.adapters.lldb = { type = "executable", command = "/usr/bin/lldb-vscode", name = "lldb", } dap.configurations.cpp = { { name = "Launch", type = "lldb", request = "launch", program = function() return vim.fn.input( "Path to executable: ", vim.fn.getcwd() .. "/", "file" ) end, cwd = "${workspaceFolder}", stopOnEntry = false, args = {}, runInTerminal = false, }, } dap.configurations.c = dap.configurations.cpp -- Autocompletion vim.cmd([[ augroup dap-repl autocmd! autocmd FileType dap-repl lua require("dap.ext.autocompl").attach() augroup END ]]) -- Visuals vim.fn.sign_define( "DapBreakpoint", { text = " ", texthl = "DiagnosticError", linehl = "", numhl = "" } ) vim.fn.sign_define("DapBreakpointRejected", { text = " ", texthl = "Ignore", linehl = "", numhl = "", }) vim.fn.sign_define( "DapLogPoint", { text = "ﯽ ", texthl = "DiagnosticInfo", linehl = "", numhl = "" } ) vim.fn.sign_define("DapStopped", { text = " ", texthl = "TSCharacter", linehl = "", numhl = "", }) -- Mappings. local opts = { noremap = true, silent = true } u.map( "n", "<Leader>b", "<Cmd>lua require('dap').toggle_breakpoint()<Cr>", opts ) u.map( "n", "<Leader>bl", "<Cmd>lua require('dap').set_breakpoint(nil, nil, vim.fn.input('Log point message: '))<Cr>", opts ) u.map("n", "<Leader>dr", "<Cmd>lua require('dap').repl.toggle()<Cr>", opts) end return M
local getDescendantsWhichIsA = require(script.Parent.getDescendantsWhichIsA) local function clearAllDescendantsWhichIsA(parent: Instance, className: string) for _, descendant in getDescendantsWhichIsA(parent, className) do descendant:Destroy() end end return clearAllDescendantsWhichIsA
-- -- Copyright (c) 2014, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. -- Rudimentary complex number support, building on top of LuaJIT's already -- existing support (1+2i is parsed correctly and produces a boxed double -- _Complex value) -- -- This provides basic mathematical operations and wrappers for the functions -- in <complex.h> local ffi = require('ffi') local M = {} local mt = {} local complex -- Ensure a number is of the complex type local function tocomplex(a) if ffi.istype(complex, a) then return a elseif type(a) == 'number' then return complex(a, 0) else error('Invalid type, numeric type expected') end end M.tocomplex = tocomplex -- Wrappers around <complex.h> functions local one_operand = { 'abs', 'acos', 'acosh', 'arg', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'exp', 'log', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', } local two_operand = { 'pow', } for _, fn in ipairs(one_operand) do local cname = 'c' .. fn ffi.cdef(string.format('double _Complex %s(double _Complex)', cname)) M[fn] = function(a) return ffi.C[cname](tocomplex(a)) end end for _, fn in ipairs(two_operand) do local cname = 'c' .. fn ffi.cdef(string.format( 'double _Complex %s(double _Complex, double _Complex)', cname)) M[fn] = function(a, b) return ffi.C[cname](tocomplex(a), tocomplex(b)) end end function M.conj(a) a = tocomplex(a) return complex(a.re, -a.im) end function mt.__add(a, b) a, b = tocomplex(a), tocomplex(b) return complex(a.re + b.re, a.im + b.im) end function mt.__sub(a, b) a, b = tocomplex(a), tocomplex(b) return complex(a.re - b.re, a.im - b.im) end function mt.__mul(a, b) a, b = tocomplex(a), tocomplex(b) return complex(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re) end function mt.__div(a, b) a, b = tocomplex(a), tocomplex(b) local d = b.re * b.re + b.im * b.im return complex((a.re * b.re + a.im * b.im) / d, (a.im * b.re - a.re * b.im) / d) end mt.__pow = M.pow function mt.__unm(a) a = tocomplex(a) return complex(-a.re, -a.im) end complex = ffi.metatype('double _Complex', mt) return M
help([[ Exposes a python instance running 3.9.7 for rivanna. ]]) local workspace = "/project/ds6011-sp22-002" local name = myModuleName() local version = myModuleVersion() local base = pathJoin(workspace, "python/base") prepend_path("PATH", pathJoin(base, 'versions', version, 'bin')) setenv("LD_LIBRARY_PATH", pathJoin(base, 'ssl/lib')) set_alias("python", "python3.9") whatis("Name: ".. name) whatis("Version: ".. version) whatis("Description: ".. "Portable Python 3.9.7 for Rivanna")
DefineClass.EffectDepositMarker = { __parents = { "DepositMarker" }, properties = { { category = "Deposit", name = T(11450, "Deposit Type"), id = "deposit_type", editor = "combo", items = ClassDescendantsCombo("EffectDeposit"), default = "" }, }, new_pos_if_obstruct = false, } function EffectDepositMarker:SpawnDeposit() if not g_Classes[self.deposit_type] then StoreErrorSource("silent", self, "Trying to place non-existing effect deposit:", self.deposit_type) return end local dep = PlaceObject(self.deposit_type) dep:SetCollectionIndex(self:GetCollectionIndex()) return dep end --This is not an explorable or minable deposit. --Instead it gives a ceterain effect to surrounding buildings. --`EffectDeposit:AffectBuilding()` will be automatically called once for each building that is in range. DefineClass.EffectDeposit = { __parents = { "SubsurfaceDeposit" }, building_class = "Building", fx_actor_class = "SubsurfaceAnomaly", city_label = "EffectDeposit", ip_template = "ipEffectDeposit", list_as_sector_expected = false, sector_expected_name = "", ConstructionStatusName = false, ResourceName = "", show_pin_toggle = false, } function GetBuildingAffectRange(building) if IsKindOfClasses(building, "Dome", "LowGLab") then return building:GetSelectionRadiusScale() end return 0 end local function GameInit_ForEachFn(building, deposit) if deposit:CanAffectBuilding(building) then local hex_dist = HexAxialDistance(deposit, building) local range = GetBuildingAffectRange(building) if hex_dist <= range then deposit:AffectBuilding(building) end end end function EffectDeposit:GetConstructionStatusText(building, all_deposits) end function EffectDeposit:GameInit() MapForEach("map", self.building_class, GameInit_ForEachFn, self) end function EffectDeposit:CanAffectBuilding(building) return IsKindOf(building, self.building_class) end function EffectDeposit:AffectBuilding(building) end local function ConstructionComplete_ForEachFn(deposit, building) if deposit:CanAffectBuilding(building) then deposit:AffectBuilding(building) end end function OnMsg.ConstructionComplete(building, dome) local range = GetBuildingAffectRange(building) MapForEach(building, "hex", range, "EffectDeposit", ConstructionComplete_ForEachFn, building) end function EffectDeposit:GetInfopanelDetails() return "" end DefineClass.PrefabFeatureChar_Effect = { __parents = { "PrefabFeatureChar" }, properties = { { category = "Effect", id = "EffectType", name = "Effect Type", editor = "combo", items = ClassDescendantsCombo("EffectDeposit"), default = "" }, } } function PrefabFeatureChar_Effect:GetDescription() return (self.EffectType ~= "") and self.EffectType or "Effect Deposit" end function PlaceEffectDeposit(effect_type, params) local classdef = g_Classes[effect_type] if IsKindOf(classdef, "EffectDeposit") then return classdef:new(params) end end ---- DefineClass.BeautyEffectDeposit = { __parents = { "EffectDeposit" }, building_class = "Dome", modifier = false, comfort_increase = 10 * const.Scale.Stat, ConstructionStatusName = "BeautyDepositNearby", resource = "Beauty", display_name = T(11458, "Vista"), IPDescription = T(11459, "Improves the Comfort of all residences when in the radius of a Dome."), display_icon = "UI/Icons/bmb_demo.tga", entity = "SignBeautyDeposit", } function BeautyEffectDeposit:GetInfopanelDetails() return T{11460, "Comfort boost<right><resource(comfort_increase)>", self} end function BeautyEffectDeposit:Init() self.encyclopedia_id = "Colonist" self.modifier = Modifier:new{ prop = "dome_comfort", amount = self.comfort_increase, percent = 0, id = "Beauty Effect Deposit", } end function BeautyEffectDeposit:AffectBuilding(building) building:UpdateModifier("add", self.modifier, self.modifier.amount, self.modifier.percent) end function BeautyEffectDeposit:GetConstructionStatusText(building, all_deposits) local sum = 0 for i,deposit in ipairs(all_deposits) do sum = sum + deposit.comfort_increase / const.Scale.Stat end return T{12263, "Vista - Comfort of residences will be boosted by <sum>", sum = sum} end ---- DefineClass.ResearchEffectDeposit = { __parents = { "EffectDeposit" }, modifier = false, research_increase = 10, research_increase_options = { 10, 15, 20 }, ConstructionStatusName = "ResearchDepositNearby", list_as_sector_expected = true, sector_expected_name = T(311, "Research"), resource = "Research", display_name = T(11461, "Research Site"), IPDescription = T(11462, "Boosts research production when in radius of a Dome or outside research facility."), display_icon = "UI/Icons/bmb_demo.tga", entity = "SignResearchDeposit", } function ResearchEffectDeposit:GetInfopanelDetails() return T{11463, "Research boost<right><percent(research_increase)>", self} end function ResearchEffectDeposit:Init() self.research_increase = table.rand(self.research_increase_options) self.modifier = Modifier:new{ prop = "ResearchPointsPerDay", amount = 0, percent = self.research_increase, id = "Research Effect Deposit", } end function ResearchEffectDeposit:CanAffectBuilding(building) return (IsKindOf(building, "ResearchBuilding") and not building.dome_required) or IsKindOf(building, "Dome") end function ResearchEffectDeposit:AffectBuilding(building) if IsKindOf(building, "ResearchBuilding") and not building.dome_required then building:UpdateModifier("add", self.modifier, self.modifier.amount, self.modifier.percent) elseif IsKindOf(building, "Dome") then building:SetLabelModifier("ResearchBuildings", self, self.modifier, false) end end function ResearchEffectDeposit:GetConstructionStatusText(building, all_deposits) local sum = 0 for i,deposit in ipairs(all_deposits) do sum = sum + deposit.research_increase end return T{12264, "Research Site - all Research will be boosted by <percent(sum)>.", sum = sum} end
setenv("B","1.0b") set_alias("BB","bb")
AddCSLuaFile() ENT.Base = "bw_base" ENT.Type = "anim" ENT.PrintName = "Base Electricals" ENT.Model = "models/props_c17/metalPot002a.mdl" ENT.Skin = 0 ENT.IsElectronic = true ENT.PowerRequired = 5 ENT.PowerCapacity = 1000 function ENT:DrainPower(val) if not self:IsPowered(val) then return false end self:SetPower(self:GetPower() - (val or self.PowerRequired)) return true end function ENT:IsPowered(val) return self:GetPower() >= (val or self.PowerRequired) end if SERVER then function ENT:Think() self:ThinkFuncBypass() if self:IsPowered() and self:BadlyDamaged() and math.random(0, 11) == 0 then self:Spark() end if self:WaterLevel() > 0 and not self:GetWaterProof() then if not self.FirstTime and self:Health() > 25 then self:SetHealth(25) self:Spark() self.FirstTime = true end if self.rtb == 2 then self.rtb = 0 self:TakeDamage(1) else self.rtb = self.rtb + 1 end else self.FirstTime = false end if not self:DrainPower() or self:BadlyDamaged() then if self:GetUsable() then self:SetUsable(false) end return end local Res = self:CheckUsable() local State = Res ~= false if State ~= self:GetUsable() then self:SetUsable(State) end self:ThinkFunc() end function ENT:CheckUsable() end function ENT:Use(activator, caller, usetype, value) self:UseFuncBypass(activator, caller, usetype, value) if not self:GetUsable() then return end if self:CheckUsable() == false then return end if not self:IsPowered() or self:BadlyDamaged() then self:EmitSound("buttons/button10.wav") return end self:UseFunc(activator, caller, usetype, value) end end
if select(1,...) == "-?" then printUsage("version","Print the current version number.") return end color(11) print("LIKO-12 V".._LIKO_Version) if old then color(6) print("Updated from: V".._LIKO_Old) end
-- must be a set of ids local idSet = KEYS[1]; -- must be a key, which holds metadata for a given id, with a `*` as a substitute for an id from idSet. Optional local metadataKey = KEYS[2]; -- hashKey to use for sorting, which is taken from `metadataKey` hash, Optional. local hashKey = ARGV[1]; -- ASC / DESC local order = ARGV[2]; -- stringified instructions for filtering local filter = ARGV[3]; -- current time local curTime = ARGV[4]; -- pagination offset local offset = tonumber(ARGV[5] or 0); -- limit of items to return in a single call local limit = tonumber(ARGV[6] or 10); -- caching time local expiration = tonumber(ARGV[7] or 30000); -- return the key only local returnKeyOnly = ARGV[8] or false; -- local caches local tempKeysSet = getIndexTempKeys(idSet); local strlower = string.lower; local strfind = string.find; local tinsert = table.insert; local tconcat = table.concat; local tsort = table.sort; local rcall = redis.call; local unpack = unpack; local pairs = pairs; -- declaring to use later local filterType; local function catch(what) return what[1] end local function try(what) local status, result = pcall(what[1]); if not status then return what[2](result); end return result; end local function isempty(s) return s == nil or s == '' or s == false; end local function isnumber(a) return try { function() local num = tonumber(a); return num ~= nil and num or tonumber(cjson.decode(a)); end, catch { function() return nil; end } } end local function subrange(t, first, last) local sub = {}; for i=first + 1,last do sub[#sub + 1] = t[i]; end return sub; end local function massive_redis_command(command, key, t) local i = 1; local temp = {}; while (i <= #t) do tinsert(temp, t[i]); tinsert(temp, t[i + 1]); if #temp >= 1000 then rcall(command, key, unpack(temp)); temp = {}; end i = i + 2; end if #temp > 0 then rcall(command, key, unpack(temp)); end end local function hashmapSize(table) local numItems = 0; for k,v in pairs(table) do numItems = numItems + 1; end return numItems; end local function storeCacheBuster(key) local tempKeyTTL = curTime + expiration; -- store key in temporary zset rcall("PEXPIRE", tempKeysSet, expiration); rcall("ZADD", tempKeysSet, tempKeyTTL, key); end local function updateExpireAndReturnWithSize(key) -- stores key for cache busting storeCacheBuster(key); -- lengthens cache rcall("PEXPIRE", key, expiration); -- returns either results or key where it's stored if returnKeyOnly ~= false then return key; end local ret = rcall("LRANGE", key, offset, offset + limit - 1); tinsert(ret, rcall("LLEN", key)); return ret; end -- create filtered list name local finalFilteredListKeys = { idSet }; local preSortedSetKeys = { idSet }; -- decoded filters local jsonFilter = cjson.decode(filter); local totalFilters = hashmapSize(jsonFilter); -- order always exists tinsert(finalFilteredListKeys, order); tinsert(preSortedSetKeys, order); if isempty(metadataKey) == false then if isempty(hashKey) == false then tinsert(finalFilteredListKeys, metadataKey); tinsert(finalFilteredListKeys, hashKey); tinsert(preSortedSetKeys, metadataKey); tinsert(preSortedSetKeys, hashKey); end -- do we have filter? if totalFilters > 0 then tinsert(finalFilteredListKeys, filter); end elseif totalFilters >= 1 and type(jsonFilter["#"]) == "string" then -- the rest of the filters are ignored, since we cant access them! tinsert(finalFilteredListKeys, "{\"#\":" .. jsonFilter["#"] .. "}"); end -- get final filtered key set local FFLKey = tconcat(finalFilteredListKeys, ":"); local PSSKey = tconcat(preSortedSetKeys, ":"); -- do we have existing filtered set? if rcall("EXISTS", FFLKey) == 1 then -- also extend live of the underlaying key rcall("PEXPIRE", PSSKey, expiration); storeCacheBuster(PSSKey); -- and ready from existing key now return updateExpireAndReturnWithSize(FFLKey); end -- do we have an existing sorted set? local valuesToSort; if rcall("EXISTS", PSSKey) == 0 then valuesToSort = rcall("SMEMBERS", idSet); -- if we sort the given set if isempty(metadataKey) == false and isempty(hashKey) == false then local arr = {}; for i,v in pairs(valuesToSort) do local metaKey = metadataKey:gsub("*", v, 1); -- defaults to empty string to avoid sorting problems arr[v] = rcall("HGET", metaKey, hashKey) or ''; end -- false implies that items stay in place -- means when they are the same - they must return false local function sortFuncASC(a, b) local sortA = arr[a]; local sortB = arr[b]; if isempty(sortA) and isempty(sortB) then return false; elseif isempty(sortA) then return false; elseif isempty(sortB) then return true; else local numA = isnumber(sortA); local numB = isnumber(sortB); if numA ~= nil and numB ~= nil then return numA < numB; end return strlower(sortA) < strlower(sortB); end end local function sortFuncDESC(a, b) local sortA = arr[a]; local sortB = arr[b]; if isempty(sortA) and isempty(sortB) then return false; elseif isempty(sortA) then return true; elseif isempty(sortB) then return false; else local numA = isnumber(sortA); local numB = isnumber(sortB); if numA ~= nil and numB ~= nil then return numA > numB; end return strlower(sortA) > strlower(sortB); end end if order == "ASC" then tsort(valuesToSort, sortFuncASC); else tsort(valuesToSort, sortFuncDESC); end else if order == "ASC" then tsort(valuesToSort, function (a, b) return a < b end); else tsort(valuesToSort, function (a, b) return a > b end); end end if #valuesToSort > 0 then massive_redis_command("RPUSH", PSSKey, valuesToSort); rcall("PEXPIRE", PSSKey, expiration); storeCacheBuster(PSSKey); else -- returns either results or key where it's stored if returnKeyOnly ~= false then return PSSKey; end return {0}; end if FFLKey == PSSKey then -- returns either results or key where it's stored if returnKeyOnly ~= false then return PSSKey; end -- early return if we have no filter local ret = subrange(valuesToSort, offset, offset + limit); tinsert(ret, #valuesToSort); return ret; end else if FFLKey == PSSKey then -- early return if we have no filter return updateExpireAndReturnWithSize(PSSKey); end -- populate in-memory data -- update expiration timer rcall("PEXPIRE", PSSKey, expiration); storeCacheBuster(PSSKey); valuesToSort = rcall("LRANGE", PSSKey, 0, -1); end -- filtered list holder local output = {}; -- filter function local function filterString(value, filter) if isempty(value) then return false; end return strfind(strlower(value), strlower(filter)) ~= nil; end -- filter: eq local function eq(value, filter) return value == filter; end -- filter: some local function some(value, filter) if isempty(value) then return false; end for _, fieldValue in pairs(filter) do if eq(value, fieldValue) then return true end end return false; end -- filter: gte local function gte(value, filter) if isempty(value) then return false; end return isnumber(value) >= filter; end -- filter: lte local function lte(value, filter) if isempty(value) then return false; end return isnumber(value) <= filter; end -- filter: not equal local function ne(value, filter) return value ~= filter; end -- filter: exists local function exists(value, filter) return isempty(value) == false; end -- filter: any local function any(fieldValue, filter) for _, filterValue in pairs(filter) do if filterType[type(filterValue)](fieldValue, filterValue) then return true; end end return false; end -- supported op type table local opType = { gte = gte, lte = lte, match = filterString, eq = eq, ne = ne, exists = exists, isempty = isempty, some = some, any = any, }; function filter(op, opFilter, fieldValue) local thunk = opType[op]; if type(thunk) ~= "function" then return error("not supported op: " .. op); end return thunk(fieldValue, opFilter); end -- when we match against a table local function tableFilter(valueToFilter, filterValue) for op, opFilter in pairs(filterValue) do if filter(op, opFilter, valueToFilter) ~= true then return false; end end return true; end filterType = { table = tableFilter, string = filterString }; -- if no metadata key, but we are still here if isempty(metadataKey) then -- only sort by value, which is id local filterValue = jsonFilter["#"]; -- iterate over filtered set for i, idValue in pairs(valuesToSort) do -- compare strings and insert if they match if filterString(idValue, filterValue) then tinsert(output, idValue); end end -- we actually have metadata else for i, idValue in pairs(valuesToSort) do local metaKey = metadataKey:gsub("*", idValue, 1); local matched = true; for fieldName, filterValue in pairs(jsonFilter) do if fieldName == '#multi' then local fieldValues = rcall('hmget', metaKey, unpack(filterValue["fields"])); local anyMatched = false; local matchValue = filterValue["match"]; for _, fieldValue in pairs(fieldValues) do if filterString(fieldValue, matchValue) then anyMatched = true; break; end end if anyMatched == false then matched = false; break; end else -- get data that we are filter local fieldValue = (fieldName == "#") and idValue or rcall("hget", metaKey, fieldName); -- traverse filter types and perform filtering if filterType[type(filterValue)](fieldValue, filterValue) ~= true then matched = false; break; end end end if matched then tinsert(output, idValue); end end end -- if output is more tha 0 - save data and return it if #output > 0 then massive_redis_command("RPUSH", FFLKey, output); return updateExpireAndReturnWithSize(FFLKey); end -- returns either results or key where it's stored if returnKeyOnly ~= false then return FFLKey; end return {0};
return { CORE = require("CORE/core"), UTILS = require("UTILS/utils"), TYPES = require("TYPES/types") }
--[[ Sklepy z odzieza @author Jakub 'XJMLN' Starzak <jack@pszmta.pl @package PSZMTA.gracz-sklep_odziezowy @copyright Jakub 'XJMLN' Starzak <jack@pszmta.pl> @contents Kacper "SzaG" Budak <szag@pszmta.pl> Nie mozesz uzywac tego skryptu bez mojej zgody. Napisz - byc moze sie zgodze na uzycie. ]]-- local sklepy = { -- x, y, z, i, vw, type = 1 - sklep odziezowy; type = 2 - sklep z bronia {207.12,-129.18,1002.5,3,0}, } local function onPlayerHitShopMarker(el,md) if (not md) or getElementType(el)~="player" then return end if (getElementInterior(source)~=getElementInterior(el)) then return end local type = getElementData(source,"wear_shop") if (not type) then return end triggerClientEvent(el,"onPlayerHitShopMarker", el) end for i,v in ipairs(sklepy) do sklepy[i].marker = createMarker(v[1],v[2],v[3],"cylinder",1.2,255,255,0,100) setElementInterior(sklepy[i].marker,v[4]) setElementDimension(sklepy[i].marker,v[5]) setElementData(sklepy[i].marker,"wear_shop",true) addEventHandler("onMarkerHit", sklepy[i].marker, onPlayerHitShopMarker) end --triggerServerEvent("onPlayerRequestEnd",getRootElement(), plr, tonumber(sid)) addEvent("onPlayerRequestEnd",true) addEventHandler("onPlayerRequestEnd", getRootElement(), function(plr,model) if model then local auid = getElementData(plr,"auth:uid") or 0 local query = string.format("UPDATE psz_postacie SET skin=%d, vipskin= NULL WHERE id=%d LIMIT 1",model,auid) exports['psz-mysql']:zapytanie(query) end end)
--[[ author by soniceryd Date:2016/07/09 Desc: urlmapping configuration ]]-- local urlmapping = { v1 = {} } urlmapping.v1.GET = { {pattern="/default",controller="luaweb.api.default.Contoller",action="index"} } return urlmapping
---@class CS.UnityEngine.Canvas : CS.UnityEngine.Behaviour ---@field public renderMode number ---@field public isRootCanvas boolean ---@field public pixelRect CS.UnityEngine.Rect ---@field public scaleFactor number ---@field public referencePixelsPerUnit number ---@field public overridePixelPerfect boolean ---@field public pixelPerfect boolean ---@field public planeDistance number ---@field public renderOrder number ---@field public overrideSorting boolean ---@field public sortingOrder number ---@field public targetDisplay number ---@field public sortingLayerID number ---@field public cachedSortingLayerValue number ---@field public additionalShaderChannels number ---@field public sortingLayerName string ---@field public rootCanvas CS.UnityEngine.Canvas ---@field public worldCamera CS.UnityEngine.Camera ---@field public normalizedSortingGridSize number ---@type CS.UnityEngine.Canvas CS.UnityEngine.Canvas = { } ---@return CS.UnityEngine.Canvas function CS.UnityEngine.Canvas.New() end ---@param value (fun():void) function CS.UnityEngine.Canvas.add_willRenderCanvases(value) end ---@param value (fun():void) function CS.UnityEngine.Canvas.remove_willRenderCanvases(value) end ---@return CS.UnityEngine.Material function CS.UnityEngine.Canvas.GetDefaultCanvasMaterial() end ---@return CS.UnityEngine.Material function CS.UnityEngine.Canvas.GetETC1SupportedCanvasMaterial() end function CS.UnityEngine.Canvas.ForceUpdateCanvases() end return CS.UnityEngine.Canvas
return { [11] = {id=11,title='测试1',sender='系统',content='测试内容1',award={1,},}, [12] = {id=12,title='测试2',sender='系统',content='测试内容2',award={1,},}, [13] = {id=13,title='测试3',sender='系统',content='测试内容3',award={1,2,3,},}, [14] = {id=14,title='测试4',sender='系统',content='测试内容4',award={2,3,},}, [15] = {id=15,title='测试5',sender='系统',content='测试内容5',award={1,},}, }
--[[ Made by Fenrier. ]] Player=game:GetService("Players").LocalPlayer Character=Player.Character PlayerGui=Player.PlayerGui Backpack=Player.Backpack Torso=Character.Torso Head=Character.Head Humanoid=Character.Humanoid LeftArm=Character["Left Arm"] LeftLeg=Character["Left Leg"] RightArm=Character["Right Arm"] RightLeg=Character["Right Leg"] LS=Torso["Left Shoulder"] LH=Torso["Left Hip"] RS=Torso["Right Shoulder"] RH=Torso["Right Hip"] Neck=Torso.Neck it=Instance.new vt=Vector3.new cf=CFrame.new euler=CFrame.fromEulerAnglesXYZ angles=CFrame.Angles necko=cf(0, 1, 0, -1, -0, -0, 0, 0, 1, 0, 1, 0) necko2=cf(0, -0.5, 0, -1, -0, -0, 0, 0, 1, 0, 1, 0) LHC0=cf(-1,-1,0,-0,-0,-1,0,1,0,1,0,0) LHC1=cf(-0.5,1,0,-0,-0,-1,0,1,0,1,0,0) RHC0=cf(1,-1,0,0,0,1,0,1,0,-1,-0,-0) RHC1=cf(0.5,1,0,0,0,1,0,1,0,-1,-0,-0) RootPart=Character.HumanoidRootPart RootJoint=RootPart.RootJoint RootCF=euler(-1.57,0,3.14) attack=false attackdebounce=false MMouse=nil combo=0 mana=0 heatcooldown=false aimrailgun=false aimcannon=false RailgunTarget=RootPart CannonTarget=RootPart changetarget=false local circle=0 bladeattack=false local con1=nil local con2=nil local con3=nil --player player=nil --save shoulders RSH, LSH=nil, nil --welds RW, LW=Instance.new("Weld"), Instance.new("Weld") RW.Name="Right Shoulder" LW.Name="Left Shoulder" LH=Torso["Left Hip"] RH=Torso["Right Hip"] Asset="http://www.roblox.com/asset/?id=" function swait(num) if num==0 or num==nil then game:service'RunService'.RenderStepped:wait() else for i=0,num do game:service'RunService'.RenderStepped:wait() end end end if Character:findFirstChild("Railgun",true) ~= nil then Character:findFirstChild("Railgun",true).Parent = nil end if Character:findFirstChild("Plasma Cannon",true) ~= nil then Character:findFirstChild("Plasma Cannon",true).Parent = nil end if Character:findFirstChild("Vanguard Blades",true) ~= nil then Character:findFirstChild("Vanguard Blades",true).Parent = nil end if Player.PlayerGui:findFirstChild("WeaponGUI",true) ~= nil then Player.PlayerGui:findFirstChild("WeaponGUI",true).Parent = nil end function NoOutline(Part) Part.TopSurface,Part.BottomSurface,Part.LeftSurface,Part.RightSurface,Part.FrontSurface,Part.BackSurface = 10,10,10,10,10,10 end function part(formfactor,parent,reflectance,transparency,brickcolor,name,size) local fp=it("Part") fp.formFactor=formfactor fp.Parent=parent fp.Reflectance=reflectance fp.Transparency=transparency fp.CanCollide=false fp.Locked=true fp.BrickColor=brickcolor fp.Name=name fp.Size=size fp.Position=Torso.Position NoOutline(fp) fp.Material="SmoothPlastic" fp:BreakJoints() return fp end function mesh(Mesh,part,meshtype,meshid,offset,scale) local mesh=it(Mesh) mesh.Parent=part if Mesh=="SpecialMesh" then mesh.MeshType=meshtype mesh.MeshId=meshid end mesh.Offset=offset mesh.Scale=scale return mesh end function weld(parent,part0,part1,c0) local weld=it("Weld") weld.Parent=parent weld.Part0=part0 weld.Part1=part1 weld.C0=c0 return weld end local fengui=it("GuiMain") fengui.Parent=Player.PlayerGui fengui.Name="WeaponGUI" local Color1=BrickColor.new("Bright orange") local Color2=BrickColor.new("Really black") local Color3=BrickColor.new("Really black") local model1=Instance.new("Model") model1.Parent=Character model1.Name="Railgun" Railgun={} RailgunWelds={} local model2=Instance.new("Model") model2.Parent=Character model2.Name="Plasma Cannon" Plasma={} PlasmaWelds={} local model3=Instance.new("Model") model3.Parent=Character model3.Name="Vanguard Blades" prt1=part(3,model1,0,0,Color1,"Part1",vt()) prt2=part(3,model1,0,0,Color2,"Part2",vt()) prt3=part(3,model1,0,0,Color2,"Part3",vt()) prt4=part(3,model1,0,0,Color2,"Part4",vt()) prt5=part(3,model1,0,0,Color2,"Part5",vt()) prt6=part(3,model1,0,0,Color2,"Part6",vt()) prt7=part(3,model1,0,0,Color1,"Part7",vt()) prt8=part(3,model1,0,0,Color3,"Part8",vt()) prt9=part(3,model1,0,0,Color1,"Part9",vt()) prt10=part(3,model1,0,0,Color1,"Part10",vt()) prt11=part(3,model1,0,0,Color1,"Part11",vt()) prt12=part(3,model1,0,0,Color1,"Part12",vt()) prt13=part(3,model1,0,0,Color1,"Part13",vt()) prt14=part(3,model1,0,0,Color1,"Part14",vt()) prt15=part(3,model1,0,0,Color1,"Part15",vt()) prt16=part(3,model1,0,0,Color1,"Part16",vt()) prt17=part(3,model1,0,0,Color1,"Part17",vt()) prt18=part(3,model1,0,0,Color2,"Part18",vt()) prt19=part(3,model1,0,0,Color2,"Part19",vt()) prt20=part(3,model1,0.2,0,Color1,"Part20",vt()) prt21=part(3,model1,0.2,0,Color1,"Part21",vt()) prt22=part(3,model1,0.5,0,Color1,"Part22",vt()) prt23=part(3,model1,0.5,0,Color1,"Part23",vt()) prt24=part(3,model1,0,0,Color2,"Part24",vt()) prt25=part(3,model1,0,0,Color2,"Part25",vt()) prt26=part(3,model1,0.2,0,Color1,"Part26",vt()) prt27=part(3,model1,0.2,0,Color1,"Part27",vt()) prt28=part(3,model1,0.5,0,Color1,"Part28",vt()) prt29=part(3,model1,0.5,0,Color1,"Part29",vt()) prt30=part(3,model1,0,0,Color2,"Part30",vt()) prt31=part(3,model1,0,0,Color2,"Part31",vt()) prt32=part(3,model1,0.2,0,Color1,"Part32",vt()) prt33=part(3,model1,0.2,0,Color1,"Part33",vt()) prt34=part(3,model1,0.5,0,Color1,"Part34",vt()) prt35=part(3,model1,0.5,0,Color1,"Part35",vt()) for _,c in pairs(model1:children()) do table.insert(Railgun,c) end -- aprt1=part(3,model2,0,0,Color1,"aPart1",vt()) aprt2=part(3,model2,0,0,Color2,"aPart2",vt()) aprt3=part(3,model2,0,0,Color2,"aPart3",vt()) aprt4=part(3,model2,0,0,Color2,"aPart4",vt()) aprt5=part(3,model2,0,0,Color2,"aPart5",vt()) aprt6=part(3,model2,0,0,Color2,"aPart6",vt()) aprt7=part(3,model2,0,0,Color2,"aPart7",vt()) aprt8=part(3,model2,0,0,Color1,"aPart8",vt()) aprt9=part(3,model2,0,0,Color1,"aPart9",vt()) aprt10=part(3,model2,0,0,Color3,"aPart10",vt()) aprt11=part(3,model2,0,0,Color3,"aPart11",vt()) aprt12=part(3,model2,0,0,Color1,"aPart12",vt()) aprt13=part(3,model2,0,0,Color1,"aPart13",vt()) aprt14=part(3,model2,0,0,Color1,"aPart14",vt()) aprt15=part(3,model2,0,0,Color1,"aPart15",vt()) aprt16=part(3,model2,0,0,Color1,"aPart16",vt()) aprt17=part(3,model2,0,0,Color1,"aPart17",vt()) aprt18=part(3,model2,0,0,Color1,"aPart18",vt()) aprt19=part(3,model2,0,0,Color2,"aPart19",vt()) aprt20=part(3,model2,0,0,Color2,"aPart20",vt()) aprt21=part(3,model2,0.2,0,Color1,"aPart21",vt()) aprt22=part(3,model2,0.2,0,Color1,"aPart22",vt()) aprt23=part(3,model2,0.5,0,Color1,"aPart23",vt()) aprt24=part(3,model2,0.5,0,Color1,"aPart24",vt()) aprt25=part(3,model2,0,0,Color2,"aPart25",vt()) aprt26=part(3,model2,0,0,Color2,"aPart26",vt()) aprt27=part(3,model2,0.2,0,Color1,"aPart27",vt()) aprt28=part(3,model2,0.2,0,Color1,"aPart28",vt()) aprt29=part(3,model2,0.5,0,Color1,"aPart29",vt()) aprt30=part(3,model2,0.5,0,Color1,"aPart30",vt()) aprt31=part(3,model2,0,0,Color2,"aPart31",vt()) aprt32=part(3,model2,0,0,Color2,"aPart32",vt()) aprt33=part(3,model2,0.2,0,Color1,"aPart33",vt()) aprt34=part(3,model2,0.2,0,Color1,"aPart34",vt()) aprt35=part(3,model2,0.5,0,Color1,"aPart35",vt()) aprt36=part(3,model2,0.5,0,Color1,"aPart36",vt()) aprt37=part(3,model2,0,0,Color2,"aPart37",vt()) aprt38=part(3,model1,0,0,Color1,"aPart38",vt()) aprt39=part(3,model1,0,0,Color1,"aPart39",vt()) for _,c in pairs(model2:children()) do table.insert(Plasma,c) end -- bref=part(3,model3,0,1,Color3,"bRef",vt()) bprt1=part(3,model3,0,1,Color1,"bPart1",vt()) bprt2=part(3,model3,0,0,Color1,"bPart2",vt()) bprt3=part(3,model3,0,0,Color2,"bPart3",vt()) bprt4=part(3,model3,0.8,0,Color1,"bPart4",vt()) bprt5=part(3,model3,0.8,0,Color1,"bPart5",vt()) bprt6=part(3,model3,0.8,0,Color1,"bPart6",vt()) bprt7=part(3,model3,0,1,Color1,"bPart7",vt()) bprt8=part(3,model3,0,0,Color1,"bPart8",vt()) bprt9=part(3,model3,0,0,Color2,"bPart9",vt()) bprt10=part(3,model3,0.8,0,Color1,"bPart10",vt()) bprt11=part(3,model3,0.8,0,Color1,"bPart11",vt()) bprt12=part(3,model3,0.8,0,Color1,"bPart12",vt()) bprt13=part(3,model3,0,1,Color1,"bPart13",vt()) bprt14=part(3,model3,0,0,Color1,"bPart14",vt()) bprt15=part(3,model3,0,0,Color2,"bPart15",vt()) bprt16=part(3,model3,0.8,0,Color1,"bPart16",vt()) bprt17=part(3,model3,0.8,0,Color1,"bPart17",vt()) bprt18=part(3,model3,0.8,0,Color1,"bPart18",vt()) msh1=mesh("BlockMesh",prt1,"","",vt(0,0,0),vt(1,1,1)) msh2=mesh("BlockMesh",prt2,"","",vt(0,0,0),vt(1.3,2.5,10)) msh3=mesh("BlockMesh",prt3,"","",vt(0,0,0),vt(1.49,2.5,5)) msh4=mesh("BlockMesh",prt4,"","",vt(0,0,0),vt(1.51,2.5,3)) msh5=mesh("CylinderMesh",prt5,"","",vt(0,0,0),vt(2.5,1,2.5)) msh6=mesh("CylinderMesh",prt6,"","",vt(0,0,0),vt(1.5,16,1.5)) msh7=mesh("CylinderMesh",prt7,"","",vt(0,0,0),vt(1.6,1,1.6)) msh8=mesh("CylinderMesh",prt8,"","",vt(0,0,0),vt(1.4,1.01,1.4)) msh9=mesh("BlockMesh",prt9,"","",vt(0,0,0),vt(1.4,14,2)) msh10=mesh("SpecialMesh",prt10,"Wedge","",vt(0,0,0),vt(1.3,4,3)) msh11=mesh("SpecialMesh",prt11,"Wedge","",vt(0,0,0),vt(1.3,2,3)) msh12=mesh("SpecialMesh",prt12,"Wedge","",vt(0,0,0),vt(1.7,3,3.5)) msh13=mesh("BlockMesh",prt13,"","",vt(0,0,0),vt(1.5,1.5,1.5)) msh14=mesh("BlockMesh",prt14,"","",vt(0,0,0),vt(1.6,4.5,2)) msh15=mesh("BlockMesh",prt15,"","",vt(0,0,0),vt(1.6,3.6,2)) msh16=mesh("SpecialMesh",prt16,"Wedge","",vt(0,0,0),vt(0.5,3,3.5)) msh17=mesh("SpecialMesh",prt17,"Wedge","",vt(0,0,0),vt(0.5,2,4)) msh19=mesh("SpecialMesh",prt19,"Sphere","",vt(0,0,0),vt(1.5,1.5,1.5)) msh20=mesh("SpecialMesh",prt20,"Wedge","",vt(0,0,0),vt(0.2,8,0.5)) msh21=mesh("SpecialMesh",prt21,"Wedge","",vt(0,0,0),vt(0.2,8,0.5)) msh22=mesh("SpecialMesh",prt22,"Wedge","",vt(0,0,0),vt(0.3,7,0.7)) msh23=mesh("SpecialMesh",prt23,"Wedge","",vt(0,0,0),vt(0.3,7,0.7)) msh25=mesh("SpecialMesh",prt25,"Sphere","",vt(0,0,0),vt(1.5,1.5,1.5)) msh26=mesh("SpecialMesh",prt26,"Wedge","",vt(0,0,0),vt(0.2,8,0.5)) msh27=mesh("SpecialMesh",prt27,"Wedge","",vt(0,0,0),vt(0.2,8,0.5)) msh28=mesh("SpecialMesh",prt28,"Wedge","",vt(0,0,0),vt(0.3,7,0.7)) msh29=mesh("SpecialMesh",prt29,"Wedge","",vt(0,0,0),vt(0.3,7,0.7)) msh31=mesh("SpecialMesh",prt31,"Sphere","",vt(0,0,0),vt(1.5,1.5,1.5)) msh32=mesh("SpecialMesh",prt32,"Wedge","",vt(0,0,0),vt(0.2,8,0.5)) msh33=mesh("SpecialMesh",prt33,"Wedge","",vt(0,0,0),vt(0.2,8,0.5)) msh34=mesh("SpecialMesh",prt34,"Wedge","",vt(0,0,0),vt(0.3,7,0.7)) msh35=mesh("SpecialMesh",prt35,"Wedge","",vt(0,0,0),vt(0.3,7,0.7)) -- msh1=mesh("BlockMesh",aprt1,"","",vt(0,0,0),vt(1,1,1)) msh2=mesh("BlockMesh",aprt2,"","",vt(0,0,0),vt(2,1.3,5)) msh3=mesh("SpecialMesh",aprt3,"Wedge","",vt(0,0,0),vt(2,2,1)) msh4=mesh("BlockMesh",aprt4,"","",vt(0,0,0),vt(2,2,6)) msh5=mesh("BlockMesh",aprt5,"","",vt(0,0,0),vt(2,2,2)) msh6=mesh("CylinderMesh",aprt6,"","",vt(0,0,0),vt(2,5,2)) msh7=mesh("CylinderMesh",aprt7,"","",vt(0,0,0),vt(2,5,2)) msh8=mesh("CylinderMesh",aprt8,"","",vt(0,0,0),vt(2.1,1,2.1)) msh9=mesh("CylinderMesh",aprt9,"","",vt(0,0,0),vt(2.1,1,2.1)) msh10=mesh("CylinderMesh",aprt10,"","",vt(0,0,0),vt(1.9,1.01,1.9)) msh11=mesh("CylinderMesh",aprt11,"","",vt(0,0,0),vt(1.9,1.01,1.9)) msh12=mesh("CylinderMesh",aprt12,"","",vt(0,0,0),vt(2.2,5.5,2.2)) msh13=mesh("SpecialMesh",aprt13,"Wedge","",vt(0,0,0),vt(1.7,3,3.5)) msh14=mesh("BlockMesh",aprt14,"","",vt(0,0,0),vt(1.5,1.5,1.5)) msh15=mesh("BlockMesh",aprt15,"","",vt(0,0,0),vt(1.6,4.5,2)) msh16=mesh("BlockMesh",aprt16,"","",vt(0,0,0),vt(1.6,3.6,2)) msh17=mesh("SpecialMesh",aprt17,"Wedge","",vt(0,0,0),vt(0.5,3,3.5)) msh18=mesh("SpecialMesh",aprt18,"Wedge","",vt(0,0,0),vt(0.5,2,4)) msh20=mesh("SpecialMesh",aprt20,"Sphere","",vt(0,0,0),vt(1.5,1.5,1.5)) msh21=mesh("SpecialMesh",aprt21,"Wedge","",vt(0,0,0),vt(0.2,8,0.5)) msh22=mesh("SpecialMesh",aprt22,"Wedge","",vt(0,0,0),vt(0.2,8,0.5)) msh23=mesh("SpecialMesh",aprt23,"Wedge","",vt(0,0,0),vt(0.3,7,0.7)) msh24=mesh("SpecialMesh",aprt24,"Wedge","",vt(0,0,0),vt(0.3,7,0.7)) msh26=mesh("SpecialMesh",aprt26,"Sphere","",vt(0,0,0),vt(1.5,1.5,1.5)) msh27=mesh("SpecialMesh",aprt27,"Wedge","",vt(0,0,0),vt(0.2,8,0.5)) msh28=mesh("SpecialMesh",aprt28,"Wedge","",vt(0,0,0),vt(0.2,8,0.5)) msh29=mesh("SpecialMesh",aprt29,"Wedge","",vt(0,0,0),vt(0.3,7,0.7)) msh30=mesh("SpecialMesh",aprt30,"Wedge","",vt(0,0,0),vt(0.3,7,0.7)) msh32=mesh("SpecialMesh",aprt32,"Sphere","",vt(0,0,0),vt(1.5,1.5,1.5)) msh33=mesh("SpecialMesh",aprt33,"Wedge","",vt(0,0,0),vt(0.2,8,0.5)) msh34=mesh("SpecialMesh",aprt34,"Wedge","",vt(0,0,0),vt(0.2,8,0.5)) msh35=mesh("SpecialMesh",aprt35,"Wedge","",vt(0,0,0),vt(0.3,7,0.7)) msh36=mesh("SpecialMesh",aprt36,"Wedge","",vt(0,0,0),vt(0.3,7,0.7)) msh37=mesh("BlockMesh",aprt37,"","",vt(0,0,0),vt(1.51,2.5,3)) msh38=mesh("SpecialMesh",aprt38,"Wedge","",vt(0,0,0),vt(1.3,4,3)) msh39=mesh("SpecialMesh",aprt39,"Wedge","",vt(0,0,0),vt(1.3,2,3)) -- msh2=mesh("CylinderMesh",bprt2,"","",vt(0,0,0),vt(3,1,3)) msh3=mesh("CylinderMesh",bprt3,"","",vt(0,0,0),vt(2.5,1.01,2.5)) msh4=mesh("BlockMesh",bprt4,"","",vt(0,0,0),vt(7,0.5,1.5)) msh5=mesh("SpecialMesh",bprt5,"Wedge","",vt(0,0,0),vt(0.5,1.5,10)) msh6=mesh("SpecialMesh",bprt6,"Wedge","",vt(0,0,0),vt(0.3,3,4)) msh8=mesh("CylinderMesh",bprt8,"","",vt(0,0,0),vt(3,1,3)) msh9=mesh("CylinderMesh",bprt9,"","",vt(0,0,0),vt(2.5,1.01,2.5)) msh10=mesh("BlockMesh",bprt10,"","",vt(0,0,0),vt(7,0.5,1.5)) msh11=mesh("SpecialMesh",bprt11,"Wedge","",vt(0,0,0),vt(0.5,1.5,10)) msh12=mesh("SpecialMesh",bprt12,"Wedge","",vt(0,0,0),vt(0.3,3,4)) msh14=mesh("CylinderMesh",bprt14,"","",vt(0,0,0),vt(3,1,3)) msh15=mesh("CylinderMesh",bprt15,"","",vt(0,0,0),vt(2.5,1.01,2.5)) msh16=mesh("BlockMesh",bprt16,"","",vt(0,0,0),vt(7,0.5,1.5)) msh17=mesh("SpecialMesh",bprt17,"Wedge","",vt(0,0,0),vt(0.5,1.5,10)) msh18=mesh("SpecialMesh",bprt18,"Wedge","",vt(0,0,0),vt(0.3,3,4)) --wld1=weld(prt1,prt1,Torso,euler(0.5,-3.14,0)*cf(2,-2,-2)) wld1=weld(prt1,prt1,Torso,euler(2.4,0,0)*cf(2,-2,-2)) wld2=weld(prt1,prt2,prt1,euler(0,0,0)*cf(0,0,0)) wld3=weld(prt1,prt3,prt2,euler(-0.3,0,0)*cf(0,0.05,-1)) wld4=weld(prt1,prt4,prt2,euler(-0.5,0,0)*cf(0,0.1,-0.3)) wld5=weld(prt1,prt5,prt4,euler(1.57+0.5,0,0)*cf(0,-0.2,0)) wld6=weld(prt1,prt6,prt2,euler(1.57,0,0)*cf(0,-0.11,1.1)) wld7=weld(prt1,prt7,prt6,euler(0,0,0)*cf(0,-1.6,0)) wld8=weld(prt1,prt8,prt7,euler(0,0,0)*cf(0,0,0)) wld9=weld(prt1,prt9,prt6,euler(0,0,0)*cf(0,-0.3,0.2)) wld10=weld(prt1,prt10,prt9,euler(0,0,0)*cf(0,1.2,0.4)) wld11=weld(prt1,prt11,prt10,euler(0,0,3.14)*cf(0,0.6,0)) wld12=weld(prt1,prt12,prt5,euler(3.14,0,0)*cf(0,-0.2,-0.55)) wld13=weld(prt1,prt13,prt12,euler(0.785,0,0)*cf(0,0.2,-0.4)) wld14=weld(prt1,prt14,prt12,euler(0,0,0)*cf(0,-0.4,-0.2)) wld15=weld(prt1,prt15,prt14,euler(-0.8,0,0)*cf(0,-0.55,-0.2)) wld16=weld(prt1,prt16,prt14,euler(0,0,3.14)*cf(0,-0.15,0.5)) wld17=weld(prt1,prt17,prt16,euler(0,0,3.14)*cf(0,0.5,-0.3)) wld18=weld(prt1,prt18,prt2,euler(0,0,0)*cf(0.2,0,0)) --1 wld19=weld(prt1,prt19,prt18,euler(0,0,0.5)*cf(0,0,0)) wld20=weld(prt1,prt20,prt19,euler(3.14,3.14,0)*cf(0,0.8,0.05)) wld21=weld(prt1,prt21,prt19,euler(3.14,0,0)*cf(0,0.8,-0.05)) wld22=weld(prt1,prt22,prt20,euler(0,0,0)*cf(0,-0.5,0.02)) wld23=weld(prt1,prt23,prt21,euler(0,0,0)*cf(0,-0.5,0.02)) wld24=weld(prt1,prt24,prt2,euler(0,0,0)*cf(0.2,-0.1,-0.3)) --2 wld25=weld(prt1,prt25,prt24,euler(0.3,0,0.6)*cf(0,0,0)) wld26=weld(prt1,prt26,prt25,euler(3.14,3.14,0)*cf(0,0.8,0.05)) wld27=weld(prt1,prt27,prt25,euler(3.14,0,0)*cf(0,0.8,-0.05)) wld28=weld(prt1,prt28,prt26,euler(0,0,0)*cf(0,-0.5,0.02)) wld29=weld(prt1,prt29,prt27,euler(0,0,0)*cf(0,-0.5,0.02)) wld30=weld(prt1,prt30,prt2,euler(0,0,0)*cf(0.2,-0.2,-0.6)) --3 wld31=weld(prt1,prt31,prt30,euler(0.6,0,0.7)*cf(0,0,0)) wld32=weld(prt1,prt32,prt31,euler(3.14,3.14,0)*cf(0,0.8,0.05)) wld33=weld(prt1,prt33,prt31,euler(3.14,0,0)*cf(0,0.8,-0.05)) wld34=weld(prt1,prt34,prt32,euler(0,0,0)*cf(0,-0.5,0.02)) wld35=weld(prt1,prt35,prt33,euler(0,0,0)*cf(0,-0.5,0.02)) for _,c in pairs(prt1:children()) do if c.className=="Weld" then table.insert(RailgunWelds,c) end end -- --awld1=weld(aprt1,aprt1,Torso,euler(0.5,3.14,0)*cf(-2,-2,-2)) awld1=weld(aprt1,aprt1,Torso,euler(2.4,0,0)*cf(-2,-2,-2)) awld2=weld(aprt1,aprt2,aprt1,euler(0,0,0)*cf(0,0,0)) awld3=weld(aprt1,aprt3,aprt2,euler(0,3.14,0)*cf(0,-0.3,-0.4)) awld4=weld(aprt1,aprt4,aprt2,euler(0,0,0)*cf(0,-0.3,0.3)) awld5=weld(aprt1,aprt5,aprt4,euler(0,0,0)*cf(0,-0.3,0.2)) awld6=weld(aprt1,aprt6,aprt4,euler(1.57,0,0)*cf(0,-0.02,0.7)) awld7=weld(aprt1,aprt7,aprt4,euler(1.57,0,0)*cf(0,0.02,0.7)) awld8=weld(aprt1,aprt8,aprt6,euler(0,0,0)*cf(0,-0.5,0)) awld9=weld(aprt1,aprt9,aprt7,euler(0,0,0)*cf(0,-0.5,0)) awld10=weld(aprt1,aprt10,aprt8,euler(0,0,0)*cf(0,0,0)) awld11=weld(aprt1,aprt11,aprt9,euler(0,0,0)*cf(0,0,0)) awld12=weld(aprt1,aprt12,aprt4,euler(1.57,0,0)*cf(0,0.2,0.75)) awld13=weld(aprt1,aprt13,aprt5,euler(-1.57,0,0)*cf(0,-0.3,0)) awld14=weld(aprt1,aprt14,aprt13,euler(0.785,0,0)*cf(0,0.2,-0.4)) awld15=weld(aprt1,aprt15,aprt13,euler(0,0,0)*cf(0,-0.4,-0.2)) awld16=weld(aprt1,aprt16,aprt15,euler(-0.8,0,0)*cf(0,-0.55,-0.2)) awld17=weld(aprt1,aprt17,aprt15,euler(0,0,3.14)*cf(0,-0.15,0.5)) awld18=weld(aprt1,aprt18,aprt17,euler(0,0,3.14)*cf(0,0.5,-0.3)) awld19=weld(aprt1,aprt19,aprt2,euler(0,0,0)*cf(-0.2,-0.2,0.7)) --1 awld20=weld(aprt1,aprt20,aprt19,euler(0,0,-0.5)*cf(0,0,0)) awld21=weld(aprt1,aprt21,aprt20,euler(3.14,3.14,0)*cf(0,0.8,0.05)) awld22=weld(aprt1,aprt22,aprt20,euler(3.14,0,0)*cf(0,0.8,-0.05)) awld23=weld(aprt1,aprt23,aprt21,euler(0,0,0)*cf(0,-0.5,0.02)) awld24=weld(aprt1,aprt24,aprt22,euler(0,0,0)*cf(0,-0.5,0.02)) awld25=weld(aprt1,aprt25,aprt2,euler(0,0,0)*cf(-0.2,-0.3,0.4)) --2 awld26=weld(aprt1,aprt26,aprt25,euler(0.3,0,-0.6)*cf(0,0,0)) awld27=weld(aprt1,aprt27,aprt26,euler(3.14,3.14,0)*cf(0,0.8,0.05)) awld28=weld(aprt1,aprt28,aprt26,euler(3.14,0,0)*cf(0,0.8,-0.05)) awld29=weld(aprt1,aprt29,aprt27,euler(0,0,0)*cf(0,-0.5,0.02)) awld30=weld(aprt1,aprt30,aprt28,euler(0,0,0)*cf(0,-0.5,0.02)) awld31=weld(aprt1,aprt31,aprt2,euler(0,0,0)*cf(-0.2,-0.4,0.1)) --3 awld32=weld(aprt1,aprt32,aprt31,euler(0.6,0,-0.7)*cf(0,0,0)) awld33=weld(aprt1,aprt33,aprt32,euler(3.14,3.14,0)*cf(0,0.8,0.05)) awld34=weld(aprt1,aprt34,aprt32,euler(3.14,0,0)*cf(0,0.8,-0.05)) awld35=weld(aprt1,aprt35,aprt33,euler(0,0,0)*cf(0,-0.5,0.02)) awld36=weld(aprt1,aprt36,aprt34,euler(0,0,0)*cf(0,-0.5,0.02)) awld37=weld(aprt1,aprt37,aprt2,euler(-0.5,0,0)*cf(0,-0.05,-0.1)) awld38=weld(aprt1,aprt38,aprt37,euler(-1.57,3.14,0)*cf(0,0.2,0.15)) awld39=weld(aprt1,aprt339,aprt39,euler(0,0,3.14)*cf(0,0.6,0)) for _,c in pairs(aprt1:children()) do if c.className=="Weld" then table.insert(PlasmaWelds,c) end end -- brefwld=weld(bref,bref,Torso,euler(0,0,0)*cf(0,0,0)) bwld1=weld(bprt1,bprt1,bref,euler(0,0,0)*cf(1,-0.6,-2)) --1 bwld2=weld(bprt1,bprt2,bprt1,euler(0,0.5,1.57+0.4)*cf(0,0,0)) bwld3=weld(bprt1,bprt3,bprt2,euler(0,0,0)*cf(0,0,0)) bwld4=weld(bprt1,bprt4,bprt2,euler(0,0,0)*cf(-0.8,0,0)) bwld5=weld(bprt1,bprt5,bprt2,euler(-1.57,0,1.57)*cf(-0.8,0,-0.35)) bwld6=weld(bprt1,bprt6,bprt4,euler(-1.57,0,1.57)*cf(-1.1,0,-0.15)) bwld7=weld(bprt1,bprt7,bref,euler(0,0,0)*cf(0,-0.6,-2)) --2 bwld8=weld(bprt1,bprt8,bprt7,euler(0,0.5,1.57)*cf(0,0,0)) bwld9=weld(bprt1,bprt9,bprt8,euler(0,0,0)*cf(0,0,0)) bwld10=weld(bprt1,bprt10,bprt8,euler(0,0,0)*cf(-0.8,0,0)) bwld11=weld(bprt1,bprt11,bprt8,euler(-1.57,0,1.57)*cf(-0.8,0,-0.35)) bwld12=weld(bprt1,bprt12,bprt10,euler(-1.57,0,1.57)*cf(-1.1,0,-0.15)) bwld13=weld(bprt1,bprt13,bref,euler(0,0,0)*cf(-1,-0.6,-2)) --3 bwld14=weld(bprt1,bprt14,bprt13,euler(0,0.5,1.57-0.4)*cf(0,0,0)) bwld15=weld(bprt1,bprt15,bprt14,euler(0,0,0)*cf(0,0,0)) bwld16=weld(bprt1,bprt16,bprt14,euler(0,0,0)*cf(-0.8,0,0)) bwld17=weld(bprt1,bprt17,bprt14,euler(-1.57,0,1.57)*cf(-0.8,0,-0.35)) bwld18=weld(bprt1,bprt18,bprt16,euler(-1.57,0,1.57)*cf(-1.1,0,-0.15)) local hitbox1=part(3,nil,0,1,BrickColor.new("Black"),"Hitbox",vt(1,1,1)) local hitbox2=part(3,nil,0,1,BrickColor.new("Black"),"Hitbox",vt(1,1,1)) local hitbox3=part(3,nil,0,1,BrickColor.new("Black"),"Hitbox",vt(1,1,1)) if (script.Parent.className~="HopperBin") then Tool=Instance.new("HopperBin") Tool.Parent=Backpack Tool.Name="Vanguard Gauntlets" script.Parent=Tool end Bin=script.Parent --Bin=Tool local bodvel=Instance.new("BodyVelocity") local bg=Instance.new("BodyGyro") so = function(id,par,vol,pit) coroutine.resume(coroutine.create(function() local sou = Instance.new("Sound",par or workspace) sou.Volume=vol sou.Pitch=pit or 1 sou.SoundId=id swait() sou:play() game:GetService("Debris"):AddItem(sou,6) end)) end function clerp(a,b,t) local qa = {QuaternionFromCFrame(a)} local qb = {QuaternionFromCFrame(b)} local ax, ay, az = a.x, a.y, a.z local bx, by, bz = b.x, b.y, b.z local _t = 1-t return QuaternionToCFrame(_t*ax + t*bx, _t*ay + t*by, _t*az + t*bz,QuaternionSlerp(qa, qb, t)) end function QuaternionFromCFrame(cf) local mx, my, mz, m00, m01, m02, m10, m11, m12, m20, m21, m22 = cf:components() local trace = m00 + m11 + m22 if trace > 0 then local s = math.sqrt(1 + trace) local recip = 0.5/s return (m21-m12)*recip, (m02-m20)*recip, (m10-m01)*recip, s*0.5 else local i = 0 if m11 > m00 then i = 1 end if m22 > (i == 0 and m00 or m11) then i = 2 end if i == 0 then local s = math.sqrt(m00-m11-m22+1) local recip = 0.5/s return 0.5*s, (m10+m01)*recip, (m20+m02)*recip, (m21-m12)*recip elseif i == 1 then local s = math.sqrt(m11-m22-m00+1) local recip = 0.5/s return (m01+m10)*recip, 0.5*s, (m21+m12)*recip, (m02-m20)*recip elseif i == 2 then local s = math.sqrt(m22-m00-m11+1) local recip = 0.5/s return (m02+m20)*recip, (m12+m21)*recip, 0.5*s, (m10-m01)*recip end end end function QuaternionToCFrame(px, py, pz, x, y, z, w) local xs, ys, zs = x + x, y + y, z + z local wx, wy, wz = w*xs, w*ys, w*zs local xx = x*xs local xy = x*ys local xz = x*zs local yy = y*ys local yz = y*zs local zz = z*zs return CFrame.new(px, py, pz,1-(yy+zz), xy - wz, xz + wy,xy + wz, 1-(xx+zz), yz - wx, xz - wy, yz + wx, 1-(xx+yy)) end function QuaternionSlerp(a, b, t) local cosTheta = a[1]*b[1] + a[2]*b[2] + a[3]*b[3] + a[4]*b[4] local startInterp, finishInterp; if cosTheta >= 0.0001 then if (1 - cosTheta) > 0.0001 then local theta = math.acos(cosTheta) local invSinTheta = 1/math.sin(theta) startInterp = math.sin((1-t)*theta)*invSinTheta finishInterp = math.sin(t*theta)*invSinTheta else startInterp = 1-t finishInterp = t end else if (1+cosTheta) > 0.0001 then local theta = math.acos(-cosTheta) local invSinTheta = 1/math.sin(theta) startInterp = math.sin((t-1)*theta)*invSinTheta finishInterp = math.sin(t*theta)*invSinTheta else startInterp = t-1 finishInterp = t end end return a[1]*startInterp + b[1]*finishInterp, a[2]*startInterp + b[2]*finishInterp, a[3]*startInterp + b[3]*finishInterp, a[4]*startInterp + b[4]*finishInterp end function hideanim() equipped=false n=2 for i=0,1,0.05 do swait() --[[Torso.Neck.C0=necko*euler(0,0,0) RootJoint.C0=RootCF*euler(0,0,0) RW.C0=cf(1.5,0.5,0)*euler(0,0,0.5-0.5*i*n) RW.C1=cf(0,0.5,0)*euler(0,0,0) LW.C0=cf(-1.5,0.5,0)*euler(0,0,-0.5+0.5*i*n) LW.C1=cf(0,0.5,0)*euler(0,0,0)]] RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.4) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(0,0,0),.4) RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(0,0,0),.4) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(0,0,0),.4) wld1.C0=clerp(wld1.C0,euler(2.4,0,0)*cf(2,-2,-2),.4) awld1.C0=clerp(awld1.C0,euler(2.4,0,0)*cf(-2,-2,-2),.4) bwld1.C0=clerp(bwld1.C0,euler(0,0,0)*cf(1,-0.6,-2),.4) bwld7.C0=clerp(bwld7.C0,euler(0,0,0)*cf(0,-0.6,-2),.4) bwld13.C0=clerp(bwld13.C0,euler(0,0,0)*cf(-1,-0.6,-2),.4) bwld2.C0=clerp(bwld2.C0,euler(0,0.5,1.57+0.4)*cf(0,0,0),.4) bwld8.C0=clerp(bwld8.C0,euler(0,0.5,1.57)*cf(0,0,0),.4) bwld14.C0=clerp(bwld14.C0,euler(0,0.5,1.57-0.4)*cf(0,0,0),.4) brefwld.C0=clerp(brefwld.C0,euler(0,0,0)*cf(0,0,0),.4) n=n-0.1 end Torso.Neck.C0=necko Torso.Neck.C1=necko2 RootJoint.C0=RootCF RW.C0=cf(1.5,0.5,0)*euler(0,0,0) RW.C1=cf(0,0.5,0)*euler(0,0,0) LW.C0=cf(-1.5,0.5,0)*euler(0,0,0) LW.C1=cf(0,0.5,0)*euler(0,0,0) RH.C0=RHC0 RH.C1=RHC1 LH.C0=LHC0 LH.C1=LHC1 end function equipanim() equipped=true circle=0 n=2 for i=0,1,0.1 do swait() --[[Torso.Neck.C0=necko*euler(0,0,0) RootJoint.C0=RootCF*euler(0,0,0) RW.C0=cf(1.5,0.5,0)*euler(0,0,0.5*i*n) RW.C1=cf(0,0.5,0)*euler(0,0,0) LW.C0=cf(-1.5,0.5,0)*euler(0,0,-0.5*i*n) LW.C1=cf(0,0.5,0)*euler(0,0,0)]] wld1.C0=clerp(wld1.C0,euler(-0.2,0,0)*cf(3,-1,-0.2),.4) awld1.C0=clerp(awld1.C0,euler(-0.2,0,0)*cf(-3,-1,-0.2),.4) bwld1.C0=clerp(bwld1.C0,euler(0,0,0)*cf(2,-0.6,-2),.4) bwld7.C0=clerp(bwld7.C0,euler(0,0,0)*cf(0,-0.6,-2),.4) bwld13.C0=clerp(bwld13.C0,euler(0,0,0)*cf(-2,-0.6,-2),.4) bwld2.C0=clerp(bwld2.C0,euler(3.14,-2,1.57-0.4)*cf(0,0,0),.4) bwld8.C0=clerp(bwld8.C0,euler(3.14,-2,1.57)*cf(0,0,0),.4) bwld14.C0=clerp(bwld14.C0,euler(3.14,-2,1.57+0.4)*cf(0,0,0),.4) brefwld.C0=clerp(brefwld.C0,euler(0,0,0)*cf(0,-2,0),.4) n=n-0.1 end --[[Torso.Neck.C0=necko*euler(0,0,0) RootJoint.C0=RootCF*euler(0,0,0) RW.C0=cf(1.5,0.5,0)*euler(0,0,0.5) RW.C1=cf(0,0.5,0)*euler(0,0,0) LW.C0=cf(-1.5,0.5,0)*euler(0,0,-0.5) LW.C1=cf(0,0.5,0)*euler(0,0,0)]] end function AimRailGun() for i=0,1,0.1 do swait() LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(1.57,0,0),.4) end coroutine.resume(coroutine.create(function(Weld) while aimrailgun==true do wait() --[[local pos=Vector3.new(MMouse.Hit.p.x,MMouse.Hit.p.y,MMouse.Hit.p.z) offset=(RootPart.Position.y-MMouse.Hit.p.y)/60 offset2=(RootPart.Position.x-MMouse.Hit.p.x)/60 mag=(RootPart.Position-MMouse.Hit.p).magnitude/80 offset=offset/mag offset2=offset2/mag ]] --[[cff=cf(prt2.CFrame.p,MMouse.Hit.p) local HitPos=cff.p local CJ=cf(HitPos) local C0=cff:inverse() *CJ local C1=prt2.CFrame:inverse() * CJ wld1.Part1=RootPart]] --[[Weld.C0=euler(0,0,0)*cf(3,-1,-0.2) wld2.C0=CFrame.Angles(math.asin(MMouse.Hit.p.x),math.rad(0),math.atan2(MMouse.Hit.p.z,MMouse.Hit.p.x))]] local mpos = prt1.CFrame*euler(0,0,0)--*CFrame.new(3,-1,-0.2) -- thx doogle <3 local cff = CFrame.new(mpos.p,MMouse.Hit.p) * CFrame.Angles(math.pi/2,0,0) local x,y,z = prt1.CFrame:toObjectSpace(cff):toEulerAnglesXYZ() wld1.Part1=RailgunTarget wld1.C0=euler(0,0,0)*cf(3,-1,-0.2) wld2.Part0=prt1 wld2.Part1=prt2 wld2.C0=clerp(wld2.C0,CFrame.Angles(x,y,z)*euler(-1.57,0,0),.3) end end),wld1) end function UnAimRailGun() for i=0,1,0.1 do swait() --LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(0,0,-0.5),.4) --[[wld2.Part0=prt2 wld2.Part1=prt1]] wld1.Part1=RailgunTarget.Parent.Torso wld1.C0=clerp(wld1.C0,euler(-0.2,0,0)*cf(3,-1,-0.2),.5) wld2.C0=clerp(wld2.C0,euler(0,0,0)*cf(0,0,0),.5) --wld1.C0=euler(-0.2,-0.3,0)*cf(3,-1,-0.2) end attack=false end function AimCannon() for i=0,1,0.1 do swait() RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(1.57,0,0),.4) end coroutine.resume(coroutine.create(function(Weld) while aimcannon==true do wait() --[[local pos=Vector3.new(MMouse.Hit.p.x,MMouse.Hit.p.y,MMouse.Hit.p.z) offset=(RootPart.Position.y-MMouse.Hit.p.y)/60 offset2=(RootPart.Position.x-MMouse.Hit.p.x)/60 mag=(RootPart.Position-MMouse.Hit.p).magnitude/80 offset=offset/mag offset2=offset2/mag ]] --[[cff=cf(prt2.CFrame.p,MMouse.Hit.p) local HitPos=cff.p local CJ=cf(HitPos) local C0=cff:inverse() *CJ local C1=prt2.CFrame:inverse() * CJ wld1.Part1=RootPart]] --[[Weld.C0=euler(0,0,0)*cf(3,-1,-0.2) wld2.C0=CFrame.Angles(math.asin(MMouse.Hit.p.x),math.rad(0),math.atan2(MMouse.Hit.p.z,MMouse.Hit.p.x))]] local mpos = aprt1.CFrame*euler(0,0,0)--*CFrame.new(3,-1,-0.2) -- thx doogle <3 local cff = CFrame.new(mpos.p,MMouse.Hit.p) * CFrame.Angles(math.pi/2,0,0) local x,y,z = aprt1.CFrame:toObjectSpace(cff):toEulerAnglesXYZ() awld1.Part1=CannonTarget awld1.C0=euler(0,0,0)*cf(-3,-1,-0.2) awld2.Part0=aprt1 awld2.Part1=aprt2 awld2.C0=clerp(awld2.C0,CFrame.Angles(x,y,z)*euler(-1.57,0,0),.3) end end),wld1) end function UnAimCannon() for i=0,1,0.1 do swait() --RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(0,0,0.5),.4) --[[awld2.Part0=aprt2 awld2.Part1=aprt1]] awld1.Part1=CannonTarget.Parent.Torso awld1.C0=clerp(awld1.C0,euler(-0.2,0,0)*cf(-3,-1,-0.2),.5) awld2.C0=clerp(awld2.C0,euler(0,0,0)*cf(0,0,0),.5) --awld1.C0=euler(-0.2,0.3,0)*cf(-3,-1,-0.2) end end function ShootRailGun() so(Asset.."169380505",prt8,.5,1) local MouseLook=cf((prt8.Position+MMouse.Hit.p)/2,MMouse.Hit.p) local hit,pos = rayCast(prt8.Position,MouseLook.lookVector,999,RailgunTarget.Parent) local mag=(prt8.Position-pos).magnitude MagicCylinder(BrickColor.new("Cyan"),CFrame.new((prt8.Position+pos)/2,pos)*angles(1.57,0,0),1,mag*5,1,1.2,0,1.2,0.1) if hit~=nil then ref=part(3,workspace,0,1,Color3,"Reference",vt()) ref.Anchored=true ref.CFrame=cf(pos) game:GetService("Debris"):AddItem(ref,1) so(Asset.."153092334",ref,.5,1.5) so(Asset.."169380505",ref,.5,1.5) MagicCircle(BrickColor.new("Cyan"),cf(pos),10,10,10,1,1,1,0.07) Damagefunc(hit,100,150,99,"Normal",RootPart,0) end end function ShootCannon() so(Asset.."161006069",hit,.5,1) local MainPos=aprt8.Position local MainPos2=MMouse.Hit.p local MouseLook=cf((MainPos+MainPos2)/2,MainPos2) --[[local mag=(MainPos-pos).magnitude MagicCylinder(BrickColor.new("Really black"),CFrame.new((MainPos+pos)/2,pos)*angles(1.57,0,0),1,mag*5,1,0.5,0,0.5,0.05)]] num=30 coroutine.resume(coroutine.create(function() repeat wait() local hit,pos = rayCast(MainPos,MouseLook.lookVector,10,CannonTarget.Parent) local mag=(MainPos-pos).magnitude MagicCylinder2(BrickColor.new("Really black"),CFrame.new((MainPos+pos)/2,pos)*angles(1.57,0,0),3,mag*5,3,1.5,0,1.5,0.1) MainPos=MainPos+(MouseLook.lookVector*10) num=num-1 if hit~=nil then num=0 Damagefunc(hit,2000,3000,990,"Normal",RootPart,.2) ref=part(3,workspace,0,1,Color3,"Reference",vt()) ref.Anchored=true ref.CFrame=cf(pos) so(Asset.."169445602",ref,1,0.8) so(Asset.."153092334",ref,1,0.8) MagicBlock(BrickColor.new("Really black"),cf(pos),20,20,20,5,5,5,0.05) game:GetService("Debris"):AddItem(ref,1) MagniDamage(ref,15,10,20,0,"Normal") end until num<=0 end)) end function ChangeTargetPose() for i=0,1,0.05 do swait() wld1.C0=clerp(wld1.C0,euler(-0.2,0,-0.3)*cf(4,-1,-0.2),.4) awld1.C0=clerp(awld1.C0,euler(-0.2,0,0.3)*cf(-4,-1,-0.2),.4) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(0.2,0,0),.3) RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(0,0,1.57),.3) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(0,0,-1.57),.3) end end function ChangeRailgunTarget() Targ=MMouse.Target if Targ~=nil and Targ.Parent:findFirstChild("Humanoid")~=nil and Targ.Parent:findFirstChild("Torso")~=nil and Targ.Parent:findFirstChild("HumanoidRootPart")~=nil then RailgunTarget=Targ.Parent.HumanoidRootPart wld1.Part1=RailgunTarget.Parent.Torso local Dur=RailgunTarget local Hum=RailgunTarget.Parent.Humanoid local WalkSpeed=16 if Hum.WalkSpeed>16 then WalkSpeed=WalkSpeed*1.2 else WalkSpeed=Hum.WalkSpeed*1.2 end coroutine.resume(coroutine.create(function(Model) while RailgunTarget==Model do if Hum.WalkSpeed>5 then Hum.WalkSpeed=WalkSpeed end MagicCircle(BrickColor.new("Bright orange"),cf(Model.Parent.HumanoidRootPart.Position)*cf(math.random(-200,200)/100,-2.5,math.random(-200,200)/100),.5,1,.5,.3,4,.3,0.05) wait(.8) end Hum.WalkSpeed=16 end),Dur) end end function ChangeCannonTarget() Targ=MMouse.Target if Targ~=nil and Targ.Parent:findFirstChild("Humanoid")~=nil and Targ.Parent:findFirstChild("Torso")~=nil and Targ.Parent:findFirstChild("HumanoidRootPart")~=nil then CannonTarget=Targ.Parent.HumanoidRootPart awld1.Part1=CannonTarget.Parent.Torso local Dur=CannonTarget local Hum=CannonTarget.Parent.Humanoid Hum.MaxHealth=Hum.MaxHealth+50 Hum.Health=Hum.Health+50 coroutine.resume(coroutine.create(function(Model) while CannonTarget==Model do MagicCircle(BrickColor.new("Bright orange"),cf(Model.Parent.HumanoidRootPart.Position)*cf(math.random(-200,200)/100,-2.5,math.random(-200,200)/100),.5,1,.5,.3,4,.3,0.05) wait(1) end if Hum.MaxHealth>150 then Hum.MaxHealth=Hum.MaxHealth-50 Hum.Health=Hum.Health-50 else Hum.MaxHealth=100 end end),Dur) end end function BackToMe() model1.Parent=Character model2.Parent=Character for i=1,#Railgun do Railgun[i].Parent=model1 RailgunWelds[i].Parent=Railgun[1] end for i=1,#Plasma do Plasma[i].Parent=model2 PlasmaWelds[i].Parent=Plasma[1] end RailgunTarget=RootPart CannonTarget=RootPart wld1.Part1=RailgunTarget.Parent.Torso awld1.Part1=CannonTarget.Parent.Torso end function attackone() attack=true bladeattack=true --bprt4, bprt10, bprt16 for i=0,1,0.1 do swait() brefwld.C0=clerp(brefwld.C0,euler(0,0,0)*cf(0,-2.5,2),.4) bwld1.C0=clerp(bwld1.C0,euler(0,0,0)*cf(3,-0.6,-2),.4) bwld7.C0=clerp(bwld7.C0,euler(0,0,0)*cf(0,-0.6,-2),.4) bwld13.C0=clerp(bwld13.C0,euler(0,0,0)*cf(-3,-0.6,-2),.4) bwld2.C0=clerp(bwld2.C0,euler(3.14,-1.5,1)*cf(0,0,0),.4) bwld8.C0=clerp(bwld8.C0,euler(3.14,-1.5,1.57)*cf(0,0,0),.4) bwld14.C0=clerp(bwld14.C0,euler(3.14,-1.5,2)*cf(0,0,0),.4) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(-0.3,0,0),.4) RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(3,0,-0.2),.4) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(3,0,0.2),.4) end BladesDamage(math.random(100,200)/100) for i=0,1,0.2 do swait() brefwld.C0=clerp(brefwld.C0,euler(1.57,0,0)*cf(0,1.5,3),i) bwld2.C0=clerp(bwld2.C0,euler(3.14,-1.5,1.57)*cf(0,0,0),i) bwld8.C0=clerp(bwld8.C0,euler(3.14,-1.5,1.57)*cf(0,0,0),i) bwld14.C0=clerp(bwld14.C0,euler(3.14,-1.5,1.57)*cf(0,0,0),i) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(0.3,0,0),i) RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(1,0,0.2),i) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(1,0,-0.2),i) end for i=0,1,0.1 do swait() brefwld.C0=clerp(brefwld.C0,euler(1.7,0,0)*cf(0,2,3),.3) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(0.4,0,0),.3) RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(.5,0,0.2),.3) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(.5,0,-0.2),.3) end attack=false bladeattack=false --equipanim() end function attacktwo() attack=true bladeattack=true for i=0,1,0.1 do swait() brefwld.C0=clerp(brefwld.C0,euler(0,-1,0)*cf(6,1,3),.4) bwld1.C0=clerp(bwld1.C0,euler(0,-0.5,0)*cf(2,-0.6,-2),.4) bwld7.C0=clerp(bwld7.C0,euler(0,0,0)*cf(0,-0.6,-2),.4) bwld13.C0=clerp(bwld13.C0,euler(0,0.5,0)*cf(-2,-0.6,-2),.4) bwld2.C0=clerp(bwld2.C0,euler(4.71,-1.57,1.57)*cf(0,0,0),.4) bwld8.C0=clerp(bwld8.C0,euler(4.71,-1.57,1.57)*cf(0,0,0),.4) bwld14.C0=clerp(bwld14.C0,euler(4.71,-1.57,1.57)*cf(0,0,0),.4) RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0.6),.4) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(0,0,-0.6),.4) RW.C0=clerp(RW.C0,cf(1,0.5,-0.5)*euler(1.57,0,-1),.4) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(0,0.1,-1.57),.4) end BladesDamage(math.random(80,150)/100) for i=0,1,0.15 do swait() brefwld.C0=clerp(brefwld.C0,euler(0,1,0)*cf(-6,1,3),i) RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,-0.6),.4) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(0,0,0.6),.4) RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(0,-0.1,1.57),.4) LW.C0=clerp(LW.C0,cf(-1,0.5,-0.5)*euler(1.57,0,1),.4) end for i=0,1,0.1 do swait() brefwld.C0=clerp(brefwld.C0,euler(0,1.7,0)*cf(-6,1,-1),.3) RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(0,-0.3,1.57),.3) LW.C0=clerp(LW.C0,cf(-1,0.5,-0.5)*euler(1.57,0,1.3),.3) end attack=false bladeattack=false end function attackthree() attack=true bladeattack=true for i=0,1,0.09 do swait() bwld1.C0=clerp(bwld1.C0,cf(0,-4,-2)*euler(0,0,2.09),.4) bwld7.C0=clerp(bwld7.C0,cf(0,-4,-2)*euler(0,0,2.09*2),.4) bwld13.C0=clerp(bwld13.C0,cf(0,-4,-2)*euler(0,0,2.09*3),.4) bwld2.C0=clerp(bwld2.C0,euler(3.14,-1.3,1.57)*cf(0,0,0),.4) bwld8.C0=clerp(bwld8.C0,euler(3.14,-1.3,1.57)*cf(0,0,0),.4) bwld14.C0=clerp(bwld14.C0,euler(3.14,-1.3,1.57)*cf(0,0,0),.4) brefwld.C0=clerp(brefwld.C0,euler(0,0,0)*cf(0,0,-2),.4) RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.4) RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(0,0,1.57),.3) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(0,0,-1.57),.3) end BladesDamage(math.random(100,200)/100) n=math.random(-50,50) for i=0,1,0.2 do swait() bwld1.C0=clerp(bwld1.C0,cf(0,-1.2,-2)*euler(0,0,2.09),.4) bwld7.C0=clerp(bwld7.C0,cf(0,-1.2,-2)*euler(0,0,2.09*2),.4) bwld13.C0=clerp(bwld13.C0,cf(0,-1.2,-2)*euler(0,0,2.09*3),.4) bwld2.C0=clerp(bwld2.C0,euler(3.14,-1.3,1.57)*cf(0,0,0),.4) bwld8.C0=clerp(bwld8.C0,euler(3.14,-1.3,1.57)*cf(0,0,0),.4) bwld14.C0=clerp(bwld14.C0,euler(3.14,-1.3,1.57)*cf(0,0,0),.4) brefwld.C0=clerp(brefwld.C0,euler(0,0,n)*cf(0,0,6),.4) RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(0,2,1.57),.4) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(0,-2,-1.57),.4) end n=math.random(-50,50) for i=0,1,0.1 do swait() bwld1.C0=clerp(bwld1.C0,cf(0,-1,-2)*euler(0,0,2.09),.3) bwld7.C0=clerp(bwld7.C0,cf(0,-1,-2)*euler(0,0,2.09*2),.3) bwld13.C0=clerp(bwld13.C0,cf(0,-1,-2)*euler(0,0,2.09*3),.3) brefwld.C0=clerp(brefwld.C0,euler(0,0,n)*cf(0,0,7),.3) end attack=false bladeattack=false end function attackfour() attack=true bladeattack=true for i=0,1,0.09 do swait() bwld1.C0=clerp(bwld1.C0,cf(0,-1,0)*euler(0,0,2.09),.4) bwld7.C0=clerp(bwld7.C0,cf(0,-1,0)*euler(0,0,2.09*2),.4) bwld13.C0=clerp(bwld13.C0,cf(0,-1,0)*euler(0,0,2.09*3),.4) bwld2.C0=clerp(bwld2.C0,euler(1.57,0,-1.57)*cf(0,0,0),.4) bwld8.C0=clerp(bwld8.C0,euler(1.57,0,-1.57)*cf(0,0,0),.4) bwld14.C0=clerp(bwld14.C0,euler(1.57,0,-1.57)*cf(0,0,0),.4) brefwld.C0=clerp(brefwld.C0,euler(-1.57,0,0)*cf(-5,-0.5,0),.4) RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,-1),.4) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(0,0,1),.4) RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(0,0,1.57),.3) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(-0.4,0,0),.3) end BladesDamage(math.random(40,80)/100) for i=0,1,0.25 do swait() bwld1.C0=clerp(bwld1.C0,cf(0,-1,0)*euler(0,0,(2.09)+3.1),.3) bwld7.C0=clerp(bwld7.C0,cf(0,-1,0)*euler(0,0,(2.09*2)+3.1),.3) bwld13.C0=clerp(bwld13.C0,cf(0,-1,0)*euler(0,0,(2.09*3)+3.1),.3) brefwld.C0=clerp(brefwld.C0,euler(-1.57,0,0)*cf(0,-0.5,8),.5) RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.5) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(0,0,0),.5) RW.C0=clerp(RW.C0,cf(1,0.5,-0.5)*euler(0,2,1.57),.5) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(-0.4,0,-0.2),.5) end for i=0,1,0.2 do swait() bwld1.C0=clerp(bwld1.C0,cf(0,-1,0)*euler(0,0,(2.09)+5),.3) bwld7.C0=clerp(bwld7.C0,cf(0,-1,0)*euler(0,0,(2.09*2)+5),.3) bwld13.C0=clerp(bwld13.C0,cf(0,-1,0)*euler(0,0,(2.09*3)+5),.3) brefwld.C0=clerp(brefwld.C0,euler(-1.57,0,0)*cf(0,-0.5,20),.3) RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.3) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(0,0,0),.3) RW.C0=clerp(RW.C0,cf(1,0.5,-0.5)*euler(0,2.5,1.57),.3) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(-0.4,0,-0.2),.3) end for i=0,1,0.2 do swait() brefwld.C0=clerp(brefwld.C0,euler(-1.57,0,0)*cf(0,-2,0),.5) bwld1.C0=clerp(bwld1.C0,cf(0,-1,0)*euler(0,0,(2.09)),.3) bwld7.C0=clerp(bwld7.C0,cf(0,-1,0)*euler(0,0,(2.09*2)),.3) bwld13.C0=clerp(bwld13.C0,cf(0,-1,0)*euler(0,0,(2.09*3)),.3) end attack=false bladeattack=false end function BladesDamage(pitch) so("http://www.roblox.com/asset/?id=161006195",bprt1,.6,pitch) so("http://www.roblox.com/asset/?id=161006195",bprt7,.6,pitch) so("http://www.roblox.com/asset/?id=161006195",bprt13,.6,pitch) hitbox1.Parent=Character hitbox1.Size=vt(1,2,1) hitbox1.CFrame=bprt4.CFrame*euler(0,0,1.57) hitbox1.Transparency=1 hitbox2.Parent=Character hitbox2.Size=vt(1,2,1) hitbox2.CFrame=bprt10.CFrame*euler(0,0,1.57) hitbox3.Parent=Character hitbox3.Size=vt(1,2,1) hitbox3.CFrame=bprt16.CFrame*euler(0,0,1.57) con1=hitbox1.Touched:connect(function(hit) Damagefunc(hit,10,20,math.random(1,5),"Normal",RootPart,.5,1) end) con2=hitbox2.Touched:connect(function(hit) Damagefunc(hit,10,20,math.random(1,5),"Normal",RootPart,.5,1) end) con3=hitbox3.Touched:connect(function(hit) Damagefunc(hit,10,20,math.random(1,5),"Normal",RootPart,.5,1) end) coroutine.resume(coroutine.create(function() while attack==true do swait() hitbox1.CFrame=bprt4.CFrame*euler(0,0,1.57) hitbox2.CFrame=bprt10.CFrame hitbox3.CFrame=bprt16.CFrame end con1:disconnect() con2:disconnect() con3:disconnect() hitbox1.Parent=nil hitbox2.Parent=nil hitbox3.Parent=nil end)) end function MagniDamage(Part,magni,mindam,maxdam,knock,Type) for _,c in pairs(workspace:children()) do local hum=c:findFirstChild("Humanoid") if hum~=nil then local head=c:findFirstChild("Torso") if head~=nil then local targ=head.Position-Part.Position local mag=targ.magnitude if mag<=magni and c.Name~=Player.Name then if c~=CannonTarget.Parent or c~=RailgunTarget.Parent then Damagefunc(head,mindam,maxdam,knock,Type,RootPart,.2,1,nil,1) end end end end end end function rayCast(Pos, Dir, Max, Ignore) -- Origin Position , Direction, MaxDistance , IgnoreDescendants return game:service("Workspace"):FindPartOnRay(Ray.new(Pos, Dir.unit * (Max or 999.999)), Ignore) end local Point=Torso.CFrame*cf(0,Torso.Size.Y,0) LastPoint=Point function effect(Color,Ref,LP,P1,returnn) local effectsmsh=Instance.new("CylinderMesh") effectsmsh.Scale=Vector3.new(0.2,1,0.2) effectsmsh.Name="Mesh" local effectsg=Instance.new("Part") effectsg.formFactor=3 effectsg.CanCollide=false effectsg.Name="Eff" effectsg.Locked=true effectsg.Anchored=true effectsg.Size=Vector3.new(0.5,1,0.5) effectsg.Parent=workspace effectsmsh.Parent=effectsg effectsg.BrickColor=BrickColor.new(Color) effectsg.Reflectance=Ref local point1=P1 local mg=(LP.p - point1.p).magnitude effectsg.Size=Vector3.new(0.5,mg,0.5) effectsg.CFrame=cf((LP.p+point1.p)/2,point1.p) * CFrame.Angles(math.rad(90),0,0) effectsmsh.Scale=Vector3.new(0.2,1,0.2) game:GetService("Debris"):AddItem(effectsg,2) if returnn then return effectsg end coroutine.resume(coroutine.create(function(Part,Mesh) if not returnn then for i=0,1,0.05 do wait() Part.Transparency=1*i Mesh.Scale=Vector3.new(0.5-0.5*i,1,0.5-0.5*i) end Part.Parent=nil end end),effectsg,effectsmsh) end local function CFrameFromTopBack(at, top, back) local right = top:Cross(back) return CFrame.new(at.x, at.y, at.z, right.x, top.x, back.x, right.y, top.y, back.y, right.z, top.z, back.z) end function Triangle(a, b, c) local edg1 = (c-a):Dot((b-a).unit) local edg2 = (a-b):Dot((c-b).unit) local edg3 = (b-c):Dot((a-c).unit) if edg1 <= (b-a).magnitude and edg1 >= 0 then a, b, c = a, b, c elseif edg2 <= (c-b).magnitude and edg2 >= 0 then a, b, c = b, c, a elseif edg3 <= (a-c).magnitude and edg3 >= 0 then a, b, c = c, a, b else assert(false, "unreachable") end local len1 = (c-a):Dot((b-a).unit) local len2 = (b-a).magnitude - len1 local width = (a + (b-a).unit*len1 - c).magnitude local maincf = CFrameFromTopBack(a, (b-a):Cross(c-b).unit, -(b-a).unit) local list = {} if len1 > 0.01 then local w1 = Instance.new('WedgePart', m) w1.Material = "SmoothPlastic" w1.FormFactor = 'Custom' w1.BrickColor = BrickColor.new("Bright orange") w1.Transparency = 0 w1.Reflectance = 0 w1.Material = "SmoothPlastic" w1.CanCollide = false NoOutline(w1) local sz = Vector3.new(0.2, width, len1) w1.Size = sz local sp = Instance.new("SpecialMesh",w1) sp.MeshType = "Wedge" sp.Scale = Vector3.new(0,1,1) * sz/w1.Size w1:BreakJoints() w1.Anchored = true w1.Parent = workspace w1.Transparency = 0.7 coroutine.resume(coroutine.create(function(Part) for i=0,1,0.1 do wait() Part.Transparency=Part.Transparency+0.03 end end),w1) w1.CFrame = maincf*CFrame.Angles(math.pi,0,math.pi/2)*CFrame.new(0,width/2,len1/2) table.insert(list,w1) end if len2 > 0.01 then local w2 = Instance.new('WedgePart', m) w2.Material = "SmoothPlastic" w2.FormFactor = 'Custom' w2.BrickColor = BrickColor.new("Bright orange") w2.Transparency = 0 w2.Reflectance = 0 w2.Material = "SmoothPlastic" w2.CanCollide = false NoOutline(w2) local sz = Vector3.new(0.2, width, len2) w2.Size = sz local sp = Instance.new("SpecialMesh",w2) sp.MeshType = "Wedge" sp.Scale = Vector3.new(0,1,1) * sz/w2.Size w2:BreakJoints() w2.Anchored = true w2.Parent = workspace w2.Transparency = 0.7 coroutine.resume(coroutine.create(function(Part) for i=0,1,0.1 do wait() Part.Transparency=Part.Transparency+0.03 end end),w2) w2.CFrame = maincf*CFrame.Angles(math.pi,math.pi,-math.pi/2)*CFrame.new(0,width/2,-len1 - len2/2) table.insert(list,w2) end return unpack(list) end --[[ Things for effects put the variables in one table like effect={brick,interval,i} ]] local Effects={} function MagicBlock(brickcolor,cframe,x1,y1,z1,x3,y3,z3,delay) local prt=part(3,workspace,0,0,brickcolor,"Effect",vt()) prt.Anchored=true prt.CFrame=cframe msh=mesh("BlockMesh",prt,"","",vt(0,0,0),vt(x1,y1,z1)) game:GetService("Debris"):AddItem(prt,5) table.insert(Effects,{prt,"Block1",delay,x3,y3,z3}) --part, type, delay --[[coroutine.resume(coroutine.create(function(Part,Mesh,dur) for i=0,1,delay do wait() Part.CFrame=Part.CFrame*euler(math.random(-50,50),math.random(-50,50),math.random(-50,50)) Part.Transparency=i Mesh.Scale=Mesh.Scale+vt(x3,y3,z3) end Part.Parent=nil end),prt,msh)]] end function MagicCircle(brickcolor,cframe,x1,y1,z1,x3,y3,z3,delay) local prt=part(3,workspace,0,0,brickcolor,"Effect",vt()) prt.Anchored=true prt.CFrame=cframe local msh=mesh("SpecialMesh",prt,"Sphere","",vt(0,0,0),vt(x1,y1,z1)) game:GetService("Debris"):AddItem(prt,5) table.insert(Effects,{prt,"Cylinder",delay,x3,y3,z3}) --[[coroutine.resume(coroutine.create(function(Part,Mesh) local wld=nil for i=0,1,delay do wait() Part.CFrame=Part.CFrame Part.Transparency=i Mesh.Scale=Mesh.Scale+vt(x3,y3,z3) end Part.Parent=nil end),prt,msh)]] end function MagicRing(brickcolor,cframe,x1,y1,z1,x3,y3,z3,delay,Type,parent) local prt=part(3,workspace,0,0,brickcolor,"Effect",vt()) if Type~=2 then prt.Anchored=true end prt.CFrame=cframe local msh=mesh("SpecialMesh",prt,"FileMesh","http://www.roblox.com/asset/?id=3270017",vt(0,0,0),vt(x1,y1,z1)) game:GetService("Debris"):AddItem(prt,5) coroutine.resume(coroutine.create(function(Part,Mesh,dur) local wld=nil if dur==2 then wld=weld(Part,Part,parent,euler(0,0,0)*cf(0,0,0)) end for i=0,1,delay do wait() if dur==1 then Part.CFrame=Part.CFrame elseif dur==2 then wld.C0=cframe end Part.Transparency=i Mesh.Scale=Mesh.Scale+vt(x3,y3,z3) end Part.Parent=nil end),prt,msh,Type) end function MagicWaveThing(brickcolor,cframe,x1,y1,z1,x3,y3,z3,delay) local prt=part(3,workspace,0,0,brickcolor,"Effect",vt()) prt.Anchored=true prt.CFrame=cframe msh=mesh("SpecialMesh",prt,"FileMesh","http://www.roblox.com/asset/?id=1051557",vt(0,0,0),vt(x1,y1,z1)) game:GetService("Debris"):AddItem(prt,5) coroutine.resume(coroutine.create(function(Part,Mesh) for i=0,1,delay do wait() Part.CFrame=Part.CFrame*euler(0,0.7,0) Part.Transparency=i Mesh.Scale=Mesh.Scale+vt(x3,y3,z3) end Part.Parent=nil end),prt,msh) end function WaveEffect(brickcolor,cframe,x1,y1,z1,x3,y3,z3,delay,mshtype) local prt=part(3,workspace,0,0,brickcolor,"Effect",vt()) prt.Anchored=true prt.CFrame=cframe local thetype="" if mshtype==1 then thetype="http://www.roblox.com/asset/?id=20329976" elseif mshtype==2 then thetype="http://www.roblox.com/asset/?id=1323306" end msh=mesh("SpecialMesh",prt,"FileMesh",thetype,vt(0,0,0),vt(x1,y1,z1)) game:GetService("Debris"):AddItem(prt,2) coroutine.resume(coroutine.create(function(Part,Mesh) for i=0,1,delay do wait() Part.CFrame=Part.CFrame*cf(0,y3/2,0) Part.Transparency=i Mesh.Scale=Mesh.Scale+vt(x3,y3,z3) end Part.Parent=nil end),prt,msh) end function MagicCylinder(brickcolor,cframe,x1,y1,z1,x3,y3,z3,delay) local prt=part(3,Character,0,0,brickcolor,"Effect",vt(0.2,0.2,0.2)) prt.Anchored=true prt.CFrame=cframe msh=mesh("SpecialMesh",prt,"Head","",vt(0,0,0),vt(x1,y1,z1)) game:GetService("Debris"):AddItem(prt,5) --table.insert(Effects,{prt,"Cylinder",delay,x3,y3,z3}) Effects[#Effects+1]={prt,"Cylinder",delay,x3,y3,z3} --part, type, delay --[[coroutine.resume(coroutine.create(function(Part,Mesh) for i=0,1,delay do wait() Part.CFrame=Part.CFrame Part.Transparency=i Mesh.Scale=Mesh.Scale+vt(x3,y3,z3) end Part.Parent=nil end),prt,msh)]] end function MagicCylinder2(brickcolor,cframe,x1,y1,z1,x3,y3,z3,delay) local prt=part(3,Character,0,0,brickcolor,"Effect",vt(0.2,0.2,0.2)) prt.Anchored=true prt.CFrame=cframe msh=mesh("CylinderMesh",prt,"","",vt(0,0,0),vt(x1,y1,z1)) game:GetService("Debris"):AddItem(prt,5) --table.insert(Effects,{prt,"Cylinder",delay,x3,y3,z3}) Effects[#Effects+1]={prt,"Cylinder",delay,x3,y3,z3} --part, type, delay --[[coroutine.resume(coroutine.create(function(Part,Mesh) for i=0,1,delay do wait() Part.CFrame=Part.CFrame Part.Transparency=i Mesh.Scale=Mesh.Scale+vt(x3,y3,z3) end Part.Parent=nil end),prt,msh)]] end function ElecEffect(cff,x,y,z) local prt=part(3,workspace,0,0,BrickColor.new("Bright orange"),"Part",vt(1,1,1)) prt.Anchored=true prt.CFrame=cf(cff)*cf(math.random(-x,x),math.random(-y,y),math.random(-z,z)) game:GetService("Debris"):AddItem(prt,2) xval=math.random()/2 yval=math.random()/2 zval=math.random()/2 msh=mesh("BlockMesh",prt,"","",vt(0,0,0),vt(xval,yval,zval)) Effects[#Effects+1]={prt,"Elec",0.1,x,y,z,xval,yval,zval} --part, type, delay --[[coroutine.resume(coroutine.create(function(Part,Mesh,Frame,xvaal,yvaal,zvaal) Part.CFrame=cf(Frame)*cf(math.random(-x,x),math.random(-y,y),math.random(-z,z)) for i=0,1,0.05 do swait() xvaal=xvaal-0.1 yvaal=yvaal-0.1 zvaal=zvaal-0.1 Mesh.Scale=vt(xvaal,yvaal,zvaal) Part.Transparency=i end Part.Parent=nil end),prt,msh,cff,xval,yval,zval)]] end Damagefunc=function(hit,minim,maxim,knockback,Type,Property,Delay,KnockbackType,decreaseblock) if hit.Parent==nil then return end h=hit.Parent:FindFirstChild("Humanoid") for _,v in pairs(hit.Parent:children()) do if v:IsA("Humanoid") then h=v end end if hit.Parent.Parent:FindFirstChild("Torso")~=nil then h=hit.Parent.Parent:FindFirstChild("Humanoid") end if hit.Parent.className=="Hat" then hit=hit.Parent.Parent:findFirstChild("Head") end -- and hit.Parent~=CannonTarget.Parent or hit.Parent~=RailgunTarget.Parent if h~=nil and hit.Parent.Name~=Character.Name and hit.Parent:FindFirstChild("Torso")~=nil then if hit.Parent~=CannonTarget.Parent and hit.Parent~=RailgunTarget.Parent then if hit.Parent:findFirstChild("DebounceHit")~=nil then if hit.Parent.DebounceHit.Value==true then return end end --[[ if game.Players:GetPlayerFromCharacter(hit.Parent)~=nil then return end]] -- hs(hit,1.2) c=Instance.new("ObjectValue") c.Name="creator" c.Value=game:service("Players").LocalPlayer c.Parent=h game:GetService("Debris"):AddItem(c,.5) Damage=math.random(minim,maxim) -- h:TakeDamage(Damage) blocked=false block=hit.Parent:findFirstChild("Block") if block~=nil then print(block.className) if block.className=="NumberValue" then if block.Value>0 then blocked=true if decreaseblock==nil then block.Value=block.Value-1 end end end if block.className=="IntValue" then if block.Value>0 then blocked=true if decreaseblock~=nil then block.Value=block.Value-1 end end end end if blocked==false then -- h:TakeDamage(Damage) h.Health=h.Health-Damage showDamage(hit.Parent,Damage,.50,BrickColor:Red()) else h.Health=h.Health-(Damage/50) showDamage(hit.Parent,Damage/100,.50,BrickColor.new("Really black")) end if Type=="Knockdown" then hum=hit.Parent.Humanoid hum.PlatformStand=true coroutine.resume(coroutine.create(function(HHumanoid) swait(1) HHumanoid.PlatformStand=false end),hum) local angle=(hit.Position-(Property.Position+Vector3.new(0,0,0))).unit --hit.CFrame=cf(hit.Position,Vector3.new(angle.x,hit.Position.y,angle.z))*CFrame.fromEulerAnglesXYZ(math.pi/4,0,0) local bodvol=Instance.new("BodyVelocity") bodvol.velocity=angle*knockback bodvol.P=5000 bodvol.maxForce=Vector3.new(8e+003, 8e+003, 8e+003) bodvol.Parent=hit rl=Instance.new("BodyAngularVelocity") rl.P=3000 rl.maxTorque=Vector3.new(500000,500000,500000)*50000000000000 rl.angularvelocity=Vector3.new(math.random(-10,10),math.random(-10,10),math.random(-10,10)) rl.Parent=hit game:GetService("Debris"):AddItem(bodvol,.5) game:GetService("Debris"):AddItem(rl,.5) elseif Type=="Normal" then vp=Instance.new("BodyVelocity") vp.P=500 vp.maxForce=Vector3.new(math.huge,0,math.huge) -- vp.velocity=Character.Torso.CFrame.lookVector*Knockback if KnockbackType==1 then vp.velocity=Property.CFrame.lookVector*knockback+Property.Velocity/1.05 elseif KnockbackType==2 then vp.velocity=Property.CFrame.lookVector*knockback end if knockback>0 then vp.Parent=hit.Parent.Torso end game:GetService("Debris"):AddItem(vp,.5) elseif Type=="Up" then local bodyVelocity=Instance.new("BodyVelocity") bodyVelocity.velocity=vt(0,30,0) bodyVelocity.P=5000 bodyVelocity.maxForce=Vector3.new(8e+003, 8e+003, 8e+003) bodyVelocity.Parent=hit game:GetService("Debris"):AddItem(bodyVelocity,1) rl=Instance.new("BodyAngularVelocity") rl.P=3000 rl.maxTorque=Vector3.new(500000,500000,500000)*50000000000000 rl.angularvelocity=Vector3.new(math.random(-5,5),math.random(-5,5),math.random(-5,5)) rl.Parent=hit game:GetService("Debris"):AddItem(rl,.5) elseif Type=="Snare" then bp=Instance.new("BodyPosition") bp.P=2000 bp.D=100 bp.maxForce=Vector3.new(math.huge,math.huge,math.huge) bp.position=hit.Parent.Torso.Position bp.Parent=hit.Parent.Torso game:GetService("Debris"):AddItem(bp,1) elseif Type=="Charge" then Charge=Charge+1 coroutine.resume(coroutine.create(function(Part) swait(30) for i=1,5 do swait(5) so("rbxasset://sounds\\unsheath.wav",hit,1,2) MagicCircle(BrickColor.new("Bright red"),hit.CFrame*euler(math.random(-50,50),math.random(-50,50),math.random(-50,50)),.2,2,.1,.2,8,.1,0.05) newdam=math.random(1,5) if blocked==false then h:TakeDamage(newdam) showDamage(hit.Parent,newdam,.5,BrickColor:Red()) else h:TakeDamage(newdam/2) showDamage(hit.Parent,newdam,.5,BrickColor.new("Really black")) end end end),hit) end debounce=Instance.new("BoolValue") debounce.Name="DebounceHit" debounce.Parent=hit.Parent debounce.Value=true game:GetService("Debris"):AddItem(debounce,Delay) c=Instance.new("ObjectValue") c.Name="creator" c.Value=Player c.Parent=h game:GetService("Debris"):AddItem(c,.5) CRIT=false hitDeb=true AttackPos=6 end end end showDamage=function(Char,Dealt,du,Color) m=Instance.new("Model") m.Name=tostring(Dealt) h=Instance.new("Humanoid") h.Health=0 h.MaxHealth=0 h.Parent=m c=Instance.new("Part") c.Transparency=0 c.BrickColor=Color c.Name="Head" c.TopSurface=0 c.BottomSurface=0 c.formFactor="Plate" c.Size=Vector3.new(1,.4,1) ms=Instance.new("CylinderMesh") ms.Scale=Vector3.new(.8,.8,.8) if CRIT==true then ms.Scale=Vector3.new(1,1.25,1) end ms.Parent=c c.Reflectance=0 Instance.new("BodyGyro").Parent=c c.Parent=m if Char:findFirstChild("Head")~=nil then c.CFrame=cf(Char["Head"].CFrame.p+Vector3.new(0,1.5,0)) elseif Char.Parent:findFirstChild("Head")~=nil then c.CFrame=cf(Char.Parent["Head"].CFrame.p+Vector3.new(0,1.5,0)) end f=Instance.new("BodyPosition") f.P=2000 f.D=100 f.maxForce=Vector3.new(math.huge,math.huge,math.huge) f.position=c.Position+Vector3.new(0,3,0) f.Parent=c game:GetService("Debris"):AddItem(m,.5+du) c.CanCollide=false m.Parent=workspace c.CanCollide=false end combo=0 local hold=false local railgunshoot=true local cannonshoot=true function ob1d(mouse) hold=true if attack==true then return end coroutine.resume(coroutine.create(function() while hold==true do wait() if aimrailgun==true and railgunshoot==true then railgunshoot=false coroutine.resume(coroutine.create(function() wait(.8) railgunshoot=true end)) ShootRailGun() end if aimcannon==true and cannonshoot==true then cannonshoot=false coroutine.resume(coroutine.create(function() wait(2.1) cannonshoot=true end)) ShootCannon() end end end)) if aimrailgun==true or aimcannon==true then return end if bladeattack==true then return end --attackfour() if combo==0 then combo=1 attackone() elseif combo==1 then combo=2 attacktwo() elseif combo==2 then combo=3 attackthree() elseif combo==3 then combo=4 attackfour() elseif combo==4 then combo=0 end coroutine.resume(coroutine.create(function() for i=1,20 do if attack==false then swait() end end if attack==false then combo=0 equipanim() end end)) end function ob1u(mouse) hold = false end buttonhold = false eul=0 holdx=false equipped=false function key(key) if key=="g" and aimrailgun==false and aimcannon==false and equipped==true then if changetarget==false then attack=true changetarget=true coroutine.resume(coroutine.create(function() while changetarget==true do ElecEffect(prt1.Position,1,1,1) wait(.1) ElecEffect(aprt1.Position,1,1,1) wait(.1) end end)) ChangeTargetPose() else attack=false changetarget=false for i=0,1,0.05 do swait() wld1.C0=clerp(wld1.C0,euler(-0.2,0,0)*cf(3,-1,-0.2),.4) awld1.C0=clerp(awld1.C0,euler(-0.2,0,0)*cf(-3,-1,-0.2),.4) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(0,0,0),.3) --[[RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(0,0,0.5),.3) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(0,0,-0.5),.3)]] --[[Torso.Neck.C0=necko*euler(0,0,0) RootJoint.C0=RootCF*euler(0,0,0) RW.C0=cf(1.5,0.5,0)*euler(0,0,0.5) RW.C1=cf(0,0.5,0)*euler(0,0,0) LW.C0=cf(-1.5,0.5,0)*euler(0,0,-0.5) LW.C1=cf(0,0.5,0)*euler(0,0,0)]] end end end if changetarget==true and aimrailgun==false and aimcannon==false then if key=="z" then ChangeRailgunTarget() end if key=="x" then ChangeCannonTarget() end if key=="c" then BackToMe() end end if attack==true then return end if key=="f" then attack=true if equipped==false then equipped=true RSH=ch.Torso["Right Shoulder"] LSH=ch.Torso["Left Shoulder"] -- RSH.Parent=nil LSH.Parent=nil -- RW.Name="Right Shoulder" RW.Part0=ch.Torso RW.C0=cf(1.5, 0.5, 0) --* CFrame.fromEulerAnglesXYZ(1.3, 0, -0.5) RW.C1=cf(0, 0.5, 0) RW.Part1=ch["Right Arm"] RW.Parent=ch.Torso -- LW.Name="Left Shoulder" LW.Part0=ch.Torso LW.C0=cf(-1.5, 0.5, 0) --* CFrame.fromEulerAnglesXYZ(1.7, 0, 0.8) LW.C1=cf(0, 0.5, 0) LW.Part1=ch["Left Arm"] LW.Parent=ch.Torso -- equipanim() else changetarget=false equipped=false hideanim() swait(0) RW.Parent=nil LW.Parent=nil RSH.Parent=player.Character.Torso LSH.Parent=player.Character.Torso end attack=false end if equipped==false then return end if changetarget==true then return end if key=="0" then Humanoid.WalkSpeed=(16*1.5) end if key=="z" then if aimrailgun==false then aimrailgun=true AimRailGun() else aimrailgun=false UnAimRailGun() end end if key=="x" then if aimcannon==false then aimcannon=true AimCannon() else aimcannon=false UnAimCannon() end end end function key2(key) if key=="0" then Humanoid.WalkSpeed=16 end end function s(mouse) mouse.Button1Down:connect(function() ob1d(mouse) end) mouse.Button1Up:connect(function() ob1u(mouse) end) mouse.KeyDown:connect(key) mouse.KeyUp:connect(key2) player=Player ch=Character MMouse=mouse end function ds(mouse) end Bin.Selected:connect(s) Bin.Deselected:connect(ds) print("Vanguard Gauntlet loaded.") local Anim="Idle" local idleanim=0 local idleanim2=false while true do swait() local torvel=(RootPart.Velocity*Vector3.new(1,0,1)).magnitude if equipped==true then if idleanim>=0.5 then idleanim2=true elseif idleanim<=0 then idleanim2=false end if idleanim2==false then idleanim=idleanim+0.002 else idleanim=idleanim-0.002 end if bladeattack==false then brefwld.C0=clerp(brefwld.C0,euler(0,0,0)*cf(0,-2+idleanim,0),.4) bwld1.C0=clerp(bwld1.C0,euler(0,0,0)*cf(2,-0.6,-2),.4) bwld7.C0=clerp(bwld7.C0,euler(0,0,0)*cf(0,-0.6,-2),.4) bwld13.C0=clerp(bwld13.C0,euler(0,0,0)*cf(-2,-0.6,-2),.4) bwld2.C0=clerp(bwld2.C0,euler(3.14,-2-(idleanim/2),1.57-0.4)*cf(0,0,0),.4) bwld8.C0=clerp(bwld8.C0,euler(3.14,-2-(idleanim/2),1.57)*cf(0,0,0),.4) bwld14.C0=clerp(bwld14.C0,euler(3.14,-2-(idleanim/2),1.57+0.4)*cf(0,0,0),.4) end if RootPart.Velocity.y > 2 then Anim="Jump" if changetarget==false and bladeattack==false then RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0.1,0,0),.2) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(-0.4,0,0),.2) RH.C0=clerp(RH.C0,cf(1,-0.5,-1)*euler(-0.5,1.57,0),.2) LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(-0.7,-1.57,0),.2) RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-0.2,0,0.3),.2) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(-0.2,0,-0.3),.2) end elseif RootPart.Velocity.y < -2 then Anim="Fall" if changetarget==false and bladeattack==false then RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(-0.1,0,0),.2) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(0.4,0,0),.2) RH.C0=clerp(RH.C0,cf(1,-1,0)*euler(0.4,1.57,0),.2) LH.C0=clerp(LH.C0,cf(-1,-1,0)*euler(-0.2,-1.57,0),.2) RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(0.4,0,0.1),.2) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(0.4,0,-0.1),.2) end elseif torvel<1 then Anim="Idle" --idleanim=idleanim+0.005 --[[if idleanim>=0.5 then idleanim=0 end]] RH.C0=clerp(RH.C0,RHC0,.2) LH.C0=clerp(LH.C0,LHC0,.2) --[[RH.C0=RHC0 RH.C1=RHC1 LH.C0=LHC0 LH.C1=LHC1]] if changetarget==false and bladeattack==false then RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.2) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(0,0,0),.2) end if aimcannon==false and attack==false then RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(idleanim,0,0.5-idleanim),.2) end if aimrailgun==false and attack==false then LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(idleanim,0,-0.5+idleanim),.2) end --elseif torvel>=22 then elseif torvel>2 and torvel<22 then Anim="Walk" if changetarget==false and bladeattack==false then RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0),.2) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(0,0,0),.2) end --RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0,0,0.5),.4) if aimcannon==false and changetarget==false and bladeattack==false then RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-0.5,0,0),.2) end if aimrailgun==false and changetarget==false and bladeattack==false then LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(-0.5,0,0),.2) end elseif torvel>=22 then --elseif torvel>2 and torvel<22 then Anim="Run" --print("runnin'") if changetarget==false and bladeattack==false then RootJoint.C0=clerp(RootJoint.C0,RootCF*euler(0.5,0,0),.3) Torso.Neck.C0=clerp(Torso.Neck.C0,necko*euler(-0.3,0,0),.3) end if aimcannon==false and changetarget==false and bladeattack==false then RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-1,0,0),.3) end if aimrailgun==false and changetarget==false and bladeattack==false then LW.C0=clerp(LW.C0,cf(-1,0.5,-0.5)*euler(1.57,0,1),.3) end end end --[[if torvel<19 then Anim="Walk" coroutine.resume(coroutine.create(function() for i=0,1,0.1 do swait() RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(-0.2,0,0),.4) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(-0.2,0,0),.4) end end)) elseif torvel<1 then Anim="Idle" coroutine.resume(coroutine.create(function() for i=0,1,0.1 do swait() RW.C0=clerp(RW.C0,cf(1.5,0.5,0)*euler(0,0,0.5),.4) LW.C0=clerp(LW.C0,cf(-1.5,0.5,0)*euler(0,0,-0.5),.4) end end)) end]] --[[if equipped==true and bladeattack==false then brefwld.C0=clerp(brefwld.C0,euler(0,0,circle)*cf(0,-2,-2),.4) circle=circle-0.1 end]] if #Effects>0 then --table.insert(Effects,{prt,"Block1",delay}) for e=1,#Effects do if Effects[e]~=nil then --for j=1,#Effects[e] do local Thing=Effects[e] if Thing~=nil then local Part=Thing[1] local Mode=Thing[2] local Delay=Thing[3] local IncX=Thing[4] local IncY=Thing[5] local IncZ=Thing[6] if Thing[1].Transparency<=1 then if Thing[2]=="Block1" then Thing[1].CFrame=Thing[1].CFrame*euler(math.random(-50,50),math.random(-50,50),math.random(-50,50)) Mesh=Thing[1].Mesh Mesh.Scale=Mesh.Scale+vt(Thing[4],Thing[5],Thing[6]) Thing[1].Transparency=Thing[1].Transparency+Thing[3] elseif Thing[2]=="Cylinder" then --local TheCF=Thing[1].CFrame --Thing[1].CFrame=TheCF Mesh=Thing[1].Mesh Mesh.Scale=Mesh.Scale+vt(Thing[4],Thing[5],Thing[6]) Thing[1].Transparency=Thing[1].Transparency+Thing[3] elseif Thing[2]=="Elec" then Mesh=Thing[1].Mesh Mesh.Scale=Mesh.Scale+vt(Thing[7],Thing[8],Thing[9]) --Thing[3]=Thing[3]+Delay Thing[1].Transparency=Thing[1].Transparency+Thing[3] --print(Thing[1].Transparency) --[[local prt=part(3,workspace,0,0,BrickColor.new("Bright orange"),"Part",vt(1,1,1)) prt.Anchored=true game:GetService("Debris"):AddItem(prt,2) xval=math.random() yval=math.random() zval=math.random() msh=mesh("BlockMesh",prt,"","",vt(0,0,0),vt(xval,yval,zval)) Effects[#Effects+1]={prt,"Elec",0.05,x,y,z,xval,yval,zval}]] --[[coroutine.resume(coroutine.create(function(Part,Mesh,Frame,xvaal,yvaal,zvaal) Part.CFrame=cf(Frame)*cf(math.random(-x,x),math.random(-y,y),math.random(-z,z)) for i=0,1,0.05 do swait() xvaal=xvaal-0.1 yvaal=yvaal-0.1 zvaal=zvaal-0.1 Mesh.Scale=vt(xvaal,yvaal,zvaal) Part.Transparency=i end Part.Parent=nil end),prt,msh,cff,xval,yval,zval)]] end else Part.Parent=nil table.remove(Effects,e) end end --end end end end end --[[ Copyrighted (C) Fenrier 2014 ]]
--- Provide a mini validation library based on lua type and presence. local validator = {} function validator.present_string(name) return {name = name, kind = "string"} end function validator.present_number(name) return {name = name, kind = "number"} end function validator.present_function(name) return {name = name, kind = "function"} end function validator.present_table(name) return {name = name, kind = "table"} end --- Validation function. -- @param rules table - the rules to apply -- @param tbl table - the table to be validated -- @return bool - status - if it's a success or not -- @return string - when there's an error this is the error message function validator.valid(rules, tbl) for _, v in pairs(rules) do if not tbl[v.name] or type(tbl[v.name]) ~= v.kind then return false, string.format("the property %s must be a %s", v.name, v.kind) end end return true, nil end return validator
local lib = require "resty.libxl.library" local setmetatable = setmetatable local ffi = require "ffi" local ffi_new = ffi.new local r = ffi_new("int[1]", 0) local g = ffi_new("int[1]", 0) local b = ffi_new("int[1]", 0) local color = {} color.__index = color function color.new(opts) return setmetatable(opts, color) end function color:pack(r, g, b) return lib.xlBookColorPackA(self.context, r or 0, g or 0, b or 0) end function color:unpack(value) lib.xlBookColorUnpackA(self.context, value, r, g, b) return r[0], g[0], b[0] end return color
ITEM.name = "S&W M10 Revolver" ITEM.description = "The Smith & Wesson Model 10 is a revolver of worldwide popularity. It was the successor to the Smith & Wesson .32 Hand Ejector Model of 1896 and was the first Smith & Wesson revolver to feature a cylinder release latch on the left side of the frame like the Colt M1889. In production since 1899, it is a six-shot double-action .38 revolver with fixed sights." ITEM.model = "models/weapons/ethereal/w_38rev.mdl" ITEM.class = "cw_kk_ins2_revolver" ITEM.weaponCategory = "secondary" ITEM.width = 1 ITEM.height = 1 ITEM.price = 800 ITEM.weight = 2
-------------------------------------------------------------------------------- --<[ Общие события ]>----------------------------------------------------------- -------------------------------------------------------------------------------- addEvent( "Character.onCharacterSpawn", false ) -- Персонаж заспавнен ( player playerElement, number characterID ) addEvent( "Character.onCharacterDespawn", false ) -- Персонаж деспавнен - выбран другой персноаж, игрок вышел в лобби или вышел из сервера ( player playerElement, number characterID ) addEvent( "Character.onCharacterDead", false ) -- Персонаж умер - здоровье установлено в 0 ( player playerElement, number characterID ) -------------------------------------------------------------------------------- --<[ Внутренние события ]>------------------------------------------------------ -------------------------------------------------------------------------------- addEvent( "Character.onClientRequestCharacters", true ) -- Клиент запросил список своих персонажей ( string requestID ) addEvent( "Character.onClientRequestCharacterSpawn", true ) -- Клиент запрашивает спавн персонажа в игру ( number characterID ) addEvent( "Character.onClientRequestCharacterDespawn", true ) -- Клиент запрашивает деспавн персонажа из игры () -------------------------------------------------------------------------------- --<[ Модуль Character ]>-------------------------------------------------------- -------------------------------------------------------------------------------- Character = { -- TODO перенести в объект персонажа satietyReductionInterval = 6500; satietyReductionValue = 0.1; playTimeExperienceAddInterval = 15000; -- 15 секунд (1 игровая минута) - интервал добавления 1ед в Objective.playOneHour zeroSatietyDamage = 1.0; despawnedPlayerPos = { x = 1732.2823; y = -1930.5439; z = 13.3563; }; characters = {}; -- Информация о персонажах по игрокам (playerElement => characters array) currentCharacters = {}; -- ID текущего персонажа (playerElement => characterID) currentByID = {}; -- Элемент игрока по текущему ID персонажа init = function() addEventHandler( "Main.onServerLoad", root, Character.onServerLoad ) Main.setModuleLoaded( "Character", 1 ) end; onServerLoad = function() addEventHandler( "Character.onClientRequestCharacters", resourceRoot, Character.onClientRequestCharacters ) addEventHandler( "Character.onClientRequestCharacterSpawn", resourceRoot, Character.onClientRequestCharacterSpawn ) addEventHandler( "Character.onClientRequestCharacterDespawn", resourceRoot, Character.onClientRequestCharacterDespawn ) addEventHandler( "Account.onPlayerLogOut", resourceRoot, Character.onPlayerLogOut ) -- Запускаем таймер обработки голода setTimer( Character._handleSatietyTimer, Character.satietyReductionInterval, 0 ) -- Добавляем опыт за время игры setTimer( Character._handlePlayTimeExperience, Character.playTimeExperienceAddInterval, 0 ) end; ---------------------------------------------------------------------------- -- Заспавнить персонаж (установить текущим персонажем игрока). Возвращает false, если персонаж не принадлежит этому игроку или не вошел в аккаунт -- > playerElement player -- > characterID number -- = bool spawnResult spawn = function( playerElement, characterID ) if not validVar( playerElement, "playerElement", "player" ) then return nil end if not validVar( characterID, "characterID", "number" ) then return nil end if ( not Account.isLogined( playerElement ) ) then -- Еще не вошел в аккаунт Debug.error( "Player didn't loged in into account to spwn character " .. characterID ) return false end local characterData = Character.getPlayerCharacters( playerElement )[ characterID ] if ( characterData == nil ) then -- Такого персонажа нет у игрока Debug.error( "Player hasn't character " .. characterID ) return false else -- Персонаж принадлежит игроку Debug.info( "Current character set: " .. characterID ) Character.currentCharacters[ playerElement ] = characterID Character.currentByID[ characterID ] = playerElement if ( characterData.health ~= 0 ) then -- У игрока есть здоровье local dim = Dimension.get( characterData.dimension_name, characterData.dimension_id ) spawnPlayer( playerElement, characterData.x, characterData.y, characterData.z, characterData.angle, characterData.skin, 0, dim ) setElementHealth( playerElement, characterData.health ) fadeCamera( playerElement, true ) setCameraTarget( playerElement, playerElement ) -- Установка данных на клиента triggerClientEvent( playerElement, "Character.onServerSetCurrentCharacter", resourceRoot, characterData ) -- Вызов события "персонаж заспавнен" triggerEvent( "Character.onCharacterSpawn", resourceRoot, playerElement, characterID ) else -- У игрока здоровье на 0 Debug.info( "Character health is zero, making him dead and respawning" ) triggerEvent( "Character.onCharacterDead", resourceRoot, playerElement, characterID ) end return true end end; -- Убрать (деспавнить) текущего персонажа -- > playerElement player -- = void despawn = function( playerElement ) if ( Character.currentCharacters[ playerElement ] ~= nil ) then -- Персонаж был заспавнен, убираем его local characterID = Character.currentCharacters[ playerElement ] triggerEvent( "Character.onCharacterDespawn", resourceRoot, playerElement, characterID ) Character.save( playerElement ) Character.currentByID[ characterID ] = nil Character.currentCharacters[ playerElement ] = nil Debug.info( "Curent character set to nil" ) --[[ Игрок никуда не перемещается (так как попадает либо в лобби, либо выходит) setTimer( function() setElementPosition( playerElement, Character.despawnedPlayerPos.x, Character.despawnedPlayerPos.y, Character.despawnedPlayerPos.z ) end, 200, 1 ) --]] setElementDimension( playerElement, Dimension.get( "Lobby" ) ) setElementPosition( playerElement, Character.despawnedPlayerPos.x, Character.despawnedPlayerPos.y, Character.despawnedPlayerPos.z ) -- Установка данных на клиента triggerClientEvent( playerElement, "Character.onServerSetCurrentCharacter", resourceRoot, nil ) end end; -- Возвращает true, есл игрок выбрал персонаж (у игрока есть заспавненный персонаж) -- > playerElement player -- = bool characterIsSelected isSelected = function( playerElement ) return Character.currentCharacters[ playerElement ] ~= nil end; -- Получить ID текущего персонажа игрока или nil, если персонаж не выбран -- > playerElement player -- = number / nil characterID getID = function( playerElement ) if ( Character.isSelected( playerElement ) ) then return Character.currentCharacters[ playerElement ] else return nil end end; -- Получить playerElement по ID текущего персонажа или nil, если игрока с таким ID персонажа нет в игре -- > characterID number -- = player / nil characterOwner getPlayerElement = function( characterID ) return Character.currentByID[ characterID ] end; -- Получить данные о текущем персонаже (например, health). Если key не указан, возвращаются все данные в виде таблицы. Если игрок не выбрал персонаж, возвращает nil -- > playerElement player -- > key string / nil - если указан nil, будет возвращена таблица со всеми данными -- = mixed / table/ nil characterData getData = function( playerElement, key ) if ( Character.isSelected( playerElement ) ) then if ( key == nil ) then return Character.characters[ playerElement ][ Character.currentCharacters[ playerElement ] ] else return Character.characters[ playerElement ][ Character.currentCharacters[ playerElement ] ][ key ] end else return nil end end; -- Установить данные текущего персонажа -- > playerElement player -- > key string -- > value mixed -- = void setData = function( playerElement, key, value ) if not validVar( key, "key", "string" ) then return nil end if not validVar( value, "value", { "string", "number" } ) then return nil end if ( Character.currentCharacters[ playerElement ] ~= nil ) then Character.characters[ playerElement ][ Character.currentCharacters[ playerElement ] ][ key ] = value else return nil end end; -- Сохранить текущие данные персонажа в базу -- > playerElement player -- = void save = function( playerElement ) -- TODO (с флажком 'changed') - создать таблицу ключей измененных полей Debug.info( "Saving player character", playerElement ) if ( Character.isSelected( playerElement ) ) then -- Позиция local x, y, z = getElementPosition( playerElement ) Character.setData( playerElement, "x", x ) Character.setData( playerElement, "y", y ) Character.setData( playerElement, "z", z ) local _, _, angle = getElementRotation( playerElement ) Character.setData( playerElement, "angle", angle ) -- Сохранение local q = "\ UPDATE mtaw.character \ SET \ x = " .. x .. ", \ y = " .. y .. ", \ z = " .. z .. ", \ angle = " .. angle .. ", \ health = " .. Character.getHealth( playerElement ) .. ", \ satiety = " .. Character.getSatiety( playerElement ) .. ", \ skin = " .. Character.getData( playerElement, "skin" ) .. ", \ experience = " .. Character.getData( playerElement, "experience" ) .. " \ WHERE id = " .. Character.getData( playerElement, "id" ); DB.syncQuery( q ) else Debug.info( "Player didn't select a character" ) end end; -- Возвращает имя персонажа, очищенное от запрещенных символов -- > name string - неочищенное имя -- = string validName filterCharacterName = function( name ) local ret = "" for i = 1, utfLen( name ) do local chr = utfSub( name, i, i ) local chrCode = utfCode( chr ) if ( ( chrCode >= 1040 and chrCode <= 1103 ) -- а-Я or ( chrCode == 1025 or chrCode == 1105 ) -- ё Ё --or ( chrCode >= 65 and chrCode <= 90 ) -- A-Z --or ( chrCode >= 97 and chrCode <= 122 ) -- a-z --or chrCode == 1108 -- є --or chrCode == 1110 -- і --or chrCode == 1111 -- ї or chrCode == 45 -- - or chrCode == 32 -- пробел ) then ret = ret .. utfChar( chrCode ) end end return ret end; -- Прверка валидности имени и фамилии персонажа -- > str string - имя или фамилия персонажа -- = bool isValid isNameValid = function( str ) if ( utfLen( str ) < 2 or utfLen( str ) >= 24 ) then return false end return Character.filterCharacterName( str ) == str end; -- Создать нового персонажа. Возвращает true и ID Нового персонажа или false и текст ошибки -- > playerElement player - игрок, для которого будет создан персонаж -- > name string - имя персонажа -- > surname string - фамилия персонажа -- > gender string - пол персонажа (male/female) -- > skin number - ID модели скина персонажа -- > avatar string / nil - аватарка персонажа, по умолчанию генерируется случайная -- = bool isCreated, number / string characterIdOrError create = function( playerElement, name, surname, gender, skin, avatar ) if not validVar( playerElement, "playerElement", "player" ) then return nil end if not validVar( name, "name", "string" ) then return nil end if not validVar( surname, "surname", "string" ) then return nil end if not validVar( gender, "gender", "string" ) then return nil end if not validVar( skin, "number", "string" ) then return nil end if not validVar( avatar, "avatar", { "string", "nil" } ) then return nil end if ( Account.isLogined( playerElement ) ) then -- Игрок вошел в аккаунт local accountID = Account.getData( playerElement, "id" ) local slotStatistic = Character.getSlotStatistic( playerElement ) if ( slotStatistic.total > slotStatistic.used ) then -- Есть свободные слоты для персонажей -- Валидация if ( gender ~= "male" and gender ~= "female" ) then -- Неверно указан пол return false, "Неверно указан пол" end if ( not Character.isNameValid( name ) ) then return false, "Неверный формат имени" end if ( not Character.isNameValid( surname ) ) then return false, "Неверный формат фамилии" end if ( ARR.characterCreatorSkins[ gender ][ tostring( skin ) ] == nil ) then return false, "Невозможно выбрать скин " .. skin end if ( avatar == nil ) then -- Генерация алиаса аватарки avatar = Avatar.generateAvatarAlias() end -- Запись в базу нового персонажа и обновления списка персонажей на клиенте local spawnAlias = Spawn.getNearestSpawnAlias( 0, 0, 0 ) local spawnData = Spawn.getSpawnInfo( spawnAlias ) local angle = 0 local q = "\ INSERT INTO mtaw.character ( account, x, y, z, angle, name, surname, gender, created, avatar, skin ) VALUES (\ " .. accountID .. ",\ " .. spawnData.x .. ",\ " .. spawnData.y .. ",\ " .. spawnData.z .. ",\ " .. angle .. ",\ '" .. sql_escape_string( name ) .. "',\ '" .. sql_escape_string( surname ) .. "',\ '" .. sql_escape_string( gender ) .. "',\ " .. Time.getServerTimestamp() .. ",\ '" .. sql_escape_string( avatar ) .. "',\ " .. skin .. "\ )\ " local isSuccess, result, num_affected_rows, last_insert_id = DB.syncQuery( q ) if ( not isSuccess ) then return nil end Debug.info( tostring( result ) .. " " .. tostring( num_affected_rows ) .. " " .. tostring( last_insert_id ) ) if ( result ) then local isSuccess, newCharacterResult = DB.syncQuery( "SELECT * FROM mtaw.character WHERE id = " .. last_insert_id ) if ( not isSuccess ) then return nil end for k, v in pairs( newCharacterResult ) do local data = {} for kk, vv in pairs( v ) do data[ kk ] = vv end Character.characters[ playerElement ][ data.id ] = data end return true, last_insert_id else return false, "Ошибка при создании записи в базе данных" end else return false, "Нет свободных слотов для создания персонажа" end else return false, "Необходимо войти в аккаунт" end end; setPosition = function( playerElement, x, y, z ) if not validVar( playerElement, "playerElement", "player" ) then return nil end if not validVar( x, "x", "number" ) then return nil end if not validVar( y, "y", "number" ) then return nil end if not validVar( z, "z", "number" ) then return nil end local characterID = Character.currentCharacters[ playerElement ] if ( characterID ~= nil ) then Character.characters[ playerElement ][ characterID ].x = x Character.characters[ playerElement ][ characterID ].y = y Character.characters[ playerElement ][ characterID ].z = z setElementPosition( playerElement, x, y, z ) else Debug.error( "Character is not selected" ) end end; setDimension = function( playerElement, dimensionName, dimensionID ) if not validVar( playerElement, "playerElement", "player" ) then return nil end if not validVar( dimensionName, "dimensionName", "string" ) then return nil end if not validVar( dimensionID, "dimensionID", { "number", "nil" } ) then return nil end local characterID = Character.currentCharacters[ playerElement ] if ( characterID ~= nil ) then if ( dimensionID == nil ) then dimensionID = 0 end -- Номер измерения не указан - значит, он не имеет значения Character.setData( playerElement, "dimension_name", dimensionName ) Character.setData( playerElement, "dimension_id", dimensionID ) setElementDimension( playerElement, Dimension.get( dimensionName, dimensionID ) ) else Debug.error( "Character is not selected" ) end end; -- Возвращает текущую сытость персонажа (0-100) или nil, если персонаж не выбран -- > playerElement player -- = number / nil characterSatiety getSatiety = function( playerElement ) if not validVar( playerElement, "playerElement", "player" ) then return nil end if ( Character.currentCharacters[ playerElement ] ~= nil ) then return Character.getData( playerElement, "satiety" ) else return nil end end; -- Установить сытость персонажа (0-100). Возвращает false, если персонаж не выбран -- Если указана сытость <0, установит 0. Если больше 100, установит 100 -- > playerElement player -- > satiety number -- = bool isSet setSatiety = function( playerElement, satiety ) if not validVar( playerElement, "playerElement", "player" ) then return nil end if not validVar( satiety, "satiety", "number" ) then return nil end if ( Character.currentCharacters[ playerElement ] ~= nil ) then if ( satiety < 0 ) then satiety = 0 elseif ( satiety > 100 ) then satiety = 100 end if ( Character.getData( playerElement, "satiety" ) ~= satiety ) then Character.setData( playerElement, "satiety", satiety ) Character.updateClientData( playerElement, { ["satiety"] = satiety; } ) end return true else Debug.info( "Character is not selected!" ) return false end end; -- Возвращает текущее здоровье персонажа (0-100) или nil, если персонаж не выбран -- > playerElement player -- = number characterHealth getHealth = function( playerElement ) if not validVar( playerElement, "playerElement", "player" ) then return nil end if ( Character.currentCharacters[ playerElement ] ~= nil ) then return Character.getData( playerElement, "health" ) else return nil end end; -- Установить текущее здоровье персонажа (0-100), возвращает false, если персонаж не выбран -- > playerElement player -- > health number -- = bool isSet setHealth = function( playerElement, health ) if not validVar( playerElement, "playerElement", "player" ) then return nil end if not validVar( health, "health", "number" ) then return nil end if ( Character.currentCharacters[ playerElement ] ~= nil ) then if ( health < 0 ) then health = 0 elseif ( health > 100 ) then health = 100 end if ( Character.getData( playerElement, "health" ) ~= health ) then Character.setData( playerElement, "health", health ) if ( health == 0 ) then -- Умер triggerEvent( "Character.onCharacterDead", resourceRoot, playerElement, Character.getData( playerElement, "id" ) ) else -- Еще не умер Character.updateClientData( playerElement, { ["health"] = health; } ) end end return true else Debug.info( "Character is not selected!" ) return false end end; -- Возвращает текущую сумму наличных денег персонажа (>=0) или nil, если персонаж не выбран -- > playerElement player -- = number / nil characterMoney getMoney = function( playerElement ) if not validVar( playerElement, "playerElement", "player" ) then return nil end if ( Character.currentCharacters[ playerElement ] ~= nil ) then return Character.getData( playerElement, "money" ) else return nil end end; -- Установить текущую сумму наличных персонажу (>=0), возвращает false, если персонаж не выбран -- > playerElement player -- > money naumber -- = bool isSet setMoney = function( playerElement, money ) if not validVar( playerElement, "playerElement", "player" ) then return nil end if not validVar( money, "money", "number" ) then return nil end if ( Character.currentCharacters[ playerElement ] ~= nil ) then Character.setData( playerElement, "money", money ) Character.updateClientData( playerElement, { ["money"] = money; } ) return true else Debug.info( "Character is not selected!" ) return false end end; -- Возвращает суммарный опыт персонажа (>=0) или nil, если персонаж не выбран -- > playerElement player -- = number experience / nil getExperience = function( playerElement ) if not validVar( playerElement, "playerElement", "player" ) then return nil end if ( Character.currentCharacters[ playerElement ] ~= nil ) then return Character.getData( playerElement, "experience" ) else return nil end end; -- Установить суммарный опыт персонажа (>=0), возвращает nil, если персонаж не выбран -- > playerElement player -- > experience number -- = bool isSet setExperience = function( playerElement, experience ) if not validVar( playerElement, "playerElement", "player" ) then return nil end if not validVar( experience, "experience", "number" ) then return nil end if ( Character.currentCharacters[ playerElement ] ~= nil ) then Character.setData( playerElement, "experience", experience ) Character.updateClientData( playerElement, { ["experience"] = experience; } ) return true else Debug.info( "Character is not selected!" ) return false end end; -- Добавить к суммарному опыту персонажа (>0) -- > playerElement player -- > addedExperience number -- = void addExperience = function( playerElement, addedExperience ) if not validVar( playerElement, "playerElement", "player" ) then return nil end if not validVar( addedExperience, "addedExperience", "number" ) then return nil end if ( addedExperience < 1 ) then Debug.error( "Invalid experience amount: " .. addedExperience ) return nil end Character.setExperience( playerElement, Character.getData( playerElement, "experience" ) + addedExperience ) end; -- Обновить данные о персонаже на стороне клиента - отправляет все данные на клиент -- > playerElement player -- > newData table - таблица с данными персонажа, которые нужно установить на клиенте -- = void updateClientData = function( playerElement, newData ) if not validVar( newData, "newData", "table" ) then return nil end triggerClientEvent( playerElement, "Character.onServerUpdateCharacterData", resourceRoot, newData ) end; -- Возвращает таблицу всех персонажей игрока или nil, если не вошел в аккаунт -- > playerElement player -- = table / nil playerCharacters getPlayerCharacters = function( playerElement ) if ( Account.isLogined( playerElement ) ) then if ( Character.characters[ playerElement ] == nil ) then local isSuccess, result = DB.syncQuery( "SELECT * FROM mtaw.character WHERE account = " .. Account.getAccountID( playerElement ) ) if ( not isSuccess ) then return nil end Character.characters[ playerElement ] = {} for k, v in pairs( result ) do local data = {} for kk, vv in pairs( v ) do data[ kk ] = vv end Character.characters[ playerElement ][ data.id ] = data end end return Character.characters[ playerElement ] else return nil end end; -- Возвращает количество занятых и всего слотов под персонажи игрока или nil, если не вошел в аккаунт -- > playerElement player -- = table / nil slotStatistic getSlotStatistic = function( playerElement ) if ( Account.isLogined( playerElement ) ) then local playerCharacters = Character.getPlayerCharacters( playerElement ) local totalExp = 0 local usedSlots = 0 for characterID, characterData in pairs( playerCharacters ) do totalExp = totalExp + characterData.experience usedSlots = usedSlots + 1 end local availableSlots = 0 local nextSlotExp = 0 local prevSlotExp = 0 for k, v in pairs( ARR.characterSlotsByTotalExp ) do if ( totalExp >= v[ 1 ] ) then availableSlots = v[ 2 ] else if ( k ~= 0 ) then prevSlotExp = ARR.characterSlotsByTotalExp[ k - 1 ][ 1 ] end nextSlotExp = v[ 1 ] break end end return { total = availableSlots; used = usedSlots; totalExp = totalExp; prevSlotExp = prevSlotExp; nextSlotExp = nextSlotExp; } else return nil end end; -- Получить информацию о текущем уровне и оставшемся опыте для перехода на следующий уровень -- > totalExperience number -- = table levelInfo getLevelInfo = function( totalExperience ) if not validVar( totalExperience, "experience", "number" ) then return nil end local level, levelExp, nextLevelExp local expSum = 0 for k, v in pairs( ARR.expByLevel ) do level = k if ( expSum + v > totalExperience ) then levelExp = totalExperience - expSum nextLevelExp = v break end expSum = expSum + v end local ret = {} ret.level = level ret.levelExp = levelExp ret.nextLevelExp = nextLevelExp return ret end; -- Обработка уменьшения сытости _handleSatietyTimer = function() local players = getElementsByType( "player" ) for _, playerElement in pairs( players ) do if ( Character.isSelected( playerElement ) ) then Character.setSatiety( playerElement, Character.getData( playerElement, "satiety" ) - Character.satietyReductionValue ) if ( Character.getData( playerElement, "satiety" ) == 0 ) then -- Сытость на нуле Character.setHealth( playerElement, Character.getHealth( playerElement ) - Character.zeroSatietyDamage ) end end end end; -- Добавление 1 очка в Objective.playOneHour всем заспавненным персонажам _handlePlayTimeExperience = function() local players = getElementsByType( "player" ) for _, playerElement in pairs( players ) do if ( Character.isSelected( playerElement ) ) then Objective.progress( Character.getID( playerElement ), "playOneHour" ) end end end; ---------------------------------------------------------------------------- --<[ Обработчики событий ]>------------------------------------------------- ---------------------------------------------------------------------------- -- Клиент запросил список своих персонажей onClientRequestCharacters = function( requestID ) local characterList = Character.getPlayerCharacters( client ) triggerClientEvent( client, "Character.onServerSentCharacters", resourceRoot, characterList, requestID ) end; -- Клиент запросил спавн персонажа onClientRequestCharacterSpawn = function( characterID ) Character.spawn( client, characterID ) end; -- Клиент запросил деспавн персонажа onClientRequestCharacterDespawn = function() Character.despawn( client ) end; -- Клиент вышел из аккаунта onPlayerLogOut = function( playerElement ) -- Так как персонажи не могут существовать без аккаунтов, деспавним персонаж if ( Character.isSelected( playerElement ) ) then -- Перенести в Character Character.despawn( playerElement ) end end; }; addEventHandler( "onResourceStart", resourceRoot, Character.init )
local input = io.open('1SonarSweep.txt', 'r') function SonarSweeps(input) local prev = 9999999999 local change = {} local count = 0 for line in input:lines() do local current = tonumber(line) if (current > prev) then count = count + 1 end prev = current end print("part 1: " .. count) end function SonarSweeps2(input) local buffer = {9999999, 9999999, 9999999} local change = {} local count = 0 input = io.open("1SonarSweep.txt") for line in input:lines() do local current = tonumber(line) local total = current + buffer[1] + buffer[2] local prevTotal = buffer[1] + buffer[2] + buffer[3] local test = "decrease"; if (total > prevTotal) then count = count + 1 test = "increase" elseif (total == prevTotal) then test = "same" end buffer[3] = buffer[2] buffer[2] = buffer[1] buffer[1] = current end print("part2: ".. count) end SonarSweeps(input) SonarSweeps2(input)
--This script builds a tree from a Lua table and puts the child nodes in parenthesis to the node if child nodes are not http site adresses --1. read input tree dofile("C:\\Tree\\html_Tree\\Tree_Baum_node_content.lua") --test with: print(Tree[1][1][2]) outputfile1=io.open("C:\\Tree\\html_Tree\\Tree_Baum_node_content.html","w") outputfile1:write('<font size="5"> ') --2.1 function to build recursively the tree function readTreetohtmlRecursive(TreeTable) if TreeTable.branchname:match("^http")==nil then AusgabeTabelle[TreeTable.branchname]=TreeTable.branchname .. " (" end --if TreeTable.branchname:match("^http")==nil then for k,v in ipairs(TreeTable) do if type(v)=="table" then if TreeTable.branchname:match("^http")==nil and v.branchname:match("^http")==nil then AusgabeTabelle[TreeTable.branchname]=AusgabeTabelle[TreeTable.branchname] .. v.branchname .. ", " end --if TreeTable.branchname:match("^http")==nil then else if TreeTable.branchname:match("^http")==nil and v:match("^http")==nil then AusgabeTabelle[TreeTable.branchname]=AusgabeTabelle[TreeTable.branchname] .. v .. ", " end --if TreeTable.branchname:match("^http")==nil then end --if type(v)=="table" then end --for k, v in ipairs(TreeTable) do --write modified or unmodified branchname if AusgabeTabelle[TreeTable.branchname] and AusgabeTabelle[TreeTable.branchname]:match("%($")==nil then outputfile1:write("<ul><li>" .. tostring(AusgabeTabelle[TreeTable.branchname]:gsub(", $",")"):gsub("([^%(]*)(%(.*%))","<b>%1</b><i>%2</i>")) :gsub("ä","&auml;") :gsub("ä","&auml;") :gsub("Ä","&Auml;") :gsub("Ä","&Auml;") :gsub("ö","&ouml;") :gsub("ö","&ouml;") :gsub("Ö","&Ouml;") :gsub("Ö","&Ouml;") :gsub("ü","&uuml;") :gsub("ü","&uuml;") :gsub("Ü","&Uuml;") :gsub("Ü","&Uuml;") :gsub("ß","&szlig;") :gsub("ß","&szlig;") .. "\n") else local TreeTable_branchname_link=TreeTable.branchname if TreeTable.branchname:match("^http") then TreeTable_branchname_link='<a href="' .. TreeTable.branchname .. '">' .. TreeTable.branchname .. '</a>' end outputfile1:write("<ul><li>" .. tostring(TreeTable_branchname_link) :gsub("ä","&auml;") :gsub("ä","&auml;") :gsub("Ä","&Auml;") :gsub("Ä","&Auml;") :gsub("ö","&ouml;") :gsub("ö","&ouml;") :gsub("Ö","&Ouml;") :gsub("Ö","&Ouml;") :gsub("ü","&uuml;") :gsub("ü","&uuml;") :gsub("Ü","&Uuml;") :gsub("Ü","&Uuml;") :gsub("ß","&szlig;") :gsub("ß","&szlig;") .. "\n") end --if AusgabeTabelle[TreeTable.branchname]:match("%($")==nil then --go to the recursion for k,v in ipairs(TreeTable) do if type(v)=="table" then readTreetohtmlRecursive(v) else local v_link=v if v:match("^http") then v_link='<a href="' .. v .. '">' .. v .. '</a>' end outputfile1:write("<ul><li>" .. v_link :gsub("ä","&auml;") :gsub("ä","&auml;") :gsub("Ä","&Auml;") :gsub("Ä","&Auml;") :gsub("ö","&ouml;") :gsub("ö","&ouml;") :gsub("Ö","&Ouml;") :gsub("Ö","&Ouml;") :gsub("ü","&uuml;") :gsub("ü","&uuml;") :gsub("Ü","&Uuml;") :gsub("Ü","&Uuml;") :gsub("ß","&szlig;") :gsub("ß","&szlig;") .. "</li></ul>" .. "\n") end --if type(v)=="table" then end --for k, v in ipairs(TreeTable) do outputfile1:write("</li></ul>" .. "\n") end --readTreetohtmlRecursive(TreeTable) --2.2 apply the recursive function and build html file AusgabeTabelle={} readTreetohtmlRecursive(Tree) outputfile1:close()
--[[ --This file implements orthognoal linear module, which wraps orthogonal weight normalization --into the linear module for 2D input used in MLP architecture. -- ------------------------------------------------------------------- --Author: Lei Huang --mail: huanglei@nlsde.buaa.edu.cn --- --]] local Linear_Weight_DBN_Row_Group, parent = torch.class('nn.Linear_Weight_DBN_Row_Group', 'nn.Module') function Linear_Weight_DBN_Row_Group:__init(inputSize,outputSize,m_perGroup,unitLength_flag) parent.__init(self) self.weight = torch.Tensor( outputSize,inputSize) --make sure the weight is symetric and semi-definite -- self.bias = torch.Tensor(outputSize) self.gradWeight = torch.Tensor(outputSize, inputSize) -- self.gradBias = torch.Tensor(outputSize) if unitLength_flag ~= nil then assert(type(unitLength_flag) == 'boolean', 'unitLength_flag has to be true/false') self.unitLength_flag = unitLength_flag else self.unitLength_flag = true end self.eps=1e-7 self.threshold=0 self.debug=false if m_perGroup~=nil then self.m_perGroup = m_perGroup > inputSize and inputSize or m_perGroup else self.m_perGroup = inputSize end self:reset() end function Linear_Weight_DBN_Row_Group:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:size(2)) end self.weight:uniform(-stdv, stdv) -- self.weight:randn(self.weight:size(1),self.weight:size(2)) -- self.bias:uniform(-stdv, stdv) return self end function Linear_Weight_DBN_Row_Group:reset_orthogonal() local initScale = 1.1 -- math.sqrt(2) local M1 = torch.randn(self.weight:size(1), self.weight:size(1)) local M2 = torch.randn(self.weight:size(2), self.weight:size(2)) local n_min = math.min(self.weight:size(1), self.weight:size(2)) -- QR decomposition of random matrices ~ N(0, 1) local Q1, R1 = torch.qr(M1) local Q2, R2 = torch.qr(M2) self.weight:copy(Q1:narrow(2,1,n_min) * Q2:narrow(1,1,n_min)):mul(initScale) -- self.bias:zero() end function Linear_Weight_DBN_Row_Group:updateOutput(input) assert(input:dim() == 2, 'only mini-batch supported (2D tensor), got ' .. input:dim() .. 'D tensor instead') function updateOutput_perGroup(weight_perGroup,groupId) local n_output=weight_perGroup:size(1) local n_input=weight_perGroup:size(2) local n_output=weight_perGroup:size(1) local n_input=weight_perGroup:size(2) local scale=weight_perGroup.new() local centered = weight_perGroup.new() self.W_perGroup=self.W_perGroup or input.new() self.W_perGroup:resizeAs(weight_perGroup) self.buffer:mean(weight_perGroup, 2) centered:add(weight_perGroup, -1, self.buffer:expandAs(weight_perGroup)) ----------------------calcualte the projection matrix---------------------- self.buffer_1:resize(weight_perGroup:size(1),weight_perGroup:size(1)) self.buffer_1:addmm(0,self.buffer_1,1/n_input,centered,centered:t()) --buffer_1 record correlation matrix self.buffer_1:add(self.eps,torch.eye(self.buffer_1:size(1))) -----------------------matrix decomposition------------- local rotation,eig,_=torch.svd(self.buffer_1) if self.debug then print(eig) end scale:resizeAs(eig) scale:copy(eig) scale:pow(-1/2) --scale=eig^(-1/2) self.buffer_1:diag(scale) --self.buffer_1 cache the scale matrix self.buffer_2:resizeAs(rotation) self.buffer_2:mm(self.buffer_1,rotation:t()) --U= Eighta^(-1/2)*D^T self.buffer_1:mm(rotation,self.buffer_2) self.W_perGroup:mm(self.buffer_1,centered) if self.unitLength_flag then self.W_perGroup:mul(math.sqrt(1/n_input)) end ----------------record the results of per groupt-------------- table.insert(self.eigs, eig) table.insert(self.scales, scale) table.insert(self.rotations, rotation) table.insert(self.centereds, centered) return self.W_perGroup end --------------------------------update main function---------------------- local nframe = input:size(1) local nElement = self.output:nElement() local n_output=self.weight:size(1) local n_input=self.weight:size(2) self.output:resize(nframe, n_output) if self.output:nElement() ~= nElement then self.output:zero() end self.W=self.W or input.new() self.W:resizeAs(self.weight) self.buffer = self.buffer or input.new() self.buffer_1 = self.buffer_1 or input.new() self.buffer_2 = self.buffer_2 or input.new() local groups=torch.floor((n_output-1)/self.m_perGroup)+1 -------------- initalize the group parameters--------------- self.eigs={} self.scales={} self.rotations={} self.centereds={} for i=1,groups do local start_index=(i-1)*self.m_perGroup+1 local end_index=math.min(i*self.m_perGroup,n_output) self.W[{{start_index,end_index},{}}]=updateOutput_perGroup(self.weight[{{start_index,end_index},{}}],i) end if input:dim() == 2 then self.output:addmm(0, self.output, 1, input, self.W:t()) -- self.output:addr(1, self.addBuffer, self.bias) --for cudnn, the bias is usually omited for efficiency else error('input must be vector or matrix') end return self.output end function Linear_Weight_DBN_Row_Group:updateGradInput(input, gradOutput) if self.gradInput then local nElement = self.gradInput:nElement() self.gradInput:resizeAs(input) if self.gradInput:nElement() ~= nElement then self.gradInput:zero() end if input:dim() == 2 then self.gradInput:addmm(0, 1, gradOutput, self.W) else error('input must be vector or matrix') end return self.gradInput end end function Linear_Weight_DBN_Row_Group:accGradParameters(input, gradOutput, scale) ------------------calculate the K matrix--------------------- function getK_new(eig) local revised=1e-45 --used for div 0, in case of that there are tow eigenValuse is the same (It's almost impossible) local K=torch.Tensor(eig:size(1),eig:size(1)):fill(revised) local b_1=torch.Tensor(eig:size(1),eig:size(1)):repeatTensor(eig, eig:size(1), 1) local b_2=torch.eye(eig:size(1)):add(b_1:t()):add(-1,b_1):add(K) K:fill(1):cdiv(b_2):add(-1, torch.eye(eig:size(1))*(1+revised)) return K end --------------------------------------------------------- function updateAccGradParameters_perGroup(gradW_perGroup, groupId) local n_output=gradW_perGroup:size(1) local n_input=gradW_perGroup:size(2) local eig=self.eigs[groupId] local scale=self.scales[groupId] local rotation=self.rotations[groupId] local centered=self.centereds[groupId] self.gradWeight_perGroup=self.gradWeight_perGroup or gradW_perGroup.new() self.gradWeight_perGroup:resizeAs(gradW_perGroup) self.hat_x=self.hat_x or gradW_perGroup.new() self.S=self.S or gradW_perGroup.new() self.M=self.M or gradW_perGroup.new() self.U=self.U or gradW_perGroup.new() self.f=self.f or gradW_perGroup.new() self.FC=self.FC or gradW_perGroup.new() self.d_hat_x=self.d_hat_x or gradW_perGroup.new() self.hat_x:resizeAs(centered) self.d_hat_x:resizeAs(centered) self.U:resizeAs(rotation) self.M:resizeAs(rotation) self.S:resizeAs(rotation) self.FC:resizeAs(rotation) self.buffer:diag(scale) self.U:mm( self.buffer,rotation:t()) self.hat_x:mm( self.U,centered) self.d_hat_x:mm(rotation:t(),gradW_perGroup) self.FC:addmm(0, self.FC, 1/n_input, self.d_hat_x, self.hat_x:t()) self.f:mean(self.d_hat_x, 2) local sz = (#self.FC)[1] local temp_diag=torch.diag(self.FC) --get the diag element of d_EighTa self.M:diag(temp_diag) --matrix form --------------------------------calculate S----------------------------- self.S:cmul(self.FC:t(), eig:view(sz, 1):expandAs(self.FC)) self.buffer:resizeAs(eig):copy(eig):pow(1/2) self.buffer_1:cmul(self.FC, self.buffer:view(sz, 1):expandAs(self.FC)) self.buffer_2:cmul(self.buffer_1, self.buffer:view(1, sz):expandAs(self.buffer_1)) self.S:add(self.buffer_2) self.buffer=getK_new(eig) self.S:cmul(self.buffer:t()) self.buffer:copy(self.S) self.S:add(self.buffer, self.buffer:t()) self.S:add(-1, self.M) -- S-M self.buffer_1:resizeAs(self.d_hat_x) self.buffer_1:mm( self.S:t(),self.hat_x) --(S-M)*self.hat_x self.buffer_1:add(self.d_hat_x):add(-1, self.f:expandAs(self.d_hat_x)) self.gradWeight_perGroup:mm( self.U:t(),self.buffer_1) if self.unitLength_flag then self.gradWeight_perGroup:mul(math.sqrt(1/n_input)) end return self.gradWeight_perGroup end -------------------------------------main function of accGrad------------ assert(input:dim() == 2, 'only mini-batch supported') assert(gradOutput:dim() == 2, 'only mini-batch supported') local n_output=self.weight:size(1) self.gradW=self.gradW or input.new() self.gradW:resize(gradOutput:size(2),input:size(2)) self.gradW:mm(gradOutput:t(), input) --dL/dW local groups=torch.floor((n_output-1)/self.m_perGroup)+1 for i=1,groups do local start_index=(i-1)*self.m_perGroup+1 local end_index=math.min(i*self.m_perGroup,n_output) self.gradWeight[{{start_index,end_index},{}}]=updateAccGradParameters_perGroup(self.gradW[{{start_index,end_index},{}}],i) end end -- we do not need to accumulate parameters when sharing Linear_Weight_DBN_Row_Group.sharedAccUpdateGradParameters = Linear_Weight_DBN_Row_Group.accUpdateGradParameters function Linear_Weight_DBN_Row_Group:__tostring__() return torch.type(self) .. string.format('(%d -> %d)', self.weight:size(2), self.weight:size(1)) end
-- Natural Selection League Plugin -- Source located at - https://github.com/xToken/NSL -- lua/NSL/nsl_predict.lua -- - Dragon -- Load shared defs Script.Load("lua/NSL/nsl_shared.lua") -- Load predict defs
Scene = {} function newScene(t) self = t or {} setmetatable(self, Scene) Scene.__index = Scene return self end function Scene.start(...) end function Scene.draw() end function Scene.update(dt) return true end function Scene.mousemoved(x, y) end function Scene.mousepressed(x, y, button) end function Scene.mousereleased(x, y, button) end function Scene.keypressed(key) end function Scene.textinput(text) end
local _, ns = ... local B, C, L, DB, P = unpack(ns) local AB = P:GetModule("ActionBar") local Bar = B:GetModule("Actionbar") ----------------- -- Credit: ElvUI ----------------- local function ClearTimers(object) if object.delayTimer then P:CancelTimer(object.delayTimer) object.delayTimer = nil end end local function DelayFadeOut(frame, timeToFade, startAlpha, endAlpha) ClearTimers(frame) if AB.db["Delay"] > 0 then frame.delayTimer = P:ScheduleTimer(P.UIFrameFadeOut, AB.db["Delay"], P, frame, timeToFade, startAlpha, endAlpha) else P:UIFrameFadeOut(frame, timeToFade, startAlpha, endAlpha) end end function AB:FadeBlingTexture(cooldown, alpha) if not cooldown then return end cooldown:SetBlingTexture(alpha > 0.5 and [[Interface\Cooldown\star4]] or P.Blank) end function AB:FadeBlings(alpha) for _, button in pairs(Bar.buttons) do AB:FadeBlingTexture(button.cooldown, alpha) end end function AB:Button_OnEnter() if not AB.fadeParent.mouseLock then ClearTimers(AB.fadeParent) P:UIFrameFadeIn(AB.fadeParent, .2, AB.fadeParent:GetAlpha(), 1) AB:FadeBlings(1) end end function AB:Button_OnLeave() if not AB.fadeParent.mouseLock then DelayFadeOut(AB.fadeParent, .38, AB.fadeParent:GetAlpha(), AB.db["Alpha"]) AB:FadeBlings(AB.db["Alpha"]) end end function AB:FadeParent_OnEvent(event) if (event == "ACTIONBAR_SHOWGRID") or (AB.db["Combat"] and UnitAffectingCombat("player")) or (AB.db["Target"] and UnitExists("target")) or (AB.db["Casting"] and (UnitCastingInfo("player") or UnitChannelInfo("player"))) or (AB.db["Health"] and (UnitHealth("player") ~= UnitHealthMax("player"))) then self.mouseLock = true ClearTimers(AB.fadeParent) P:UIFrameFadeIn(self, .2, self:GetAlpha(), 1) AB:FadeBlings(1) else self.mouseLock = false DelayFadeOut(self, .38, self:GetAlpha(), AB.db["Alpha"]) AB:FadeBlings(AB.db["Alpha"]) end end local options = { Combat = { enable = function(self) self:RegisterEvent("PLAYER_REGEN_ENABLED") self:RegisterEvent("PLAYER_REGEN_DISABLED") self:RegisterUnitEvent("UNIT_FLAGS", "player") end, events = {"PLAYER_REGEN_ENABLED", "PLAYER_REGEN_DISABLED", "UNIT_FLAGS"} }, Target = { enable = function(self) self:RegisterEvent("PLAYER_TARGET_CHANGED") end, events = {"PLAYER_TARGET_CHANGED"} }, Casting = { enable = function(self) self:RegisterUnitEvent("UNIT_SPELLCAST_START", "player") self:RegisterUnitEvent("UNIT_SPELLCAST_STOP", "player") self:RegisterUnitEvent("UNIT_SPELLCAST_CHANNEL_START", "player") self:RegisterUnitEvent("UNIT_SPELLCAST_CHANNEL_STOP", "player") end, events = {"UNIT_SPELLCAST_START", "UNIT_SPELLCAST_STOP", "UNIT_SPELLCAST_CHANNEL_START", "UNIT_SPELLCAST_CHANNEL_STOP"} }, Health = { enable = function(self) self:RegisterUnitEvent("UNIT_HEALTH", "player") end, events = {"UNIT_HEALTH"} }, } function AB:UpdateFaderSettings() for key, option in pairs(options) do if AB.db[key] then if option.enable then option.enable(AB.fadeParent) end else if option.events and next(option.events) then for _, event in ipairs(option.events) do AB.fadeParent:UnregisterEvent(event) end end end end end local NDui_ActionBar = { ["Bar1"] = "NDui_ActionBar1", ["Bar2"] = "NDui_ActionBar2", ["Bar3"] = "NDui_ActionBar3", ["Bar4"] = "NDui_ActionBar4", ["Bar5"] = "NDui_ActionBar5", ["CustomBar"] = "NDui_ActionBarX", ["PetBar"] = "NDui_ActionBarPet", ["StanceBar"] = "NDui_ActionBarStance", ["AspectBar"] = "NDuiHunterAspectFrame", ["MageBarFade"] = "NDuiPlus_MageBar", } local function updateAfterCombat(event) AB:UpdateFaderState() B:UnregisterEvent(event, updateAfterCombat) end function AB:UpdateFaderState() if InCombatLockdown() then B:RegisterEvent("PLAYER_REGEN_ENABLED", updateAfterCombat) return end for key, name in pairs(NDui_ActionBar) do local bar = _G[name] if bar then bar:SetParent(AB.db[key] and AB.fadeParent or UIParent) end end if not AB.isHooked then for _, button in ipairs(Bar.buttons) do button:HookScript("OnEnter", AB.Button_OnEnter) button:HookScript("OnLeave", AB.Button_OnLeave) end AB.isHooked = true end end do if Bar.CreateAspectButton then hooksecurefunc(Bar, "CreateAspectButton", function (self, _, index) local button = _G["NDuiHunterAspectFrameButton"..index] if button and AB.db["GlobalFade"] then button:HookScript("OnEnter", AB.Button_OnEnter) button:HookScript("OnLeave", AB.Button_OnLeave) end end) end end function AB:GlobalFade() if not AB.db["GlobalFade"] then return end AB.fadeParent = CreateFrame("Frame", "NDuiPlus_Fader", _G.UIParent, "SecureHandlerStateTemplate") RegisterStateDriver(AB.fadeParent, "visibility", "[petbattle] hide; show") AB.fadeParent:SetAlpha(AB.db["Alpha"]) AB.fadeParent:RegisterEvent("ACTIONBAR_SHOWGRID") AB.fadeParent:RegisterEvent("ACTIONBAR_HIDEGRID") AB.fadeParent:SetScript("OnEvent", AB.FadeParent_OnEvent) AB:UpdateFaderSettings() AB:UpdateFaderState() end
local oakrouting = require("resty.oakrouting") local match_count = 100000 local table_insert = table.insert local match_path local routers = {} for i = 1, match_count do table_insert(routers, { path = "/bench/" .. ngx.md5(i) .. "/{name}", method = "GET", handler = function() end }) if i == match_count then match_path = "/bench/" .. ngx.md5(i) .. "/apioak" end end local oak_routing = oakrouting.new(routers) ngx.update_time() local begin_time = ngx.now() local succeed = oak_routing:dispatch(match_path, "GET") ngx.update_time() local used_time = ngx.now() - begin_time ngx.say("matched succeed : ", succeed) ngx.say("matched count : ", match_count) ngx.say("matched time : ", used_time, " sec") ngx.say("QPS : ", math.floor(match_count / used_time))
----------------------------------------------------------------------------- -- An icon representing a diff. ----------------------------------------------------------------------------- module(..., package.seeall) NODE = { prototype = "@Image", file_name = "diff.png", copyright = "Yuri Takhteyev", title = "Diff Icon", file_type = "image/png", } NODE.content = [[ iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIW XMAAAsSAAALEgHS3X78AAAAB3RJTUUH2QIQAxQTe2rLagAAAEBJREFUOMtj/P//PwMtAOPQNbizs5 MqNpSXlzMO8aC4x8hIFRuU/v8f6kHBeI86QfFfacgHxWgGGQ2K0aCgo8EA+q5Z1fsvGuwAAAAASUV ORK5CYII= ]]
local blips = { -- Example {title="", colour=, id=, x=, y=, z=}, -- Postes de polices {title="Дървар", colour=21, id=285, x=-582.984375, y=5359.9150390625, z=70.242919921875}, -- -582.984375,5359.9150390625,70.242919921875 {title="Дървар", colour=21, id=285, x=-580.0170288086, y=5276.4233398438, z=70.264877319336}, -- -580.0170288086,5276.4233398438,70.264877319336 {title="Дървар", colour=21, id=285, x=-497.21310424804, y=5299.390625, z=80.610038757324} -- -497.21310424804,5299.390625,80.610038757324 } Citizen.CreateThread(function() for _, info in pairs(blips) do info.blip = AddBlipForCoord(info.x, info.y, info.z) SetBlipSprite(info.blip, info.id) SetBlipDisplay(info.blip, 4) SetBlipScale(info.blip, 1.0) SetBlipColour(info.blip, info.colour) SetBlipAsShortRange(info.blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(info.title) EndTextCommandSetBlipName(info.blip) end end) local blips = { -- Example {title="", colour=, id=, x=, y=, z=}, -- Postes de polices {title="San Andreas Gang", colour=84, id=441, x=1365.5704345703, y=-577.87469482422, z=74.380264282227}, {title="Vagos Gang", colour=84, id=441, x=333.71691894531, y=-2037.8930664063, z=21.097738265991}, {title="Mafia Соленцево", colour=47, id=84, x=-1805.7919921875, y=433.7053527832, z=138.06114196777}, -- -1805.7919921875,433.7053527832,138.06114196777 {title="Rich Gang", colour=84, id=441, x=-927.61187744141, y=175.60478210449, z=66.497741699219}, -- -927.61187744141,175.60478210449,66.497741699219 {title="Factory Gang", colour=84, id=441, x=1155.3002929688, y=-1326.6574707031, z=34.731269836426} -- 1155.3002929688,-1326.6574707031,34.731269836426 } Citizen.CreateThread(function() for _, info in pairs(blips) do info.blip = AddBlipForCoord(info.x, info.y, info.z) SetBlipSprite(info.blip, info.id) SetBlipDisplay(info.blip, 4) SetBlipScale(info.blip, 1.9) SetBlipColour(info.blip, info.colour) SetBlipAsShortRange(info.blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(info.title) EndTextCommandSetBlipName(info.blip) end end) local blips = { -- Example {title="", colour=, id=, x=, y=, z=}, -- Postes de polices {title="Zone", colour=2, id=1, x=1365.5704345703, y=-577.87469482422, z=74.380264282227}, {title="Zone", colour=2, id=1, x=333.71691894531, y=-2037.8930664063, z=21.097738265991}, {title="Mafia Zone", colour=1, id=1, x=-1805.7919921875, y=433.7053527832, z=138.06114196777}, {title="Zone", colour=2, id=1, x=-927.61187744141, y=175.60478210449, z=66.497741699219}, {title="Zone", colour=2, id=1, x=1155.3002929688, y=-1326.6574707031, z=34.731269836426} } Citizen.CreateThread(function() for _, info in pairs(blips) do info.blip = AddBlipForCoord(info.x, info.y, info.z) SetBlipSprite(info.blip, info.id) SetBlipDisplay(info.blip, 4) SetBlipScale(info.blip, 3.9) SetBlipColour(info.blip, info.colour) SetBlipAsShortRange(info.blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(info.title) EndTextCommandSetBlipName(info.blip) end end) local blips = { -- Example {title="", colour=, id=, x=, y=, z=}, -- Postes de polices {title="Тунинг Сервиз", colour=75, id=72, x=-210.4983215332, y=-1317.3449707031, z=43.427940368652} } Citizen.CreateThread(function() for _, info in pairs(blips) do info.blip = AddBlipForCoord(info.x, info.y, info.z) SetBlipSprite(info.blip, info.id) SetBlipDisplay(info.blip, 4) SetBlipScale(info.blip, 0.9) SetBlipColour(info.blip, info.colour) SetBlipAsShortRange(info.blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(info.title) EndTextCommandSetBlipName(info.blip) end end) local blips = { -- Example {title="", colour=, id=, x=, y=, z=}, -- Postes de polices {title="Тунинг Сервиз", colour=42, id=72, x=732.64373779297, y=-1089.0834960938, z=29.699953079224} } Citizen.CreateThread(function() for _, info in pairs(blips) do info.blip = AddBlipForCoord(info.x, info.y, info.z) SetBlipSprite(info.blip, info.id) SetBlipDisplay(info.blip, 4) SetBlipScale(info.blip, 0.9) SetBlipColour(info.blip, info.colour) SetBlipAsShortRange(info.blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(info.title) EndTextCommandSetBlipName(info.blip) end end) local blips = { -- Example {title="", colour=, id=, x=, y=, z=}, -- Postes de polices {title="Тунинг Сервиз", colour=42, id=72, x=-336.18408203125, y=-137.22038269043, z=60.444530487061} } Citizen.CreateThread(function() for _, info in pairs(blips) do info.blip = AddBlipForCoord(info.x, info.y, info.z) SetBlipSprite(info.blip, info.id) SetBlipDisplay(info.blip, 4) SetBlipScale(info.blip, 0.9) SetBlipColour(info.blip, info.colour) SetBlipAsShortRange(info.blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(info.title) EndTextCommandSetBlipName(info.blip) end end) local blips = { -- Example {title="", colour=, id=, x=, y=, z=}, -- Postes de polices {title="Тунинг Сервиз", colour=42, id=72, x=-1155.6254882813, y=-2007.1301269531, z=18.504007339478} } Citizen.CreateThread(function() for _, info in pairs(blips) do info.blip = AddBlipForCoord(info.x, info.y, info.z) SetBlipSprite(info.blip, info.id) SetBlipDisplay(info.blip, 4) SetBlipScale(info.blip, 0.9) SetBlipColour(info.blip, info.colour) SetBlipAsShortRange(info.blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(info.title) EndTextCommandSetBlipName(info.blip) end end) local blips = { -- Example {title="", colour=, id=, x=, y=, z=}, -- Postes de polices {title="Тунинг Сервиз", colour=42, id=72, x=1178.8117675781, y=2638.3559570313, z=44.118740081787} } Citizen.CreateThread(function() for _, info in pairs(blips) do info.blip = AddBlipForCoord(info.x, info.y, info.z) SetBlipSprite(info.blip, info.id) SetBlipDisplay(info.blip, 4) SetBlipScale(info.blip, 0.9) SetBlipColour(info.blip, info.colour) SetBlipAsShortRange(info.blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(info.title) EndTextCommandSetBlipName(info.blip) end end) local blips = { -- Example {title="", colour=, id=, x=, y=, z=}, -- Postes de polices {title="Тунинг Сервиз", colour=42, id=72, x=110.12259674072, y=6627.2524414063, z=31.787244796753} } Citizen.CreateThread(function() for _, info in pairs(blips) do info.blip = AddBlipForCoord(info.x, info.y, info.z) SetBlipSprite(info.blip, info.id) SetBlipDisplay(info.blip, 4) SetBlipScale(info.blip, 0.9) SetBlipColour(info.blip, info.colour) SetBlipAsShortRange(info.blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(info.title) EndTextCommandSetBlipName(info.blip) end end) local blips = { -- Example {title="", colour=, id=, x=, y=, z=}, -- Postes de polices {title="Летище", colour=26, id=43, x=-1454.3540039063, y=-2482.4790039063, z=31.787244796753} } Citizen.CreateThread(function() for _, info in pairs(blips) do info.blip = AddBlipForCoord(info.x, info.y, info.z) SetBlipSprite(info.blip, info.id) SetBlipDisplay(info.blip, 4) SetBlipScale(info.blip, 0.9) SetBlipColour(info.blip, info.colour) SetBlipAsShortRange(info.blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(info.title) EndTextCommandSetBlipName(info.blip) end end)
local skynet = require "skynet" local ini = require "utils.inifile" local validator = require "utils.validator" local text = require("text").app local log = require "log" local sys = require "sys" local api = require "api" local running = false local frpcini = sys.run_root.."/frpc.ini" local svc = "frpc" local localhost = "127.0.0.1" local frpcconf = { common = { log_file = "logs/frpc.log", pool_count = 2, admin_addr = "127.0.0.1", admin_port = 7400 } } local proxylist = { ssh = { name = "ssh", type = "tcp", local_port = sys.ssh_port }, console = { name = "console", type = "tcp", local_port = sys.console_port }, ws = { name = "ws", type = "tcp", local_port = sys.ws_port }, vnc = { name = "vnc", type = "tcp", }, vpn = { name = "vpn", } } local cfg_schema = { server_addr = validator.ipv4, server_port = validator.port, token = validator.string, protocol = validator.vals("tcp", "kcp") } local p_schema = { name = validator.string, type = validator.vals("tcp", "udp"), local_ip = validator.ipv4, local_port = validator.port, remote_port = validator.port } local vnc_schema = { local_ip = validator.ipv4, local_port = validator.port, remote_port = validator.port } local vpn_type = { tcp = "stcp", udp = "sudp" } local default_vpn_type = "sudp" local cmd_desc = { open_console = "<remote_port>", close_console = "Close console port", open_ssh = "<remote_port>", close_ssh = "Close ssh port", open_ws = "<remote_port>", close_ws = "Close websocket port", open_vpn = "<token>", close_vpn = "<token>", open_vnc = "{ local_ip=<string>, local_port=<number>, remote_port=<number> }", close_vnc = "<remote_port>", open_proxy = "{ name=<string>, type=<string>, local_ip=<string>, local_port=<number>, remote_port=<number> }", close_proxy = "<name>", list_proxy = "list all opened proxy" } local function reg_cmd() for k, v in pairs(cmd_desc) do api.reg_cmd(k, v) end end local function init_proxylist(conf) for k, v in pairs(conf) do if v.name ~= "vpn" then local p = proxylist[v.name] if p then p.remote_port = v.remote_port end end end end local function init_conf(cfg) local ok, conf = pcall(ini.parse, frpcini) if ok then frpcconf = conf init_proxylist(conf) end frpcconf.common.server_addr = cfg.server_addr frpcconf.common.server_port = cfg.server_port frpcconf.common.token = cfg.token frpcconf.common.protocol = cfg.protocol local err ok, err = pcall(ini.save, frpcini, frpcconf) if not ok then log.error(err) return ok end ok, err = sys.start_svc(svc) if ok then log.info(err) else log.error(err) end if ok then ok, err = sys.enable_svc(svc) if ok then log.info(err) else log.error(err) end running = true end return ok end local function dup(proxy) for name, p in pairs(frpcconf) do if proxy.name == name or (proxy.type == p.type and proxy.remote_port == p.remote_port) then return true end end return false end local function get_vpninfo() return api.external_request(api.vpnappid, "vpn_info") end local function reload() ini.save(frpcini, frpcconf) local ok, err = sys.reload_svc(svc) if ok then log.info(err) else log.error(err) end return ok, err end local function make_name(prefix, remote_port) return string.format("%s-%d", prefix, remote_port) end local function do_open(proxy, remote_port) if not running then return false, text.app_stopped end local p = tonumber(remote_port) if not p then return false, text.invalid_arg end local name = make_name(proxy.name, p) if frpcconf[name] then return false, text.invalid_arg end proxy.local_ip = localhost proxy.remote_port = p frpcconf[name] = proxy return reload() end local function do_close(proxy) if not running then return false, text.app_stopped end local name if type(proxy) == "string" then name = proxy else name = make_name(proxy.name, proxy.remote_port) end if frpcconf[name] then frpcconf[name] = nil return reload() else return false, text.invalid_arg end end function open_console(port) return do_open(proxylist.console, port) end function close_console() return do_close(proxylist.console) end function open_ssh(port) return do_open(proxylist.ssh, port) end function close_ssh() return do_close(proxylist.ssh) end function open_ws(port) return do_open(proxylist.ws, port) end function close_ws() return do_close(proxylist.ws) end function open_vnc(vnc) if not running then return false, text.app_stopped end local ok = pcall(validator.check, vnc, vnc_schema) vnc.name = make_name(proxylist.vnc.name, vnc.remote_port) vnc.type = proxylist.vnc.type if ok and not dup(vnc) then local k = vnc.name vnc.name = proxylist.vnc.name frpcconf[k] = vnc return reload() else return false, text.invalid_arg end end function close_vnc(port) local p = tonumber(port) if p then local name = make_name(proxylist.vnc.name, p) return do_close(name) else return false, text.invalid_arg end end function open_proxy(proxy) if not running then return false, text.app_stopped end local ok = pcall(validator.check, proxy, p_schema) if ok and not dup(proxy) then frpcconf[proxy.name] = proxy return reload() else return false, text.invalid_arg end end function close_proxy(name) if type(name) == "string" then return do_close(name) else return false, text.invalid_arg end end function open_vpn(token) if not running then return false, text.app_stopped end if type(token) == "string" then local vpn = get_vpninfo() if vpn.running then frpcconf[token] = { local_port = vpn.listenport, name = proxylist.vpn.name, local_ip = localhost, type = vpn_type[vpn.proto] or default_vpn_type, sk = token } return reload() else return false, text.app_stopped end else return false, text.invalid_arg end end function close_vpn(token) if type(token) == "string" then return do_close(token) else return false, text.invalid_arg end end function list_proxy() if not running then return false, text.app_stopped end local ret = {} for k, v in pairs(frpcconf) do if k ~= "common" then ret[k] = v end end return ret end function on_conf(cfg) if cfg.server_addr == '' then -- init config return true else local ok = pcall(validator.check, cfg, cfg_schema) if ok then return init_conf(cfg) else return false, text.invalid_conf end end end reg_cmd()
local M = {} M.base_30 = { white = "#b0b0b0", darker_black = "#151b21", black = "#1a2026", -- nvim bg black2 = "#20262c", one_bg = "#242a30", one_bg2 = "#292f35", one_bg3 = "#2e343a", grey = "#42484e", grey_fg = "#474d53", grey_fg2 = "#50565c", light_grey = "#565c62", red = "#ac8a8c", baby_pink = "#de878f", pink = "#e89199", line = "#2d3339", -- for lines like vertsplit green = "#8aac8b", vibrant_green = "#9ec49f", blue = "#6b8bab", nord_blue = "#7797b7", yellow = "#c4c19e", sun = "#aca98a", purple = "#a39ec4", dark_purple = "#8f8aac", teal = "#7c9cbc", orange = "#C9938A", cyan = "#9aafe6", statusline_bg = "#1e242a", lightbg = "#2d3339", pmenu_bg = "#8aac8b", folder_bg = "#6b8bab", } M.base_16 = { base00 = "#1a2026", base01 = "#242a30", base02 = "#292f35", base03 = "#2e343a", base04 = "#42484e", base05 = "#bebebe", base06 = "#bbbbbb", base07 = "#b0b0b0", base08 = "#ac8a8c", base09 = "#C9938A", base0A = "#aca98a", base0B = "#8aac8b", base0C = "#8aabac", base0D = "#7797b7", base0E = "#948fb1", base0F = "#ac8a8c", } M.type = "dark" M = require("base46").override_theme(M, "chadtain") return M
require 'user/plugins/packer' require 'user/plugins/treesitter' require 'user/plugins/git-signs' require 'user/plugins/indent-blank-line' require 'user/plugins/null-ls' require 'user/plugins/nvim-tree' require 'user/plugins/telescope' require 'user/plugins/harpoon' require 'user/plugins/nvim-dashboard' require 'user/plugins/lua-line' require 'user/plugins/lua-snip' require 'user/plugins/lsp-saga' require 'user/plugins/lsp-cmp'
if ACF.Version then --fallback to old acf, its not set in acf3 function ACF_DefineEngineold(id,data) ACF_DefineEngine(id,data) end else local class = "zACFE B" local typeoverwrite = nil -- Flat 2 engines ACF.RegisterEngineClass(class, { Name = "ACFE Flat Engines", }) do function ACF_DefineEngineold(id,data) local Fueltype = {} if data.fuel == "Petrol" then Fueltype = { Petrol = true } end if data.fuel == "Diesel" then Fueltype = { Diesel = true } end if data.fuel == "Multifuel" then Fueltype = { Petrol = true, Diesel = true } end if data.fuel == "Electric" then Fueltype = { Electric = true } end ACF.RegisterEngine(id, class, { Name = data.name, Description = data.desc, Model = data.model, Sound = data.sound, Fuel = Fueltype, Type = typeoverwrite or data.enginetype, Mass = data.weight, Torque = data.torque, FlywheelMass = data.flywheelmass, RPM = { Idle = data.idlerpm, PeakMin = data.peakminrpm, PeakMax = data.peakmaxrpm, Limit = data.limitrpm, }, }) end end end -- boxer 2 engines ACF_DefineEngineold( "B2-1.2", { name = "B2 1.2L Flat 2 Petrol", desc = "[ACFE] bike sized flat two engine, sporty and light", model = "models/engines/b2s.mdl", sound = "acf_engines/b2s.wav", category = "B", fuel = "Petrol", enginetype = "GenericPetrol", weight = 35, torque = 120, flywheelmass = 0.08, idlerpm = 750, peakminrpm = 5500, peakmaxrpm = 7500, limitrpm = 8500 } ) ACF_DefineEngineold( "B2-2.3", { name = "B2 2.3L Flat 2 Petrol", desc = "[ACFE] car grade flat two, cuz it looks cool", model = "models/engines/b2m.mdl", sound = "acf_engines/b2m.wav", category = "B", fuel = "Petrol", enginetype = "GenericPetrol", weight = 75, torque = 290, flywheelmass = 0.1, idlerpm = 900, peakminrpm = 4300, peakmaxrpm = 6500, limitrpm = 7200 } ) ACF_DefineEngineold( "B2-4.6", { name = "B2 4.6L Flat 2 Petrol", desc = "[ACFE] Aircraft grade boxer", model = "models/engines/b2l.mdl", sound = "acf_engines/b2l.wav", category = "B", fuel = "Petrol", enginetype = "GenericPetrol", weight = 160, torque = 480, flywheelmass = 0.7, idlerpm = 620, peakminrpm = 2800, peakmaxrpm = 5200, limitrpm = 6000 } )
local module = {} -- CONFIG cfg_wifi = require("CFG_wifi") local mod_timer -- dynamic timer object local mod_callback = nil local function wifi_wait_ip() if wifi.sta.getip()== nil then print("IP?") else mod_timer:unregister() mod_timer = nil print("IP: "..wifi.sta.getip()) -- print("MAC: " .. wifi.ap.getmac()) if mod_callback ~= nil then mod_callback() end end end function module.init(cb) mod_callback = cb wifi.setmode(wifi.STATION) wifi.sta.config(cfg_wifi.WIFICFG) mod_timer = tmr.create() mod_timer:alarm(1000, tmr.ALARM_AUTO, wifi_wait_ip) end return module
local function explosion_effects(pos,strength) minetest.sound_play("td_explosion", {pos = pos, gain = strength/100, max_hear_distance = 60,}, true) minetest.add_particlespawner({ amount = 20, time = 0.1, minpos = vector.add(pos,{x=-0.5,y=-0.5,z=-0.5}), maxpos = vector.add(pos,{x=0.5,y=0.5,z=0.5}), minvel = {x=-2,y=-2,z=-2}, maxvel = {x=2,y=2,z=2}, minacc = {x=0,y=0,z=0}, maxacc = {x=0,y=0,z=0}, minexptime = 0.5, maxexptime = 1, minsize = 5, maxsize = 10, collisiondetection = false, collision_removal = false, object_collision = false, texture = "tower_defense_explosion_smoke.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1, }, }) end function tower_defense.explode_nodes(base_pos,base_strength) local visited = {} local neighbors = { {x=-1,y=0,z=0}, {x=1,y=0,z=0}, {x=0,y=-1,z=0}, {x=0,y=1,z=0}, {x=0,y=0,z=-1}, {x=0,y=0,z=1}, } local function boom(pos,strength) visited[pos.x.." "..pos.y.." "..pos.z] = true local node = minetest.get_node(pos) if node.name == "air" then strength = strength - 5 else local def = minetest.registered_nodes[node.name] if def and def.groups and def.groups.health then local meta = minetest.get_meta(pos) local health = meta:get_int("td_health") if health == 0 then health = def.groups.health end health = health - strength if health == 0 then strength = 0 minetest.set_node(pos,{name="air"}) elseif health > 0 then strength = 0 meta:set_int("td_health", health) elseif health < 0 then strength = math.abs(health) minetest.set_node(pos,{name="air"}) end else strength = 0 end end if strength > 0 then for _,neighbor in pairs(neighbors) do local n_pos = vector.add(pos,neighbor) if not visited[n_pos.x.." "..n_pos.y.." "..n_pos.z] then boom(n_pos,strength) end end end end boom(base_pos,base_strength) explosion_effects(base_pos,base_strength) end function tower_defense.explode_tanks(pos,strength) local ents = minetest.get_objects_inside_radius(pos,strength/25) for _, ent in ipairs(ents) do if ent:get_luaentity() and ent:get_luaentity()._is_tank then local t_pos = ent:get_pos() local dist = vector.distance(pos,t_pos) local punch_strength = math.max(strength - dist*25,0) if punch_strength > 0 then ent:punch(ent, 1, {damage_groups = {armored = punch_strength},full_punch_interval = 0.5}) end end end explosion_effects(pos,strength) end
-- This is an example showing how to configure analog input settings on -- on T-Series devices. print("Configure & Read Analog Input") ainChannels = {0,1} -- Read AIN0 and AIN1 ainRange = 10 -- +/-10V ainResolution = 1 -- Fastest ainSettling = 0 -- Default -- This function can be used to configure general analog input settings such as -- Range, Resolution, and Settling. More information about these settings can -- be found on the LabJack website under the AIN section: -- https://labjack.com/support/datasheets/t-series/ain function ainChConfig(ainChNum, range, resolution, settling, isDifferential) MB.W(40000 + ainChNum * 2, 3, range) -- Set AIN Range MB.W(41500 + ainChNum * 1, 0, resolution) -- Set Resolution Index MB.W(42000 + ainChNum * 2, 3, settling) -- Set Settling US dt = MB.R(60000, 3) -- Read device type if isDifferential and (ainChNum%2 == 0) and (dt == 7) then -- The negative channels setting is only valid for even -- analog input channels and is not valid for the T4. if (ainChNum < 14) then -- The negative channel is 1+ the channel for AIN0-13 on the T7 MB.W(41000 + ainChNum, 0, ainChNum + 1) elseif (ainChNum > 47) then -- The negative channel is 8+ the channel for AIN48-127 on the T7 -- when using a Mux80. -- https://labjack.com/support/datasheets/accessories/mux80 MB.W(41000 + ainChNum, 0, ainChNum + 8) else print(string.format("Can not set negative channel for AIN%d",ainChNum)) end end end -- Configure each analog input for i=1,table.getn(ainChannels) do ainChConfig(ainChannels[i], ainRange, ainResolution, ainSettling) end LJ.IntervalConfig(0, 500) -- Configure interval local checkInterval=LJ.CheckInterval while true do if checkInterval(0) then -- interval finished -- Read & Print out each read AIN channel for i=1, table.getn(ainChannels) do ainVal = MB.R(ainChannels[i] * 2, 3) print(string.format("AIN%d: %.3f", ainChannels[i], ainVal)) end end end
function _G.stringify(data) if data == nil then return "nil" end return tostring(data) end function _G.listToString(data) local s = "{" for k, v in pairs(data) do local toAppend = stringify(v) if type(v) == "table" then toAppend = listToString(v) end s = s .. stringify(k) .. ": " .. toAppend .. ", " end return s .. "}" end -- ToDo: -- Fire rate etc. not determined by host -- Custom laser color for sentry -- Hooks:PostHook(SentryGunWeapon, "setup", "opsentry_init", function (self, unit) if OpSentriesMenu:enabled() then log("Sentry init") self._auto_reload = true self._shot_cooldown = OpSentriesMenu:shot_cooldown() end end ) Hooks:PostHook(SentryGunWeapon, "_set_fire_mode", "opsentry_change_firerate", function (self, unit) if OpSentriesMenu:enabled() then self._fire_rate_reduction = self._shot_cooldown end end ) Hooks:PostHook(SentryGunWeapon, "fire", "opsentry_no_ammo_usage", function (self, blanks, expend_ammo, shoot_player, target_unit) if expend_ammo then if not OpSentriesMenu:use_ammo() then self:change_ammo(1) end end end )
function SpawnPoints() return { constructionworker = { { worldX = 41, worldY = 15, posX = 212, posY = 3, posZ = 0 } }, fireofficer = { { worldX = 41, worldY = 15, posX = 212, posY = 3, posZ = 0 } }, parkranger = { { worldX = 41, worldY = 15, posX = 212, posY = 3, posZ = 0 } }, policeofficer = { { worldX = 41, worldY = 15, posX = 212, posY = 3, posZ = 0 } }, securityguard = { { worldX = 41, worldY = 15, posX = 212, posY = 3, posZ = 0 } }, unemployed = { { worldX = 41, worldY = 15, posX = 212, posY = 3, posZ = 0 } } } end
local body_data = require("app.public.data.body_data") local global_data = {} function global_data.load() --读取全局变量 g_data = {} g_data.player = {[1]=body_data.new()} g_data.language = 0--默认中文 g_data.gate_id = 1--当前关卡 g_data.wait_time = 3--找怪等待时间 end return global_data
local web = require 'lj.web' web.route {'/', function(req, resp, param) resp:say {'hello, resty web!'} end} web.route {'/baidu', function(req, resp, param) local http = require "resty.http" local hc = http:new() local ok, code, headers, status, body = hc:request { url = "http://www.baidu.com/", } resp:say {ok, code, body} end} web.route {'/hello/:name', function(req, resp, param) resp:printf {'hello, %s!\n', param.name or 'nil'} print 'abc end' end} web.run()
-- A lualine theme that infers palette from the current style. local palette = require('monarized.palette') local M = { normal = { a = {bg = palette.accent0, fg = palette.bg0, gui = 'bold'}, b = {bg = palette.bg1, fg = palette.fg0}, c = {bg = palette.bg1, fg = palette.fg1} }, insert = { a = {bg = palette.accent1, fg = palette.bg0, gui = 'bold'}, b = {bg = palette.bg1, fg = palette.fg0}, c = {bg = palette.bg1, fg = palette.fg1} }, replace = { a = {bg = palette.hl0, fg = palette.bg0, gui = 'bold'}, b = {bg = palette.bg1, fg = palette.fg0}, c = {bg = palette.bg1, fg = palette.fg1} }, visual = { a = {bg = palette.hl1, fg = palette.bg0, gui = 'bold'}, b = {bg = palette.bg1, fg = palette.fg0}, c = {bg = palette.bg1, fg = palette.fg1} }, command = { a = {bg = palette.hl1, fg = palette.bg0, gui = 'bold'}, b = {bg = palette.bg1, fg = palette.fg0}, c = {bg = palette.bg1, fg = palette.fg1} } } M.terminal = M.command M.inactive = M.normal return M
--local expect = require("cc.expect").expect -- Init ComputerCraft built-in expect function. --^^^ Not available in os.loadAPI() ^^^ --local function expectColor(var) -- --end function drawpixel(x,y,c) --expect(1, x, "number") --expect(2, y, "number") term.setPixel(x,y,c) end function drawRect(x,y,x2,y2,c) --expect(1, x, "number") --expect(2, y, "number") --expect(3, x2, "number") --expect(4, y2, "number") local oldColor = term.getTextColor() local cOk, cErr = pcall(term.setTextColor, c) if cOk then term.setTextColor(oldColor) else error(cErr, 2) end for i = x,x2,1 do for o = y,y2,1 do graphics.drawpixel(i,o,c) end end end function getSize() local w, h = term.getSize() return w * 6, h * 9 end function enableGraphicsMode(cn) --expect(1, cn, "number") if cn == 16 then term.setGraphicsMode(1) elseif cn == 256 then term.setGraphicsMode(2) else error("Graphics mode not supported") end end function disableGraphicsMode() term.setGraphicsMode(0) end function screenshot() term.screenshot() end
function dump(o) if type(o) == 'table' then local s = '{ ' for k,v in pairs(o) do if type(k) ~= 'number' then k = '"'..k..'"' end s = s .. '['..k..'] = ' .. dump(v) .. ',' end return s .. '} ' else return tostring(o) end end function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end return { { Pandoc = function(pdoc) entry = string.format(" - [%s](/%s/index.html) - %s\n", pandoc.utils.stringify(pdoc.meta.title), string.gsub(PANDOC_STATE.input_files[1],"%..*",""), pandoc.utils.stringify(pdoc.meta.date)) if not file_exists("post_list.md") then file = io.open("post_list.md", "w") io.output(file) io.write("---\ntitle: \"Archive\"\n---\n"); io.close(file) end file = io.open("post_list.md","a") io.output(file) io.write(entry) io.close(file) return pandoc.Pandoc({}) end, } }
local tArgs, installer, err = {...}, nil, nil local response = http.get("https://raw.githubusercontent.com/blunty666/CC-Programs-and-APIs/master/installer/main.lua") if response then installer = response.readAll() response.close() else printError("Failed to download installer script") return end installer, err = load(installer, "githubInstaller", "t", _G) if not installer then printError("Error loading installer script: "..err) return end installer, err = pcall(installer, unpack(tArgs)) if not installer then printError(err) end
Panel = g_panel_mgr.new_panel_class('editor/uieditor/uieditor_action_demon') -- overwrite function Panel:init_panel(actionName) self:updateAction(actionName) end function Panel:updateAction(actionName) if actionName == self.actionName then self:close_panel() else self.actionName = actionName local __temp_path = string.format("%s/action_demon_config/__temp_generate_%s.txt", g_fileUtils:getWritablePath(), actionName) if g_fileUtils:isFileExist(__temp_path) then local info_list = table.read_from_file(__temp_path) self:_drawActionByActionConfig(info_list) else editor_utils_generate_action_info(actionName, true, function(info_list) self:_drawActionByActionConfig(info_list) end) end end end function Panel:_drawActionByActionConfig(posList) if not self:get_layer():IsValid() then return end local drawNode = cc.DrawNode:create() self.node:AddChild(nil, drawNode) local lastPosition = posList[1] for _, pos in ipairs(posList) do drawNode:drawSegment(lastPosition, pos, 2, cc.c4f(0, 1, 0, 1)) lastPosition = pos end end
project "Utils-RapidJSON" AddModuleConfig() uuid "6F48D799-73F6-4581-AC7D-1A5A322A21AB" pchheader "stdafx_RapidJSON.h" pchsource "../src/stdafx_RapidJSON.cpp" defines { "RAPIDJSON_HAS_STDSTRING=0", "RAPIDJSON_SSE2", } includedirs { "../Externals/rapidjson/include", }
local playsession = { {"ruetama", {759638}}, {"waxman", {268447}}, {"drill95", {263569}}, {"WorldofWarIII", {826616}}, {"remarkablysilly", {613986}}, {"tykak", {168265}}, {"belbo", {636652}}, {"Flashbacks", {796974}}, {"Sharuh", {695439}}, {"akrause", {262840}}, {"Krengrus", {818580}}, {"sjonny87", {777417}}, {"Dimava", {243315}}, {"Nate66873", {804280}}, {"StarPirate", {287796}}, {"wekkka", {559501}}, {"NoGames", {768183}}, {"KIRkomMAX", {281494}}, {"SuchRandom", {2144}}, {"wildgrim", {752640}}, {"IvnSoft", {747856}}, {"Scuideie-Guy", {549448}}, {"redlabel", {739008}}, {"Deadycool", {291325}}, {"mar123322", {101774}}, {"albo", {184906}}, {"Farglon", {314217}}, {"Duncaniax", {648858}}, {"Marwonline", {617710}}, {"Order", {10955}}, {"svjatosha", {2792}}, {"beggs2k", {622245}}, {"cogito123", {306196}}, {"SiddCon", {141685}}, {"tyce1234", {17385}}, {"EPO666", {577969}}, {"LT.Jack", {61890}}, {"stead08", {553095}}, {"Patchouli.K", {13141}}, {"Zorky", {542823}}, {"xmicx22", {2961}}, {"sivael", {219101}}, {"Bucheron09", {236685}}, {"Yoy3k", {74613}}, {"beranabus", {348006}}, {"rew5huerherw98zzuh", {19380}}, {"ZeroBeta", {45049}}, {"Mr.Pestilence", {4527}}, {"JuanMore", {820}}, {"beol", {489}}, {"lthcweb", {9793}}, {"littleminion007", {3087}}, {"Taylor3", {1811}}, {"maximuskylus", {273926}}, {"michielvermaat01", {155943}}, {"FireFox736", {256707}}, {"Krono", {8531}}, {"DKarma", {235166}}, {"LymBAOBEI", {18056}}, {"zaxb5357915", {6612}}, {"Gerkiz", {190143}}, {"D0pex", {183796}}, {"Ruslan_kc", {16379}}, {"raskl", {175}}, {"Kimerss", {645}}, {"keysersoyze", {142073}}, {"Idefix88", {100362}}, {"danyal_knights", {57510}}, {"Drakelor", {47061}}, {"die_ott", {94859}}, {"Headscrew", {52743}}, {"opt_natter", {2737}}, {"jagger23", {30513}}, {"bgs187", {19433}}, {"Notandor", {54310}}, {"Kalkune", {6683}}, {"Esik", {225}}, {"fqbbq", {6774}}, {"crusher_sut", {9314}}, {"Guitoune", {7149}} } return playsession
local BulletKonkie = Projectile:extend("BulletKonkie") function BulletKonkie:new(x, y, angle) BulletKonkie.super.new(self, x, y) self:setImage("bosses/lekkerchat/konkie") self.solid = 0 self:addIgnoreOverlap(LekkerChat, SolidTile) self.autoFlip.x = false self.speed = 700 self.velocity.x = -self.speed self.damaging = true self.scale:set(0) self.flux:to(self.scale, 0.3, {x = 1, y = 1}) end function BulletKonkie:update(dt) BulletKonkie.super.update(self, dt) end function BulletKonkie:draw() BulletKonkie.super.draw(self) end return BulletKonkie
--[[ s:UI NPC Scan Martin Karer / Sezz, 2014 http://www.sezz.at --]] local S = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:GetAddon("SezzUI"); local M = S:CreateSubmodule("NPCScan"); local Apollo = Apollo; local log; ----------------------------------------------------------------------------- -- Initialization ----------------------------------------------------------------------------- function M:OnInitialize() log = S.Log; end function M:OnEnable() Apollo.RegisterTimerHandler("SezzUITimer_NPCScan", "RestoreVolume", self); self:RegisterEvent("UnitCreated"); end function M:OnDisable() self:UnregisterEvent("UnitCreated"); end ----------------------------------------------------------------------------- -- Code ----------------------------------------------------------------------------- local fVolumeMaster = Apollo.GetConsoleVariable("sound.volumeMaster"); local tWatchedUnits = { ["Goldensun Dawngrazer"] = true, ["Scorchwing"] = true, ["Subject K - Brute"] = true, ["Subject V - Tempest"] = true, ["Subject Tau"] = true, ["Subject J - Fiend"] = true, -- ["Softsnow Jabbit"] = true, }; function M:UnitCreated(event, unit) if (unit and unit:IsValid() and not unit:IsACharacter()) then local strName = unit:GetName(); if (strName and tWatchedUnits[strName] and S.bCharacterLoaded and unit ~= S.myCharacter:GetAlternateTarget()) then Print(string.format("Found Unit: %s", strName)); S.myCharacter:SetAlternateTarget(unit); if (not self.bAlertPlaying) then self.bAlertPlaying = true; fVolumeMaster = Apollo.GetConsoleVariable("sound.volumeMaster"); Apollo.SetConsoleVariable("sound.volumeMaster", 1); Sound.Play(Sound.PlayUISoldierHoldoutAchieved); Apollo.CreateTimer("SezzUITimer_NPCScan", 1, false); end -- Sound.Play(Sound.PlayUIStoryPanelUrgent); end end end function M:RestoreVolume() self.bAlertPlaying = false; Apollo.SetConsoleVariable("sound.volumeMaster", fVolumeMaster); end
-- +-- lolwut -- V local Path_PATH=({...})[1]:gsub("[%.\\/]path$", "") .. '/' local class =require (Path_PATH .. 'vendor/30log') local Path=class { _toX, _toY, _fromX, _fromY, _passableCallback, _options, _dirs} function Path:__init(toX, toY, passableCallback, options) self._toX =toX self._toY =toY self._fromX=nil self._fromY=nil self._passableCallback=passableCallback self._options= { topology=8 } if options then for k,_ in pairs(options) do self._options[k]=options[k] end end self._dirs= self._options.topology==8 and ROT.DIRS.EIGHT or ROT.DIRS.FOUR end function Path:compute(fromX, fromY, callback) end function Path:_getNeighbors(cx, cy) local result={} for i=1,#self._dirs do local dir=self._dirs[i] local x=cx+dir[1] local y=cy+dir[2] if self._passableCallback(x, y) then table.insert(result, {x, y}) end end return result end return Path
local helper = require("curstr.lib.testlib.helper") local curstr = helper.require("curstr") describe("vim/search", function() before_each(helper.before_each) after_each(helper.after_each) it("file_one", function() curstr.setup({ sources = {["vim/search"] = {opts = {source_pattern = "\\v\\k+", search_pattern = "\\1:\\1"}}}, }) helper.open_new_file("entry", [[ hoge hoge:hoge]]) helper.cd() curstr.execute("vim/search") assert.current_row(3) assert.current_line("hoge:hoge") end) it("not_found", function() helper.open_new_file("entry") curstr.execute("vim/search") assert.current_row(1) end) end)
require "conf" require "audio" require "Screens/menu" require "Game/game" require "Screens/gameover" --require "PUC_Logo/PUC_Logo" require "RPG_Full_Logo/RPG_Logo" require "inputData" --io.stdout:setvbuf("no") local gameState = RPG_Logo--PUC_Logo local goToState function love.load() menu.load() audio.load() game.load() gameover.load() RPG_Logo.load(1.2,1.5,1.2,love.returnToMenu)--PUC_Logo.load(1,1,1,1,love.returnToMenu) audio.play(audio.stageMusic) gameState.start() inputData.start() end function love.keypressed(key) gameState.keypressed(key) end function love.gamepadpressed(joy,but) if gameState.gamepadpressed ~= nil then gameState.gamepadpressed(joy,but) end end function love.mousepressed(x,y,button) gameState.mousepressed(x,y,button) end function love.update(dt) gameState.update(dt) end function love.startGame(data) goToState(game,data) end function love.returnToMenu() goToState(menu,data) end function love.gameover() goToState(gameover) end function goToState(s,data) gameState = s --gameState.start(data) gameState.start(data) end function love.draw() gameState.draw() end
--[[ -- All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -- its licensors. -- -- For complete copyright and license terms please see the LICENSE at the root of this -- distribution (the "License"). All use of this software is governed by the License, -- or, if provided, by the license below or the license accompanying this file. Do not -- remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --]] local weaponswitcher = { Properties = { Events = { ControlsEnabled = { default = "EnableControlsEvent", description = "If passed '1.0' it will enable controls, oherwise it will disable them." }, EnableWeapon = { default = "EventEnableWeapon", description = "Sent with the name of the weapon in ofder to switch the weapon selection on." }, }, -- The weapons to be used. Weapons = { Pistol = { Weapon = {default = EntityId()}, Enabled = { default = true, description = "am i available to the player?" }, }, Grenade = { Weapon = {default = EntityId()}, Enabled = { default = false, description = "am i available to the player?" }, }, }, WeaponSetup = { GenericEvents = { Activate = "EventActivate"; }, -- The bone that the weapons will attach to. -- This may need to become weapon-specific if we end up having weird weapons (e.g. shoulder-mounted). Bone = { default = "r_handProp", description = "The bone to attach the weapon to." }, }, Audio = { WpnSwitchSound = { default = "Play_HUD_wpn_switch", description = "Weapon Switch Sound" }, }, }, } -------------------------------------------------- -- Component behavior -------------------------------------------------- function weaponswitcher:OnActivate() --Debug.Log("weaponswitcher entityId: ".. tostring(self.entityId)) -- Play the specified Audio Trigger (wwise event) on this component AudioTriggerComponentRequestBus.Event.Play(self.entityId); -- Enable and disable events self.enableEventId = GameplayNotificationId(self.entityId, "Enable", "float"); self.enableHandler = GameplayNotificationBus.Connect(self, self.enableEventId); self.disableEventId = GameplayNotificationId(self.entityId, "Disable", "float"); self.disableHandler = GameplayNotificationBus.Connect(self, self.disableEventId); self.setVisibleEventId = GameplayNotificationId(self.entityId, "SetVisible", "float"); self.setVisibleHandler = GameplayNotificationBus.Connect(self, self.setVisibleEventId); -- Input listeners (weapon). self.weaponSwitchEventId = GameplayNotificationId(self.entityId, "WeaponSwitch", "float"); self.weaponSwitchHandler = GameplayNotificationBus.Connect(self, self.weaponSwitchEventId); self.enableWeaponEventId = GameplayNotificationId(self.entityId, self.Properties.Events.EnableWeapon, "float"); self.enableWeaponHandler = GameplayNotificationBus.Connect(self, self.enableWeaponEventId); -- Set the weapon information. Debug.Assert(self.Properties.Weapons.Pistol.Weapon ~= 0 and self.Properties.Weapons.Pistol.Weapon); Debug.Assert(self.Properties.Weapons.Grenade.Weapon ~= 0 and self.Properties.Weapons.Grenade.Weapon); self.varWpnSwitchSound = self.Properties.Audio.WpnSwitchSound; -- Tick needed to detect aim timeout self.tickBusHandler = TickBus.Connect(self); self.enabled = true; self.controlsDisabledCount = 0; self.controlsEnabled = true; self.controlsEnabledEventId = GameplayNotificationId(self.entityId, self.Properties.Events.ControlsEnabled, "float"); self.controlsEnabledHandler = GameplayNotificationBus.Connect(self, self.controlsEnabledEventId); --Debug.Log("weaponswitcher:OnActivate " .. tostring(self.controlsEnabledEventId)); end function weaponswitcher:OnDeactivate() self.weaponSwitchHandler:Disconnect(); self.weaponSwitchHandler = nil; self.enableWeaponHandler:Disconnect(); self.enableWeaponHandler = nil; if(self.tickBusHandler ~= nil) then self.tickBusHandler:Disconnect(); self.tickBusHandler = nil; end if (self.enableHandler ~= nil) then self.enableHandler:Disconnect(); self.enableHandler = nil; end if (self.disableHandler ~= nil) then self.disableHandler:Disconnect(); self.disableHandler = nil; end if (self.setVisibleHandler ~= nil) then self.setVisibleHandler:Disconnect(); self.setVisibleHandler = nil; end end function weaponswitcher:ChangeWeapon() if (self.activeWeapon == nil) then self.activeWeapon = self.Properties.Weapons[1]; self:SetupNewWeapon(); else local foundExisting = false; local foundNext = false; local newWeapon = nil; for key,value in pairs(self.Properties.Weapons) do if (value == self.activeWeapon) then foundExisting = true; elseif (foundExisting and (not foundNext) and value.Enabled) then foundNext = true; newWeapon = value; break; end end -- if i have not found the next one to use do a search from the beginning till our current to wrap our search if (foundExisting and (not foundNext)) then for key,value in pairs(self.Properties.Weapons) do if (value == self.activeWeapon) then -- i have done a full loop, so bail break; elseif (value.Enabled) then foundNext = true; newWeapon = value; break; end end end if(foundExisting and foundNext) then -- Detach the old weapon. AttachmentComponentRequestBus.Event.Detach(self.activeWeapon.Weapon); MeshComponentRequestBus.Event.SetVisibility(self.activeWeapon.Weapon, false); -- fire an event off to tell the current weapon that we are not using it anymore GameplayNotificationBus.Event.OnEventBegin(self.activeWeaponActivateEventId, 0); AudioTriggerComponentRequestBus.Event.ExecuteTrigger(self.entityId, self.varWpnSwitchSound); self.activeWeapon = newWeapon; self:SetupNewWeapon(); end end -- if (self.activeWeapon == self.Properties.Weapons.Pistol) then -- self.activeWeapon = self.Properties.Weapons.Grenade; -- elseif (self.activeWeapon == self.Properties.Weapons.Grenade) then -- self.activeWeapon = self.Properties.Weapons.Pistol; -- else -- self.activeWeapon = self.Properties.Weapons.Pistol; -- end end function weaponswitcher:SetupNewWeapon() Debug.Assert(self.activeWeapon ~= 0 and self.activeWeapon); local tm = TransformBus.Event.GetWorldTM(self.activeWeapon.Weapon); local scale = tm:ExtractScale(); tm = Transform:CreateIdentity(); tm:MultiplyByScale(scale); MeshComponentRequestBus.Event.SetVisibility(self.activeWeapon.Weapon, true); AttachmentComponentRequestBus.Event.Attach(self.activeWeapon.Weapon, self.entityId, self.Properties.WeaponSetup.Bone, tm); self.activeWeaponActivateEventId = GameplayNotificationId(self.activeWeapon.Weapon, self.Properties.WeaponSetup.GenericEvents.Activate, "float"); GameplayNotificationBus.Event.OnEventBegin(self.activeWeaponActivateEventId, 1); local onSetupNewWeaponEventId = GameplayNotificationId(self.entityId, "OnSetupNewWeapon", "float"); GameplayNotificationBus.Event.OnEventBegin(onSetupNewWeaponEventId, self.activeWeapon.Weapon); end function weaponswitcher:OnTick(deltaTime, timePoint) -- First update initialisation self.activeWeapon = self.Properties.Weapons.Pistol; self:SetupNewWeapon(); self.tickBusHandler:Disconnect(); self.tickBusHandler = nil; end function weaponswitcher:SetControlsEnabled(newControlsEnabled) self.controlsEnabled = newControlsEnabled; end function weaponswitcher:EnableWeapon(weapon) for key,value in pairs(self.Properties.Weapons) do if (key == weapon) then value.Enabled = true; return; end end end function weaponswitcher:OnEventBegin(value) local busId = GameplayNotificationBus.GetCurrentBusId(); --Debug.Log("weaponswitcher:OnEventBegin " .. tostring(busId) .. " " .. tostring(value)); if (busId == self.controlsEnabledEventId) then --Debug.Log("weaponswitcher:controlsEnabledEventId " .. tostring(value)); if (value == 1.0) then self.controlsDisabledCount = self.controlsDisabledCount - 1; else self.controlsDisabledCount = self.controlsDisabledCount + 1; end if (self.controlsDisabledCount < 0) then Debug.Log("[Warning] WeaponSwitcher: controls disabled ref count is less than 0. Probable enable/disable mismatch."); self.controlsDisabledCount = 0; end local newEnabled = self.controlsDisabledCount == 0; if (self.controlsEnabled ~= newEnabled) then self:SetControlsEnabled(newEnabled); end end if (self.controlsEnabled) then -- Player controls. if ((busId == self.weaponSwitchEventId) and (self.enabled)) then self:ChangeWeapon(); end end if (busId == self.enableEventId) then self:OnEnable(); elseif (busId == self.disableEventId) then self:OnDisable(); elseif (busId == self.setVisibleEventId) then MeshComponentRequestBus.Event.SetVisibility(self.activeWeapon.Weapon, value); elseif (busId == self.enableWeaponEventId) then self:EnableWeapon(value); end end function weaponswitcher:OnEnable() self.enabled = true; MeshComponentRequestBus.Event.SetVisibility(self.activeWeapon.Weapon, true); -- We don't want to re-join the tick bus because it's only meant to be for setup; -- which should have been done when we were disabled. If we perform the tick again -- then it may forcibly reset values (such as the active weapon). --self.tickBusHandler = TickBus.Connect(self); end function weaponswitcher:OnDisable() self.enabled = false; -- If the active weapon hasn't been assigned yet then it means we haven't ticked but -- something else has in order to send us a 'disable' message. Therefore, assume that -- enough things have been setup by now for the tick function to process things -- correctly. if (self.activeWeapon == nil) then self:OnTick(0, 0); end MeshComponentRequestBus.Event.SetVisibility(self.activeWeapon.Weapon, false); if (self.tickBusHandler ~= nil) then self.tickBusHandler:Disconnect(); end end return weaponswitcher;
local _2afile_2a = "fnl/conjure/event.fnl" local _0_ do local name_0_ = "conjure.event" local module_0_ do local x_0_ = package.loaded[name_0_] if ("table" == type(x_0_)) then module_0_ = x_0_ else module_0_ = {} end end module_0_["aniseed/module"] = name_0_ module_0_["aniseed/locals"] = ((module_0_)["aniseed/locals"] or {}) do end (module_0_)["aniseed/local-fns"] = ((module_0_)["aniseed/local-fns"] or {}) do end (package.loaded)[name_0_] = module_0_ _0_ = module_0_ end local autoload local function _1_(...) return (require("conjure.aniseed.autoload")).autoload(...) end autoload = _1_ local function _2_(...) local ok_3f_0_, val_0_ = nil, nil local function _2_() return {autoload("conjure.aniseed.core"), autoload("conjure.client"), autoload("conjure.aniseed.nvim"), autoload("conjure.aniseed.string"), autoload("conjure.text")} end ok_3f_0_, val_0_ = pcall(_2_) if ok_3f_0_ then _0_["aniseed/local-fns"] = {autoload = {a = "conjure.aniseed.core", client = "conjure.client", nvim = "conjure.aniseed.nvim", str = "conjure.aniseed.string", text = "conjure.text"}} return val_0_ else return print(val_0_) end end local _local_0_ = _2_(...) local a = _local_0_[1] local client = _local_0_[2] local nvim = _local_0_[3] local str = _local_0_[4] local text = _local_0_[5] local _2amodule_2a = _0_ local _2amodule_name_2a = "conjure.event" do local _ = ({nil, _0_, nil, {{}, nil, nil, nil}})[2] end local emit do local v_0_ do local v_0_0 local function emit0(...) do local names = a.map(text["upper-first"], {...}) local function _3_() while not a["empty?"](names) do nvim.ex.doautocmd("User", ("Conjure" .. str.join(names))) table.remove(names) end return nil end client.schedule(_3_) end return nil end v_0_0 = emit0 _0_["emit"] = v_0_0 v_0_ = v_0_0 end local t_0_ = (_0_)["aniseed/locals"] t_0_["emit"] = v_0_ emit = v_0_ end return nil
object_mobile_dressed_officer_merc5 = object_mobile_shared_dressed_officer_merc5:new { } ObjectTemplates:addTemplate(object_mobile_dressed_officer_merc5, "object/mobile/dressed_officer_merc5.iff")
package("lzo") set_homepage("http://www.oberhumer.com/opensource/lzo") set_description("LZO is a portable lossless data compression library written in ANSI C.") set_license("GPL-2.0") add_urls("http://www.oberhumer.com/opensource/lzo/download/lzo-$(version).tar.gz") add_versions("2.10", "c0f892943208266f9b6543b3ae308fab6284c5c90e627931446fb49b4221a072") add_deps("cmake") on_install(function (package) local configs = {} table.insert(configs, "-DENABLE_SHARED=" .. (package:config("shared") and "ON" or "OFF")) table.insert(configs, "-DENABLE_STATIC=" .. (package:config("shared") and "OFF" or "ON")) table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:debug() and "Debug" or "Release")) import("package.tools.cmake").install(package, configs) end) on_test(function (package) assert(package:has_cfuncs("lzo_version", {includes = "lzo/lzo1x.h"})) end)
-- nil, significa "sin referencia" nombre = "Mucha informacion" if nombre == nil then print("No tiene referencia") else print("con referencia") end nombre = nil -- aquí elmino la referencia -- libero memoria if nombre == nil then print("No tiene referencia") else print("con referencia") end ---
package.path = "../?.lua;"..package.path; local winman = require("WinMan") local spiroapp = require("BEST_spiroapp") local framestatapp = require("BEST_framestat") local keyboardapp = require("BEST_CompKeyboard") local GImage = require("GIMage") local GRandomLines = require("GRandomlines") local desktopWidth = 1024 local desktopHeight = 768 local liner = GRandomLines:new({frame={width=desktopWidth, height=desktopHeight}}) local img, err = BLImageCodec:readImageFromFile("resources/kibera_1.jpg") --print("readImage: ", img, err) local bkgnd, err = GImage:new({image = img, frame = BLRect({0,0,desktopWidth, desktopHeight})}) --print("bkgnd: ", bkgnd, err) --WMSetWallpaper(bkgnd) WMSetWallpaper(liner) local function startup() spawn(framestatapp, {frame = {x=0, y=40, width=desktopWidth, height=40}}) spawn(spiroapp,{frame = {x=100, y=100, width=640, height=480}}) spawn(keyboardapp, {frame = {x= 280, y = 600, width=640, height=360}}) end winman {width = desktopWidth, height=desktopHeight, startup = startup, frameRate=30}
-- add / change settings in here too aliveai.team_fight=true --attacking members from other teams aliveai.set_bones=true --set bones on death aliveai.constant_node_testing=false -- constantly checks if bots can use nodes / vehicles, usefull for test vehilces aliveai.check_spawn_space=true -- e.g.g check if the bot spawns in air, and not in the ground aliveai.enable_build=true -- makes bots can build aliveai.status=false -- show bot status/dev mode (using more cpy) /aliveai status=true /aliveai status=false aliveai.tools=0 -- hide bot tools aliveai.get_everything_to_build_chance=50 -- get everything bots need to build chance aliveai.get_random_stuff_chance=50 -- get random stuff on spawn (npc only) aliveai.max_delay=100 -- max bot delay/lag aliveai.max_new_bots=10 -- max spawning new bots, will be called old if they has been inactive aliveai.lifetimer=60 -- remove unbehavior none nps aliveai.default_team="Sam" furnishings= {"default:torch","default:chest","default:furnace","default:chest_locked","default:sign_wall_wood","default:sign_wall_steel","vessels:steel_bottle","vessels:drinking_glass","vessels:glass_bottle","aliveai:bed","aliveai:bed_blue","aliveai:chair"} aliveai.windows= {"default:glass","default:glass"} aliveai.ladders= {"default:ladder_wood","default:ladder_steel"} aliveai.beds= {"aliveai:bed","aliveai:bed_blue","beds:bed","beds:fancy_bed"} aliveai.tools_handler["default"]={ -- see extras.lua for use try_to_craft=true, use=false, tools={"pick_wood","pick_stone","steel_steel","pick_mese","pick_diamond","sword_steel","sword_mese","sword_diamond"}, } aliveai.tools_handler["aliveai"]={ try_to_craft=true, use=false, tools={"cudgel"}, } aliveai.nodes_handler={ -- dig, mesecon_on, mesecon_off, punch, function ["default:apple"]="dig",["aliveai_ants:antbase"]="dig",["tnt:tnt"]="dig",["tnt:tnt_burning"]="dig",["fire:basic_flame"]="dig", } minetest.register_craft({ -- right click to see output = "aliveai:protector", recipe = { {"default:steel_ingot"}, {"default:bronzeblock"}, {"default:steel_ingot"}, } }) minetest.register_craft({ --punch bot from another team to become their member output = "aliveai:team_gift", recipe = { {"","default:bronze_ingot",""}, {"default:mese_crystal","default:diamond","default:steel_ingot"}, {"","default:gold_ingot",""}, } }) minetest.register_craft({ --give to a laying bot output = "aliveai:relive 6", recipe = { {"default:apple","default:iron_lump","farming:bread"}, {"vessels:glass_bottle","vessels:glass_bottle","vessels:glass_bottle"}, {"vessels:glass_bottle","vessels:glass_bottle","vessels:glass_bottle"}, } }) minetest.register_craft({ --give to a laying bot output = "aliveai:hypnotics 6", recipe = { {"default:apple","default:tin_lump","farming:bread"}, {"vessels:glass_bottle","vessels:glass_bottle","vessels:glass_bottle"}, {"vessels:glass_bottle","vessels:glass_bottle","vessels:glass_bottle"}, } }) minetest.register_craft({ --punch bot from another team to become their member output = "aliveai:cudgel", recipe = { {"","default:stick"}, {"","default:stick"}, } }) minetest.register_craft({ type = "fuel", recipe = "aliveai:cudgel", burntime = 4, }) minetest.register_craft({ output = "aliveai:bed", recipe = { {"wool:red","wool:red","wool:red"}, {"group:wood","group:wood","group:wood"}, } }) minetest.register_craft({ output = "aliveai:bed_blue", recipe = { {"wool:blue","wool:blue","wool:blue"}, {"group:wood","group:wood","group:wood"}, } }) minetest.register_craft({ output = "aliveai:chair", recipe = {{"group:stick","",""}, {"group:wood","",""}, {"group:stick","",""}, } }) minetest.register_craft({ type = "fuel", recipe = "aliveai:bed", burntime = 10, }) minetest.register_craft({ type = "fuel", recipe = "aliveai:bed_blue", burntime = 10, }) minetest.register_craft({ type = "fuel", recipe = "aliveai:chair", burntime = 5, }) minetest.register_craft({ type = "fuel", recipe = "aliveai_aliens:ozer_sword", burntime = 10, }) minetest.register_craft({ type = "fuel", recipe = "aliveai_aliens:alien_nrifle", burntime = 10, }) minetest.register_craft({ type = "fuel", recipe = "aliveai_aliens:alien_rifle", burntime = 10, }) minetest.register_craft({ type = "fuel", recipe = "aliveai_aliens:alien_homing_rifle", burntime = 10, }) minetest.register_craft({ type = "fuel", recipe = "aliveai_aliens:vexcazer", burntime = 10, }) minetest.register_craft({ type = "fuel", recipe = "aliveai_threats:mind_manipulator", burntime = 10, }) aliveai.make_door({ name="wood", description = "Wooden door", texture="default_wood.png", material="default:wood", craft={ {"default:wood","",""}, {"default:wood","",""}, {"default:wood","",""} } }) aliveai.make_door({ name="acacia", description = "Wooden acacia door", texture="default_acacia_wood.png", material="default:acacia_wood", craft={ {"default:acacia_wood","",""}, {"default:acacia_wood","",""}, {"default:acacia_wood","",""} } }) aliveai.make_door({ name="jungle", description = "Wooden jungle door", texture="default_junglewood.png", material="default:junglewood", craft={ {"default:junglewood","",""}, {"default:junglewood","",""}, {"default:junglewood","",""} } }) aliveai.make_door({ name="aspen", description = "Wooden aspen door", texture="default_aspen_wood.png", material="default:aspen_wood", craft={ {"default:aspen_wood","",""}, {"default:aspen_wood","",""}, {"default:aspen_wood","",""} } }) aliveai.make_door({ name="pine", description = "Wooden pine door", texture="default_pine_wood.png", material="default:pine_wood", craft={ {"default:pine_wood","",""}, {"default:pine_wood","",""}, {"default:pine_wood","",""} } }) aliveai.make_door({ name="glass", description = "Glass door", texture="default_glass.png", material="default:glass", craft={ {"default:glass","",""}, {"default:glass","",""}, {"default:glass","",""} } }) aliveai.make_door({ name="ice", description = "Ice door", texture="default_ice.png", material="default:ice", craft={ {"default:ice","",""}, {"default:ice","",""}, {"default:ice","",""} } }) aliveai.make_door({ name="steel", description = "Steel door", texture="default_steel_block.png", material="default:steelblock", craft={ {"default:steelblock","",""}, {"default:steelblock","",""}, {"default:steelblock","",""} } }) if minetest.get_modpath("kpgmobs") then aliveai.nodes_handler["default:grass_1"]={func=aliveai.drive_vehicle,item="kpgmobs:horseh1",pos={x=0,y=20,z=0}} aliveai.nodes_handler["default:grass_2"]={func=aliveai.drive_vehicle,item="kpgmobs:horsearah1",pos={x=0,y=20,z=0}} aliveai.nodes_handler["default:grass_3"]={func=aliveai.drive_vehicle,item="kpgmobs:horsepegh1",pos={x=0,y=20,z=0}} end
---@class CS.UnityEngine.BuoyancyEffector2D : CS.UnityEngine.Effector2D ---@field public surfaceLevel number ---@field public density number ---@field public linearDrag number ---@field public angularDrag number ---@field public flowAngle number ---@field public flowMagnitude number ---@field public flowVariation number ---@type CS.UnityEngine.BuoyancyEffector2D CS.UnityEngine.BuoyancyEffector2D = { } ---@return CS.UnityEngine.BuoyancyEffector2D function CS.UnityEngine.BuoyancyEffector2D.New() end return CS.UnityEngine.BuoyancyEffector2D
require ('prototypes.animations.travel-worm') local travel_worm_sounds = require('prototypes.entity.travel-worm-sounds') local movement_triggers = require('__base__.prototypes.entity.movement-triggers') local hit_effects = require ('__base__.prototypes.entity.hit-effects') local sounds = require('__base__.prototypes.entity.sounds') local tank_shift_y = 6 function travel_worm(tier) return { type = 'car', name = 'nm-travel-worm-'..tier, icon = '__nauvis-melange__/graphics/icons/'..tier..'-travel-worm.png', icon_size = 64, icon_mipmaps = 4, flags = {'placeable-neutral', 'player-creation', 'placeable-off-grid', 'not-flammable'}, minable = {mining_time = 0.4, result = 'nm-travel-worm-'..tier}, mined_sound = travel_worm_sounds.mined, max_health = health_worm(tier), corpse = ''..tier..'-worm-corpse', dying_explosion = ''..tier..'-worm-die', alert_icon_shift = util.by_pixel(0, -13), energy_per_hit_point = 1, crash_trigger = crash_trigger(), resistances = resistances_worm(tier), collision_box = collision_box_worm(tier), selection_box = collision_box_worm(tier), damaged_trigger_effect = hit_effects.entity(), effectivity = 0.5, braking_power = '400kW', consumption = '50kW', terrain_friction_modifier = 0.2, friction = 0.002, render_layer = 'object', animation = worm_start_attack_animation(scale_worm(tier), tint_worm(tier)), energy_source = { type = 'void' }, working_sound = { sound = travel_worm_sounds.working, activate_sound = travel_worm_sounds.starting, --deactivate_sound = travel_worm_sounds.stopping, idle_sound = travel_worm_sounds.idling, match_speed_to_activity = true }, stop_trigger_speed = 0.15, stop_trigger = { { type = 'play-sound', sound = travel_worm_sounds.stopping } }, sound_minimum_speed = 0.25, vehicle_impact_sound = travel_worm_sounds.impact, open_sound = travel_worm_sounds.slimy, close_sound = travel_worm_sounds.slimy, rotation_speed = 0.025, weight = 700, turret_rotation_speed = 0, turret_return_timeout = 0, --guns = { 'travel-worm-gun' }, guns = {}, inventory_size = 0, } end function worm_change_pos_animation(tier, direction) local playback = {submerge = 'backward', emerge = 'forward'} return { type = 'corpse', name = 'nm-'..direction..'-animation-'..tier, icon = '__nauvis-melange__/graphics/icons/'..tier..'-travel-worm.png', icon_size = 64, icon_mipmaps = 4, time_before_removed = 60 * 8, dying_speed = 1.0, time_before_shading_off = 60 * 0, animation = worm_preparing_animation(scale_worm[tier], tint_worm[tier], playback[direction]) } end data:extend({ travel_worm('small'), travel_worm('medium'), travel_worm('big'), travel_worm('behemoth'), { type = 'car', name = 'nm-d-u-n-e', -- Deison United - Newton Extractor icon = '__base__/graphics/icons/tank.png', icon_size = 64, icon_mipmaps = 4, flags = {'placeable-neutral', 'player-creation', 'placeable-off-grid', 'not-flammable'}, minable = {mining_time = 0.5, result = 'tank'}, mined_sound = {filename = '__core__/sound/deconstruct-large.ogg',volume = 0.8}, max_health = 2000, corpse = 'tank-remnants', dying_explosion = 'tank-explosion', alert_icon_shift = util.by_pixel(0, -13), immune_to_tree_impacts = true, immune_to_rock_impacts = true, energy_per_hit_point = 0.5, resistances = {}, collision_box = {{-0.9, -1.3}, {0.9, 1.3}}, selection_box = {{-0.9, -1.3}, {0.9, 1.3}}, damaged_trigger_effect = hit_effects.entity(), drawing_box = {{-1.8, -1.8}, {1.8, 1.5}}, effectivity = 0.9, braking_power = '800kW', burner = { fuel_category = 'chemical', effectivity = 1, fuel_inventory_size = 2, smoke = { { name = 'tank-smoke', deviation = {0.25, 0.25}, frequency = 50, position = {0, 1.5}, starting_frame = 0, starting_frame_deviation = 60 } } }, consumption = '600kW', terrain_friction_modifier = 0.2, friction = 0.002, light = { { type = 'oriented', minimum_darkness = 0.3, picture = { filename = '__core__/graphics/light-cone.png', priority = 'extra-high', flags = { 'light' }, scale = 2, width = 200, height = 200 }, shift = {-0.1, -14 + tank_shift_y / 32}, size = 2, intensity = 0.8, color = {r = 1.0, g = 1.0, b = 0.8}, source_orientation_offset = -0.02 }, { type = 'oriented', minimum_darkness = 0.3, picture = { filename = '__core__/graphics/light-cone.png', priority = 'extra-high', flags = { 'light' }, scale = 2, width = 200, height = 200 }, shift = {0.1, -14 + tank_shift_y / 32}, size = 2, intensity = 0.8, color = {r = 1.0, g = 1.0, b = 0.8}, source_orientation_offset = 0.02 } }, light_animation = { filename = '__base__/graphics/entity/tank/tank-light.png', priority = 'low', blend_mode = 'additive', draw_as_glow = true, width = 132, height = 108, line_length = 8, direction_count = 64, shift = util.by_pixel(-2, -18 + 6), repeat_count = 2, hr_version = { filename = '__base__/graphics/entity/tank/hr-tank-light.png', priority = 'low', blend_mode = 'additive', draw_as_glow = true, width = 260, height = 210, line_length = 8, direction_count = 64, scale = 0.5, shift = util.by_pixel(-1, -17 + 6), repeat_count = 2, } }, animation = { layers = { { priority = 'low', width = 136, height = 106, frame_count = 2, direction_count = 64, shift = util.by_pixel(0, -16 + tank_shift_y), animation_speed = 8, max_advance = 1, stripes = { { filename = '__base__/graphics/entity/tank/tank-base-1.png', width_in_frames = 2, height_in_frames = 16 }, { filename = '__base__/graphics/entity/tank/tank-base-2.png', width_in_frames = 2, height_in_frames = 16 }, { filename = '__base__/graphics/entity/tank/tank-base-3.png', width_in_frames = 2, height_in_frames = 16 }, { filename = '__base__/graphics/entity/tank/tank-base-4.png', width_in_frames = 2, height_in_frames = 16 } }, hr_version = { priority = 'low', width = 270, height = 212, frame_count = 2, direction_count = 64, shift = util.by_pixel(0, -16 + tank_shift_y), animation_speed = 8, max_advance = 1, stripes = { { filename = '__base__/graphics/entity/tank/hr-tank-base-1.png', width_in_frames = 2, height_in_frames = 16 }, { filename = '__base__/graphics/entity/tank/hr-tank-base-2.png', width_in_frames = 2, height_in_frames = 16 }, { filename = '__base__/graphics/entity/tank/hr-tank-base-3.png', width_in_frames = 2, height_in_frames = 16 }, { filename = '__base__/graphics/entity/tank/hr-tank-base-4.png', width_in_frames = 2, height_in_frames = 16 } }, scale = 0.5 } }, { priority = 'low', width = 104, height = 83, frame_count = 2, apply_runtime_tint = true, direction_count = 64, shift = util.by_pixel(0, -27.5 + tank_shift_y), max_advance = 1, line_length = 2, stripes = util.multiplystripes(2, { { filename = '__base__/graphics/entity/tank/tank-base-mask-1.png', width_in_frames = 1, height_in_frames = 22 }, { filename = '__base__/graphics/entity/tank/tank-base-mask-2.png', width_in_frames = 1, height_in_frames = 22 }, { filename = '__base__/graphics/entity/tank/tank-base-mask-3.png', width_in_frames = 1, height_in_frames = 20 } }), hr_version = { priority = 'low', width = 208, height = 166, frame_count = 2, apply_runtime_tint = true, direction_count = 64, shift = util.by_pixel(0, -27.5 + tank_shift_y), max_advance = 1, line_length = 2, stripes = util.multiplystripes(2, { { filename = '__base__/graphics/entity/tank/hr-tank-base-mask-1.png', width_in_frames = 1, height_in_frames = 22 }, { filename = '__base__/graphics/entity/tank/hr-tank-base-mask-2.png', width_in_frames = 1, height_in_frames = 22 }, { filename = '__base__/graphics/entity/tank/hr-tank-base-mask-3.png', width_in_frames = 1, height_in_frames = 20 } }), scale = 0.5 } }, { priority = 'low', width = 151, height = 98, frame_count = 2, draw_as_shadow = true, direction_count = 64, shift = util.by_pixel(22.5, 1 + tank_shift_y), max_advance = 1, stripes = util.multiplystripes(2, { { filename = '__base__/graphics/entity/tank/tank-base-shadow-1.png', width_in_frames = 1, height_in_frames = 16 }, { filename = '__base__/graphics/entity/tank/tank-base-shadow-2.png', width_in_frames = 1, height_in_frames = 16 }, { filename = '__base__/graphics/entity/tank/tank-base-shadow-3.png', width_in_frames = 1, height_in_frames = 16 }, { filename = '__base__/graphics/entity/tank/tank-base-shadow-4.png', width_in_frames = 1, height_in_frames = 16 } }), hr_version = { priority = 'low', width = 302, height = 194, frame_count = 2, draw_as_shadow = true, direction_count = 64, shift = util.by_pixel(22.5, 1 + tank_shift_y), max_advance = 1, stripes = util.multiplystripes(2, { { filename = '__base__/graphics/entity/tank/hr-tank-base-shadow-1.png', width_in_frames = 1, height_in_frames = 16 }, { filename = '__base__/graphics/entity/tank/hr-tank-base-shadow-2.png', width_in_frames = 1, height_in_frames = 16 }, { filename = '__base__/graphics/entity/tank/hr-tank-base-shadow-3.png', width_in_frames = 1, height_in_frames = 16 }, { filename = '__base__/graphics/entity/tank/hr-tank-base-shadow-4.png', width_in_frames = 1, height_in_frames = 16 } }), scale = 0.5 } } } }, turret_rotation_speed = 0, turret_return_timeout = 0, sound_no_fuel = { { filename = '__base__/sound/fight/tank-no-fuel-1.ogg', volume = 0.4 } }, sound_minimum_speed = 0.2, sound_scaling_ratio = 0.8, vehicle_impact_sound = sounds.generic_impact, working_sound = { sound = { filename = '__base__/sound/fight/tank-engine.ogg', volume = 0.37 }, activate_sound = { filename = '__base__/sound/fight/tank-engine-start.ogg', volume = 0.37 }, deactivate_sound = { filename = '__base__/sound/fight/tank-engine-stop.ogg', volume = 0.37 }, match_speed_to_activity = true }, stop_trigger_speed = 0.1, stop_trigger = { { type = 'play-sound', sound = { { filename = '__base__/sound/fight/tank-brakes.ogg', volume = 0.3 } } } }, open_sound = { filename = '__base__/sound/fight/tank-door-open.ogg', volume=0.48 }, close_sound = { filename = '__base__/sound/fight/tank-door-close.ogg', volume = 0.43 }, rotation_speed = 0.0035, tank_driving = true, weight = 20000, inventory_size = 80, track_particle_triggers = movement_triggers.tank, guns = {}, water_reflection = { pictures = { filename = '__base__/graphics/entity/car/car-reflection.png', priority = 'extra-high', width = 20, height = 24, shift = util.by_pixel(0, 35), variation_count = 1, scale = 5 * 1.2 }, rotate = true, orientation_to_variation = false } } })
id = 'V-38686' severity = 'medium' weight = 10.0 title = 'The systems local firewall must implement a deny-all, allow-by-exception policy for forwarded packets.' description = 'In "iptables" the default policy is applied only after all the applicable rules in the table are examined for a match. Setting the default policy to "DROP" implements proper design for a firewall, i.e., any packets which are not explicitly permitted should not be accepted.' fixtext = [=[To set the default policy to DROP (instead of ACCEPT) for the built-in FORWARD chain which processes packets that will be forwarded from one interface to another, add or correct the following line in "/etc/sysconfig/iptables": :FORWARD DROP [0:0]]=] checktext = [=[Run the following command to ensure the default "FORWARD" policy is "DROP": grep ":FORWARD" /etc/sysconfig/iptables The output must be the following: # grep ":FORWARD" /etc/sysconfig/iptables :FORWARD DROP [0:0] If it is not, this is a finding.]=] function test() end function fix() end
if not table.pack then function table.pack (...) return {n=select('#',...), ...} end end if not table.unpack then table.unpack = unpack end function memoize( fn ) local function fnKey( ... ) local key = "" local args = table.pack( ... ) for i = 1, args.n do key = key .. "[" .. tostring( args[ i ] ) .. "]" end return key end local object = { __call = function( targetTable, ... ) local key = fnKey( ... ) local values = targetTable.__memoized[ key ] if ( values == nil ) then values = table.pack( fn( ... ) ) targetTable.__memoized[ key ] = values end if ( values.n > 0 ) then return table.unpack( values ) end return nil end, __forget = function( self ) self.__memoized = {} end, __memoized = {}, __mode = "v", } return setmetatable( object, object ) end local function fn1(...) return ... end local m1 = memoize( fn1 ) local t = m1( 1, 2, 3 ) print( m1(1, 2, 3) )
local usingStroke = false; local usingFill = true; local function randomColor() local r = random(30,255) local g = random(30,255) local b = random(30,255) return color(r,g,b,0x7f) end function setup() background(0x80) end function draw() if not usingStroke then noStroke() else stroke(randomColor()) end if not usingFill then noFill() end for i=1,500 do local x = random(0,width-10) local y = random(0, height-10) local w = 20; local h = 20; if usingFill then local c = randomColor() fill(c) end rect(x,y, w,h) end end local T_S = string.byte("S") local T_F = string.byte("F") function keyTyped(event) --print("keyTyped: ", keyCode, T_S, T_F) if keyCode == T_S then usingStroke = not usingStroke end if keyCode == T_F then usingFill = not usingFill end end go()
-- Matter recipes for Krastorio2 if mods["Krastorio2"] then local util = require("data-util"); local matter = require("__Krastorio2__/lib/public/data-stages/matter-util") data:extend( { { type = "technology", name = "aluminum-matter-processing", icons = { { icon = util.k2assets().."/technologies/matter-coal.png", icon_size = 256, }, { icon = "__bzaluminum__/graphics/icons/aluminum-ore.png", icon_size = 64, scale = 1.4, } }, prerequisites = {"kr-matter-processing"}, unit = { count = 350, ingredients = { {"production-science-pack", 1}, {"utility-science-pack", 1}, {"matter-tech-card", 1} }, time = 45 } }, }) local flake_graphite_matter = { item_name = "aluminum-ore", minimum_conversion_quantity = 10, matter_value = 5, energy_required = 1, need_stabilizer = false, unlocked_by_technology = "aluminum-matter-processing" } matter.createMatterRecipe(flake_graphite_matter) local graphite_matter = { item_name = "alumina", minimum_conversion_quantity = 10, matter_value = 7.5, energy_required = 2, only_deconversion = true, need_stabilizer = true, unlocked_by_technology = "aluminum-matter-processing" } matter.createMatterRecipe(graphite_matter) local graphite_matter = { item_name = "aluminum-plate", minimum_conversion_quantity = 10, matter_value = 10, energy_required = 3, only_deconversion = true, need_stabilizer = true, unlocked_by_technology = "aluminum-matter-processing" } matter.createMatterRecipe(graphite_matter) end
local vigenere = require("vigenere") local secretKey = "iLoveLua" local text = "Hello, World!" local encrypted = vigenere.encrypt(text, secretKey) local decrypted = vigenere.decrypt(encrypted, secretKey) print("Original Text: " .. text) print("Encrypted Text: " .. encrypted) print("Decrypted Text: " .. decrypted) assert(text == decrypted) do local key = "testkey1234567890" local text = "Encrypted Text" assert(vigenere.decrypt(vigenere.encrypt(text, key), key) == text) end do local key = "abcdefghijklmnopqrstuvwxyz" local text = "abcdefghijklmnopqrstuvwxyz" assert(vigenere.decrypt(vigenere.encrypt(text, key), key) == text) end print("Tests Passed")
local utils = require('/usr/local/openresty/nginx/lua/utils') local json_decode = utils.json_decode local limit_req = require "resty.limit.req" local lim, err = limit_req.new("mylimit", 5000, 2000) if err ~= nil then ngx.log(ngx.ERR,"limit_req.new fail: ", err) end local balance_table = require("/usr/local/openresty/nginx/lua/chainnode/config_rules"); local data = ngx.req.get_body_data() local t = json_decode(data) -- 如果请求没有传值则报错 416 且打印出 error 日志 if not t then ngx.log(ngx.ERR, "request no values") return ngx.exit(416) end -- 如果解析请求后是数组类型则使用泛型方式进行取值 if t[1] ~= nil then for i, w in ipairs(t) do local method = w.method local host = balance_table[method] ngx.var.balance_host = host ngx.var.json_method = method if not host then ngx.log(ngx.ERR, "balance host not found", host ) return ngx.exit(500) end local delay, err = lim:incoming(method, true) if not delay then if err == "rejected" then ngx.log(ngx.ERR, "regulation array-method too many requests: ", err) return ngx.exit(429) end ngx.log(ngx.ERR, "regulation array-method not delay but not rejected: ", err) return ngx.exit(500) end end -- 如果解析请求后是表类型则直接取值 elseif t ~= nil then local method = t.method local host = balance_table[method] ngx.var.balance_host = host ngx.var.json_method = method if not host then ngx.log(ngx.ERR, "balance host not found", host ) return ngx.exit(500) end local delay, err = lim:incoming(method, true) if not delay then if err == "rejected" then ngx.log(ngx.ERR, "regulation json-method too many requests: ", err) return ngx.exit(429) end ngx.log(ngx.ERR, "regulation json-method not delay but not rejected: ", err) return ngx.exit(500) end -- 暂时走不到这一步,需要看明确需求 else local delay, err = lim:incoming(ngx.var.binary_remote_addr, true) if not delay then if err == "rejected" then ngx.log(ngx.ERR, "remote-ip too many requests: ", err) return ngx.exit(429) end ngx.log(ngx.ERR, "remote-ip not delay but not rejected: ", err) return ngx.exit(500) end end
t={} t[10001] = { hp = 100, name = "a", def = 5, atk = 10 } t[10002] = { hp = 100, name = "b", def = 6, atk = 11 } t[10003] = { hp = 100, name = "c", def = 7, atk = 12 } t[10004] = { hp = 100, name = "d", def = 8, atk = 13 } t[10005] = { hp = 100, name = "e", def = 9, atk = 14 } t[10006] = { hp = 100, name = "f", def = 10, atk = 15 } t[10007] = { hp = 100, name = "g", def = 11, atk = 16 } t[10008] = { hp = 100, name = "h", def = 12, atk = 17 } t[10009] = { hp = 100, name = "i", def = 13, atk = 18 }
local Modules = script.Parent.Parent.Parent local Roact = require(Modules.Roact) local RoactRodux = require(Modules.RoactRodux) local Input = require(Modules.Plugin.Components.Input) local Data = require(Modules.Plugin.Components.Data) local Info = require(Modules.Plugin.Components.Info) local PickerMenu = require(Modules.Plugin.Components.PickerMenu) local function MainFrame(props) return Roact.createElement("Frame", { Size = UDim2.new(1, 0, 1, 0), Active = true, BackgroundColor3 = Color3.fromRGB(255, 255, 255), BorderSizePixel = 0, }, { InputFrame = Roact.createElement("Frame", { Position = UDim2.new(0, 0, 0, 0), Size = UDim2.new(1, 0, 0, 50), BackgroundTransparency = 1.0, ZIndex = 2, }, { Input = Roact.createElement(Input, { Position = UDim2.new(0, 7, 0, 7), Size = UDim2.new(1, -30, 1, -14), }), Picker = Roact.createElement(PickerMenu, { Position = UDim2.new(1, -6, 0, 6), AnchorPoint = Vector2.new(1, 0), }), }), Body = Roact.createElement("Frame", { Size = UDim2.new(1, 0, 1, -50), Position = UDim2.new(0, 0, 0, 50), BackgroundTransparency = 1.0, }, { UIListLayout = Roact.createElement("UIListLayout", { SortOrder = Enum.SortOrder.LayoutOrder, FillDirection = Enum.FillDirection.Horizontal, }), Data = Roact.createElement(Data, { Size = props.selected and UDim2.new(1, -250, 1, 0) or UDim2.new(1, 0, 1, 0), }), Info = Roact.createElement(Info, { Size = props.selected and UDim2.new(0, 250, 1, 0) or UDim2.new(0, 0, 0, 0), }), }) }) end local function mapStateToProps(state) return { selected = state.selected, } end MainFrame = RoactRodux.connect(mapStateToProps)(MainFrame) return MainFrame
-- hiscore.lua -- by borgar@borgar.net, CC0 license -- -- This uses MAME's built-in Lua scripting to implement -- high-score saving with hiscore.dat infom just as older -- builds did in the past. -- local exports = { name = 'hiscore', version = '1.0.1', description = 'Hiscore', license = 'CC0', author = { name = 'borgar@borgar.net' } } local hiscore = exports local hiscore_plugin_path = "" function hiscore.set_folder(path) hiscore_plugin_path = path end function hiscore.startplugin() local function get_data_path() return emu.subst_env(manager.machine.options.entries.homepath:value():match('([^;]+)')) .. '/hiscore' end -- configuration local config_read = false local timed_save = true -- read configuration file from data directory local function read_config() if config_read then return true end local filename = get_data_path() .. '/plugin.cfg' local file = io.open(filename, 'r') if file then local json = require('json') local parsed_settings = json.parse(file:read('a')) file:close() if parsed_settings then if parsed_settings.only_save_at_exit and (parsed_settings.only_save_at_exit ~= 0) then timed_save = false end -- TODO: other settings? maybe path overrides for hiscore.dat or the hiscore data? config_read = true return true else emu.print_error(string.format('Error loading hiscore plugin settings: error parsing file "%s" as JSON', filename)) end end return false end -- save configuration file local function save_config() local path = get_data_path() local attr = lfs.attributes(path) if not attr then lfs.mkdir(path) elseif attr.mode ~= 'directory' then emu.print_error(string.format('Error saving hiscore plugin settings: "%s" is not a directory', path)) return end local settings = { only_save_at_exit = not timed_save } -- TODO: other settings? local filename = path .. '/plugin.cfg' local json = require('json') local data = json.stringify(settings, { indent = true }) local file = io.open(filename, 'w') if not file then emu.print_error(string.format('Error saving hiscore plugin settings: error opening file "%s" for writing', filename)) return end file:write(data) file:close() end -- build menu local function populate_menu() local items = { } local setting = timed_save and _p('plugin-hiscore', 'When updated') or _p('plugin-hiscore', 'On exit') table.insert(items, { _p('plugin-hiscore', 'Hiscore Support Options'), '', 'off' }) table.insert(items, { '---', '', '' }) table.insert(items, { _p('plugin-hiscore', 'Save scores'), setting, timed_save and 'l' or 'r' }) return items end -- handle menu events local function handle_menu(index, event) if event == 'left' then timed_save = false return true elseif event == 'right' then timed_save = true return true end return false end local hiscoredata_path = "hiscore.dat"; local current_checksum = 0; local default_checksum = 0; local scores_have_been_read = false; local mem_check_passed = false; local found_hiscore_entry = false; local delaytime = 0; local function parse_table ( dsting ) local _table = {} for line in string.gmatch(dsting, '([^\n]+)') do local delay = line:match('^@delay=([.%d]*)') if delay and #delay > 0 then delaytime = emu.time() + tonumber(delay) else local cpu, mem; local cputag, space, offs, len, chk_st, chk_ed, fill = string.match(line, '^@([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),?(%x?%x?)'); cpu = manager.machine.devices[cputag]; if not cpu then error(cputag .. " device not found") end local rgnname, rgntype = space:match("([^/]*)/?([^/]*)") if rgntype == "share" then mem = manager.machine.memory.shares[rgnname] else mem = cpu.spaces[space] end if not mem then error(space .. " space not found") end _table[ #_table + 1 ] = { mem = mem, addr = tonumber(offs, 16), size = tonumber(len, 16), c_start = tonumber(chk_st, 16), c_end = tonumber(chk_ed, 16), fill = tonumber(fill, 16) }; end end return _table; end local function read_hiscore_dat () local file = io.open( hiscoredata_path, "r" ); local rm_match; if not file then file = io.open( hiscore_plugin_path .. "/hiscore.dat", "r" ); end if emu.softname() ~= "" then local soft = emu.softname():match("([^:]*)$") rm_match = '^' .. emu.romname() .. ',' .. soft .. ':'; else rm_match = '^' .. emu.romname() .. ':'; end local cluster = ""; local current_is_match = false; if file then repeat line = file:read("*l"); if line then -- remove comments line = line:gsub( '[ \t\r\n]*;.+$', '' ); -- handle lines if string.find(line, '^@') then -- data line if current_is_match then cluster = cluster .. "\n" .. line; end elseif string.find(line, rm_match) then --- match this game current_is_match = true; elseif string.find(line, '^[a-z0-9_]+:') then --- some game if current_is_match and string.len(cluster) > 0 then break; -- we're done end else --- empty line or garbage -- noop end end until not line; file:close(); end return cluster; end local function check_mem ( posdata ) if #posdata < 1 then return false; end for ri,row in ipairs(posdata) do -- must pass mem check if row["c_start"] ~= row["mem"]:read_u8(row["addr"]) then return false; end if row["c_end"] ~= row["mem"]:read_u8(row["addr"]+row["size"]-1) then return false; end end return true; end local function get_file_name() local r; if emu.softname() ~= "" then local soft = emu.softname():match("([^:]*)$") r = get_data_path() .. '/' .. emu.romname() .. "_" .. soft .. ".hi"; else r = get_data_path() .. '/' .. emu.romname() .. ".hi"; end return r; end local function write_scores ( posdata ) emu.print_verbose("hiscore: write_scores") local output = io.open(get_file_name(), "wb"); if not output then -- attempt to create the directory, and try again lfs.mkdir(get_data_path()); output = io.open(get_file_name(), "wb"); end emu.print_verbose("hiscore: write_scores output") if output then for ri,row in ipairs(posdata) do t = {} for i=0,row["size"]-1 do t[i+1] = row["mem"]:read_u8(row["addr"] + i) end output:write(string.char(table.unpack(t))); end output:close(); end emu.print_verbose("hiscore: write_scores end") end local function read_scores ( posdata ) local input = io.open(get_file_name(), "rb"); if input then for ri,row in ipairs(posdata) do local str = input:read(row["size"]); for i=0,row["size"]-1 do local b = str:sub(i+1,i+1):byte(); row["mem"]:write_u8( row["addr"] + i, b ); end end input:close(); return true; end return false; end local function check_scores ( posdata ) local r = 0; for ri,row in ipairs(posdata) do for i=0,row["size"]-1 do r = r + row["mem"]:read_u8( row["addr"] + i ); end end return r; end local function init () if not scores_have_been_read then if (delaytime <= emu.time()) and check_mem( positions ) then default_checksum = check_scores( positions ); if read_scores( positions ) then emu.print_verbose( "hiscore: scores read OK" ); else -- likely there simply isn't a .hi file around yet emu.print_verbose( "hiscore: scores read FAIL" ); end scores_have_been_read = true; current_checksum = check_scores( positions ); mem_check_passed = true; else -- memory check can fail while the game is still warming up -- TODO: only allow it to fail N many times end end end local last_write_time = -10; local function tick () -- set up scores if they have been init(); -- only allow save check to run when if mem_check_passed and timed_save then -- The reason for this complicated mess is that -- MAME does expose a hook for "exit". Once it does, -- this should obviously just be done when the emulator -- shuts down (or reboots). local checksum = check_scores( positions ); if checksum ~= current_checksum and checksum ~= default_checksum then -- 5 sec grace time so we don't clobber io and cause -- latency. This would be bad as it would only ever happen -- to players currently reaching a new highscore if emu.time() > last_write_time + 5 then write_scores( positions ); current_checksum = checksum; last_write_time = emu.time(); -- emu.print_verbose( "SAVE SCORES EVENT!", last_write_time ); end end end end local function reset() -- the notifier will still be attached even if the running game has no hiscore.dat entry if mem_check_passed and found_hiscore_entry then local checksum = check_scores(positions) if checksum ~= current_checksum and checksum ~= default_checksum then write_scores(positions) end end found_hiscore_entry = false mem_check_passed = false scores_have_been_read = false; end emu.register_start(function() found_hiscore_entry = false mem_check_passed = false scores_have_been_read = false; last_write_time = -10 emu.print_verbose("Starting " .. emu.gamename()) read_config(); local dat = read_hiscore_dat() if dat and dat ~= "" then emu.print_verbose( "hiscore: found hiscore.dat entry for " .. emu.romname() ); res, positions = pcall(parse_table, dat); if not res then emu.print_error("hiscore: hiscore.dat parse error " .. positions); return; end for i, row in pairs(positions) do if row.fill then for i=0,row["size"]-1 do row["mem"]:write_u8(row["addr"] + i, row.fill) end end end found_hiscore_entry = true end end) emu.register_frame(function() if found_hiscore_entry then tick() end end) emu.register_stop(function() reset() save_config() end) emu.register_prestart(function() reset() end) emu.register_menu(handle_menu, populate_menu, _p('plugin-hiscore', 'Hiscore Support')) end return exports
require "socket" math.randomseed(socket.gettime()*1000) math.random(); math.random(); math.random() random_string = "adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00adsadasd00" local function get_user() local id = math.random(0, 500) local user_name = "Cornell_" .. tostring(id) local pass_word = "" for i = 0, 9, 1 do pass_word = pass_word .. tostring(id) end return user_name, pass_word end local function user_login() local user_name, password = get_user() local method = "GET" local path = "http://localhost:5000/user?username=" .. user_name .. "&password=" .. password local headers = {} -- headers["Content-Type"] = "application/x-www-form-urlencoded" return wrk.format(method, path, headers, random_string) end request = function() return user_login() end
module 'mock_edit' -------------------------------------------------------------------- EditorEntity = mock.EditorEntity
--[[ Name: "sh_citizen.lua". Product: "nexus". --]] local CLASS = {}; CLASS.color = Color(150, 100, 50, 255); CLASS.factions = {FACTION_CITIZEN}; CLASS.isDefault = true; CLASS.description = "A regular Citizen living in the city."; CLASS_CITIZEN = nexus.class.Register(CLASS, "Citizen");
local condition = Condition(CONDITION_DROWN) condition:setParameter(CONDITION_PARAM_DELAYED, true) condition:addDamage(20, 5000, -20) local combat = Combat() combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_DROWNDAMAGE) combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE) combat:setArea(createCombatArea(AREA_SQUAREWAVE7)) combat:setCondition(condition) function onCastSpell(creature, variant) return combat:execute(creature, variant) end
XYZ_HITMAN = {} XYZ_HITMAN.Config = {} XYZ_HITMAN.Core = {} XYZ_HITMAN.Core.ActiveHits = {} XYZ_HITMAN.Core.ClaimedHits = {} XYZ_HITMAN.Phones = {} print("Loading Hitman System") local path = "xyz_hitman/" if SERVER then local files, folders = file.Find(path .. "*", "LUA") for _, folder in SortedPairs(folders, true) do print("Loading folder:", folder) for b, File in SortedPairs(file.Find(path .. folder .. "/sh_*.lua", "LUA"), true) do print("Loading file:", File) AddCSLuaFile(path .. folder .. "/" .. File) include(path .. folder .. "/" .. File) end for b, File in SortedPairs(file.Find(path .. folder .. "/sv_*.lua", "LUA"), true) do print("Loading file:", File) include(path .. folder .. "/" .. File) end for b, File in SortedPairs(file.Find(path .. folder .. "/cl_*.lua", "LUA"), true) do print("Loading file:", File) AddCSLuaFile(path .. folder .. "/" .. File) end end end if CLIENT then local files, folders = file.Find(path .. "*", "LUA") for _, folder in SortedPairs(folders, true) do print("Loading folder:", folder) for b, File in SortedPairs(file.Find(path .. folder .. "/sh_*.lua", "LUA"), true) do print("Loading file:", File) include(path .. folder .. "/" .. File) end for b, File in SortedPairs(file.Find(path .. folder .. "/cl_*.lua", "LUA"), true) do print("Loading file:", File) include(path .. folder .. "/" .. File) end end end print("Loaded Hitman System")
RenderModel = function(model , pos , angle , color) for n = 1 , #model do if #model[n] == 3 then Render:FillTriangle( angle * model[n][1] + pos , angle * model[n][2] + pos , angle * model[n][3] + pos , color ) elseif #model[n] == 2 then Render:DrawLine( angle * model[n][1] + pos , angle * model[n][2] + pos , color ) end end end Models = {} -- Checkpoint pointer arrow. local arrowWidth = 0.18 local arrowLength = 0.58 local arrowHead = 0.70 local arrowHeadWidthMult = 3 local arrowHeight = 0.0375 do local X = arrowWidth local Y = arrowHeight local Z = arrowLength Models.arrowTriangles = { -- Bottom { Vector3(-X , -Y , Z) , Vector3(X , -Y , Z) , Vector3(X , -Y , -Z) } , { Vector3(-X , -Y , Z) , Vector3(X , -Y , -Z) , Vector3(-X , -Y , -Z) } , { Vector3(-X*arrowHeadWidthMult , -Y , -Z) , Vector3(X*arrowHeadWidthMult , -Y , -Z) , Vector3(0 , -Y , -Z - arrowHead) } , -- Top { Vector3(-X , Y , Z) , Vector3(X , Y , Z) , Vector3(X , Y , -Z) } , { Vector3(-X , Y , Z) , Vector3(X , Y , -Z) , Vector3(-X , Y , -Z) } , { Vector3(-X*arrowHeadWidthMult , Y , -Z) , Vector3(X*arrowHeadWidthMult , Y , -Z) , Vector3(0 , Y , -Z - arrowHead) } , -- Back { Vector3(-X , -Y , Z) , Vector3(X , -Y , Z) , Vector3(X , Y , Z) } , { Vector3(-X , -Y , Z) , Vector3(X , Y , Z) , Vector3(-X , Y , Z) } , -- Front { Vector3(-X*arrowHeadWidthMult , -Y , -Z) , Vector3(X*arrowHeadWidthMult , -Y , -Z) , Vector3(X*arrowHeadWidthMult , Y , -Z) } , { Vector3(-X*arrowHeadWidthMult , -Y , -Z) , Vector3(X*arrowHeadWidthMult , Y , -Z) , Vector3(-X*arrowHeadWidthMult , Y , -Z) } , -- Left { Vector3(-X , -Y , Z) , Vector3(-X , -Y , -Z) , Vector3(-X , Y , -Z) } , { Vector3(-X , -Y , Z) , Vector3(-X , Y , -Z) , Vector3(-X , Y , Z) } , -- Right { Vector3(X , -Y , Z) , Vector3(X , -Y , -Z) , Vector3(X , Y , -Z) } , { Vector3(X , -Y , Z) , Vector3(X , Y , -Z) , Vector3(X , Y , Z) } , -- Front left { Vector3(-X*arrowHeadWidthMult , -Y , -Z) , Vector3(-X*arrowHeadWidthMult , Y , -Z) , Vector3(0 , Y , -Z - arrowHead) } , { Vector3(-X*arrowHeadWidthMult , -Y , -Z) , Vector3(0 , -Y , -Z - arrowHead) , Vector3(0 , Y , -Z - arrowHead) } , -- Front right { Vector3(X*arrowHeadWidthMult , -Y , -Z) , Vector3(X*arrowHeadWidthMult , Y , -Z) , Vector3(0 , Y , -Z - arrowHead) } , { Vector3(X*arrowHeadWidthMult , -Y , -Z) , Vector3(0 , -Y , -Z - arrowHead) , Vector3(0 , Y , -Z - arrowHead) } } end -- Flat version. Just in case the solid version is horribly slow. do local X = arrowWidth local Z = arrowLength Models.arrowTrianglesFast = { { Vector3(-X , 0 , Z) , Vector3(X , 0 , Z) , Vector3(X , 0 , -Z) } , { Vector3(-X , 0 , Z) , Vector3(X , 0 , -Z) , Vector3(-X , 0 , -Z) } , { Vector3(-X*arrowHeadWidthMult , 0 , -Z) , Vector3(X*arrowHeadWidthMult , 0 , -Z) , Vector3(0 , 0 , -Z - arrowHead) } , } end -- Checkpoint do local Y = 0.75 local Z = 1.35 local arrowHead = 3.75 Models.nextCPArrowTriangles = { { Vector3(0 , -Y , Z + arrowHead*0.25) , Vector3(0 , Y , Z + arrowHead*0.25) , Vector3(0 , Y , -Z) } , { Vector3(0 , -Y , Z + arrowHead*0.25) , Vector3(0 , Y , -Z) , Vector3(0 , -Y , -Z) } , { Vector3(0 , -Y*arrowHeadWidthMult , -Z) , Vector3(0 , Y*arrowHeadWidthMult , -Z) , Vector3(0 , 0 , -Z - arrowHead*0.5) } , } end ---------------------------------------------------------------------------------------------------- -- Course editor ---------------------------------------------------------------------------------------------------- -- Object spawner gizmo, used for the course editor. do local radius = 1 local height = 3.5 local numSegments = 7 local segmentAngle = (math.pi*2) / numSegments Models.objectSpawnerGizmo = {} for n = 0 , numSegments - 1 do local angle1 = segmentAngle * n local angle2 = segmentAngle * (n + 1) table.insert( Models.objectSpawnerGizmo , { Vector3(0 , 0 , 0) , Vector3(math.cos(angle1) * radius , height , math.sin(angle1) * radius) , Vector3(math.cos(angle2) * radius , height , math.sin(angle2) * radius) } ) end end -- Used for the course editor's checkpoint spawner gizmo. do local radius = 9.5 local numSegments = 13 local segmentAngle = (math.pi*2) / numSegments Models.checkpoint = {} for n = 0 , numSegments - 1 do local angle1 = segmentAngle * n local angle2 = segmentAngle * (n + 1) local angleMid = math.lerp(angle1 , angle2 , 0.5) local pos1 = Angle.AngleAxis(angle1 , Vector3(0 , 0 , -1)) * Vector3(radius , 0 , 0) local pos2 = Angle.AngleAxis(angleMid , Vector3(0 , 0 , -1)) * Vector3(radius*1.15 , 0 , 0) local pos3 = Angle.AngleAxis(angle2 , Vector3(0 , 0 , -1)) * Vector3(radius , 0 , 0) table.insert( Models.checkpoint , { pos1 , pos2 , pos3 } ) end end -- Vehicle spawn gizmo. do local width = 3 local length = 5.25 local height = 0.3333 Models.vehicleSpawn = {} local Line = function(a , b) table.insert( Models.vehicleSpawn , {a , b , b + Vector3(0 , height , 0)} ) table.insert( Models.vehicleSpawn , {a , a + Vector3(0 , height , 0) , b + Vector3(0 , height , 0)} ) end -- Create the box. Line( Vector3(width * -0.5 , 0 , length * 0.5) , Vector3(width * -0.5 , 0 , length * -0.5) ) Line( Vector3(width * -0.5 , 0 , length * -0.5) , Vector3(width * 0.5 , 0 , length * -0.5) ) Line( Vector3(width * 0.5 , 0 , length * -0.5) , Vector3(width * 0.5 , 0 , length * 0.5) ) Line( Vector3(width * 0.5 , 0 , length * 0.5) , Vector3(width * -0.5 , 0 , length * 0.5) ) -- Create the arrow. Line( Vector3(0 , 1 , length * 0.3333) , Vector3(0 , 1 , length * -0.3333) ) Line( Vector3(0 , 1 , length * -0.3333) , Vector3(width * 0.3333 , 1 , length * -0.075) ) Line( Vector3(0 , 1 , length * -0.3333) , Vector3(width * -0.3333 , 1 , length * -0.075) ) end
TestUtil = {} function TestUtil:testIntToPos() local edge = math.floor(0xFFFF / 2) local subjects = { vector.new(edge, edge, edge), vector.new(-edge, -edge, -edge), vector.new(0, 0, 0), vector.new(1, 1, 1), vector.new(-1, -1, -1) } for _, pos in pairs(subjects) do local int = stm.pos_to_int(pos) local result = stm.int_to_pos(int) assert(vector.distance(pos, result) == 0) end end
local desc_EN = [[Platform Signs is a mod to demostrate the Livetext mod, which permets any mods to put dynamically generated text on game scene. Though, this mod is still a very interesting one to use mod. The Livetext mod must be activated to use this mod. There are two types of signs in this mod: 1. Station name sign 2. Combined text sign, you can find them in the depot menu. Usage: 1. Station Name Sign Place a Station Name Sign around a station, by default there is a snapping track to help you align the sign onto the platform, use offset and distance options to place it accurately, choose the font and style before finish it. Use the Platform Signs finalizer when everything is done, the finalizer will inject the station name onto the sign. The name injected is the closest staion to the sign. If you want to place the station name sign on a combined sign, please uncheck the pole option. Renaming the sign and start with #, that will force the finalizer to inject any text you want on the sign 2. Combined Sign A combined sign permets you have multiple signs on a same pole, you can have one or some rows of signs and in each row you have can zero to two signs. Rename the sign to prepare the text to inject: - The name of the sign should be started with # - "|" means a new row - Use comma "," to seperate the two signs in the same row - E.g #|1,2|3|4,|,5 -> * The most top row will be empty * The second row will be "1" on the left and "2" on the right * The third row will be a "3" in the middle * The forth row will have an empty right side * The fifth row will have an empty left side Use the finalizer to inject the designated text on the sign. You can hide off the poles to make signs combined on other poles. 3. Remover The remove helps you removing all signs, since the models will be broken into many pieces once finished. Place a remover around the area to clean, and reclick on the remover icon to remove signs around it. The font support comes with Livetext mod, there are two fonts supplied with Livetext mod: Lato (game build-in font) and Alte DIN 1451 Mittelschrift font which is free to use. The Livetext mod use unicode, the following charset are supported: - ASCII and Latin, Latin Supplement and Latin Extended A + B - Cyrilic and Cyrilic Supplement - Greek - Math signs, Arrow signs and per mille sign Attention: not all glyphs are present in DIN 1451 font To extend the charset to other languages or other fonts, for example CJK, a generator will be supplied later for Livetext mod. Changelog 1.4 * Added text option in strip decoration * Order change to avoid mixed with Track Design Patterns 1.3 * Added strip decoration * Added possibilty to have two poles on the sides * Unlocked bold style for DIN font 1.2 * Fixed crash when there's no station close to the sign * Fixed crash when there're more than one station close to the sign * Fixed incorrect station name injection when there is depot close to the sign * Chinese and French UI translations 1.1 * Fixed crashes linked to the params failure * Improved the materials * Improved the usage of remover * Corrected the station name capture when the station has any subfix or have been renamed ]] function data() return { en = { ["name"] = "Platform Signs", ["desc"] = desc_EN, }, fr = { ["name"] = "Panneau du Quai", ["desc"] = desc_EN, ["Font"] = "Police", ["Text Weight"] = "Poids", ["Upper case"] = "Majuscule", ["Outline"] = "Contour", ["Pole Type"] = "Type de pôle", ["Sign Color"] = "Couleur du panneau", ["Text Color"] = "Couleur des caractères", ["Outline Color"] = "Couleur du contour", ["Distance to track"] = "Distance vers la voie d'aide", ["Height Adjustment"] = "Ajustement d'hauteur", ["Offset Adjustment"] = "Décalage", ["Orientation"] = "Orientation", ["Default"] = "Défault", ["Regular"] = "Ordinaire", ["Bold"] = "Gras", ["Cylinder"] = "Cylindre", ["Prism"] = "Prisme", ["No Pole"] = "Sans", ["White"] = "Blanc", ["D.Blue"] = "Marine", ["Blue"] = "Bleu", ["Azur"] = "Azure", ["Black"] = "Noir", ["Text"] = "Script", ["Strip"] = "Bande", ["Decoration"] = "Décoration", ["Decoration Color"] = "Couleur de déco", ["Pole Count"] = "Nombre de pôle", ["Single"] = "Simple", ["Double"] = "Double", ["None"] = "Aucun", ["Track Snapping"] = "Voie d'aide magnétique" }, zh_CN = { ["name"] = "站台牌", ["desc"] = desc_EN, ["Font"] = "字体", ["Text Weight"] = "字重", ["Upper case"] = "全大写", ["Outline"] = "外廓线", ["Pole Type"] = "支撑杆类型", ["Sign Color"] = "站牌颜色", ["Text Color"] = "文字颜色", ["Outline Color"] = "外廓线颜色", ["Distance to track"] = "到辅助轨道距离", ["Height Adjustment"] = "高度调整", ["Offset Adjustment"] = "平移调整", ["Orientation"] = "指向", ["Track Snapping"] = "辅助吸附轨道", ["Default"] = "默认", ["Regular"] = "普通", ["Bold"] = "粗体", ["Cylinder"] = "圆柱", ["Prism"] = "方柱", ["No Pole"] = "无", ["White"] = "白色", ["D.Blue"] = "海蓝", ["Blue"] = "蓝色", ["Azur"] = "天蓝", ["Black"] = "黑色", ["Text"] = "文字", ["Station Name Sign"] = "站台牌", ["Strip"] = "色带", ["Decoration"] = "装饰", ["Decoration Color"] = "装饰颜色", ["Pole Count"] = "支撑杆数量", ["Single"] = "单", ["Double"] = "双", ["None"] = "无", ["Combined Signs"] = "组合指示牌" }, zh_TW = { ["name"] = "站台牌", ["desc"] = desc_EN, ["Font"] = "字體", ["Text Weight"] = "字重", ["Upper case"] = "全大寫", ["Outline"] = "外廓線", ["Pole Type"] = "支撐桿類型", ["Sign Color"] = "站牌顏色", ["Text Color"] = "文字顏色", ["Outline Color"] = "外廓線顏色", ["Distance to track"] = "到輔助軌道距離", ["Height Adjustment"] = "高度調整", ["Offset Adjustment"] = "平移調整", ["Orientation"] = "指向", ["Track Snapping"] = "輔助吸附軌道", ["Default"] = "默認", ["Regular"] = "普通", ["Bold"] = "粗體", ["Cylinder"] = "圓柱", ["Prism"] = "方柱", ["No Pole"] = "無", ["White"] = "白色", ["D.Blue"] = "海藍", ["Blue"] = "藍色", ["Azur"] = "天藍", ["Black"] = "黑色", ["Text"] = "文字", ["Station Name Sign"] = "站台牌", ["Strip"] = "色帶", ["Decoration"] = "裝飾", ["Decoration Color"] = "裝飾顏色", ["Pole Count"] = "支撐桿數量", ["Single"] = "單", ["Double"] = "雙", ["None"] = "無", ["Combined Signs"] = "組合指示牌", ["Strip Color"] = "色带颜色" } } end