content
stringlengths
5
1.05M
local clear_weather_type_persist = ClearWeatherTypePersist local pause_clock = PauseClock local set_weather_type_now = SetWeatherTypeNow local set_weather_type_overtime_persist = SetWeatherTypeNowPersist local network_override_clock_time = NetworkOverrideClockTime RegisterNetEvent("setTimeWeather") AddEventHandler( "setTimeWeather", function(h, m, s, w) clear_weather_type_persist() pause_clock(false) set_weather_type_now(w) set_weather_type_overtime_persist(w, 1) network_override_clock_time(h, m, s) pause_clock(true) end )
local installer = require("nvim-lsp-installer") local servers = { sumneko_lua = require("lsp.lua"), rust_analyzer = require("lsp.rust"), tsserver = {}, clangd = {}, rescriptls = require("lsp.rescript"), sourcekit = {}, hls = {}, } for name, _ in pairs(servers) do local server_is_found, server = installer.get_server(name) if server_is_found then if not server:is_installed() then print("Installing " .. name) server:install() end end end installer.on_server_ready(function(serve) local opts = servers[serve.name] if opts then opts.on_attach = function(_, bufnr) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end require("keybinding").map_lsp(buf_set_keymap) end opts.flags = { debounce_text_changes = 150, } if serve.name == "rust_analyzer" then require("rust-tools").setup({ server = vim.tbl_deep_extend("force", serve:get_default_options(), opts), }) serve:attach_buffers() else serve:setup(opts) end end end)
--------------------------------------------------- -- ___ _ -- -- | __| |___ _ __ _____ __ _____ _ _ -- -- | _|| / -_) '_ \/ _ \ V V / -_) '_| -- -- |___|_\___| .__/\___/\_/\_/\___|_| -- -- |_| -- -- _____ -- -- |_ _|__ _ __ ___ -- -- | |/ _ \ ' \/ -_) -- -- |_|\___/_|_|_\___| -- --------------------------------------------------- -- -- --------------------------------------------------- -- Global variable for mod eletome = rawget(_G, "eletome") or {} -- path, modname and translation local modname = minetest.get_current_modname() local modpath = minetest.get_modpath(modname) eletome.S = minetest.get_translator(modname) local S = eletome.S -- includes dofile(modpath .. "/i_eletome_additional_info.lua") dofile(modpath .. "/i_functions.lua") dofile(modpath .. "/i_page_contents.lua") dofile(modpath .. "/i_page_crafts.lua") dofile(modpath .. "/i_page_machines.lua") dofile(modpath .. "/i_page_instructions.lua") dofile(modpath .. "/i_page_help.lua") -- register our Tome/Book item minetest.register_craftitem("elepower_tome:tome", { description = "Elepower Tome", inventory_image = "elepower_tome.png", groups = {book = 1, flammable = 3}, on_use = function(itemstack, user, pointed_thing) local eletome_bg = eletome.tome_bg local eletome_contents = eletome.contents_page() minetest.show_formspec(user:get_player_name(), "elepower_tome:tome", eletome_bg..eletome_contents) end, }) -- Give player elepower tome on initial logon minetest.register_on_newplayer(function(player) player:get_inventory():add_item("main", "elepower_tome:tome") end) -- Player tome meta - setup back button meta minetest.register_on_joinplayer(function(player) local pmeta = player:get_meta() local back = {} pmeta:set_string("elepower_tome_back", minetest.serialize(back)) end) -- register our recieve field callback minetest.register_on_player_receive_fields(function(player, formname, fields) if formname ~= "elepower_tome:tome" then return end -- Back Button local pmeta = player:get_meta() local back = minetest.deserialize(pmeta:get_string("elepower_tome_back")) local show_back = "" if fields.quit == "true" then back = {} pmeta:set_string("elepower_tome_back", minetest.serialize(back)) elseif fields.back then local prev_page = #back-1 if prev_page <= 0 then -- must be going back to contents fields = {} back = {} pmeta:set_string("elepower_tome_back", minetest.serialize(back)) fields.content = "Content" else fields = back[prev_page] table.remove(back,#back) pmeta:set_string("elepower_tome_back", minetest.serialize(back)) end else table.insert(back,fields) pmeta:set_string("elepower_tome_back", minetest.serialize(back)) end if #back > 0 then show_back = eletome.back_button end -- Clicked contents button on any page. if fields.content then local eletome_bg = eletome.tome_bg..show_back local eletome_contents = eletome.contents_page() minetest.show_formspec(player:get_player_name(), "elepower_tome:tome", eletome_bg..eletome_contents) end -- Clicked a craft link on contents if fields.craft_click then local eletome_bg = eletome.tome_bg..show_back local eletome_craft = eletome.craft_page(fields.craft_click) minetest.show_formspec(player:get_player_name(), "elepower_tome:tome", eletome_bg..eletome_craft) end -- Clicked craft bwd/fwd button on craft sub-page if fields.craft_bwd_fwd then local page_num = string.match(fields.craft_bwd_fwd , "%s(%w+)%s") -- eletome.craft_page() expects description in format "something:craft_description" local craft_value = "cd:"..fields.description local eletome_bg = eletome.tome_bg..show_back local eletome_craft = eletome.craft_page(craft_value,page_num) minetest.show_formspec(player:get_player_name(), "elepower_tome:tome", eletome_bg..eletome_craft) end -- Clicked Machine page if fields.machine then local eletome_bg = eletome.tome_bg..show_back local eletome_machine = eletome.machines(fields.machine) minetest.show_formspec(player:get_player_name(), "elepower_tome:tome", eletome_bg..eletome_machine) end -- Clicked Machine bwd/fwd button on Machine page if fields.mach_bwd_fwd then local page_num = string.match(fields.mach_bwd_fwd, "%s(%w+)%s") local mach_value = fields.description local eletome_bg = eletome.tome_bg..show_back local eletome_machine = eletome.machines(mach_value,page_num) minetest.show_formspec(player:get_player_name(), "elepower_tome:tome", eletome_bg..eletome_machine) end -- Clicked Instructions page if fields.instructions then local eletome_bg = eletome.tome_bg..show_back local eletome_instruct = eletome.instructions_page(fields.description) minetest.show_formspec(player:get_player_name(), "elepower_tome:tome", eletome_bg..eletome_instruct) end -- Clicked Large Image page if fields.large_image then local eletome_bg = eletome.tome_bg..show_back local eletome_lrg_img = eletome.large_image_page(fields.description) minetest.show_formspec(player:get_player_name(), "elepower_tome:tome", eletome_bg..eletome_lrg_img) end -- Clicked Help page if fields.help then local eletome_bg = eletome.tome_bg..show_back local eletome_how_use = eletome.how_use_page(fields.help) minetest.show_formspec(player:get_player_name(), "elepower_tome:tome", eletome_bg..eletome_how_use) end -- Clicked How to use page if fields.description == "action:machine-ele_user" then local how_use = false local node_name for k,v in pairs(eletome.ai.nodes) do if fields[k] then if eletome.ai.nodes[k].how_use_1 then how_use = true node_name = k end end end if how_use then local eletome_bg = eletome.tome_bg..show_back local eletome_how_use = eletome.how_use_page(node_name) minetest.show_formspec(player:get_player_name(), "elepower_tome:tome", eletome_bg..eletome_how_use) end end --minetest.debug(dump(fields)) end) ------------------- -- Page Defaults -- ------------------- eletome.tome_bg = "formspec_version[4]size[18,11]".. "bgcolor[#003782;true]".. -- fails (my understanding limitation) "box[0.0,0.0;18,11;#003782]".. -- workaround the above "box[0.5,0.5;8.5,10;#d1caaeFF]".. "box[9.0,0.5;8.5,10;#d1caaeFF]".. "style_type[button;bgcolor=#003782]".. "style_type[button_exit;bgcolor=#003782]".. "button[0,0;2.5,0.5;content;Content]".. "style[fake_back;textcolor=#777777]".. "button[2.5,0;2.5,0.5;fake_back;Back]".. "style[fake_prev_page;textcolor=#777777]".. "button[12.5,0;2.5,0.5;fake_prev_page;<< Prev]".. "style[fake_next_page;textcolor=#777777]".. "button[15,0;2.5,0.5;fake_prev_page;Next >>]".. "button_exit[17.5,0;0.5,0.5;X;X]" eletome.back_button = "style[back;textcolor=#ffffff]".."button[2.5,0;2.5,0.5;back;Back]" eletome.font_color = "#1f1f1fFF" eletome.y_space_line = 0.4 eletome.char_per_line = 60 eletome.tooltip_color = "#30434c;#f9f9f9" -- Common style components - some end duplicates but kept for ease of reading/updating later -- s = start ie pre text -- e = end ie post text -- Used for hypertext eletome.common_styles = { style_h0s = "<style color="..eletome.font_color.." size=26><b><center>", style_h0e = "</center></b></style>", style_h1s = "<style color="..eletome.font_color.." size=20><b><center>", style_h1e = "</center></b></style>", style_h2s = "<style color="..eletome.font_color.." size=18><center>", style_h2e = "</center></style>", style_h3s = "<style color="..eletome.font_color.." size=14><center>", style_h3e = "</center></style>", -- approximate default "label" size style_h4s = "<style color="..eletome.font_color.." size=12><center>", style_h4e = "</center></style>" }
-- =========================================================================== -- -- CivicsChooser -- Slideout panel containing available civic options. -- -- =========================================================================== -- Include self contained additional tabs g_ExtraIconData = {} include("CivicsTreeIconLoader_", true) include("ToolTipHelper") include("TechAndCivicSupport") -- Already includes Civ6Common and InstanceManager include("AnimSidePanelSupport") include("SupportFunctions") include("Civ6Common") include("cui_tech_civic_support") -- CUI -- =========================================================================== -- CONSTANTS -- =========================================================================== local RELOAD_CACHE_ID = "CivicChooser" -- Must be unique (usually the same as the file name) local MAX_BEFORE_TRUNC_BOOST_MSG = 210 -- Size in which boost messages will be truncated and tooltipified local SIZE_ICON_LARGE = 38 local SIZE_ICON_SMALL = 38 -- =========================================================================== -- MEMBERS -- =========================================================================== local m_civicsIM = InstanceManager:new("CivicListInstance", "TopContainer", Controls.CivicStack) local m_kSlideAnimator -- AnimSidePanelSupport local m_currentID = -1 local m_isExpanded = false local m_lastCompletedID = -1 local m_needsRefresh = false -- used to track whether a given series of events (terminated by GameCoreEventPublishComplete) local m_CachedModifiers = {} -- =========================================================================== -- METHODS -- =========================================================================== -- =========================================================================== -- Determine the current data. -- =========================================================================== function GetData() local kData = {} local ePlayer = Game.GetLocalPlayer() if (ePlayer >= 0) then local pPlayer = Players[ePlayer] local pPlayerCulture = pPlayer:GetCulture() local pResearchQueue = {} -- Get recommendations local civicRecommendations = {} local pGrandAI = pPlayer:GetGrandStrategicAI() if pGrandAI then civicRecommendations = pGrandAI:GetCivicsRecommendations() end pResearchQueue = pPlayerCulture:GetCivicQueue(pResearchQueue) -- Fill in the "other" (not-current) items for kCivic in GameInfo.Civics() do local iCivic = kCivic.Index if iCivic == m_currentID or iCivic == m_lastCompletedID or (iCivic ~= m_currentID and pPlayerCulture:CanProgress(iCivic)) then local kCivicData = GetCivicData(ePlayer, pPlayerCulture, kCivic) kCivicData.IsCurrent = (iCivic == m_currentID) kCivicData.IsLastCompleted = (iCivic == m_lastCompletedID) kCivicData.ResearchQueuePosition = -1 for i, civicNum in pairs(pResearchQueue) do if civicNum == iCivic then kCivicData.ResearchQueuePosition = i end end -- Determine if this civic is recommended kCivicData.IsRecommended = false if civicRecommendations ~= nil then for i, recommendation in pairs(civicRecommendations) do if kCivicData.Hash == recommendation.CivicHash then kCivicData.IsRecommended = true kCivicData.AdvisorType = kCivic.AdvisorType end end end table.insert(kData, kCivicData) end end end return kData end -- =========================================================================== -- Populate the list of research options. -- =========================================================================== function View(playerID, kData) m_civicsIM:ResetInstances() for _, iconData in pairs(g_ExtraIconData) do iconData:Reset() end local kActive = GetActiveData(kData) if kActive == nil then RealizeCurrentCivic(nil) -- No research done yet end table.sort(kData, function(a, b) return Locale.Compare(a.Name, b.Name) == -1 end) for i, data in ipairs(kData) do if data.IsCurrent or data.IsLastCompleted then RealizeCurrentCivic(playerID, data, nil, m_CachedModifiers) if (data.Repeatable) then AddAvailableCivic(playerID, data) end else AddAvailableCivic(playerID, data) end end RealizeSize() end -- =========================================================================== -- Get the latest data and visualize. -- =========================================================================== function Refresh() local player = Game.GetLocalPlayer() if (player >= 0) then local kData = GetData() View(player, kData) end m_needsRefresh = false end -- =========================================================================== -- No culture? No government for you! -- =========================================================================== function CanPlayerCivicAnything(playerID) local pPlayer = Players[playerID] local pPlayerCulture = pPlayer:GetCulture() local currentCultureYield = pPlayerCulture:GetCultureYield() return currentCultureYield <= 0 end -- =========================================================================== -- -- =========================================================================== function AddAvailableCivic(playerID, kData) local numUnlockables local isDisabled = CanPlayerCivicAnything(playerID) -- Create main instance and the Instance Manager for any unlocks. local kItemInstance = m_civicsIM:GetInstance() local unlockIM = GetUnlockIM(kItemInstance) kItemInstance.TechName:SetText(Locale.ToUpper(kData.Name)) kItemInstance.Top:LocalizeAndSetToolTip(kData.ToolTip) kItemInstance.Top:SetTag(UITutorialManager:GetHash(kData.CivicType)) -- Mark for tutorial dynamic element RealizeMeterAndBoosts(kItemInstance, kData) RealizeIcon(kItemInstance.Icon, kData.CivicType, SIZE_ICON_SMALL) RealizeTurnsLeft(kItemInstance, kData) local callback = nil if not isDisabled then callback = function() ResetOverflowArrow(kItemInstance) OnChooseCivic(kData.Hash) end end -- Include extra icons in total unlocks local extraUnlocks = {} local hideDescriptionIcon = false local cachedModifiers = m_CachedModifiers[kData.CivicType] if (cachedModifiers) then for _, tModifier in ipairs(cachedModifiers) do local tIconData = g_ExtraIconData[tModifier.ModifierType] if (tIconData) then hideDescriptionIcon = hideDescriptionIcon or tIconData.HideDescriptionIcon table.insert(extraUnlocks, {IconData = tIconData, ModifierTable = tModifier}) end end end -- Handle overflow for unlock icons numUnlockables = PopulateUnlockablesForCivic(playerID, kData.ID, unlockIM, nil, callback, hideDescriptionIcon) -- Initialize extra icons for _, tUnlock in pairs(extraUnlocks) do tUnlock.IconData:Initialize(kItemInstance.UnlockStack, tUnlock.ModifierTable) numUnlockables = numUnlockables + 1 end if numUnlockables ~= nil then HandleOverflow(numUnlockables, kItemInstance, 5, 5) end if kData.ResearchQueuePosition ~= -1 then kItemInstance.QueueBadge:SetHide(false) kItemInstance.NodeNumber:SetHide(false) if (kData.ResearchQueuePosition < 10) then kItemInstance.NodeNumber:SetOffsetX(-2) else kItemInstance.NodeNumber:SetOffsetX(-5) end kItemInstance.NodeNumber:SetText(tostring(kData.ResearchQueuePosition)) else kItemInstance.QueueBadge:SetHide(true) kItemInstance.NodeNumber:SetHide(true) end -- Set up callback that changes the current research kItemInstance.Top:RegisterCallback(Mouse.eLClick, function() ResetOverflowArrow(kItemInstance) OnChooseCivic(kData.Hash) end) kItemInstance.Top:SetDisabled(isDisabled) -- Only wire up Civilopedia handlers if not in a on-rails tutorial if IsTutorialRunning() == false then kItemInstance.Top:RegisterCallback(Mouse.eRClick, function() LuaEvents.OpenCivilopedia(kData.CivicType) end) end -- Hide/Show Recommendation Icon if kData.IsRecommended and kData.AdvisorType ~= nil then kItemInstance.RecommendedIcon:SetIcon(kData.AdvisorType) kItemInstance.RecommendedIcon:SetHide(false) else kItemInstance.RecommendedIcon:SetHide(true) end end -- =========================================================================== function OnChooseCivic(civicHash) if civicHash == nil then UI.DataError("Attempt to choose a civic but a NIL hash!") return end ResetOverflowArrow(Controls) if (Game.GetLocalPlayer() >= 0) then local tParameters = {} tParameters[PlayerOperations.PARAM_CIVIC_TYPE] = civicHash tParameters[PlayerOperations.PARAM_INSERT_MODE] = PlayerOperations.VALUE_EXCLUSIVE UI.RequestPlayerOperation(Game.GetLocalPlayer(), PlayerOperations.PROGRESS_CIVIC, tParameters) UI.PlaySound("Confirm_Civic") end if m_isExpanded then OnClosePanel() end end -- =========================================================================== function RealizeSize() local _, screenY = UIManager:GetScreenSizeVal() Controls.ChooseCivicList:SetSizeY(screenY - Controls.ChooseCivicList:GetOffsetY() - 30) Controls.ChooseCivicList:CalculateInternalSize() Controls.CivicStack:CalculateSize() Controls.CivicStack:ReprocessAnchoring() if (Controls.ChooseCivicList:GetScrollBar():IsHidden()) then Controls.ChooseCivicList:SetOffsetX(10) else Controls.ChooseCivicList:SetOffsetX(20) end end -- =========================================================================== function OnOpenPanel() LuaEvents.ResearchChooser_ForceHideWorldTracker() UI.PlaySound("Tech_Tray_Slide_Open") m_isExpanded = true m_kSlideAnimator.Show() end -- =========================================================================== function OnClosePanel() m_kSlideAnimator.Hide() end -- =========================================================================== -- Callback from Slide Animator -- =========================================================================== function OnSlideAnimatorClose() LuaEvents.ResearchChooser_RestoreWorldTracker() UI.PlaySound("Tech_Tray_Slide_Closed") m_isExpanded = false end -- =========================================================================== function OnUpdateUI(type) m_kSlideAnimator.OnUpdateUI() if type == SystemUpdateUI.ScreenResize then RealizeSize() end end -- =========================================================================== -- Game Engine EVENT -- City added to map, refresh for local player needed if it's the 1st city. -- =========================================================================== function OnCityInitialized(owner, cityID) local localPlayer = Game.GetLocalPlayer() if owner == localPlayer then m_needsRefresh = true end end -- =========================================================================== -- Game Engine EVENT -- =========================================================================== function OnLocalPlayerTurnBegin() local localPlayer = Game.GetLocalPlayer() if localPlayer >= 0 then local pPlayerCulture = Players[localPlayer]:GetCulture() m_currentID = pPlayerCulture:GetProgressingCivic() m_needsRefresh = true end end -- =========================================================================== -- Game Engine EVENT -- =========================================================================== function OnPhaseBegin() if Game.GetLocalPlayer() >= 0 then m_needsRefresh = true end end -- =========================================================================== -- Game Engine EVENT -- =========================================================================== function OnCivicChanged(ePlayer, eCivic) local localPlayer = Game.GetLocalPlayer() if localPlayer ~= -1 and localPlayer == ePlayer then local pPlayerCulture = Players[localPlayer]:GetCulture() m_currentID = pPlayerCulture:GetProgressingCivic() m_lastCompletedID = -1 m_needsRefresh = true end end -- =========================================================================== function OnCivicCompleted(ePlayer, eCivic) if ePlayer == Game.GetLocalPlayer() then m_lastCompletedID = eCivic m_currentID = -1 -- CUI: repeat local futureCivic = CuiIsFutureCivicAndGet(eCivic) if futureCivic then CuiRepeatCivic(futureCivic.Hash) end -- m_needsRefresh = true end end -- =========================================================================== function OnCultureYieldChanged(ePlayer) if ePlayer == Game.GetLocalPlayer() then m_needsRefresh = true end end -- =========================================================================== -- This will get called after a series of game events (before any other events or -- input processing) so we can defer the rebuild until here. -- =========================================================================== function FlushChanges() if m_needsRefresh and ContextPtr:IsVisible() then Refresh() end end -- =========================================================================== -- UI Event -- =========================================================================== function OnInputHandler(kInputStruct) return m_kSlideAnimator.OnInputHandler(kInputStruct) end -- =========================================================================== -- -- Init/Uninit/Hot-Loading Events -- -- =========================================================================== function OnInit(isReload) if isReload then LuaEvents.GameDebug_GetValues(RELOAD_CACHE_ID) else local localPlayer = Game.GetLocalPlayer() if (localPlayer >= 0) then local pPlayerCulture = Players[localPlayer]:GetCulture() m_currentID = pPlayerCulture:GetProgressingCivic() Refresh() end end end -- =========================================================================== function OnShow() Refresh() end -- =========================================================================== function OnShutdown() LuaEvents.GameDebug_AddValue(RELOAD_CACHE_ID, "m_currentID", m_currentID) LuaEvents.GameDebug_AddValue(RELOAD_CACHE_ID, "m_isExpanded", m_isExpanded) LuaEvents.GameDebug_AddValue(RELOAD_CACHE_ID, "m_lastCompletedID", m_lastCompletedID) end -- =========================================================================== function OnGameDebugReturn(context, contextTable) if context == RELOAD_CACHE_ID then m_currentID = contextTable["m_currentID"] m_lastCompletedID = contextTable["m_lastCompletedID"] Refresh() if contextTable["m_isExpanded"] ~= nil and contextTable["m_isExpanded"] then OnOpenPanel() else LuaEvents.ResearchChooser_RestoreWorldTracker() end end end -- CUI ======================================================================= function CuiRepeatCivic(civicHash) if civicHash == nil then UI.DataError("Attempt to choose a civic but a NIL hash!") return end ResetOverflowArrow(Controls) if (Game.GetLocalPlayer() >= 0) then local tParameters = {} tParameters[PlayerOperations.PARAM_CIVIC_TYPE] = civicHash tParameters[PlayerOperations.PARAM_INSERT_MODE] = PlayerOperations.VALUE_EXCLUSIVE UI.RequestPlayerOperation(Game.GetLocalPlayer(), PlayerOperations.PROGRESS_CIVIC, tParameters) UI.PlaySound("Confirm_Civic") end end -- =========================================================================== -- INIT -- =========================================================================== function Initialize() -- Cache frequently used / expensive data m_CachedModifiers = TechAndCivicSupport_BuildCivicModifierCache() -- Hot-reload events ContextPtr:SetInitHandler(OnInit) ContextPtr:SetShowHandler(OnShow) ContextPtr:SetShutdown(OnShutdown) LuaEvents.GameDebug_Return.Add(OnGameDebugReturn) -- Animation controller and events m_kSlideAnimator = CreateScreenAnimation(Controls.SlideAnim, OnSlideAnimatorClose) -- Screen events LuaEvents.ActionPanel_OpenChooseCivic.Add(OnOpenPanel) LuaEvents.WorldTracker_OpenChooseCivic.Add(OnOpenPanel) LuaEvents.LaunchBar_CloseChoosers.Add(OnClosePanel) -- Game events Events.CityInitialized.Add(OnCityInitialized) Events.CivicChanged.Add(OnCivicChanged) Events.CivicCompleted.Add(OnCivicCompleted) Events.CultureYieldChanged.Add(OnCultureYieldChanged) Events.LocalPlayerTurnBegin.Add(OnLocalPlayerTurnBegin) Events.LocalPlayerChanged.Add(OnLocalPlayerTurnBegin) Events.PhaseBegin.Add(OnPhaseBegin) Events.SystemUpdateUI.Add(OnUpdateUI) Events.GameCoreEventPublishComplete.Add(FlushChanges) -- This event is raised directly after a series of gamecore events. -- UI Event / Callbacks ContextPtr:SetInputHandler(OnInputHandler, true) Controls.CloseButton:RegisterCallback(Mouse.eLClick, OnClosePanel) Controls.CloseButton:RegisterCallback(Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over") end) Controls.TitleButton:RegisterCallback(Mouse.eLClick, OnClosePanel) Controls.IconButton:RegisterCallback(Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over") end) Controls.IconButton:RegisterCallback(Mouse.eLClick, OnClosePanel) Controls.OpenTreeButton:RegisterCallback(Mouse.eLClick, function() LuaEvents.CivicsChooser_RaiseCivicsTree() OnClosePanel() end) Controls.OpenTreeButton:RegisterCallback(Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over") end) -- Populate static controls Controls.Title:SetText(Locale.ToUpper(Locale.Lookup("LOC_CIVICS_CHOOSER_CHOOSE_CIVIC"))) Controls.OpenTreeButton:SetText(Locale.Lookup("LOC_CIVICS_CHOOSER_OPEN_CIVICS_TREE")) -- To make it render beneath the banner image Controls.MainPanel:SetOffsetX(Controls.Background:GetOffsetX() * -1) Controls.MainPanel:ChangeParent(Controls.Background) end Initialize()
exports.name = "websocketutils" exports.version = "0.0.1" exports.author = "Niklas Kühtmann" local bitmap = require('bitmap') local bit = require('bit') local bytemap = require('bytemap') local b64 = require("base64") local sha1 = require("sha1") local string = require("string") string.split = function(inputstr, sep) if sep == nil then sep = "%s" end local t={} local i=1 for str in string.gmatch(inputstr, "([^"..sep.."]+)") do t[i] = str i = i + 1 end return t end exports.disassemblePacket = function(buffer) local bytemap = bytemap.fromString(buffer) -- flag evaluation local bitmap = bitmap.fromNumber(bytemap[1]) local fin = bitmap:isSet(1); local rsv1 = bitmap:isSet(2); rsv2 = bitmap:isSet(3); rsv3 = bitmap:isSet(4) local opcode = tonumber(bitmap[5] .. bitmap[6] .. bitmap[7] .. bitmap[8], 2) -- message fragmentation check if not fin then print("WebSocket Error: Message Fragmentation not supported.") return end -- client request close if opcode == 8 then return 2 end -- ping - pong if opcode == 9 then bitmap[8] = true bitmap[7] = false bytemap[1] = bitmap:toNumber() return 1, bytemap:toString() end -- remove flags from bytemap bytemap:popStart() -- get packet size (needed for message fragmentation later on, sits inbetween so get it, why not) -- need to know where to cut off anyway local length = bytemap[1] - 128 bytemap:popStart() if length == 126 then length = bytemap:toNumber(1,2) bytemap:popStart(2) elseif length == 127 then length = bytemap:toNumber(1,2,3,4,5,6,7,8) bytemap:popStart(8) end -- get mask local mask = {bytemap:get(1,2,3,4)} -- remove mask from bytemap bytemap:popStart(4) -- check if the tcp handler missed to push something if length > #bytemap.bytes then return 3 end -- finally decode and return local ret = "" bytemap:forEach(function(k,v) local i = k % 4 ret = ret .. string.char(bit.bxor(mask[i > 0 and i or 4], v)) end) return ret end exports.assemblePacket = function(buffer) local flags = "10000001" local bytemap = bytemap.new({tonumber(flags, 2), #buffer}) if bytemap[2] >= 65536 then local length = bytemap[2] for i = 10, 3, -1 do bytemap[i] = bit.band(length, 0xFF) length = bit.rshift(length, 8) end bytemap[2] = 127 elseif bytemap[2] >= 126 then bytemap[4] = bit.band(bytemap[2], 0xFF) bytemap[3] = bit.band(bit.rshift(bytemap[2], 8), 0xFF) bytemap[2] = 126 end for i = 1, #buffer do bytemap:push(string.byte(buffer:sub(i, i))) end local ret = "" bytemap:forEach(function(k,v) ret = ret .. string.char(v) end) return ret end exports.assembleHandshakeResponse = function(handshake) local lines = handshake:split('\r\n') local title = lines[1] lines[1] = nil local data = {} for k,v in pairs(lines) do if #v > 2 then local line = v:split(": ") data[line[1]] = line[2] end end local responseKey = data["Sec-WebSocket-Key"] .. '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' responseKey = b64.encode(sha1.binary(responseKey)) return "HTTP/1.1 101 Switching Protocols\r\n" .."Connection: Upgrade\r\n" .."Upgrade: websocket\r\n" .."Sec-WebSocket-Accept: " .. responseKey .. "\r\n" .."\r\n" end
local Direction = require "me.strangepan.games.specialdelivery.direction" local class = require "me.strangepan.libs.util.v1.class" local assert_that = require "me.strangepan.libs.truth.v1.assert_that" local Path = class.build() function Path:_init(graph) assert_that(graph):is_a_table() self.graph = graph self.direction = 1 end local updateDirection = function(self) if self.start.edge == self.dest.edge then if self.start.dist < self.dest.dist then self.direction = Direction.FORWARD elseif self.start.dist > self.dest.dist then self.direction = Direction.BACKWARD end else if self.graph.edges[self.start.edge].to == self.nodes[1] then self.direction = Direction.FORWARD else self.direction = Direction.BACKWARD end end end function Path:setEndpoints(startEdgeId, startEdgeDist, endEdgeId, endEdgeDist) self.start = { edge = startEdgeId, dist = startEdgeDist, } self.dest = { edge = endEdgeId, dist = endEdgeDist, } self.nodes = self.graph:findPath(self.start.edge, self.start.dist, self.dest.edge, self.dest.dist) updateDirection(self) self.nextEdge = nil self:refreshDrawPoints() end function Path:setStart(startEdgeId, startEdgeDist) assert_that(startEdgeId):is_a_number():is_a_key_in(self.graph.edges) assert_that(startEdgeDist) :is_a_number() :is_greater_than_or_equal_to(0) :is_less_than_or_equal_to(self.graph:lengthOfEdge(startEdgeId)) -- Trivial case, short-circuit. No need to recalculate path. if startEdgeId == self.start.edge then self.start.dist = startEdgeDist if self.drawPoints then self.drawPoints[1] = self.graph:pointOnEdge(self.start.edge, self.start.dist) end return end self.start.edge = startEdgeId self.start.dist = startEdgeDist -- See if new start is on path, short-circuit. No need to recalculate path. local newNodes local drawPointsOffset for i = 2,#self.nodes do if not newNodes then local edge = self.graph:edgeBetweenNodes(self.nodes[i-1], self.nodes[i]) if edge and edge.id == startEdgeId then newNodes = {} drawPointsOffset = i - 1 self.drawPoints[1 + i - drawPointsOffset] = self.drawPoints[1 + i] self.drawPoints[1 + i] = nil end end if newNodes then table.insert(newNodes, self.nodes[i]) -- Draw points contain #nodes + 2 (start, end, and all nodes in between). self.drawPoints[2 + i - drawPointsOffset] = self.drawPoints[2 + i] self.drawPoints[2 + i] = nil end end if newNodes then self.nodes = newNodes updateDirection(self) self.nextEdge = nil return end -- Start does not exist on path; recalculate self.nodes = self.graph:findPath(self.start.edge, self.start.dist, self.dest.edge, self.dest.dist) updateDirection(self) self.nextEdge = nil self:refreshDrawPoints() end function Path:getDirectionToNextNode() return self.direction end function Path:getNextEdge() if not self.nextEdge then local nNodes if not self.nodes then nNodes = 0 else nNodes = #self.nodes end if nNodes == 0 then self.nextEdge = nil elseif nNodes == 1 then self.nextEdge = self.dest.edge else self.nextEdge = self.graph:edgeBetweenNodes(self.nodes[1], self.nodes[2]).id end end return self.nextEdge end function Path:getNextNode() if not self.nodes then return nil end return self.nodes[1] end function Path:refreshDrawPoints() self.drawPoints = {} table.insert(self.drawPoints, self.graph:pointOnEdge(self.start.edge, self.start.dist)) for _,nodeId in ipairs(self.nodes) do table.insert(self.drawPoints, self.graph.nodes[nodeId]) end table.insert(self.drawPoints, self.graph:pointOnEdge(self.dest.edge, self.dest.dist)) end function Path:draw() if not self.drawPoints then return end local points = self.drawPoints love.graphics.setColor(224, 76, 118) love.graphics.setLineWidth(12) love.graphics.ellipse('fill', points[1].x, points[1].y, 6, 6) for i = 2,#self.drawPoints,1 do love.graphics.line(points[i-1].x, points[i-1].y, points[i].x, points[i].y) love.graphics.ellipse('fill', points[i].x, points[i].y, 6, 6) end end return Path
----------------------------------------------------------------------------- --=========================================================================== IDENTIFIER = 'S7_Journal' ---@class MODINFO: ModInfo ---@field ModVersion string ---@field ModSettings table ---@field DefaultSettings table ---@field SubdirPrefix string MODINFO = Ext.GetModInfo('6b1aee95-bd4c-4190-a919-4aa7096eaa2b') MODINFO.SubdirPrefix = "TakeNotes/" MODINFO.DefaultSettings = { ["Storage"] = "Internal", ["SyncTo"] = "ItemGUID", ["Uniques"] = false } -- ======= AUX FUNCTIONS ========== Ext.Require('AuxFunctions/Index.lua') -- ================================= --=========================================================================== ----------------------------------------------------------------------------- UCL = Mods["S7_UI_Components_Library"] -- Import UI Components Library if UCL == nil then Debug:HFError("Could Not Find UI Components Library!") end -- ====== -- VARDEC -- ====== JournalTemplate = "df7a8779-f908-43ac-b0ba-cb49d16308a9" -- Journal's Item Root Template PersistentVars = {} PersistentVars.JournalData = {}
-- Default Hilbish config lunacolors = require 'lunacolors' bait = require 'bait' function doPrompt(fail) prompt(lunacolors.format( '{blue}%u {cyan}%d ' .. (fail and '{red}' or '{green}') .. '∆ ' )) end print(lunacolors.format(hilbish.greeting)) doPrompt() bait.catch('command.exit', function(code) doPrompt(code ~= 0) end)
fx_version 'adamant' game 'gta5' client_script 'Client.net.dll' server_scripts { 'Server.net.dll', 'main.lua', }
local spikeJumpThruController = {} spikeJumpThruController.name = "YetAnotherHelper/SpikeJumpThruController" spikeJumpThruController.depth = 0 spikeJumpThruController.placements = { name = "normal", data = { persistent = false } } spikeJumpThruController.texture = "ahorn/YetAnotherHelper/spikeJumpThruController" return spikeJumpThruController
local Keys = { ["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57, ["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177, ["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18, ["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182, ["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81, ["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70, ["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178, ["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173, ["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118 } local listOn = false local faketimer = 0 local connectedPlayers = {} local formattedPlayerList = {} ESX = nil Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end Citizen.Wait(2000) ESX.TriggerServerCallback('scoreboard:getPlayers', function(playerTable) connectedPlayers = playerTable UpdatePlayerTable() end) end) RegisterNetEvent('scoreboard:updatePlayers') AddEventHandler('scoreboard:updatePlayers', function(playerTable) connectedPlayers = playerTable UpdatePlayerTable() end) Citizen.CreateThread(function() if faketimer >= 3 then faketimer = 0 end listOn = false while true do Citizen.Wait(10) if IsControlPressed(0, Keys['F10']) then if not listOn then if faketimer >= 2 then ESX.TriggerServerCallback('scoreboard:getScoreboard', function(ems, police, taxi, mek, bil, maklare, spelare) SendNUIMessage({ text = table.concat(formattedPlayerList), ems = ems, police = police, taxi = taxi, mek = mek, bil = bil, maklare = maklare, spelare = spelare }) end) faketimer = 0 else SendNUIMessage({ text = table.concat(formattedPlayerList)}) faketimer = 0 end listOn = true while listOn do Citizen.Wait(10) if IsControlPressed(0, Keys['F10']) == false then listOn = false SendNUIMessage({ meta = 'close' }) break end end end end end end) function UpdatePlayerTable() formattedPlayerList = {} for k,v in pairs(connectedPlayers) do table.insert(formattedPlayerList, '<tr style=\"color: rgb(' .. 255 .. ', ' .. 255 .. ', ' .. 255 .. ')\"><td>' .. k .. '</td><td>' .. v.name .. '</td></tr>') end end Citizen.CreateThread(function() -- Thread for timer while true do Citizen.Wait(5000) faketimer = faketimer + 1 end end)
local a = require 'plenary.async' local M = {} function M.new(builder_fn) local instance = { state = { name = nil, switches = {}, options = {}, actions = {{}}, env = {}, }, builder_fn = builder_fn } setmetatable(instance, { __index = M }) return instance end function M:name(x) self.state.name = x return self end function M:env(x) self.state.env = x return self end function M:new_action_group() table.insert(self.state.actions, {}) return self end --@param parse Whether the switch is internal to neogit or should be included in the cli command. -- If `false` we don't include it in the cli comand. function M:switch(key, cli, description, enabled, parse) if enabled == nil then enabled = false end if parse == nil then parse = true end table.insert(self.state.switches, { id = '-' .. key, key = key, cli = cli, description = description, enabled = enabled, parse = parse }) return self end function M:option(key, cli, value, description) table.insert(self.state.options, { id = '=' .. key, key = key, cli = cli, value = value, description = description, }) return self end function M:action(key, description, callback) table.insert(self.state.actions[#self.state.actions], { key = key, description = description, callback = callback and a.void(callback) or nil }) return self end function M:action_if(cond, key, description, callback) if cond then table.insert(self.state.actions[#self.state.actions], { key = key, description = description, callback = callback and a.void(callback) or nil }) end return self end function M:build() if self.state.name == nil then error("A popup needs to have a name!") end return self.builder_fn(self.state) end return M
function RegisterMap(name) warning("RegisterMap() is deprecated, please use the base game mod loader for custom maps.") end
require("background") require("bird") require("tube") GameScene = class() function GameScene:onInit() self.bird = Bird() self.bg = Background() self.tubes = {} self.gameOverImg = luna.graphics.Sprite(luna.assets.art.items.gameover) self.gameOverImg:setOriginToCenter() self.gameOverImg:setPos(luna.sizes.getScreenWidth() / 2, luna.sizes.getScreenHeight() / 2) self.spawnTime = 0 self.gameOver = false end function GameScene:spawnTube() local gapY = math.random(settings.gapMargins, luna.sizes.getScreenHeight() - settings.gapMargins) table.insert(self.tubes, Tube(gapY)) end function GameScene:updateTubes(dt) local count = #self.tubes local i = 1 while i <= count do local tube = self.tubes[i] tube:update(dt) if tube:isOutOfScreen() then table.remove(self.tubes, i) count = #self.tubes else i = i + 1 end end self.spawnTime = self.spawnTime - dt if self.spawnTime <= 0 then self:spawnTube() self.spawnTime = settings.tubeSpawnDelay end end function GameScene:checkCollisions() if self.bird:isUnderFloor() then self.gameOver = true return end for _, tube in pairs(self.tubes) do if tube:isIntersectWithRect(self.bird:getRect()) then self.bird:fall() self.gameOver = true break end end end function GameScene:onTouchDown(x, y) if self.gameOver then luna.scenes.setScene(GameScene()) end self.bird:jump() end function GameScene:onTouchMoved(x, y) end function GameScene:onTouchUp(x, y) end function GameScene:onUpdate(dt) self.bird:update(dt) if self.gameOver then return end self.bg:update(dt) self:updateTubes(dt) self:checkCollisions() end function GameScene:onRender() self.bg:render() self.bird:render() for _, tube in pairs(self.tubes) do tube:render() end if self.gameOver then self.gameOverImg:render() end end
object_ship_nova_orion_intro_01_tier7 = object_ship_shared_nova_orion_intro_01_tier7:new { } ObjectTemplates:addTemplate(object_ship_nova_orion_intro_01_tier7, "object/ship/nova_orion_intro_01_tier7.iff")
local CarAddient = {} CarAddient.id = "car_addident" CarAddient.eventRequirement = timeline.EVENTS.NEW_DAY CarAddient.rollMin = 7 CarAddient.rollMax = 1000 CarAddient.occurChance = 7 -- 7 in 10000 CarAddient.awayDuration = 42 -- 42 days CarAddient.validEmployees = {} CarAddient.fact_baselineAge = 20 -- the additional chance per year is only added if the person's age is equal to or greater than this value CarAddient.fact_deathChance = 45 -- the base chance CarAddient.fact_chancePerYear = 1.25 -- additional success chance per each yeah past the fact_baselineAge value CarAddient.formatTable = {} CarAddient.popupText = _T("CAR_ACCIDENT_DESC", "NAME SURNAME had an car accident. They have taken leave for recovery in hospital for TIMETEXT.") CarAddient.popupTitle = _T("CAR_ACIDENT", "Car accident") function CarAddient:occur() for key, employee in ipairs(studio:getEmployees()) do if employee:isAvailable() and not employee:getFact(self.id) and not employee:isPlayerCharacter() then table.insert(self.validEmployees, employee) end end if #self.validEmployees > 0 then local randomIndex = math.random(1, #self.validEmployees) local randomEmployee = self.validEmployees[randomIndex] randomEmployee:setFact(self.id, true) randomEmployee:setAwayUntil(timeline.curTime + self.awayDuration) self.formatTable.NAME = randomEmployee:getName() self.formatTable.SURNAME = randomEmployee:getSurname() self.formatTable.TIMETEXT = timeline:getTimePeriodText(self.awayDuration) --string.timegroup(self.awayDuration * 86400)) local popup = gui.create("Popup") popup:setWidth(400) popup:centerX() popup:setTextFont(fonts.get("pix20")) popup:setFont(fonts.get("pix24")) popup:setTitle(self.popupTitle) popup:setText(string.formatbykeys(self.popupText, self.formatTable)) popup:setDepth(105) popup:addButton(fonts.get("pix20"), "OK") popup:performLayout() popup:centerY() frameController:push(popup) end table.clear(self.validEmployees) -- it has to be clean after we've done everything end function CarAddient:validateFact(employee) local yearAffector = math.max(employee:getAge() - self.fact_baselineAge, 0) * self.fact_chancePerYear local factChance = self.fact_deathChance + yearAffector if math.random(1, 100) <= factChance then -- looks like this guy's parents are dead already employee:setFact(self.id, true) end end randomEvents:registerNew(CarAddient)
local Settings = { ["token"] = "YOUR_TOKEN_HERE", ["url"] = "YOUR_URL_HERE" --// Note: Remove the slash at the end of your url, it'll be automatically replaced. } return Settings
--[[ © CloudSixteen.com do not share, re-distribute or modify without permission of its author (kurozael@gmail.com). Clockwork was created by Conna Wiles (also known as kurozael.) http://cloudsixteen.com/license/clockwork.html --]] local Clockwork = Clockwork; local ITEM = Clockwork.item:New(nil, true); ITEM.name = "Alcohol Base"; ITEM.useText = "Drink"; ITEM.category = "Consumables"; ITEM.useSound = {"npc/barnacle/barnacle_gulp1.wav", "npc/barnacle/barnacle_gulp2.wav"}; ITEM.expireTime = 120; ITEM.attributes = {}; -- Called when a player uses the item. function ITEM:OnUse(player, itemEntity) for k, v in pairs(self("attributes")) do player:BoostAttribute(self("name"), k, v, self("expireTime")); end; Clockwork.player:SetDrunk(player, self("expireTime")); if (self.OnDrink) then self:OnDrink(player); end; end; -- Called when a player drops the item. function ITEM:OnDrop(player, position) end; Clockwork.item:Register(ITEM);
import("colors.lua") import("draw.lua") import("keys.lua") local pos_x = 0 local pos_y = 0 function init() renderer_h = 25 renderer_w = 25 renderer_text = 'test_app' end function on_logic() if key_down(keys.esc) then quit(0) end if key_down(keys.up) then if pos_y ~= 0 then pos_y = pos_y - 1 end end if key_down(keys.down) then local max_y = renderer_h - 1 if pos_y < max_y then pos_y = pos_y + 1 end end if key_down(keys.left) then if pos_x ~= 0 then pos_x = pos_x - 1 end end if key_down(keys.right) then local max_x = renderer_w - 1 if pos_x < max_x then pos_x = pos_x + 1 end end end function on_frame() put_glyph(201, pos_x, pos_y, colors.green, colors.black) put_glyph(205, pos_x+1, pos_y, colors.green, colors.black) put_glyph(205, pos_x+2, pos_y, colors.green, colors.black) put_glyph(205, pos_x+3, pos_y, colors.green, colors.black) put_glyph(187, pos_x+4, pos_y, colors.green, colors.black) end
#!/usr/bin/env th -- Original by @eladhoffer at https://github.com/eladhoffer/DeepDream.torch. -- Modifications by @bamos at https://github.com/bamos/dream-art. -- Both licensed under the MIT license. require 'torch' require 'nn' require 'image' require 'optim' torch.setdefaulttensortype('torch.DoubleTensor') local loadcaffe_wrap = require 'loadcaffe_wrapper' -------------------------------------------------------------------------------- local cmd = torch.CmdLine() -- Basic options cmd:option('-content_image', 'examples/inputs/tubingen.jpg', 'Content target image') cmd:option('-gpu', 0, 'Zero-indexed ID of the GPU to use; for CPU mode set -gpu = -1') -- DeepDream options cmd:option('-num_iter', 100) cmd:option('-num_octave', 5) cmd:option('-octave_scale', 1.4) cmd:option('-end_layer', 32) cmd:option('-clip', true) -- Other options cmd:option('-proto_file', 'models/VGG_ILSVRC_19_layers_deploy.prototxt') cmd:option('-model_file', 'models/VGG_ILSVRC_19_layers.caffemodel') cmd:option('-backend', 'nn', 'nn|cudnn') cmd:option('-output_image', 'out.png') local Normalization = {mean = 118.380948/255, std = 61.896913/255} function main(params) if params.gpu >= 0 then require 'cutorch' require 'cunn' cutorch.setDevice(params.gpu + 1) else params.backend = 'nn-cpu' end if params.backend == 'cudnn' then require 'cudnn' end local cnn = loadcaffe_wrap.load(params.proto_file, params.model_file, params.backend):double() local is_cuda = params.gpu >= 0 if is_cuda then cnn:cuda() end local content_image = grayscale_to_rgb(image.load(params.content_image)):double() deepdream_image = deepdream(cnn, content_image, is_cuda, params.num_iter, params.num_octave, params.octave_scale, params.end_layer, params.clip) image.save(params.output_image, deepdream_image) end -- From neural-style.lua function grayscale_to_rgb(img) local c, h, w = img:size(1), img:size(2), img:size(3) if c == 1 then return img:expand(3, h, w):contiguous() else return img end end function reduceNet(full_net,end_layer) local net = nn.Sequential() for l=1,end_layer do net:add(full_net:get(l)) end return net end function make_step(net, img, is_cuda, clip, step_size, jitter) local step_size = step_size or 0.01 local jitter = jitter or 32 local clip = clip if clip == nil then clip = true end local ox = 0--2*jitter - math.random(jitter) local oy = 0--2*jitter - math.random(jitter) img = image.translate(img,ox,oy) -- apply jitter shift local dst, g if is_cuda then local cuda_img = img:cuda():view(1,img:size(1),img:size(2),img:size(3)) dst = net:forward(cuda_img) g = net:updateGradInput(cuda_img,dst):double():squeeze() else dst = net:forward(img) g = net:updateGradInput(img,dst) end -- apply normalized ascent step to the input image img:add(g:mul(step_size/torch.abs(g):mean())) img = image.translate(img,-ox,-oy) -- apply jitter shift if clip then bias = Normalization.mean/Normalization.std img:clamp(-bias,1/Normalization.std-bias) end return img end function deepdream(net, base_img, is_cuda, iter_n, octave_n, octave_scale, end_layer, clip) local iter_n = iter_n or 10 local octave_n = octave_n or 4 local octave_scale = octave_scale or 1.4 local end_layer = end_layer or 20 local net = reduceNet(net, end_layer) local clip = clip if clip == nil then clip = true end -- prepare base images for all octaves local octaves = {} octaves[octave_n] = torch.add(base_img, -Normalization.mean):div(Normalization.std) local _,h,w = unpack(base_img:size():totable()) for i=octave_n-1,1,-1 do octaves[i] = image.scale(octaves[i+1], math.ceil((1/octave_scale)*w), math.ceil((1/octave_scale)*h),'simple') end local detail local src for octave, octave_base in pairs(octaves) do print("deepdream.octave:",octave) src = octave_base local _,h1,w1 = unpack(src:size():totable()) if octave > 1 then -- upscale details from the previous octave detail = image.scale(detail, w1, h1,'simple') src:add(detail) end for i=1,iter_n do if math.fmod(i-1,10) == 0 then print(" deepdream.iter:",i) end src = make_step(net, src, is_cuda, clip) end -- extract details produced on the current octave detail = src-octave_base end -- returning the resulting image src:mul(Normalization.std):add(Normalization.mean) return src end local params = cmd:parse(arg) main(params)
local function loader(t, k) return rawget(t, k) or require("widgets." .. k) end return setmetatable({}, { __index = loader })
a=Motion(1,39488,39531) b=Motion(1,52177,52271) e=stitch(a,b, "stitch", 40,true, false, true, true) e:show() f=stitch(a,b, "concat") f:show("green") test("PositionStitch", 53536, 53601, 25908, 25960)
-- GUN (Give Up Now) os.exit()
ZO_CreateStringId("SI_BUI_INV_ITEM_ALL","Inventário") ZO_CreateStringId("SI_BUI_INV_ITEM_MATERIALS","Materiais") ZO_CreateStringId("SI_BUI_INV_ITEM_QUICKSLOT","|cFF6600Consumíveis|r") ZO_CreateStringId("SI_BUI_INV_ITEM_WEAPONS","Armas") ZO_CreateStringId("SI_BUI_INV_ITEM_APPAREL","Vestuário") ZO_CreateStringId("SI_BUI_INV_ITEM_CONSUMABLE","Conveniências") ZO_CreateStringId("SI_BUI_INV_ITEM_MISC","Variado") ZO_CreateStringId("SI_BUI_INV_ITEM_JUNK","Lixo") ZO_CreateStringId("SI_BUI_INV_EQUIPSLOT_TITLE","Equipar...") ZO_CreateStringId("SI_BUI_INV_EQUIPSLOT_PROMPT","Que mão quere escolher?") ZO_CreateStringId("SI_BUI_INV_EQUIPSLOT_MAIN","Primeira") ZO_CreateStringId("SI_BUI_INV_EQUIPSLOT_OFF","Segunda") ZO_CreateStringId("SI_BUI_INV_EQUIP_PROMPT_MAIN","Primeira") ZO_CreateStringId("SI_BUI_INV_EQUIP_PROMPT_BACKUP","Segunda") ZO_CreateStringId("SI_BUI_INV_EQUIP_PROMPT_CANCEL","Cancelar") ZO_CreateStringId("SI_BUI_INV_SWITCH_EQUIPSLOT","Modar de arma") ZO_CreateStringId("SI_BUI_INV_ACTION_QUICKSLOT_ASSIGN","Atribuir conveniência") ZO_CreateStringId("SI_BUI_INV_EQUIPSLOT_MAIN","Primeira Arma") ZO_CreateStringId("SI_BUI_INV_EQUIPSLOT_BACKUP","Segunda Arma") ZO_CreateStringId("SI_BUI_BANKING_WITHDRAW","Retirar") ZO_CreateStringId("SI_BUI_BANKING_DEPOSIT","Depósitar") ZO_CreateStringId("SI_BUI_BANKING_BUYSPACE","Comprar Mais espaço (<<1>>)") ZO_CreateStringId("SI_BUI_INV_ACTION_TO_TEMPLATE","Vai para o <<1>>") ZO_CreateStringId("SI_BUI_INV_ACTION_CB","ESO Plus Inventário") ZO_CreateStringId("SI_BUI_INV_ACTION_INV","Inventário") -- A little patch to correct the scaling of items displaying the incorrect CP values ZO_CreateStringId("SI_ITEM_ABILITY_SCALING_CHAMPION_POINTS_RANGE", "Scala de <<X:1>> <<2>>0 ate <<X:1>> <<3>>0")
local diff = { ["axisDiffs"] = { ["a3032cd16"] = { ["added"] = { [1] = { ["key"] = "JOY_RX", }, }, ["name"] = "ANT ELEV Knob", }, }, ["keyDiffs"] = { ["d3001pnilu3001cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN3", }, }, ["name"] = "NWS A/R DISC MSL STEP Button", }, ["d3004pnilu3004cd7vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN8", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "ANTI-SKID Switch - PARKING BRAKE/ANTI-SKID", }, ["d3006pnilu3006cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN16", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "Display Management Switch - Up", }, ["d3007pnilu3007cd16vd-1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN18", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "Display Management Switch - Down", }, ["d3008pnilu3008cd16vd-1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN19", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "Display Management Switch - Left", }, ["d3009pnilu3009cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN17", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "Display Management Switch - Right", }, ["d3010pnilu3010cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN16", }, }, ["name"] = "Target Management Switch - Up", }, ["d3011pnilu3011cd16vd-1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN18", }, }, ["name"] = "Target Management Switch - Down", }, ["d3011pnilunilcd2vd0vpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN14", }, }, ["name"] = "STORES CONFIG Switch - CAT III", }, ["d3011pnilunilcd2vd1vpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN13", }, }, ["name"] = "STORES CONFIG Switch - CAT I", }, ["d3012pnilu3012cd16vd-1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN19", }, }, ["name"] = "Target Management Switch - Left", }, ["d3013pnilu3013cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN17", }, }, ["name"] = "Target Management Switch - Right", }, ["d3014pnilu3014cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN20", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "Countermeasures Management Switch - Fwd", }, ["d3015pnilu3015cd16vd-1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN22", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "Countermeasures Management Switch - Aft", }, ["d3016pnilu3016cd16vd-1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN23", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "Countermeasures Management Switch - Left", }, ["d3017pnilu3017cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN21", ["reformers"] = { [1] = "JOY_BTN6", }, }, }, ["name"] = "Countermeasures Management Switch - Right", }, ["d3018pnilu3018cd17vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN27", }, }, ["name"] = "ICP Master Mode Button - A-A", }, ["d3019pnilu3019cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN5", }, }, ["name"] = "Paddle Switch - Depress", }, ["d3019pnilu3019cd17vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN28", }, }, ["name"] = "ICP Master Mode Button - A-G", }, ["d3020pnilu3020cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN1", }, }, ["name"] = "CAMERA/GUN Trigger - FIRST DETENT", }, ["d3021pnilu3021cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN15", }, }, ["name"] = "CAMERA/GUN Trigger - SECOND DETENT", }, ["d3022pnilu3022cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN2", }, }, ["name"] = "WPN REL Button - Depress", }, ["d3024pnilu3024cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN22", }, }, ["name"] = "Transmit Switch - VHF", }, ["d3025pnilu3025cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN20", }, }, ["name"] = "Transmit Switch - UHF", }, ["d3026pnilu3026cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN23", }, }, ["name"] = "Transmit Switch - IFF OUT", }, ["d3027pnilu3027cd16vd1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN21", }, }, ["name"] = "Transmit Switch - IFF IN", }, ["d3030pnilunilcd16vd-1vpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN26", }, }, ["name"] = "DOGFIGHT/Missile Override Switch - MISSILE OVERRIDE", }, ["d3030pnilunilcd16vd0vpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN25", }, }, ["name"] = "DOGFIGHT/Missile Override Switch - CENTER", }, ["d3030pnilunilcd16vd1vpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN24", }, }, ["name"] = "DOGFIGHT/Missile Override Switch - DOGFIGHT", }, ["d3031pnilu3031cd16vd-1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN11", }, }, ["name"] = "SPD BRK Switch - Aft/EXTEND (Momentary)", }, ["d3031pnilunilcd16vd0vpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN12", }, }, ["name"] = "SPD BRK Switch - OFF", }, ["d3032pnilu3032cd17vd-1vpnilvu0"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN29", }, }, ["name"] = "ICP Data Control Switch - RET", }, ["d313pnilu311cdnilvd1vpnilvu1"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN30", }, }, ["name"] = "Throttle - OFF/IDLE", }, ["d430pnilunilcdnilvdnilvpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN9", }, }, ["name"] = "LG Handle - UP", }, ["d431pnilunilcdnilvdnilvpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN10", }, }, ["name"] = "LG Handle - DN", }, ["d74pnilu75cdnilvdnilvpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN4", }, }, ["name"] = "Wheel Brake - ON/OFF", }, ["dnilp32u214cdnilvdnilvpnilvunil"] = { ["name"] = "View Left slow", ["removed"] = { [1] = { ["key"] = "JOY_BTN_POV1_L", }, }, }, ["dnilp33u214cdnilvdnilvpnilvunil"] = { ["name"] = "View Right slow", ["removed"] = { [1] = { ["key"] = "JOY_BTN_POV1_R", }, }, }, ["dnilp34u214cdnilvdnilvpnilvunil"] = { ["name"] = "View Up slow", ["removed"] = { [1] = { ["key"] = "JOY_BTN_POV1_U", }, }, }, ["dnilp35u214cdnilvdnilvpnilvunil"] = { ["name"] = "View Down slow", ["removed"] = { [1] = { ["key"] = "JOY_BTN_POV1_D", }, }, }, ["dnilp93u215cdnilvdnilvpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN_POV1_L", }, }, ["name"] = "TRIM Button - LEFT WING DOWN", }, ["dnilp94u215cdnilvdnilvpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN_POV1_R", }, }, ["name"] = "TRIM Button - RIGHT WING DOWN", }, ["dnilp95u215cdnilvdnilvpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN_POV1_U", }, }, ["name"] = "TRIM Button - NOSE DOWN", }, ["dnilp96u215cdnilvdnilvpnilvunil"] = { ["added"] = { [1] = { ["key"] = "JOY_BTN_POV1_D", }, }, ["name"] = "TRIM Button - NOSE UP", }, }, } return diff
local setmetatable = setmetatable module("tiles") TRIPLE_WORD = "x3W" DOUBLE_WORD = "x2W" TRIPLE_LETTER = "x3L" DOUBLE_LETTER = "x2L" local ptsLookup = {["a"]=1, ["b"]=3, ["c"]=3, ["d"]=2, ["e"]=1, ["f"]=4, ["g"]=2, ["h"]=4, ["i"]=1, ["j"]=8, ["k"]=5, ["l"]=1, ["m"]=3, ["n"]=1, ["o"]=1, ["p"]=3, ["q"]=10, ["r"]=1, ["s"]=1, ["t"]=1, ["u"]=1, ["v"]=4, ["w"]=4, ["x"]=8, ["y"]=4, ["z"]=10, [" "]=0} local Tiles = {} Tiles.__index = Tiles Tiles.__type = "tile" function Tiles:GetContents() return self.Letter end function Tiles:GetMod() return self.Mod end function Tiles:SetContents(c) self.Letter = c end function Tiles:SetMod(m) self.Mod = m end function Tiles:GetScore() if self.Mod == DOUBLE_LETTER then return ptsLookup[self:GetContents() or " "] * 2 elseif self.Mod == TRIPLE_LETTER then return ptsLookup[self:GetContents() or " "] * 3 else return ptsLookup[self:GetContents() or " "] end end function Tiles:GetDisplay() if self:GetContents() then return " "..self:GetContents().." " end return self:GetMod() or " " end function New() local b = {} setmetatable(b,Tiles) return b end
-- Copyright 2022 SmartThings -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local capabilities = require "st.capabilities" --- @type st.zwave.CommandClass local cc = require "st.zwave.CommandClass" --- @type st.zwave.CommandClass.Notification local Notification = (require "st.zwave.CommandClass.Notification")({ version = 3 }) local GLENTRONICS_WATER_LEAK_SENSOR_FINGERPRINTS = { { manufacturerId = 0x0084, productType = 0x0093, productId = 0x0114 } -- glentronics water leak sensor } --- Determine whether the passed device is glentronics water leak sensor --- --- @param driver Driver driver instance --- @param device Device device isntance --- @return boolean true if the device proper, else false local function can_handle_glentronics_water_leak_sensor(opts, driver, device, ...) for _, fingerprint in ipairs(GLENTRONICS_WATER_LEAK_SENSOR_FINGERPRINTS) do if device:id_match(fingerprint.manufacturerId, fingerprint.productType, fingerprint.productId) then return true end end return false end local function notification_report_handler(self, device, cmd) local event if cmd.args.notification_type == Notification.notification_type.POWER_MANAGEMENT then if cmd.args.event == Notification.event.power_management.AC_MAINS_DISCONNECTED then event = capabilities.powerSource.powerSource.battery() elseif cmd.args.event == Notification.event.power_management.AC_MAINS_RE_CONNECTED then event = capabilities.powerSource.powerSource.mains() elseif cmd.args.event == Notification.event.power_management.REPLACE_BATTERY_NOW then event = capabilities.battery.battery(1) elseif cmd.args.event == Notification.event.power_management.BATTERY_IS_FULLY_CHARGED then event = capabilities.battery.battery(100) end elseif cmd.args.notification_type == Notification.notification_type.SYSTEM then if cmd.args.event == Notification.event.system.HARDWARE_FAILURE_MANUFACTURER_PROPRIETARY_FAILURE_CODE_PROVIDED then if cmd.args.event_parameter:byte(1) == 0 then event = capabilities.waterSensor.water.dry() elseif cmd.args.event_parameter:byte(1) == 2 then event = capabilities.waterSensor.water.wet() end end end if (event ~= nil) then device:emit_event(event) end end local function device_added(driver, device) device:emit_event(capabilities.battery.battery(100)) device:emit_event(capabilities.waterSensor.water.dry()) device:emit_event(capabilities.powerSource.powerSource.mains()) end local glentronics_water_leak_sensor = { zwave_handlers = { [cc.NOTIFICATION] = { [Notification.REPORT] = notification_report_handler } }, lifecycle_handlers = { added = device_added }, NAME = "glentronics water leak sensor", can_handle = can_handle_glentronics_water_leak_sensor } return glentronics_water_leak_sensor
return {'pueblo','pueriel','pueriele','pueblos'}
return { gok_cv = { acceleration = 0.242, brakerate = 2.4816, buildcostenergy = 2125, buildcostmetal = 135, builddistance = 180, builder = true, buildpic = "gok_cv.dds", buildtime = 4000, canguard = true, canmove = true, canpatrol = true, canreclamate = 1, canstop = 1, category = "ALL MOBILE SMALL SURFACE UNDERWATER", corpse = "dead", collisionvolumeoffsets = "0 0 0", collisionvolumescales = "24 20 42", collisionvolumetype = "Box", defaultmissiontype = "Standby", description = "Tech Level 1", energymake = 15, energystorage = 15, explodeas = "BIG_UNITEX", footprintx = 3, footprintz = 3, idleautoheal = 5, idletime = 1800, leavetracks = true, losemitheight = 25, maneuverleashlength = 640, mass = 128, maxdamage = 945, maxslope = 16, maxvelocity = 1.85, maxwaterdepth = 255, metalmake = 0.05, metalstorage = 5, mobilestandorders = 1, movementclass = "ATANK3", name = "Amphibious Construction Vehicle", noautofire = false, objectname = "gok_cv", radaremitheight = 25, reclaimspeed = 40, repairspeed = 40, selfdestructas = "BIG_UNIT", shownanospray = false, sightdistance = 253, standingmoveorder = 1, steeringmode = 1, trackoffset = 12, trackstrength = 6, trackstretch = 1, tracktype = "StdTank", trackwidth = 22, turninplace = 1, turninplaceanglelimit = 60, turninplacespeedlimit = 1.2705, turnrate = 435, unitname = "gok_cv", workertime = 80, buildoptions = { [1] = "gok_solar", [2] = "gok_advsolar", [3] = "gok_win", [4] = "gok_win1", [5] = "gok_geo", [6] = "gok_mstor", [7] = "gok_estor", [8] = "gok_mex", [9] = "gok_mex1", [10] = "gok_makr", [11] = "gok_makr1", --[12] = "", [13] = "gok_lab", [14] = "gok_alab", [15] = "gok_ap", [16] = "gok_hp", [17] = "gok_nanotc", [18] = "gok_eyes", [19] = "gok_rad", [20] = "gok_jam", [21] = "gok_juno", [22] = "gok_gate2", [23] = "gok_drag", [24] = "gok_claw", [25] = "gok_llt", [26] = "gok_blackdawn", --[27] = "gok_painless", [28] = "gok_rl", [29] = "gok_cir", [31] = "gok_tide", [32] = "gok_tide1", --[33] = "", [34] = "gok_fmkr", --[35] = "gok_hpns", [36] = "gok_sy", --[37] = "gok_asy", [38] = "gok_fnanotc", [39] = "gok_frad", [40] = "gok_sonar", [41] = "gok_fdrag", [42] = "gok_tl", --[43] = "gok_fhlt", [44] = "gok_frl", }, customparams = { buildpic = "gok_cv.dds", faction = "GOK", }, featuredefs = { dead = { blocking = true, collisionvolumeoffsets = "2.14814758301 -0.0528551147461 0.625", collisionvolumescales = "39.296295166 32.5338897705 48.75", collisionvolumetype = "Box", damage = 1405, description = "Construction Vehicle Wreckage", energy = 0, featuredead = "heap", footprintx = 3, footprintz = 3, metal = 102, object = "gok_cv_DEAD", reclaimable = true, }, heap = { blocking = false, damage = 1757, description = "Construction Vehicle Debris", energy = 0, footprintx = 3, footprintz = 3, metal = 54, object = "3X3C", reclaimable = true, }, }, nanocolor = { [1] = 0.072, [2] = 0.472, [3] = 0.072, }, sfxtypes = { pieceexplosiongenerators = { [1] = "piecetrail0", [2] = "piecetrail1", [3] = "piecetrail2", [4] = "piecetrail3", [5] = "piecetrail4", [6] = "piecetrail6", }, }, sounds = { build = "nanlath1", canceldestruct = "cancel2", repair = "repair1", underattack = "warning1", working = "reclaim1", cant = { [1] = "cantdo4", }, count = { [1] = "count6", [2] = "count5", [3] = "count4", [4] = "count3", [5] = "count2", [6] = "count1", }, ok = { [1] = "varmmove", }, select = { [1] = "varmsel", }, }, }, }
-- Petit script pour faire office de crontab pour les --mesures print("\n 0_cron.lua zf191225.1803 \n") cron1=tmr.create() cron1:alarm(300*1000, tmr.ALARM_AUTO, function() send_data() end)
--[[ ------------------------------------------------------------------------------- Menori @author rozenmad 2022 ------------------------------------------------------------------------------- this module based on CPML - Cirno's Perfect Math Library https://github.com/excessive/cpml/blob/master/modules/intersect.lua --]] --[[-- Intersect. menori.ml.intersect ]] -- @classmod intersect local modules = (...):gsub('%.[^%.]+$', '') .. "." local vec3 = require(modules .. "vec3") local DBL_EPSILON = 2.2204460492503131e-16 local intersect = {} intersect.__index = intersect --- -- See [cpml](https://github.com/excessive/cpml/blob/cf707cb6af59c8be13918ea4ac9478eba9e8a7a0/modules/intersect.lua#L101). -- @tparam table ray -- ray.position is a vec3; -- ray.direction is a vec3. -- @tparam table triangle -- triangle[1] is a vec3; -- triangle[2] is a vec3; -- triangle[3] is a vec3. -- @bool[opt] backface_cull function intersect.ray_triangle(ray, triangle, backface_cull) local e1 = triangle[2] - triangle[1] local e2 = triangle[3] - triangle[1] local h = vec3.cross(ray.direction, e2) local a = vec3.dot(h, e1) -- if a is negative, ray hits the backface if backface_cull and a < 0 then return false end -- if a is too close to 0, ray does not intersect triangle if math.abs(a) <= DBL_EPSILON then return false end local f = 1 / a local s = ray.position - triangle[1] local u = vec3.dot(s, h) * f -- ray does not intersect triangle if u < 0 or u > 1 then return false end local q = vec3.cross(s, e1) local v = vec3.dot(ray.direction, q) * f -- ray does not intersect triangle if v < 0 or u + v > 1 then return false end -- at this stage we can compute t to find out where -- the intersection point is on the line local t = vec3.dot(q, e2) * f -- return rayhit (point, distance, triangle normal) if t >= DBL_EPSILON then return { point = h:set(ray.direction):scale(t):add(ray.position), distance = t, normal = vec3.cross(e1, e2), } end -- ray does not intersect triangle return false end return intersect
local core = require "uuid.core" local skynet = require "skynet" local skynet_timeout = skynet.timeout -- [[uuid format : (33bits timestamp)(6bits harbor)(15bits service)(10bits sequence)]] local uuid = {} local timestamp local service local sequence function uuid.gen () if not service then local sid = core.sid () or error ("init uuid failed") local harbor = skynet.harbor (skynet.self ()) service = ((harbor & 0x3f) << 25) | ((sid & 0xffff) << 10) end if not timestamp then timestamp = (os.time () << 31) | service sequence = 0 skynet_timeout (100, function () timestamp = nil end) end sequence = sequence + 1 assert (sequence < 1024) return (timestamp | sequence) end function uuid.split (id) local timestamp = id >> 31 local harbor = (id & 0x7fffffff) >> 25 local service = (id & 0x1ffffff) >> 10 local sequence = id & 0x3ff return timestamp, harbor, service, sequence end return uuid
----------------------------------- -- Area: Caedarva Mire -- Door: Heavy Iron Gate -- !pos -299 -6 -80 79 ----------------------------------- local ID = require("scripts/zones/Caedarva_Mire/IDs") require("scripts/globals/keyitems") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) if player:hasKeyItem(tpz.keyItem.PERIQIA_ASSAULT_ORDERS) then player:messageSpecial(ID.text.CANNOT_LEAVE, tpz.keyItem.PERIQIA_ASSAULT_ORDERS) elseif player:getZPos() <= -79.1 and player:getZPos() >= -82 then player:messageSpecial(ID.text.STAGING_POINT_DVUCCA) player:messageSpecial(ID.text.IMPERIAL_CONTROL) player:startEvent(122) elseif player:getZPos() >= -77.8 and player:getZPos() <= -75 then player:messageSpecial(ID.text.STAGING_POINT_DVUCCA) player:messageSpecial(ID.text.IMPERIAL_CONTROL) player:startEvent(123) else player:messageSpecial(ID.text.MOVE_CLOSER) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) --[[ if csid == 122 and option == 0 then Todo add function that when entering staging point that a player looses all agro on mobs end]] end
mapFields = require "lib/mapFields" target.play_portal_sound_effect() target.transfer_field(mapFields.getID("MushroomForestField"), 1)
--[[ Unit tests for the file path manipulation module of the Lua/APR binding. Author: Peter Odding <peter@peterodding.com> Last Change: March 27, 2011 Homepage: http://peterodding.com/code/lua/apr/ License: MIT --]] local status, apr = pcall(require, 'apr') if not status then pcall(require, 'luarocks.require') apr = require 'apr' end local helpers = require 'apr.test.helpers' -- Test apr.filepath_root(). {{{1 if apr.platform_get() == 'WIN32' then assert(apr.filepath_root 'c:/foo/bar' == 'c:/') else -- Doesn't really do anything useful on UNIX :-P assert(apr.filepath_root '/foo/bar' == '/') end -- Test apr.filepath_parent(). {{{1 for _, path in ipairs { 'foo/bar/baz', -- clean and simple path with 3 segments 'foo//bar//baz///' -- same path with some empty segments (should be ignored) } do local root = apr.platform_get() == 'WIN32' and 'c:/' or '/' local abs = function(s) return apr.filepath_merge(root, s) end local p1, n1 = apr.filepath_parent(abs(path)) local p2, n2 = apr.filepath_parent(p1) local p3, n3 = apr.filepath_parent(p2) local p4, n4 = apr.filepath_parent(p3) assert(p4 == root and n4 == '') assert(p3 == root and n3 == 'foo') assert(p2 == abs 'foo/' and n2 == 'bar') assert(p1 == abs 'foo/bar/' and n1 == 'baz') end -- Test apr.filepath_name(). {{{1 assert(apr.filepath_name('/usr/bin/lua') == 'lua') local parts = { apr.filepath_name('/home/xolox/.vimrc', true) } assert(#parts == 2 and parts[1] == '.vimrc' and parts[2] == '') parts = { apr.filepath_name('index.html.en', true) } assert(#parts == 2 and parts[1] == 'index.html' and parts[2] == '.en') -- Test apr.filepath_merge(). {{{1 if apr.platform_get() == 'WIN32' then assert(apr.filepath_merge('c:/', 'foo') == 'c:/foo') else assert(apr.filepath_merge('/foo', 'bar') == '/foo/bar') end -- Test apr.filepath_list_split()/merge(). {{{1 -- Based on http://svn.apache.org/viewvc/apr/apr/trunk/test/testpath.c?view=markup. local PSEP, DSEP local p = apr.platform_get() if p == 'WIN32' or p == 'NETWARE' or p == 'OS2' then PSEP, DSEP = ';', '\\' else PSEP, DSEP = ':', '/' end local PX = "" local P1 = "first path" local P2 = "second" .. DSEP .. "path" local P3 = "th ird" .. DSEP .. "path" local P4 = "fourth" .. DSEP .. "pa th" local P5 = "fifthpath" local parts_in = { P1, P2, P3, PX, P4, P5 } local path_in = table.concat(parts_in, PSEP) local parts_out = { P1, P2, P3, P4, P5 } local path_out = table.concat(parts_out, PSEP) -- list_split_multi do local pathelts = assert(apr.filepath_list_split(path_in)) assert(#parts_out == #pathelts) for i = 1, #pathelts do assert(parts_out[i] == pathelts[i]) end end -- list_split_single for i = 1, #parts_in do local pathelts = assert(apr.filepath_list_split(parts_in[i])) if parts_in[i] == '' then assert(#pathelts == 0) else assert(#pathelts == 1) assert(parts_in[i] == pathelts[1]) end end -- list_merge_multi do local pathelts = {} for i = 1, #parts_in do pathelts[i] = parts_in[i] end local liststr = assert(apr.filepath_list_merge(pathelts)) assert(liststr == path_out) end -- list_merge_single for i = 1, #parts_in do local liststr = assert(apr.filepath_list_merge{ parts_in[i] }) if parts_in[i] == '' then assert(liststr == '') else assert(liststr == parts_in[i]) end end
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local choose = {} local cancel = {} local available = {} local grizzlyAdamsConfig = { ranks = { --NOTE: The variable 'name' is not necessary to be declared. I let it so people who wants to change the script will now wich item is each one. huntsMan_rank = { {id=11208, buy=0, sell=50, name='antlers'}, {id=10549, buy=0, sell=100, name='bloody pincers'}, {id=11183, buy=0, sell=35, name='crab pincers'}, {id=10573, buy=0, sell=55, name='cyclops toe'}, {id=10564, buy=0, sell=30, name='frosty ear of a troll'}, {id=11193, buy=0, sell=600, name='hydra head'}, {id=11366, buy=0, sell=80, name='lancer beetle shell'}, {id=10578, buy=0, sell=420, name='mutated bat ear'}, {id=11222, buy=0, sell=400, name='sabretooth'}, {id=11367, buy=0, sell=20, name='sandcrawler shell'}, {id=10547, buy=0, sell=280, name='scarab pincers'}, {id=11365, buy=0, sell=60, name='terramite legs'}, {id=11363, buy=0, sell=170, name='terramite shell'}, {id=11184, buy=0, sell=95, name='terrorbird beak'}, {id=7398, buy=0, sell=500, name='cyclops trophy'}, {id=11315, buy=0, sell=15000, name='draken trophy'}, {id=11336, buy=0, sell=8000, name='lizard trophy'}, {id=7401, buy=0, sell=500, name='minotaur trophy'} }, bigGameHunter_rank = { {id=7397, buy=0, sell=3000, name='deer trophy'}, {id=7400, buy=0, sell=3000, name='lion trophy'}, {id=7394, buy=0, sell=3000, name='wolf trophy'} }, trophyHunter_rank = { {id=7393, buy=0, sell=40000, name='demon trophy'}, {id=7396, buy=0, sell=20000, name='behemoth trophy'}, {id=7399, buy=0, sell=10000, name='dragon lord trophy'}, {id=10518, buy=1000, sell=0, name='demon backpack'}, }, } } local items, data = {} for i = 1, #grizzlyAdamsConfig.ranks.huntsMan_rank do data = grizzlyAdamsConfig.ranks.huntsMan_rank[i] items[data.id] = {id = data.id, buy = data.buy, sell = data.sell, name = ItemType(data.id):getName():lower()} end for i = 1, #grizzlyAdamsConfig.ranks.bigGameHunter_rank do data = grizzlyAdamsConfig.ranks.bigGameHunter_rank[i] items[data.id] = {id = data.id, buy = data.buy, sell = data.sell, name = ItemType(data.id):getName():lower()} end for i = 1, #grizzlyAdamsConfig.ranks.trophyHunter_rank do data = grizzlyAdamsConfig.ranks.trophyHunter_rank[i] items[data.id] = {id = data.id, buy = data.buy, sell = data.sell, name = ItemType(data.id):getName():lower()} end local function greetCallback(cid) local player = Player(cid) if player:getStorageValue(JOIN_STOR) == -1 then npcHandler:setMessage(MESSAGE_GREET, 'Welcome |PLAYERNAME|. Would you like to join the \'Paw and Fur - Hunting Elite\'?') else npcHandler:setMessage(MESSAGE_GREET, 'Welcome back old chap. What brings you here this time?') end return true end local function getTradeItems(t) local list, obj = {} for i = 1, #t do obj = t[i] list[obj.id] = {id = obj.id, buy = obj.buy, sell = obj.sell, name = ItemType(obj.id):getName():lower()} end return list end local function joinTables(old, new) for k, v in pairs(new) do old[k] = v end return old end local function creatureSayCallback(cid, type, msg) if not npcHandler:isFocused(cid) then return false end local player = Player(cid) if msgcontains('trade', msg) then local tradeItems = {} if player:getPawAndFurRank() >= 2 then tradeItems = grizzlyAdamsConfig.ranks.huntsMan_rank if player:getPawAndFurRank() == 4 then tradeItems = joinTables(tradeItems, grizzlyAdamsConfig.ranks.bigGameHunter_rank) elseif player:getPawAndFurRank() == 5 or player:getPawAndFurRank() == 6 then tradeItems = joinTables(tradeItems, grizzlyAdamsConfig.ranks.bigGameHunter_rank) tradeItems = joinTables(tradeItems, grizzlyAdamsConfig.ranks.trophyHunter_rank) end openShopWindow(cid, tradeItems, onBuy, onSell) return npcHandler:say('It\'s my offer.', cid) else return npcHandler:say('You don\'t have any rank.', cid) end elseif (msgcontains('join', msg) or msgcontains('yes', msg)) and npcHandler.topic[cid] == 0 and player:getStorageValue(JOIN_STOR) ~= 1 then player:setStorageValue(JOIN_STOR, 1) npcHandler:say('Great!, now you can start tasks.', cid) --I'm not sure if this is as real tibia. I let this piece of code because it was in the original file. elseif isInArray({'tasks', 'task', 'mission'}, msg:lower()) then local can = player:getTasks() if player:getStorageValue(JOIN_STOR) == -1 then return npcHandler:say('You\'ll have to {join}, to get any {tasks}.',cid) end if #can > 0 then local text = '' local sep = ', ' table.sort(can, function(a, b) return a < b end) local t = 0 local id for i = 1, #can do id = can[i] t = t + 1 if t == #can - 1 then sep = ' and ' elseif t == #can then sep = '.' end text = text .. '{' .. (tasks[id].name or tasks[id].raceName) .. '}' .. sep end npcHandler:say('The current task' .. (#can > 1 and 's' or '') .. ' that you can choose ' .. (#can > 1 and 'are' or 'is') .. ' ' .. text, cid) npcHandler.topic[cid] = 0 else npcHandler:say('I don\'t have any task for you right now.', cid) end elseif msg ~= '' and player:canStartTask(msg) then if #player:getStartedTasks() >= tasksByPlayer then npcHandler:say('Sorry, but you already started ' .. tasksByPlayer .. ' tasks. You can check their {status} or {cancel} a task.', cid) return true end local task = getTaskByName(msg) if task and player:getStorageValue(QUESTSTORAGE_BASE + task) > 0 then return false end npcHandler:say('In this task you must defeat ' .. tasks[task].killsRequired .. ' ' .. tasks[task].raceName .. '. Are you sure that you want to start this task?', cid) choose[cid] = task npcHandler.topic[cid] = 1 elseif msg:lower() == 'yes' and npcHandler.topic[cid] == 1 then player:setStorageValue(QUESTSTORAGE_BASE + choose[cid], 1) player:setStorageValue(KILLSSTORAGE_BASE + choose[cid], 0) npcHandler:say('Excellent! You can check the {status} of your task saying {report} to me. Also you can {cancel} tasks to.', cid) choose[cid] = nil npcHandler.topic[cid] = 0 elseif msgcontains('status', msg) then local started = player:getStartedTasks() if started and #started > 0 then local text = '' local sep = ', ' table.sort(started, (function(a, b) return (a < b) end)) local t = 0 local id for i = 1, #started do id = started[i] t = t + 1 if t == #started - 1 then sep = ' and ' elseif t == #started then sep = '.' end text = text .. 'Task name: ' .. tasks[id].raceName .. '. Current kills: ' .. player:getStorageValue(KILLSSTORAGE_BASE + id) .. '.\n' end npcHandler:say({'The status of your current tasks is:\n' .. text}, cid) else npcHandler:say('You haven\'t started any task yet.', cid) end elseif msgcontains('report', msg) then local started = player:getStartedTasks() local finishedAtLeastOne = false local finished = 0 if started and #started > 0 then local id, reward for i = 1, #started do id = started[i] if player:getStorageValue(KILLSSTORAGE_BASE + id) >= tasks[id].killsRequired then for j = 1, #tasks[id].rewards do reward = tasks[id].rewards[j] local deny = false if reward.storage then if player:getStorageValue(reward.storage[1]) >= reward.storage[2] then deny = true end end if isInArray({REWARD_MONEY, 'money'}, reward.type:lower()) and not deny then player:addMoney(reward.value[1]) elseif isInArray({REWARD_EXP, 'exp', 'experience'}, reward.type:lower()) and not deny then player:addExperience(reward.value[1], true) elseif isInArray({REWARD_ACHIEVEMENT, 'achievement', 'ach'}, reward.type:lower()) and not deny then player:addAchievement(reward.value[1]) elseif isInArray({REWARD_STORAGE, 'storage', 'stor'}, reward.type:lower()) and not deny then player:setStorageValue(reward.value[1], reward.value[2]) elseif isInArray({REWARD_POINT, 'points', 'point'}, reward.type:lower()) and not deny then player:setStorageValue(POINTSSTORAGE, getPlayerTasksPoints(cid) + reward.value[1]) elseif isInArray({REWARD_ITEM, 'item', 'items', 'object'}, reward.type:lower()) and not deny then player:addItem(reward.value[1], reward.value[2]) end if reward.storage then player:setStorageValue(reward.storage[1], reward.storage[2]) end end player:setStorageValue(QUESTSTORAGE_BASE + id, (tasks[id].norepeatable and 2 or 0)) player:setStorageValue(KILLSSTORAGE_BASE + id, -1) player:setStorageValue(REPEATSTORAGE_BASE + id, math.max(player:getStorageValue(REPEATSTORAGE_BASE + id), 0)) player:setStorageValue(REPEATSTORAGE_BASE + id, player:getStorageValue(REPEATSTORAGE_BASE + id) + 1) finishedAtLeastOne = true finished = finished + 1 end end if not finishedAtLeastOne then local started = player:getStartedTasks() if started and #started > 0 then local text = '' local sep = ', ' table.sort(started, (function(a, b) return (a < b) end)) local t = 0 local id for i = 1, #started do id = started[i] t = t + 1 if (t == #started - 1) then sep = ' and ' elseif (t == #started) then sep = '.' end text = text .. '{' .. (tasks[id].name or tasks[id].raceName) .. '}' .. sep end npcHandler:say('The current task' .. (#started > 1 and 's' or '') .. ' that you started ' .. (#started > 1 and 'are' or 'is') .. ' ' .. text, cid) end else npcHandler:say('Awesome! you finished ' .. (finished > 1 and 'various' or 'a') .. ' task' .. (finished > 1 and 's' or '') .. '. Talk to me again if you want to start a {task}.', cid) end else npcHandler:say('You haven\'t started any task yet.', cid) end elseif msg:lower() == 'started' then local started = player:getStartedTasks() if started and #started > 0 then local text = '' local sep = ', ' table.sort(started, (function(a, b) return (a < b) end)) local t = 0 local id for i = 1, #started do id = started[i] t = t + 1 if t == #started - 1 then sep = ' and ' elseif t == #started then sep = '.' end text = text .. '{' .. (tasks[id].name or tasks[id].raceName) .. '}' .. sep end npcHandler:say('The current task' .. (#started > 1 and 's' or '') .. ' that you started ' .. (#started > 1 and 'are' or 'is') .. ' ' .. text, cid) else npcHandler:say('You haven\'t started any task yet.', cid) end elseif msg:lower() == 'cancel' then local started = player:getStartedTasks() local task = getTaskByName(msg) local text = '' local sep = ', ' table.sort(started, (function(a, b) return (a < b) end)) local t = 0 local id for i = 1, #started do id = started[i] t = t + 1 if t == #started - 1 then sep = ' or ' elseif t == #started then sep = '?' end text = text .. '{' .. (tasks[id].name or tasks[id].raceName) .. '}' .. sep end if started and #started > 0 then npcHandler:say('Cancelling a task will make the counter restart. Which of these tasks you want cancel?' .. (#started > 1 and '' or '') .. ' ' .. text, cid) npcHandler.topic[cid] = 2 else npcHandler:say('You haven\'t started any task yet.', cid) end elseif getTaskByName(msg) and npcHandler.topic[cid] == 2 and isInArray(getPlayerStartedTasks(cid), getTaskByName(msg)) then local task = getTaskByName(msg) if player:getStorageValue(KILLSSTORAGE_BASE + task) > 0 then npcHandler:say('You currently killed ' .. player:getStorageValue(KILLSSTORAGE_BASE + task) .. '/' .. tasks[task].killsRequired .. ' ' .. tasks[task].raceName .. '. Cancelling this task will restart the count. Are you sure you want to cancel this task?', cid) else npcHandler:say('Are you sure you want to cancel this task?', cid) end npcHandler.topic[cid] = 3 cancel[cid] = task elseif getTaskByName(msg) and npcHandler.topic[cid] == 1 and isInArray(getPlayerStartedTasks(cid), getTaskByName(msg)) then local task = getTaskByName(msg) if player:getStorageValue(KILLSSTORAGE_BASE + task) > 0 then npcHandler:say('You currently killed ' .. player:getStorageValue(KILLSSTORAGE_BASE + task) .. '/' .. tasks[task].killsRequired .. ' ' .. tasks[task].raceName .. '.', cid) else npcHandler:say('You currently killed 0/' .. tasks[task].killsRequired .. ' ' .. tasks[task].raceName .. '.', cid) end npcHandler.topic[cid] = 0 elseif msg:lower() == 'yes' and npcHandler.topic[cid] == 3 then player:setStorageValue(QUESTSTORAGE_BASE + cancel[cid], -1) player:setStorageValue(KILLSSTORAGE_BASE + cancel[cid], -1) npcHandler:say('You have cancelled the task ' .. (tasks[cancel[cid]].name or tasks[cancel[cid]].raceName) .. '.', cid) npcHandler.topic[cid] = 0 elseif isInArray({'points', 'rank'}, msg:lower()) then if player:getPawAndFurPoints() < 1 then npcHandler:say('At this time, you have ' .. player:getPawAndFurPoints() .. ' Paw & Fur points. You ' .. (player:getPawAndFurRank() == 6 and 'are an Elite Hunter' or player:getPawAndFurRank() == 5 and 'are a Trophy Hunter' or player:getPawAndFurRank() == 4 and 'are a Big Game Hunter' or player:getPawAndFurRank() == 3 and 'are a Ranger' or player:getPawAndFurRank() == 2 and 'are a Huntsman' or player:getPawAndFurRank() == 1 and 'are a Member' or 'haven\'t been ranked yet') .. '.', cid) else npcHandler:say('At this time, you have ' .. player:getPawAndFurPoints() .. ' Paw & Fur points. You ' .. (player:getPawAndFurRank() == 6 and 'are an Elite Hunter' or player:getPawAndFurRank() == 5 and 'are a Trophy Hunter' or player:getPawAndFurRank() == 4 and 'are a Big Game Hunter' or player:getPawAndFurRank() == 3 and 'are a Ranger' or player:getPawAndFurRank() == 2 and 'are a Huntsman' or player:getPawAndFurRank() == 1 and 'are a Member' or 'haven\'t been ranked yet') .. '.', cid) end npcHandler.topic[cid] = 0 elseif isInArray({'special task'}, msg:lower()) then if player:getPawAndFurPoints() >= 90 then -- Tiquandas Revenge 90 points if player:getStorageValue(Storage.KillingInTheNameOf.MissionTiquandasRevenge) == 1 then -- Check if he has already started the task. npcHandler:say('You have already started the task. Go find Tiquandas Revenge and take revenge yourself!', cid) else npcHandler:say({ 'Have you heard about Tiquandas Revenge? It is said that the jungle itself is alive and takes revenge for all the bad things people have done to it. ...', 'I myself believe that there is some truth in this clap trap. Something \'real\' which therefore must have a hideout somewhere. Go find it and take revenge yourself!' }, cid) player:setStorageValue(Storage.KillingInTheNameOf.TiquandasRevengeTeleport, 1) -- Task needed to enter Tiquandas Revenge TP player:setStorageValue(Storage.KillingInTheNameOf.MissionTiquandasRevenge, 1) -- Won't give this task again. end end if player:getPawAndFurPoints() >= 100 then -- Demodras 100 points if player:getStorageValue(Storage.KillingInTheNameOf.MissionDemodras) == 1 then -- Check if he has already started the task. npcHandler:say('You have already started the special task. Find Demodras and kill it.', cid) else npcHandler:say('This task is a very dangerous one. I want you to look for Demodras\' hideout. It might be somewhere under the Plains of Havoc. Good luck, old chap.', cid) player:setStorageValue(Storage.KillingInTheNameOf.DemodrasTeleport, 1) -- Task needed to enter Demodras TP player:setStorageValue(Storage.KillingInTheNameOf.MissionDemodras, 1) -- Won't give this task again. end end npcHandler.topic[cid] = 0 end end local function onBuy(cid, item, subType, amount, ignoreCap, inBackpacks) local player = Player(cid) if not ignoreCap and player:getFreeCapacity() < ItemType(items[item].id):getWeight(amount) then return player:sendTextMessage(MESSAGE_INFO_DESCR, 'You don\'t have enough cap.') end if items[item].buy then player:removeMoney(amount * items[item].buy) player:addItem(items[item].id, amount) return player:sendTextMessage(MESSAGE_INFO_DESCR, 'Bought '..amount..'x '..items[item].name..' for '..items[item].buy * amount..' gold coins.') end return true end local function onSell(cid, item, subType, amount, ignoreCap, inBackpacks) local player = Player(cid) if items[item].sell then player:addMoney(items[item].sell * amount) player:removeItem(items[item].id, amount) return player:sendTextMessage(MESSAGE_INFO_DESCR, 'Sold '..amount..'x '..items[item].name..' for '..items[item].sell * amount..' gold coins.') end return true end npcHandler:setMessage(MESSAGE_FAREWELL, 'Happy hunting, old chap!') npcHandler:setCallback(CALLBACK_GREET, greetCallback) npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:28' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] ZO_PointerBoxTutorial = ZO_TutorialHandlerBase:Subclass() function ZO_PointerBoxTutorial:Initialize(parent) self.tutorial = CreateControlFromVirtual(parent:GetName(), parent, "ZO_PointerBoxTutorialTip", "PointerBoxTip") end do local g_triggerLayoutInfo = {} function ZO_PointerBoxTutorial:RegisterTriggerLayoutInfo(tutorialTrigger, parent, fragment, anchor, optionalParams) g_triggerLayoutInfo[tutorialTrigger] = { parent = parent, fragment = fragment, anchor = anchor, optionalParams = optionalParams, } end function ZO_PointerBoxTutorial:GetTriggerLayoutInfo(tutorialTrigger) return g_triggerLayoutInfo[tutorialTrigger] end end function ZO_PointerBoxTutorial:SuppressTutorials(suppress, reason) -- Suppression is disabled in ZO_PointerBoxTutorial end function ZO_PointerBoxTutorial:DisplayTutorial(tutorialIndex) self.tutorialIndex = tutorialIndex local title, description = GetTutorialInfo(tutorialIndex) local trigger = GetTutorialTrigger(tutorialIndex) local layoutInfo = self:GetTriggerLayoutInfo(trigger) self.tutorial:SetText(description) self.pointerBox = POINTER_BOXES:Acquire() self.pointerBox:SetContentsControl(self.tutorial) self.pointerBox:SetParent(layoutInfo.parent) self.pointerBox:SetCloseable(true) self.pointerBox:SetReleaseOnHidden(true) self.pointerBox:SetOnHiddenCallback(function() self.pointerBox = nil self:RemoveTutorial(tutorialIndex) end) layoutInfo.anchor:Set(self.pointerBox) if layoutInfo.fragment then self.pointerBox:SetHideWithFragment(layoutInfo.fragment) end self:SetOptionalPointerBoxParams(layoutInfo.optionalParams) self.pointerBox:Commit() self.pointerBox:Show() SetTutorialSeen(tutorialIndex) self:SetCurrentlyDisplayedTutorialIndex(tutorialIndex, trigger) end do local DEFAULT_VERTICAL_ALIGNMENT = TEXT_ALIGN_TOP local DEFAULT_HORIZONTAL_ALIGNMENT = TEXT_ALIGN_CENTER local DEFAULT_WIDTH = 290 local DEFAULT_HEIGHT = 0 function ZO_PointerBoxTutorial:SetOptionalPointerBoxParams(optionalParams) if optionalParams then if optionalParams.dimensionConstraintsMinX or optionalParams.dimensionConstraintsMinY or optionalParams.dimensionConstraintsMaxX or optionalParams.dimensionConstraintsMaxY then self.tutorial:SetDimensionConstraints(optionalParams.dimensionConstraintsMinX or 0, optionalParams.dimensionConstraintsMinY or 0, optionalParams.dimensionConstraintsMaxX or 0, optionalParams.dimensionConstraintsMaxY or 0) else self.tutorial:SetDimensions(optionalParams.width or DEFAULT_WIDTH, optionalParams.height or DEFAULT_HEIGHT) end self.tutorial:SetVerticalAlignment(optionalParams.verticalAlignment or DEFAULT_VERTICAL_ALIGNMENT) self.tutorial:SetHorizontalAlignment(optionalParams.horizontalAlignment or DEFAULT_HORIZONTAL_ALIGNMENT) else self.tutorial:SetDimensionConstraints(0, 0, 0, 0) self.tutorial:SetDimensions(DEFAULT_WIDTH, DEFAULT_HEIGHT) self.tutorial:SetVerticalAlignment(DEFAULT_VERTICAL_ALIGNMENT) self.tutorial:SetHorizontalAlignment(DEFAULT_HORIZONTAL_ALIGNMENT) end end end function ZO_PointerBoxTutorial:OnDisplayTutorial(tutorialIndex, priority) if tutorialIndex ~= self:GetCurrentlyDisplayedTutorialIndex() then if self:CanShowTutorial() then self:DisplayTutorial(tutorialIndex) end end end function ZO_PointerBoxTutorial:SetCurrentlyDisplayedTutorialIndex(currentlyDisplayedTutorialIndex, currentlyDisplayedTutorialTrigger) self.currentlyDisplayedTutorialIndex = currentlyDisplayedTutorialIndex self.currentlyDisplayedTutorialTrigger = currentlyDisplayedTutorialTrigger end function ZO_PointerBoxTutorial:RemoveTutorialByTrigger(tutorialTrigger) if self.currentlyDisplayedTutorialTrigger == tutorialTrigger then self:RemoveTutorial(self:GetCurrentlyDisplayedTutorialIndex()) end end function ZO_PointerBoxTutorial:RemoveTutorial(tutorialIndex) if self:GetCurrentlyDisplayedTutorialIndex() == tutorialIndex then self:SetCurrentlyDisplayedTutorialIndex(nil) if self.pointerBox then self.pointerBox:Hide() end end end function ZO_PointerBoxTutorial:GetTutorialType() return TUTORIAL_TYPE_POINTER_BOX end function ZO_PointerBoxTutorial:ClearAll() self:SetCurrentlyDisplayedTutorialIndex(nil) end
--[[ TheNexusAvenger Wrapped plugin instance with additional functionality. --]] local INSTANCE_CREATION_PRESETS = { Frame = { BackgroundColor3 = Enum.StudioStyleGuideColor.MainBackground, BorderColor3 = Enum.StudioStyleGuideColor.Border, BorderSizePixel = 0, }, ImageButton = { BackgroundColor3 = Enum.StudioStyleGuideColor.Button, BorderColor3 = Enum.StudioStyleGuideColor.ButtonBorder, }, ScrollingFrame = { BackgroundColor3 = Enum.StudioStyleGuideColor.MainBackground, BorderColor3 = Enum.StudioStyleGuideColor.Border, ScrollBarThickness = 12, ScrollBarImageColor3 = Enum.StudioStyleGuideColor.ScrollBar, BottomImage = "rbxasset://textures/AvatarEditorImages/LightPixel.png", MidImage = "rbxasset://textures/AvatarEditorImages/LightPixel.png", TopImage = "rbxasset://textures/AvatarEditorImages/LightPixel.png", }, TextLabel = { BackgroundTransparency = 1, TextColor3 = Enum.StudioStyleGuideColor.MainText, TextXAlignment = Enum.TextXAlignment.Left, Font = Enum.Font.SourceSans, TextSize = 14, }, TextButton = { BackgroundColor3 = Enum.StudioStyleGuideColor.Button, BorderColor3 = Enum.StudioStyleGuideColor.ButtonBorder, BorderSizePixel = 1, TextColor3 = Enum.StudioStyleGuideColor.ButtonText, Font = Enum.Font.SourceSans, TextSize = 14, }, TextBox = { BackgroundColor3 = Enum.StudioStyleGuideColor.InputFieldBackground, BorderColor3 = Enum.StudioStyleGuideColor.InputFieldBorder, BorderSizePixel = 1, TextColor3 = Enum.StudioStyleGuideColor.MainText, PlaceholderColor3 = Enum.StudioStyleGuideColor.DimmedText, TextXAlignment = Enum.TextXAlignment.Left, Font = Enum.Font.SourceSans, TextSize = 14, ClearTextOnFocus = false, ClipsDescendants = true, }, } local NexusPluginComponents = require(script.Parent.Parent) local NexusWrappedInstance = NexusPluginComponents:GetResource("NexusWrappedInstance") local PluginColor = NexusPluginComponents:GetResource("Base.PluginColor") local PluginInstance = NexusWrappedInstance:Extend() PluginInstance:SetClassName("PluginInstance") PluginInstance.ColorProperties = {} pcall(function() PluginInstance.Settings = settings() end) --[[ Creates the plugin instance. --]] function PluginInstance:__new(InstanceToWrap) self:InitializeSuper(InstanceToWrap) --Set up the color property storage. self:DisableChangeReplication("WrappedClassName") local WrappedInstance = self:GetWrappedInstance() local WrappedClassName = WrappedInstance.ClassName self.WrappedClassName = WrappedClassName if not self.ColorProperties[WrappedClassName] then self.ColorProperties[WrappedClassName] = {} end local ColorProperties = self.ColorProperties[WrappedClassName] --Connect colors being changed. self:AddGenericPropertyValidator({ ValidateChange = function(_, _, Name, Value) --Determine if the property is a Color3. if ColorProperties[Name] == nil then xpcall(function() --Store if the property is a Color3. ColorProperties[Name] = (typeof(WrappedInstance[Name]) == "Color3") end, function() --Store false (failed to index). ColorProperties[Name] = false end) end --Return the PluginColor or the original value. if ColorProperties[Name] and typeof(Value) ~= "Color3" and (typeof(Value) == "string" or typeof(Value) == "EnumItem") then return PluginColor.new(Value) end return Value end, }) --Connect updating the themes. self:DisableChangeReplication("Settings") if self.Settings then table.insert(self.EventsToDisconnect, self.Settings.Studio.ThemeChanged:Connect(function() for PropertyName, IsColorProperty in pairs(ColorProperties) do if IsColorProperty then local Color = self[PropertyName] if typeof(Color) == "table" and Color.IsA and Color:IsA("PluginColor") then self[PropertyName] = PluginColor.new(Color.ColorEnum, Color.ModiferEnum) end end end end)) end --Set the defaults. if typeof(InstanceToWrap) == "string" and INSTANCE_CREATION_PRESETS[WrappedClassName] then for Name, Value in pairs(INSTANCE_CREATION_PRESETS[WrappedClassName]) do self[Name] = Value end end end --[[ Updates the modifier of a plugin color. If a PluginColor is not in use, there will be no effect. --]] function PluginInstance:SetColorModifier(PropertyName, Modifier) Modifier = Modifier or Enum.StudioStyleGuideModifier.Default --Return if the color isn't a PluginColor. local Color = self[PropertyName] if not (typeof(Color) == "table" and Color.IsA and Color:IsA("PluginColor")) then return end --Return if the modifer is the same. if Color.ModiferEnum == Modifier then return end --Change the color. self[PropertyName] = PluginColor.new(Color.ColorEnum, Modifier) end --[[ Sets all the color modifiers of the plugin colors. --]] function PluginInstance:SetAllColorModifiers(Modifier) for PropertyName, IsColorProperty in pairs(self.ColorProperties[self.WrappedClassName]) do if IsColorProperty then self:SetColorModifier(PropertyName, Modifier) end end end --[[ Converts a property for replicating to the wrapped instance. --]] function PluginInstance:ConvertProperty(PropertyName, PropertyValue) --Return the color if a PluginColor is used. if typeof(PropertyValue) == "table" and PropertyValue.IsA and PropertyValue:IsA("PluginColor") then return PropertyValue:GetColor() end --Return the super result. return self.super:ConvertProperty(PropertyName, PropertyValue) end return PluginInstance
-- huangxin <3203317@qq.com> redis.replicate_commands(); local db = KEYS[1]; local server_id = KEYS[2]; local channel_id = KEYS[3]; local group_uuid = KEYS[4]; local group_type = KEYS[5]; redis.call('SELECT', db); -- local user_id = redis.call('GET', server_id ..'::'.. channel_id); if (false == user_id) then return 'invalid_user_id'; end; -- -- local exist = redis.call('EXISTS', 'prop::groupType::'.. group_type); -- if (1 ~= exist) then return 'invalid_group_type'; end; -- 找一个空闲的群组 local idle_group = redis.call('SPOP', 'idle::groupType::'.. group_type); if (false == idle_group) then local total_players = redis.call('HGET', 'cfg', 'group_type_'.. group_type ..'_total_players'); if (false == total_players) then return 'invalid_group_type'; end; for i=1, tonumber(total_players) do redis.call('SADD', 'idle::groupType::'.. group_type, group_uuid ..'::'.. i); end; -- 为新创建的群组设置群组类型 local total_visitors = redis.call('HGET', 'cfg', 'group_type_'.. group_type ..'_total_visitors'); local min_run = redis.call('HGET', 'cfg', 'group_type_'.. group_type ..'_min_run'); local capacity = redis.call('HGET', 'cfg', 'group_type_'.. group_type ..'_capacity'); local free_swim_time = redis.call('HGET', 'cfg', 'group_type_'.. group_type ..'_free_swim_time'); local bullet_lv_max = redis.call('HGET', 'cfg', 'group_type_'.. group_type ..'_bullet_lv_max'); local bullet_lv_min = redis.call('HGET', 'cfg', 'group_type_'.. group_type ..'_bullet_lv_min'); local consume_freeze = redis.call('HGET', 'cfg', 'group_type_'.. group_type ..'_consume_freeze'); local profit_loss_rate = redis.call('HGET', 'cfg', 'group_type_'.. group_type ..'_profit_loss_rate'); redis.call('HMSET', 'prop::group::'.. group_uuid, 'id', group_uuid, 'type', group_type, 'total_players', total_players, 'total_visitors', total_visitors, 'min_run', min_run, 'capacity', capacity, 'free_swim_time', free_swim_time, 'bullet_lv_max', bullet_lv_max, 'bullet_lv_min', bullet_lv_min, 'consume_freeze', consume_freeze, 'profit_loss_rate', profit_loss_rate); -- 再次找一个空闲的群组 idle_group = redis.call('SPOP', 'idle::groupType::'.. group_type); -- 又没有找到 if (false == idle_group) then return 'non_idle_group'; end; end; -- local group_id, group_pos_id = string.match(idle_group, '(.*)::(.*)'); -- 把用户放到这个座位上 redis.call('HSET', 'pos::group::'.. group_type ..'::'.. group_id, group_pos_id, user_id ..'::0'); -- 获取现在座位上的所有人 local group_pos = redis.call('HGETALL', 'pos::group::'.. group_type ..'::'.. group_id); if (0 == #group_pos) then return 'invalid_group_pos'; end; -- redis.call('HMSET', 'prop::user::'.. user_id, 'group_id', group_id, 'group_pos_id', group_pos_id); local arr1 = {}; local user_info = {}; for i=2, #group_pos, 2 do local u = string.match(group_pos[i], '(.*)::(.*)'); table.insert(arr1, redis.call('HGET', 'prop::user::'.. u, 'server_id')); table.insert(arr1, redis.call('HGET', 'prop::user::'.. u, 'channel_id')); -- table.insert(user_info, redis.call('HGET', 'prop::user::'.. u, 'extend_data')); table.insert(user_info, redis.call('HGET', 'prop::user::'.. u, 'open_time')); end; -- local arr2 = {}; table.insert(arr2, user_info); table.insert(arr2, group_pos); local result = {}; table.insert(result, arr1); table.insert(result, arr2); return result;
if SERVER then AddCSLuaFile() resource.AddFile("materials/vgui/ttt/dynamic/roles/icon_cap.vmt") end function ROLE:PreInitialize() self.color = Color(136, 81, 50, 255) self.abbr = "cap" self.score.surviveBonusMultiplier = 0.5 self.score.timelimitMultiplier = -0.5 self.score.killsMultiplier = 2 self.score.teamKillsMultiplier = -8 self.score.bodyFoundMuliplier = 0 self.unknownTeam = true self.preventWin = not GetConVar("ttt_pir_win_alone"):GetBool() self.avoidTeamIcons = false self.notSelectable = true self.defaultTeam = TEAM_PIRATE self.defaultEquipment = SPECIAL_EQUIPMENT self.conVarData = { credits = 0, shopFallback = SHOP_DISABLED } end function ROLE:Initialize() roles.SetBaseRole(self, ROLE_PIRATE) end function ROLE:GiveRoleLoadout(ply, isRoleChange) if not isRoleChange then ply:SetRole(ROLE_PIRATE, TEAM_PIRATE) SendFullStateUpdate() end end function ROLE:RemoveRoleLoadout(ply, isRoleChange) if not IsValid(ply.pir_contract) then return end local contract = ply.pir_contract local master = contract:GetOwner() if IsValid(master) then net.Start("TTT2PirContractTerminatedMaster") net.WriteEntity(ply) net.Send(master) master.is_pir_master = false ply.pirate_master = nil end contract:Remove() for _, pir in ipairs(player.GetAll()) do if pir:GetBaseRole() == ROLE_PIRATE then pir:UpdateTeam(TEAM_PIRATE) end end PIRATE.preventWin = not GetConVar("ttt_pir_win_alone"):GetBool() PIRATE_CAPTAIN.preventWin = not GetConVar("ttt_pir_win_alone"):GetBool() PIRATE.unknownTeam = false PIRATE_CAPTAIN.unknownTeam = false SendFullStateUpdate() ChooseNewCaptain() end
local ReplicatedStorage = game:GetService("ReplicatedStorage") --- local state = require(ReplicatedStorage:FindFirstChild("state")) --- return function() it("should have a public API", function() expect(state.table.append).to.be.a("function") expect(state.table.getn).to.be.a("function") expect(state.table.insert).to.be.a("function") expect(state.table.remove).to.be.a("function") end) describe("state.table.getn", function() it("should correctly determine the length of a drafted table", function() local baseState = { test = {"A", { 1 }, 3, 4} } state.produce(baseState, function(draftState) expect(#draftState.test).to.never.equal(#baseState.test) expect(state.table.getn(draftState.test)).to.equal(#baseState.test) end) end) it("should interpret state.undefined correctly", function() local baseState = { test = {"A", { 1 }, 3, 4} } state.produce(baseState, function(draftState) draftState.test[3] = nil expect(#draftState.test).to.never.equal(#baseState.test) expect(state.table.getn(draftState.test)).to.equal(2) end) end) it("should be equivalent to table.getn for non-draft tables", function() local t = {"A", { 1 }, nil , 4} expect(state.table.getn(t)).to.equal(#t) end) end) describe("state.table.insert", function() it("should correctly insert values into a drafted table", function() local baseState = { test = {1, 2, 3, 4} } state.produce(baseState, function(draftState) state.table.insert(draftState.test, 1, 0) expect(draftState.test[1]).to.equal(0) end) end) it("should interpret state.undefined correctly", function() local baseState = { test = {1, 2, 3, 4} } state.produce(baseState, function(draftState) draftState.test[3] = nil state.table.insert(draftState.test, state.table.getn(draftState.test) + 1, 0) expect(draftState.test[3]).to.equal(0) end) end) it("should work equivalent to table.insert for non-draft tables", function() local t1 = {1, 2, nil, 4} local t2 = {1, 2, nil, 4} state.table.insert(t1, 3, 0) table.insert(t2, 3, 0) expect(t1[3]).to.equal(t2[3]) expect(t1[3]).to.equal(0) expect(t2[3]).to.equal(0) end) end) describe("state.table.append", function() it("should correctly append values onto a drafted table", function() local baseState = { test = {1, 2, 3, 4} } state.produce(baseState, function(draftState) state.table.append(draftState.test, 5) expect(draftState.test[5]).to.equal(5) end) end) it("should interpret state.undefined correctly", function() local baseState = { test = {1, 2, 3, 4} } state.produce(baseState, function(draftState) draftState.test[4] = nil state.table.append(draftState.test, 5) expect(draftState.test[4]).to.equal(5) end) end) it("should work equivalent to table.insert for non-draft tables", function() local t1 = {1, 2, 3} local t2 = {1, 2, 3} state.table.append(t1, 4) table.insert(t2, 4) expect(t1[4]).to.equal(t2[4]) expect(t1[4]).to.equal(4) expect(t2[4]).to.equal(4) end) end) describe("state.table.remove", function() it("should correctly remove values from a drafted table", function() local baseState = { test = {1, 2, 3, 4} } state.produce(baseState, function(draftState) state.table.remove(draftState.test, 1) expect(draftState.test[1]).to.equal(2) state.table.remove(draftState.test) expect(draftState.test[3]).to.equal(nil) expect(draftState.test[4]).to.equal(nil) end) end) it("should work equivalent to table.remove for non-draft tables", function() local t1 = {1, 2, 3, 4} local t2 = {1, 2, 3, 4} state.table.remove(t1, 3) table.remove(t2, 3) expect(t1[3]).to.equal(t2[3]) expect(t1[3]).to.equal(4) end) end) end
DarkRP.PLAYER.newHungerData = DarkRP.stub{ name = "newHungerData", description = "Create the initial hunger data (called on PlayerInitialSpawn).", parameters = { }, returns = { }, metatable = DarkRP.PLAYER } DarkRP.PLAYER.hungerUpdate = DarkRP.stub{ name = "hungerUpdate", description = "Makes the player slightly more hungry. Called in a timer by default.", parameters = { }, returns = { }, metatable = DarkRP.PLAYER }
local SyntaxKind = require("lunar.ast.syntax_kind") local SyntaxNode = require("lunar.ast.syntax_node") local FunctionCallExpression = setmetatable({}, { __index = SyntaxNode, }) FunctionCallExpression.__index = setmetatable({}, SyntaxNode) function FunctionCallExpression.new(base, arguments) return FunctionCallExpression.constructor(setmetatable({}, FunctionCallExpression), base, arguments) end function FunctionCallExpression.constructor(self, base, arguments) SyntaxNode.constructor(self, SyntaxKind.function_call_expression) self.base = base self.arguments = arguments return self end return FunctionCallExpression
local AceLocale = LibStub("AceLocale-3.0") local is_default, errors_turned_of_on_unknown_locale = true, true local L = AceLocale:NewLocale( "ServTr", "enUS", is_default, errors_turned_of_on_unknown_locale) if not L then return end --global things L[" loaded. Type /servtr for help."] = true -- article for connecting item with random bonus: sword of the Whale L[" of "] = true --databases L["areatrigger_teleport_desc"] = "Database with messages when the requirements for entering the dungeon are not met." L["creature_ai_texts_desc"] = "Database of NPC/Creature phrase." L["creature_Name_desc"] = "Database of NPC name." L["creature_SubName_desc"] = "Database of NPC signature." L["dbscript_string_desc"] = "Database of NPC/Creature phrase." L["gameobject_desc"] = "Database of object names." L["gossip_menu_option_desc"] = "Database of dialog items with the NPC." L["gossip_texts_desc"] = "Database of dialog items with the NPC." L["item_description_desc"] = "Database of signature items." L["item_name_desc"] = "Database of item names." L["mangos_string_desc"] = "Database of MaNGOS strings." L["npc_text_desc"] = "Database of NPC text." L["page_text_desc"] = "Database of books." L["points_of_interest_desc"] = "Database of points of interest" L["questgiver_greeting_desc"] = "Database of NPC text." L["quest_details_desc"] = "Database of details quest." L["quest_EndText_desc"] = "Database of objectives quest." L["quest_objectives_desc"] = "Database of objectives quest." L["quest_ObjectiveText_desc"] = "Database of objective text quest." L["quest_OfferRewardText_desc"] = "Database of progress texts quest." L["quest_RequestItemsText_desc"] = "Database of progress texts quest." L["quest_title_desc"] = "Database of title quest." L["script_texts_desc"] = "Database of NPC/Creature phrase." --dependences L["Tooltips"] = true L["Tooltips_desc"] = "Setting up the translation of tooltips." L["Quests"] = true L["Quests_desc"] = "Setting up the translation of quests." L["QuestLogFrame_desc"] = "QuestLog Frame." L["QuestFrame_desc"] = "Quest Frame." L["QuestWatchFrame_desc"] = "Quest Watch Frame." L["Items"] = true L["Items_desc"] = "Setting up the translation of items." L["NPC"] = true L["NPC_desc"] = "Setting up the translation of NPC." L["Books"] = true L["Books_desc"] = "Setting up the translation of books." L["Phrases/Messages"] = true L["Phrases/Messages_desc"] = "Setting up the translation of phrases and messages in ChatFrame." L["Other"] = true L["Other_desc"] = "What does not fall into categories." --blizzard functions L["GameTooltip_desc"] = "Usual tooltips." L["ItemRefTooltip_desc"] = "Tooltip when you click on its link." L["ShoppingTooltip1_desc"] = "Tooltip when comparing the current item to the equipment." L["ShoppingTooltip2_desc"] = "Tooltip when comparing the current item to the equipment, if there are two. (For example, weapons in left and right hands or two trinkets)." L["AuctionFrameAuctions_Update_desc"] = "Frame of lot auction." L["AuctionFrameBid_Update_desc"] = "Frame of bid auction." L["AuctionFrameBrowse_Update_desc"] = "Frame of browse auction." L["AuctionSellItemButton_OnEvent_desc"] = "Item for sale." L["BankFrame_OnEvent_desc"] = "Bank frame." L["ChatFrameEditBox:AddMessage_desc"] = "Panel for entering messages into the chat." L["ChatFrame_OnEvent_desc"] = "Chat frame." L["ClassTrainerFrame_Update_desc"] = "Class trainer frame." L["CraftFrame_SetSelection_desc"] = "Profession frame." L["GossipFrameUpdate_desc"] = "Gossip frame." L["GroupLootFrame_OnShow_desc"] = "Roll frame." L["GuildRegistrar_OnShow_desc"] = "Guild registration frame." L["InboxFrame_Update_desc"] = "Input mail frame." L["ItemTextFrame_OnEvent_desc"] = "Book reading frame." L["LootFrame_Update_desc"] = "Loot frame." L["MerchantFrame_UpdateBuybackInfo_desc"] = "Frame of buyout frame of merchant." L["MerchantFrame_UpdateMerchantInfo_desc"] = "Frame of purchase of merchant." L["OpenMail_Update_desc"] = "Frame of open letter." L["QuestInfo_ShowRewards"] = "Items in the quest log frame with description and completion quest text of NPC." L["QuestFrameDetailPanel_OnShow_desc"] = "Frame with quest descriptions of NPC." L["QuestFrameGreetingPanel_OnShow_desc"] = "Frame with the text of the NPC greeting." L["QuestFrameItems_Update_desc"] = "Items in the quest dialog frame with description and completion quest text of NPC." L["QuestFrameProgressItems_Update_desc"] = "Items in the frame with the progress quest text of NPC." L["QuestFrameProgressPanel_OnShow_desc"] = "Frame with the progress text of NPC." L["QuestFrameRewardPanel_OnShow_desc"] = "Frame with quest completion text of NPC." L["QuestFrame_SetPortrait_desc"] = "Frame with the name of the NPC giving the quest." L["QuestLog_UpdateQuestDetails_desc"] = "Description of quests in the QuestLog." L["QuestLog_Update_desc"] = "Quest title in the QuestLog." L["QuestWatch_Update_desc"] = "Quest tracking frame." L["SendMailFrame_Update_desc"] = "Mail sending frame." L["StaticPopup_Show_desc"] = "Pop-up message frame." L["TabardFrame_OnEvent_desc"] = "Tabard setting frame." L["TaxiFrame_OnEvent_desc"] = "Flight frame." L["TradeFrame_UpdatePlayerItem_desc"] = "Trade frame for player items." L["TradeFrame_UpdateTargetItem_desc"] = "Trade frame for target's items." L["TradeSkillFrame_SetSelection_desc"] = "Frame of standart professions (First Aid etc)." L["UIErrorsFrame_OnEvent_desc"] = "Pop-up messages at the top part of screen (red errors, or yellow info message)." L["UnitFrame_Update_desc"] = "Unit frame." --api functions L["Container/Bag Functions"] = true L["GetBagName_desc"] = "Returns the name of one of the player's bags." L["Loot Functions"] = true L["GetLootRollItemInfo_desc"] = "Returns information about an item currently up for loot rolling." L["GetLootSlotInfo_desc"] = "Returns icon path, item name, and item quantity for the item in the given loot window." L["Gossip Functions"] = true L["GetGossipText_desc"] = "Returns greeting or other text to be displayed in an NPC dialog." L["Mail Functions"] = true L["GetInboxInvoiceInfo_desc"] = "Returns auction house invoice information for a mail." L["Merchant Functions"] = true L["GetMerchantItemInfo_desc"] = "Returns information about an item available for purchase from a vendor." L["Trade Functions"] = true L["GetTradePlayerItemInfo_desc"] = "Returns information about items in the player trade window." L["GetTradeTargetItemInfo_desc"] = "Returns information about items in the target's trade window." L["Training Functions"] = true L["GetTrainerGreetingText_desc"] = "Returns the current trainer's greeting text." L["Quest Functions"] = true L["GetGreetingText_desc"] = "Returns the greeting text displayed for quest NPCs with multiple quests." L["GetTitleText_desc"] = "Retrieves the title of the quest while talking to the NPC about it." L["GetObjectiveText_desc"] = "Gets the objective of the current quest." L["GetQuestText_desc"] = "Gets the description of the current quest." L["GetProgressText_desc"] = "Returns the quest progress text presented by a questgiver." L["GetRewardText_desc"] = "Returns questgiver dialog to be displayed when completing a quest." L["GetQuestItemInfo_desc"] = "Returns basic information about the quest items." L["GetQuestLogTitle_desc"] = "Returns the string which is associated with the specific QuestLog quest_title in the game." L["GetQuestLogLeaderBoard_desc"] = "Gets information about the objectives for a quest." L["GetQuestLogQuestText_desc"] = "Returns the description and objectives required for the specified quest." L["GetQuestLogChoiceInfo_desc"] = "Returns a bunch of data about a quest reward choice from the quest log." L["GetQuestLogRewardInfo_desc"] = "Returns a pile of reward item info." L["Unit Functions"] = true L["GetUnitName_desc"] = "Returns name of the unit." --other options L["Is compensated with following API hooks:"] = true L["Databases"] = true L["Global database switching.\nATTENTION! If you disable the databases in this menu, they will be disabled throughout the addon and will not be used. Use this menu to quickly enable / disable databases."] = true L["Translation"] = true L["Select categories to translate."] = true L["Refresh intervals"] = true L["Set the refresh interval."] = true L["Nameplates"] = true L["Set refresh interval for nameplates. Zero value will stop updating and translating."] = true L["Bubbles"] = true L["Set refresh interval for chat bubbles. Zero value will stop updating and translating."] = true L["API localization"] = true L["Full api translation can translate many things in other addons, but addons, which works with databases, containing original language info won't work."] = true --you should create dir for your language (like ruRU) and make same prefixes of all tables names, like ruRU_creature_ai_texts L["Language"] = true L["Set language."] = true L["Databases loading"] = true L["Config speed depending on the hardware capabilities."] = true L["Delay"] = true L["Set delay after after loading the interface and addons.\n(non-negative number of seconds)"] = true L["Speed"] = "Скорость" L["Set delay between processing of the database blocks."] = true L["<Type seconds >= 0.>"] = true L["Size of block"] = true L["Set size of block that is processed at a time.\n(non-negative number of database strings)"] = true if GetLocale() == "enUS" then EMOTE_LIST = {} strlower_hook = function(letter) return nil end BINDING_NAME_TRANSLATE = "Toggle translation" end
local M = {} local defaults = { -- opts for the handlers client = { hover = { use_split = false, split_size = '30%', auto_resize_split = false, split_position = 'bottom', with_history = false, use_as_popup = false, }, }, -- opts for nvim-lspconfig server = {}, autostart_semantic = true, use_default_semantic_hl_groups = true, default_regexp_syntax = true, } M.options = {} M.semantic_refresh = false M.split_open = false M.split_history = false function M.setup(options) M.options = vim.tbl_deep_extend('force', {}, defaults, options or {}) if M.options.autostart_semantic then M.semantic_refresh = true end if M.options.client.hover.use_split and not M.options.client.hover.use_as_popup then M.split_open = true end vim.g.idris2_regexp_syntax_enabled = options.default_regexp_syntax end return M
local dire = "ChibbiScripts/" local url = "https://raw.githubusercontent.com/chibbi/ComputerCraftScripts/main/" if(fs.exists(dire)) then fs.delete(dire) end fs.makeDir(dire) local primaryRequest = http.get(url .. "scriptList.txt") local allFiles = {} local temp = primaryRequest.readAll() temp:gsub(".",function(c) table.insert(allFiles,c) end) for i = 1, #allFiles, 1 do local fileName = allFiles[i] local request = http.get(url .. fileName) local err, file = fs.open(dire .. fileName, "w") -- => FIXME: file doesn't exist yet file.write(request.readAll()) end
object_tangible_storyteller_prop_hoth_pr_hoth_icicle_03 = object_tangible_storyteller_prop_hoth_shared_pr_hoth_icicle_03:new { } ObjectTemplates:addTemplate(object_tangible_storyteller_prop_hoth_pr_hoth_icicle_03, "object/tangible/storyteller/prop/hoth/pr_hoth_icicle_03.iff")
KiwiItemInfo.Locale["ptBR"] = { ["TOOLTIP_UNIT"] = "Unidade: ", ["TOOLTIP_STACK"] = "Pilha:", ["TOOLTIP_ILVL"] = "iLvl ", ["TOOLTIP_PRY_EQUIP"] = "EQUIPAR: ", ["TOOLTIP_PRY_USE"] = "USO: ", ["TOOLTIP_PRY_CHANCE"] = "CHANCE AO ACERTAR: ", ["TOOLTIP_CMP_AGILITY"] = "[+-]%d+%s[AGILIDADE]+", ["TOOLTIP_PRY_AGILITY"] = "AGILIDADE", ["TOOLTIP_IC_AGILITY"] = "Agilidade", ["TOOLTIP_CMP_STAMINA"] = "[+-]%d+%s[VIGOR]+", ["TOOLTIP_PRY_STAMINA"] = "VIGOR", ["TOOLTIP_IC_STAMINA"] = "Vigor", ["TOOLTIP_CMP_STRENGTH"] = "[+-]%d+%s[FORÇA]+", ["TOOLTIP_PRY_STRENGTH"] = "FORÇA", ["TOOLTIP_IC_STRENGTH"] = "Força", ["TOOLTIP_CMP_INTELLECT"] = "[+-]%d+%s[INTELECTO]+", ["TOOLTIP_PRY_INTELLECT"] = "INTELECTO", ["TOOLTIP_IC_INTELLECT"] = "Intelecto", ["TOOLTIP_CMP_SPIRIT"] = "[+-]%d+%s[ESPÍRITO]+", ["TOOLTIP_PRY_SPIRIT"] = "ESPÍRITO", ["TOOLTIP_IC_SPIRIT"] = "Espírito", ["TOOLTIP_CMP_ARMOR"] = "%d+%s[ARMADURA]+", ["TOOLTIP_PRY_ARMOR"] = "ARMADURA", ["TOOLTIP_IC_ARMOR"] = "Armadura", ["TOOLTIP_CMP_BLOCK"] = "[BLOQUEIO DE]+%s%d+", ["TOOLTIP_PRY_BLOCK"] = "BLOQUEIO DE", ["TOOLTIP_IC_BLOCK"] = "Bloqueio de", ["TOOLTIP_CMP_DURABILITY"] = "[DURABILIDADE]+%s%d+%s/%s%d+", ["TOOLTIP_PRY_DURABILITY"] = "DURABILIDADE", ["TOOLTIP_IC_DURABILITY"] = "Durabilidade", ["TOOLTIP_CMP_DPS"] = "%(%d+%.%d+%s[DE DANO POR SEGUNDO]+%)", ["TOOLTIP_PRY_DPS"] = "DE DANO POR SEGUNDO", ["TOOLTIP_IC_DPS"] = "DPS", ["TOOLTIP_CMP_DAMAGE"] = "%d+%s%-%s%d+%s[DE DANO]+", ["TOOLTIP_PRY_DAMAGE"] = "DE DANO", ["TOOLTIP_IC_DAMAGE"] = "de dano", ["TOOLTIP_CMP_DODGE"] = "[+-]%d+%%%s[ESQUIVA]+", ["TOOLTIP_PRY_DODGE"] = "ESQUIVA", ["TOOLTIP_IC_DODGE"] = "Esquiva", ["TOOLTIP_CMP_ARCANE"] = "[+-]%d+%s[DE RESISTÊNCIA A ARCANO]+", ["TOOLTIP_PRY_ARCANE"] = "DE RESISTÊNCIA A ARCANO", ["TOOLTIP_IC_ARCANE"] = "de resistência a Arcano", ["TOOLTIP_CMP_FIRE"] = "[+-]%d+%s[DE RESISTÊNCIA A FOGO]+", ["TOOLTIP_PRY_FIRE"] = "DE RESISTÊNCIA A FOGO", ["TOOLTIP_IC_FIRE"] = "de resistência a Fogo", ["TOOLTIP_CMP_FROST"] = "[+-]%d+%s[DE RESISTÊNCIA A GELO]+", ["TOOLTIP_PRY_FROST"] = "DE RESISTÊNCIA A GELO", ["TOOLTIP_IC_FROST"] = "de resistência a Gelo", ["TOOLTIP_CMP_NATURE"] = "[+-]%d+%s[DE RESISTÊNCIA A NATUREZA]+", ["TOOLTIP_PRY_NATURE"] = "DE RESISTÊNCIA A NATUREZA", ["TOOLTIP_IC_NATURE"] = "de resistência a Natureza", ["TOOLTIP_CMP_SHADOW"] = "[+-]%d+%s[DE RESISTÊNCIA A SOMBRA]+", ["TOOLTIP_PRY_SHADOW"] = "DE RESISTÊNCIA A SOMBRA", ["TOOLTIP_IC_SHADOW"] = "de resistência a Sombra", ["TOOLTIP_IC_DAMAGE_DELTA"] = " de dano (delta: ", ["TOOLTIP_ITEM_COMPARE"] = "Kiwi diz que quando equipado:", ["TOOLTIP_ITEM_CONTRIB"] = "Contribuição Stat:", ["TOOLTIP_EX_AGI_M_AP"] = "Agilidade C. AP: ", ["TOOLTIP_EX_AGI_R_AP"] = "Agilidade D. AP: ", ["TOOLTIP_EX_AGI_CRIT"] = "Agilidade Crit: ", ["TOOLTIP_EX_AGI_DODGE"] = "Agilidade Esquiva: ", ["TOOLTIP_EX_AGI_AR"] = "Agilidade Armadura: ", ["TOOLTIP_EX_AGI_M_CAT_AP"] = "Agilidade GatoForma AP: ", ["TOOLTIP_EX_STM_HP"] = "Vigor Saúde: ", ["TOOLTIP_EX_STR_M_AP"] = "Força C. AP: ", ["TOOLTIP_EX_STR_BLOCK"] = "Força Bloqueio: ", ["TOOLTIP_EX_INT_MANA"] = "Intelecto Mana: ", ["TOOLTIP_EX_INT_CRIT"] = "Intelecto Crit: ", ["TOOLTIP_EX_SPT_HP5"] = "Espírito S/5: ", ["TOOLTIP_EX_SPT_MP5"] = "Espírito M/5: ", ["TOOLTIP_EX_RES_ARCANE"] = "Resistência a Arcano: ", ["TOOLTIP_EX_RES_FIRE"] = "Resistência a Fogo: ", ["TOOLTIP_EX_RES_FROST"] = "Resistência a Gelo: ", ["TOOLTIP_EX_RES_NATURE"] = "Resistência a Natureza: ", ["TOOLTIP_EX_RES_SHADOW"] = "Resistência a Sombra: ", ["COMMAND_ERROR_ARG_LEN"] = "Kiwi Item Info: Tamanho de argumento inválido.", ["COMMAND_RELOAD"] = "Recarregando KiwiItemInfo...", ["COMMAND_RELOAD_DONE"] = "Tudo pronto! :D Kiwi está funcionando!", ["COMMAND_RESET"] = "Reiniciando KiwiItemInfo...", ["COMMAND_VARS_DUMP"] = "Descarregando configurações de usuário...", ["COMMAND_VARS_DONE"] = "Tudo pronto!", ["COMMAND_SET_ERROR_BOOLEAN"] = "Kiwi espera por um valor booleano (true/false). Desculpe.", ["COMMAND_SET_ERROR_NUMBER"] = "Kiwi espera um valor númerico. Desculpe.", ["COMMAND_SET_ERROR_STRING"] = "Kiwi espera um valor string (texto). Desculpe", ["COMMAND_SET_ERROR_VAR"] = "Kiwi não possui essa variável. Desculpe", ["COMMAND_SET_ERROR_VALUE"] = "Kiwi precisa de um valor para atribuir à variável", ["COMMAND_SET_ERROR_INDEX"] = "Kiwi precisa de uma variável para atribuir", ["COMMAND_SEARCH_ARG_LEN"] = "Kiwi Item Info: Tamanho de argumento inválido para o argumento", ["COMMAND_SEARCH_ONE_HANDED"] = "Uma mão ", ["COMMAND_SEARCH_TWO_HANDED"] = "Duas mãos ", ["COMMAND_SEARCH_1H"] = "Uma", ["COMMAND_SEARCH_2H"] = "Duas", ["COMMAND_SEARCH_DONE"] = "Kiwi diz `esse é seu item`:", ["COMMAND_SEARCH_DONE1"] = "Kiwi é tão legal. Kiwi é tão maneiro. Kiwi encontrou", ["COMMAND_SEARCH_FAIL"] = "Kiwi não pode encontrar nenhum item! :(", ["KIWIII_HELP"] = "socorro", ["KIWIII_RELOAD"] = "recarregar", ["KIWIII_RESET"] = "recompor", ["KIWIII_VARS"] = "vars", ["KIWIII_SET"] = "pôr", ["KIWIII_ACI"] = "aci", ["KIWIII_SEARCH"] = "procurar", ["VUI_FLASH_GREY_ITEMS"] = "Itens em Flash Cinza:", ["VUI_FLASH_HOTKEY"] = "Tecla de atalho do Flash:", ["VUI_ITEM_COMPARE"] = "Item comparar em:", ["VUI_IC_VERBOSE"] = "Comparar item detalhado:", ["VUI_VENDOR_PRICE"] = "Item Fornecedor Preço:", ["VUI_SHOW_ILVL"] = "Mostre o iLvl:", ["VUI_ITEM_ILVL"] = "Mostrar iLvl nos itens:", ["VUI_DEFAULT_ILVL_COLOR"] = "Coloração padrão do iLvl:", ["VUI_CUSTOM_ILVL_COLOR"] = "Cor personalizada do iLvl:", ["VUI_FORMAT_ERROR"] = "Formato de cor inválido inserido.", } local temp = KiwiItemInfo.Locale["ptBR"] temp["COMMAND_SEARCH_ERROR_DB"] = "Kiwi recusou o uso de `/kiwiii " .. temp["KIWIII_SEARCH"] .. "`(devido o não carregamento do banco de dados)" temp["KII_BAD_DB"] = "Banco de dados de Kiwi Item Info não foi carregado! Não use `/kiwiii " .. temp["KIWIII_SEARCH"] .. "`" temp["KII_HELP"] = "Por favor, use `/kiwii " .. temp["KIWIII_HELP"] .. "` para listar os comandos!" temp["KII_THANKS"] = "Kiwi agradece por instalar KiwiItemInfo " .. KiwiItemInfo._VERSION .. "! <3" temp["COMMAND_HELP1"] = "Kiwi Item Info " .. KiwiItemInfo._VERSION .. " -- socorro" temp["COMMAND_HELP2"] = "https://github.com/tilkinsc/KiwiItemInfo - para reportar bugs e problemas." temp["COMMAND_HELP3"] = "Uso: /kiwiii [" .. temp["KIWIII_RELOAD"] .. "] [" .. temp["KIWIII_RESET"] .. "] [" .. temp["KIWIII_VARS"] .. "] [" .. temp["KIWIII_ACI"] .. "]" temp["COMMAND_HELP4"] = " [" .. temp["KIWIII_SET"] .. " variable_name value]" temp["COMMAND_HELP5"] = " [" .. temp["KIWIII_SEARCH"] .. " ${=,>,<}num, #Type, @subtype, {itemid, itemname}]" temp["COMMAND_HELP6"] = " > |cFF888888" .. temp["KIWIII_HELP"] .. "|r -- para está mensagem" temp["COMMAND_HELP7"] = " > |cFF888888" .. temp["KIWIII_RELOAD"] .. "|r -- recarrega addon" temp["COMMAND_HELP8"] = " > |cFF888888" .. temp["KIWIII_RESET"] .. "|r -- reinicia todas as variáveis salvas e também às recarrega" temp["COMMAND_HELP9"] = " > |cFF888888" .. temp["KIWIII_VARS"] .. "|r -- mostra todas as variáveis de configuração" temp["COMMAND_HELP10"] = " > |cFF888888" .. temp["KIWIII_SET"] .. "|r -- muda uma configuração" temp["COMMAND_HELP11"] = " * |cFFBBBBBBvariable_name|r -- variáveis mostradas em /kiwii vars" .. temp["KIWIII_VARS"] temp["COMMAND_HELP12"] = " * |cFFBBBBBBvalue|r -- entre true, false, string ou number" temp["COMMAND_HELP13"] = " > |cFF888888" .. temp["KIWIII_ACI"] .. "|r -- muda alwaysCompareItems CVar" temp["COMMAND_HELP14"] = " > |cFF888888" .. temp["KIWIII_SEARCH"] .. "|r -- procura por itens no banco de dados de item" temp["COMMAND_HELP15"] = " * |cFFBBBBBB${=,>,<}num|r -- mostra apenas 'num' de iLvls na operação" temp["COMMAND_HELP16"] = " * |cFFBBBBBB#Type|r -- mostra por tipos(Armor, Weapon, etc)" temp["COMMAND_HELP17"] = " * |cFFBBBBBB@SubType|r -- mostra por subtipos (Mail, 1HSwords, 2HSwords, etc)" temp["COMMAND_HELP18"] = " * |cFFBBBBBBitemid|r -- procura por itens usando o id" temp["COMMAND_HELP19"] = " * |cFFBBBBBBitemname|r -- procura por itens usando o nome"
print("Toggle the digital I/O called FIO3 (FIO5 on T4) at 1 Hz. Generates a 0.5Hz square wave.") local count = 0 local high = 0 local mbWrite=MB.W LJ.IntervalConfig(0, 1000) --set interval to 1000 for 1000ms local checkInterval=LJ.CheckInterval local outPin = 2003--FIO3. Changed if T4 instead of T7 devType = MB.R(60000, 3) if devType == 4 then outPin = 2005--FIO5 on T4 end while true do if checkInterval(0) then --interval completed if high == 1 then high = 0 mbWrite(outPin, 0, 0) --write 0 to FIO3 (FIO5 on T4). Address is 2003, type is 0, value is 0(output low) print(high, "low") mbWrite(46000, 3, 0) -- Set register "USER_RAM0_F32". Address 46000, type 3 mbWrite(46002, 3, 200) -- Set register "USER_RAM1_F32". Address 46002, type 3 else high = 1 mbWrite(outPin, 0, 1) --write 1 to FIO3 (FIO5 on T4). Address is 2003, type is 0, value is 1(output high) print(high, "high") mbWrite(46000, 3, 200) -- Set register "USER_RAM0_F32". Address 46000, type 3 mbWrite(46002, 3, 0) -- Set register "USER_RAM1_F32". Address 46002, type 3 end end end
--- Template for action file -- @submodule Actions -- @local local const = require("adam.const") local helper = require("adam.system.helper") local ActionInstance = require("adam.system.action_instance") local M = {} --- Add operator -- @treturn ActionInstance function M.func(source, value, is_every_frame) local action = ActionInstance(function(self) end) action:set_name("template.func") return action end return M
--[[ Molten Core - Thrash mobs This is all the thrash mobs scripted in Molten Core. ~~End of Script Forenote -- Viggo-xd, November 29th, 2008. ]]-- -----Molten Giant----- function MoltenGiant_OnEnterCombat(pUnit, Event) pUnit:RegisterEvent("MoltenGiant_Smash", 20000,1) pUnit:RegisterEvent("MoltenGiant_Knockback", 10000,1) end function MoltenGiant_OnDied(pUnit, Event) pUnit:RemoveEvents() end function MoltenGiant_OnLeaveCombat(pUnit, Event) pUnit:RemoveEvents() end function MoltenGiant_Smash(pUnit, Event) pUnit:FullCastSpellOnTarget(18944,pUnit:GetClosestPlayer()) end function MoltenGiant_Knockback(pUnit, Event) pUnit:FullCastSpellOnTarget(18945,pUnit:GetClosestPlayer()) end RegisterUnitEvent(11658, 1, "MoltenGiant_OnEnterCombat") RegisterUnitEvent(11658, 2, "MoltenGiant_OnDied") RegisterUnitEvent(11658, 4, "MoltenGiant_OnLeaveCombat") -----Molten Destroyer----- function MoltenDestroyer_OnEnterCombat(pUnit, Event) pUnit:RegisterEvent("MoltenDestroyer_Knockdown", 10000,1) pUnit:RegisterEvent("MoltenDestroyer_MassiveTremor", 10000,1) end function MoltenDestroyer_OnDied(pUnit, Event) pUnit:RemoveEvents() end function MoltenDestroyer_OnLeaveCombat(pUnit, Event) pUnit:RemoveEvents() end function MoltenDestroyer_Knockdown(pUnit, Event) pUnit:FullCastSpellOnTarget(20276,pUnit:GetClosestPlayer()) end function MoltenDestroyer_MassiveTremor(pUnit, Event) pUnit:FullCastSpellOnTarget(19129,pUnit:GetClosestPlayer()) end RegisterUnitEvent(11659, 1, "MoltenDestroyer_OnEnterCombat") RegisterUnitEvent(11659, 2, "MoltenDestroyer_OnDied") RegisterUnitEvent(11659, 4, "MoltenDestroyer_OnLeaveCombat") -----Firelord----- function Firelord_OnEnterCombat(pUnit, Event) pUnit:RegisterEvent("Firelord_Fireball", 10000,1) pUnit:RegisterEvent("Firelord_FireSpawn", 15000,1) end function FireLord_OnDied(pUnit, Event) pUnit:RemoveEvents() end function FireLord_OnLeaveCombat(pUnit, Event) pUnit:RemoveEvents() end function Firelord_Fireball(pUnit, Event) pUnit:FullCastSpellOnTarget(48246,pUnit:GetClosestPlayer()) end function Firelord_FireSpawn(pUnit, Event) pUnit:FullCastSpellOnTarget(19392,pUnit:GetClosestPlayer()) end RegisterUnitEvent(11668, 1, "Firelord_OnEnterCombat") RegisterUnitEvent(11668, 2, "FireLord_OnDied") RegisterUnitEvent(11668, 4, "FireLord_OnLeaveCombat") -----Lava Spawn----- function LavaSpawn_OnEnterCombat(pUnit, Event) pUnit:RegisterEvent("LavaSpawn_Split", 10000,1) pUnit:RegisterEvent("LavaSpawn_Fireball", 5000,1) end function LavaSpawn_OnDied(pUnit, Event) pUnit:RemoveEvents() end function LavaSpawn_OnLeaveCombat(pUnit, Event) pUnit:RemoveEvents() end function LavaSpawn_Split(pUnit, Event) pUnit:FullCastSpellOnTarget(19570,pUnit:GetClosestPlayer()) end function LavaSpawn_Fireball(pUnit, Event) pUnit:FullCastSpellOnTarget(19391,pUnit:GetClosestPlayer()) end RegisterUnitEvent(12265, 1, "LavaSpawn_OnEnterCombat") RegisterUnitEvent(12265, 2, "LavaSpawn_OnDied") RegisterUnitEvent(12265, 4, "LavaSpawn_OnLeaveCombat") -----Ancient Core Hound----- function AncientCoreHound_OnEnterCombat(pUnit, Event) pUnit:RegisterEvent("AncientCoreHound_Debuffs", 30000, 0) pUnit:RegisterEvent("AncientCoreHound_Bite", 10000, 1) pUnit:RegisterEvent("AncientCoreHound_LavaBreath", 20000, 1) end function AncientCoreHound_OnDied(pUnit, Event) pUnit:RemoveEvents() end function AncientCoreHound_OnLeaveCombat(pUnit, Event) pUnit:RemoveEvents() end function AncientCoreHound_Bite(pUnit, Event) pUnit:FullCastSpellOnTarget(19319,pUnit:GetClosestPlayer()) end function AncientCoreHound_LavaBreath(pUnit, Event) pUnit:FullCastSpellOnTarget(19272,pUnit:GetClosestPlayer()) end function AncientCoreHound_Debuffs(pUnit,Event) local Choice = math.random(1, 6) if Choice == 1 then pUnit:FullCastSpellOnTarget(19367,pUnit:GetClosestPlayer()) end if Choice == 2 then pUnit:FullCastSpellOnTarget(19369,pUnit:GetClosestPlayer()) end if Choice == 3 then pUnit:FullCastSpellOnTarget(19365,pUnit:GetClosestPlayer()) end if Choice == 4 then pUnit:FullCastSpellOnTarget(19372,pUnit:GetClosestPlayer()) end if Choice == 5 then pUnit:FullCastSpellOnTarget(19366,pUnit:GetClosestPlayer()) end if Choice == 6 then pUnit:FullCastSpellOnTarget(19364,pUnit:GetClosestPlayer()) end end RegisterUnitEvent(11673, 1, "AncientCoreHound_OnEnterCombat") RegisterUnitEvent(11673, 2, "AncientCoreHound_OnDied") RegisterUnitEvent(11673, 4, "AncientCoreHound_OnLeaveCombat") -----Lava Surger----- function LavaSurger_OnEnterCombat(pUnit, Event) pUnit:RegisterEvent("LavaSurger_Charge", 10000, 0) end function LavaSurger_OnDied(pUnit, Event) pUnit:RemoveEvents() end function LavaSurger_OnLeaveCombat(pUnit, Event) pUnit:RemoveEvents() end function LavaSurger_Charge(pUnit, Event) pUnit:FullCastSpellOnTarget(19196,pUnit:GetRandomPlayer(3)) end RegisterUnitEvent(12101, 1, "LavaSurger_OnEnterCombat") RegisterUnitEvent(12101, 2, "LavaSurger_OnDied") RegisterUnitEvent(12101, 4, "LavaSurger_OnLeaveCombat") -----Core Hound----- function CoreHound_OnEnterCombat(pUnit, Event) pUnit:RegisterEvent ("CoreHound_Bite", 5000, 0) end function CoreHound_OnDied(pUnit, Event) pUnit:RemoveEvents() end function CoreHound_OnLeaveCombat(pUnit, Event) pUnit:RemoveEvents() end function CoreHound_Bite(pUnit, Event) pUnit:FullCastSpellOnTarget(19771,pUnit:GetMainTank()) end RegisterUnitEvent(11671, 1, "CoreHound_OnEnterCombat") RegisterUnitEvent(11671, 2, "CoreHound_OnDied") RegisterUnitEvent(11671, 4, "CoreHound_OnLeaveCombat") -----Lava Pack (alot of Lava's)----- function LavaReaver_OnEnterCombat(pUnit, Event) pUnit:RegisterEvent("LavaReaver_Cleave", 5000, 0) end function LavaReaver_OnDied(pUnit, Event) pUnit:RemoveEvents() end function LavaReaver_OnLeaveCombat(pUnit, Event) pUnit:RemoveEvents() end function LavaReaver_Cleave(pUnit, Event) pUnit:FullCastSpellOnTarget(19642, pUnit:GetClosestPlayer()) end RegisterUnitEvent(12100, 1, "LavaReaver_OnEnterCombat") RegisterUnitEvent(12100, 2, "LavaReaver_OnDied") RegisterUnitEvent(12100, 4, "LavaReaver_OnLeaveCombat") function LavaElemental_OnEnterCombat(pUnit, Event) pUnit:RegisterEvent("LavaReaver_Pyroclast", 10000, 0) end function LavaElemental_OnDied(pUnit, Event) pUnit:RemoveEvents() end function LavaElemental_OnLeaveCombat(pUnit, Event) pUnit:RemoveEvents() end function LavaElemental_Pyroclast(pUnit, Event) pUnit:FullCastSpellOnTarget(19641, pUnit:GetMainTank()) end RegisterUnitEvent(12076, 1, "LavaElemental_OnEnterCombat") RegisterUnitEvent(12076, 2, "LavaElemental_OnDied") RegisterUnitEvent(12076, 4, "LavaElemental_OnLeaveCombat") function Flameguard_OnEnterCombat(pUnit, Event) pUnit:RegisterEvent("Flameguard_ArmorDebuff", 10000, 0) pUnit:RegisterEvent("Flameguard_ConeofFire", 10000, 0) end function Flameguard_OnDied(pUnit, Event) pUnit:RemoveEvents() end function Flameguard_OnLeaveCombat(pUnit, Event) pUnit:RemoveEvents() end function Flameguard_ArmorDebuff(pUnit, Event) pUnit:FullCastSpellOnTarget(19631, pUnit:GetMainTank()) end function Flameguard_ConeofFire(pUnit, Event) pUnit:FullCastSpellOnTarget(19630, pUnit: GetRandomPlayer(0)) end RegisterUnitEvent(11667, 1, "Flameguard_OnEnterCombat") RegisterUnitEvent(11667, 2, "Flameguard_OnDied") RegisterUnitEvent(11667, 4, "Flameguard_OnLeaveCombat") function Firewalker_OnEnterCombat(pUnit, Event) pUnit:RegisterEvent("Firewalker_ResistDebuff", 15000, 0) pUnit:RegisterEvent("Firewalker_FireBlossom", 10000, 0) end function Firewalker_OnDied(pUnit, Event) pUnit:RemoveEvents() end function Firewalker_OnLeaveCombat(pUnit, Event) pUnit:RemoveEvents() end function Firewalker_ResistDebuff(pUnit, Event) pUnit:FullCastSpellOnTarget(19635, pUnit:GetRandomPlayer(0)) end function Firewalker_FireBlossom(pUnit, Event) pUnit:FullCastSpellOnTarget(19636, pUnit:GetMainTank()) end RegisterUnitEvent(11666, 1, "Firewalker_OnEnterCombat") RegisterUnitEvent(11666, 2, "Firewalker_OnDied") RegisterUnitEvent(11666, 4, "Firewalker_OnLeaveCombat")
-- Copyright 2018-2022 Hugo O. Rivera. See LICENSE. -- Reason (https://reasonml.github.io/) LPeg lexer. local lexer = require('lexer') local token, word_match = lexer.token, lexer.word_match local P, S = lpeg.P, lpeg.S local lex = lexer.new('reason') -- Whitespace. lex:add_rule('whitespace', token(lexer.WHITESPACE, lexer.space^1)) -- Keywords. lex:add_rule('keyword', token(lexer.KEYWORD, word_match{ 'and', 'as', 'asr', 'begin', 'class', 'closed', 'constraint', 'do', 'done', 'downto', 'else', 'end', 'exception', 'external', 'failwith', 'false', 'flush', 'for', 'fun', 'function', 'functor', 'if', 'in', 'include', 'inherit', 'incr', 'land', 'let', 'load', 'los', 'lsl', 'lsr', 'lxor', 'method', 'mod', 'module', 'mutable', 'new', 'not', 'of', 'open', 'option', 'or', 'parser', 'private', 'ref', 'rec', 'raise', 'regexp', 'sig', 'struct', 'stdout', 'stdin', 'stderr', 'switch', 'then', 'to', 'true', 'try', 'type', 'val', 'virtual', 'when', 'while', 'with' })) -- Types. lex:add_rule('type', token(lexer.TYPE, word_match('int float bool char string unit'))) -- Functions. lex:add_rule('function', token(lexer.FUNCTION, word_match{ 'raise', 'invalid_arg', 'failwith', 'compare', 'min', 'max', 'succ', 'pred', 'mod', 'abs', 'max_int', 'min_int', 'sqrt', 'exp', 'log', 'log10', 'cos', 'sin', 'tan', 'acos', 'asin', 'atan', 'atan2', 'cosh', 'sinh', 'tanh', 'ceil', 'floor', 'abs_float', 'mod_float', 'frexp', 'ldexp', 'modf', 'float', 'float_of_int', 'truncate', 'int_of_float', 'infinity', 'nan', 'max_float', 'min_float', 'epsilon_float', 'classify_float', 'int_of_char', 'char_of_int', 'ignore', 'string_of_bool', 'bool_of_string', 'string_of_int', 'int_of_string', 'string_of_float', 'float_of_string', 'fst', 'snd', 'stdin', 'stdout', 'stderr', 'print_char', 'print_string', 'print_int', 'print_float', 'print_endline', 'print_newline', 'prerr_char', 'prerr_string', 'prerr_int', 'prerr_float', 'prerr_endline', 'prerr_newline', 'read_line', 'read_int', 'read_float', 'open_out', 'open_out_bin', 'open_out_gen', 'flush', 'flush_all', 'output_char', 'output_string', 'output', 'output_byte', 'output_binary_int', 'output_value', 'seek_out', 'pos_out', 'out_channel_length', 'close_out', 'close_out_noerr', 'set_binary_mode_out', 'open_in', 'open_in_bin', 'open_in_gen', 'input_char', 'input_line', 'input', 'really_input', 'input_byte', 'input_binary_int', 'input_value', 'seek_in', 'pos_in', 'in_channel_length', 'close_in', 'close_in_noerr', 'set_binary_mode_in', 'incr', 'decr', 'string_of_format', 'format_of_string', 'exit', 'at_exit' })) -- Identifiers. lex:add_rule('identifier', token(lexer.IDENTIFIER, lexer.word)) -- Strings. local sq_str = lexer.range("'", true) local dq_str = lexer.range('"', true) lex:add_rule('string', token(lexer.STRING, sq_str + dq_str)) -- Comments. local line_comment = lexer.to_eol('//') local block_comment = lexer.range('/*', '*/', false, false, true) lex:add_rule('comment', token(lexer.COMMENT, line_comment + block_comment)) -- Numbers. lex:add_rule('number', token(lexer.NUMBER, lexer.number)) -- Operators. lex:add_rule('operator', token(lexer.OPERATOR, S('=<>+-*/.,:;~!#%^&|?[](){}'))) return lex
return function (conn) conn:send(wifi.sta.getip()); print(wifi.sta.getip()); end
function init() effect.setParentDirectives(config.getParameter("directives", "")) self.healthPercentage = config.getParameter("healthPercentage", 0.1) end function update(dt) status.setResourcePercentage("health", math.min(status.resourcePercentage("health"), self.healthPercentage)) end function uninit() end
--[[ ___ .___ . .' `. , __ ` __. , __ / \ .___ __. . ___ ___ _/_ | | |' `. | .' \ |' `. |,_-' / \ .' \ \ .' ` .' ` | | | | | | | | | | | | ' | | | |----' | | `.__.' / | / `._.' / | / / `._.' /` | `.___, `._.' \__/ \___/` Onion Security Suite Started on January 18th, 2018 Main Contributors: - JupiterGuy2/dCarr2 Managed & Published by Millennium Interactive ]]-- -- // Environment setup // -- local Host = script.Parent -- Less annoying way of typing "script.Parent" every 5 seconds local Base = {} -- This will hold some internal functions local LocalCache = {} -- This holds a small amount of memory for quick internal usage local SecurityKey = nil -- Later, this will be set to a 16bit key later that will ensure very secure communication between modules local Library = nil -- Later, this will be set to our external module library local RunService = game:GetService("RunService") -- We need this service to figure out what the h*ck we're doing local LogService = game:GetService("LogService") -- We need to use this to detect the environment.. unfortunately local HttpService = game:GetService("HttpService") -- We need this to access the sweet 'ol cloud local API = { -- This is a set of functions/data that can be utilized by the runtime/module libraries ShowNotification = (function(NotifData) -- Lets external services utilize the GUI notifications end) } --------------------------------------------------------------------------------------------- -- // Adding functionality to our local environment // -- LocalCache.RuntimeName = "Onion Security Suite" -- This is an identifiable string so people don't remove our precious files in ServerSettings print("IsClient:",RunService:IsClient(),"IsStudio:",RunService:IsStudio(),"IsServer:",RunService:IsServer()) function Base:print(...) -- This function is designed to handle place branding/add logging functionality to the internal Lua print function if (LocalCache.DisableOutput) then return end -- If the DisableOutput bool is enabled, don't run this function local Str = "[ "..Host.Name.." ]: " -- Create the prefix for our cool new string for _,PassedPar in ipairs({...}) do -- Create loop to go through all the passed parameters and add them together Str = Str .. " " .. tostring(PassedPar) -- Append a forced-string version of the parameter to the existing string end warn(Str) -- Send it to the output with fancy orange text end -- This will get around the invalid security level to access HTTPEnabled. -- We want to: -- * Check if a last tick cache existed, if it does... Only proceed if it's < 60 seconds. Unless the "force" parameter is passed as true -- * Pcall a function sending a ping to a versatile web host -- * If Pcall returns that it failed, we know that HttpEnabled is set to FALSE. function Base:CheckHttpAvailability(force) local LastHttpAttempt = (LocalCache.LastHttpAttempt or 0) -- See if the last Http attempt is recorded, if not then set to 0 so it can be overwritten if not (((tick() - LastHttpAttempt) < 60) or (force)) then -- If it's been at least 60 seconds return (LocalCache.LastHttpTestResult or false) -- Kill the function, return value end local Attempt = pcall(function() game:GetService("HttpService"):GetAsync("https//google.ca") end) end -- Roblox's API to do this is broken and terrible so we're gonna have to do something hacky function Base:FigureOutEnv() local PluginTest = pcall(function() plugin:GetSetting(math.random()) end) -- We're gonna try to load a fake setting under a pcall to see if it's running under the plugin security level if PluginTest == true then -- If true, we know it's a plugin return "eplugin" -- can't say "plugin" or Lua will have a hissy fit else return "server" -- Not a plugin end end local ExecutionInstructions = { eplugin = function() Base:print("Plugin mode") end; server = function() Base:print("Server mode") end; } ExecutionInstructions[Base:FigureOutEnv()]()
-- Titanium recipe & tech changes -- local util = require("__bzlead__.data-util"); if (not mods["pyrawores"] and not mods["bobplates"] and not mods["angelssmelting"] and not mods["IndustrialRevolution"]) then util.replace_ingredient("pipe", "iron-plate", "lead-plate") util.replace_ingredient("pipe-to-ground", "iron-plate", "lead-plate") util.replace_some_ingredient("storage-tank", "iron-plate", 10, "lead-plate", 10) util.replace_ingredient("battery", "iron-plate", "lead-plate") if util.me.sulfuric() then util.replace_ingredient("sulfuric-acid", "iron-plate", "lead-plate") end util.replace_ingredient("uranium-fuel-cell", "iron-plate", "lead-plate") util.replace_some_ingredient("gun-turret", "iron-plate", 4, "lead-plate", 4) util.add_ingredient("big-electric-pole", "lead-plate", 2) util.add_ingredient("substation", "lead-plate", 2) util.add_ingredient("electric-furnace", "lead-plate", 4) if not (mods.bzsilicon and util.has_ingredient("solar-panel", "solar-cell")) then util.add_ingredient("solar-panel", "lead-plate", 5) end util.add_ingredient("flamethrower-turret", "lead-plate", 4) util.add_ingredient("artillery-turret", "lead-plate", 40) -- ammunition util.replace_ingredient("firearm-magazine", "iron-plate", "lead-plate") util.replace_ingredient("shotgun-shell", "iron-plate", "lead-plate") end -- Krastorio 2 changes util.add_ingredient("kr-laser-artillery-turret", "lead-plate", 10) util.add_ingredient("kr-railgun-turret", "lead-plate", 10) util.add_ingredient("kr-rocket-turret", "lead-plate", 10) -- Space Exploration util.add_product("se-scrap-recycling", {name="lead-ore", amount=1, probability=0.1}) util.replace_some_ingredient("se-pulveriser", "iron-plate", 10, "lead-plate", 10) util.replace_some_ingredient("se-canister", "copper-plate", 5, "lead-plate", 5) util.add_ingredient("industrial-furnace", "lead-plate", 16) -- AAII util.add_ingredient("se-material-testing-pack", "lead-plate", 1) util.add_ingredient("se-space-radiation-laboratory", "lead-plate", 100) util.add_ingredient("se-delivery-cannon", "lead-plate", 16) util.add_ingredient("se-meteor-point-defence", "lead-plate", 16) util.add_ingredient("se-meteor-defence", "lead-plate", 64) util.add_ingredient("se-experimental-alloys-data", "lead-plate", 1) util.add_to_product("se-experimental-alloys-data", "se-experimental-alloys-data", 1) util.add_to_product("se-experimental-alloys-data", "se-scrap", 1) util.add_to_ingredient("se-experimental-alloys-data", "se-empty-data", 1) if mods["WeaponPack"] then util.replace_ingredient("9x18", "iron-plate", "lead-plate") util.replace_some_ingredient("9x19", "iron-plate", 1, "lead-plate", 1) util.replace_some_ingredient("7,62x25", "iron-plate", 9, "lead-plate", 9) util.replace_some_ingredient("7,62x51", "iron-plate", 11, "lead-plate", 11) util.replace_some_ingredient("5,56x45", "iron-plate", 9, "lead-plate", 9) util.replace_some_ingredient("5,45x39", "iron-plate", 7, "lead-plate", 7) util.replace_some_ingredient("5,7x28", "iron-plate", 7, "lead-plate", 7) util.replace_some_ingredient("5,7 × 28", "iron-plate", 7, "lead-plate", 7) util.replace_some_ingredient("357", "iron-plate", 9, "lead-plate", 9) util.replace_some_ingredient("45acp", "iron-plate", 7, "lead-plate", 7) util.replace_some_ingredient("12gauge", "iron-plate", 3, "lead-plate", 3) end if mods["More_Ammo"] then util.replace_ingredient("sp-ammo-recipe", "iron-plate", "lead-plate") end if mods["eve-weaponry"] then util.replace_ingredient("small-carbonized-lead", "iron-plate", "lead-plate") end util.add_ingredient("howitzer-turret-recipe","lead-plate", 8) -- Additional turrets util.add_ingredient("at-acidthrower-turret","lead-plate", 4) util.add_ingredient("at-cannon-turret-mk1","lead-plate", 4) util.add_ingredient("at-rocket-turret-mk1","lead-plate", 4) util.replace_ingredient("small-coal-cannon-shell", "copper-plate", "lead-plate") util.replace_ingredient("small-coal-cannon-shell", "copper-plate", "lead-plate") util.add_ingredient("at_A1_b","lead-plate", 20) -- Other one-offs util.replace_some_ingredient("zinfinite_buffer_fluid_tank1", "iron-plate", 1000, "lead-plate", 1000) util.add_ingredient("storage-tank2", "lead-plate", 32) util.add_ingredient("advanced-substation", "lead-plate", 20) util.add_ingredient("substation-2", "lead-plate", 20) util.add_ingredient("advanced-accumulator", "lead-plate", 16) util.add_ingredient("vtk-cannon-turret", "lead-plate", 20) util.add_ingredient("vtk-cannon-turret-heavy", "lead-plate", 30) util.add_ingredient("w93-modular-turret-base", "lead-plate", 8) util.add_ingredient("w93-modular-turret2-base", "lead-plate", 4) -- rampant arsenal util.add_ingredient("rifle-item-rampant-arsenal", "lead-plate", 10) util.add_ingredient("shotgun-item-rampant-arsenal", "lead-plate", 10) util.add_ingredient("rocket-item-rampant-arsenal", "lead-plate", 10) util.add_ingredient("rapid-rocket-item-rampant-arsenal", "lead-plate", 10) util.add_ingredient("cannon-item-rampant-arsenal", "lead-plate", 20) util.add_ingredient("rapid-cannon-item-rampant-arsenal", "lead-plate", 20) util.add_ingredient("suppression-cannon-item-rampant-arsenal", "lead-plate", 30) util.add_ingredient("capsule-item-rampant-arsenal", "lead-plate", 10) util.add_ingredient("lite-artillery-turret-rampant-arsenal", "lead-plate", 20) -- Scraver's Atomic Artillery util.add_ingredient("sc-artillery-turret", "lead-plate", 40) -- Light artillery util.add_ingredient("derpy-artillery", "lead-plate", 20) -- Bigger artillery util.add_ingredient("big-artillery-turret", "lead-plate", 100) -- Heavy Machine Gun Turret util.add_ingredient("kr-heavy-machine-gun-turret", "lead-plate", 10) -- King Jo util.replace_ingredient("bolt75mk1", "steel-plate", "lead-plate") util.replace_some_ingredient("bolt100mk1", "steel-plate", 3, "lead-plate", 3) util.replace_some_ingredient("bolt75metalstorm", "steel-plate", 3, "lead-plate", 2) util.replace_some_ingredient("bolt100metalstorm", "steel-plate", 5, "lead-plate", 5) -- Geothermal util.add_ingredient("geothermal-well", "lead-plate", 120) -- Nuclear furnace util.add_ingredient("nuclear-furnace-1", "lead-plate", 200) util.add_ingredient("nuclear-furnace-2", "lead-plate", 200) -- Mega furnace util.add_ingredient("mega-furnace", "lead-plate", 4) -- Nuclear fuel, Plutonium energy util.replace_ingredient("breeder-fuel-cell", "iron-plate", "lead-plate") util.replace_ingredient("mox-fuel-cell", "iron-plate", "lead-plate") util.replace_ingredient("MOX-fuel", "iron-plate", "lead-plate") -- True Nukes util.replace_ingredient("tritium-breeder-fuel-cell", "iron-plate", "lead-plate") -- Hazmat suit util.add_ingredient("hazmat-suit", "lead-plate", 2) util.add_ingredient("mil-grade-fuel-cell", "lead-plate", 10) -- RITEG util.add_ingredient("RITEG-1", "lead-plate", 10) util.add_ingredient("RITEG-cyan", "lead-plate", 10) util.add_ingredient("RITEG-breeder", "lead-plate", 10) -- Zane's Car Turret util.add_ingredient("car-turret", "lead-plate", 4) -- Endgame Combat util.add_ingredient("concussion-turret", "lead-plate", 20) util.add_ingredient("sticky-turret", "lead-plate", 4) util.add_ingredient("cannon-turret", "lead-plate", 20) util.add_ingredient("plasma-turret", "lead-plate", 8) -- Other util.add_ingredient("rocket-turret", "lead-plate", 8) util.add_ingredient("hl-rocket-turret-recipe", "lead-plate", 20) -- Realistic Reactors util.add_ingredient("reactor-sarcophagus", "lead-plate", 300) -- Nuclear locomotive util.replace_ingredient("Nuclear_Train", "iron-plate", "lead-plate") -- Uranium Rework util.add_ingredient("uraniumrework-uranium-waste-container", "lead-plate", 25) -- Schall util.add_ingredient("Schall-radioactive-waste-incinerator", "lead-plate", 25) util.replace_ingredient("Schall-sniper-firearm-magazine", "iron-plate", "lead-plate") util.add_ingredient("Schall-rocket-turret", "lead-plate", 8) util.add_ingredient("Schall-minigun-turret", "lead-plate", 8) util.add_ingredient("Schall-sniper-turret", "lead-plate", 16) util.add_ingredient("Schall-force-cannon-turret", "lead-plate", 16) util.add_ingredient("Schall-particle-beam-turret", "lead-plate", 16) util.add_ingredient("Schall-mega-particle-beam-turret", "lead-plate", 32) util.add_ingredient("Schall-particle-cannon-turret", "lead-plate", 32) util.add_ingredient("Schall-BFG-turret", "lead-plate", 64) util.add_ingredient("Schall-cannon-turret", "lead-plate", 16) util.add_ingredient("Schall-autocannon-turret", "lead-plate", 16) util.add_ingredient("Schall-cannon-H1-turret", "lead-plate", 16) util.add_ingredient("Schall-cannon-H2-turret", "lead-plate", 64) -- Nuclear Reprocessing Rebalance util.replace_product("nuclear-fuel-reprocessing", "iron-plate", "lead-plate")
local createrole = { [1] = {ID=1,OccupationID=10,title="jk_zi.png",background="js_1.png",bust="zhujue1.png",portrait="cj_nzj.png",Money=0,Emoney=0,Level=1,Head="wjxxtx_nanzhu.png",Card="zjJK.png",Picture=1,Item="",Weapon=41101001,sex=0,ATK=4,Magic=0,Def=2,Life=3,rolebutton="UI_icon_js.png"}, [2] = {ID=2,OccupationID=20,title="qs_zi.png",background="js_2.png",bust="zhujue2.png",portrait="cj_nvzj.png",Money=0,Emoney=0,Level=1,Head="wjxxtx_nvzhu.png",Card="zjQS.png",Picture=2,Item="",Weapon=41201001,sex=1,ATK=0,Magic=4,Def=1,Life=2,rolebutton="UI_icon_js3.png"}, [3] = {ID=3,OccupationID=30,title="qfj_zi.png",background="js_3.png",bust="zhujue3.png",portrait="cj_qs.png",Money=0,Emoney=0,Level=1,Head="wjxxtx_quanfajia.png",Card="qfj.png",Picture=3,Item="",Weapon=41301001,sex=0,ATK=4,Magic=0,Def=2,Life=3,rolebutton="UI_icon_js2.png"}, [4] = {ID=4,OccupationID=43,title="mdxz_zi.png",background="js_4.png",bust="zhujue4.png",portrait="cj_mdxz.png",Money=0,Emoney=0,Level=1,Head="wjxxtx_modaoxuezhe.png",Card="mdxz.png",Picture=4,Item="",Weapon=41431006,sex=0,ATK=2,Magic=3,Def=1,Life=1,rolebutton="UI_icon_js4.png"}, } return createrole
Config = {} Config.Locale = 'fr' Config.Price = 15 Config.DrawDistance = 100.0 Config.MarkerSize = {x = 1.5, y = 1.5, z = 1.0} Config.MarkerColor = {r = 102, g = 102, b = 204} Config.MarkerType = 27 Config.Zones = {} Config.Shops = { {x=70.519, y=-1399.876, z=29.383}, --#1 {x=430.811, y=-798.989, z=29.498}, --#2 {x=-831.346, y=-1072.535, z=11.335}, --#3 {x=-1192.039, y=-776.669, z=17.332}, --#4 {x=119.939, y=-217.215, z=54.557}, --#5 {x=-166.369, y=-311.230, z=39.733}, --#6 {x=-714.294, y=-145.338, z=37.415}, --#7 {x=-1444.468, y=-230.901, z=49.810}, --#8 {x=-3175.868, y=1015.812, z=20.863}, --#9 {x=-1110.328, y=2709.745, z=19.115}, --#10 {x=622.151, y=2759.058, z=42.088}, --#11 {x=1189.504, y=2715.535, z=38.230}, --#12 {x=1698.197, y=4830.648, z=42.070}, --#13 {x=13.695, y=6513.442, z=31.885}, --#14 } for i=1, #Config.Shops, 1 do Config.Zones['Shop_' .. i] = { Pos = Config.Shops[i], Size = Config.MarkerSize, Color = Config.MarkerColor, Type = Config.MarkerType } end
--[[ Steps to modify chunk_size to 64 - set qconsts.chunk_size to 64 in UTILS/lua/q_consts.lua - modify Q_CHUNK_SIZE constant to 64 in UTILS/inc/q_constants.h - rebuild Q ]] -- For all tests, set chunk size to 64 -- Weird behavior: if I uncomment Q.print_csv() statement from below tests then all tests works except t1 -- Date 9/12/2017 - now not observing weird behavior because of fix in vector code local Q = require 'Q' local c_to_txt = require 'Q/UTILS/lua/C_to_txt' local tests = {} -- Problem with MK_COL -- mk_col for B1 with values more than chunk size not working correctly, -- for second chunk it gives wrong values tests.t1 = function() local input_table = {} for i=1, 65536 do input_table[i] = 1 end input_table[655537] = 0 input_table[65538] = 1 local b = Q.mk_col(input_table, "B1") -- Q.print_csv(b, nil, "/tmp/b_out.txt") for i = 1, b:length() do val, nn_val = c_to_txt(b, i) if not val then val = 0 end assert(val == input_table[i], "Mismatch at index " .. i .. ", expected: " .. input_table[i] .. ", actual: " .. val) end -- Q.print_csv(b, nil, "/tmp/mk_col_B1_out.txt") end -- Problem with Seq -- When specifying len greater than chunk_size, the first value I am getting is zero instead of start value. -- But if I set len equal to chunk_size or less than that then getting proper values. tests.t2 = function() local a = Q.seq( {start = 1, by = 1, qtype = "I4", len = 65540} ) a:eval() -- Q.print_csv(a, nil, "/tmp/seq_out") val, nn_val = c_to_txt(a, 1) assert(val == 1) end -- Problem with vvadd -- Not getting proper result when using vector with length greater than chunk_size tests.t3 = function() local a_input_table = {} for i=1, 65538 do a_input_table[i] = i end local a = Q.mk_col(a_input_table, "I4") -- Q.print_csv(a, nil, "/tmp/a_out.txt") local b = Q.mk_col(a_input_table, "I4") -- Q.print_csv(b, nil, "/tmp/b_out.txt") local res = Q.vvadd(a, b) res:eval() -- Q.print_csv(res, nil, "/tmp/vvadd_out.txt") for i = 1, a:length() do val, nn_val = c_to_txt(res, i) assert(val == a_input_table[i] * 2, "Mismatch at index " .. i .. ", expected: " .. a_input_table[i] * 2 .. ", actual " .. val) end end -- Problem with sum -- Not getting correct result with Q.sum tests.t4 = function() local a_input_table = {} for i=1, 65538 do a_input_table[i] = i end local a = Q.mk_col(a_input_table, "I4") -- Q.print_csv(a, nil, "/tmp/a_out.txt") local res = Q.sum(a):eval():to_num() assert(res == ( ( 65538 * 65539 ) / 2 ) ) local b = Q.seq({start = 1, by = 1, qtype = "I4", len = 65538}) b:eval() -- Q.print_csv(b, nil, "/tmp/b_out.txt") res = Q.sum(b):eval():to_num() assert(res == ( ( 65538 * 65539 ) / 2 ) ) end return tests
-- Scripts juste pour éteindre toutes les LED du ruban -- tout sur la couleur: https://www.w3schools.com/colors/default.asp -- roue des couleurs: https://iro.js.org/?ref=oldsite print("\n az_init_led.lua zf181201.1751 \n") znbled=300 function RGB_clear() ws2812.init() buffer = ws2812.newBuffer(znbled, 3) buffer:fill(0, 0, 0) ws2812.write(buffer) end print("Initializing LED strip...") RGB_clear() print("done.")
-- https://www.reddit.com/r/vim/comments/d77t6j/guide_how_to_setup_ctags_with_gutentags_properly/ vim.g.gutentags_ctags_exclude = { '*.git', '*.svg', '*.hg', '*/tests/*', 'build', 'dist', '*sites/*/files/*', 'bin', 'node_modules', 'bower_components', 'cache', 'compiled', 'docs', 'example', 'bundle', 'vendor', '*.md', '*-lock.json', '*.lock', '*bundle*.js', '*build*.js', '.*rc*', '*.json', '*.min.*', '*.map', '*.bak', '*.zip', '*.pyc', '*.class', '*.sln', '*.Master', '*.csproj', '*.tmp', '*.csproj.user', '*.cache', '*.pdb', 'tags*', 'cscope.*', -- '*.css', -- '*.less', -- '*.scss', '*.exe', '*.dll', '*.mp3', '*.ogg', '*.flac', '*.swp', '*.swo', '*.bmp', '*.gif', '*.ico', '*.jpg', '*.png', '*.rar', '*.zip', '*.tar', '*.tar.gz', '*.tar.xz', '*.tar.bz2', '*.pdf', '*.doc', '*.docx', '*.ppt', '*.pptx', } vim.g.gutentags_add_default_project_roots = false vim.g.gutentags_project_root = {'package.json', '.git'} vim.g.gutentags_cache_dir = vim.fn.expand('~/.cache/nvim/ctags/') vim.g.gutentags_generate_on_new = true vim.g.gutentags_generate_on_missing = true vim.g.gutentags_generate_on_write = true vim.g.gutentags_generate_on_empty_buffer = true vim.cmd([[command! -nargs=0 GutentagsClearCache call system('rm ' . g:gutentags_cache_dir . '/*')]]) vim.g.gutentags_ctags_extra_args = {'--tag-relative=yes', '--fields=+ailmnS', }
-- This script is part of lua2exe -- Loader for embedded scripts local load2 = loadembed local names = embeddedfiles local function loader (name) if names[name] then return load2(name, names[name]) else return 'No embedded module \''..name ..'\'' end end loadembed = nil embeddedfiles = nil table.insert(package.loaders, 2, loader)
local function map(mode, lhs, rhs, opts) local options = {noremap = true} if opts then options = vim.tbl_extend('force', options, opts) end vim.api.nvim_set_keymap(mode, lhs, rhs, options) end -- Nerdtree map('n', '<C-n>', '<cmd>NERDTreeToggle<CR>') map('n', '<Leader>v', '<cmd>NERDTreeFind<CR>') -- Hop map('n', '<Leader>l', "<cmd>HopLine<CR>", {}) map('n', '<Leader>s', "<cmd>HopPattern<CR>", {}) map('n', '<Leader>f', "<cmd>HopChar1<CR>", {}) -- Telescope map('n', '<C-p>', "<cmd>Telescope find_files<CR>") map('n', '<C-b>', "<cmd>Telescope buffers<CR>") map('n', '<C-s>', "<cmd>Telescope<CR>") map('n', '<leader>fg', "<cmd>Telescope live_grep<CR>") -- Diff map('n', '<Leader>gh', "<cmd>diffget //3<CR>") map('n', '<Leader>gu', "<cmd>diffget //2<CR>") map('n', '<Leader>gs', "<cmd>G<CR>") -- Arrows map('', '<up>', "<nop>") map('', '<down>', "<nop>") map('', '<left>', "<nop>") map('', '<right>', "<nop>") -- Tabs map('n', '<C-t>', "<cmd>tabnew<CR>") -- Gundo map('n', '<leader>u', "<cmd>GundoToggle<CR>") -- Easy Escape map('i', 'jj', "<ESC>") map('t', 'jj', "<C-\\><C-n>") -- Menu Nav map('i', '<C-j>', 'pumvisible() ? "\\<C-n>" : "\\<C-j>"', {expr = true}) map('i', '<C-k>', 'pumvisible() ? "\\<C-p>" : "\\<C-k>"', {expr = true}) map('n', 'n', 'nzzzv') map('n', 'N', 'Nzzzv') -- QuickFixList map('n', '<C-k>', '<cmd>copen<CR>') map('n', '<leader>p', '"_dP')
local setmetatable = setmetatable local string = string local gtable = require("gears.table") local vertical = require("wibox.layout.fixed").vertical local grid = require("wibox.layout.grid") local textbox = require("wibox.widget.textbox") local bgcontainer = require("wibox.container.background") local base = require("wibox.widget.base") local beautiful = require("beautiful") local calendar = { mt = {} } local properties = { "date", "font", "spacing", "week_numbers", "start_sunday", "long_weekdays", "fn_embed" } local function make_cell(text, font, center) local w = textbox() w:set_markup(text) w:set_align(center and "center" or "right") w:set_valign("center") w:set_font(font) return w end --- Create a grid layout with the month calendar local function create_month(props, date) local num_rows = 8 local num_columns = props.week_numbers and 8 or 7 -- Create grid layout local layout = grid() layout:set_expand(true) layout:set_expand(true) layout:set_homogeneous(true) layout:set_spacing(props.spacing) layout:set_forced_num_rows(num_rows) layout:set_forced_num_cols(num_columns) local start_row = 3 local start_column = num_columns - 6 local week_start = props.start_sunday and 1 or 2 local last_day = os.date("*t", os.time{year=date.year, month=date.month+1, day=0}) local month_days = last_day.day local column_fday = (last_day.wday - month_days + 1 - week_start ) % 7 --local flags = {"header", "weekdays", "weeknumber", "normal", "focus"} local cell_date, t, i, j, w, flag, text, cell_date -- Header flag = "header" t = os.time{year=date.year, month=date.month, day=1} if props.subtype=="monthheader" then flag = "monthheader" text = os.date("%B", t) else text = os.date("%B %Y", t) end w = props.fn_embed(make_cell(text, props.font, true), flag, date, cell_date) layout:add_widget_at(w, 1, 1, 1, num_columns) -- Days i = start_row j = column_fday + start_column local current_week = nil local drawn_weekdays = 0 for d=1, month_days do cell_date = {year=date.year, month=date.month, day=d} t = os.time(cell_date) -- Week number if props.week_numbers then text = os.date("%V", t) if tonumber(text) ~= current_week then flag = "weeknumber" w = props.fn_embed(make_cell(text, props.font), flag, cell_date, cell_date) layout:add_widget_at(w, i, 1, 1, 1) current_week = tonumber(text) end end -- Week days if drawn_weekdays < 7 then flag = "weekday" text = os.date("%a", t) if not props.long_weekdays then text = string.sub(text, 1, 2) end w = props.fn_embed(make_cell(text, props.font), flag, cell_date, cell_date) layout:add_widget_at(w, 2, j, 1, 1) drawn_weekdays = drawn_weekdays +1 end -- Normal day flag = "normal" text = string.format("%2d", d) -- Focus day if date.day == d then flag = "focus" text = "<b>"..text.."</b>" end w = props.fn_embed(make_cell(text, props.font), flag, cell_date, cell_date) layout:add_widget_at(w, i, j, 1, 1) -- find next cell i,j = layout:get_next_empty(i,j) if j < start_column then j = start_column end end return props.fn_embed(layout, "month", date, cell_date) end --- Set the container to the current date local function fill_container(self) local date = self._private.date if date then -- Create calendar grid if self._private.type == "month" then self._private.container:set_widget(create_month(self._private, date)) elseif self._private.type == "year" then self._private.container:set_widget(create_year(self._private, date)) end else self._private.container:set_widget(nil) end self:emit_signal("widget::layout_changed") end -- Set the calendar date function calendar:set_date(date) if date ~= self._private.date then self._private.date = date -- (Re)create calendar grid fill_container(self) end end -- Build properties function for _, prop in ipairs(properties) do -- setter if not calendar["set_" .. prop] then calendar["set_" .. prop] = function(self, value) if (string.sub(prop,1,3)=="fn_" and type(value) == "function") or self._private[prop] ~= value then self._private[prop] = value -- (Re)create calendar grid fill_container(self) end end end -- getter if not calendar["get_" .. prop] then calendar["get_" .. prop] = function(self) return self._private[prop] end end end --- Return a new calendar widget by type. -- -- @tparam string type Type of the calendar, `year` or `month` -- @tparam table date Date of the calendar -- @tparam number date.year Date year -- @tparam number|nil date.month Date month -- @tparam number|nil date.day Date day -- @tparam[opt="Monospace 10"] string font Font of the calendar -- @treturn widget The calendar widget local function get_calendar(type, date, font) local ct = bgcontainer() local ret = base.make_widget(ct, "calendar", {enable_properties = true}) gtable.crush(ret, calendar, true) ret._private.type = type ret._private.container = ct -- default values ret._private.date = date ret._private.font = font or beautiful.calendar_font or "Monospace 10" ret._private.spacing = beautiful.calendar_spacing or 5 ret._private.week_numbers = beautiful.calendar_week_numbers or false ret._private.start_sunday = beautiful.calendar_start_sunday or false ret._private.long_weekdays = beautiful.calendar_long_weekdays or false ret._private.fn_embed = function (w, _) return w end -- header specific ret._private.subtype = type=="year" and "monthheader" or "fullheader" fill_container(ret) return ret end --- A month calendar widget. function calendar.month(date, font) return get_calendar("month", date, font) end return setmetatable(calendar, calendar.mt) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
require("curses"); curses.initscr(); while (true) do local s = curses.getnstr(1000); curses.addstr(s); curses.addstr(":" .. table.concat({curses.getyx(curses.stdscr())}, ' ') .. "\n"); if (s == "exit") then break; end end curses.endwin();
bestine_election_smooth_stone = { description = "", minimumLevel = 0, maximumLevel = 0, lootItems = { {itemTemplate = "smooth_stone", weight = 10000000}, } } addLootGroupTemplate("bestine_election_smooth_stone", bestine_election_smooth_stone)
local framework, loadError = loadfile("personalFramework.lua") if loadError then error(loadError) end framework() term.clear() local table1 = { {a=1, b=2, c={1,2}}, {a=2, b=3, c={5,7}}, {a=2, b=5, c={8,9}}, } local table2 = table.blend(table1) rPrint(table2, 10, "Blended table") local str1 = "This statement will not be shown, " local str2 = "but this statement will." print(str1..str2) term.moveCursor(-1, 0) print(string.rep(" ", #str1))
DoorSlot = CustomItem:extend() DoorSlot.Icons = { [0] = "none", [1] = "doortracker/unknown", [2] = "overlays/overlay-x", [3] = "doortracker/caution", [4] = "doortracker/exit", [5] = "items/smallkey", [6] = "items/bigkey", [7] = "doortracker/boss", [8] = "doortracker/crystalswitch", [9] = "doortracker/peg-blue", [10] = "doortracker/peg-red", [11] = "doortracker/firesource", [12] = "items/firerod", [13] = "items/lamp", [14] = "items/bombos", [15] = "items/somaria", [16] = "items/hammer", [17] = "items/hookshot", [18] = "items/bow", [19] = "items/flippers", [20] = "items/glove-1", [21] = "items/boots", [22] = "items/sword", [23] = "doortracker/weapon", [24] = "doortracker/1", [25] = "doortracker/2", [26] = "doortracker/3", [27] = "doortracker/4", [28] = "doortracker/5", [29] = "doortracker/6" } DoorSlot.OWIcons = { [4] = "items/portal", [5] = "items/smallkey", [6] = "items/bigkey", [7] = "doortracker/boss", [8] = "items/frog", [9] = "items/purplechest", [10] = "icons/entrances/potionshop", [11] = "items/firerod", [12] = "items/lamp", [13] = "items/bombos", [15] = "items/mirror", [16] = "items/book", [17] = "items/hammer", [18] = "items/hookshot", [22] = "doortracker/weapon", [23] = "", [24] = "doortracker/1", [25] = "doortracker/2", [26] = "doortracker/3", [27] = "doortracker/4", [28] = "doortracker/5", [29] = "doortracker/6" } function DoorSlot:init(roomSlotNum, doorSlotNum) self:createItem("Door Slot " .. (string.char(string.byte("A") + (roomSlotNum - 1))) .. doorSlotNum) self.code = "doorSlot" .. roomSlotNum .. "_" .. doorSlotNum self.roomSlot = roomSlotNum self.doorSlot = doorSlotNum self:setState(0) end function DoorSlot:setState(state) self:setProperty("state", state) end function DoorSlot:getState() return self:getProperty("state") end function DoorSlot:setDisabled() self.ItemInstance.IgnoreUserInput = self:getState() == 0 end function DoorSlot:updateIcon() local img = "" if INSTANCE.ROOMSLOTS[self.roomSlot][1] > 0x1000 then img = DoorSlot.OWIcons[self:getState()] end if not img or img == "" then img = DoorSlot.Icons[self:getState()] end local imgPath = "images/" .. img .. ".png" self.ItemInstance.Icon = ImageReference:FromPackRelativePath(imgPath) end function DoorSlot:onLeftClick() local state = self:getState() if DoorSlotSelection.Selection == 0 then state = (state % #DoorSlot.Icons) + 1 else if DoorSlotSelection.Groups[DoorSlotSelection.Selection] and state >= DoorSlotSelection.Selection and state <= DoorSlotSelection.Groups[DoorSlotSelection.Selection][1] then state = (((state - DoorSlotSelection.Selection) + 1) % ((DoorSlotSelection.Groups[DoorSlotSelection.Selection][1] - DoorSlotSelection.Selection) + 1)) + DoorSlotSelection.Selection else state = DoorSlotSelection.Selection end end if INSTANCE.DOORSLOTS[INSTANCE.ROOMSLOTS[self.roomSlot][1]] then INSTANCE.DOORSLOTS[INSTANCE.ROOMSLOTS[self.roomSlot][1]][self.doorSlot] = state end self:setState(state) refreshDoorSlots() end function DoorSlot:onRightClick() local state = self:getState() if DoorSlotSelection.Selection == 0 then state = (state - 2) % #DoorSlot.Icons + 1 else state = 1 end if INSTANCE.DOORSLOTS[INSTANCE.ROOMSLOTS[self.roomSlot][1]] then INSTANCE.DOORSLOTS[INSTANCE.ROOMSLOTS[self.roomSlot][1]][self.doorSlot] = state end self:setState(state) refreshDoorSlots() end function DoorSlot:canProvideCode(code) return code == self.code end function DoorSlot:propertyChanged(key, value) if key == "state" then self:updateIcon() self:setDisabled() end end
--[[ module:FlyweightTest author:DylanYang time:2021-02-10 22:08:35 ]] local ShapeFactory = require("patterns.structural.flyweight.ShapeFactory") local super = require("patterns.BaseTest") local _M = Class("FlyweightTest", super) local static = _M.static _M.static.readonly.colors = { "Red", "Green", "Blue", "White", "Black" } function _M.protected:DoExecTest() for i = 1, 20 do local circle = ShapeFactory:GetCircle(self:GetRandomColor()) circle.x = self:GetRandomX() circle.y = self:GetRandomY() circle.radius = 100 circle:Draw() end end function _M:GetRandomColor() return self.colors[math.ceil(math.random() * #self.colors)] end function _M:GetRandomX() return math.random() * 100 end function _M:GetRandomY() return math.random() * 100 end return _M
function SelectableMixin:OnSighted(sighted) if not sighted then local selectedByTeamOne = bit.band(self.selectionMask, 1) ~= 0 local selectedByTeamTwo = bit.band(self.selectionMask, 2) ~= 0 if (self:GetTeamNumber() == 2 or self:GetTeamNumber() == 0) and selectedByTeamOne then if Server then self:SetSelected(1, false) end elseif (self:GetTeamNumber() == 1 or self:GetTeamNumber() == 0) and selectedByTeamTwo then if Server then self:SetSelected(2, false) end end end end function SelectableMixin:UpdateIncludeRelevancyMask() -- Make entities which are active for a commander relevant to all commanders -- on the same team. local includeMask = 0 if bit.band(self.selectionMask, 1) ~= 0 or (self:GetTeamNumber() == 1 and self:GetHotGroupNumber() ~= 0) then includeMask = bit.bor(includeMask, kRelevantToTeam1Commander) end if bit.band(self.selectionMask, 2) ~= 0 or (self:GetTeamNumber() == 2 and self:GetHotGroupNumber() ~= 0) then includeMask = bit.bor(includeMask, kRelevantToTeam2Commander) end -- special hack for special stuff if self:isa("PowerPoint") then if kTeam1Type == kMarineTeamType then includeMask = bit.bor(includeMask, kRelevantToTeam1Commander) end if kTeam2Type == kMarineTeamType then includeMask = bit.bor(includeMask, kRelevantToTeam2Commander) end end self:SetIncludeRelevancyMask( includeMask ) end function SelectableMixin:GetIsSelectable(byTeamNumber) local isValid = HasMixin(self, "LOS") and self:GetIsSighted() or HasMixin(self, "Team") and (byTeamNumber == self:GetTeamNumber() or self:GetTeamNumber() == kNeutralTeamType) if isValid and self.OnGetIsSelectable then -- A table is passed in so that all the OnGetIsSelectable functions -- have a say in the matter. local resultTable = { selectable = true } self:OnGetIsSelectable(resultTable, byTeamNumber) isValid = resultTable.selectable end return isValid end
-- -- Created by IntelliJ IDEA. -- User: sdcuike -- Date: 2015 -- Time: 下午4:09 -- local cjson = require('cjson.safe') -- 日志功能组件 begin --- local modulename = "Util" local _M = {} _M._VERSION = '0.0.1' _M.logInfo = function ( info ) ngx.log(ngx.INFO, "[["..info.."]]") end _M.logError = function (error) ngx.log(ngx.ERR, "[["..error.."]]") end -- 日志功能组件 end --- local function tableToString2(tableValue) if not tableValue then return "" end if type(tableValue) ~= "table" then return ""..tableValue end local info = "" for k, v in pairs(tableValue) do info = info.."[key:"..k.." value:"..tableToString2(v).."]" end return info end _M.tableToString = function(tableValue) if type(tableValue) ~= "table" then _M.logError("input is not a tabe type :"..tableValue) return nil end return tableToString2(tableValue); end return _M
--MoveCurve --H_Tokisaki/curve_Attack_1 curve_Attack_1 return { filePath = "H_Tokisaki/curve_Attack_1", startTime = Fixed64(0) --[[0]], startRealTime = Fixed64(0) --[[0]], endTime = Fixed64(20447232) --[[19.5]], endRealTime = Fixed64(136315) --[[0.13]], isZoom = false, isCompensate = false, curve = { [1] = { time = 0 --[[0]], value = 0 --[[0]], inTangent = 1048576 --[[1]], outTangent = 1048576 --[[1]], }, [2] = { time = 1048576 --[[1]], value = 1048576 --[[1]], inTangent = 1048576 --[[1]], outTangent = 1048576 --[[1]], }, }, }
-- https://github.com/aubergine10/Style require 'lib.style' require 'lib.image' require 'lib.sound' require 'lib.shortcut'
object_tangible_food_crafted_beastfood_blubbery_fish_substitute = object_tangible_food_crafted_shared_beastfood_blubbery_fish_substitute:new { } ObjectTemplates:addTemplate(object_tangible_food_crafted_beastfood_blubbery_fish_substitute, "object/tangible/food/crafted/beastfood_blubbery_fish_substitute.iff")
-- myauth.jwt local _M = {} local cjson = require "cjson" _M.secret = nil _M.ignore_audience = false function _M.authorize(token, host) -- token, error_code, error_reason if token == nil then return nil, 'missing_token', nil; end local jwt = require "resty.jwt" if _M.secret == nil then error("Secret not specified") end local jwt_obj = jwt:verify(_M.secret, token) if not jwt_obj.verified then if string.find(jwt_obj.reason, "signature mismatch") then return nil, 'invalid_token_sign', jwt_obj.reason; elseif string.find(jwt_obj.reason, "invalid jwt string") then return nil, 'invalid_token_format', jwt_obj.reason; else return nil, 'invalid_token', jwt_obj.reason; end end if not _M.ignore_audience then if jwt_obj.payload.aud ~= null then if host ~= nil then if(jwt_obj.payload.aud ~= host) then return nil, 'invalid_audience', "Expected '" .. jwt_obj.payload.aud .. "' but actual '" .. host .. "'"; end else return nil, 'no_host', "Cant detect a host to check audience"; end end end return jwt_obj, nil,nil end function _M.get_token_roles(jwt_obj) local role = jwt_obj.payload['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'] if role ~= nil then return { role } end role = jwt_obj.payload['role'] if role ~= nil then return { role } end return jwt_obj.payload.roles; end function _M.get_token_biz_claims(jwt_obj) local claims = {} for k,v in pairs(jwt_obj.payload) do if k ~= "iss" and k ~= "aud" and k ~= "exp" and k ~= "nbf" and k ~= "iat" and k ~= "jti" then claims[k] = v end end return claims end return _M
function dumpGameInfo() -- dump Game Information that the Archipelago Randomizer needs. local data_collection = {} local force = game.forces["player"] for tech_name, tech in pairs(force.technologies) do if tech.enabled and tech.research_unit_count_formula == nil then local tech_data = {} local unlocks = {} tech_data["unlocks"] = unlocks local requires = {} tech_data["requires"] = requires local ingredients = {} tech_data["ingredients"] = ingredients for tech_requirement, _ in pairs(tech.prerequisites) do table.insert(requires, tech_requirement) end for _, modifier in pairs(tech.effects) do if modifier.type == "unlock-recipe" then table.insert(unlocks, modifier.recipe) end end for _, ingredient in pairs(tech.research_unit_ingredients) do table.insert(ingredients, ingredient.name) end data_collection[tech_name] = tech_data tech.researched = true -- enable all available recipes end game.write_file("techs.json", game.table_to_json(data_collection), false) game.print("Exported Tech Data") end data_collection = {} for recipe_name, recipe in pairs(force.recipes) do if recipe.enabled then local recipe_data = {} recipe_data["ingredients"] = {} recipe_data["products"] = {} recipe_data["category"] = recipe.category for _, ingredient in pairs(recipe.ingredients) do recipe_data["ingredients"][ingredient.name] = ingredient.amount end for _, product in pairs(recipe.products) do recipe_data["products"][product.name] = product.amount end data_collection[recipe_name] = recipe_data end end game.write_file("recipes.json", game.table_to_json(data_collection), false) game.print("Exported Recipe Data") data_collection = {} for _, proto in pairs(game.entity_prototypes) do if proto.crafting_categories then data_collection[proto.name] = proto.crafting_categories end end game.write_file("machines.json", game.table_to_json(data_collection), false) game.print("Exported Machine Data") end commands.add_command("ap-get-info-dump", "Dump Game Info, used by Archipelago.", function(call) dumpGameInfo() end)
-- license:BSD-3-Clause -- copyright-holders:Vas Crabb local exports = { name = 'timer', version = '0.0.3', description = 'Game play timer', license = 'BSD-3-Clause', author = { name = 'Vas Crabb' } } local timer = exports function timer.startplugin() local total_time = 0 local start_time = 0 local play_count = 0 local emu_total = emu.attotime() local reference = 0 local lastupdate local highlight -- hacky - workaround for the menu not remembering the selected item if its ref is nullptr local function sectohms(time) local hrs = time // 3600 local min = (time % 3600) // 60 local sec = time % 60 return string.format(_p('plugin-timer', '%03d:%02d:%02d'), hrs, min, sec) end local function menu_populate() lastupdate = os.time() local refname = (reference == 0) and _p('plugin-timer', 'Wall clock') or _p('plugin-timer', 'Emulated time') local time = (reference == 0) and (lastupdate - start_time) or manager.machine.time.seconds local total = (reference == 0) and (total_time + time) or (manager.machine.time + emu_total).seconds return { { _p("plugin-timer", "Reference"), refname, (reference == 0) and 'r' or 'l' }, { '---', '', '' }, { _p("plugin-timer", "Current time"), sectohms(time), "off" }, { _p("plugin-timer", "Total time"), sectohms(total), "off" }, { _p("plugin-timer", "Play Count"), play_count, "off" } }, highlight, "idle" end local function menu_callback(index, event) if (index == 1) and ((event == 'left') or (event == 'right') or (event == 'select')) then reference = reference ~ 1 return true end highlight = index return os.time() > lastupdate end emu.register_start( function() if emu.romname() ~= '___empty' then start_time = os.time() local persister = require('timer/timer_persist') total_time, play_count, emu_total = persister:start_session() end end) emu.register_stop( function() if emu.romname() ~= '___empty' then local persister = require('timer/timer_persist') persister:update_totals(start_time) end end) emu.register_menu(menu_callback, menu_populate, _p("plugin-timer", "Timer")) end return exports
-- See LICENSE for terms local props = { PlaceObj("ModItemOptionToggle", { "name", "EnableMod", "DisplayName", T(302535920011303, "<color ChoGGi_yellow>Enable Mod</color>"), "Help", T(302535920011793, "Disable mod without having to see missing mod msg."), "DefaultValue", true, }), PlaceObj("ModItemOptionToggle", { "name", "SurfaceOnly", "DisplayName", T(302535920012054, "Surface Only"), "Help", T(302535920012055, "You only get deposits on the surface colony."), "DefaultValue", true, }), PlaceObj("ModItemOptionToggle", { "name", "SafeLanding", "DisplayName", T(302535920012040, "Safe Landing"), "Help", T(302535920012041, "Buildings won't be hit by falling rocks."), "DefaultValue", false, }), PlaceObj("ModItemOptionNumber", { "name", "MetalsThreshold", "DisplayName", T(302535920012042, "Metals Threshold"), "Help", T(302535920012043, "Threshold for a new Metals deposit."), "DefaultValue", 1, "MinValue", 1, "MaxValue", 50, }), PlaceObj("ModItemOptionNumber", { "name", "RareMetalsThreshold", "DisplayName", T(302535920012044, "Rare Metals Threshold"), "Help", T(302535920012045, "Threshold for a new Rare Metals deposit."), "DefaultValue", 1, "MinValue", 1, "MaxValue", 50, }), PlaceObj("ModItemOptionNumber", { "name", "WaterThreshold", "DisplayName", T(302535920012046, "Water Threshold"), "Help", T(302535920012047, "Threshold for a new Water deposit."), "DefaultValue", 1, "MinValue", 1, "MaxValue", 50, }), PlaceObj("ModItemOptionNumber", { "name", "ConcreteThreshold", "DisplayName", T(302535920012048, "Concrete Threshold"), "Help", T(302535920012049, "Threshold for a new Concrete deposit."), "DefaultValue", 1, "MinValue", 1, "MaxValue", 50, }), } if g_AvailableDlc.picard then props[#props+1] = PlaceObj("ModItemOptionToggle", { "name", "ExoticMinerals", "DisplayName", T(608869515243, "Exotic Minerals"), "Help", T(302535920012090, "Drop mineral deposits."), "DefaultValue", false, }) props[#props+1] = PlaceObj("ModItemOptionNumber", { "name", "ExoticMineralsThreshold", "DisplayName", T(302535920012091, "Exotic Minerals Threshold"), "Help", T(302535920012092, "Threshold for a new Exotic Minerals deposit."), "DefaultValue", 1, "MinValue", 1, "MaxValue", 50, }) end return props
local enums = require "enums" require "position" Character = {} function Character:newCharacter(x, y, z, movement_speed, attack_damage, width, height) local new_character = { position = Position:newPosition(x, y, z), movement_speed = movement_speed, attack_damage = attack_damage, width = width, height = height } self.__index = self return setmetatable(new_character, self) end function Character:newEnemy(x, y, movement_speed, attack_damage, width, height) local new_enemy = Character:newCharacter(x, y, 0, movement_speed, attack_damage, width, height) return new_enemy end function new_grunt(x, y) local char = Character:newEnemy(x, y, 0, 10, 5, 64, 128) char.kind = "grunt" return char end function new_heavy(x, y) local char = Character:newEnemy(x, y, 0, 5, 10, 64, 128) char.kind = "heavy" return char end function Character:Update() if self.kind == "heavy" then end if self.kind == "grunt" then end end function Character:newPlayerChar(x, y, movement_speed, attack_damage) local new_player = Character:newCharacter(x, y, 0, movement_speed, attack_damage, 64, 128) new_player.control_scheme = enums.control_schemes.left_control_scheme return new_player end function Character:updatePlayer(delta_time) if (enums.control_schemes.left_control_scheme == self.control_scheme) then return update_as_left() elseif (enums.control_schemes.right_control_scheme == self.control_scheme) then return update_as_right() elseif (enums.control_schemes.controller == self.control_scheme) then return update_as_controller() end end function update_as_left(delta_time) local x = 0 local y = 0 local punch = false local kick = false local jump = false if love.keyboard.isDown("a") then x = x - 1 end if love.keyboard.isDown("d") then x = x + 1 end if love.keyboard.isDown("w") then y = y - 1 end if love.keyboard.isDown("s") then y = y + 1 end if love.keyboard.isDown("q") then punch = true end if love.keyboard.isDown("e") then kick = true end return x, y, punch, kick end function update_as_right(delta_time) local x = 0 local y = 0 local punch = false local kick = false local jump = false if love.keyboard.isDown("j") then x = x - 1 end if love.keyboard.isDown("l") then x = x + 1 end if love.keyboard.isDown("i") then y = y - 1 end if love.keyboard.isDown("k") then y = y + 1 end if love.keyboard.isDown("u") then punch = true end if love.keyboard.isDown("o") then kick = true end return x, y, punch, kick end function update_as_controller(delta_time) if love.joystick.getJoystickCount() == 0 then return end local joystick = love.joystick.getJoysticks()[1] print(lastbutton) local x = 0 local y = 0 local punch = false local kick = false local jump = false if joystick:isGamepadDown("dpleft") then x = x - 1 else x = joystick:getAxis( 1 ) end if joystick:isGamepadDown("dpright") then x = x + 1 end if joystick:isGamepadDown("dpup") then y = y - 1 end if joystick:isGamepadDown("dpdown") then y = y + 1 else y = joystick:getAxis( 2 ) end if joystick:isDown(3) then punch = true end if joystick:isDown(4) then kick = true end return x, y, punch, kick end
--abcdd = {} print(abcdd.a) abcdd.addd().ddd.dddp() abcdd.eff() abcdd.addd().ddd.dddp() abcdd.eff() abcdd:dd().dd1() abcdd:dd().dd1() print(abcdd.addd().ddd.a.d) print(abcdd.addd().ddd.dd.ddd) abcdd:dd() abcdd.ccc(one, one).a.b.c()
local HooI return function(lib) HooI = lib local SelectableSystem = HooI.class("SelectableSystem", HooI.system) function SelectableSystem:initialize(canvas) self.class.super.initialize(self) canvas.eventManager:addListener("HoverEvent", self, self.hoverEvent) canvas.eventManager:addListener("ClickEvent", self, self.clickEvent) canvas.eventManager:addListener("KeyInputEvent", self, self.keyInputEvent) canvas.eventManager:addListener("SelectionEvent", self, self.selectionEvent) self.selectedEntity = nil end function SelectableSystem:onEntityAdded(entity) if not self.selectedEntity then self.selectedEntity = entity end end function SelectableSystem:selectionEvent(event) local entity, sc, hc, cc entity = event.entity sc = entity:get("SelectableComponent") hc = entity:get("HoverableComponent") cc = entity:get("ClickableComponent") if event.selected then if event.pressed then if hc then if hc.selectedCallback then hc.selectedCallback(entity) else sc.selectedCallback(entity) end else sc.selectedCallback(entity) end elseif event.released then if cc then if cc.executedCallback then cc.executedCallback(entity) else sc.executedCallback(entity) end else sc.executedCallback(entity) end else if hc then if hc.deselectedCallback then hc.deselectedCallback(entity) else sc.deselectedCallback(entity) end else sc.deselectedCallback(entity) end end end end -- ToDo Add input listener. Directional and execution. function SelectableSystem:keyInputEvent(event) if self.selectedEntity then if self.selectedEntity:get("SelectableComponent")[event.inputType] then local entity = self.selectedEntity:get("SelectableComponent")[event.inputType] self.selectedEntity.selected = false self.selectedEntity.pressed = false entity.selected = true entity.pressed = false entity.eventManager:fireEvent(HooI.events.SelectionEvent(entity, true, false, false)) self.selectedEntity.eventManager:fireEvent(HooI.events.SelectionEvent(self.selectedEntity, false, false, false)) self.selectedEntity = entity elseif event.inputType == "press" then self.selectedEntity.pressed = true self.selectedEntity.eventManager:fireEvent(HooI.events.SelectionEvent(self.selectedEntity, true, true, false)) elseif event.inputType == "execute" then if self.selectedEntity.pressed then self.selectedEntity.pressed = false self.selectedEntity.eventManager:fireEvent(HooI.events.SelectionEvent(self.selectedEntity, true, false, true)) end end end end function SelectableSystem:hoverEvent(event) local entity, sc entity = event.entity sc = entity:get("SelectableComponent") if event.isHovered then if self.selectedEntity then self.selectedEntity:get("SelectableComponent").selected = false end self.selectedEntity = entity sc.selected = true entity.eventManager:fireEvent(HooI.events.SelectionEvent(entity, true, false, false)) else sc.selected = false entity.eventManager:fireEvent(HooI.events.SelectionEvent(entity, false, false, false)) end end function SelectableSystem:clickEvent(event) local entity, sc entity = event.entity sc = entity:get("SelectableComponent") if sc.selected then if event.isPressed then sc.pressed = true entity.eventManager:fireEvent(HooI.events.SelectionEvent(entity, true, true, false)) else sc.pressed = false entity.eventManager:fireEvent(HooI.events.SelectionEvent(entity, true, false, true)) end end end function SelectableSystem:requires() return {"WidgetComponent", "SelectableComponent"} end return SelectableSystem end
--------------------------------------------------------------------------------------------------- ---player_resource.lua ---author: Karl ---date: 2021.8.7 ---desc: A PlayerResource object is a struct that contains the resources of one player --------------------------------------------------------------------------------------------------- ---@class gameplay_resources.Player local M = LuaClass("PlayerResource") function M.__create() return { num_life = 0, num_bomb = 0, num_graze = 0, num_power = 0, } end local _double_fields = { "num_life", "num_bomb", "num_graze", "num_power", } local _string_fields = {} function M:copy() local copy = M() copy.num_life = self.num_life copy.num_bomb = self.num_bomb copy.num_graze = self.num_graze copy.num_power = self.num_power return copy end --------------------------------------------------------------------------------------------------- ---save to/load from file ---manages saving the object to file at the current file cursor position ---@param file_writer SequentialFileWriter the object for writing to file function M:writeToFile(file_writer) file_writer:writeFieldsOfTable(self, _double_fields, _string_fields) end ---manages reading the object from file at the current file cursor position ---@param file_reader SequentialFileReader the object for reading from file function M:readFromFile(file_reader) file_reader:readFieldsOfTable(self, _double_fields, _string_fields) end return M
--[[ parent : irrelevant children: cell.lua, cellList.lua, matrix.lua ModuleScript ]]-- --i use comments like the one above to easily tell what the parent > child tree is without having to read through the code local automata = {}; --constant declarations up here unecessary, if you're going to have constants, atleast put them at the earliest point they're used --control variables also unused, we can just break from the main loop when needed --[[ GetLivingCellCount has been omitted entirely it is entirely unecessary for us to iterate through the **entire** matrix to figure out how many cells are alive as we can keep track manually within the loop this function will bottleneck in large boards, it'd perform not only a large iteration, but also a generic table.sort (not that optimized) *every frame* ]]-- local function gridSpace(position, origin) --[[ used to translate world space to a grid position since the cells are all offset from the center in this version, you can do (current pos of axis - center axis) to get the board coordinate for that axis from a world space position this function avoids the need of several tables that just hold the grid position, as we can simply translate it when needed ]]-- return Vector2.new(position.X - origin.X, position.Z - origin.Z); end; local function adjacent(host, board, origin) local adjacents = {}; --[[ the old name of this function was extremely wordy, "GetMovableCells" is alot to describe a function that just gets the adjacent cells of another instead of having an ugly wall of manual move position declarations, i instead use the gridSpace function to get the grid position, and then simply iterate from one to the left of the cell, to one to the right of the cell and one to the bottom, one to the top this ensures every possible adjacent cell is checked and avoids wasting cycles manually declaring moves in a table addtionally, the "Board[pos] ~= nil" statements are unecessary, if statements execute if the expression given can be casted to a boolean true "nil" and "false" are the only types in lua that can be casted to false, everything else casts to true so all you need to do to ensure the square exists is just "if board[x]", if "board[x]" is nil, it'll be casted to false, so the if statement wont run it's block i also used the "and" logical operator to avoid unecessary nested if statements this is also significantly more readable ]]-- local gridPos = gridSpace(host.pos, origin) for x = gridPos.X - 1, gridPos.X + 1 do for y = gridPos.Y - 1, gridPos.Y + 1 do if board[x] and board[x][y] and board[x][y].name ~= host.name then adjacents[#adjacents + 1] = board[x][y]; end; end; end; return adjacents; end; local cell = require(script.cell); --i put the declaration for the require at it's earliest use point, this function, so that others reading the code don't have to scroll up 50 lines to find it's declaration at the top of the file when they see it's name, instead it's just right here local function infectCells(host, board, origin) --[[ several problems with this function have been fixed 1) the name is less wordy 2) MovableCells is an unecessary variable, it's only used once, you may as well just put the function call directly into the pairs statement 3) the check of "if NeighborCell.CellName == "None" then NeighborCell:Infect(Host) end" is pointless, none cells have a strength of 0, so "host.dna.strength > victim.dna.strength" will always succeed against them i still check for the cell name being none, but not to capture it, instead to determine that a new cell has been created which is used to keep track of the current cell count (more on the start function) ]]-- local newCells = {}; for _, victim in ipairs(adjacent(host, board, origin)) do if host.dna.strength > victim.dna.strength then if victim.name == "None" then newCells[#newCells + 1] = victim; end; cell.infect(host, victim); else cell.infect(victim, host); end; end; return newCells; end; --[[ Setup has also been omitted there is no reason to make the board a property of the module itself, why would the user ever want to access it? there is also no need for constants that control the board size, why not let the user define the board size in the start function and make the board appropriately? it's also more intuitive to use, since all the user needs to do is call module.start, rather than module:Setup() (which takes no args) and *then* module.start ]]-- local matrix = require(script.matrix); function automata.start(boardX, boardY, origin, cellsPerFrame, tickSpeed, cellList) --[[ this function has gone through several improvements, both for usability but also better code let's start with the immediate code improvements 1) less wordy name, "StartSimulation" is a bit much. I know im using a simulation module. there aren't any other functions related to "starting" anything, it'd be pretty clear what this does if we just named it "start" 2) no uses of classes or :, there's nothing that's worth making a property of the module besides the functions for controlling the simulation 3) removed use of Random, it's just "math.random" wrapped in a slower, OOP shell arguments like cellList give the user more control over the behavior of the function, allowing them to provide custom cell lists without modifying the cellList module ]]-- local board = matrix.new(boardX, boardY); --default argument setting if typeof(origin ) ~= "Vector3" then origin = Vector3.new(0, 1, 0 ) end; if type (cellsPerFrame) ~= "number" then cellsPerFrame = 10 end; if type (tickSpeed ) ~= "number" then tickSpeed = 0 end; if type (cellList ) ~= "table" then cellList = require(script.cellList) end; local livingCells = 0; --instead of having a dedicated function to keep track of living cells, we increment a number throughout the main loop local activeCells = {}; do local alreadyUsed = {}; for i, template in pairs(cellList) do if i > board.size then warn("cell list is larger than total board size, only "..(i - 1).." cell"..(i - 1 > 1 and "s" or "").." spawned"); break; end; local x, y; repeat wait() x, y = math.random(1, board.cols), math.random(1, board.rows); until not alreadyUsed[x..y]; alreadyUsed[x..y] = true; local host = cell.clone(template, Vector3.new(origin.X + x, origin.Y, origin.Z + y)) --cloning the template, but providing a position for the node from the origin board[x][y] = host; activeCells[#activeCells + 1] = host livingCells += 1; end; --instead of filling the board with "none" cells and then recoloring them, i spawn each normal cell randomly first, then fill in all empty spaces with none cells local empty = cell.new("None", { color = Color3.new(1,1,1), strength = 0 }); for x = 1, board.cols do for y = 1, board.rows do if not board[x][y] then board[x][y] = cell.clone(empty, Vector3.new(origin.X + x, origin.Y, origin.Z + y)); end; end; end; end; local heartbeat = game:GetService("RunService").Heartbeat; local lastTick = tick(); --removed coroutines, can be added back in if asynchronous behavior is desired, but felt it was unecessary for this function --one thing though, the nested coroutine is entirely unecessary and wastes resources since you're remaking it each frame in the original loop while livingCells < board.size do --instead of having a control variable, we can just put the check directly into the expression for the while loop if tick() - lastTick >= tickSpeed then --controls the speed of the simulation using the tickspeed arg, allowing the user to choose how fast the simulation progresses lastTick = tick(); for i = 1, cellsPerFrame do --allow the user to control how many cells are processed per tick --[[ this is an optimization and a QoL improvement activeCells is used to control the cells that we iterate through this array includes every cell that isn't a "none" cell, so we dont waste iterations skipping past "none" cells this allows for faster visible simulation on larger boards ]]-- local host = activeCells[math.random(1, #activeCells)]; --removed unecessary variable declarations, they're only used once, just move their values directly into the expression in the if statement if math.random() / host.dna.mutRate <= 0.01 then cell.mutate(host); end; local newCells = infectCells(host, board, origin); livingCells += #newCells; --since infectCells returns an array of all new cells, we can simply increment livingCells by the length of the array table.move(newCells, 1, #newCells, #activeCells + 1, activeCells); end; end; heartbeat:Wait(); end; print("pandemic reached"); end; return automata;
--[[ Copyright (C) 2018 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ]] local events = require 'dmlab.system.events' local game = require 'dmlab.system.game' local tensor = require 'dmlab.system.tensor' local inventory = require 'common.inventory' local api = {} local map = 'seekavoid_arena_01' function api:nextMap() local result = map map = '' return result end function api:spawnInventory(loadout) local view = inventory.View(loadout) view:setGadgets{ inventory.GADGETS.IMPULSE, inventory.GADGETS.RAPID, inventory.GADGETS.BEAM, inventory.GADGETS.DISC, } view:setGadgetAmount(inventory.GADGETS.IMPULSE, inventory.UNLIMITED) view:setGadgetAmount(inventory.GADGETS.RAPID, inventory.UNLIMITED) view:setGadgetAmount(inventory.GADGETS.BEAM, inventory.UNLIMITED) view:setGadgetAmount(inventory.GADGETS.DISC, inventory.UNLIMITED) return view:loadOut() end function api:updateInventory(loadout) local view = inventory.View(loadout) local gadget = view:gadget() for k, i in pairs(inventory.GADGETS) do if i == gadget then events:add('GADGET', k) return end end events:add('GADGET', tostring(gadget)) end function api:customDiscreteActionSpec() return {{name = 'NEXT_GADGET', min = 0, max = 1}} end function api:customDiscreteActions(actions) if actions[1] ~= 0 then game:console('weapnext') end end function api:hasEpisodeFinished(time) return false end return api
local NoteResult = { Miss = 1; Okay = 2; Good = 3; Great = 4; Perfect = 5; Marvelous = 6; } function NoteResult:timedelta_to_result(time_to_end, _game) time_to_end = time_to_end / _game._audio_manager.get_song_rate() if time_to_end >= _game._audio_manager.NOTE_OKAY_MIN and time_to_end <= _game._audio_manager.NOTE_OKAY_MAX then local note_result = nil if time_to_end > _game._audio_manager.NOTE_OKAY_MIN and time_to_end <= _game._audio_manager.NOTE_GOOD_MIN then note_result = NoteResult.Okay elseif time_to_end > _game._audio_manager.NOTE_GOOD_MIN and time_to_end <= _game._audio_manager.NOTE_GREAT_MIN then note_result = NoteResult.Good elseif time_to_end > _game._audio_manager.NOTE_GREAT_MIN and time_to_end <= _game._audio_manager.NOTE_PERFECT_MIN then note_result = NoteResult.Great elseif time_to_end > _game._audio_manager.NOTE_PERFECT_MIN and time_to_end <= _game._audio_manager.NOTE_MARVELOUS_MIN then note_result = NoteResult.Perfect elseif time_to_end > _game._audio_manager.NOTE_MARVELOUS_MIN and time_to_end <= _game._audio_manager.NOTE_MARVELOUS_MAX then note_result = NoteResult.Marvelous elseif time_to_end > _game._audio_manager.NOTE_MARVELOUS_MAX and time_to_end <= _game._audio_manager.NOTE_PERFECT_MAX then note_result = NoteResult.Perfect elseif time_to_end > _game._audio_manager.NOTE_PERFECT_MAX and time_to_end <= _game._audio_manager.NOTE_GREAT_MAX then note_result = NoteResult.Great elseif time_to_end > _game._audio_manager.NOTE_GREAT_MAX and time_to_end <= _game._audio_manager.NOTE_GOOD_MAX then note_result = NoteResult.Good elseif time_to_end > _game._audio_manager.NOTE_OKAY_MAX and time_to_end <= _game._audio_manager.NOTE_OKAY_MAX then note_result = NoteResult.Okay else note_result = NoteResult.Miss end return true, note_result end return false, NoteResult.Miss end function NoteResult:release_timedelta_to_result(time_to_end, _game) time_to_end = time_to_end / _game._audio_manager.get_song_rate() if time_to_end >= _game._audio_manager.NOTE_OKAY_MIN * 2.0 and time_to_end <= _game._audio_manager.NOTE_OKAY_MAX * 2.0 then local note_result = nil if time_to_end > _game._audio_manager.NOTE_OKAY_MIN * 2.0 and time_to_end <= _game._audio_manager.NOTE_GOOD_MIN * 2.0 then note_result = NoteResult.Okay elseif time_to_end > _game._audio_manager.NOTE_GOOD_MIN * 2.0 and time_to_end <= _game._audio_manager.NOTE_GREAT_MIN * 2.0 then note_result = NoteResult.Good elseif time_to_end > _game._audio_manager.NOTE_GREAT_MIN * 2.0 and time_to_end <= _game._audio_manager.NOTE_PERFECT_MIN * 2.0 then note_result = NoteResult.Great elseif time_to_end > _game._audio_manager.NOTE_PERFECT_MIN * 2.0 and time_to_end <= _game._audio_manager.NOTE_MARVELOUS_MIN * 2.0 then note_result = NoteResult.Perfect elseif time_to_end > _game._audio_manager.NOTE_MARVELOUS_MIN * 2.0 and time_to_end <= _game._audio_manager.NOTE_MARVELOUS_MAX * 2.0 then note_result = NoteResult.Marvelous elseif time_to_end > _game._audio_manager.NOTE_MARVELOUS_MAX * 2.0 and time_to_end <= _game._audio_manager.NOTE_PERFECT_MAX * 2.0 then note_result = NoteResult.Perfect elseif time_to_end > _game._audio_manager.NOTE_PERFECT_MAX * 2.0 and time_to_end <= _game._audio_manager.NOTE_GREAT_MAX * 2.0 then note_result = NoteResult.Great elseif time_to_end > _game._audio_manager.NOTE_GREAT_MAX * 2.0 and time_to_end <= _game._audio_manager.NOTE_GOOD_MAX * 2.0 then note_result = NoteResult.Good else note_result = NoteResult.Okay end return true, note_result end return false, NoteResult.Miss end return NoteResult
fx_version 'cerulean' game 'gta5' author 'Yamie#9680' description 'Pizza Runs' lua54 'yes' shared_scripts { 'config.lua' } client_scripts { 'client.lua' } escrow_ignore { 'config.lua', -- Only ignore one file } server_script 'server.lua' --[[ client_scripts { "client.lua", "config.lua"} server_scripts { "server.lua", "config.lua" } ]]
-- See LICENSE for terms local mod_BuildDist -- fired when settings are changed/init local function ModOptions() local value = CurrentModOptions:GetProperty("BuildDist") mod_BuildDist = value if GameState.gameplay then CityDomeTeleporterConstruction[UICity].max_hex_distance_to_allow_build = value CityDomeTeleporterConstruction[UICity].max_range = value < 100 and 100 or value -- I don't think anymore will spawn once one has, but whatever DomeTeleporterConstructionController.max_hex_distance_to_allow_build = value DomeTeleporterConstructionController.max_range = value < 100 and 100 or value end end -- load default/saved settings OnMsg.ModsReloaded = ModOptions function OnMsg.ApplyModOptions(id) if id ~= CurrentModId then return end ModOptions() end GlobalVar("CityDomeTeleporterConstruction", {}) local table_unpack = table.unpack -- chooses which construct mode to start local orig_GetConstructionController = GetConstructionController function GetConstructionController(mode, ...) mode = mode or InGameInterfaceMode return mode == "dome_teleporter_construction" and CityDomeTeleporterConstruction[UICity] or orig_GetConstructionController(mode, ...) end -- add our custom construction controller function OnMsg.NewMap() if UICity then CityDomeTeleporterConstruction[UICity] = DomeTeleporterConstructionController:new() end end function OnMsg.LoadGame() CityDomeTeleporterConstruction[UICity] = DomeTeleporterConstructionController:new() --~ -- dbg --~ local dlg = ChoGGi.ComFuncs.OpenInExamineDlg(CityDomeTeleporterConstruction[UICity]) --~ dlg:EnableAutoRefresh() --~ dlg = ChoGGi.ComFuncs.OpenInExamineDlg(CityTunnelConstruction[UICity]) --~ dlg:EnableAutoRefresh() --~ -- dbg local AddPFTunnel = Tunnel.AddPFTunnel MapForEach("map", "DomeTeleporter", AddPFTunnel) end -- backup the CityTunnelConstruction obj local orig_CityTunnelConstruction local function GetCityTunnelConstruction() if not orig_CityTunnelConstruction or not orig_CityTunnelConstruction[UICity] then orig_CityTunnelConstruction = CityTunnelConstruction end return orig_CityTunnelConstruction end -- this is called by some func in TunnelConstructionDialog local function CallTunnelFunc(func, ...) GetCityTunnelConstruction() CityTunnelConstruction = CityDomeTeleporterConstruction local ret = {func(...)} CityTunnelConstruction = GetCityTunnelConstruction() return table_unpack(ret) end local orig_OpenTunnelConstructionInfopanel = OpenTunnelConstructionInfopanel function OpenTunnelConstructionInfopanel(template, ...) if template == "DomeTeleporter" then return CallTunnelFunc(orig_OpenTunnelConstructionInfopanel, template, ...) end return orig_OpenTunnelConstructionInfopanel(template, ...) end DefineClass.DomeTeleporterConstructionDialog = { __parents = {"TunnelConstructionDialog"}, mode_name = "dome_teleporter_construction", } -- we need to swap out the CityTunnelConstruction obj for these funcs local funcs = { "Init", "Open", "Close", "TryPlace", "OnKbdKeyDown", "OnMouseButtonDown", "OnMouseButtonDoubleClick", "OnMousePos", "OnShortcut", "OnSystemVirtualKeyboard", "OnXButtonRepeat", "OnXNewPacket", } local TunnelConstructionController_cls function OnMsg.ClassesBuilt() TunnelConstructionController_cls = TunnelConstructionController local TunnelConstructionDialog = TunnelConstructionDialog local DomeTeleporterConstructionDialog = DomeTeleporterConstructionDialog for i = 1, #funcs do local name = funcs[i] DomeTeleporterConstructionDialog[name] = function(...) return CallTunnelFunc(TunnelConstructionDialog[name], ...) end end end -- controller-> DefineClass.DomeTeleporterConstructionController = { __parents = {"TunnelConstructionController"}, max_hex_distance_to_allow_build = mod_BuildDist, } local orig_CreateConstructionGroup = CreateConstructionGroup function DomeTeleporterConstructionController.Activate(...) -- replace func so it returns our template function CreateConstructionGroup(template, ...) if template == "Tunnel" then template = "DomeTeleporter" end return orig_CreateConstructionGroup(template, ...) end -- get obj local ret = {TunnelConstructionController_cls.Activate(...)} -- restore func CreateConstructionGroup = orig_CreateConstructionGroup -- and done return table_unpack(ret) end
-- Copyright (c) 2016 Clockwork Engine. All Rights Reserved. -- See License.txt in the project root for license information. function Bullet_Project() group "Libs" project "Bullet" targetname "Bullet" kind "StaticLib" language "C++" prepareProject("Bullet", "../lib") files { "../Source/ThirdParty/Bullet/src/*.*", "../Source/ThirdParty/Bullet/src/BulletCollision/BroadphaseCollision/*.*", "../Source/ThirdParty/Bullet/src/BulletCollision/CollisionDispatch/*.*", "../Source/ThirdParty/Bullet/src/BulletCollision/CollisionShapes/*.*", "../Source/ThirdParty/Bullet/src/BulletCollision/Gimpact/*.*", "../Source/ThirdParty/Bullet/src/BulletCollision/NarrowPhaseCollision/*.*", "../Source/ThirdParty/Bullet/src/BulletDynamics/Character/*.*", "../Source/ThirdParty/Bullet/src/BulletDynamics/ConstraintSolver/*.*", "../Source/ThirdParty/Bullet/src/BulletDynamics/Dynamics/*.*", "../Source/ThirdParty/Bullet/src/BulletDynamics/Featherstone/*.*", "../Source/ThirdParty/Bullet/src/BulletDynamics/MLCPSolvers/*.*", "../Source/ThirdParty/Bullet/src/BulletDynamics/Vehicle/*.*", "../Source/ThirdParty/Bullet/src/BulletSoftBody/*.*", "../Source/ThirdParty/Bullet/src/LinearMath/*.*" } includedirs { "../Source/ThirdParty/Bullet/src/" } vpaths { ["*"] = "../Source/ThirdParty/Bullet/src/" } configuration {} strip() end
local editor = NewFile() editor:SetText('print("select")') -- this is to set proper styles, which are needed for EditorCallTip editor:Colourise(0, -1) local value = '' local CTS = editor.CallTipShow editor.CallTipShow = function(editor, pos, tip) value = tip end EditorCallTip(editor, 10) editor.CallTipShow = CTS if ide.osname == 'Windows' then ok(value:find("print") and not value:find("select"), "Tooltip ignores values in strings.") end local api = { t = { childs = { func = { args = "(args)", description = [[Description Line1 Line2 Line4 Line5 Line7]], returns = "(returns)", type = "function" } } } } ide:AddAPI("lua", "test", api) table.insert(ide.interpreter.api, "test") ReloadAPIs() local tooltip = GetTipInfo(editor, "t.func(") ok(tooltip:find("Line1\nLine2"), "Newlines are shown as newlines in tooltip") ok(tooltip:find("Line2\n\nLine4"), "Empty lines are shown as empty lines in tooltip") ok(tooltip:find("Line4\n\tLine5"), "Newlines with indentation are shown as lines with indentation in tooltip") ok(tooltip:find("Line5\n\t\n\tLine7"), "Empty lines with indentation are shown in tooltip") ide:RemoveAPI("lua", "test") ReloadAPIs() -- cleanup ide:GetDocument(editor):SetModified(false) ClosePage()
-- moves all folders to ReplicatedStorage. -- This is so we can edit things in the workspace. local new_parent = game.ReplicatedStorage for _, inst in pairs(script.Parent:GetChildren()) do if inst:IsA("Folder") then inst.Parent = new_parent end end script.Disabled = true script.Parent = nil
-- -*- lua -*- conflict("intel", "gcc") local version="2016" local xeversion=version..".".."1.40.463413" local intel_prefix="/opt/intel" local intelxe_prefix=pathJoin(intel_prefix, version) local icc_prefix=pathJoin(intelxe_prefix, "compilers_and_libraries_2016.3.210/linux") whatis("Name: Intel 64 Compiler XE") whatis("Version: 16.0.7") whatis("Description: Intel compiler can be used as an alternative to GNU's compiler") setenv("COMPILER_PREFIX", intel_prefix) setenv("COMPILER", "intel") setenv("COMPILER_TYPE", "intel") setenv("COMPILER_VERSION", version) setenv("FORTRAN_TYPE", "ifort") pushenv("CC", "icc") pushenv("CXX", "icpc") pushenv("FC", "ifort") setenv("DAALROOT", pathJoin(icc_prefix, "daal")) setenv("IPPROOT", pathJoin(icc_prefix, "ipp")) setenv("MKLROOT", pathJoin(icc_prefix, "mkl")) setenv("TBBROOT", pathJoin(icc_prefix, "tbb")) setenv("MPM_LAUNCHER", pathJoin(intelxe_prefix, "debugger_2016/mpm/mic/bin/start_mpm.sh")) setenv("F77", "ifort") setenv("F90", "ifort") prepend_path("PATH", pathJoin(intelxe_prefix, "debugger_2016/gdb/intel64_mic/bin")) prepend_path("PATH", pathJoin(icc_prefix, "bin/intel64")) prepend_path("CLASSPATH", pathJoin(os.getenv("DAALROOT"), "lib/daal.jar")) prepend_path("LD_LIBRARY_PATH", pathJoin(icc_prefix, "compiler/lib/intel64")) prepend_path("LD_LIBRARY_PATH", pathJoin(icc_prefix, "compiler/lib/intel64_lin")) prepend_path("LD_LIBRARY_PATH", pathJoin(os.getenv("IPPROOT"), "lib/intel64")) prepend_path("LD_LIBRARY_PATH", pathJoin(icc_prefix, "compiler/lib/intel64")) prepend_path("LD_LIBRARY_PATH", pathJoin(os.getenv("MKLROOT"), "lib/intel64")) prepend_path("LD_LIBRARY_PATH", pathJoin(os.getenv("TBBROOT"), "lib/intel64/gcc4.4")) prepend_path("LD_LIBRARY_PATH", pathJoin(intelxe_prefix, "debugger_2016/libipt/intel64/lib")) prepend_path("LD_LIBRARY_PATH", pathJoin(os.getenv("DAALROOT"), "lib/intel64_lin")) prepend_path("LD_LIBRARY_PATH", pathJoin(os.getenv("DAALROOT"), "../tbb/lib/intel64_lin/gcc4.4")) prepend_path("LD_LIBRARY_PATH", pathJoin(os.getenv("DAALROOT"), "../compiler/lib/intel64_lin")) prepend_path("LIBRARY_PATH", pathJoin(os.getenv("IPPROOT"), "lib/intel64")) prepend_path("LIBRARY_PATH", pathJoin(icc_prefix, "compiler/lib/intel64")) prepend_path("LIBRARY_PATH", pathJoin(os.getenv("MKLROOT"), "lib/intel64")) prepend_path("LIBRARY_PATH", pathJoin(os.getenv("TBBROOT"), "lib/intel64/gcc4.4")) prepend_path("LIBRARY_PATH", pathJoin(os.getenv("DAALROOT"), "lib/intel64_lin")) prepend_path("LIBRARY_PATH", pathJoin(os.getenv("DAALROOT"), "../tbb/lib/intel64_lin/gcc4.4")) prepend_path("LIBRARY_PATH", pathJoin(os.getenv("DAALROOT"), "../compiler/lib/intel64_lin")) prepend_path("NLSPATH", pathJoin(icc_prefix, "compiler/lib/intel64/locale/%l_%t/%N")) prepend_path("NLSPATH", pathJoin(os.getenv("MKLROOT"), "lib/intel64/locale/%l_%t/%N")) prepend_path("NLSPATH", pathJoin(icc_prefix, "debugger_2016/gdb/intel64_mic/share/locale/%l_%t/%N")) prepend_path("NLSPATH", pathJoin(icc_prefix, "debugger_2016/gdb/intel64/share/locale/%l_%t/%N")) prepend_path("CPATH", pathJoin(os.getenv("IPPROOT"), "ipp/include")) prepend_path("CPATH", pathJoin(os.getenv("MKLROOT"), "include")) prepend_path("CPATH", pathJoin(os.getenv("TBBROOT"), "tbb/include")) prepend_path("CPATH", pathJoin(os.getenv("DAALROOT"), "daal/include")) prepend_path("MIC_LD_LIBRARY_PATH", pathJoin(icc_prefix, "compiler/lib/mic")) prepend_path("MIC_LD_LIBRARY_PATH", pathJoin(os.getenv("IPPROOT"), "lib/mic")) prepend_path("MIC_LD_LIBRARY_PATH", pathJoin(icc_prefix, "compiler/lib/mic")) prepend_path("MIC_LD_LIBRARY_PATH", pathJoin(os.getenv("MKLROOT"), "lib/mic")) prepend_path("MIC_LD_LIBRARY_PATH", pathJoin(os.getenv("TBBROOT"), "lib/mic")) prepend_path("MIC_LIBRARY_PATH", pathJoin(icc_prefix, "compiler/lib/mic")) prepend_path("MIC_LIBRARY_PATH", pathJoin(os.getenv("TBBROOT"), "lib/mic")) prepend_path("FPATH", pathJoin(os.getenv("MKLROOT"), "include")) prepend_path("GDB_CROSS", pathJoin(intelxe_prefix, "debugger_2016/gdb/intel64_mic/bin/gdb-mic")) prepend_path("GDBSERVER_MIC", pathJoin(intelxe_prefix, "debugger_2016/gdb/targets/mic/bin/gdbserver")) prepend_path("INFOPATH", pathJoin(intelxe_prefix, "documentation_2016/en/debugger/gdb-ia/info")) prepend_path("INFOPATH", pathJoin(intelxe_prefix, "documentation_2016/en/debugger/gdb-mic/info")) prepend_path("INFOPATH", pathJoin(intelxe_prefix, "documentation_2016/en/debugger/gdb-igfx/info")) prepend_path("INTEL_PYTHONHOME", pathJoin(intelxe_prefix, "debugger_2016/python/intel64")) prepend_path("INTEL_LICENSE_FILE", pathJoin(intelxe_prefix, "licenses")) prepend_path("MANPATH", pathJoin(intelxe_prefix, "documentation_2016/en/debugger/gdb-ia/man/")) prepend_path("MANPATH", pathJoin(intelxe_prefix, "documentation_2016/en/debugger/gdb-mic/man/")) prepend_path("MANPATH", pathJoin(intelxe_prefix, "documentation_2016/en/debugger/gdb-igfx/man/"))
return { fadeOut = 1.5, mode = 2, id = "WANSHENGJIE5", once = true, fadeType = 1, fadein = 1.5, scripts = { { mode = 1, sequence = { { "“魔女们”的万圣夜\n\n<size=45>其五 Trick or treat!</size>", 1 } } }, { actor = 301171, actorShadow = true, actorName = "{namecode:87}&{namecode:19}", side = 0, dir = -1, hideOther = true, nameColor = "#ff0000", say = "Trick or treat!", subActors = { { actor = 306051, dir = -1, pos = { x = -1125 } } }, painting = { alpha = 0.3, time = 1 } }, { actor = 301051, actorShadow = true, actorName = "{namecode:6}&克利夫兰", side = 0, dir = -1, hideOther = true, nameColor = "#ff0000", say = "Trick or treat!", subActors = { { actor = 102091, dir = -1, pos = { x = -1125 } } }, painting = { alpha = 0.3, time = 1 } }, { actor = 307050, nameColor = "#a9f548", side = 2, actorName = "{namecode:95}", dir = 1, say = "给~顺便尝尝我烤的南瓜派吧", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 301171, side = 0, nameColor = "#a9f548", actorName = "{namecode:19}", dir = -1, say = "真美味,南瓜的香甜完全被诱发出来了!", paintingFadeOut = { time = 0.5, side = 1 }, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 306051, nameColor = "#a9f548", side = 0, actorName = "{namecode:87}", dir = -1, say = "没想到早已吃腻的南瓜,还能变得这么美味!{namecode:95}无论哪方面都是吾学习的榜样呢", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307050, nameColor = "#a9f548", side = 1, actorName = "{namecode:95}", dir = 1, say = "哈哈~我可不是完美无缺的哟", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 102091, side = 0, nameColor = "#a9f548", dir = -1, say = "嗯……我还是更中意海伦娜的", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 306051, actorName = "{namecode:87}", side = 2, nameColor = "#a9f548", dir = 1, say = "吾们走啦~", flashout = { black = true, dur = 1, alpha = { 0, 1 } }, flashin = { delay = 1, dur = 1, black = true, alpha = { 1, 0 } }, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307060, side = 0, nameColor = "#a9f548", actorName = "{namecode:96}", dir = 1, say = "一路走好", paintingFadeOut = { time = 0.5, side = 1 }, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307050, nameColor = "#a9f548", side = 1, actorName = "{namecode:95}", dir = 1, say = "呼……欸——!!", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 306051, actorName = "{namecode:87}", side = 2, nameColor = "#a9f548", dir = 1, say = "呀——南瓜灯都飘起来了?是、是幽灵吗——!", flashout = { black = true, dur = 1, alpha = { 0, 1 } }, flashin = { delay = 1, dur = 1, black = true, alpha = { 1, 0 } }, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 301051, side = 0, nameColor = "#a9f548", actorName = "{namecode:6}", dir = -1, say = "南瓜灯对着我们冲了过来——", paintingFadeOut = { time = 0.5, side = 1 }, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 301171, nameColor = "#a9f548", side = 1, actorName = "{namecode:19}", dir = 1, say = "眼前什么都看不到,全是南瓜灯……你们没事吧,可恶,吾辈的连装炮呢!?", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 102091, side = 0, nameColor = "#a9f548", dir = -1, say = "等等——", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307050, nameColor = "#a9f548", side = 1, actorName = "{namecode:95}", dir = 1, say = "你是——呀呀呀呀!", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 306051, nameColor = "#a9f548", side = 0, actorName = "{namecode:87}", dir = -1, say = "{namecode:95}——!!!", typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 301171, actorName = "{namecode:19}", side = 2, nameColor = "#a9f548", dir = -1, say = "南瓜灯都飞到天空中了……{namecode:96}也不见了!", flashout = { black = true, dur = 1, alpha = { 0, 1 } }, flashin = { delay = 1, dur = 1, black = true, alpha = { 1, 0 } }, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 306051, side = 1, nameColor = "#a9f548", actorName = "{namecode:87}", dir = 1, say = "发、发生了什么!?", paintingFadeOut = { time = 0.5, side = 0 }, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307060, actorName = "???", side = 2, nameColor = "#a9f548", dir = 1, blackBg = true, say = "翔——White姐,我本来也想像你那样缝几套衣服,可是动手后发现缝衣服好难……所以,先勉强用这个吧", withoutPainting = true, flashout = { black = true, dur = 1, alpha = { 0, 1 } }, flashin = { delay = 1, dur = 1, black = true, alpha = { 1, 0 } }, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307050, side = 1, nameColor = "#a9f548", say = "这个南瓜是不是忘记挖透气孔了,我怎么什么都看不到!?{namecode:96}、企业你们究竟要干什么?", dir = 1, blackBg = true, actorName = "???", withoutPainting = true, paintingFadeOut = { time = 0.5, side = 0 }, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307060, side = 0, nameColor = "#a9f548", actorName = "???", dir = 1, blackBg = true, say = "咳咳,我是gold,她是gray。总、总之,现在我们不是“大人”而是“孩子”,所以在万圣夜大闹一番也完全没问题!", withoutPainting = true, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 107060, side = 1, nameColor = "#a9f548", actorName = "???", dir = 1, blackBg = true, say = "我是输给了瑞……gold,所以来帮她忙——", withoutPainting = true, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307060, side = 0, nameColor = "#a9f548", actorName = "???", dir = 1, blackBg = true, say = "喂,你难道一点不甘心都没有吗!", withoutPainting = true, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 107060, side = 1, nameColor = "#a9f548", actorName = "???", dir = 1, blackBg = true, say = "好好好,那么长不大的孩子们就尽情恶作剧吧,我会用南瓜灯配合你们的", withoutPainting = true, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } }, { actor = 307060, side = 0, nameColor = "#a9f548", actorName = "???", dir = 1, blackBg = true, say = "哼哼,毕竟“我”可比你小不少,gray", withoutPainting = true, typewriter = { speed = 0.05, speedUp = 0.01 }, painting = { alpha = 0.3, time = 1 } } } }
local agw_service = require "service.agw" local log = ngx.log local ERR = ngx.ERR local DEBUG = ngx.DEBUG local new_timer = ngx.timer.at local api_sync_interval = 3 local server_state_check_interval = 20 local api_sync_timer local server_state_check_timer -- sync api proxy infos from mysql api_sync_timer = function(premature) if not premature then local ret, result=pcall(agw_service.syncApiInfo) if ret then log(DEBUG, "sync api info over") else log(ERR, "sync api info failed:", result) end local ok, err = new_timer(api_sync_interval, api_sync_timer) end end -- check servers' status server_state_check_timer = function(premature) if not premature then local ret, result = pcall(agw_service.checkState) if ret then log(DEBUG, "server state check over") else log(ERR, "error occured when check server state:", result) end local ok, err = new_timer(server_state_check_interval, server_state_check_timer) end end local ok, err = new_timer(api_sync_interval, api_sync_timer) if not ok then log(ERR, "failed to create timer: ", err) return end ok, err = new_timer(server_state_check_interval, server_state_check_timer) if not ok then log(ERR, "failed to create timer: ", err) return end
local nvim_lsp = require('lspconfig') -- enable null-ls integration (optional) require("null-ls").config {} require("lspconfig")["null-ls"].setup {} -- make sure to only run this once! nvim_lsp.tsserver.setup { -- Only needed for inlayHints. Merge this table with your settings or copy -- it from the source if you want to add your own init_options. init_options = require("nvim-lsp-ts-utils").init_options, -- on_attach = function(client, bufnr) -- disable tsserver formatting if you plan on formatting via null-ls client.resolved_capabilities.document_formatting = false client.resolved_capabilities.document_range_formatting = false local ts_utils = require("nvim-lsp-ts-utils") -- defaults ts_utils.setup { debug = false, disable_commands = false, enable_import_on_completion = false, -- import all import_all_timeout = 5000, -- ms -- lower numbers indicate higher priority import_all_priorities = { same_file = 1, -- add to existing import statement local_files = 2, -- git files or files with relative path markers buffer_content = 3, -- loaded buffer content buffers = 4, -- loaded buffer names }, import_all_scan_buffers = 100, import_all_select_source = false, -- eslint eslint_enable_code_actions = true, eslint_enable_disable_comments = true, eslint_bin = "eslint_d", eslint_enable_diagnostics = true, eslint_opts = {}, -- formatting enable_formatting = true, formatter = "eslint_d", formatter_opts = { "--fix" }, -- update imports on file move update_imports_on_move = false, require_confirmation_on_move = false, watch_dir = nil, -- filter diagnostics filter_out_diagnostics_by_severity = {}, filter_out_diagnostics_by_code = {}, -- inlay hints auto_inlay_hints = true, inlay_hints_highlight = "Comment", } -- required to fix code action ranges and filter diagnostics ts_utils.setup_client(client) -- no default maps, so you may want to define some here local opts = { silent = true } -- vim.api.nvim_buf_set_keymap(bufnr, "n", "gs", ":TSLspOrganize<CR>", opts) -- vim.api.nvim_buf_set_keymap(bufnr, "n", "gr", ":TSLspRenameFile<CR>", opts) -- vim.api.nvim_buf_set_keymap(bufnr, "n", "gi", ":TSLspImportAll<CR>", opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'go', '<cmd>lua vim.lsp.buf.document_symbol()<cr>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gy', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gr', '<cmd>lua vim.lsp.buf.rename()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>ff', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts) vim.api.nvim_buf_set_keymap( bufnr, 'n', '<leader>,k', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts ) vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>,c', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', ']g', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts) vim.api.nvim_buf_set_keymap(bufnr, 'n', '[g', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts) end } -- Use lua language server require'lua_lang_server'; -- Use telescope for few of fuzzy finding symbols local telescope = require('telescope') telescope.load_extension('lsp_handlers') -- Use nvim-compe for lsp auto completion require'compe_config' -- require'lsp_diagnostics'
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ========== PlaceObj('XTemplate', { group = "Infopanel Sections", id = "customRocketExpedition", PlaceObj('XTemplateGroup', { '__context_of_kind', "SupplyRocket", }, { PlaceObj('XTemplateTemplate', { 'comment', "cancel expedition", '__condition', function (parent, context) return context:CanCancel() end, '__template', "InfopanelButton", 'RolloverText', T(786602256921, --[[XTemplate customRocketExpedition RolloverText]] "Cancel the current expedition"), 'RolloverTitle', T(311734996852, --[[XTemplate customRocketExpedition RolloverTitle]] "Cancel Expedition"), 'Id', "idCancelExpedition", 'FoldWhenHidden', true, 'OnContextUpdate', function (self, context, ...) self:SetVisible(context:CanCancel()) end, 'OnPress', function (self, gamepad) CancelExpedition(self.context) end, 'Icon', "UI/Icons/IPButtons/cancel.tga", }), PlaceObj('XTemplateTemplate', { 'comment', "auto export", '__condition', function (parent, context) return context:IsLaunchValid() and context.expedition and context.expedition.route_id end, '__template', "InfopanelButton", 'RolloverHint', T(10110, --[[XTemplate customRocketExpedition RolloverHint]] "<left_click> Activate<newline><em>"), 'OnContextUpdate', function (self, context, ...) if context.expedition and not context.expedition.route then self:SetIcon("UI/Icons/IPButtons/automated_mode_off.tga") self:SetRolloverTitle(T(7814, "Automated Mode")) self:SetRolloverText(T(7815, "Automated Mode not possible while Rare Metal exports are forbidden.")) self:SetEnabled(false) else self:SetEnabled(true) if context.auto_export then self:SetIcon("UI/Icons/IPButtons/automated_mode_on.tga") self:SetRolloverTitle(T(7814, "Automated Mode")) self:SetRolloverText(T{11648, "If Automated mode is activated the Rocket will repeatedly travel to the Rival Colony and back while exchanging the negotiated resources. It'll land on the same amount and will launch to the rival when the cargo hold is full and the rocket is refueld.", context}) self:SetRolloverHint(T(10111, --[[XTemplate customSupplyRocket RolloverHint]] "<left_click> Activate Manual Mode <newline><em>")) self:SetRolloverHintGamepad(T(10112, "<ButtonA> Activate Manual Mode <newline><em>")) else self:SetIcon("UI/Icons/IPButtons/automated_mode_off.tga") self:SetRolloverTitle(T(7814, "Automated Mode")) self:SetRolloverText(T{11648, "If Automated mode is activated the Rocket will repeatedly travel to the Rival Colony and back while exchanging the negotiated resources. It'll land on the same amount and will launch to the rival when the cargo hold is full and the rocket is refueld.", context}) self:SetRolloverHint(T(8724, --[[XTemplate customSupplyRocket RolloverHint]] "<left_click> Activate Automated Mode <newline><em>")) self:SetRolloverHintGamepad(T(10113, "<ButtonA> Activate Automated Mode <newline><em>")) end end end, 'OnPressParam', "ToggleAutoExport", }), PlaceObj('XTemplateTemplate', { 'comment', "drones", '__template', "InfopanelSection", 'RolloverText', T(260933228141, --[[XTemplate customRocketExpedition RolloverText]] "Drones commanded by the Rocket ship."), 'OnContextUpdate', function (self, context, ...) self:SetVisible(context.landed and not context.cargo) end, 'Title', T(963695586350, --[[XTemplate customRocketExpedition Title]] "Drones<right><drone(DronesCount)>"), 'Icon', "UI/Icons/Sections/drone.tga", 'TitleHAlign', "stretch", }, { PlaceObj('XTemplateTemplate', { '__template', "InfopanelText", 'Text', T(134923339494, --[[XTemplate customRocketExpedition Text]] "<DronesStatusText>"), }), }), PlaceObj('XTemplateTemplate', { 'comment', "status", '__template', "InfopanelSection", 'RolloverText', T(414, --[[XTemplate customRocketExpedition RolloverText]] "Current status of the Rocket."), 'Title', T(49, --[[XTemplate customRocketExpedition Title]] "Status"), 'Icon', "UI/Icons/Sections/sensor.tga", }, { PlaceObj('XTemplateTemplate', { '__template', "InfopanelText", 'Text', T(301951063645, --[[XTemplate customRocketExpedition Text]] "<UIRocketStatus>"), }), }), PlaceObj('XTemplateTemplate', { 'comment', "payload", '__template', "InfopanelSection", 'RolloverText', T(416, --[[XTemplate customRocketExpedition RolloverText]] "Payload of the Rocket."), 'OnContextUpdate', function (self, context, ...) self:SetVisible(context.cargo) end, 'Title', T(415, --[[XTemplate customRocketExpedition Title]] "Payload"), 'Icon', "UI/Icons/Sections/storage.tga", }, { PlaceObj('XTemplateTemplate', { '__template', "InfopanelText", 'Text', T(417, --[[XTemplate customRocketExpedition Text]] "<CargoManifest>"), }), }), PlaceObj('XTemplateTemplate', { 'comment', "expedition cargo", '__template', "InfopanelSection", 'RolloverText', T(11252, --[[XTemplate customRocketExpedition RolloverText]] "The following payload is needed for the succesful completion of the mission. The Rocket won't launch itself until everything is loaded."), 'OnContextUpdate', function (self, context, ...) local visible = false local expedition = context.expedition if context.status~= "landing" and expedition and (expedition.export or expedition.num_drones or expedition.num_crew or expedition.rover_type) then visible = true end self:SetVisible(visible) end, 'Title', T(585890281334, --[[XTemplate customRocketExpedition Title]] "Required Payload"), 'Icon', "UI/Icons/Sections/basic.tga", }, { PlaceObj('XTemplateTemplate', { 'comment', "metals", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local export = context.expedition and context.expedition.export local amount = export and export.Metals or 0 self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(807216337504, --[[XTemplate customRocketExpedition Text]] "<resource('Metals' )><right><metals(ExportAmount_Metals, ExportTarget_Metals)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "concrete", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local export = context.expedition and context.expedition.export local amount = export and export.Concrete or 0 self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(669532297816, --[[XTemplate customRocketExpedition Text]] "<resource('Concrete' )><right><concrete(ExportAmount_Concrete,ExportTarget_Concrete)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "food", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local export = context.expedition and context.expedition.export local amount = export and export.Food or 0 self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(611737732106, --[[XTemplate customRocketExpedition Text]] "<resource('Food' )><right><food(ExportAmount_Food, ExportTarget_Food)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "polymers", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local export = context.expedition and context.expedition.export local amount = export and export.Polymers or 0 self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(936245422528, --[[XTemplate customRocketExpedition Text]] "<resource('Polymers' )><right><polymers(ExportAmount_Polymers, ExportTarget_Polymers)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "electronics", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local export = context.expedition and context.expedition.export local amount = export and export.Electronics or 0 self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(884086661379, --[[XTemplate customRocketExpedition Text]] "<resource('Electronics' )><right><electronics(ExportAmount_Electronics, ExportTarget_Electronics)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "seeds", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local export = context.expedition and context.expedition.export local amount = export and export.Seeds or 0 self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(761002033501, --[[XTemplate customRocketExpedition Text]] "<resource('Seeds' )><right><seeds(ExportAmount_Seeds, ExportTarget_Seeds)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "machine parts", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local export = context.expedition and context.expedition.export local amount = export and export.MachineParts or 0 self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(357955187464, --[[XTemplate customRocketExpedition Text]] "<resource('MachineParts' )><right><machineparts(ExportAmount_MachineParts, ExportTarget_MachineParts)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "drones", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local n = context.expedition and context.expedition.num_drones or 0 self:SetVisible(n > 0) self:SetText(self.Text) end, 'Text', T(851695389532, --[[XTemplate customRocketExpedition Text]] "Drones<right><drone(Crew_Drones, CrewTarget_Drones)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "colonists", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local expedition = context.expedition or empty_table self:SetVisible((expedition.num_crew or 0) > 0) self:SetText(self.Text) end, 'Text', T(917780390790, --[[XTemplate customRocketExpedition Text]] "<Crew_Specialization><right><colonist(Crew_Num, Crew_TargetNum)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "rover", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local rover = context.expedition and context.expedition.rover_type self:SetVisible(not not rover) self:SetText(self.Text) end, 'Text', T(382859997979, --[[XTemplate customRocketExpedition Text]] "<CrewRoverType><right><Crew_Rover>/<CrewTarget_Rover>"), }), PlaceObj('XTemplateTemplate', { 'comment', "fuel", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local export = context.expedition and context.expedition.export local amount = export and export.Fuel or 0 self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(199858432094, --[[XTemplate customRocketExpedition Text]] "<resource('Fuel' )><right><fuel(ExportAmount_Fuel, ExportTarget_Fuel)>"), }), }), PlaceObj('XTemplateTemplate', { '__template', "InfopanelSection", 'RolloverText', T(145440802511, --[[XTemplate customRocketExpedition RolloverText]] "Determines the amount of tradable resource to load.\n\nExport Amount<right><resource(TradeAmount)>"), 'RolloverHintGamepad', T(11553, --[[XTemplate customRocketExpedition RolloverHintGamepad]] "<LB> / <RB> change export amount"), 'OnContextUpdate', function (self, context, ...) self:SetVisible(context:CanChangeTradeAmount()) end, 'Title', T(504954621520, --[[XTemplate customRocketExpedition Title]] "Export Amount"), 'Icon', "UI/Icons/Sections/facility.tga", }, { PlaceObj('XTemplateTemplate', { '__template', "InfopanelSlider", 'BindTo', "TradeAmount", }), }), PlaceObj('XTemplateTemplate', { 'comment', "unload", '__template', "InfopanelSection", 'RolloverText', T(11253, --[[XTemplate customRocketExpedition RolloverText]] "The following cargo is not necessary for the mission and it's waiting to be unloaded. If you force launch the Rocket, the cargo will be dumped in orbit to provide space for the mission."), 'OnContextUpdate', function (self, context, ...) self:SetVisible(context.status~= "landing" and (context:HasExtraFuel() or context:GetStoredAmount() > 0)) end, 'Title', T(761527590297, --[[XTemplate customRocketExpedition Title]] "Unloading"), 'Icon', "UI/Icons/Sections/advanced.tga", }, { PlaceObj('XTemplateTemplate', { 'comment', "metals", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local amount = context:GetStoredAmount("Metals") self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(696833816815, --[[XTemplate customRocketExpedition Text]] "<resource('Metals' )><right><metals(Stored_Metals)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "concrete", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local amount = context:GetStoredAmount("Concrete") self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(729899810633, --[[XTemplate customRocketExpedition Text]] "<resource('Concrete' )><right><concrete(Stored_Concrete)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "food", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local amount = context:GetStoredAmount("Food") self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(511, --[[XTemplate customRocketExpedition Text]] "<resource('Food' )><right><food(Stored_Food)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "precious metals", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local amount = context:GetStoredAmount("PreciousMetals") self:SetVisible(amount > 0) self:SetText(T{12017, "<resource('PreciousMetals' )><right><preciousmetals(amount)>",amount=amount}) end, 'Text', T(563702272918, --[[XTemplate customRocketExpedition Text]] "<resource('PreciousMetals' )><right><preciousmetals(Stored_PreciousMetals)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "polymers", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local amount = context:GetStoredAmount("Polymers") self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(512, --[[XTemplate customRocketExpedition Text]] "<resource('Polymers' )><right><polymers(Stored_Polymers)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "electronics", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local amount = context:GetStoredAmount("Electronics") self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(513, --[[XTemplate customRocketExpedition Text]] "<resource('Electronics' )><right><electronics(Stored_Electronics)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "seeds", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local amount = context:GetStoredAmount("Seeds") self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(953471643149, --[[XTemplate customRocketExpedition Text]] "<resource('Seeds' )><right><seeds(Stored_Seeds)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "machine parts", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) local amount = context:GetStoredAmount("MachineParts") self:SetVisible(amount > 0) self:SetText(self.Text) end, 'Text', T(514, --[[XTemplate customRocketExpedition Text]] "<resource('MachineParts' )><right><machineparts(Stored_MachineParts)>"), }), PlaceObj('XTemplateTemplate', { 'comment', "fuel", '__template', "InfopanelText", 'FoldWhenHidden', true, 'ContextUpdateOnOpen', true, 'OnContextUpdate', function (self, context, ...) self:SetVisible(context:HasExtraFuel()) self:SetText(self.Text) end, 'Text', T(398402985264, --[[XTemplate customRocketExpedition Text]] "<resource('Fuel' )><right><fuel(Stored_Fuel)>"), }), }), }), })
-- Base16 Atelier Forest color -- Author: Bram de Haan (http://atelierbramdehaan.nl) -- to be use in your theme.lua -- symlink or copy to config folder `local color = require('color')` local M = {} M.base00 = "#1b1918" -- ---- M.base01 = "#2c2421" -- --- M.base02 = "#68615e" -- -- M.base03 = "#766e6b" -- - M.base04 = "#9c9491" -- + M.base05 = "#a8a19f" -- ++ M.base06 = "#e6e2e0" -- +++ M.base07 = "#f1efee" -- ++++ M.base08 = "#f22c40" -- red M.base09 = "#df5320" -- orange M.base0A = "#c38418" -- yellow M.base0B = "#7b9726" -- green M.base0C = "#3d97b8" -- aqua/cyan M.base0D = "#407ee7" -- blue M.base0E = "#6666ea" -- purple M.base0F = "#c33ff3" -- brown return M
--[[ Test loading the hms (body joints predictor) networks (LSTM + ConvNet3D). ]] require 'torch' require 'paths' require 'string' require 'nn' require 'nngraph' require 'image' require 'cutorch' require 'cunn' require 'cudnn' disp = require 'display' paths.dofile('../projectdir.lua') torch.manualSeed(14) torch.setdefaulttensortype('torch.FloatTensor') utils = paths.dofile('../util/utils.lua') paths.dofile('../util/draw.lua') paths.dofile('../util/heatmaps.lua') paths.dofile('../data.lua') paths.dofile('../sample_batch.lua') local opts = paths.dofile('../options.lua') opt = opts.parse(arg) opt.netType = 'hms-convnet3d_8' opt.dataset = 'ucf_sports' opt.nFeats = 256 opt.num_activities = 10 opt.nLayers = 2 opt.batchSize = 6 opt.seq_length = 16 opt.GPU = 1 opt.nGPU = 1 opt.rotRate=1 opt.scale = 0 opt.db = 'lsp' mode = 'train' nparts = 14 opt.params = { pixel_scale = 1, dims = {nparts, 64, 64}, feat_size = nparts } -- fetch data local data_loader = select_dataset_loader(opt.dataset, mode) local loader = data_loader[mode] local imgs_hms, imgs_feats, labels_tensor = getSampleBatch(loader, opt.batchSize, false) c = drawImgHeatmapSingle(batch_img[1][16], batch_heatmaps[1][16]:squeeze()) for ibatch=1, opt.batchSize do disp.image(batch_skeletons[ibatch]) end
local core = require("apisix.core") -- TODO: need a more powerful way to define the schema local args_schema = { i = "int", s = "string", t = "table", } local plugin_name = "example-plugin" local _M = { version = 0.1, priority = 1000, -- TODO: add a type field, may be a good idea name = plugin_name, } function _M.check_args(conf) local ok, err = core.schema.check_args(conf, args_schema) if not ok then return false, err end return true end function _M.rewrite(conf, ctx) core.log.warn("plugin rewrite phase, conf: ", core.json.encode(conf)) -- core.log.warn(" ctx: ", core.json.encode(ctx, true)) end function _M.access(conf, ctx) core.log.warn("plugin access phase, conf: ", core.json.encode(conf)) -- return 200, {message = "hit example plugin"} end return _M
-- @Author:pandayu -- @Version:1.0 -- @DateTime:2018-09-09 -- @Project:pandaCardServer CardGame -- @Contact: QQ:815099602 local _M = function(role,data) if not data.id or type(data.id) ~= "number" then return 2 end if not data.num or type(data.num) ~= "number" then return 2 end local pass,typ = role.shop:can_buy(data.id,data.num,data.pos) if not pass then return 2700 end local cost = role.shop:get_buy_cost(data.id,data.num,typ) local en,diamond,cost = role:check_resource_num(cost) if not en then return 100 end role:consume_resource(cost) local profit = role.shop:buy(data.id,data.num,typ,data.pos) role:gain_resource(profit) return 0,{data = profit} end return _M
ropes.can_place_rope_in_node = function(target_node_name) if ropes.can_extend_into_nodes[target_node_name] == true then return true end local target_def = minetest.registered_nodes[target_node_name] if target_def then if target_def.drawtype == "airlike" and ropes.can_extend_into_airlike then return true end if target_def.groups and target_def.groups.ropes_can_extend_into then return true end end return false end ropes.make_rope_on_timer = function(rope_node_name) return function(pos, elapsed) local currentend = minetest.get_node(pos) local currentmeta = minetest.get_meta(pos) local currentlength = currentmeta:get_int("length_remaining") local placer_name = currentmeta:get_string("placer") local newpos = {x=pos.x, y=pos.y-1, z=pos.z} local newnode = minetest.get_node(newpos) local oldnode = minetest.get_node(pos) if currentlength > 1 and (not minetest.is_protected(newpos, placer_name) or minetest.check_player_privs(placer_name, "protection_bypass")) then if ropes.can_place_rope_in_node(newnode.name) then minetest.add_node(newpos, {name=currentend.name, param2=oldnode.param2}) local newmeta = minetest.get_meta(newpos) newmeta:set_int("length_remaining", currentlength-1) newmeta:set_string("placer", placer_name) minetest.set_node(pos, {name=rope_node_name, param2=oldnode.param2}) ropes.move_players_down(pos, 1) else local timer = minetest.get_node_timer( pos ) timer:start( 1 ) end end end end local data = {} local c_air = minetest.get_content_id("air") ropes.destroy_rope = function(pos, nodes) local top = pos.y local bottom = pos.y-15 local voxel_manip = minetest.get_voxel_manip() local finished = false local ids_to_destroy = {} for _, node in pairs(nodes) do if minetest.registered_nodes[node] then ids_to_destroy[minetest.get_content_id(node)] = true end end while not finished do local emin, emax = voxel_manip:read_from_map({x=pos.x, y=bottom, z=pos.z}, {x=pos.x, y=top, z=pos.z}) voxel_manip:get_data(data) local voxel_area = VoxelArea:new{MinEdge=emin, MaxEdge=emax} bottom = emin.y for y = top, bottom, -1 do local index = voxel_area:index(pos.x, y, pos.z) if ids_to_destroy[data[index]] then data[index] = c_air else finished = true break end end voxel_manip:set_data(data) voxel_manip:write_to_map() voxel_manip:update_map() top = bottom - 1 bottom = bottom - 15 end end ropes.hanging_after_destruct = function(pos, top_node, middle_node, bottom_node) local node = minetest.get_node(pos) if node.name == top_node or node.name == middle_node or node.name == bottom_node then return -- this was done by another ladder or rope node changing this one, don't react end pos.y = pos.y + 1 -- one up local node_above = minetest.get_node(pos) if node_above.name == middle_node then minetest.swap_node(pos, {name=bottom_node, param2=node_above.param2}) end pos.y = pos.y - 2 -- one down local node_below = minetest.get_node(pos) if node_below.name == middle_node then ropes.destroy_rope(pos, {middle_node, bottom_node}) elseif node_below.name == bottom_node then minetest.swap_node(pos, {name="air"}) end end ropes.move_players_down = function(pos, radius) local all_objects = minetest.get_objects_inside_radius({x=pos.x, y=pos.y+radius, z=pos.z}, radius) local players = {} local _,obj for _,obj in pairs(all_objects) do if obj:is_player() then local obj_pos = obj:get_pos() if math.abs(obj_pos.x-pos.x) < 0.5 and math.abs(obj_pos.z-pos.z) < 0.5 then obj:set_pos({x=obj_pos.x, y=obj_pos.y-1, z=obj_pos.z}, true) end end end end