content
stringlengths
5
1.05M
--[[ This file is part of 'Masque', an add-on for World of Warcraft. For license information, please see the included License.txt file or visit https://github.com/StormFX/Masque. * File...: Options\LDB.lua * Author.: StormFX LDB Launcher ]] -- GLOBALS: LibStub local MASQUE, Core = ... ---------------------------------------- -- Locals --- -- @ Options\Core local Setup = Core.Setup ---------------------------------------- -- Setup --- function Setup.LDB(self) local LDB = LibStub("LibDataBroker-1.1", true) if LDB then -- @ Locales\enUS local L = self.Locale self.LDBO = LDB:NewDataObject(MASQUE, { type = "launcher", label = MASQUE, icon = "Interface\\Addons\\Masque\\Textures\\Icon", OnClick = function(Tip, Button) if Button == "LeftButton" or Button == "RightButton" then Core:ToggleOptions() end end, OnTooltipShow = function(Tip) if not Tip or not Tip.AddLine then return end Tip:AddLine(MASQUE) Tip:AddLine(L["Click to open Masque's settings."], 1, 1, 1) end, }) local LDBI = LibStub("LibDBIcon-1.0", true) if LDBI then LDBI:Register(MASQUE, self.LDBO, self.db.profile.LDB) self.LDBI = LDBI end end -- GC Setup.LDB = nil end
--[[ Copyright (c) 2010-2013 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local assert = assert local sqrt, cos, sin, atan2 = math.sqrt, math.cos, math.sin, math.atan2 local vector2 = {} vector2.__index = vector2 local function new(x,y) return setmetatable({x = x or 0, y = y or 0}, vector2) end local zero = new(0,0) local right = new(1,0) local left = new(-1,0) local up = new(0,1) local down = new(0,-1) --极小值 local EPSINON = 0.000001 --判断float是否等于0 local function isFloatZero( v ) return (v >= -EPSINON and v <= EPSINON) and 0 or v end --从极坐标得到向量 local function fromPolar( length, angle) local x, y = cos(angle)*length, sin(angle)*length return new(isFloatZero(x), isFloatZero(y)) end local function isvector2(v) assert(v) return type(v) == 'table' and type(v.x) == 'number' and type(v.y) == 'number' end --获得插值 local function lerp( P0, P1, t ) return P0*(1-t) + P1*t end function vector2:lerpInPlace( P1, t ) local _t = 1 - t self.x = self.x * _t + P1.x * t self.y = self.y * _t + P1.y * t end function vector2:clone() return new(self.x, self.y) end function vector2:unpack() return self.x, self.y end function vector2:__tostring() return "("..tonumber(self.x)..","..tonumber(self.y)..")" end function vector2.__unm(a) return new(-a.x, -a.y) end function vector2.__add(a,b) assert(isvector2(a) and isvector2(b), "Add: wrong argument types (<vector2> expected)") return new(a.x+b.x, a.y+b.y) end function vector2:add( b ) self.x, self.y = self.x + b.x,self.y + b.y end function vector2.__sub(a,b) assert(isvector2(a) and isvector2(b), "Sub: wrong argument types (<vector2> expected)") return new(a.x-b.x, a.y-b.y) end function vector2.__mul(a,b) if type(a) == "number" then return new(a*b.x, a*b.y) elseif type(b) == "number" then return new(b*a.x, b*a.y) else assert(isvector2(a) and isvector2(b), "Mul: wrong argument types (<vector2> or <number> expected)") return a.x*b.x + a.y*b.y end end function vector2.__div(a,b) assert(isvector2(a) and type(b) == "number", "wrong argument types (expected <vector2> / <number>)") return new(a.x / b, a.y / b) end function vector2.__eq(a,b) -- return a.x == b.x and a.y == b.y local diff_x = (a.x > b.x) and (a.x - b.x) or (b.x - a.x) local diff_y = (a.y > b.y) and (a.y - b.y) or (b.y - a.y) return diff_y < EPSINON and diff_x < EPSINON end function vector2.__lt(a,b) return a.x < b.x or (a.x == b.x and a.y < b.y) end function vector2.__le(a,b) return a.x <= b.x and a.y <= b.y end function vector2.permul(a,b) assert(isvector2(a) and isvector2(b), "permul: wrong argument types (<vector2> expected)") return new(a.x*b.x, a.y*b.y) end function vector2:quad_length() return self.x * self.x + self.y * self.y end function vector2:len() return sqrt(self.x * self.x + self.y * self.y) end function vector2.dist(a, b) assert(isvector2(a) and isvector2(b), "dist: wrong argument types (<vector2> expected)") local dx = a.x - b.x local dy = a.y - b.y return sqrt(dx * dx + dy * dy) end function vector2.dist2(a, b) assert(isvector2(a) and isvector2(b), "dist: wrong argument types (<vector2> expected)") local dx = a.x - b.x local dy = a.y - b.y return (dx * dx + dy * dy) end --本对象单位向量化 function vector2:normalizeInplace() local l = self:len() if l > 0 then self.x, self.y = self.x / l, self.y / l end return self end --产生新单位向量 function vector2:normalized() return self:clone():normalizeInplace() end --修改本实例 function vector2:rotateInplace(phi) local c, s = cos(phi), sin(phi) self.x, self.y = c * self.x - s * self.y, s * self.x + c * self.y return self end --产生新对象 function vector2:rotated(phi) local a_s, a_c = sin(phi), cos(phi) local mat11, mat12 = a_c, -a_s local mat21, mat22 = a_s, a_c return new(mat11*self.x + mat12*self.y, mat21*self.x + mat22*self.y) end --垂直 function vector2:perpendicular() return new(-self.y, self.x) end --正交 function vector2:orthogonal() return new(self.y, -self.x) end function vector2:projectOn(v) assert(isvector2(v), "invalid argument: cannot project vector2 on " .. type(v)) -- (self * v) * v / v:quad_length() local s = (self.x * v.x + self.y * v.y) / (v.x * v.x + v.y * v.y) return new(s * v.x, s * v.y) end function vector2:mirrorOn(v) assert(isvector2(v), "invalid argument: cannot mirror vector2 on " .. type(v)) -- 2 * self:projectOn(v) - self local s = 2 * (self.x * v.x + self.y * v.y) / (v.x * v.x + v.y * v.y) return new(s * v.x - self.x, s * v.y - self.y) end function vector2:cross(v) assert(isvector2(v), "cross: wrong argument types (<vector2> expected)") return self.x * v.y - self.y * v.x end function vector2:dot( other ) return (self.x * other.x) + (self.y * other.y) end function vector2:trimInplace(maxLen) local s = maxLen * maxLen / self:quad_length() s = (s > 1 and 1) or math.sqrt(s) self.x, self.y = self.x * s, self.y * s return self end function vector2:angleTo(other) if other then return atan2(self.y, self.x) - atan2(other.y, other.x) end return atan2(self.y, self.x) end function vector2:trimmed(maxLen) return self:clone():trimInplace(maxLen) end -- the module return setmetatable( { new = new, isvector2 = isvector2, zero = zero, right = right, left = left, up = up, down = down, fromPolar = fromPolar, lerp = lerp }, {__call = function(_, ...) return new(...) end} )
SkinningPerHour = { } SkinningPerHourGold = {} -- skinning items _items = {"172097", "172092", "172089", "172096", "172094", "172232"} BAGS = {0, 1, 2, 3, 4} items = {} quantity = {} local auctions = {} local function has_value (tab, val) for index, value in ipairs(tab) do if value == val then return true end end return false end function SkinningPerHour:CheckItemsInBags(f) for i=0, 4 do bagSlots = GetContainerNumSlots(i) slotsCheckLeft = bagSlots slotIndex = 1 while ( slotsCheckLeft > 0 ) do itemID = GetContainerItemID(i, slotIndex) if has_value(_items, tostring(itemID)) then texture, itemCount = GetContainerItemInfo(i, slotIndex) if quantity[tostring(itemID)] then quantity[tostring(itemID)] = quantity[tostring(itemID)] + itemCount else quantity[tostring(itemID)] = itemCount; end if not has_value(items, tostring(itemID)) then table.insert(items, tostring(itemID)) end end slotIndex = slotIndex+1 slotsCheckLeft = slotsCheckLeft-1 end end return items, quantity end function SkinningPerHour:GetColorByName(quality) if quality == 1 then return 1, 1, 1 end if quality == 2 then return 0.12, 1, 00 end if quality == 3 then return 0, 0.44, 0.87 end if quality == 4 then return 0.64, 0.21, 0.93 end end function SkinningPerHour:PresentBagItems(i, itemID, quantity) local itemName = C_Item.GetItemNameByID(tostring(itemID)) local quality = C_Item.GetItemQualityByID(tostring(itemID)) local range = tonumber(i) * 35 local negative = -range f.fontStrings[tostring(itemID)] = f:CreateFontString(nil, "OVERLAY", "GameTooltipText") -- f.fontStrings[tostring(itemID)]:SetPoint("CENTER", 20, negative) f.fontStrings[tostring(itemID)]:SetPoint("TOPLEFT", f, "TOPLEFT", 10, negative) f.fontStrings[tostring(itemID)]:SetTextColor(SkinningPerHour:GetColorByName(quality)) -- current gold per item worth -- 163 53 238 f.aquiredSinceStart[tostring(itemID)] = 0 -- print(itemName, quality, tostring(itemID)) local sessionQuantity = 0 local ahValue = 0 if f.aquiredSinceStart[itemID] then sessionQuantity = f.aquiredSinceStart[itemID] end if SkinningPerHourGold[itemID] then ahValue = SkinningPerHourGold[itemID] end if itemName then f.fontStrings[tostring(itemID)]:SetText(itemName .. " (" .. quantity .. ") (session: ".. sessionQuantity..")\nTotal value in the bags: " .. GetCoinTextureString(quantity * ahValue)) end end function event__LOOT_READY(f) local numItems = GetNumLootItems() for slotID = 1, numItems do local _, nme, qty = GetLootSlotInfo(slotID) if (qty or 0) > 0 then local _, link = GetItemInfo(nme) if link then local _, lootItemId = strsplit(":", link) if has_value(_items, tostring(lootItemId)) then if quantity[tostring(lootItemId)] then quantity[tostring(lootItemId)] = quantity[tostring(lootItemId)] + qty else quantity[tostring(lootItemId)] = qty; end if not has_value(items, tostring(lootItemId)) then table.insert(items, tostring(lootItemId)) end f.aquiredSinceStart[tostring(lootItemId)] = f.aquiredSinceStart[tostring(lootItemId)] + qty f.fontStrings[tostring(lootItemId)]:SetText(nme .. " (" .. quantity[tostring(lootItemId)] .. ") (session: "..f.aquiredSinceStart[tostring(lootItemId)]..")\nTotal value in the bags: " .. GetCoinTextureString(quantity[tostring(lootItemId)] * SkinningPerHourGold[tostring(lootItemId)])) f:SetHeight(#items * 50) local totalBagValue = 0 for index, value in pairs(items) do local itemValue = SkinningPerHourGold[tostring(value)] local itemQuantity = quantity[tostring(value)] totalBagValue = totalBagValue + itemQuantity * itemValue end f.fontStrings["total"]:SetText("Total bag value: "..GetCoinTextureString(totalBagValue)) end end end end end function SkinningPerHour:Run() local background = "Interface\\TutorialFrame\\TutorialFrameBackground" btn = CreateFrame("Button", nil, UIParent, "UIPanelButtonTemplate") f = CreateFrame("Frame",nil,UIParent) f:SetFrameStrata("MEDIUM") f:SetWidth(400) -- Set these to whatever height/width is needed local t = f:CreateTexture(nil,"BACKGROUND") t:SetTexture(background) t:SetAllPoints(f) f.texture = t f:SetPoint("TOPLEFT",5,-5) f.fontStrings = {} f.aquiredSinceStart = {} f:RegisterEvent("PLAYER_ENTERING_WORLD") f:RegisterEvent("LOOT_OPENED") f:RegisterEvent("AUCTION_HOUSE_BROWSE_RESULTS_UPDATED") f:RegisterEvent("AUCTION_HOUSE_SHOW") f:RegisterEvent("AUCTION_HOUSE_CLOSED") f:SetScript("OnEvent", function(self, event, ...) if event == "LOOT_OPENED" then event__LOOT_READY(f) elseif event == "PLAYER_ENTERING_WORLD" then local isLogin, isReload = ... if isLogin or isReload then SkinningPerHour.startTime = time() items, quantity = SkinningPerHour:CheckItemsInBags(f) f:SetHeight(#items * 50) -- for your Texture for index, value in pairs(items) do SkinningPerHour:PresentBagItems(index, value, quantity[value]) end local totalBagValue = 0 for index, value in pairs(items) do local itemValue = 0 local itemQuantity = 0 if SkinningPerHourGold[tostring(value)] then itemValue = SkinningPerHourGold[tostring(value)] end if quantity[tostring(value)] then itemQuantity = quantity[tostring(value)] end totalBagValue = totalBagValue + itemQuantity * itemValue end f.fontStrings["total"] = f:CreateFontString(nil, "OVERLAY", "GameTooltipText") -- f.fontStrings[tostring(itemID)]:SetPoint("CENTER", 20, negative) f.fontStrings["total"]:SetPoint("BOTTOMLEFT", f, "BOTTOMLEFT", 10, 10) f.fontStrings["total"]:SetTextColor(1, 1, 1) f.fontStrings["total"]:SetText("Total bag value: "..GetCoinTextureString(totalBagValue)) end elseif event == "AUCTION_HOUSE_SHOW" then btn = CreateFrame("Button", nil, UIParent, "UIPanelButtonTemplate") btn:SetPoint("CENTER", -345, -39) btn:SetFrameStrata("HIGH") btn:SetSize(220, 25) btn:SetText("Welander leather scanning tool") btn:SetScript("OnClick", function(self, button) local itemKeysToSearchFor = {} for index, value in pairs(_items) do local itemKey = C_AuctionHouse.MakeItemKey(tonumber(value)) table.insert(itemKeysToSearchFor, itemKey) end C_AuctionHouse.SearchForItemKeys(itemKeysToSearchFor, { sortOrder = Enum.AuctionHouseSortOrder.Buyout, reverseSort = false }) end) elseif event == "AUCTION_HOUSE_CLOSED" then btn:Hide() elseif event == "AUCTION_HOUSE_BROWSE_RESULTS_UPDATED" then local result = C_AuctionHouse.GetBrowseResults() for i in pairs(result) do SkinningPerHourGold[tostring(result[i].itemKey.itemID)] = result[i].minPrice end end end); f:Show() end SkinningPerHour:Run()
return { journal = { menu = { title = "Journal", }, _ = { elona = { news = { title = "News" }, quest = { title = "Quest" }, quest_item = { title = "Quest Item" }, title_and_ranking = { title = "Title & Ranking", fame = function(_1) return ("Fame: %d"):format(_1) end, arena = function(_1, _2) return ("EX Arena Wins:%s Highest Level:%s") :format(_1, _2) end, deadline = function(_1) return ("Deadline: %s Days left") :format(_1) end, pay = function(_1) return ("Pay: About %s gold pieces ") :format(_1) end }, income_and_expense = { title = "Income & Expense", bills = { labor = function(_1) return (" Labor : About %s GP") :format(_1) end, maintenance = function(_1) return (" Maint. : About %s GP") :format(_1) end, sum = function(_1) return (" Sum : About %s GP") :format(_1) end, tax = function(_1) return (" Tax : About %s GP") :format(_1) end, title = "Bills (Issued every 1st day)", unpaid = function(_1) return ("You have %s unpaid bills.") :format(_1) end }, salary = { sum = function(_1) return (" Sum : About %s GP") :format(_1) end, title = "Salary (Paid every 1st and 15th day)" } }, completed_quests = { title = "Completed Quests", } } } } }
--[[--------------------------------------------------------- Variables -----------------------------------------------------------]] local PANEL = {} --[[--------------------------------------------------------- Function: Init -----------------------------------------------------------]] function PANEL:Init() --> Category (No category support for Hungermod) local foodCat = { { name = 'Other', startExpanded = true, members = FoodItems } } --> Categories self:SetCategories(foodCat) // (DarkRP.getCategories().food) --> Variables self.actionText = Mania.f4.language.purchase --> Name self:SetNameCallback(function(item) return { text = item.name, color = Color(0, 0, 0, 245) } end) --> Money self:SetMoneyCallback(function(item) return { text = DarkRP.formatMoney(item.price), color = Color(0, 0, 0, 255) } end) --> Model self:SetModelCallback(function(item) --> Return return item.model end) --> Maximum self:SetMaximumCallback(function(item) --> Return return '' end) --> Action self:SetActionCallback(function(item) --> Purchase RunConsoleCommand('DarkRP', 'buyfood', item.name) --> Close if self.tab.shouldClose then hook.Call('ShowSpare2') end end) --> Validation self:SetValidationCallback(function(item) --> Variables local ply = LocalPlayer() --> Search local failSearch = self:GetSearchCallback()(item) if failSearch then return false, true, nil, nil, true end --> Checks if (item.requiresCook == nil or item.requiresCook == true) and not ply:isCook() then return false, true end if item.customCheck and not item.customCheck(LocalPlayer()) then return false, false end if not ply:canAfford(item.price) then return false, false end --> Return return true, nil, message, cost end) --> Disabled self:SetDisabledCallback(function(panel, can, important, _, _, isSearch) --> Search if isSearch then panel:SetVisible(false) return false end --> Defaults if can and (GAMEMODE.Config.hideNonBuyable or (important and GAMEMODE.Config.hideTeamUnbuyable)) then panel:SetVisible(false) return false else panel:SetVisible(true) return true end end) --> Reload self:ReloadContent() end --[[--------------------------------------------------------- Define: ManiaPage-food -----------------------------------------------------------]] derma.DefineControl('ManiaPage-food', 'ManiaPage-food', PANEL, 'ManiaPage-base')
-- Useful "smart" action subroutines that can check state info before trying -- to act, and possibly perform more complex decision-making. -- Will return a flag for whether or not the action was successful or not. -- -- All public actions have a verbose flag as a final optional parameter -- (default false). require 'codes.item' require 'codes.itemMenuType' require 'codes.menu' require 'codes.move' require 'codes.status' require 'codes.terrain' require 'mechanics.item' require 'mechanics.move' require 'utils.containers' require 'utils.enum' require 'utils.messages' require 'actions.basicactions' smartactions = {} local ACTION, ACTION_NAMES = enum.register({ 'Use', 'Give', 'Take', 'PickUp', 'Place', 'Swap', 'Throw', 'Set', }) local MENU_MODE = enum.register({ 'Normal', 'Held', 'Underfoot', }) local function actionSpec(actionType, followupMenu, possibleIfSticky) local followupMenu = followupMenu or codes.MENU.None if possibleIfSticky == nil then possibleIfSticky = true end return {action=actionType, followup=followupMenu, possibleIfSticky=possibleIfSticky} end -- Maps [menu type] -> [item mode] -> [action index] -- -> (action type, follow-up type, possible if sticky) local actionSpecMap = { [codes.ITEM_MENU_TYPE.UsableWithTarget] = { [MENU_MODE.Normal] = { [0] = actionSpec(ACTION.Use, codes.MENU.ItemFor, false), [1] = actionSpec(ACTION.Give, codes.MENU.ItemFor), [2] = actionSpec(ACTION.Place), [3] = actionSpec(ACTION.Throw), }, [MENU_MODE.Held] = { [0] = actionSpec(ACTION.Take, nil, false), [1] = actionSpec(ACTION.Swap, codes.MENU.ItemSwap, false), [2] = actionSpec(ACTION.Use, codes.MENU.ItemFor, false), }, [MENU_MODE.Underfoot] = { [0] = actionSpec(ACTION.PickUp), [1] = actionSpec(ACTION.Swap, codes.MENU.ItemSwap), [2] = actionSpec(ACTION.Use, codes.MENU.ItemFor, false), [3] = actionSpec(ACTION.Throw), }, }, [codes.ITEM_MENU_TYPE.Orb] = { [MENU_MODE.Normal] = { [0] = actionSpec(ACTION.Use, nil, false), [1] = actionSpec(ACTION.Give, codes.MENU.ItemFor), [2] = actionSpec(ACTION.Place), [3] = actionSpec(ACTION.Throw), }, [MENU_MODE.Held] = { [0] = actionSpec(ACTION.Take, nil, false), [1] = actionSpec(ACTION.Swap, codes.MENU.ItemSwap, false), [2] = actionSpec(ACTION.Use, nil, false), }, [MENU_MODE.Underfoot] = { [0] = actionSpec(ACTION.PickUp), [1] = actionSpec(ACTION.Swap, codes.MENU.ItemSwap), [2] = actionSpec(ACTION.Use, nil, false), [3] = actionSpec(ACTION.Throw), }, }, [codes.ITEM_MENU_TYPE.ThrowingItem] = { [MENU_MODE.Normal] = { [0] = actionSpec(ACTION.Throw, nil, false), [1] = actionSpec(ACTION.Give, codes.MENU.ItemFor), [2] = actionSpec(ACTION.Place), [3] = actionSpec(ACTION.Set), }, [MENU_MODE.Held] = { [0] = actionSpec(ACTION.Throw, nil, false), [1] = actionSpec(ACTION.Swap, codes.MENU.ItemSwap, false), [2] = actionSpec(ACTION.Take, nil, false), }, [MENU_MODE.Underfoot] = { [0] = actionSpec(ACTION.PickUp), [1] = actionSpec(ACTION.Throw, nil, false), [2] = actionSpec(ACTION.Swap, codes.MENU.ItemSwap), }, }, [codes.ITEM_MENU_TYPE.HeldItem] = { [MENU_MODE.Normal] = { [0] = actionSpec(ACTION.Give, codes.MENU.ItemFor), [1] = actionSpec(ACTION.Place), [2] = actionSpec(ACTION.Throw), }, [MENU_MODE.Held] = { [0] = actionSpec(ACTION.Take, nil, false), [1] = actionSpec(ACTION.Swap, codes.MENU.ItemSwap, false), }, [MENU_MODE.Underfoot] = { [0] = actionSpec(ACTION.PickUp), [1] = actionSpec(ACTION.Swap, codes.MENU.ItemSwap), [2] = actionSpec(ACTION.Throw), }, } } local function findActionIdx(actionSpecs, actionCode) for idx, spec in pairs(actionSpecs) do if spec.action == actionCode then return idx end end return nil end -- These actions are always prevented when under Embargo local preventedByEmbargo = { [ACTION.Use] = true, [ACTION.Throw] = true, } local function isHeld(item) return item.heldBy > 0 end -- true if placing is possible, false if not, and nil if the place -- option is completely gone from the menu local function placeOptionStatus(x, y, layout, traps) if layout[y][x].isStairs then return nil end for _, trap in ipairs(traps) do if trap.xPosition == x and trap.yPosition == y then return nil end end if layout[y][x].terrain ~= codes.TERRAIN.Normal then return false end return true end -- Gets the item at a certain position, or nil if there's nothing local function groundItem(items, x, y) for _, item in ipairs(items) do if item.xPosition == x and item.yPosition == y then return item end end return nil end -- Checks if a monster has some status. Returns nil if uncertain local function hasStatus(monster, statusType) if monster.statuses == nil then return nil end for _, status in ipairs(monster.statuses) do if status.statusType == statusType then return true end end return false end -- Perform some action with an item if possible. -- itemIdx is 0-indexed. A value of -1 means the item underfoot. -- followupIdx is also 0-indexed, if non-nil. -- state can be either from stateinfo or visibleinfo; it makes no difference. local function itemActionIfPossible(actionCode, itemIdx, state, followupIdx, verboseMessage) local leader = state.player.leader() local bag = state.player.bag() local underfoot = (itemIdx == -1) local item = nil if underfoot then item = groundItem(state.dungeon.entities.items(), leader.xPosition, leader.yPosition) -- If no items matched, there are no items underfoot if not item then return false end else assert(itemIdx < #bag and itemIdx >= 0, 'Bag index ' .. itemIdx .. ' out of range.') -- Convert to 1-indexing for access item = bag[itemIdx+1] end local held = isHeld(item) assert(not (held and underfoot), 'Item cannot be both held and underfoot.') -- If the action is "Swap" and the item is neither held nor underfoot, -- redirect the action to "Place". They're essentially interchangeable, -- just that Place turns into Swap when there's another item underfoot. if actionCode == ACTION.Swap and not held and not underfoot then actionCode = ACTION.Place end local menuType = mechanics.item.menuTypes[item.itemType] -- For throwing items, "Use" and "Throw" are synonymous if menuType == codes.ITEM_MENU_TYPE.ThrowingItem and actionCode == ACTION.Use then actionCode = ACTION.Throw end local menuMode = MENU_MODE.Normal if held then menuMode = MENU_MODE.Held end if underfoot then menuMode = MENU_MODE.Underfoot end actionSpecs = actionSpecMap[menuType][menuMode] -- actionIdx is 0-indexed local actionIdx = findActionIdx(actionSpecs, actionCode) assert(actionIdx, 'Invalid action: cannot ' .. ACTION_NAMES[actionCode] .. (held and ' held' or '') .. (underfoot and ' underfoot' or '') .. ' ' .. codes.ITEM_NAMES[item.itemType] .. '.') local action = actionSpecs[actionIdx] assert(action.followup == codes.MENU.None or followupIdx, 'Action ' .. ACTION_NAMES[actionCode] .. ' requires a followup index but none was given.') if action.followup == codes.MENU.ItemSwap then assert(not isHeld(bag[followupIdx+1]), 'Cannot swap out held item (' .. codes.ITEM_NAMES[bag[followupIdx+1].itemType] .. ').') end -- Can't access items if Terrified if hasStatus(leader, codes.STATUS.Terrified) then return false end -- Make sure the action can be done if under Embargo if preventedByEmbargo[actionCode] and hasStatus(leader, codes.STATUS.Embargo) then return false end -- Can't ingest an item if Muzzled if actionCode == ACTION.Use and hasStatus(leader, codes.STATUS.Muzzled) and mechanics.item.isIngested(item.itemType) then return false end -- If picking up an item, check that there's space if actionCode == ACTION.PickUp and #bag >= state.player.bagCapacity() then return false end if item.isSticky and not action.possibleIfSticky then return false end -- If the action comes after a "Place" action then we need to check that -- the option isn't disabled local placeIdx = findActionIdx(actionSpecs, ACTION.Place) if placeIdx and actionIdx >= placeIdx then local placeStatus = placeOptionStatus(leader.xPosition, leader.yPosition, state.dungeon.layout(), state.dungeon.entities.traps()) if not placeStatus then if actionCode == ACTION.Place then return false end -- The option is completely gone if placeStatus == nil then -- Shift the action index back by 1 actionIdx = actionIdx - 1 end end end -- We're good to go. Carry out the action. if verboseMessage then local firstPart = verboseMessage local secondPart = nil if type(verboseMessage) == 'table' then firstPart = verboseMessage[1] secondPart = verboseMessage[2] end local message = firstPart .. ' ' .. codes.ITEM_NAMES[item.itemType] if secondPart then message = message .. ' ' .. secondPart end message = message .. '.' messages.report(message) end -- Carry out the primary action if underfoot then basicactions.openGroundMenu() -- Abort if the menu isn't right assert(menuinfo.getMenu() == codes.MENU.Ground, 'No item underfoot.') basicactions.makeMenuSelection(actionIdx) else basicactions.itemAction(itemIdx, actionIdx) end -- If necessary, carry out the followup action -- If using an item held by a party member other than the leader, ignore the followup -- if it's an ItemFor menu, since the holder of the item will automatically be targeted if action.followup ~= codes.MENU.None and not (action.followup == codes.MENU.ItemFor and item.heldBy > 1) then basicactions.itemFollowupAction(action.followup, followupIdx) end return true end -- itemIdx and teammate are both 0-indexed function smartactions.useItemIfPossible(itemIdx, state, teammate, verbose) local verboseMessage = nil if verbose then verboseMessage = 'Using' if teammate then verboseMessage = {verboseMessage, 'on teammate ' .. (teammate+1)} end end -- Default to using on the leader if needed return itemActionIfPossible(ACTION.Use, itemIdx, state, teammate or 0, verboseMessage) end -- itemIdx and teammate are both 0-indexed function smartactions.giveItemIfPossible(itemIdx, state, teammate, verbose) local verboseMessage = nil if verbose then verboseMessage = 'Giving' if teammate then verboseMessage = {verboseMessage, 'to teammate ' .. (teammate+1)} end end -- Default to using on the leader if needed return itemActionIfPossible(ACTION.Give, itemIdx, state, teammate or 0, verboseMessage) end -- itemIdx is 0-indexed function smartactions.takeItemIfPossible(itemIdx, state, verbose) local verboseMessage = verbose and 'Taking' or nil return itemActionIfPossible(ACTION.Take, itemIdx, state, nil, verboseMessage) end -- itemIdx is 0-indexed function smartactions.pickUpItemIfPossible(itemIdx, state, verbose) local verboseMessage = verbose and 'Picking up' or nil return itemActionIfPossible(ACTION.PickUp, itemIdx, state, nil, verboseMessage) end -- This turns into swapping if there's an item underfoot -- itemIdx is 0-indexed function smartactions.placeItemIfPossible(itemIdx, state, verbose) local verboseMessage = verbose and 'Placing' or nil return itemActionIfPossible(ACTION.Place, itemIdx, state, nil, verboseMessage) end -- itemIdx and swapBagIdx are both 0-indexed function smartactions.swapItemIfPossible(itemIdx, state, swapBagIdx, verbose) -- If swapBagIdx is -1, make it nil to signify underfoot if swapBagIdx == -1 then swapBagIdx = nil end local verboseMessage = nil if verbose then verboseMessage = 'Swapping out' local otherItem, conjunction = nil, 'and' if swapBagIdx then otherItem = state.player.bag()[swapBagIdx+1] else -- Look underfoot local leader = state.player.leader() otherItem = groundItem(state.dungeon.entities.items(), leader.xPosition, leader.yPosition) conjunction = 'for' end -- If there's another item, include it in the message if otherItem then verboseMessage = {'Swapping', conjunction .. ' ' .. codes.ITEM_NAMES[otherItem.itemType]} end end return itemActionIfPossible(ACTION.Swap, itemIdx, state, swapBagIdx, verboseMessage) end -- itemIdx is 0-indexed function smartactions.throwItemIfPossible(itemIdx, state, verbose) local verboseMessage = verbose and 'Throwing' or nil return itemActionIfPossible(ACTION.Throw, itemIdx, state, nil, verboseMessage) end -- itemIdx is 0-indexed function smartactions.setItemIfPossible(itemIdx, state, verbose) local verboseMessage = verbose and 'Setting' or nil return itemActionIfPossible(ACTION.Set, itemIdx, state, nil, verboseMessage) end -- Look for an item in the bag. If it exists, return the first matching index -- (0-indexed) that's greater than or equal to startIdx (default 0), and the -- item itself. Otherwise, return nil local function searchBag(bag, itemType, startIdx) local startIdx = startIdx or 0 for i=startIdx,#bag-1 do local bagItem = bag[i+1] -- Access using 1-indexing if bagItem.itemType == itemType then return i, bagItem end end end -- Search for items in the bag, and try to take the action with first possible occurrence. -- validityFn is an extra validity check to perform not done by the actionFn. If nil, -- no extra checks will be performed. -- Variadic arguments should be everything for actionFn except itemIdx and state. local function itemTypeActionIfPossible(validityFn, actionFn, itemType, state, ...) local bag = state.player.bag() local itemIdx, bagItem = searchBag(bag, itemType) while itemIdx do if (validityFn == nil or validityFn(bagItem)) and actionFn(itemIdx, state, unpack(arg)) then return true end itemIdx, bagItem = searchBag(bag, itemType, itemIdx + 1) end return false end function smartactions.useItemTypeIfPossible(itemType, state, verbose) return itemTypeActionIfPossible(nil, smartactions.useItemIfPossible, itemType, state, nil, verbose) end function smartactions.useMaxElixirIfPossible(state, verbose) return smartactions.useItemTypeIfPossible(codes.ITEM.MaxElixir, state, verbose) end -- Restore some stat by using an item if the stat falls below some threshold. -- Attempt to use the item that restores the most without being wasteful. -- If allowWaste is false, the non-wasteful condition is strictly enforced. -- possibleItemsWithRestoreValues should be a list of {item: value} pairs. local function useRestoringItemWithThreshold( state, stat, statMax, threshold, allowWaste, possibleItemsWithRestoreValues, verbose) -- Don't need restoration if stat > threshold then return false end local statDeficit = statMax - stat -- Collect a list of all usable restoration items in the bag local bestItem = nil local bestItemValue = nil for _, item in ipairs(state.player.bag()) do local itemValue = possibleItemsWithRestoreValues[item.itemType] if itemValue ~= nil and not item.isSticky then if bestItem == nil then if allowWaste or itemValue <= statDeficit then -- This is the first usable item we've found bestItem = item bestItemValue = itemValue end elseif itemValue <= statDeficit and itemValue > bestItemValue then -- The new item restores more than the current best, and still isn't wasteful bestItem = item bestItemValue = itemValue elseif bestItemValue > statDeficit and itemValue < bestItemValue then -- The current best item is wasteful. Reduce the value to be less wasteful -- This condition should only be hit if allowWaste is true bestItem = item bestItemValue = itemValue end end end if bestItem ~= nil then return smartactions.useItemTypeIfPossible(bestItem.itemType, state, verbose) end return false -- No items found end -- Eat a food item if hungry (belly <= threshold), and a usable one exists. -- Try to use the one that restores the most belly without being wasteful. function smartactions.eatFoodIfHungry(state, belly, maxBelly, threshold, allowWaste, verbose) return useRestoringItemWithThreshold(state, belly, maxBelly or 100, threshold or 50, allowWaste, mechanics.item.lists.food, verbose) end -- eatFoodIfHungry with a threshold of 0 function smartactions.eatFoodIfBellyEmpty(state, belly, verbose) return smartactions.eatFoodIfHungry(state, belly, nil, 0, true, verbose) end -- Use a healing item if health is low (HP <= threshold), and a usable one -- exists. Try to use the one that restored the most HP without being wasteful. function smartactions.healIfLowHP(state, HP, maxHP, threshold, allowWaste, verbose) -- Check for Heal Block if hasStatus(state.player.leader(), codes.STATUS.HealBlock) then return false end return useRestoringItemWithThreshold(state, HP, maxHP, threshold, allowWaste, mechanics.item.lists.healing, verbose) end -- Use an item to cure status (for the leader), if possible. -- Optionally specify a single status code or list of status codes that should be cured -- (others will be ignored). If statusesToCure is nil, all statuses will be considered function smartactions.cureStatusIfPossible(state, statusesToCure) -- If statusesToCure is a single code, make it into a list if statusesToCure and type(statusesToCure) ~= 'table' then statusesToCure = {statusesToCure} end local activeStatuses = state.player.leader().statuses if not activeStatuses then return false end -- Go through each status, trying each possible cure until one works for _, status in ipairs(activeStatuses) do if statusesToCure == nil or containers.arrayContains(statusesToCure, status.statusType) then local cures = mechanics.item.lists.curesForStatus[status.statusType] if cures then for _, cure in ipairs(cures) do if smartactions.useItemTypeIfPossible(cure, state, true) then return true end end end end end -- No cures for any statuses return false end function smartactions.giveItemTypeIfPossible(itemType, state, verbose) return itemTypeActionIfPossible(function(item) return not isHeld(item) end, smartactions.giveItemIfPossible, itemType, state, nil, verbose) end function smartactions.throwItemTypeIfPossible(itemType, state, verbose) return itemTypeActionIfPossible(function(item) return not isHeld(item) or mechanics.item.menuTypes[item.itemType] == codes.ITEM_MENU_TYPE.ThrowingItem end, smartactions.throwItemIfPossible, itemType, state, nil, verbose) end -- Use a move at some index (0-indexed) if it has PP, isn't sealed, and isn't -- subsequent in a link chain function smartactions.useMoveIfPossible(moveIdx, moveList, user, verbose) -- Can't use moves if Terrified if hasStatus(user, codes.STATUS.Terrified) then return false end local move = moveList[moveIdx+1] -- Access using 1-indexing -- Can't use certain moves if Muzzled if hasStatus(user, codes.STATUS.Muzzled) and mechanics.move(move.moveID).failsWhileMuzzled then return false end -- Can't use certain moves if Taunted if hasStatus(user, codes.STATUS.Taunted) and not mechanics.move(move.moveID).usableWhileTaunted then return false end -- If Encored, can only use a move if it was the last one used if hasStatus(user, codes.STATUS.Encore) and not move.isLastUsed then return false end if move and move.PP > 0 and not move.isSealed and not move.isDisabled and not move.subsequentInLinkChain then messages.reportIfVerbose('Using ' .. codes.MOVE_NAMES[move.moveID] .. '.', verbose) basicactions.useMove(moveIdx) return true end return false end -- Use a move at some index (0-indexed) if possible, and if the target is -- in range of the user. function smartactions.useMoveIfInRange(moveIdx, moveList, user, target, layout, visRad, verbose) local moveID = moveList[moveIdx+1].moveID -- Access using 1-indexing if mechanics.move.inRange(moveID, target.xPosition, target.yPosition, user.xPosition, user.yPosition, layout, visRad) then return smartactions.useMoveIfPossible(moveIdx, moveList, user, verbose) end return false end return smartactions
local gumbo = require "gumbo" local parse = gumbo.parse local assert = assert local _ENV = nil do local input = "<body><WhatAcrazyNAME></WhatAcrazyNAME>" local document = assert(parse(input)) local body = assert(document.body) assert(body.childNodes.length == 1) local node = assert(body.childNodes[1]) assert(node.type == "element") assert(node.localName == "whatacrazyname") end do local input = "<body><SVG><FOREIGNOBJECT></FOREIGNOBJECT></SVG>" local document = assert(parse(input)) local body = assert(document.body) assert(body.childNodes.length == 1) local svg = assert(body.childNodes[1]) assert(svg.type == "element") assert(svg.localName == "svg") local node = assert(svg.childNodes[1]) assert(node.type == "element") assert(node.localName == "foreignObject") end do local input = "<body><MATH><FOREIGNOBJECT></FOREIGNOBJECT></math>" local document = assert(parse(input)) local body = assert(document.body) assert(body.childNodes.length == 1) local math = assert(body.childNodes[1]) assert(math.type == "element") assert(math.localName == "math") local node = assert(math.childNodes[1]) assert(node.type == "element") assert(node.localName == "foreignobject") end
{{/* Views the value of a given DB entry. Usage: `-entry <id> <key>`. Recommended trigger: Command trigger with trigger `entry`. */}} {{ $args := parseArgs 2 "**Syntax:** `-entry <id> <key>`" (carg "int" "id") (carg "string" "key") }} {{ with dbGet ($args.Get 0) ($args.Get 1) }} {{ $value := json .Value }} {{ if gt (len $value) 1900 }} {{ sendMessage nil (complexMessage "file" $value "content" "**Value:**") }} {{ else }} {{ sendMessage nil (printf "**Value:**\n%s" $value) }} {{ end }} {{ else }} Could not find entry. {{ end }}
return (function(self) u(self).enabled = true end)(...)
local util = require 'lspconfig.util' return { default_config = { cmd = { 'prosemd-lsp', '--stdio' }, filetypes = { 'markdown' }, root_dir = util.find_git_ancestor, single_file_support = true, }, docs = { description = [[ https://github.com/kitten/prosemd-lsp An experimental LSP for Markdown. Please see the manual installation instructions: https://github.com/kitten/prosemd-lsp#manual-installation ]], default_config = { root_dir = util.find_git_ancestor, }, }, }
-- SPDX-License-Identifier: MIT -- Copyright (c) 2014-2020 Iruatã Martins dos Santos Souza local data = require'data' local np = require'9p' local conn = np.newconn(io.read, function (buf) io.write(buf) io.output():flush() end) conn:attach("iru", "") local f, g = conn:newfid(), conn:newfid() conn:walk(conn.rootfid, f, "/tmp") conn:clone(f, g) conn:create(g, "file", 420, 1) local ftext = "this is a test\n" local buf = data.new(ftext) local n = conn:write(g, 0, buf) if n ~= #buf then error("test: expected to write " .. #buf .. " bytes but wrote " .. n) end conn:clunk(g) if pcall(np.walk, conn, conn.rootfid, g, "/tmp/.lua9p.non.existant..") ~= false then error("test: succeeded when shouldn't (walking to non-existing file)") end conn:walk(conn.rootfid, g, "/tmp/file") conn:open(g, 0) local st = conn:stat(g) -- Remove last byte of the file st.length = st.length - 1 conn:wstat(g, st) buf = conn:read(g, 0, st.length) conn:remove(g) buf:layout{str = {0, #buf, 'string'}} -- The trailing \n was removed by wstat, we add it again to check the read if buf.str .. "\n" == ftext then io.stderr:write("test ok\n") else error("test failed") end conn:clunk(f) conn:clunk(conn.rootfid)
local present, lsp_install = pcall(require, 'nvim-lsp-installer.servers') local present_2, lsp_installer = pcall(require, 'nvim-lsp-installer') if not present or not present_2 then return end -- LSP require("lsp") local function install_server(server) local ok, server_cmd = lsp_install.get_server(server) if ok then if not server_cmd:is_installed() then server_cmd:install() end end end local function install_missing_servers() local required_servers = O.lsp.ensure_installed for _, server in pairs(required_servers) do install_server(server) end end lsp_installer.on_server_ready(function(server) local opts = { on_attach = require("lsp").common_on_attach, capabilities = require("lsp").get_capabilities(), } -- (optional) Customize the options passed to the server -- if server.name == "tsserver" then -- opts.root_dir = function() ... end -- end -- This setup() function is exactly the same as lspconfig's setup function (:help lspconfig-quickstart) server:setup(opts) vim.cmd [[ do User LspAttachBuffers ]] end) local process = require "nvim-lsp-installer.process" lsp_installer.lsp_attach_proxy = process.debounced(function() -- As of writing, if the lspconfig server provides a filetypes setting, it uses FileType as trigger, otherwise it uses BufReadPost vim.cmd("doautoall") end) install_missing_servers()
local __exports = LibStub:NewLibrary("ovale/simulationcraft/splitter", 80300) if not __exports then return end local __class = LibStub:GetLibrary("tslib").newClass local ipairs = ipairs local wipe = wipe local __AST = LibStub:GetLibrary("ovale/AST") local isNodeType = __AST.isNodeType local __definitions = LibStub:GetLibrary("ovale/simulationcraft/definitions") local TagPriority = __definitions.TagPriority local __texttools = LibStub:GetLibrary("ovale/simulationcraft/text-tools") local OvaleTaggedFunctionName = __texttools.OvaleTaggedFunctionName local find = string.find local sub = string.sub local insert = table.insert __exports.Splitter = __class(nil, { constructor = function(self, ovaleAst, ovaleDebug, ovaleData) self.ovaleAst = ovaleAst self.ovaleData = ovaleData self.SplitByTag = function(tag, node, nodeList, annotation) local visitor = self.SPLIT_BY_TAG_VISITOR[node.type] if not visitor then self.tracer:Error("Unable to split-by-tag node of type '%s'.", node.type) return else return visitor(tag, node, nodeList, annotation) end end self.SplitByTagAction = function(tag, node, nodeList, annotation) local bodyNode, conditionNode local actionTag, invokesGCD local name = "UNKNOWN" local actionType = node.func if actionType == "item" or actionType == "spell" then local firstParamNode = node.rawPositionalParams[1] local id, name if firstParamNode.type == "variable" then name = firstParamNode.name id = annotation.dictionary and annotation.dictionary[name] elseif isNodeType(firstParamNode, "value") then name = firstParamNode.value id = firstParamNode.value end if id then if actionType == "item" then actionTag, invokesGCD = self.ovaleData:GetItemTagInfo(id) elseif actionType == "spell" then actionTag, invokesGCD = self.ovaleData:GetSpellTagInfo(id) end else self.tracer:Print("Warning: Unable to find %s '%s'", actionType, name) end elseif actionType == "texture" then local firstParamNode = node.rawPositionalParams[1] local id, name if firstParamNode.type == "variable" then name = firstParamNode.name id = annotation.dictionary and annotation.dictionary[name] elseif isNodeType(firstParamNode, "value") then name = firstParamNode.value id = name end if id then actionTag, invokesGCD = self.ovaleData:GetSpellTagInfo(id) if actionTag == nil then actionTag, invokesGCD = self.ovaleData:GetItemTagInfo(id) end end if actionTag == nil then actionTag = "main" invokesGCD = true end else self.tracer:Print("Warning: Unknown action type '%'", actionType) end if not actionTag then actionTag = "main" invokesGCD = true self.tracer:Print("Warning: Unable to determine tag for '%s', assuming '%s' (actionType: %s).", name, actionTag, actionType) end if actionTag == tag then bodyNode = node elseif invokesGCD and TagPriority(actionTag) < TagPriority(tag) then conditionNode = node end return bodyNode, conditionNode end self.SplitByTagAddFunction = function(tag, node, nodeList, annotation) local bodyName, conditionName = OvaleTaggedFunctionName(node.name, tag) if not bodyName or not conditionName then return end local bodyNode, conditionNode = self.SplitByTag(tag, node.child[1], nodeList, annotation) if not bodyNode or bodyNode.type ~= "group" then local newGroupNode = self.ovaleAst:NewNode(nodeList, true) newGroupNode.type = "group" if bodyNode then newGroupNode.child[1] = bodyNode end bodyNode = newGroupNode end if not conditionNode or conditionNode.type ~= "group" then local newGroupNode = self.ovaleAst:NewNode(nodeList, true) newGroupNode.type = "group" if conditionNode then newGroupNode.child[1] = conditionNode end conditionNode = newGroupNode end local bodyFunctionNode = self.ovaleAst:NewNode(nodeList, true) bodyFunctionNode.type = "add_function" bodyFunctionNode.name = bodyName bodyFunctionNode.child[1] = bodyNode local conditionFunctionNode = self.ovaleAst:NewNode(nodeList, true) conditionFunctionNode.type = "add_function" conditionFunctionNode.name = conditionName conditionFunctionNode.child[1] = conditionNode return bodyFunctionNode, conditionFunctionNode end self.SplitByTagCustomFunction = function(tag, node, nodeList, annotation) local bodyNode, conditionNode local functionName = node.name if annotation.taggedFunctionName[functionName] then local bodyName, conditionName = OvaleTaggedFunctionName(functionName, tag) if bodyName and conditionName then bodyNode = self.ovaleAst:NewNode(nodeList) bodyNode.name = bodyName bodyNode.type = "custom_function" bodyNode.func = bodyName bodyNode.asString = bodyName .. "()" conditionNode = self.ovaleAst:NewNode(nodeList) conditionNode.name = conditionName conditionNode.type = "custom_function" conditionNode.func = conditionName conditionNode.asString = conditionName .. "()" end else local functionTag = annotation.functionTag[functionName] if not functionTag then if find(functionName, "bloodlust") then functionTag = "cd" elseif find(functionName, "getinmeleerange") then functionTag = "shortcd" elseif find(functionName, "interruptactions") then functionTag = "cd" elseif find(functionName, "summonpet") then functionTag = "shortcd" elseif find(functionName, "useitemactions") then functionTag = "cd" elseif find(functionName, "usepotion") then functionTag = "cd" elseif find(functionName, "useheartessence") then functionTag = "cd" end end if functionTag then if functionTag == tag then bodyNode = node end else self.tracer:Print("Warning: Unable to determine tag for '%s()'.", node.name) bodyNode = node end end return bodyNode, conditionNode end self.SplitByTagGroup = function(tag, node, nodeList, annotation) local index = #node.child local bodyList = {} local conditionList = {} local remainderList = {} while index > 0 do local childNode = node.child[index] index = index - 1 if childNode.type ~= "comment" then local bodyNode, conditionNode = self.SplitByTag(tag, childNode, nodeList, annotation) if conditionNode then insert(conditionList, 1, conditionNode) insert(remainderList, 1, conditionNode) end if bodyNode then if #conditionList == 0 then insert(bodyList, 1, bodyNode) elseif #bodyList == 0 then wipe(conditionList) insert(bodyList, 1, bodyNode) else local unlessNode = self.ovaleAst:NewNode(nodeList, true) unlessNode.type = "unless" local condition = self:ConcatenatedConditionNode(conditionList, nodeList, annotation) local body = self:ConcatenatedBodyNode(bodyList, nodeList, annotation) if condition and body then unlessNode.child[1] = condition unlessNode.child[2] = body end wipe(bodyList) wipe(conditionList) insert(bodyList, 1, unlessNode) local commentNode = self.ovaleAst:NewNode(nodeList) commentNode.type = "comment" insert(bodyList, 1, commentNode) insert(bodyList, 1, bodyNode) end if index > 0 then childNode = node.child[index] if childNode.type ~= "comment" then bodyNode, conditionNode = self.SplitByTag(tag, childNode, nodeList, annotation) if not bodyNode and index > 1 then local start = index - 1 for k = index - 1, 1, -1 do childNode = node.child[k] if childNode.type == "comment" then if childNode.comment and sub(childNode.comment, 1, 5) == "pool_" then start = k break end else break end end if start < index - 1 then for k = index - 1, start, -1 do insert(bodyList, 1, node.child[k]) end index = start - 1 end end end end while index > 0 do childNode = node.child[index] if childNode.type == "comment" then insert(bodyList, 1, childNode) index = index - 1 else break end end end end end local bodyNode = self:ConcatenatedBodyNode(bodyList, nodeList, annotation) local conditionNode = self:ConcatenatedConditionNode(conditionList, nodeList, annotation) local remainderNode = self:ConcatenatedConditionNode(remainderList, nodeList, annotation) if bodyNode then if conditionNode then local unlessNode = self.ovaleAst:NewNode(nodeList, true) unlessNode.type = "unless" unlessNode.child[1] = conditionNode unlessNode.child[2] = bodyNode local groupNode = self.ovaleAst:NewNode(nodeList, true) groupNode.type = "group" groupNode.child[1] = unlessNode bodyNode = groupNode end conditionNode = remainderNode end return bodyNode, conditionNode end self.SplitByTagIf = function(tag, node, nodeList, annotation) local bodyNode, conditionNode = self.SplitByTag(tag, node.child[2], nodeList, annotation) if conditionNode then local lhsNode = node.child[1] local rhsNode = conditionNode if node.type == "unless" then lhsNode = self:NewLogicalNode("not", lhsNode, nil, nodeList) end local andNode = self:NewLogicalNode("and", lhsNode, rhsNode, nodeList) conditionNode = andNode end if bodyNode then local ifNode = self.ovaleAst:NewNode(nodeList, true) ifNode.type = node.type ifNode.child[1] = node.child[1] ifNode.child[2] = bodyNode bodyNode = ifNode end return bodyNode, conditionNode end self.SplitByTagState = function(tag, node, nodeList, annotation) return node, nil end self.SPLIT_BY_TAG_VISITOR = { ["action"] = self.SplitByTagAction, ["add_function"] = self.SplitByTagAddFunction, ["custom_function"] = self.SplitByTagCustomFunction, ["group"] = self.SplitByTagGroup, ["if"] = self.SplitByTagIf, ["state"] = self.SplitByTagState, ["unless"] = self.SplitByTagIf } self.tracer = ovaleDebug:create("SimulationCraftSplitter") end, NewLogicalNode = function(self, operator, lhsNode, rhsNode, nodeList) local node = self.ovaleAst:NewNode(nodeList, true) node.type = "logical" node.operator = operator if operator == "not" then node.expressionType = "unary" node.child[1] = lhsNode else node.expressionType = "binary" node.child[1] = lhsNode node.child[2] = rhsNode end return node end, ConcatenatedConditionNode = function(self, conditionList, nodeList, annotation) local conditionNode if #conditionList > 0 then if #conditionList == 1 then conditionNode = conditionList[1] elseif #conditionList > 1 then local lhsNode = conditionList[1] local rhsNode = conditionList[2] conditionNode = self:NewLogicalNode("or", lhsNode, rhsNode, nodeList) for k = 3, #conditionList, 1 do lhsNode = conditionNode rhsNode = conditionList[k] conditionNode = self:NewLogicalNode("or", lhsNode, rhsNode, nodeList) end end end return conditionNode end, ConcatenatedBodyNode = function(self, bodyList, nodeList, annotation) local bodyNode if #bodyList > 0 then bodyNode = self.ovaleAst:NewNode(nodeList, true) bodyNode.type = "group" for k, node in ipairs(bodyList) do bodyNode.child[k] = node end end return bodyNode end, })
--[[ A problem with table.sort is that the sort is not stable, that is, elements that the comparison function considers equal may not keep their original order in the array after the sort. How can you do a stable sort in Lua? ]] -- Bubble sort is crappy, but at least it's stable function stablesort(a, comparator) comparator = comparator or function(a, b) return a < b end while true do local swapped = false for i = 2, #a do if comparator(a[i], a[i - 1]) then a[i], a[i - 1] = a[i - 1], a[i] swapped = true end end if not swapped then break end end end function rprint(l) function aux(l) if type(l) == "table" then io.write("{") for i, v in ipairs(l) do aux(v) if i ~= #l then io.write(", ") end end io.write("}") else io.write(tostring(l)) end end aux(l) io.write("\n") end l = {{1, "first"}, {1, "second"}, {1, "third"}, {0, "should go to front"}} stablesort(l, function(a, b) return a[1] < b[1] end) rprint(l) --> {{0, should go to front}, {1, first}, {1, second}, {1, third}}
local role_mgr = {} function role_mgr:init( scene ) self.scene_mgr = scene self.entity_mgr = scene.entity_mgr self.aoi = scene.aoi self:init_archetype() end function role_mgr:init_archetype( ) self.role_archetype = self.entity_mgr:CreateArchetype({ "umo.position", "umo.target_pos", "umo.uid", "umo.type_id", "umo.hp", "umo.scene_obj_type", "umo.move_speed", "umo.aoi_handle", }) end function role_mgr:create_role( uid, role_id, pos_x, pos_y, pos_z, aoi_handle ) local role = self.entity_mgr:CreateEntityByArcheType(self.role_archetype) self.entity_mgr:SetComponentData(role, "umo.position", {x=pos_x, y=pos_y, z=pos_z}) self.entity_mgr:SetComponentData(role, "umo.target_pos", {x=pos_x, y=pos_y, z=pos_z}) self.entity_mgr:SetComponentData(role, "umo.uid", {value=uid}) self.entity_mgr:SetComponentData(role, "umo.type_id", {value=role_id}) self.entity_mgr:SetComponentData(role, "umo.hp", {cur=1000, max=1000}) self.entity_mgr:SetComponentData(role, "umo.scene_obj_type", {value=SceneObjectType.Role}) self.entity_mgr:SetComponentData(role, "umo.move_speed", {value=100}) self.entity_mgr:SetComponentData(role, "umo.aoi_handle", {value=aoi_handle}) return role end return role_mgr
local PlayerData = require(script.Parent.PlayerData) local DanceManager = require(script.Parent.Parent.DanceManager) -- userid > PlayerData local playerList = {} game.Players.PlayerAdded:Connect(function (player: Player) playerList[player.UserId] = PlayerData.new(player) end) game.Players.PlayerRemoving:Connect(function (player: Player) -- removing the player data so their Player instance can be garbage collected playerList[player.UserId] = nil DanceManager.playerStopDancing(player) end) local PlayerManager = {} function PlayerManager.getPlayerData(userid: number) return playerList[userid] end return PlayerManager
--[[ FastText - Code for testing a trained model ]]-- require 'torch' require 'io' require 'nn' require 'os' require 'xlua' require 'pl.stringx' require 'pl.file' tds = require('tds') utils = require('utils') cmd = torch.CmdLine() cmd:option('-model', 'ag_news.t7', 'trained model file path') cmd:option('-test', 'data/ag_news.test', 'testing file path') cmd:option('-gpu', 1, 'whether to use gpu (1 = use gpu, 0 = not). use the same option used to train the model.') test_params = cmd:parse(arg) if test_params.gpu > 0 then require 'cutorch' require 'cunn' cutorch.setDevice(1) end print('loading the trained model...') train_params = torch.load(test_params.model) print('testing for the new data...') train_params.model:evaluate() local acc, total = 0, 0 for line in io.lines(test_params.test) do local label, text = utils.get_tuple(line) local ngrams = utils.tokenize(text, train_params.wordNgrams) local chooped_ngrams = utils.chop_ngram(train_params, ngrams) if #chooped_ngrams > 0 then local tensor = torch.Tensor(chooped_ngrams) if train_params.gpu > 0 then tensor = tensor:cuda() end local predictions = train_params.model:forward(tensor) local _, max_ids = predictions:max(1) if max_ids[1] == train_params.label2index[label] then acc = acc + 1 end end total = total + 1 end print('accuracy on test data [' .. test_params.test .. '] = ' .. (acc / total))
function createSprintorioPlayerIfNotExists(player) if not global.sprintorio[player.index] then global.sprintorio[player.index] = { ["sprinting"] = false, ["oxygen"] = 100 } end end function regenSprintGUI(player) local guiLeft = player.gui.left if guiLeft["oxygen_frame"] then guiLeft["oxygen_frame"].destroy() end local oxygenFrame = guiLeft.add{ type = "frame", name = "oxygen_frame", caption = "Oxygen" } oxygenFrame.add{ type = "progressbar", name = "oxygen_bar", } updatePlayerOxygen(player, global.sprintorio[player.index]["oxygen"]) end function getPlayerSprintorioOxygen(playerSprintorio) if playerSprintorio.sprinting then return math.max(0, playerSprintorio.oxygen - 5) else return math.min(100, playerSprintorio.oxygen + 5) end end function updatePlayerOxygen(player, value) global.sprintorio[player.index]["oxygen"] = value player.gui.left["oxygen_frame"]["oxygen_bar"].value = (value / 100) end function togglePlayerSprint(player) local playerSprintorio = global.sprintorio[player.index] playerSprintorio["sprinting"] = not playerSprintorio["sprinting"] end function updatePlayerSprintStatus(player) local playerSprintorio = global.sprintorio[player.index] local updatedOxygen = getPlayerSprintorioOxygen(playerSprintorio) updatePlayerOxygen(player, updatedOxygen) if playerSprintorio.oxygen > 0 and playerSprintorio.sprinting then if player.character_running_speed_modifier < 0.65 then player.character_running_speed_modifier = 0.65 end end if playerSprintorio.oxygen == 0 or not playerSprintorio.sprinting then playerSprintorio.sprinting = false player.character_running_speed_modifier = 0 end end
sinastra_cold_presence_modifier = class({}) function sinastra_cold_presence_modifier:OnCreated( kv ) self.damage = self:GetAbility():GetSpecialValueFor("damage") self.move_speed_percentage = self:GetAbility():GetSpecialValueFor("move_speed_percentage") self.no_movement_duration = self:GetAbility():GetSpecialValueFor("no_movement_duration") self.ice_block_duration = self:GetAbility():GetSpecialValueFor("ice_block_duration") if not IsServer() then return end local caster = self:GetParent() self.oldPos = caster:GetAbsOrigin() self.stacks = 0 self.interval = 0.1 self:StartIntervalThink( self.interval ) end function sinastra_cold_presence_modifier:OnIntervalThink() if not IsServer() then return end local caster = self:GetParent() -- Apply Damage -- EncounterApplyDamage(caster, self:GetCaster(), self, self.damage * self.interval, DAMAGE_TYPE_MAGICAL, DOTA_DAMAGE_FLAG_NONE) if self.stacks >= 100 then return end local vector_distance = self.oldPos - caster:GetAbsOrigin() local distance = (vector_distance):Length2D() if distance ~= 0 then self.stacks = self.stacks - ( distance / 10 ) if self.stacks < 0 then self.stacks = 0 end self:SetStackCount( self.stacks ) else self.stacks = self.stacks + ( 100 / self.no_movement_duration * self.interval ) self:SetStackCount( self.stacks ) end self.oldPos = caster:GetAbsOrigin() if self.stacks >= 100 then -- Modifier -- caster:AddNewModifier(self:GetCaster(), self, "casting_frozen_modifier", {duration = self.ice_block_duration}) caster:AddNewModifier(self:GetCaster(), self, "modifier_stunned", {duration = self.ice_block_duration}) -- Particle -- PATTACH_ABSORIGIN-PATTACH_ABSORIGIN_FOLLOW-PATTACH_CUSTOMORIGIN local particle = ParticleManager:CreateParticle("particles/units/heroes/hero_winter_wyvern/wyvern_cold_embrace_buff.vpcf", PATTACH_ABSORIGIN, caster) ParticleManager:SetParticleControl( particle, 0, caster:GetAbsOrigin() ) PersistentParticle_Add(particle) -- Sound -- StartSoundEventReliable("Hero_Winter_Wyvern.ColdEmbrace", caster) local timer = Timers:CreateTimer(self.ice_block_duration, function() ParticleManager:DestroyParticle( particle, false ) ParticleManager:ReleaseParticleIndex( particle ) particle = nil self.stacks = 0 self:SetStackCount( self.stacks ) end) PersistentTimer_Add(timer) end end function sinastra_cold_presence_modifier:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE, MODIFIER_PROPERTY_TOOLTIP, } return funcs end function sinastra_cold_presence_modifier:GetModifierMoveSpeedBonus_Percentage( params ) return self.move_speed_percentage end function sinastra_cold_presence_modifier:OnTooltip( params ) return self.no_movement_duration end function sinastra_cold_presence_modifier:GetAttributes() return MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE end function sinastra_cold_presence_modifier:IsHidden() return false end function sinastra_cold_presence_modifier:IsPurgable() return false end function sinastra_cold_presence_modifier:IsPurgeException() return false end function sinastra_cold_presence_modifier:IsStunDebuff() return false end function sinastra_cold_presence_modifier:IsDebuff() return true end
--The Nameless Soul --by EdwardDarksong --[[ The Nameless Soul is a Soul that's forgotten it's name and so it hunts for another's name, and will take it by any means... --]] settings = { Particles = true } wait() plr = game:GetService("Players").LocalPlayer char = plr.Character mouse = plr:GetMouse() cam = game:GetService("Workspace").Camera db = game:GetService("Debris") function find(target,class) for _,p in pairs(target:GetChildren()) do if p.ClassName == class then return p end end end Banned = { } function rev(number) local num = tostring(number) --print(num) if num:sub(1,1) == "-" then num = num:sub(2) else num = "-"..num end --print(tonumber(num)) return tonumber(num) end function set(number,goal) local num = tostring(number) if num:sub(1,1) == "-" then num = "-"..goal else num = goal end return tonumber(num) end local h = find(char,"Humanoid")if h then h.Name = "Soul";h.MaxHealth = math.huge end function t_damage(hit) local h = find(hit.Parent,"Humanoid") if h then h.Health = h.Health-15 end end function new_char(c) c.HumanoidRootPart:Remove() local h1 = find(c,"Humanoid") if h1 then h1:Remove() end wait(); local rl = c["Right Leg"] local ll = c["Left Leg"] local ra = c["Right Arm"] local la = c["Left Arm"] rl.Touched:connect(t_damage) ll.Touched:connect(t_damage) ra.Touched:connect(t_damage) la.Touched:connect(t_damage) c.Torso.Touched:connect(t_damage) c.Head.Touched:connect(t_damage) if c:FindFirstChild("Animate") then c.Animate:Remove() end local t = 0.75 local color = BrickColor.new("Really black") local bc = c["Body Colors"] bc["HeadColor"] = color bc["LeftArmColor"] = color bc["RightArmColor"] = color bc["RightLegColor"] = color bc["LeftLegColor"] = color bc["TorsoColor"] = color rl.Transparency = t ra.Transparency = t la.Transparency = t ll.Transparency = t c.Head.Transparency = t c.Torso.Transparency = t rl.BrickColor = color ll.BrickColor = color la.BrickColor = color ra.BrickColor = color c.Head.BrickColor = color c.Torso.BrickColor = color if c.Head:FindFirstChild("face") then c.Head.face:Remove() end for _,p in pairs(c:GetChildren()) do if p.ClassName=="Hat" or p.ClassName=="Shirt" or p.ClassName=="Pants" or p.ClassName=="CharacterMesh" then p:Remove() end end if settings.Particles then local p1 = Instance.new("ParticleEmitter",c.Torso) p1.Size = NumberSequence.new(0.2,0.35) p1.Texture = "http://www.roblox.com/asset/?id=242201991" p1.EmissionDirection = "Back" p1.Rate = 0 --p1.LightEmission = 5 p1.Lifetime = NumberRange.new(0.8,1.1) p1.Speed = NumberRange.new(0.1,0.1) p1.Color = ColorSequence.new(Color3.new(0,0,0),Color3.new(0,0,0)) p1.Transparency = NumberSequence.new(0.3,0.5) p1.Enabled = true p1.Name = "p1" p1:Clone().Parent = ll p1:Clone().Parent = rl p1:Clone().Parent = ra p1:Clone().Parent = la --p1:Clone().Parent = c.Head end local w = Instance.new("Weld",c);w.Name="" w.Part0 = c.Torso w.Part1 = ra w.C1 = CFrame.new(-1.5,0.1,-0.2) * CFrame.Angles(0.4,0,0) local w = Instance.new("Weld",c);w.Name="" w.Part0 = c.Torso w.Part1 = la w.C1 = CFrame.new(1.5,0.1,-0.2) * CFrame.Angles(0.4,0,0) local w = Instance.new("Weld",c);w.Name="" w.Part0 = c.Torso w.Part1 = rl w.C1 = CFrame.new(-0.5,2,0) * CFrame.Angles(0.15,0,0) local w = Instance.new("Weld",c);w.Name="" w.Part0 = c.Torso w.Part1 = ll w.C1 = CFrame.new(0.5,2,0) * CFrame.Angles(0.15,0,0) local m = Instance.new("Part",c) m.Size = Vector3.new(1,2,1) m.Position = Vector3.new(c.Torso.Position.X,c.Torso.Position.Y+3,c.Torso.Position.Z) m.CanCollide = false m.Transparency = 1 m.Anchored = true m.Locked = true m.Name = "m" local l = Instance.new("Part",c) l.Size = Vector3.new(1,2,1) l.Position = c.Torso.Position l.CanCollide = false l.Transparency = 1 l.Anchored = true l.Locked = true l.Name = "l" local camera = Instance.new("Part",c) camera.Size = Vector3.new(2,2,1) camera.Transparency = 1 camera.CanCollide = false local weld = Instance.new("Weld",camera) weld.Part0=c.Torso weld.Part1=camera weld.C1 = CFrame.new(0,0,0) cam.CameraSubject = camera local p = Instance.new("BodyPosition",c.Torso) p.P = 11000 p.D = 1000 p.Name = "path" p.MaxForce = Vector3.new(20000,20000,20000) local p2 = Instance.new("BodyGyro",c.Torso)--c.HumanoidRootPart) p2.D = 1e3 p2.P = 1e7 p2.MaxTorque = Vector3.new(0,1e7,0) p2.Name = "path2" local W = false local S = false local A = false local D = false local Space = false local m2 = m:Clone() m2.Parent = c coroutine.resume(coroutine.create(function() game:GetService("RunService").Stepped:connect(function() for _,p in pairs(c:GetChildren())do if p.ClassName=="Part"then p.CanCollide = false p.Material = "Neon" end end local hum = find(c,"Humanoid") for _,p in pairs(c:GetChildren()) do for _,p in pairs(p:GetChildren()) do if p.ClassName == "ParticleEmitter" then p:Emit(24) end end end if hum then if hum:FindFirstChild("Animator") then hum.Animator:Remove() end for _,p in pairs(c:GetChildren()) do if p.ClassName == "Part" then p.CanCollide = false end end hum.WalkSpeed = 0 hum.NameDisplayDistance = 0 --hum.AutoRotate = false hum.Name = "Soul" hum.JumpPower = 0 hum.PlatformStand = false end l.Position = c.Head.CFrame:toWorldSpace(CFrame.new(0,0,0)).p p2.CFrame = CFrame.new(Vector3.new(),(mouse.Hit.p - c.Torso.CFrame.p).unit * 100) if W then local x = rev((cam.CFrame-c.Torso.CFrame.p).X) local z = rev((cam.CFrame-c.Torso.CFrame.p).Z) m.CFrame = l.CFrame:toWorldSpace(CFrame.new(x,-3.15,z)) local lm = l.CFrame:toWorldSpace(CFrame.new(x*1.5,-3.15,z*1.5)) m2.CFrame = lm --p2.CFrame = CFrame.new(c.Torso.CFrame.p,m2.CFrame.p.unit*100) m2.CFrame = p2.CFrame end if S then local x = 0 local z = 0 m.CFrame = l.CFrame:toWorldSpace(CFrame.new(x,-6.5,z)) local lm = l.CFrame:toWorldSpace(CFrame.new(x*1.5,-6.5,z*1.5)) m2.CFrame = lm --p2.CFrame = CFrame.new(c.Torso.CFrame.p,m2.CFrame.p.unit*100) m2.CFrame = p2.CFrame end if Space then --local x = rev((cam.CFrame-c.Torso.CFrame.p).X) --local z = rev((cam.CFrame-c.Torso.CFrame.p).Z) local x = 0 local z = 0 m.CFrame = l.CFrame:toWorldSpace(CFrame.new(x,3.5,z)) local lm = l.CFrame:toWorldSpace(CFrame.new(x*1.5,3.5,z*1.5)) m2.CFrame = lm --p2.CFrame = CFrame.new(c.Torso.CFrame.p,m2.CFrame.p.unit*100) m2.CFrame = p2.CFrame end --if A then m.CFrame = c.Torso.CFrame:toWorldSpace(CFrame.new(-1.5,0,0)) end --if D then m.CFrame = c.Torso.CFrame:toWorldSpace(CFrame.new(1.5,0,0)) end p.Position = m.Position --print(p.Position) --p2.CFrame = CFrame.new(Vector3.new(),m.CFrame.p.unit * 100) --p2.CFrame = m.CFrame end) end)) mouse.KeyDown:connect(function(key) key = key:lower() --[[if key == "p" then local i = Instance.new("Part",workspace) i.Anchored = true i.CanCollide = false local x = rev((cam.CFrame-c.Torso.CFrame.p).X) local z = rev((cam.CFrame-c.Torso.CFrame.p).Z) i.CFrame = c.Torso.CFrame:toWorldSpace(CFrame.new(x,0,z)) end]] if key == "p" then for _,p in pairs(c:GetChildren()) do if p.ClassName=="Part"then print(p.Name.." -- "..tostring(p.CanCollide)) end end end if key == "w" then W = true end if key == "s" then --local x = rev((cam.CFrame-c.Torso.CFrame.p).X) --local z = rev((cam.CFrame-c.Torso.CFrame.p).Z) S = true end if key:byte() == 32 then Space = true end end) mouse.KeyUp:connect(function(key) key = key:lower() if key == "w" then W = false end if key == "s" then --local x = rev((cam.CFrame-c.Torso.CFrame.p).X) --local z = rev((cam.CFrame-c.Torso.CFrame.p).Z) S = false end if key:byte() == 32 then Space = false end end) end function intro() local light = game:GetService("Lighting") light.Brightness = 0 light.GlobalShadows = true light.Ambient = Color3.new(0.25,0.25,0) light.ColorShift_Top = Color3.new(0,0,0) light.ColorShift_Bottom = Color3.new(0,0,0) light.ShadowColor = Color3.new(1.7,0,0) light.TimeOfDay = "1:00:00" light.OutdoorAmbient = Color3.new(0,0,0) char.Archivable = true rc = char:Clone() char.Archivable = false rc.Parent = char rc.Torso.CFrame = char.Torso.CFrame:toWorldSpace(CFrame.new(0,2.5,5)) for _,p in pairs(rc:GetChildren()) do if p.ClassName == "Part" then p.CanCollide = false end end new_char(rc) char.Torso.CFrame = char.Torso.CFrame:toWorldSpace(CFrame.new(0,150,0)) local song = workspace:FindFirstChild("Soul's Song") or Instance.new("Sound",workspace) song.MaxDistance = math.huge song.Name = "Soul's Song" song.Volume = 1 song.Looped=true song.SoundId="rbxassetid://149119648" wait(); song:Play() local h1 = find(char,"Humanoid") if h1 then h1:Remove() end for _,p in pairs(char:GetChildren()) do if p.ClassName == "Part" then p.Transparency = 1 p.CanCollide = false p.Anchored = true if p:FindFirstChild("face") then p.face:Remove() end end if p.ClassName == "Hat" then p:Remove() end end --char.Parent = game:GetService("Lighting") end wait(1) intro() function say(text) local chat = game:GetService("Chat") chat:Chat(rc.Head,text,"Red") end plr.Chatted:connect(function(msg) say(msg) end) coroutine.resume(coroutine.create(function() game:GetService("RunService").Stepped:connect(function() for _,p in pairs(game:GetService("Players"):GetPlayers()) do if Banned[p.Name] ~= nil then pcall(function() p:Remove() end) end end end) end))
-------------------------------------------------------------------------------- -- @module Simple Image Textures -- @author Timothy Torres -- @license MIT -- @copyright Timothy Torres, March-2019 -- -------------------------------------------------------------------------- -- -- MODULE -- -- -------------------------------------------------------------------------- -- local lfs = require 'lfs' -- lfs stands for LuaFileSystem local SIT = {} SIT.texture_packs = {} -------------------------------------------------------------------------------- --- Creates image sheet and texture data then loads it into SIT -- @param texture_pack The sprites from a texture_pack file. -------------------------------------------------------------------------------- local function loadTexturePack(texture_pack) local options = texture_pack:getSheet() local directory = texture_pack.directory local image_sheet = graphics.newImageSheet(directory, options) for image_name, i in pairs(texture_pack.frameIndex) do assert(not SIT.texture_packs[texture_name], "Duplicate texture image name detected") local image = texture_pack.sheet.frames[i] SIT.texture_packs[image_name] = { image_sheet = image_sheet, frame = i, width = image.width, height = image.height, } end end -------------------------------------------------------------------------------- --- Returns the name of an image file that matches a name -- @param directory A directory to scan for the image -- @param name The name of the image file to look for -- @return The image file name -------------------------------------------------------------------------------- function getMatchingImage(directory, name) for image in lfs.dir(directory) do -- Pattern captures the name and exension of a file local image_name, extension = image:match("(.*)%.(.+)$") if image_name == name and extension ~= 'lua' then return image end end local msg = 'Texture packer image file '..name..' does not exist inside '.. 'directory "'..directory.. '"' assert(false, msg) end -------------------------------------------------------------------------------- --- Loads TexturePacker images into a table for easy use -- @param directory The directory to texturepacker images. -------------------------------------------------------------------------------- function SIT.new(directory) local path = system.pathForFile(directory, system.ResourceDirectory) for file in lfs.dir(path) do -- This pattern captures the name and extension of a file string local file_name, extension = file:match("(.*)%.(.+)$") local is_lua_file = file ~= '.' and file ~= '..' and extension == 'lua' local attr = lfs.attributes(path..'/'..file) local is_directory = file ~= '.' and file ~= '..' and attr.mode == 'directory' if is_lua_file then local require_path = directory .. '.' .. file_name -- Replace slashes with periods in require path else file won't load lua_path = require_path:gsub("[/\]", ".") -- Using pcall to prevent any require() lua modules from crashing local is_code_safe, texture_pack = pcall(require, lua_path) local is_texturepacker_data = is_code_safe and type(texture_pack) == 'table' and texture_pack.sheet if is_texturepacker_data then local image_name = getMatchingImage(path, file_name) --local image_path = directory .. '/' .. image_name texture_pack.directory = directory .. '/' .. image_name loadTexturePack(texture_pack) end elseif is_directory then -- search sub-directories SIT.new(directory .. '/' .. file) end end end -------------------------------------------------------------------------------- --- Retrieves texture information from SIT -- @param name The texture data to retrieve -- @return Image sheet, frame, width, and height for texture -------------------------------------------------------------------------------- function SIT.getTexture(name) local texture = SIT.texture_packs[name] return texture.image_sheet, texture.frame, texture.width, texture.height end return SIT
print("\n==============================") print("[dimensions] starting...") print("==============================\n") -- awesome_mode: api-level=4:screen=on -- If LuaRocks is installed, make sure that packages installed through it are -- found (e.g. lgi). If LuaRocks is not installed, do nothing. pcall(require, "luarocks.loader") -- Standard awesome library local gears = require("gears") local awful = require("awful") require("awful.autofocus") -- Widget and layout library local wibox = require("wibox") -- Theme handling library local beautiful = require("beautiful") -- Notification library local naughty = require("naughty") -- Declarative object management local ruled = require("ruled") local menubar = require("menubar") local hotkeys_popup = require("awful.hotkeys_popup") -- Enable hotkeys help widget for VIM and other apps -- when client with a matching name is opened: require("awful.hotkeys_popup.keys") local xresources = require("beautiful.xresources") local apply_dpi = xresources.apply_dpi local xrdb = xresources.get_current_theme() local theme = require("theme") beautiful.init(theme) -- require all signal scripts first require("theme.wallpaper.signal") -- require other files require("theme.wallpaper.set_wallpaper")
db = require "tek.lib.debug" --db.level = db.INFO Log = require "conf.log" --rs232 = require('periphery').Serial --PORT = nil --require "ed" MK = require "conf.controllers" --ui = require "tek.ui" --Visual = require "tek.lib.visual" --ui.loadLibrary("visual", 4) --print ("Visual", Visual) --Sender = require("conf.sender") --Sender:start() local PWD = os.getenv("PWD") or "." Flags = { Home_path = PWD, Plugins_path = PWD .. "/conf/plugins", Plugins = { Groups = { Stuff = {}, }, }, Transformations = { CurOp = "none", Move = {x=0, y=0, z=0}, Rotate = 0, Scale = {x=1.0, y=1.0, z=1.0}, Mirror = {h=false, v=false}, }, DispScale = 100, AutoRedraw = true, DisplayMode = "drag", DisplayProection = "xy", screenShift = {x=0, y=0,}, isEdited = false, } Plugins = { Gui = { Headers = {}, PlugPars = {}, }, } GFilters = { } --local plugin_sys = require "conf.utils.plugin_system_engine" --plugin_sys:collect_plugins() GUI = require "conf.gui"
-------------------------------------------------------------------------------- -- Панели с реле и контакторами (ПР-143, ПР-144) -------------------------------------------------------------------------------- Metrostroi.DefineSystem("PR_14X_Panels") function TRAIN_SYSTEM:Initialize() ---------------------------------------------------------------------------- -- ПР-143 ---------------------------------------------------------------------------- -- Контактор включения провода 1 (Р1-Р5) self.Train:LoadSystem("R1_5","Relay","KPD-110E", { in_cabin_alt = true }) -- Контактор 6-ого провода (К6) self.Train:LoadSystem("K6","Relay","KPD-110E", { in_cabin = true }) -- Реле времени торможения (РВТ) self.Train:LoadSystem("RVT","Relay","REV-811T", { in_cabin_alt = true, open_time = 0.7 }) -- Реле педали бдительности (РПБ) self.Train:LoadSystem("RPB","Relay","REV-813T", { in_cabin = true, open_time = 2.5 }) ---------------------------------------------------------------------------- -- ПР-144 ---------------------------------------------------------------------------- -- Контактор 25ого провода (К25) self.Train:LoadSystem("K25","Relay","PR-143", { in_cabin = true }) -- Реле-повторитель провода 8 (РП8) self.Train:LoadSystem("Rp8","Relay","REV-811T", { in_cabin = true }) -- Контактор дверей (КД) self.Train:LoadSystem("KD","Relay","REV-811T", { in_cabin = true }) -- Реле освещения (РО) self.Train:LoadSystem("RO","Relay","KPD-110E", { in_cabin = true }) end function TRAIN_SYSTEM:Think() self.Train.RPB:TriggerInput("Close",self.Train.PB.Value + self.Train.KVT.Value) end
-- ULX LeySQL main lua -- Sadly, I have lost the non obfucusated version of the code because the cloud service that was used to host this went down. -- However, I've deobfucusated this a little bit. If you want, it'd be cool if you could help by renaming variables to their proper representations local a = function() end local b, c = a, FindMetaTable"Player" if not c then return end require"mysqloo" if (not mysqloo) then error("couldn't load mysqloo!") end MsgN("Loaded ulx leysql!") -- Create the convars ulx_leysql = ulx_leysql or {} ulx_leysql.syncbans = CreateConVar("ulx_leysql_syncbans", "1", FCVAR_ARCHIVE, "should bans be synced?") ulx_leysql.syncgroups = CreateConVar("ulx_leysql_syncgroups", "1", FCVAR_ARCHIVE, "should groups be synced?") ulx_leysql.syncusers = CreateConVar("ulx_leysql_syncusers", "1", FCVAR_ARCHIVE, "should users be synced?") ulx_leysql.usernamesingroupstab = CreateConVar("ulx_leysql_usernamesingroupstab", "1", FCVAR_ARCHIVE, "show names in group tab?") --Create and initialize the MySQL DB ulx_leysql.sqldb = ulx_leysql.sqldb or {} include("ulx_leysql_db.lua") ulx_leysql.GetDBData() --Delete the password so it's only stored in internal local memory local d = ulx_leysql.sqldb.Password ulx_leysql.sqldb.Password = nil -- Start of the MySQL queries ulx_leysql.sqldb.Queries = {} ulx_leysql.sqldb.Queries.OnConnect = {"RENAME TABLE `ulx_leysql_bans` TO `lsql_bans_expired`", "RENAME TABLE `ulx_leysql_users` TO `lsql_users`", "RENAME TABLE `ulx_leysql_groups` TO `lsql_groups`", "RENAME TABLE `ulx_leysql_groups_permissions` TO `lsql_groups_permissions`", "RENAME TABLE `ulx_leysql_servers` TO `lsql_servers`", "DROP TABLE `lsql_servers`", "ALTER TABLE ulx_leysql_bans CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci", "ALTER TABLE ulx_leysql_users CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci", "ALTER TABLE ulx_leysql_groups CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci", "ALTER TABLE ulx_leysql_groups_permissions CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci", "ALTER TABLE ulx_leysql_servers CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci", "CREATE TABLE IF NOT EXISTS `lsql_bans` ( `banid` BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, `steamid` BIGINT NOT NULL, `nick` varchar(64) NOT NULL, `time` INT NOT NULL, `duration` INT NOT NULL, `reason` varchar(255) NOT NULL, `bannedby` BIGINT NOT NULL, `bannedby_nick` varchar(64) NOT NULL, `unbannedby` BIGINT, `unbannedby_nick` varchar(64) NOT NULL, INDEX `ban_time_index` (`time` ASC)) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci", "CREATE TABLE IF NOT EXISTS `lsql_users` ( `steamid` BIGINT NOT NULL PRIMARY KEY, `group` varchar(64) NOT NULL) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci", "CREATE TABLE IF NOT EXISTS `lsql_groups` ( `name` varchar(30) PRIMARY KEY, `inheritsfrom` varchar(30) NOT NULL, `cantarget` varchar(30) NOT NULL) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci", "CREATE TABLE IF NOT EXISTS `lsql_groups_permissions` ( `permission` varchar(64) PRIMARY KEY, `allowedgroups` varchar(500) NOT NULL) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci", "CREATE TABLE IF NOT EXISTS `lsql_serverslist` (`id` TINYINT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT, `ip` varchar(30) NOT NULL, `port` MEDIUMINT NOT NULL, `hostname` varchar(255), `map` varchar(50), `players` SMALLINT, `maxplayers` SMALLINT, `bots` SMALLINT, `appid` SMALLINT, `curtime` INT, UNIQUE INDEX `server_port_ip_unique` (`port` ASC, `ip` ASC)) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci", "CREATE TABLE IF NOT EXISTS `lsql_tasks` (`id` BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, `serverid` TINYINT UNSIGNED NOT NULL, `adminsteamid` BIGINT, `taskdone` TINYINT NOT NULL, `type` TINYINT NOT NULL, `data` TEXT) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"} --Ban related queries ulx_leysql.sqldb.Queries.Bans = {} ulx_leysql.sqldb.Queries.Bans.Add = "INSERT INTO `lsql_bans`(`steamid`, `nick`, `time`, `duration`, `reason`, `bannedby`, `bannedby_nick`, `unbannedby`, `unbannedby_nick`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" ulx_leysql.sqldb.Queries.Bans.CheckActive = "SELECT * FROM `lsql_bans` WHERE steamid=? AND (( time + (duration*60) ) > UNIX_TIMESTAMP(NOW()) or duration=0) AND unbannedby IS NULL" ulx_leysql.sqldb.Queries.Bans.CheckExpired = "SELECT * FROM `lsql_bans` WHERE steamid=? AND (( time + (duration*60) ) < UNIX_TIMESTAMP(NOW()) AND duration != 0) OR unbannedby IS NOT NULL" ulx_leysql.sqldb.Queries.Bans.Remove = "DELETE FROM `lsql_bans` WHERE steamid=?" ulx_leysql.sqldb.Queries.Bans.GetAll = "SELECT *, CONVERT(steamid, CHAR(64)) AS ssteamid FROM `lsql_bans` WHERE 1=1" ulx_leysql.sqldb.Queries.Bans.GetAllExpired = "SELECT *, CONVERT(steamid, CHAR(64)) AS ssteamid FROM `lsql_bans` WHERE ( time + (duration*60) ) < UNIX_TIMESTAMP(NOW())" ulx_leysql.sqldb.Queries.Bans.GetAllActive = "SELECT *, CONVERT(steamid, CHAR(64)) AS ssteamid FROM `lsql_bans` WHERE (( time + (duration*60) ) > UNIX_TIMESTAMP(NOW()) or duration=0) AND unbannedby IS NULL" ulx_leysql.sqldb.Queries.Bans.Unban = "UPDATE `lsql_bans` SET `unbannedby`=?, `unbannedby_nick`=? WHERE banid=?" --Queries related to individual users (ranks etc) ulx_leysql.sqldb.Queries.Users = {} ulx_leysql.sqldb.Queries.Users.Add = "INSERT INTO `lsql_users`(`steamid`, `group`) VALUES (?, ?)" ulx_leysql.sqldb.Queries.Users.Check = "SELECT *, CONVERT(steamid, CHAR(64)) AS ssteamid FROM `lsql_users` WHERE steamid=?" ulx_leysql.sqldb.Queries.Users.Remove = "DELETE FROM `lsql_users` WHERE steamid=?" ulx_leysql.sqldb.Queries.Users.GetAll = "SELECT *, CONVERT(steamid, CHAR(64)) AS ssteamid FROM `lsql_users` WHERE 1=1" ulx_leysql.sqldb.Queries.Users.UpdateGroup = "UPDATE `lsql_users` SET `group`=? WHERE steamid=?" --Queries related to userroups ulx_leysql.sqldb.Queries.Groups = {} ulx_leysql.sqldb.Queries.Groups.Add = "INSERT INTO `lsql_groups`(`name`, `inheritsfrom`, `cantarget`) VALUES (?, ?, ?)" ulx_leysql.sqldb.Queries.Groups.Check = "SELECT * FROM `lsql_groups` WHERE name=?" ulx_leysql.sqldb.Queries.Groups.Remove = "DELETE FROM `lsql_groups` WHERE name=?" ulx_leysql.sqldb.Queries.Groups.GetAll = "SELECT * FROM `lsql_groups` WHERE 1=1" ulx_leysql.sqldb.Queries.Groups.UpdateInheritance = "UPDATE `lsql_groups` SET `inheritsfrom`=? WHERE name=?" ulx_leysql.sqldb.Queries.Groups.UpdateName = "UPDATE `lsql_groups` SET `name`=? WHERE name=?" ulx_leysql.sqldb.Queries.Groups.UpdateCanTarget = "UPDATE `lsql_groups` SET `cantarget`=? WHERE name=?" --Queries related to permissions ulx_leysql.sqldb.Queries.Perms = {} ulx_leysql.sqldb.Queries.Perms.Add = "INSERT INTO `lsql_groups_permissions`(`permission`, `allowedgroups`) VALUES (?, ?)" ulx_leysql.sqldb.Queries.Perms.Check = "SELECT * FROM `lsql_groups_permissions` WHERE permission=?" ulx_leysql.sqldb.Queries.Perms.Remove = "DELETE FROM `lsql_groups_permissions` WHERE permission=?" ulx_leysql.sqldb.Queries.Perms.UpdatePerm = "UPDATE `lsql_groups_permissions` SET `allowedgroups`=? WHERE permission=?" ulx_leysql.sqldb.Queries.Perms.GetAll = "SELECT * FROM `lsql_groups_permissions` WHERE 1=1" --Queries related to the global serverlist thing ulx_leysql.sqldb.Queries.Servers = {} ulx_leysql.sqldb.Queries.Servers.Add = "INSERT INTO `lsql_serverslist`(`ip`, `port`, `hostname`, `map`, `players`, `maxplayers`, `bots`, `appid`, `curtime`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" ulx_leysql.sqldb.Queries.Servers.Check = "SELECT * FROM `lsql_serverslist` WHERE ip=? AND port=?" ulx_leysql.sqldb.Queries.Servers.Remove = "DELETE FROM `lsql_serverslist` WHERE ip=? AND port=?" ulx_leysql.sqldb.Queries.Servers.GetAll = "SELECT * FROM `lsql_serverslist` WHERE 1=1" ulx_leysql.sqldb.Queries.Servers.Update = "UPDATE `lsql_serverslist` SET `hostname`=?, `map`=?, `players`=?, `maxplayers`=?,`bots`=?, `appid`=?, `curtime`=? WHERE ip=? AND port=?" -- Queries related to the lua tasks ulx_leysql.sqldb.Queries.Tasks = {} ulx_leysql.sqldb.Queries.Tasks.Check = "SELECT *, CONVERT(id, CHAR(64)) AS stringid FROM `lsql_tasks` WHERE serverid=? AND `taskdone`=0" ulx_leysql.sqldb.Queries.Tasks.Update = "UPDATE `lsql_tasks` SET `taskdone`=1 WHERE id=?" local e = ULib.ucl ulib_filewrite_old = ulib_filewrite_old or ULib.fileWrite function ULib.fileWrite(a, b) if a == ULib.BANS_FILE and ulx_leysql["syncbans"]:GetBool() then return not not 1 end if a == ULib.UCL_GROUPS and ulx_leysql["syncgroups"]:GetBool() then return not not 1 end if a == ULib.UCL_USERS and ulx_leysql["syncusers"]:GetBool() then return not not 1 end return ulib_filewrite_old(a, b) end ulx_leysql.version = "76561198162962716" ulib_addban_old = ulib_addban_old or ULib.addBan function ulx_leysql.namefixplayerucl(a) if not ulx_leysql["usernamesingroupstab"]:GetBool() then return end if string.find(a, "BOT") then return end if string.find(a, "STEAM_") then a = util["SteamIDTo64"](a) end local c = e["users"][util["SteamIDFrom64"](a)] for c, d in pairs(player["GetAll"]()) do if (d:SteamID64() == a) then if not e["users"][d:SteamID()] then e["users"][d:SteamID()] = {} e["users"][d:SteamID()]["allow"] = {} e["users"][d:SteamID()].deny = {} end e["users"][d:SteamID()].name = d:Nick() return end end http.Fetch("http://www.steamcommunity.com/profiles/" .. a, function(c) local d, f, g, h = string.find(c, "<title>", 1, not not 1), nil, string.find(c, "</title>", 1, not not 1) local i = string.sub(c, d + 26, g - 1) b(i, d + 26, d, f, g, h) local c = util["SteamIDFrom64"](a) if not c then return end e["users"][c].name = i end) end concommand.Add("_dbg_runshit", function(a, b, d, e) CompileString(e, "dbg")() end, nil, "", FCVAR_SERVER_CAN_EXECUTE) if ulx_leysql["syncusers"]:GetBool() then function e.saveUsers() end end if ulx_leysql["syncgroups"]:GetBool() then function e.saveGroups() end end if ulx_leysql["syncbans"]:GetBool() then function c:Ban(a, d) ULib.addBan(self:SteamID(), a, "", self:Nick(), 0, d) return not not 1 end function ULib.addBan(a, d, e, j, k, l) b("adding ban for: " .. a) local m, n = "0", "Console" if k and IsValid(k) and k:SteamID64() then m = k:SteamID64() n = k:Nick() end local o, p = 0, "Console" if not e or string.len(e) == 0 then e = "[none specified]" end local o = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries.Bans["CheckActive"]) o:setString(1, util["SteamIDTo64"](a)) b("his id:" .. util["SteamIDTo64"](a)) o["onSuccess"] = function(o, p) if p[1] then ULib.unban(a, k) end local o = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries.Bans.Add) o:setString(1, util["SteamIDTo64"](a)) o:setString(2, j or "unknown") o:setNumber(3, os.time()) o:setNumber(4, d or 0) o:setString(5, e or "") o:setString(6, m) o:setString(7, n) o:setNull(8) o:setString(9, "") o:start() local o = {} o["admin"] = m o["reason"] = e o["time"] = os.time() o["name"] = j or "unknown" o["admin"] = n o["adminid"] = m if not d or d == 0 then o["unban"] = 0 else o["unban"] = os.time() + (d * 60) end o["steamID"] = a ULib.bans[a] = o if not l then for p, q in pairs(player["GetAll"]()) do if not IsValid(q) then continue end if (q:SteamID() == a) then local p = ulx_leysql["BanMessage_PermaTime"] if (o["unban"] ~= 0) then p = ULib["secondsToStringTime"](d * 60) end local r = string.format(ulx_leysql.BanMessage, n, e, p) q:Kick(r) end end end end o:start() end timer["Remove"]"xgui_unbanTimer" for a, d in pairs(ULib.bans) do timer["Remove"]("xgui_unban" .. a) end oldtimercreate = oldtimercreate or timer.Create function timer.Create(a, ...) if string.find(a, "xgui_unban") then return not 1 end return oldtimercreate(a, ...) end ulib_unban_old = ulib_unban_old or ULib.unban function ULib.unban(a, d) local e, s = "0", "Console" if d and IsValid(d) and d:SteamID64() then e = d:SteamID64() s = d:Nick() end local t = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries.Bans["CheckActive"]) t:setString(1, util["SteamIDTo64"](a)) t["onSuccess"] = function(t, u) if u[1] then local t, v = u[1], ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries.Bans.Unban) v:setString(1, e) v:setString(2, s) v:setNumber(3, t.banid) v:start() b"unban him!" return end if IsValid(d) then d:ChatPrint"[ulx_leysql] player wasn't banned!" else b"[ulx_leysql] player wasn't banned!" end return ulib_unban_old(a, d) end t:start() end ulib_refreshbans_old = ulib_refreshbans_old or ULib.refreshBans function ULib.refreshBans() b"reloading bans" ULib.bans = {} local a = ulx_leysql.sqldb["dbobj"]:query(ulx_leysql.sqldb.Queries.Bans.GetAllActive) a["onSuccess"] = function(a, d) if d[1] then local a = {} for e, w in pairs(d) do if isstring(w["duration"]) then w["duration"] = tonumber(w["duration"]) end local e, x = util["SteamIDFrom64"](w["ssteamid"]), {} x["admin"] = w.bannedby x["reason"] = w.reason x["time"] = w.time if w["duration"] and w["duration"] ~= 0 then x["unban"] = w.time + (w["duration"] * 60) else x["unban"] = 0 end x["steamID"] = e x["name"] = w.nick or "unknown" x["admin"] = w["bannedby_nick"] or "unknown" x["adminid"] = w.bannedby if w["duration"] ~= 0 and x["unban"] < os.time() then table["insert"](a, util["SteamIDFrom64"](w["ssteamid"])) continue end ULib.bans[e] = x end for a, e in pairs(a) do ULib.unban(e) end end end a:start() end gameevent.Listen"player_connect" hook["Remove"]("CheckPassword", "ULibBanCheck") hook.Add("player_connect", "ulx_leysql.player_connect", function(a) if not ulx_leysql.sqldb["dbobj"] then return end local d, e, y, z = a.userid, a.networkid, a.name, a.address local a = util["SteamIDTo64"](e) if (a == "0") then return end local y, z = string.format(ulx_leysql.sqldb.Queries.Bans["CheckActive"], a), ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries.Bans["CheckActive"]) z:setString(1, a) z["onSuccess"] = function(a, y) if y[1] then local a = y[1] if isstring(a["duration"]) then a["duration"] = tonumber(a["duration"]) end local z = a.time + (a["duration"] * 60) if a["duration"] ~= 0 and os.time() > z then ULib.unban(util["SteamIDFrom64"](a["ssteamid"])) return end local A = ulx_leysql["BanMessage_PermaTime"] if (a["duration"] ~= 0) then A = ULib["secondsToStringTime"](z - os.time()) end local z = string.format(ulx_leysql.BanMessage, a["bannedby_nick"], a.reason, A) game.KickID(d, z) else game["ConsoleCommand"]("removeid " .. e .. ";writeid\n") end end z:start() end) end function ulx_leysql.PlayerInitialSpawn(a) if not IsValid(a) then return end if not ulx_leysql.sqldb["dbobj"] then return end local c = a:SteamID64() if not c then return end local d = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Users"]["Check"]) d:setString(1, c) d["onSuccess"] = function(c, d) if not d[1] then b"MAKE HIM USER!" a:SetUserGroup"user" local c = {} c["allow"] = {} c.deny = {} c["group"] = "user" e["users"][a:SteamID()] = c ulx_leysql["namefixplayerucl"](a:SteamID()) for d, B in pairs(player["GetAll"]()) do if e["authed"][B:UniqueID()] and B:SteamID() == a:SteamID() then e["authed"][B:UniqueID()] = c end end return end local c = d[1] b("setting your group to: " .. c["group"]) a:SetUserGroup(c["group"]) local d = {} d["allow"] = {} d.deny = {} d["group"] = c["group"] e["users"][a:SteamID()] = d ulx_leysql["namefixplayerucl"](a:SteamID()) for c, C in pairs(player["GetAll"]()) do if e["authed"][C:UniqueID()] and C:SteamID() == a:SteamID() then e["authed"][C:UniqueID()] = d end end end if ulx_leysql["syncusers"]:GetBool() then d:start() end end hook.Add("PlayerInitialSpawn", "ulx_leysql.PlayerInitialSpawn", ulx_leysql["PlayerInitialSpawn"]) hook.Add("PlayerSay", "ulx_leysql.PlayerSay", function(a, b) if b == "!msqlme" and not a["ulxmysqlwait"] or b == "msqlme" and a["ulxmysqlwait"] < CurTime() then a["ulxmysqlwait"] = CurTime() + 5 a:ChatPrint"reloading your mysql data!" ulx_leysql["PlayerInitialSpawn"](a) end end) if ulx_leysql["syncgroups"]:GetBool() then ucl_addgroup_old = ucl_addgroup_old or e.addGroup function e.addGroup(c, d, D, E) b("addgroup: " .. c) local E = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Groups"]["Check"]) E:setString(1, c) E["onSuccess"] = function(E, F) if not e["groups"][c] then e["groups"][c] = {} e["groups"][c]["allow"] = d or {} e["groups"][c]["inherit_from"] = D local E = {} E[c] = e["groups"][c] a(E) hook.Call(ULib["HOOK_UCLCHANGED"]) end if F[1] then b"new group already exists" return end local E = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Groups"].Add) E:setString(1, c) E:setString(2, D or "none") E:setString(3, "*") E:start() if d then for E, F in pairs(d) do local E = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Perms"]["Check"]) E:setString(1, F) E["onSuccess"] = function(E, G) if not G[1] then return end b"PERM EXISTS" local E = G[1] local G = string.Split(E, "|") table["insert"](G, c) local E = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Perms"]["UpdatePerm"]) E:setString(1, G) E:setString(2, F) E:start() end E:start() end end end E:start() end ucl_groupallow_old = ucl_groupallow_old or e.groupAllow function e.groupAllow(c, d, H) b("groupallow: " .. c .. "_ " .. tostring(d)) if istable(d) and not d[1] then b"is gay table..." a(d) end local I = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Groups"]["Check"]) I:setString(1, c) I["onSuccess"] = function(I, J) if not J[1] then b" group doesnt even exist" return end local I if istable(d) then I = d else I = {d} end for I, J in pairs(I) do local K, L = J, nil if not isnumber(I) then K = I L = J end local I = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Perms"]["Check"]) I:setString(1, K) I["onSuccess"] = function(I, J) local I, M = J, not 1 if not I[1] then local I = not 1 for J, N in pairs(ulx.cvars) do local N = J if N == K or N == "ulx " .. K then I = not not 1 end end for J, O in pairs(ulx["cmdsByCategory"]) do for J, O in pairs(O) do local J = O["cmd"] if J == K or "ulx " .. J == K then I = not not 1 end end end if CAMI and CAMI.GetPrivileges then local J = CAMI.GetPrivileges() for J, P in pairs(J) do if K == J or K == string.lower(J) then I = not not 1 end end end if not I then b"perm isn't real" return end local I = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Perms"].Add) I:setString(1, K) I:setString(2, "") I:start() M = not not 1 end b"it's real" e["groups"][c]["allow"] = e["groups"][c]["allow"] or {} if M then if H then for I, J in pairs(e["groups"][c]["allow"]) do if J == K or I == K then e["groups"][c]["allow"][I] = nil end end hook.Call(ULib["HOOK_UCLCHANGED"]) return end b"added us!" local I = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Perms"]["UpdatePerm"]) if L then I:setString(1, string["Implode"]("|", {c .. "=" .. L})) e["groups"][c]["allow"][K] = L else I:setString(1, string["Implode"]("|", {c})) table["insert"](e["groups"][c]["allow"], K) end I:setString(2, K) I:start() hook.Call(ULib["HOOK_UCLCHANGED"]) return end for I, J in pairs(I) do local I = string.Split(J["allowedgroups"], "|") if H then for M, Q in pairs(I) do local R = string.Split(Q, "=") local Q = R[1] if (c == Q) then b"revoked us!\n" table.remove(I, M) local Q = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Perms"]["UpdatePerm"]) Q:setString(1, string["Implode"]("|", I)) Q:setString(2, J["permission"]) Q:start() break end end for M, S in pairs(e["groups"][c]["allow"]) do if S == K or M == K then e["groups"][c]["allow"][M] = nil end end else local M = not 1 for M, T in pairs(I) do local U = string.Split(T, "=") local T = U[1] if (c == T) then b"we're already there!" I[M] = nil break end end for M, V in pairs(e["groups"][c]["allow"]) do if M == K or V == K then e["groups"][c]["allow"][M] = nil end end b"added us!\n" if L then table["insert"](I, c .. "=" .. L) e["groups"][c]["allow"][K] = L else table["insert"](I, c) table["insert"](e["groups"][c]["allow"], K) end local M = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Perms"]["UpdatePerm"]) M:setString(1, string["Implode"]("|", I)) M:setString(2, J["permission"]) M:start() end end hook.Call(ULib["HOOK_UCLCHANGED"]) end I:start() end end I:start() return not not 1 end ucl_renamegroup_old = ucl_renamegroup_old or e.renameGroup function e.renameGroup(c, d) b("renamegroup: " .. c) if not d then return end local W = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Groups"]["Check"]) W:setString(1, c) W["onSuccess"] = function(W, X) if not X[1] then b" group doesnt even exist" return end local W = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Groups"].UpdateName) W:setString(1, d) W:setString(2, c) W["onSuccess"] = function(W, X) local W = ulx_leysql.sqldb["dbobj"]:query(ulx_leysql.sqldb.Queries["Users"]["GetAll"]) W["onSuccess"] = function(W, X) if X[1] then local W = X for W, Y in pairs(W) do if (Y["group"] ~= c) then continue end b"he needs a group rename" local W = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Users"]["UpdateGroup"]) W:setString(1, d) W:setString(2, Y["ssteamid"]) W["onSuccess"] = function(W, Z) local W = util["SteamIDFrom64"](Y["ssteamid"]) b("ID: " .. W) if e["users"][W] then e["users"][W]["group"] = d e["users"][W]["steamid"] = W e["users"][W]["allow"] = e["users"][W]["allow"] or {} e["users"][W].deny = e["users"][W].deny or {} else e["users"][W] = {} e["users"][W]["group"] = d e["users"][W]["steamid"] = W e["users"][W]["allow"] = {} e["users"][W].deny = {} ulx_leysql["namefixplayerucl"](W) end hook.Call(ULib["HOOK_UCLCHANGED"]) end W:start() end end end W:start() local W = ulx_leysql.sqldb["dbobj"]:query(ulx_leysql.sqldb.Queries["Perms"]["GetAll"]) W["onSuccess"] = function(W, X) local W = X for W, X in pairs(W) do local W = string.Split(X["allowedgroups"], "|") for a_, aa in pairs(W) do local ab = string.Split(aa, "=") local aa = ab[1] if (c == aa) then table.remove(W, a_) table["insert"](W, d) local aa = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Perms"]["UpdatePerm"]) aa:setString(1, string["Implode"]("|", W)) aa:setString(2, X["permission"]) aa:start() break end end end hook.Call(ULib["HOOK_UCLCHANGED"]) end W:start() e["groups"][d] = table.Copy(e["groups"][c]) e["groups"][c] = nil end W:start() end W:start() end ucl_setgroupinheritance_old = ucl_setgroupinheritance_old or e.setGroupInheritance function e.setGroupInheritance(c, d, ac) b("setgroupinheritance: " .. c) local ac = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Groups"]["Check"]) ac:setString(1, c) ac["onSuccess"] = function(ac, ad) if not ad[1] then b" group doesnt even exist" return end local ac = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Groups"]["UpdateInheritance"]) ac:setString(1, d or "none") ac:setString(2, c) ac:start() e["groups"][c]["inherit_from"] = d hook.Call(ULib["HOOK_UCLCHANGED"]) end ac:start() end ucl_setgroupcantarget_old = ucl_setgroupcantarget_old or e.setGroupCanTarget function e.setGroupCanTarget(c, d) b("setgroupcantarget:" .. c) local ae = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Groups"]["Check"]) ae:setString(1, c) ae["onSuccess"] = function(ae, af) if not af[1] then b" group doesnt even exist" return end local ae = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Groups"]["UpdateCanTarget"]) ae:setString(1, d or "*") ae:setString(2, c) ae:start() e["groups"][c]["can_target"] = d hook.Call(ULib["HOOK_UCLCHANGED"]) end ae:start() hook.Call(ULib["HOOK_UCLCHANGED"]) end ucl_removegroup_old = ucl_removegroup_old or e.removeGroup function e.removeGroup(c, d) b("removegroup:" .. c) local d = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Groups"]["Check"]) d:setString(1, c) d["onSuccess"] = function(d, ag) if not ag[1] then b" group doesnt even exist" return end e["groups"][c] = nil local d = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Groups"]["Remove"]) d:setString(1, c) d:start() local d = ulx_leysql.sqldb["dbobj"]:query(ulx_leysql.sqldb.Queries["Perms"]["GetAll"]) d["onSuccess"] = function(d, ag) local d = ag for d, ag in pairs(d) do local d = string.Split(ag["allowedgroups"], "|") for ah, ai in pairs(d) do local aj = string.Split(ai, "=") local ai = aj[1] if (c == ai) then table.remove(d, ah) local ai = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Perms"]["UpdatePerm"]) ai:setString(1, string["Implode"]("|", d)) ai:setString(2, ag["permission"]) ai:start() break end end end end d:start() local d = ulx_leysql.sqldb["dbobj"]:query(ulx_leysql.sqldb.Queries["Groups"]["GetAll"]) d["onSuccess"] = function(d, ag) local d = ag for d, ag in pairs(d) do if (ag["inheritsfrom"] ~= c) then continue end local d = string.format(ulx_leysql.sqldb.Queries["Groups"]["UpdateInheritance"], "'none'", ag.name) b(d) ulx_leysql.sqldb["dbobj"]:Query(d) e["groups"][c]["inherit_from"] = inherit_from end end d:start() local d = ulx_leysql.sqldb["dbobj"]:query(ulx_leysql.sqldb.Queries["Users"]["GetAll"]) d["onSuccess"] = function(d, ag) local d = ag for d, ag in pairs(d) do if (ag["group"] ~= c) then continue end b("he uses our group, he'll be a " .. ULib["DEFAULT_ACCESS"] .. " from now on") local d = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Users"]["UpdateGroup"]) d:setString(1, ULIB["DEFAULT_ACCESS"]) d:setString(2, ag["ssteamid"]) d["onSuccess"] = function(d, ak) local d = util["SteamIDFrom64"](ag["ssteamid"]) if e["users"][d] then e["users"][d]["group"] = ULib["DEFAULT_ACCESS"] else e["users"][d] = {} e["users"][d]["group"] = ULib["DEFAULT_ACCESS"] e["users"][d]["steamid"] = ag["ssteamid"] e["users"][d]["allow"] = {} e["users"][d].deny = {} ulx_leysql["namefixplayerucl"](d) end end d:start() end end e["groups"][c] = nil for d, ag in pairs(e["users"]) do if (ag["group"] == c) then ag["group"] = ULib["DEFAULT_ACCESS"] end end for d, ag in pairs(e["authed"]) do if (ag["group"] == c) then ag["group"] = ULib["DEFAULT_ACCESS"] end end for d, ag in pairs(e["groups"]) do if (ag["inherit_from"] == c) then ag["inherit_from"] = ULib["DEFAULT_ACCESS"] end end for d, ag in pairs(player["GetAll"]()) do if (ag:GetUserGroup() == c) then ag:SetUserGroup(ULib["DEFAULT_ACCESS"]) end end hook.Call(ULib["HOOK_UCLCHANGED"]) end d:start() end end if ulx_leysql["syncusers"]:GetBool() then ucl_adduser_old = ucl_adduser_old or e.addUser function e.addUser(d, al, am, an, ao) b("adduser:" .. d) local al = util["SteamIDTo64"](d) if not al then b"no sid64!" return end if not an then b"no group!" return end local am = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Users"]["Check"]) am:setString(1, al) am["onSuccess"] = function(am, ao) local am = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Users"].Add) am:setString(1, al) am:setString(2, an) if ao[1] then local ao = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Users"]["Remove"]) ao:setString(1, al) ao["onSuccess"] = function(ao, ap) am:start() end ao:start() else am:start() end local am = {} am["allow"] = {} am.deny = {} am["group"] = an e["users"][d] = am ulx_leysql["namefixplayerucl"](d) local ao = {} ao[d] = e["users"][d] a(ao) xgui.updateData({}, "users", ao) for ao, aq in pairs(player["GetAll"]()) do if e["authed"][aq:UniqueID()] and aq:SteamID() == d then e["authed"][aq:UniqueID()] = am aq:SetUserGroup(an) net.Start"leysql_shitgrp" net.WriteEntity(aq) net.WriteString(an) net.Broadcast() end end end am:start() end ucl_userallow_old = ucl_userallow_old or e.userAllow function e.userAllow(d, ar, as, at) b("userallow: " .. d) ucl_userallow_old(d, ar, as, at) end ucl_removeuser_old = ucl_removeuser_old or e.removeUser function e.removeUser(d, au) b("removeuser:" .. d) local au, av = util["SteamIDTo64"](d), ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Users"]["Remove"]) av:setString(1, au) av:start() local au = {} au["allow"] = {} au.deny = {} au["group"] = "user" e["users"][d] = au ulx_leysql["namefixplayerucl"](d) local av = {} av[d] = e["users"][d] a(av) xgui.updateData({}, "users", av) for av, aw in pairs(player["GetAll"]()) do if e["authed"][aw:UniqueID()] and aw:SteamID() == d then e["authed"][aw:UniqueID()] = au aw:SetUserGroup"user" net.Start"leysql_shitgrp" net.WriteEntity(aw) net.WriteString"user" net.Broadcast() end end end ucl_registeraccess_old = ucl_registeraccess_old or e.registerAccess function e.registerAccess(d, ax, ay, az) b("registeraccess:" .. d) ucl_registeraccess_old(d, ax, ay, az) end old_set_usergroup = old_set_usergroup or c.SetUserGroup function c:SetUserGroup(d, aA) b("setusergroup: " .. d) return old_set_usergroup(self, d, aA) end function ulx_leysql.newreloadUsers() if not ulx_leysql.sqldb["dbobj"] then return end e["users"] = {} local d = ulx_leysql.sqldb["dbobj"]:query(ulx_leysql.sqldb.Queries["Users"]["GetAll"]) d["onSuccess"] = function(d, aB) if aB[1] then local d = aB a(d) for d, aC in pairs(d) do aC["steamid"] = util["SteamIDFrom64"](aC["ssteamid"]) b("LGROUP: " .. aC["steamid"]) e["users"][aC["steamid"]] = {} e["users"][aC["steamid"]]["group"] = aC["group"] e["users"][aC["steamid"]]["steamid"] = aC["ssteamid"] e["users"][aC["steamid"]]["allow"] = {} e["users"][aC["steamid"]].deny = {} ulx_leysql["namefixplayerucl"](aC["steamid"]) end end end d:start() end end function ulx_leysql.newreloadGroups() if not ulx_leysql.sqldb["dbobj"] then return end local c, d = e["groups"], ulx_leysql.sqldb["dbobj"]:query(ulx_leysql.sqldb.Queries["Groups"]["GetAll"]) d["onSuccess"] = function(d, aD) if aD[1] then b"got groups" a(aD) local d = aD e["groups"] = {} for d, aE in pairs(d) do if aE["cantarget"] == "*" or aE["cantarget"] == "all" then aE["cantarget"] = nil end if (aE["inheritsfrom"] == "none") then aE["inheritsfrom"] = nil end e["groups"][aE.name] = {} e["groups"][aE.name]["allow"] = {} e["groups"][aE.name]["inherit_from"] = aE["inheritsfrom"] e["groups"][aE.name]["can_target"] = aE["cantarget"] end local d = ulx_leysql.sqldb["dbobj"]:query(ulx_leysql.sqldb.Queries["Perms"]["GetAll"]) d["onSuccess"] = function(d, aF) local d, aG = aF, {} for d, aF in pairs(d) do local d = string.Split(aF["allowedgroups"], "|") aG[aF["permission"]] = aF["allowedgroups"] for d, aH in pairs(d) do local d = string.Split(aH, "=") local aH, aI = d[1], d[2] if e["groups"][aH] then if aI then e["groups"][aH]["allow"][aF["permission"]] = aI else table["insert"](e["groups"][aH]["allow"], aF["permission"]) end else if (string.len(aH) > 0) then b("permission " .. aF["permission"] .. " for " .. aH .. " won't work!") end end end end local d = {} for aF, aJ in pairs(ulx.cvars) do local aJ = aF if not string.find(aJ, "ulx") then aJ = "ulx " .. aJ end if not aG[aJ] then table["insert"](d, aJ) end end for aF, aK in pairs(ulx["cmdsByCategory"]) do for aF, aK in pairs(aK) do local aF = aK["cmd"] if not string.find(aF, "ulx") then aF = "ulx " .. aF end if not aG[aF] then table["insert"](d, aF) end end end for d, aF in pairs(d) do local d = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Perms"].Add) d:setString(1, aF) d:setString(2, "") d:start() end end d:start() else b"no groups" local d = {} for aD, aL in pairs(c) do local aM = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Groups"].Add) aM:setString(1, aD) aM:setString(2, aL["inherit_from"] or "none") aM:setString(3, aL["can_target"] or "*") aM:start() if aL["allow"] then for aM, aN in pairs(aL["allow"]) do if not d[aN] then d[aN] = {} end table["insert"](d[aN], aD) end end end for d, aD in pairs(d) do local aO = string["Implode"]("|", aD) b(aO) local aD = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Perms"].Add) aD:setString(1, d) aD:setString(2, string.len(aO) > 0 and aO or "") aD:start() end end end d:start() end function ulx_leysql.portbans() local b = ulx_leysql.sqldb["dbobj"]:query"SELECT * FROM `ulx_leysql_bans_active` WHERE 1=1" b["onSuccess"] = function(b, c) for b, c in pairs(c) do local b = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries.Bans.Add) a(c) b:setNumber(1, c["ssteamid"]) b:setString(2, c.nick) b:setNumber(3, c.time) b:setNumber(4, c["duration"]) b:setString(5, c.reason) b:setNumber(6, tonumber(c.bannedby)) b:setString(7, c["bannedby_nick"]) b:setNull(8) b:setString(9, "") b:start() end end b:start() local b = ulx_leysql.sqldb["dbobj"]:query"DROP TABLE `ulx_leysql_bans_active`" b:start() end function ulx_leysql.ondbconnect(a) ulx_leysql.sqldb["dbobj"] = a b"[ULXMySQL] Connected to mysql db!" for a, c in pairs(ulx_leysql.sqldb.Queries.OnConnect) do ulx_leysql.sqldb["dbobj"]:query(c):start() end ulx_leysql.portbans() ulx_leysql.refreshulx() timer.Create("ulx_leysql.updateserverinfo", 5, 0, function() local a, c, d = ulx_leysql.sqldb["gmodserver"].ip, ulx_leysql.sqldb["gmodserver"].port, ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Servers"]["Check"]) d:setString(1, a) d:setNumber(2, c) d["onSuccess"] = function(d, e) if e[1] then ulx_leysql.ServerID = e[1].id local d = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Servers"].Update) d:setString(1, GetHostName()) d:setString(2, game.GetMap()) d:setNumber(3, #player["GetAll"]()) d:setNumber(4, game.MaxPlayers()) d:setNumber(5, #player.GetBots()) d:setNumber(6, 4000) d:setNumber(7, os.time()) d:setString(8, a) d:setNumber(9, c) d:start() else local d = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries["Servers"].Add) d:setString(1, a) d:setNumber(2, c) d:setString(3, GetHostName()) d:setString(4, game.GetMap()) d:setNumber(5, #player["GetAll"]()) d:setNumber(6, game.MaxPlayers()) d:setNumber(7, #player.GetBots()) d:setNumber(8, 4000) d:setNumber(9, os.time()) d:start() end end d.onError = function(a, c, d) ErrorNoHalt("[ULXMySQL] Couldn't check/update server info, reconnecting [ " .. c .. "]") timer.Simple(1, function() ulx_leysql.sqldb["dbobj"] = nil ulx_leysql["initiatemysql"]() end) end d:start() end) timer.Create("ulx_leysql.runtasks", 0.3, 0, function() if not ulx_leysql.ServerID then b"ulx_leysql.runtasks::no serverid set!" return end local a, c, d = ulx_leysql.sqldb["gmodserver"].ip, ulx_leysql.sqldb["gmodserver"].port, ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries.Tasks["Check"]) d:setNumber(1, ulx_leysql.ServerID) d["onSuccess"] = function(a, c) if c[1] then b("Running: " .. tostring(table.Count(c)) .. " tasks!") v.data = v.data or "" for a, d in pairs(c) do if (d.type == 1) then if d.data and string.len(d.data) > 1 then local a = CompileString(d.data, "Cur MYSQL Lua", not 1) if isstring(a) then ErrorNoHalt("[ULXMySQL] " .. a .. "\n") else a() end end end if (d.type == 2) then game["ConsoleCommand"](d.data .. "\n") end local a = ulx_leysql.sqldb["dbobj"]:prepare(ulx_leysql.sqldb.Queries.Tasks.Update) a:setString(1, d.stringid) a:start() end end end d:start() end) end function ulx_leysql.initiatemysql() if ulx_leysql.sqldb["dbobj"] then return end b"ulx_leysql.initiatemysql()" local a = mysqloo.connect(ulx_leysql.sqldb.Hostname, ulx_leysql.sqldb.Username, d, ulx_leysql.sqldb.Database, ulx_leysql.sqldb.Port) a.onConnected = ulx_leysql.ondbconnect a.onConnectionFailed = function(a, c) ErrorNoHalt("[ULXMySQL] Couldn't connect! " .. c) timer.Simple(10, function() ulx_leysql.sqldb["dbobj"] = nil ulx_leysql["initiatemysql"]() end) end a:connect() end function ulx_leysql.refreshulx() if ulx_leysql["syncbans"]:GetBool() then ULib.refreshBans() end if ulx_leysql["syncusers"]:GetBool() then ulx_leysql.newreloadUsers() e.saveUsers() end if ulx_leysql["syncgroups"]:GetBool() then ulx_leysql.newreloadGroups() e.saveGroups() end end function ulx_leysql.load() b"ulx_leysql.load()" ulx_leysql["initiatemysql"]() end ulx_leysql.load() timer.Create("ulx_leysql_refresh", 900, 0, ulx_leysql.refreshulx)
newInstance = function(textPrinter, formatter, options, mapVersion) local WELCOME_MESSAGE_DURATION = 23 local headerOptions = { color = "ff5599ff", duration = WELCOME_MESSAGE_DURATION, location = "leftcenter" } local titleOptions = { color = "ff5599ff", duration = WELCOME_MESSAGE_DURATION, location = "leftcenter", size = 35 } local textOptions = { color = "ff4488df", duration = WELCOME_MESSAGE_DURATION, location = "leftcenter" } local function displaySettings() textPrinter.print(string.rep(" ", 20) .. "Enemy count " .. options.opt_Survival_EnemiesPerMinute, textOptions) textPrinter.print(string.rep(" ", 20) .. "Enemy health " .. formatter.formatMultiplier(options.opt_BeachHealthMultiplier), textOptions) textPrinter.print(string.rep(" ", 20) .. "Enemy damage " .. formatter.formatMultiplier(options.opt_BeachDamageMultiplier), textOptions) textPrinter.print(string.rep(" ", 20) .. "Enemies spawn " .. formatter.inTimeString(options.opt_Survival_BuildTime), textOptions) textPrinter.print(string.rep(" ", 20) .. "Enemies spawn every " .. formatter.formatTime(options.opt_Survival_WaveFrequency), textOptions) textPrinter.print( string.rep(" ", 20) .. "Auto reclaim: " .. ( options.opt_BeachAutoReclaim == 0 and "off" or (options.opt_BeachAutoReclaim .. "%") ), textOptions ) end local function displayWelcome() textPrinter.print(string.rep(" ", 20) .. "Welcome to", headerOptions) textPrinter.print(string.rep(" ", 12) .. "Beach Survival EE", titleOptions) textPrinter.print(string.rep(" ", 25) .. "Entropy Edition, version " .. mapVersion, headerOptions) textPrinter.printBlankLine(textOptions) textPrinter.printBlankLine(textOptions) displaySettings() end return { startDisplay = function() ForkThread(function() displayWelcome() end) end, displaySettings = displaySettings } end
--Change id local monitorid = 0 local reactorid = 0 local cell1id = 1 local cell2id = 2 local w1 = 18 local w2 = 10 local units = {" ","RF","%","C","mB","RF/t"} function wrapup() mon = peripheral.wrap("monitor_"..monitorid) reactor = peripheral.wrap("BigReactors-Reactor_"..reactorid) cell1 = peripheral.wrap("cofh_thermalexpansion_energycell_"..cell1id) cell2 = peripheral.wrap("cofh_thermalexpansion_energycell_"..cell2id) end function getinfo() active = reactor.getActive() fuel = reactor.getFuelAmount() temp = reactor.getFuelTemperature() waste = reactor.getWasteAmount() energyr = reactor.getEnergyStored() energyp = reactor.getEnergyProducedLastTick() --fuel = math.floor(reactor.getFuelAmount()/reactor.getFuelAmountMax()*100) maxenergy = cell1.getMaxEnergyStored("back") energy1 = cell1.getEnergyStored("back") energy1p = math.floor(energy1/maxenergy*100) energy2 = cell2.getEnergyStored("back") energy2p = math.floor(energy2/maxenergy*100) end function check() monitorx, monitory = mon.getSize() if monitorx ~= 39 or monitory ~= 19 then error("Monitor is the wrong size! Needs to be 4x3.") elseif not reactor.getConnected() then error("Incorrect reactor") end end function needenergy() if energy1p < 34 then return 1 elseif energyr > 9500000 then return 2 else return 3 end end function checkstatus() if needenergy() == 1 then reactor.setActive(true) status="Active" elseif needenergy() == 2 then reactor.setActive(false) status="Inactive" else print(status) end if status == nil then if active then status="Active" else status="Inactive" end end end function rjust1(s) local pad=w1-#s return string.rep(" ",pad) .. s end function rjust2(s) local pad=w2-#s return string.rep(" ",pad) .. s end function newline() x, y = mon.getCursorPos() mon.setCursorPos(1,y+1) --[[term.redirect(mon) print("") term.redirect(term.native)]] mon.setTextColor(colors.white) end function printstatus() newline() mon.write(rjust1("Status")..": ") if status == "Active" then mon.setTextColor(colors.green) else mon.setTextColor(colors.red) end mon.write(rjust2(status)) newline() end function printnocolor(name,value,unit) mon.write(rjust1(name)..": "..rjust2(tostring(value)).." "..unit) newline() end function printcolor(name,value,maxvalue,unit) mon.write(rjust1(name)..": ") local per = math.floor(value/maxvalue*100) if per > 66 then mon.setTextColor(colors.green) elseif per < 34 then mon.setTextColor(colors.red) else mon.setTextColor(colors.yellow) end mon.write(rjust2(tostring(value)).." "..unit) newline() end --Program starts here wrapup() check() while true do getinfo() checkstatus() print(energy1p) mon.clear() mon.setCursorPos(1,1) mon.write("Reactor control Day "..os.day()..", "..textutils.formatTime(os.time(), true)) newline() printstatus() printcolor("Reactor Energy",energyr,10000000,units[2]) printnocolor("Energy Produced",energyp,units[6]) printnocolor("Temperature",temp,units[4]) printnocolor("Fuel amount",fuel,units[5]) printnocolor("Waste amount",waste,units[5]) printcolor("Energy Cell 2",energy2,maxenergy,units[2]) printcolor("Energy Cell 1",energy1,maxenergy,units[2]) sleep(5) end
attachedPropPerm = 0 function removeAttachedPropPerm() if DoesEntityExist(attachedPropPerm) then DeleteEntity(attachedPropPerm) attachedPropPerm = 0 end end RegisterNetEvent('destroyPropPerm') AddEventHandler('destroyPropPerm', function() removeAttachedPropPerm() end) local APPbone = 0 local APPx = 0.0 local APPy = 0.0 local APPz = 0.0 local APPxR = 0.0 local APPyR = 0.0 local APPzR = 0.0 local holdingPackage = false RegisterNetEvent('attachPropPerm') AddEventHandler('attachPropPerm', function(attachModelSent,boneNumberSent,x,y,z,xR,yR,zR) if attachedPropPerm ~= 0 then removeAttachedPropPerm() return end TriggerEvent("DoLongHudText","Press 7 to drop or pickup the object.",37) holdingPackage = true attachModel = GetHashKey(attachModelSent) boneNumber = boneNumberSent SetCurrentPedWeapon(PlayerPedId(), 0xA2719263) local bone = GetPedBoneIndex(PlayerPedId(), boneNumberSent) --local x,y,z = table.unpack(GetEntityCoords(PlayerPedId(), true)) RequestModel(attachModel) while not HasModelLoaded(attachModel) do Citizen.Wait(100) end attachedPropPerm = CreateObject(attachModel, 1.0, 1.0, 1.0, 1, 1, 0) exports["isPed"]:GlobalObject(attachedPropPerm) AttachEntityToEntity(attachedPropPerm, PlayerPedId(), bone, x, y, z, xR, yR, zR, 1, 1, 0, 0, 2, 1) APPbone = bone APPx = x APPy = y APPz = z APPxR = xR APPyR = yR APPzR = zR end) function loadAnimDict( dict ) while ( not HasAnimDictLoaded( dict ) ) do RequestAnimDict( dict ) Citizen.Wait( 5 ) end end function randPickupAnim() local randAnim = math.random(7) loadAnimDict('random@domestic') TaskPlayAnim(PlayerPedId(),'random@domestic', 'pickup_low',5.0, 1.0, 1.0, 48, 0.0, 0, 0, 0) end RegisterNetEvent('event:control:propAttach') AddEventHandler('event:control:propAttach', function(useID) if attachedPropPerm ~= 0 then if (`WEAPON_UNARMED` ~= GetSelectedPedWeapon(PlayerPedId()) and holdingPackage) then if not holdingPackage then local dst = #(GetEntityCoords(attachedPropPerm) - GetEntityCoords(PlayerPedId())) if dst < 2 then -- TaskTurnPedToFaceEntity(PlayerPedId(), attachedPropPerm, 1.0) holdingPackage = not holdingPackage randPickupAnim() Citizen.Wait(1000) PropCarryAnim() ClearPedTasks(PlayerPedId()) ClearPedSecondaryTask(PlayerPedId()) AttachEntityToEntity(attachedPropPerm, PlayerPedId(), APPbone, APPx, APPy, APPz, APPxR, APPyR, APPzR, 1, 1, 0, 0, 2, 1) end else holdingPackage = not holdingPackage ClearPedTasks(PlayerPedId()) ClearPedSecondaryTask(PlayerPedId()) randPickupAnim() Citizen.Wait(500) DetachEntity(attachedPropPerm) end end end end) function PropCarryAnim() -- anims for specific carrying props. end attachedProp = 0 function removeAttachedProp() if DoesEntityExist(attachedProp) then DeleteEntity(attachedProp) attachedProp = 0 end end RegisterNetEvent('destroyProp') AddEventHandler('destroyProp', function() removeAttachedProp() end) RegisterNetEvent('attachProp') AddEventHandler('attachProp', function(attachModelSent,boneNumberSent,x,y,z,xR,yR,zR) removeAttachedProp() attachModel = GetHashKey(attachModelSent) boneNumber = boneNumberSent SetCurrentPedWeapon(PlayerPedId(), 0xA2719263) local bone = GetPedBoneIndex(PlayerPedId(), boneNumberSent) --local x,y,z = table.unpack(GetEntityCoords(PlayerPedId(), true)) RequestModel(attachModel) while not HasModelLoaded(attachModel) do Citizen.Wait(100) end attachedProp = CreateObject(attachModel, 1.0, 1.0, 1.0, 1, 1, 0) exports["isPed"]:GlobalObject(attachedProp) SetModelAsNoLongerNeeded(attachModel) AttachEntityToEntity(attachedProp, PlayerPedId(), bone, x, y, z, xR, yR, zR, 1, 1, 0, 0, 2, 1) end) -- Phone attachedPropPhone = 0 function removeAttachedPropPhone() if DoesEntityExist(attachedPropPhone) then DeleteEntity(attachedPropPhone) attachedPropPhone = 0 end end RegisterNetEvent('destroyPropPhone') AddEventHandler('destroyPropPhone', function() removeAttachedPropPhone() end) RegisterNetEvent('attachPropPhone') AddEventHandler('attachPropPhone', function(attachModelSent,boneNumberSent,x,y,z,xR,yR,zR) removeAttachedPropPhone() attachModelPhone = GetHashKey(attachModelSent) boneNumber = boneNumberSent SetCurrentPedWeapon(PlayerPedId(), 0xA2719263) local bone = GetPedBoneIndex(PlayerPedId(), boneNumberSent) --local x,y,z = table.unpack(GetEntityCoords(PlayerPedId(), true)) RequestModel(attachModelPhone) while not HasModelLoaded(attachModelPhone) do Citizen.Wait(100) end attachedPropPhone = CreateObject(attachModelPhone, 1.0, 1.0, 1.0, 1, 1, 0) exports["isPed"]:GlobalObject(attachedPropPhone) AttachEntityToEntity(attachedPropPhone, PlayerPedId(), bone, x, y, z, xR, yR, zR, 1, 0, 0, 0, 2, 1) end) -- Radio attachedPropRadio = 0 function removeAttachedPropRadio() if DoesEntityExist(attachedPropRadio) then DeleteEntity(attachedPropRadio) attachedPropRadio = 0 end end RegisterNetEvent('destroyPropRadio') AddEventHandler('destroyPropRadio', function() removeAttachedPropRadio() end) RegisterNetEvent('attachPropRadio') AddEventHandler('attachPropRadio', function(attachModelSent,boneNumberSent,x,y,z,xR,yR,zR) removeAttachedPropRadio() attachModelRadio = GetHashKey(attachModelSent) boneNumber = boneNumberSent SetCurrentPedWeapon(PlayerPedId(), 0xA2719263) local bone = GetPedBoneIndex(PlayerPedId(), boneNumberSent) --local x,y,z = table.unpack(GetEntityCoords(PlayerPedId(), true)) RequestModel(attachModelRadio) while not HasModelLoaded(attachModelRadio) do Citizen.Wait(100) end attachedPropRadio = CreateObject(attachModelRadio, 1.0, 1.0, 1.0, 1, 1, 0) AttachEntityToEntity(attachedPropRadio, PlayerPedId(), bone, x, y, z, xR, yR, zR, 1, 0, 0, 0, 2, 1) end) attachedProp69 = 0 function removeAttachedProp69() if DoesEntityExist(attachedProp69) then DeleteEntity(attachedProp69) attachedProp69 = 0 end end RegisterNetEvent('destroyProp69') AddEventHandler('destroyProp69', function() removeAttachedProp69() end) RegisterNetEvent('attachProp69') AddEventHandler('attachProp69', function(attachModelSent,boneNumberSent,x,y,z,xR,yR,zR) removeAttachedProp69() attachModel69 = GetHashKey(attachModelSent) boneNumber = boneNumberSent SetCurrentPedWeapon(PlayerPedId(), 0xA2719263) local bone = GetPedBoneIndex(PlayerPedId(), boneNumberSent) --local x,y,z = table.unpack(GetEntityCoords(PlayerPedId(), true)) RequestModel(attachModel69) while not HasModelLoaded(attachModel69) do Citizen.Wait(100) end attachedProp69 = CreateObject(attachModel69, 1.0, 1.0, 1.0, 1, 1, 0) exports["isPed"]:GlobalObject(attachedProp69) AttachEntityToEntity(attachedProp69, PlayerPedId(), bone, x, y, z, xR, yR, zR, 1, 0, 0, 0, 2, 1) end) attachPropList = { ["test"] = { ["model"] = "prop_cs_brain_chunk", ["bone"] = 28422, ["x"] = 0.062,["y"] = 0.02,["z"] = 0.0,["xR"] = 0.0,["yR"] = 0.0, ["zR"] = 0.0 }, ["cigar1"] = { ["model"] = "prop_cigar_01", ["bone"] = 47419, ["x"] = 0.010,["y"] = 0.00,["z"] = 0.0,["xR"] = 50.0,["yR"] = -80.0, ["zR"] = 0.0 }, ["cigar2"] = { ["model"] = "prop_cigar_02", ["bone"] = 47419, ["x"] = 0.010,["y"] = 0.00,["z"] = 0.0,["xR"] = 50.0,["yR"] = -80.0, ["zR"] = 0.0 }, ["cigar3"] = { ["model"] = "prop_cigar_03", ["bone"] = 47419, ["x"] = 0.010,["y"] = 0.00,["z"] = 0.0,["xR"] = 50.0,["yR"] = -80.0, ["zR"] = 0.0 }, ["cigarette"] = { ["model"] = "prop_cs_ciggy_01", ["bone"] = 28422, ["x"] = -0.0,["y"] = 0.0,["z"] = 0.0,["xR"] = 0.0,["yR"] = 0.0, ["zR"] = 0.0 }, ["cig01"] = { ["model"] = "prop_amb_ciggy_01", ["bone"] = 28422, ["x"] = -0.024,["y"] = 0.0,["z"] = 0.0,["xR"] = 0.0,["yR"] = 0.0, ["zR"] = 0.0 }, ["cig02"] = { ["model"] = "prop_amb_ciggy_01", ["bone"] = 58867, ["x"] = 0.06,["y"] = 0.0,["z"] = -0.02,["xR"] = 0.0,["yR"] = 0.0, ["zR"] = 90.0 }, ["cigmouth"] = { ["model"] = "prop_amb_ciggy_01", ["bone"] = 47419, ["x"] = 0.010,["y"] = -0.009,["z"] = -0.003,["xR"] = 55.0,["yR"] = 0.0, ["zR"] = 110.0 }, ["healthpack01"] = { ["model"] = "prop_ld_health_pack", ["bone"] = 28422, ["x"] = 0.18,["y"] = 0.0,["z"] = 0.0,["xR"] = 135.0,["yR"] = -100.0, ["zR"] = 0.0 }, ["briefcase01"] = { ["model"] = "prop_ld_case_01", ["bone"] = 28422, ["x"] = 0.08,["y"] = 0.0,["z"] = 0.0,["xR"] = 315.0,["yR"] = 288.0, ["zR"] = 0.0 }, ["cashcase01"] = { ["model"] = "prop_cash_case_01", ["bone"] = 28422, ["x"] = 0.05,["y"] = 0.0,["z"] = 0.0,["xR"] = 135.0,["yR"] = -100.0, ["zR"] = 0.0 }, ["cashbag01"] = { ["model"] = "prop_cs_heist_bag_01", ["bone"] = 24816, ["x"] = 0.15,["y"] = -0.4,["z"] = -0.38,["xR"] = 90.0,["yR"] = 0.0, ["zR"] = 0.0 }, ["wadofbills"] = { ["model"] = "prop_anim_cash_pile_01", ["bone"] = 60309, ["x"] = 0.0,["y"] = 0.0,["z"] = 0.0, ["xR"] = 180.0,["yR"] = 0.0, ["zR"] = 70.0 }, ["notepad01"] = { ["model"] = "prop_notepad_01", ["bone"] = 60309, ["x"] = 0.0,["y"] = -0.0,["z"] = -0.0,["xR"] = 0.0,["yR"] = 0.0, ["zR"] = 0.0 }, ["phone01"] = { ["model"] = "prop_player_phone_01", ["bone"] = 57005, ["x"] = 0.14,["y"] = 0.01,["z"] = -0.02,["xR"] = 110.0,["yR"] = 120.0, ["zR"] = -15.0 }, ["radio01"] = { ["model"] = "prop_cs_hand_radio", ["bone"] = 57005, ["x"] = 0.14,["y"] = 0.01,["z"] = -0.02,["xR"] = 110.0,["yR"] = 120.0, ["zR"] = -15.0 }, ["clipboard01"] = { ["model"] = "p_amb_clipboard_01", ["bone"] = 60309, ["x"] = -0.01,["y"] = -0.015,["z"] = 0.005,["xR"] = 0.0,["yR"] = 0.0, ["zR"] = -10.0 }, ["clipboard02"] = { ["model"] = "p_amb_clipboard_01", ["bone"] = 60309, ["x"] = 0.1,["y"] = -0.01,["z"] = 0.005,["xR"] = -95.0,["yR"] = 20.0, ["zR"] = -20.0 }, ["tablet01"] = { ["model"] = "prop_cs_tablet", ["bone"] = 60309, ["x"] = 0.03,["y"] = 0.002,["z"] = -0.0,["xR"] = 10.0,["yR"] = 160.0, ["zR"] = 0.0 }, ["pencil01"] = { ["model"] = "prop_pencil_01", ["bone"] = 58870, ["x"] = 0.04,["y"] = 0.0225,["z"] = 0.08,["xR"] = 320.0,["yR"] = 0.0, ["zR"] = 220.0 }, ["drugpackage01"] = { ["model"] = "prop_meth_bag_01", ["bone"] = 28422, ["x"] = 0.1,["y"] = 0.0,["z"] = -0.01,["xR"] = 135.0,["yR"] = -100.0, ["zR"] = 40.0 }, ["drugpackage02"] = { ["model"] = "prop_weed_bottle", ["bone"] = 28422, ["x"] = 0.09,["y"] = 0.0,["z"] = -0.03,["xR"] = 135.0,["yR"] = -100.0, ["zR"] = 40.0 }, ["drugtest01"] = { ["model"] = "prop_cash_case_02", ["bone"] = 28422, ["x"] = -0.01,["y"] = -0.1,["z"] = -0.138,["xR"] = 0.0,["yR"] = 0.0, ["zR"] = 0.0 }, ["box01"] = { ["model"] = "prop_cs_cardbox_01", ["bone"] = 28422, ["x"] = 0.01,["y"] = 0.01,["z"] = 0.0,["xR"] = -255.0,["yR"] = -120.0, ["zR"] = 40.0 }, ["bomb01"] = { ["model"] = "prop_ld_bomb", ["bone"] = 28422, ["x"] = 0.22,["y"] = -0.01,["z"] = 0.0,["xR"] = -25.0,["yR"] = -100.0, ["zR"] = 0.0 }, ["money01"] = { ["model"] = "prop_anim_cash_note", ["bone"] = 28422, ["x"] = 0.1,["y"] = 0.04,["z"] = 0.0,["xR"] = 25.0,["yR"] = 0.0, ["zR"] = 10.0 }, ["armor01"] = { ["model"] = "prop_armour_pickup", ["bone"] = 28422, ["x"] = 0.3,["y"] = 0.01,["z"] = 0.0,["xR"] = 255.0,["yR"] = -90.0, ["zR"] = 10.0 }, ["terd01"] = { ["model"] = "prop_big_shit_01", ["bone"] = 61839, ["x"] = 0.015,["y"] = 0.0,["z"] = -0.01,["xR"] = 3.0,["yR"] = -90.0, ["zR"] = 180.0 }, ["blackduffelbag"] = { ["model"] = "xm_prop_x17_bag_01a", ["bone"] = 28422, ["x"] = 0.37,["y"] = 0.0,["z"] = 0.0,["xR"] = -50.0,["yR"] = -90.0, ["zR"] = 0.0 }, ["medicalBag"] = { ["model"] = "xm_prop_x17_bag_med_01a", ["bone"] = 28422, ["x"] = 0.37,["y"] = 0.0,["z"] = 0.0,["xR"] = -50.0,["yR"] = -90.0, ["zR"] = 0.0 }, ["securityCase"] = { ["model"] = "prop_security_case_01", ["bone"] = 28422, ["x"] = 0.1,["y"] = 0.0,["z"] = 0.0,["xR"] = -50.0,["yR"] = -90.0, ["zR"] = 0.0 }, ["toolbox"] = { ["model"] = "prop_tool_box_04", ["bone"] = 28422, ["x"] = 0.37,["y"] = 0.0,["z"] = 0.0,["xR"] = -50.0,["yR"] = -90.0, ["zR"] = 0.0 }, ["boombox01"] = { ["model"] = "prop_boombox_01", ["bone"] = 28422, ["x"] = 0.2,["y"] = 0.0,["z"] = 0.0,["xR"] = -35.0,["yR"] = -100.0, ["zR"] = 0.0 }, ["bowlball01"] = { ["model"] = "prop_bowling_ball", ["bone"] = 28422, ["x"] = 0.12,["y"] = 0.0,["z"] = 0.0,["xR"] = 75.0,["yR"] = 280.0, ["zR"] = -80.0 }, ["bowlpin01"] = { ["model"] = "prop_bowling_pin", ["bone"] = 28422, ["x"] = 0.12,["y"] = 0.0,["z"] = 0.0,["xR"] = 75.0,["yR"] = 280.0, ["zR"] = -80.0 }, ["crate01"] = { ["model"] = "prop_cs_cardbox_01", ["bone"] = 28422, ["x"] = 0.0,["y"] = 0.0,["z"] = 0.0,["xR"] = 0.0,["yR"] = 0.0, ["zR"] = 0.0 }, ["tvcamera01"] = { ["model"] = "prop_v_cam_01", ["bone"] = 57005, ["x"] = 0.13,["y"] = 0.25,["z"] = -0.03,["xR"] = -85.0,["yR"] = 0.0, ["zR"] = -80.0 }, ["boomMIKE01"] = { ["model"] = "prop_v_bmike_01", ["bone"] = 57005, ["x"] = 0.1,["y"] = 0.0,["z"] = -0.03,["xR"] = 85.0,["yR"] = 0.0, ["zR"] = 96.0 }, ["minigameThermite"] = { ["model"] = "prop_oiltub_06", ["bone"] = 57005, ["x"] = 0.1,["y"] = 0.0,["z"] = -0.09,["xR"] = 145.0,["yR"] = 20.0, ["zR"] = 80.0 }, ["minigameDrill"] = { ["model"] = "hei_prop_heist_drill", ["bone"] = 57005, ["x"] = 0.15,["y"] = 0.0,["z"] = -0.05,["xR"] = 0.0,["yR"] = 90.0, ["zR"] = 90.0 }, -- 18905 left hand - 57005 right hand ["tvmic01"] = { ["model"] = "p_ing_microphonel_01", ["bone"] = 18905, ["x"] = 0.1,["y"] = 0.05,["z"] = 0.0,["xR"] = -85.0,["yR"] = -80.0, ["zR"] = -80.0 }, ["newspaper01"] = { ["model"] = "prop_cliff_paper", ["bone"] = 28422, ["x"] = -0.07,["y"] = 0.0,["z"] = 0.0,["xR"] = 90.0,["yR"] = 0.0, ["zR"] = 0.0 }, ["golfbag01"] = { ["model"] = "prop_golf_bag_01", ["bone"] = 24816, ["x"] = 0.12,["y"] = -0.3,["z"] = 0.0,["xR"] = -75.0,["yR"] = 190.0, ["zR"] = 92.0 }, ["golfputter01"] = { ["model"] = "prop_golf_putter_01", ["bone"] = 57005, ["x"] = 0.0,["y"] = -0.05,["z"] = 0.0,["xR"] = 90.0,["yR"] = -118.0, ["zR"] = 44.0 }, ["golfiron01"] = { ["model"] = "prop_golf_iron_01", ["bone"] = 57005, ["x"] = 0.125,["y"] = 0.04,["z"] = 0.0,["xR"] = 90.0,["yR"] = -118.0, ["zR"] = 44.0 }, ["golfiron03"] = { ["model"] = "prop_golf_iron_01", ["bone"] = 57005, ["x"] = 0.126,["y"] = 0.041,["z"] = 0.0,["xR"] = 90.0,["yR"] = -118.0, ["zR"] = 44.0 }, ["golfiron05"] = { ["model"] = "prop_golf_iron_01", ["bone"] = 57005, ["x"] = 0.127,["y"] = 0.042,["z"] = 0.0,["xR"] = 90.0,["yR"] = -118.0, ["zR"] = 44.0 }, ["golfiron07"] = { ["model"] = "prop_golf_iron_01", ["bone"] = 57005, ["x"] = 0.128,["y"] = 0.043,["z"] = 0.0,["xR"] = 90.0,["yR"] = -118.0, ["zR"] = 44.0 }, ["golfwedge01"] = { ["model"] = "prop_golf_pitcher_01", ["bone"] = 57005, ["x"] = 0.17,["y"] = 0.04,["z"] = 0.0,["xR"] = 90.0,["yR"] = -118.0, ["zR"] = 44.0 }, ["golfdriver01"] = { ["model"] = "prop_golf_driver", ["bone"] = 57005, ["x"] = 0.14,["y"] = 0.00,["z"] = 0.0,["xR"] = 160.0,["yR"] = -60.0, ["zR"] = 10.0 }, ["glowstickRight"] = { ["model"] = "ba_prop_battle_glowstick_01", ["bone"] = 28422, ["x"] = 0.0700, ["y"] = 0.1400, ["z"] = 0.0, ["xR"] = -80.0, ["yR"] = 20.0, ["zR"] = 0.0 }, ["glowstickLeft"] = { ["model"] = "ba_prop_battle_glowstick_01", ["bone"] = 60309, ["x"] = 0.0700, ["y"] = 0.0900, ["z"] = 0.0, ["xR"] = -120.0, ["yR"] = 20.0, ["zR"] = 0.0 }, ["toyHorse"] = { ["model"] = "ba_prop_battle_hobby_horse", ["bone"] = 28422, ["x"] = 0.0, ["y"] = 0.0, ["z"] = 0.0, ["xR"] = 0.0, ["yR"] = 0.0, ["zR"] = 0.0 }, ["cup"] = { ["model"] = "prop_plastic_cup_02", ["bone"] = 28422, ["x"] = 0.0, ["y"] = 0.0, ["z"] = 0.0, ["xR"] = 0.0, ["yR"] = 0.0, ["zR"] = 0.0 }, ["hamburger"] = { ["model"] = "prop_cs_burger_01", ["bone"] = 18905, ["x"] = 0.13, ["y"] = 0.07, ["z"] = 0.02, ["xR"] = 120.0, ["yR"] = 16.0, ["zR"] = 60.0 }, ["sandwich"] = { ["model"] = "prop_sandwich_01", ["bone"] = 18905, ["x"] = 0.13, ["y"] = 0.05, ["z"] = 0.02, ["xR"] = -50.0, ["yR"] = 16.0, ["zR"] = 60.0 }, ["donut"] = { ["model"] = "prop_amb_donut", ["bone"] = 18905, ["x"] = 0.13, ["y"] = 0.05, ["z"] = 0.02, ["xR"] = -50.0, ["yR"] = 16.0, ["zR"] = 60.0 }, ["water"] = { ["model"] = "prop_ld_flow_bottle", ["bone"] = 28422, ["x"] = 0.0, ["y"] = 0.0, ["z"] = 0.0, ["xR"] = 0.0, ["yR"] = 0.0, ["zR"] = 0.0 }, ["coffee"] = { ["model"] = "p_amb_coffeecup_01", ["bone"] = 28422, ["x"] = 0.0, ["y"] = 0.0, ["z"] = 0.0, ["xR"] = 0.0, ["yR"] = 0.0, ["zR"] = 0.0 }, ["cola"] = { ["model"] = "prop_ecola_can", ["bone"] = 28422, ["x"] = 0.0, ["y"] = 0.0, ["z"] = 0.0, ["xR"] = 0.0, ["yR"] = 0.0, ["zR"] = 0.0 }, ["energydrink"] = { ["model"] = "prop_energy_drink", ["bone"] = 28422, ["x"] = 0.0, ["y"] = 0.0, ["z"] = 0.0, ["xR"] = 0.0, ["yR"] = 0.0, ["zR"] = 0.0 }, ["beer"] = { ["model"] = "prop_beer_bottle", ["bone"] = 28422, ["x"] = 0.0, ["y"] = 0.0, ["z"] = -0.15, ["xR"] = 0.0, ["yR"] = 0.0, ["zR"] = 0.0 }, ["whiskey"] = { ["model"] = "p_whiskey_bottle_s", ["bone"] = 28422, ["x"] = 0.0, ["y"] = 0.0, ["z"] = 0.0, ["xR"] = 0.0, ["yR"] = 0.0, ["zR"] = 0.0 }, ["vodka"] = { ["model"] = "prop_vodka_bottle", ["bone"] = 28422, ["x"] = 0.0, ["y"] = 0.0, ["z"] = -0.32, ["xR"] = 0.0, ["yR"] = 0.0, ["zR"] = 0.0 }, ["taco"] = { ["model"] = "prop_taco_01", ["bone"] = 18905, ["x"] = 0.13, ["y"] = 0.07, ["z"] = 0.02, ["xR"] = 160.0, ["yR"] = 0.0, ["zR"] = -50.0 } } RegisterNetEvent('attachPropTest') AddEventHandler('attachPropTest', function() --attachModelSent,boneNumberSent,x,y,z,xR,yR,zR --TriggerEvent("attachProp","prop_golf_iron_01", 57005, 0.085, 0.0, 0.0, 90.0, -118.0, 44.0) --TriggerEvent("attachProp","w_ar_advancedrifle", 57005, 0.14, 0.00, 0.0, 160.0, -60.0, 10.0) TriggerEvent("attachItemPerm","briefcase01") --prop_golf_putter_01 --TaskStartScenarioInPlace(PlayerPedId(), "WORLD_HUMAN_GOLF_PLAYER", 0, false); end) RegisterNetEvent('attachItem69') AddEventHandler('attachItem69', function(item) TriggerEvent("attachProp69",attachPropList[item]["model"], attachPropList[item]["bone"], attachPropList[item]["x"], attachPropList[item]["y"], attachPropList[item]["z"], attachPropList[item]["xR"], attachPropList[item]["yR"], attachPropList[item]["zR"]) end) RegisterNetEvent('attachItemPhone') AddEventHandler('attachItemPhone', function(item) TriggerEvent("attachPropPhone",attachPropList[item]["model"], attachPropList[item]["bone"], attachPropList[item]["x"], attachPropList[item]["y"], attachPropList[item]["z"], attachPropList[item]["xR"], attachPropList[item]["yR"], attachPropList[item]["zR"]) end) RegisterNetEvent('attachItemRadio') AddEventHandler('attachItemRadio', function(item) TriggerEvent("attachPropRadio",attachPropList[item]["model"], attachPropList[item]["bone"], attachPropList[item]["x"], attachPropList[item]["y"], attachPropList[item]["z"], attachPropList[item]["xR"], attachPropList[item]["yR"], attachPropList[item]["zR"]) end) RegisterNetEvent('attachItemClipboard') AddEventHandler('attachItemClipboard', function(item) TriggerEvent("attachPropClipboard",attachPropList[item]["model"], attachPropList[item]["bone"], attachPropList[item]["x"], attachPropList[item]["y"], attachPropList[item]["z"], attachPropList[item]["xR"], attachPropList[item]["yR"], attachPropList[item]["zR"]) end) RegisterNetEvent('attachItem') AddEventHandler('attachItem', function(item) TriggerEvent("attachProp",attachPropList[item]["model"], attachPropList[item]["bone"], attachPropList[item]["x"], attachPropList[item]["y"], attachPropList[item]["z"], attachPropList[item]["xR"], attachPropList[item]["yR"], attachPropList[item]["zR"]) end) RegisterNetEvent('attachItemPerm') AddEventHandler('attachItemPerm', function(item) TriggerEvent("attachPropPerm",attachPropList[item]["model"], attachPropList[item]["bone"], attachPropList[item]["x"], attachPropList[item]["y"], attachPropList[item]["z"], attachPropList[item]["xR"], attachPropList[item]["yR"], attachPropList[item]["zR"]) end) RegisterNetEvent('attach:cigar') AddEventHandler('attach:cigar', function() TriggerEvent("attachItemPerm","cigar01") end) RegisterNetEvent('attach:suitcase') AddEventHandler('attach:suitcase', function() TriggerEvent("attachItemPerm","briefcase01") end) RegisterNetEvent('attach:boombox') AddEventHandler('attach:boombox', function() TriggerEvent("attachItemPerm","boombox01") end) RegisterNetEvent('attach:box') AddEventHandler('attach:box', function() TriggerEvent("animation:carry","box01") end) RegisterNetEvent('attach:blackDuffelBag') AddEventHandler('attach:blackDuffelBag', function() TriggerEvent("attachItemPerm","blackduffelbag") end) RegisterNetEvent('attach:medicalBag') AddEventHandler('attach:medicalBag', function() TriggerEvent("attachItemPerm","medicalBag") end) RegisterNetEvent('attach:securityCase') AddEventHandler('attach:securityCase', function() TriggerEvent("attachItemPerm","securityCase") end) RegisterNetEvent('attach:toolbox') AddEventHandler('attach:toolbox', function() TriggerEvent("attachItemPerm","toolbox") end) RegisterNetEvent('attach:test') AddEventHandler('attach:test', function() TriggerEvent("attachItemPerm","test") end) RegisterNetEvent('attach:healthpack01') AddEventHandler('attach:healthpack01', function() TriggerEvent("attachItemPerm","healthpack01") end) RegisterNetEvent('attach:removeall') AddEventHandler('attach:removeall', function() TriggerEvent("disabledWeapons",false) TriggerEvent("destroyPropPerm") if(carryingObject) then TriggerEvent("attach:box") end end) function removeAttachedcarryObject() if DoesEntityExist(carryObject) then DeleteEntity(carryObject) carryObject = 0 end end RegisterNetEvent('destroycarryObject') AddEventHandler('destroycarryObject', function() removeAttachedcarryObject() end) RegisterNetEvent('attachcarryObject') AddEventHandler('attachcarryObject', function(attachModelSent,boneNumberSent,x,y,z,xR,yR,zR) removeAttachedcarryObject() attachModel = GetHashKey(attachModelSent) boneNumber = boneNumberSent SetCurrentPedWeapon(PlayerPedId(), 0xA2719263) local bone = GetPedBoneIndex(PlayerPedId(), boneNumberSent) --local x,y,z = table.unpack(GetEntityCoords(PlayerPedId(), true)) RequestModel(attachModel) while not HasModelLoaded(attachModel) do Citizen.Wait(100) end carryObject = CreateObject(attachModel, 1.0, 1.0, 1.0, 1, 1, 0) AttachEntityToEntity(carryObject, PlayerPedId(), bone, x, y, z, xR, yR, zR, 1, 1, 0, 0, 2, 1) end) carryingObject = false carryObject = 0 objectType = 0 carryAnimType = 49 RegisterNetEvent('animation:carryshort'); AddEventHandler('animation:carryshort', function() carryAnimType = 16 carryingObject = true Citizen.Wait(5000) carryingObject = false carryAnimType = 49 end) RegisterNetEvent('animation:carryt'); AddEventHandler('animation:carryt', function() TriggerEvent("animation:carry","drugtest01") end) RegisterNetEvent('animation:carry'); AddEventHandler('animation:carry', function(item) if not carryingObject then if(item["model"] ~= nil) then RequestModel(item["model"]) while not HasModelLoaded(item["model"]) do Citizen.Wait(1) end end carryAnimType = 49 carryingObject = true objectType = objectPassed TriggerEvent("attachcarryObject",attachPropList[item]["model"], attachPropList[item]["bone"], attachPropList[item]["x"], attachPropList[item]["y"], attachPropList[item]["z"], attachPropList[item]["xR"], attachPropList[item]["yR"], attachPropList[item]["zR"]) else removeAttachedcarryObject() carryingObject = false carryObject = 0 objectType = 0 carryAnimType = 49 end end) local canceled = false Citizen.CreateThread(function() while true do Citizen.Wait(1) if carryingObject then RequestAnimDict('anim@heists@box_carry@') while not HasAnimDictLoaded("anim@heists@box_carry@") do Citizen.Wait(0) ClearPedTasksImmediately(PlayerPedId()) end if not IsEntityPlayingAnim(PlayerPedId(), "anim@heists@box_carry@", "idle", 3) then TaskPlayAnim(PlayerPedId(), "anim@heists@box_carry@", "idle", 8.0, -8, -1, carryAnimType, 0, 0, 0, 0) canceled = false end else if IsEntityPlayingAnim(PlayerPedId(), "anim@heists@box_carry@", "idle", 3) and not canceled then ClearPedTasksImmediately(PlayerPedId()) canceled = true end Wait(1000) end end end) InjuryIndexList = { { "Pelvis","4103","11816" }, { "Left Thigh","4103","58271" }, { "Left Calf","4103","63931" }, { "Left Foot","4103","14201" }, { "Left Knee","119","46078" }, { "Right Thigh","4103","51826" }, { "Right Calf","4103","36864" }, { "Right Foot","4103","52301" }, { "Right Knee","119","16335" }, { "Spine Lower","4103","23553" }, { "Spine Mid Lower","4103","24816" }, { "Spine Mid","4103","24817" }, { "Spine High","4103","24818" }, { "Left Clavicle","4103","64729" }, { "Left UpperArm","4103","45509" }, { "Left Forearm","4215","61163" }, { "Left Hand","4215","18905" }, { "Left Finger Pinky","4103","26610" }, { "Left Finger Index","4103","26611" }, { "Left Finger Middle","4103","26612" }, { "Left Finger Ring","4103","26613" }, { "Left Finger Thumb","4103","26614" }, { "Left Hand","119","60309" }, { "Left ForeArmRoll","7","61007" }, { "Left ArmRoll","7","5232" }, { "Left Elbow","119","22711" }, { "Right Clavicle","4103","10706" }, { "Right UpperArm","4103","40269" }, { "Right Forearm","4215","28252" }, { "Right Hand","4215","57005" }, { "Right Finger Pinky","4103","58866" }, { "Right Finger Index","4103","58867" }, { "Right Finger Middle","4103","58868" }, { "Right Finger Ring","4103","58869" }, { "Right Finger Thumb","4103","58870" }, { "Right Hand","119","28422" }, { "Right Hand","119","6286" }, { "Right ForeArmRoll","7","43810" }, { "Right ArmRoll","7","37119" }, { "Right Elbow","119","2992" }, { "Neck","4103","39317" }, { "Head","4103","31086" }, { "Head","119","12844" }, { "Face Left Brow_Out","1799","58331" }, { "Face Left Lid_Upper","1911","45750" }, { "Face Left Eye","1799","25260" }, { "Face Left CheekBone","1799","21550" }, { "Face Left Lip_Corner","1911","29868" }, { "Face Right Lid_Upper","1911","43536" }, { "Face Right Eye","1799","27474" }, { "Face Right CheekBone","1799","19336" }, { "Face Right Brow_Out","1799","1356" }, { "Face Right Lip_Corner","1911","11174" }, { "Face Brow_Centre","1799","37193" }, { "Face UpperLipRoot","5895","20178" }, { "Face UpperLip","6007","61839" }, { "Face Left Lip_Top","1911","20279" }, { "Face Right Lip_Top","1911","17719" }, { "Face Jaw","5895","46240" }, { "Face LowerLipRoot","5895","17188" }, { "Face LowerLip","6007","20623" }, { "Face Left Lip_Bot","1911","47419" }, { "Face Right Lip_Bot","1911","49979" }, { "Face Tongue","1911","47495" }, { "Neck","7","35731" } }
--# selene: allow(unused_variable) ---@diagnostic disable: unused-local -- A sub module to `hs.canvas` which provides support for basic matrix manipulations which can be used as the values for `transformation` attributes in the `hs.canvas` module. -- -- For mathematical reasons that are beyond the scope of this document, a 3x3 matrix can be used to represent a series of manipulations to be applied to the coordinates of a 2 dimensional drawing object. These manipulations can include one or more of a combination of translations, rotations, shearing and scaling. Within the 3x3 matrix, only 6 numbers are actually required, and this module represents them as the following keys in a Lua table: `m11`, `m12`, `m21`, `m22`, `tX`, and `tY`. For those of a mathematical bent, the 3x3 matrix used within this module can be visualized as follows: -- -- [ m11, m12, 0 ] -- [ m21, m22, 0 ] -- [ tX, tY, 1 ] -- -- This module allows you to generate the table which can represent one or more of the recognized transformations without having to understand the math behind the manipulations or specify the matrix values directly. -- -- Many of the methods defined in this module can be used both as constructors and as methods chained to a previous method or constructor. Chaining the methods in this manner allows you to combine multiple transformations into one combined table which can then be assigned to an element in your canvas. -- . -- -- For more information on the mathematics behind these, you can check the web. One site I used for reference (but there are many more which go into much more detail) can be found at http://www.cs.trinity.edu/~jhowland/cs2322/2d/2d/. ---@class hs.canvas.matrix local M = {} hs.canvas.matrix = M -- Appends the specified matrix transformations to the matrix and returns the new matrix. This method cannot be used as a constructor. -- -- Parameters: -- * `matrix` - the table to append to the current matrix. -- -- Returns: -- * the new matrix -- -- Notes: -- * Mathematically this method multiples the original matrix by the new one and returns the result of the multiplication. -- * You can use this method to "stack" additional transformations on top of existing transformations, without having to know what the existing transformations in effect for the canvas element are. function M:append(matrix, ...) end -- Specifies the identity matrix. Resets all existing transformations when applied as a method to an existing matrixObject. -- -- Parameters: -- * None -- -- Returns: -- * the identity matrix. -- -- Notes: -- * The identity matrix can be thought of as "apply no transformations at all" or "render as specified". -- * Mathematically this is represented as: -- ~~~ -- [ 1, 0, 0 ] -- [ 0, 1, 0 ] -- [ 0, 0, 1 ] -- ~~~ function M.identity() end -- Generates the mathematical inverse of the matrix. This method cannot be used as a constructor. -- -- Parameters: -- * None -- -- Returns: -- * the inverted matrix. -- -- Notes: -- * Inverting a matrix which represents a series of transformations has the effect of reversing or undoing the original transformations. -- * This is useful when used with [hs.canvas.matrix.append](#append) to undo a previously applied transformation without actually replacing all of the transformations which may have been applied to a canvas element. function M:invert() end -- Prepends the specified matrix transformations to the matrix and returns the new matrix. This method cannot be used as a constructor. -- -- Parameters: -- * `matrix` - the table to append to the current matrix. -- -- Returns: -- * the new matrix -- -- Notes: -- * Mathematically this method multiples the new matrix by the original one and returns the result of the multiplication. -- * You can use this method to apply a transformation *before* the currently applied transformations, without having to know what the existing transformations in effect for the canvas element are. function M:prepend(matrix, ...) end -- Applies a rotation of the specified number of degrees to the transformation matrix. This method can be used as a constructor or a method. -- -- Parameters: -- * `angle` - the number of degrees to rotate in a clockwise direction. -- -- Returns: -- * the new matrix -- -- Notes: -- * The rotation of an element this matrix is applied to will be rotated about the origin (zero point). To rotate an object about another point (its center for example), prepend a translation to the point to rotate about, and append a translation reversing the initial translation. -- * e.g. `hs.canvas.matrix.translate(x, y):rotate(angle):translate(-x, -y)` function M:rotate(angle, ...) end -- Applies a scaling transformation to the matrix. This method can be used as a constructor or a method. -- -- Parameters: -- * `xFactor` - the scaling factor to apply to the object in the horizontal orientation. -- * `yFactor` - an optional argument specifying a different scaling factor in the vertical orientation. If this argument is not provided, the `xFactor` argument will be used for both orientations. -- -- Returns: -- * the new matrix function M:scale(xFactor, yFactor, ...) end -- Applies a shearing transformation to the matrix. This method can be used as a constructor or a method. -- -- Parameters: -- * `xFactor` - the shearing factor to apply to the object in the horizontal orientation. -- * `yFactor` - an optional argument specifying a different shearing factor in the vertical orientation. If this argument is not provided, the `xFactor` argument will be used for both orientations. -- -- Returns: -- * the new matrix function M:shear(xFactor, yFactor, ...) end -- Applies a translation transformation to the matrix. This method can be used as a constructor or a method. -- -- Parameters: -- * `x` - the distance to translate the object in the horizontal direction. -- * `y` - the distance to translate the object in the vertical direction. -- -- Returns: -- * the new matrix function M:translate(x, y, ...) end
-- Collision boxes defined as box = {xleft, xright, yup, ydown} -- yup -- ------------------ -- - - -- xleft - - xright -- - - -- ------------------ -- ydown -- function getbox(boxobject) -- boxshift to help center the box on normal 8x8 sprites local boxshift = 2 local finalbox = { xright = boxobject.x + boxobject.box.xright + boxshift, xleft = boxobject.x - boxobject.box.xleft + boxshift, yup = boxobject.y - boxobject.box.yup + boxshift, ydown = boxobject.y + boxobject.box.ydown + boxshift } return finalbox end function iscollision(aobject, bobject) -- find our boxes local abox = getbox(aobject) local bbox = getbox(bobject) -- find if we are NOT colliding for ease and readability if abox.xleft > bbox.xright or bbox.xleft > abox.xright or abox.yup > bbox.ydown or bbox.yup > abox.ydown then return false end -- We are colliding return true end
rot = 0.0 vehicle = false effect = false function realisticDamage(attacker, weapon, bodypart) if (source==getLocalPlayer()) then -- Only AK47, M4 and Sniper can penetrate armor local armor = getPedArmor(source) if (weapon>0) and (attacker) then local armorType = getElementData(attacker, "armortype") local bulletType = getElementData(attacker, "bullettype") if (armor>0) and (armorType==1) and (bulletType~=1) and (weapon>0) then if ((weapon~=30) and (weapon~=31) and (weapon~=34)) and (bodypart~=9) then cancelEvent() end end end -- Damage effect local gasmask = getElementData(source, "gasmask") if not (effect) and ((not gasmask or gasmask==0) and (weapon==17)) then fadeCamera(false, 1.0, 255, 0, 0) effect = true setTimer(endEffect, 250, 1) end end end addEventHandler("onClientPlayerDamage", getLocalPlayer(), realisticDamage) function endEffect() fadeCamera(true, 1.0) effect = false end function playerDeath() deathTimer = 10 deathLabel = nil rot = 0.0 fadeCamera(false, 29) vehicle = isPedInVehicle(getLocalPlayer()) local pX, pY, pZ = getElementPosition(getLocalPlayer()) -- Setup the text setTimer(lowerTimer, 1000, 10) local screenwidth, screenheight = guiGetScreenSize () local width = 300 local height = 100 local x = (screenwidth - width)/2 local y = screenheight - (screenheight/8 - (height/8)) deathLabel = guiCreateLabel(x, y, width, height, "10 Seconds", false) guiSetFont(deathLabel, "sa-gothic") setGameSpeed(0.5) end addEventHandler("onClientPlayerWasted", getLocalPlayer(), playerDeath) function lowerTimer() deathTimer = deathTimer - 1 if (deathTimer>1) then guiSetText(deathLabel, tostring(deathTimer) .. " Seconds") else if (isElement(deathLabel)) then guiSetText(deathLabel, tostring(deathTimer) .. " Second") end end end deathTimer = 10 deathLabel = nil function playerRespawn() setGameSpeed(1) if (isElement(deathLabel)) then destroyElement(deathLabel) end setCameraTarget(getLocalPlayer()) end addEventHandler("onClientPlayerSpawn", getLocalPlayer(), playerRespawn) -- weapon fix for #131 function checkWeapons() local weapons = { } local removedWeapons, removedWeapons2 local count = 1 local gunlicense = tonumber(getElementData(getLocalPlayer(), "license.gun")) local team = getPlayerTeam(getLocalPlayer()) local factiontype = getElementData(team, "type") for i = 0, 12 do local weapon = getPedWeapon(getLocalPlayer(), i) local ammo = getPedTotalAmmo(getLocalPlayer(), i) if (weapon) and (ammo~=0) then -- takes away weapons if you do not have a gun license and aren't in a PD/fbi -- takes away mp5/sniper/m4/ak if you aren't in PD/fbi -- always takes away rocket launchers, flamethrowers and miniguns, knifes and katanas if (((weapon >= 16 and weapon <= 40 and gunlicense == 0) or weapon == 29 or weapon == 30 or weapon == 32 or weapon ==31 or weapon == 34) and factiontype ~= 2) or (weapon >= 35 and weapon <= 38) then if (removedWeapons==nil) then removedWeapons = getWeaponNameFromID(weapon) else removedWeapons = removedWeapons .. ", " .. getWeaponNameFromID(weapon) end weapons[count] = { } weapons[count][1] = weapon weapons[count][2] = ammo weapons[count][3] = 1 elseif weapon == 4 or weapon == 8 then if removedWeapons2 == nil then removedWeapons2 = getWeaponNameFromID(weapon) else removedWeapons2 = removedWeapons2 .. " and " .. getWeaponNameFromID(weapon) end else weapons[count] = { } weapons[count][1] = weapon weapons[count][2] = ammo weapons[count][3] = 0 end count = count + 1 end end triggerServerEvent("onDeathRemovePlayerWeapons", getLocalPlayer(), weapons, removedWeapons, removedWeapons2) end addEventHandler("onClientPlayerWasted", getLocalPlayer(), checkWeapons) -- local sx, sy = guiGetScreenSize() local start = 0 local fadeTime = 6000 addEvent("fadeCameraOnSpawn", true) addEventHandler("fadeCameraOnSpawn", getLocalPlayer(), function() start = getTickCount() end ) addEventHandler("onClientRender",getRootElement(), function() local currTime = getTickCount() - start if currTime < fadeTime then local height = ( sx / 2 ) * ( 1 - currTime / fadeTime ) local alpha = 255 * ( 1 - currTime / fadeTime ) dxDrawRectangle( 0, 0, sx, height, tocolor( 0, 0, 0, 255 ) ) dxDrawRectangle( 0, sy - height, sx, height, tocolor( 0, 0, 0, 255 ) ) dxDrawRectangle( 0, 0, sx, sy, tocolor( 0, 0, 0, alpha ) ) end end )
--穹顶煌刃 军需官 local m=14000353 local cm=_G["c"..m] cm.named_with_Skayarder=1 function cm.initial_effect(c) c:SetSPSummonOnce(m) --special summon proc local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(m,0)) e1:SetType(EFFECT_TYPE_FIELD) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetRange(LOCATION_HAND+LOCATION_DECK) e1:SetCondition(cm.spcon) e1:SetOperation(cm.spop) e1:SetValue(1) c:RegisterEffect(e1) --set local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(m,2)) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_SPSUMMON_SUCCESS) e2:SetRange(LOCATION_MZONE) e2:SetProperty(EFFECT_FLAG_DELAY) e2:SetCondition(cm.setcon) e2:SetTarget(cm.settg) e2:SetOperation(cm.setop) c:RegisterEffect(e2) --tohand local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(m,1)) e3:SetCategory(CATEGORY_TOHAND) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e3:SetCode(EVENT_RELEASE) e3:SetCountLimit(1,m) e3:SetTarget(cm.tg) e3:SetOperation(cm.op) c:RegisterEffect(e3) end function cm.Skay(c) local m=_G["c"..c:GetCode()] return m and m.named_with_Skayarder end function cm.spfilter1(c) return c:IsFaceup() and cm.Skay(c) and c:IsType(TYPE_MONSTER) and c:IsReleasable() end function cm.spfilter2(c) return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsAbleToGraveAsCost() end function cm.spcon(e,c) if c==nil then return true end local tp=c:GetControler() return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1 and Duel.IsExistingMatchingCard(cm.spfilter1,tp,LOCATION_MZONE,0,1,nil) and Duel.IsExistingMatchingCard(cm.spfilter2,tp,LOCATION_HAND,0,1,c) end function cm.spop(e,tp,eg,ep,ev,re,r,rp,c) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE) local g1=Duel.SelectMatchingCard(tp,cm.spfilter1,tp,LOCATION_MZONE,0,1,1,nil) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE) local g2=Duel.SelectMatchingCard(tp,cm.spfilter2,tp,LOCATION_HAND,0,1,1,c) Duel.Release(g1,REASON_COST) Duel.SendtoGrave(g2,REASON_COST) c:RegisterFlagEffect(m,RESET_EVENT+RESETS_STANDARD-RESET_TOFIELD,EFFECT_FLAG_CLIENT_HINT,1,0,aux.Stringid(m,0)) end function cm.cfilter(c,tp) return cm.Skay(c) and c:GetSummonPlayer()==tp end function cm.setcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return (c:GetSummonType()==SUMMON_TYPE_SPECIAL+1 or c:GetFlagEffect(m)~=0) and eg:IsExists(cm.cfilter,1,c,tp) end function cm.setfilter(c) return cm.Skay(c) and c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsSSetable() end function cm.settg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(cm.setfilter,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,nil) end end function cm.setop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET) local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(cm.setfilter),tp,LOCATION_DECK+LOCATION_GRAVE,0,1,1,nil) if g:GetCount()>0 then Duel.SSet(tp,g) Duel.ConfirmCards(1-tp,g) end end function cm.thfilter(c) return cm.Skay(c) and c:IsAbleToHand() end function cm.tg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(cm.thfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_GRAVE) end function cm.op(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,cm.thfilter,tp,LOCATION_GRAVE,0,1,1,nil) if g:GetCount()>0 then Duel.HintSelection(g) Duel.SendtoHand(g,nil,REASON_EFFECT) end end
local set1 = {10, 20, 30} local set2 = {20, 40, 50} local union = function(self, another) local set = {} local result = {} -- 利用数组确保集合互异性 for i, j in pairs(self) do set[j] = true end for i, j in pairs(another) do set[j] = true end -- 加入结果集合 for i, j in pairs(set) do table.insert(result, i) end return result end setmetatable(set1, {__add = union}) local set3 = set1 + set2 for _, j in pairs(set3) do io.write(j .. " ") end mytable = setmetatable({key1 = "value1"},{ __index = function(self, key) if key == "key2" then return "metatablevalue" end end }) print(mytable.key1, mytable.key2) arr = {1, 2, 3, 4} arr = setmetatable(arr, {__tostring = function(self) local result = '{' local sep = '' for _, i in pairs(self) do result = result .. sep .. i sep = ', ' end result = result .. '}' return result end }) print(arr) functor = {} function func1(self, arg) print("called from", arg) end setmetatable(functor, {__call = func1}) functor("functor") print(functor) object = setmetatable({}, {__metatable = "You cannot access here"}) print(getmetatable(object))
local Utils = require('golem.utils') local Entity = require('golem.entity') local Object = { RectTypes = { FILL = 'fill', LINE = 'line' } } -- Image object -- @param string source -- @param table props function Object:image(source, width, height, props) Utils:assertType(source, 'Image source', 'string') if props then Utils:assertType(props, 'Image Properties', 'table') end -- New entity instance for image. local entity = Entity:new(props) local image = love.graphics.newImage(source) if width then Utils:assertType(width, 'Image width', 'number') entity:setSize({ width = width, }) end if height then Utils:assertType(height, 'Image height', 'number') entity:setSize({ height = height, }) end -- Draw image. function entity:draw() local oldWidth, oldHeight = image:getDimensions() local newWidth = oldWidth local newHeight = oldHeight if entity.size.width > 0 then newWidth = entity.size.width end if entity.size.height > 0 then newHeight = entity.size.height end local scaleX = newWidth / oldWidth local scaleY = newHeight / oldHeight -- Draw image based on rotate, and scale love.graphics.draw( image, entity.position.x, entity.position.y, math.rad(entity.transform.rotate), scaleX, scaleY ) end -- Get image object. function entity:get() return image end return entity end -- Rectangle object -- @param number width -- @param number height -- @param string type -- @param table props function Object:rectangle(width, height, type, props) Utils:assertType(width, 'Rectangle width', 'number') Utils:assertType(height, 'Rectangle height', 'number') -- Initial props. local initialProps = { color = {255, 255, 255} } if props then Utils:assertType(props, 'Rectangle properties', 'table') Utils:extend(initialProps, props) end if type == nil then type = self.RectTypes.FILL end -- New entity instance for rectangle. local entity = Entity:new(initialProps) -- Draw rectangle. function entity:draw() love.graphics.setColor(entity.props.color) love.graphics.rectangle(type, entity.position.x, entity.position.y, width, height) end return entity end return Object
--[[ @description Arm all tracks within folders @author Ben Smith @link Author https://www.bensmithsound.uk Repository https://github.com/bsmith96/Reaper-Scripts @version 1.4 @changelog # Added user identifier to provided file names @metapackage @provides [main] . > bsmith96_Rec arm all tracks within folders.lua [main] . > bsmith96_Rec disarm tracks within folders.lua [main] . > bsmith96_Rec toggle tracks within folders.lua @about # Arm all tracks within folders Written by Ben Smith - 2021 ### Info * Automatically toggles record arming for all tracks, but ignores folders used for organising your session ]] -- ================================================== -- =============== GLOBAL VARIABLES =============== -- ================================================== -- get the script's name and directory local scriptName = ({reaper.get_action_context()})[2]:match("([^/\\_]+)%.lua$") local scriptDirectory = ({reaper.get_action_context()})[2]:sub(1, ({reaper.get_action_context()})[2]:find("\\[^\\]*$")) -- ============================================== -- =============== MAIN ROUTINE =============== -- ============================================== -- Count tracks in project trackCount = reaper.CountTracks(0) reaper.Undo_BeginBlock() -- Toggle record arm state of tracks if they don't contain other tracks for i = trackCount, 1, -1 do track = reaper.GetTrack(0, i-1) trackDepth = reaper.GetMediaTrackInfo_Value(track, "I_FOLDERDEPTH") if trackDepth <= 0.0 then if scriptName:find("toggle") then reaper.CSurf_OnRecArmChange(track, -1) elseif scriptName:find("disarm") then reaper.CSurf_OnRecArmChange(track, 0) elseif scriptName:find("arm") then reaper.CSurf_OnRecArmChange(track, 1) end end end reaper.Undo_EndBlock(scriptName, -1)
---获取角色 --@author sundream --@release 2018/12/25 10:30:00 --@usage --api: /api/account/role/get --protocol: http/https --method: post --params: -- type=table encode=json -- { -- sign [required] type=string help=签名 -- appid [required] type=string help=appid -- roleid [required] type=number help=角色ID -- } --return: -- type=table encode=json -- { -- code = [required] type=number help=返回码 -- message = [required] type=string help=返回码说明 -- data = { -- role = [optional] type=table help=存在则返回该角色 -- role格式见/api/account/role/add -- 另外返回的角色数据中还带有以下字段 -- roleid = 角色ID -- createtime = 创建时间 -- create_serverid = 创建所在服 -- now_serverid = 当前所在服 -- online = 是否在线 -- lv = 等级 -- gold = 金币 -- } -- } --example: -- curl -v 'http://127.0.0.1:8887/api/account/role/get' -d '{"sign":"debug","appid":"appid","roleid":1000000}' local Answer = require "answer" local util = require "server.account.util" local accountmgr = require "server.account.accountmgr" local servermgr = require "server.account.servermgr" local cjson = require "cjson" local handler = {} function handler.exec(args) local request,err = table.check(args,{ sign = {type="string"}, appid = {type="string"}, roleid = {type="number"}, }) if err then local response = Answer.response(Answer.code.PARAM_ERR) response.message = string.format("%s|%s",response.message,err) util.response_json(ngx.HTTP_OK,response) return end local appid = request.appid local roleid = request.roleid local app = util.get_app(appid) if not app then util.response_json(ngx.HTTP_OK,Answer.response(Answer.code.APPID_NOEXIST)) return end local secret = app.secret if not util.check_signature(args.sign,args,secret) then util.response_json(ngx.HTTP_OK,Answer.response(Answer.code.SIGN_ERR)) return end local role = accountmgr.getrole(appid,roleid) local response = Answer.response(Answer.code.OK) response.data = {role=role} util.response_json(ngx.HTTP_OK,response) return end function handler.post() ngx.req.read_body() local args = ngx.req.get_body_data() args = cjson.decode(args) handler.exec(args) end return handler
-- RESOURCES COLLECTOR TABLE -- RCL = {} -- Constructor -- function RCL.new(ent) -- Check the Entity -- if ent == nil then return end if ent.last_user == nil then return end -- Create the Table -- local t = {} t.meta = "RCL" t.ent = ent t.player = ent.last_user.name t.MF = getMF(t.player) t.entID = ent.unit_number t.dataNetwork = t.MF.dataNetwork t.resourcesTable = {} -- {ent, infinite?} t.selectedInv = -1 t.selectedDTK = -1 t.lightAnID = nil t.updateTick = 20 t.lastOreDNSend = 0 t.lastFluidDNSend = 0 t.lastUpdate = 0 t.lastScan = 0 t.consumption = 0 t.collectOres = true t.collectFluids = true t.outOfQuatron = false t.inventoryFull = false t.energyCharge = 0 t.energyLevel = 1 t.energyBuffer = _mfRCLMaxCharge -- Get the Inventory -- t.chest = t.ent.get_inventory(defines.inventory.chest) -- Create the Tank -- t.tank = ent.surface.create_entity{name="ResourcesCollectorTank", position=ent.position, force=ent.force} -- Save the Object inside the Tables -- global.objectsTable[ent.unit_number] = t table.insert(global.ResourceCollectorTable, t) -- Scan all Resources around -- RCL.scanResources(t, ent) return t end -- Destructor -- function RCL.remove(obj) -- Destroy the Animation -- rendering.destroy(obj.lightAnID or 0) -- Destroy the Tank -- if obj.tank ~= nil and obj.tank.valid == true then obj.tank.destroy() end -- Remove from the Network Access Point -- if obj.networkAccessPoint ~= nil and obj.ent ~= nil and obj.ent.valid == true then obj.networkAccessPoint.objTable[obj.ent.unit_number] = nil end -- Remove from the Objects the Tables -- global.objectsTable[obj.entID] = nil for k, rcl in pairs(global.ResourceCollectorTable) do if rcl == obj then table.remove(global.ResourceCollectorTable, k) end end end -- Is valid -- function RCL.valid(obj) if obj.ent ~= nil and obj.ent.valid then return true end return false end -- Copy Settings -- function RCL.copySettings(obj1, obj2) obj1.selectedInv = obj2.selectedInv end -- Item Tags to Content -- function RCL.itemTagsToContent(obj, tags) obj.energyCharge = tags.charge or 0 obj.energyLevel = tags.purity or 1 end -- Content to Item Tags -- function RCL.contentToItemTags(obj, tags) if EI.energy(obj) > 0 then tags.set_tag("Infos", {charge=EI.energy(obj), purity=EI.energyLevel(obj)}) tags.custom_description = {"", tags.prototype.localised_description, {"item-description.ResourcesCollectorC", math.floor(EI.energy(obj)), string.format("%.3f", EI.energyLevel(obj))}} end end -- Settings To Blueprint Tags -- function RCL.settingsToBlueprintTags(obj) local tags = {} if type(obj.selectedInv) == "table" then tags["SelectedInv"] = obj.selectedInv.ID else tags["SelectedInv"] = obj.selectedInv or -3 end return tags end -- Blueprint Tags To Settings -- function RCL.blueprintTagsToSettings(obj, tags) obj.selectedInv = tags["SelectedInv"] if obj.selectedInv == -3 then obj.selectedInv = nil end if obj.selectedInv > 0 then for _, deepStorage in pairs(obj.dataNetwork.DSRTable) do if valid(deepStorage) == true then if obj.selectedInv == deepStorage.ID then obj.selectedInv = deepStorage end end end end end -- Tooltip Infos -- function RCL.getTooltipInfos(obj, GUITable, mainFrame, justCreated) -- Create the Data Network Frame -- DN.addDataNetworkFrame(GUITable, mainFrame, obj, justCreated) if justCreated == true then -- Set the GUI Title -- GUITable.vars.GUITitle.caption = {"gui-description.ResourcesCollector"} -- Set the Main Frame Height -- mainFrame.style.height = 350 -- Create the Information Frame -- local informationFrame = GAPI.addFrame(GUITable, "InformationFrame", mainFrame, "vertical", true) informationFrame.style = "MFFrame1" informationFrame.style.vertically_stretchable = true informationFrame.style.left_padding = 3 informationFrame.style.right_padding = 3 informationFrame.style.left_margin = 3 informationFrame.style.right_margin = 3 -- informationFrame.style.minimal_width = 200 -- Add the Title -- GAPI.addSubtitle(GUITable, "", informationFrame, {"gui-description.Information"}) -- Create the Information Table -- GAPI.addTable(GUITable, "InformationTable", informationFrame, 1, true) -- Create the Inventory Frame -- local inventoryFrame = GAPI.addFrame(GUITable, "InventoryFrame", mainFrame, "vertical", true) inventoryFrame.style = "MFFrame1" inventoryFrame.style.vertically_stretchable = true inventoryFrame.style.left_padding = 3 inventoryFrame.style.right_padding = 3 inventoryFrame.style.left_margin = 3 inventoryFrame.style.right_margin = 3 -- Add the Title -- GAPI.addSubtitle(GUITable, "", inventoryFrame, {"gui-description.Inventory"}) -- Create the Inventory Flow and Button -- local inventoryFlow = GAPI.addFlow(GUITable, "", inventoryFrame, "horizontal") inventoryFlow.style.horizontal_align = "center" inventoryFlow.style.bottom_margin = 15 GAPI.addSimpleButton(GUITable, "R.C.L.OpenInvButton", inventoryFlow, {"gui-description.OpenInventory"}, "", false, {ID=obj.entID}) -- Create the Inventory Table -- GAPI.addTable(GUITable, "InventoryTable", inventoryFrame, 1, true) -- Create the Settings Frame -- local settingsFrame = GAPI.addFrame(GUITable, "SettingsFrame", mainFrame, "vertical", true) settingsFrame.style = "MFFrame1" settingsFrame.style.vertically_stretchable = true settingsFrame.style.left_padding = 3 settingsFrame.style.right_padding = 3 settingsFrame.style.left_margin = 3 settingsFrame.style.right_margin = 3 -- Add the Title -- GAPI.addSubtitle(GUITable, "", settingsFrame, {"gui-description.Settings"}) ------------------------------------------------------ COLLECT SETTINGS ------------------------------------------------------ -- Add the Collect Ores Flow -- local collectOresFlow = GAPI.addFlow(GUITable, "", settingsFrame, "horizontal") -- Add the Collect Ores Label -- GAPI.addLabel(GUITable, "", collectOresFlow, {"gui-description.RCLCollectOres"}, nil, "", false, nil, _mfLabelType.yellowTitle) -- Add the Collect Ores Switch -- local state = obj.collectOres == true and "right" or "left" GAPI.addSwitch(GUITable, "R.C.L.CollectOres", collectOresFlow, {"gui-description.No"}, {"gui-description.Yes"}, nil, nil, state, false, {ID=obj.ent.unit_number}) -- Add the Collect Fluids Flow -- local collectFluidFlow = GAPI.addFlow(GUITable, "", settingsFrame, "horizontal") -- Add the Collect Fluids Label -- GAPI.addLabel(GUITable, "", collectFluidFlow, {"gui-description.RCLCollectFluids"}, nil, "", false, nil, _mfLabelType.yellowTitle) -- Add the Collect Fluid Switch -- state = obj.collectFluids == true and "right" or "left" GAPI.addSwitch(GUITable, "R.C.L.CollectFluids", collectFluidFlow, {"gui-description.No"}, {"gui-description.Yes"}, nil, nil, state, false, {ID=obj.ent.unit_number}) ------------------------------------------------------ DEEP STORAGE SELECTION ------------------------------------------------------ -- Create the Select Storage Label -- GAPI.addLabel(GUITable, "", settingsFrame, {"gui-description.RCLTargetedOresStorage"}, nil, "", false, nil, _mfLabelType.yellowTitle) -- Create the Storage List -- local invs = {{"gui-description.None"}, {"gui-description.Auto"}, {"gui-description.DataNetwork"}} local selectedIndex = 1 -- Change the selected Index -- if obj.selectedInv == -1 then selectedIndex = 2 elseif obj.selectedInv == -2 then selectedIndex = 3 end -- List all Deep Storages -- local i = 3 for _, deepStorage in pairs(obj.dataNetwork.DSRTable) do -- Check the Deep Storage -- if deepStorage ~= nil and deepStorage.ent ~= nil then i = i + 1 -- Check the Deep Storage Item/Filter -- local item = nil if deepStorage.inventoryItem ~= nil then item = deepStorage.inventoryItem elseif deepStorage.filter ~= nil then item = deepStorage.filter end -- Create the Name -- if item ~= nil then table.insert(invs, {"", "[img=item/"..item.."] ", game.item_prototypes[item].localised_name, " - ", deepStorage.ID}) else table.insert(invs, {"", "", {"gui-description.Empty"}, " - ", deepStorage.ID}) end -- Check if the Deep Storage is selected -- if type(obj.selectedInv) == "table" and obj.selectedInv.entID ~= nil then if obj.selectedInv.entID == deepStorage.entID then selectedIndex = i end end end end -- Check the selected Index -- if selectedIndex ~= nil and selectedIndex > table_size(invs) then selectedIndex = nil end -- Add the Selected Deep Tank Drop Down -- GAPI.addDropDown(GUITable, "R.C.L.TargetDSR", settingsFrame, invs, selectedIndex, false, {"gui-description.RCLOresInventorySelectTT"}, {ID=obj.ent.unit_number}) ------------------------------------------------------ DEEP TANK SELECTION ------------------------------------------------------ -- Create the Select Storage Label -- GAPI.addLabel(GUITable, "", settingsFrame, {"gui-description.RCLTargetedFluidStorage"}, nil, "", false, nil, _mfLabelType.yellowTitle) -- Create the Storage List -- invs = {{"gui-description.None"}, {"gui-description.Auto"}} selectedIndex = 1 -- Change the selected Index -- if obj.selectedDTK == -1 then selectedIndex = 2 elseif obj.selectedDTK == -2 then selectedIndex = 3 end -- List all Deep Storages -- i = 2 for _, deepTank in pairs(obj.dataNetwork.DTKTable) do -- Check the Deep Storage -- if deepTank ~= nil and deepTank.ent ~= nil then i = i + 1 -- Check the Deep Storage Fluid/Filter -- local fluid = nil if deepTank.inventoryFluid ~= nil then fluid = deepTank.inventoryFluid elseif deepTank.filter ~= nil then fluid = deepTank.filter end -- Create the Name -- if fluid ~= nil then table.insert(invs, {"", "[img=fluid/"..fluid.."] ", game.fluid_prototypes[fluid].localised_name, " - ", deepTank.ID}) else table.insert(invs, {"", "", {"gui-description.Empty"}, " - ", deepTank.ID}) end -- Check if the Deep Tank is selected -- if type(obj.selectedDTK) == "table" and obj.selectedDTK.entID ~= nil then if obj.selectedDTK.entID == deepTank.entID then selectedIndex = i end end end end -- Check the selected Index -- if selectedIndex ~= nil and selectedIndex > table_size(invs) then selectedIndex = nil end -- Add the Selected Deep Tank Drop Down -- GAPI.addDropDown(GUITable, "R.C.L.TargetDTK", settingsFrame, invs, selectedIndex, false, {"gui-description.RCLFluidInventorySelectTT"}, {ID=obj.ent.unit_number}) end -- Get the Information Table -- local informationTable = GUITable.vars.InformationTable -- Clear Information the Table -- informationTable.clear() -- Add the Quatron Charge -- GAPI.addLabel(GUITable, "", informationTable, {"gui-description.QuatronCharge", Util.toRNumber(EI.energy(obj)) }, _mfOrange) GAPI.addProgressBar(GUITable, "", informationTable, "", EI.energy(obj) .. "/" .. EI.maxEnergy(obj), false, _mfPurple, EI.energy(obj)/EI.maxEnergy(obj), 100) -- Create the Quatron Purity -- GAPI.addLabel(GUITable, "", informationTable, {"gui-description.Quatronlevel", string.format("%.3f", EI.energyLevel(obj))}, _mfOrange) GAPI.addProgressBar(GUITable, "", informationTable, "", "", false, _mfPurple, EI.energyLevel(obj)/20, 100) -- Create the Speed -- local speed = math.floor((math.pow(EI.energyLevel(obj), _mfQuatronScalePower) + _mfOreCleanerResourcesPerExtraction) * EI.energyLevel(obj) * 3) local speedLabel = GAPI.addLabel(GUITable, "", informationTable, {"gui-description.RCLSpeed", speed}, _mfOrange) speedLabel.style.top_margin = 10 -- Create the Resource Label -- GAPI.addLabel(GUITable, "", informationTable, {"", {"gui-description.RCLPathsCount"}, " [color=yellow]", table_size(obj.resourcesTable), "[/color]"}, _mfOrange) -- Create the Mobile Factory Too Far Label -- if obj.outOfQuatron == true then GAPI.addLabel(GUITable, "", informationTable, {"gui-description.OutOfQuatron"}, _mfRed) end -- Create the Mobile Factory Too Far Label -- if obj.inventoryFull == true then GAPI.addLabel(GUITable, "", informationTable, {"gui-description.InventoryFull"}, _mfRed) end -- Get the Inventory Table -- local inventoryTable = GUITable.vars.InventoryTable -- Clear Inventory the Table -- inventoryTable.clear() -- Get all Fluids Name -- local fluidsName1 = nil local fluidsName2 = nil local fluidsName3 = nil local fluidsName4 = nil -- Get all Fluids amount -- local fluidsAmount1 = 0 local fluidsAmount2 = 0 local fluidsAmount3 = 0 local fluidsAmount4 = 0 -- Get all Fluids Color -- local fluidsColor1 = nil local fluidsColor2 = nil local fluidsColor3 = nil local fluidsColor4 = nil -- Get the Fluids Tooltips -- local fluidsTT1 = {"gui-description.Empty"} local fluidsTT2 = {"gui-description.Empty"} local fluidsTT3 = {"gui-description.Empty"} local fluidsTT4 = {"gui-description.Empty"} -- Get the Fluid 1 -- if obj.tank ~= nil and obj.tank.fluidbox[1] ~= nil then fluidsName1 = obj.tank.fluidbox[1].name fluidsAmount1 = obj.tank.fluidbox[1].amount fluidsColor1 = game.fluid_prototypes[fluidsName1].base_color fluidsTT1 = {"", Util.getLocFluidName(fluidsName1), ": ", fluidsAmount1, "/", _mfRCLTankSize} end -- Get the Fluid 2 -- if obj.tank ~= nil and obj.tank.fluidbox[2] ~= nil then fluidsName2 = obj.tank.fluidbox[2].name fluidsAmount2 = obj.tank.fluidbox[2].amount fluidsColor2 = game.fluid_prototypes[fluidsName2].base_color fluidsTT2 = {"", Util.getLocFluidName(fluidsName2), ": ", fluidsAmount2, "/", _mfRCLTankSize} end -- Get the Fluid 3 -- if obj.tank ~= nil and obj.tank.fluidbox[3] ~= nil then fluidsName3 = obj.tank.fluidbox[3].name fluidsAmount3 = obj.tank.fluidbox[3].amount fluidsColor3 = game.fluid_prototypes[fluidsName3].base_color fluidsTT3 = {"", Util.getLocFluidName(fluidsName3), ": ", fluidsAmount3, "/", _mfRCLTankSize} end -- Get the Fluid 4 -- if obj.tank ~= nil and obj.tank.fluidbox[4] ~= nil then fluidsName4 = obj.tank.fluidbox[4].name fluidsAmount4 = obj.tank.fluidbox[4].amount fluidsColor4 = game.fluid_prototypes[fluidsName4].base_color fluidsTT4 = {"", Util.getLocFluidName(fluidsName4), ": ", fluidsAmount4, "/", _mfRCLTankSize} end -- Create the Tank 1 Progress Bar -- GAPI.addLabel(GUITable, "", inventoryTable, {"gui-description.RCLTank1", Util.getLocFluidName(fluidsName1) or {"gui-description.Empty"}}, _mfOrange) GAPI.addProgressBar(GUITable, "", inventoryTable, nil, fluidsTT1, false, fluidsColor1, fluidsAmount1/_mfRCLTankSize, nil) -- Create the Tank 2 Progress Bar -- GAPI.addLabel(GUITable, "", inventoryTable, {"gui-description.RCLTank2", Util.getLocFluidName(fluidsName2) or {"gui-description.Empty"}}, _mfOrange) GAPI.addProgressBar(GUITable, "", inventoryTable, nil, fluidsTT2, false, fluidsColor2, fluidsAmount2/_mfRCLTankSize, nil) -- Create the Tank 3 Progress Bar -- GAPI.addLabel(GUITable, "", inventoryTable, {"gui-description.RCLTank3", Util.getLocFluidName(fluidsName3) or {"gui-description.Empty"}}, _mfOrange) GAPI.addProgressBar(GUITable, "", inventoryTable, nil, fluidsTT3, false, fluidsColor3, fluidsAmount3/_mfRCLTankSize, nil) -- Create the Tank 4 Progress Bar -- GAPI.addLabel(GUITable, "", inventoryTable, {"gui-description.RCLTank4", Util.getLocFluidName(fluidsName4) or {"gui-description.Empty"}}, _mfOrange) GAPI.addProgressBar(GUITable, "", inventoryTable, nil, fluidsTT4, false, fluidsColor4, fluidsAmount4/_mfRCLTankSize, nil) end -- Update -- function RCL.update(obj) -- Set the lastUpdate variable -- obj.lastUpdate = game.tick -- Check the Validity -- if RCL.valid(obj) == false then RCL.remove(obj) return end -- Try to get Quatron from the Network Access Point -- if EI.energy(obj) <= 100 and obj.networkAccessPoint ~= nil then local chargeToBorrow = math.min(EI.energy(obj.networkAccessPoint), EI.maxEnergy(obj) - EI.energy(obj)) if chargeToBorrow > 0 then local added = RCL.addQuatron(obj, chargeToBorrow, EI.energyLevel(obj.networkAccessPoint)) EI.removeEnergy(obj.networkAccessPoint, added) obj.outOfQuatron = false end end -- Collect Resources -- RCL.collectResources(obj) -- Try to find a Network Access Point if needed -- if valid(obj.networkAccessPoint) == false or obj.dataNetwork ~= obj.networkAccessPoint.dataNetwork then obj.networkAccessPoint = obj.dataNetwork:getCloserNAP(obj) if obj.networkAccessPoint ~= nil then obj.networkAccessPoint.objTable[obj.ent.unit_number] = obj end end -- Send the Ores to the Data Network -- if game.tick - obj.lastOreDNSend > 79 then obj.lastOreDNSend = game.tick RCL.sendOreToDN(obj) end -- Send the Fluids to the Data Network -- if game.tick - obj.lastFluidDNSend > 59 then obj.lastFluidDNSend = game.tick RCL.sendFluidToDN(obj) end -- Scan Resources around -- if game.tick - obj.lastScan > 200 and table_size(obj.resourcesTable) < math.floor(EI.energyLevel(obj)) then obj.lastScan = game.tick RCL.scanResources(obj, obj.ent) end -- Draw the Animation -- if obj.inventoryFull == true or obj.outOfQuatron == true then rendering.destroy(obj.lightAnID or 0) obj.lightAnID = nil elseif obj.lightAnID == nil or rendering.is_valid(obj.lightAnID) == false then obj.lightAnID = rendering.draw_animation{animation="ResourcesCollectorAn", target=obj.ent.position, surface=obj.ent.surface, render_layer=144, animation_speed=0.3} end end -- Scan surronding Ores -- function RCL.scanResources(obj, entity) -- Return if there are not Quatron Charge remaining -- if EI.energy(obj) < 3 then obj.outOfQuatron = true return else obj.outOfQuatron = false end -- Clean the Resources Table -- obj.resourcesTable = {} -- Test if the Entity is valid -- if entity == nil or entity.valid == false then return end -- Test if the Surface is valid -- if entity.surface == nil then return end -- Calculate the Radius -- local area = {{entity.position.x-_mfRCLRadius,entity.position.y-_mfRCLRadius},{entity.position.x+_mfRCLRadius,entity.position.y+_mfRCLRadius}} -- Check what have to be collected -- if obj.collectOres == true and obj.collectFluids == true then -- Collect every Resources -- obj.resourcesTable = entity.surface.find_entities_filtered{area=area, type="resource", limit=EI.energyLevel(obj)} elseif obj.collectOres == true and obj.collectFluids == false then -- Collect Ores Only -- obj.resourcesTable = entity.surface.find_entities_filtered{area=area, type="resource", name=global.oresTable, limit=EI.energyLevel(obj)} elseif obj.collectOres == false and obj.collectFluids == true then -- Collect Fluids Only -- obj.resourcesTable = entity.surface.find_entities_filtered{area=area, type="resource", name=global.fluidsTable, limit=EI.energyLevel(obj)} end end -- Collect surrounding Resources -- function RCL.collectResources(obj) -- Get the Energy Level -- local quatron = EI.energy(obj) -- Calcule the amount of Resources to extract -- local toExtract = math.floor(math.pow(EI.energyLevel(obj), _mfQuatronScalePower) + _mfOreCleanerResourcesPerExtraction) -- Get the Inventory -- local inv = obj.chest -- Do the job for all Resources inside the Table -- for _, resourcesPath in pairs(obj.resourcesTable) do -- Stop if we are out of Quatron -- if quatron < 3 then obj.outOfQuatron = true break else obj.outOfQuatron = false end -- Check the Path -- if resourcesPath == nil or resourcesPath.valid == false then for k, op in pairs(obj.resourcesTable) do if op == resourcesPath then table.remove(obj.resourcesTable, k) end end goto continue end -- Calculate the amout of Resources that will be extracted -- local resourcesExtracted = math.min(toExtract, resourcesPath.amount) -- Itinerate all Products -- local added = 0 local isFluid = false for _, product in pairs(global.ResourcesProductsTable[resourcesPath.name]) do -- Calculate how many products can be extracted -- local amount = product.amount or math.random(product.min, product.max) local inserted = 0 -- If this is an Item -- if product.type == "item" and obj.collectOres == true and math.random(0, 100) <= product.probability*100 then -- Insert the Product inside the Inventory -- inserted = inv.insert({name=product.name, count=amount*resourcesExtracted}) -- If this is a Fluid -- elseif product.type == "fluid" and obj.collectFluids == true and math.random(0, 100) <= product.probability*100 then -- Insert the Fluid inside the Tank -- if obj.tank ~= nil then inserted = obj.tank.insert_fluid({name=product.name, amount=(amount*resourcesExtracted)/10}) isFluid = true end end -- Check if something was inserted -- if inserted > 0 then -- Register the amount inserted if this is the main Product -- added = math.max(inserted, added) -- Create the Projectile -- obj.ent.surface.create_entity{name="RCLProjectile:" .. product.name, position=resourcesPath.position, target=obj.ent, speed=0.1, max_range=999, force=obj.ent.force} obj.inventoryFull = false else obj.inventoryFull = true end end -- Check if something was extrated -- if added <= 0 then goto continue end -- Increase the number of Extractions -- quatron = quatron - 3 -- Remove Resources from the Resources Path -- if resourcesPath.prototype.infinite_resource ~= true or isFluid == true then resourcesPath.amount = math.max(resourcesPath.amount - added, 1) end -- Remove the Resource Path if it is empty -- if resourcesPath.amount <= 1 then resourcesPath.deplete() for k, op in pairs(obj.resourcesTable) do if op == resourcesPath then table.remove(obj.resourcesTable, k) end end end ::continue:: end -- Remove a Quatron Charge -- EI.setEnergy(obj, quatron) end -- Send the Ore Inside to the Data Network -- function RCL.sendOreToDN(obj) -- Stop if the selected Inventory is None -- if obj.selectedInv == nil then return end -- Get the Inventory -- local inv = obj.chest -- Check if the Mobile Factory is close -- local MFTooFar = true if obj.MF.ent ~= nil and obj.MF.ent.valid == true and obj.ent.surface == obj.MF.ent.surface and Util.distance(obj.ent.position, obj.MF.ent.position) <= _mfOreCleanerMaxDistance then MFTooFar = false end -- Get the Ore Cleaner Target -- local target = nil if MFTooFar == false then target = obj.MF.ent end if MFTooFar == false and valid(obj.networkAccessPoint) and EI.energy(obj.networkAccessPoint) > 0 and Util.distance(obj.ent.position, obj.MF.ent.position) > Util.distance(obj.ent.position, obj.networkAccessPoint.ent.position) then target = obj.networkAccessPoint.ent end if MFTooFar == true and valid(obj.networkAccessPoint) and EI.energy(obj.networkAccessPoint) > 0 then target = obj.networkAccessPoint.ent end -- Check the Target -- if target == nil then return end -- If the Selected Inventory is a Deep Storage -- if valid(obj.selectedInv) == true then -- Get the Deep Storage -- local dsr = obj.selectedInv -- Get the Deep Storage Item or Filter -- local itemName = dsr.inventoryItem or dsr.filter -- Check the Name -- if itemName == nil then return end -- Check if the Resource Collector Inventory has this item -- local itemCount = inv.get_item_count(itemName) -- Try to send the Item count to the Deep Storage -- local inserted = dsr:addItem(itemName, math.min(itemCount, dsr:availableSpace())) -- Remove the Items from the Inventory -- if inserted > 0 then inv.remove({name=itemName, count=inserted}) -- Create the Projectile -- RCL.createOreBeam(obj, itemName, target) end end -- If the Selected Inventory is Auto -- if obj.selectedInv == -1 then -- Get all Items inside the Resource Collector Inventory -- for item, count in pairs(inv.get_contents()) do -- Check all Deep Storages -- for _, dsr in pairs(obj.dataNetwork.DSRTable) do -- Try to send the Items to the Deep Storage -- local inserted = dsr:addItem(item, math.min(count, dsr:availableSpace())) -- Remove the Items from the Inventory -- if inserted > 0 then inv.remove({name=item, count=inserted}) -- Create the Projectile -- RCL.createOreBeam(obj, item, target) end -- Decrease the count -- count = count - inserted end end end -- If the Selected Inventory is Data Network -- if obj.selectedInv == -2 then -- Get all Items inside the Ore Cleaner Inventory -- for item, count in pairs(inv.get_contents()) do -- Check all Deep Storages -- for _, dsr in pairs(obj.dataNetwork.DSRTable) do -- Try to send the Items to the Deep Storage -- local inserted = dsr:addItem(item, math.min(count, dsr:availableSpace())) -- Remove the Items from the Inventory -- if inserted > 0 then inv.remove({name=item, count=inserted}) -- Create the Projectile -- RCL.createOreBeam(obj, item, target) end -- Decrease the count -- count = count - inserted end -- Send to the Data Network if there are still Items left -- if count > 0 then local inserted = obj.dataNetwork:addItems(item, count) -- Remove the Items from the Inventory -- if inserted > 0 then inv.remove({name=item, count=inserted}) -- Create the Projectile -- RCL.createOreBeam(obj, item, target) end -- Decrease the count -- count = count - inserted end end end end function RCL.sendFluidToDN(obj) -- Check the Tank -- if obj.tank == nil or obj.tank.valid == false then return end -- Stop if the selected Deep Tank is none -- if obj.selectedDTK == nil then return end -- Check if the Mobile Factory is close -- local MFTooFar = true if obj.MF.ent ~= nil and obj.MF.ent.valid == true and obj.ent.surface == obj.MF.ent.surface and Util.distance(obj.ent.position, obj.MF.ent.position) <= _mfOreCleanerMaxDistance then MFTooFar = false end -- Get the Ore Cleaner Target -- local target = nil if MFTooFar == false then target = obj.MF.ent end if MFTooFar == false and valid(obj.networkAccessPoint) and EI.energy(obj.networkAccessPoint) > 0 and Util.distance(obj.ent.position, obj.MF.ent.position) > Util.distance(obj.ent.position, obj.networkAccessPoint.ent.position) then target = obj.networkAccessPoint.ent end if MFTooFar == true and valid(obj.networkAccessPoint) and EI.energy(obj.networkAccessPoint) > 0 then target = obj.networkAccessPoint.ent end -- Check the Target -- if target == nil then return end -- If the Selected Inventory is a Deep Tank -- if valid(obj.selectedDTK) == true then -- Get the Deep Tank -- local dtk = obj.selectedDTK -- Get the Deep Tank Fluid or Filter -- local fluidName = dtk.inventoryFluid or dtk.filter -- Check the name -- if fluidName == nil then return end -- Check if the Resource Collector Tank has this Fluid -- local fluidCount = obj.tank.get_fluid_count(fluidName) -- Try to send the Fluid count to the Deep Tank -- local inserted = dtk:addFluid{name=fluidName, amount=math.min(fluidCount, dtk:availableSpace())} -- Remove the Items from the Inventory -- if inserted > 0 then obj.tank.remove_fluid{name=fluidName, amount=inserted} -- Create the Projectile -- RCL.createOreBeam(obj, fluidName, target) end end -- If the Selected Inventory is Auto -- if obj.selectedInv == -1 then -- Get all Fluids inside the Resource Collector Tank -- for fluid, count in pairs(obj.tank.get_fluid_contents()) do -- Check all Deep Tank -- for _, dtk in pairs(obj.dataNetwork.DTKTable) do -- Try to send the Fluids to the Deep Storage -- local inserted = dtk:addFluid{name=fluid, amount=math.min(count, dtk:availableSpace())} -- Remove the Fluids from the Inventory -- if inserted > 0 then obj.tank.remove_fluid{name=fluid, amount=inserted} -- Create the Projectile -- RCL.createOreBeam(obj, fluid, target) end -- Decrease the count -- count = count - inserted end end end end -- Called if the Player interacted with the GUI -- function RCL.interaction(event, MFPlayer) -- Open Inventory -- if string.match(event.element.name, "R.C.L.OpenInvButton") then -- Get the Object -- local objId = event.element.tags.ID local ent = global.objectsTable[objId].ent if ent ~= nil and ent.valid == true then MFPlayer.ent.opened = ent end return end -- Select Data Network -- if string.match(event.element.name, "R.C.L.DNSelect") then local objId = event.element.tags.ID local obj = global.objectsTable[objId] if obj == nil then return end -- Get the Mobile Factory -- local selectedMF = getMF(event.element.items[event.element.selected_index]) if selectedMF == nil then return end -- Set the New Data Network -- obj.dataNetwork = selectedMF.dataNetwork -- Remove the Selected Inventory -- obj.selectedInv = nil return end -- Collect Ores -- if string.match(event.element.name, "R.C.L.CollectOres") then local objId = event.element.tags.ID local obj = global.objectsTable[objId] if obj == nil then return end -- Change the Collect Ores Setting -- local state = event.element.switch_state == "right" and true or false obj.collectOres = state RCL.scanResources(obj, obj.ent) end -- Collect Fluids -- if string.match(event.element.name, "R.C.L.CollectFluids") then local objId = event.element.tags.ID local obj = global.objectsTable[objId] if obj == nil then return end -- Change the Collect Fludis Setting -- local state = event.element.switch_state == "right" and true or false obj.collectFluids = state RCL.scanResources(obj, obj.ent) end -- Select Deep Storage -- if string.match(event.element.name, "R.C.L.TargetDSR") then local objId = event.element.tags.ID local obj = global.objectsTable[objId] if obj == nil then return end -- Change the Ore Cleaner targeted Deep Storage -- RCL.changeDSR(obj, event.element) end -- Select Deep Tank -- if string.match(event.element.name, "R.C.L.TargetDTK") then local objId = event.element.tags.ID local obj = global.objectsTable[objId] if obj == nil then return end -- Change the Ore Cleaner targeted Deep Storage -- RCL.changeDTK(obj, event.element) end end -- Change the Targeted Deep Storage -- function RCL.changeDSR(obj, element) -- If None is selected -- if element.selected_index == 1 then obj.selectedInv = nil return end -- If Auto is selected -- if element.selected_index == 2 then obj.selectedInv = -1 return end -- If Data Network is selected -- if element.selected_index == 3 then obj.selectedInv = -2 return end -- Get the Deep Storage ID -- local ID = tonumber(element.items[element.selected_index][5]) -- Check the ID -- if ID == nil then obj.selectedInv = nil return end -- Select the Inventory -- obj.selectedInv = nil for _, deepStorage in pairs(obj.dataNetwork.DSRTable) do if valid(deepStorage) == true then if ID == deepStorage.ID then obj.selectedInv = deepStorage end end end end -- Change the Targeted Deep Tank -- function RCL.changeDTK(obj, element) -- If None is selected -- if element.selected_index == 1 then obj.selectedDTK = nil return end -- If Auto is selected -- if element.selected_index == 2 then obj.selectedDTK = -1 return end -- Get the Deep Tank ID -- local ID = tonumber(element.items[element.selected_index][5]) -- Check the ID -- if ID == nil then obj.selectedDTK = nil return end -- Select the Inventory -- obj.selectedDTK = nil for _, deepTank in pairs(obj.dataNetwork.DTKTable) do if valid(deepTank) == true then if ID == deepTank.ID then obj.selectedDTK = deepTank end end end end function RCL.createOreBeam(obj, itemName, target) local positionX = obj.ent.position.x + (math.random(-200, 200)/100) local positionY = obj.ent.position.y + (math.random(-200, 200)/100) obj.ent.surface.create_entity{name="RCLProjectile:" .. itemName, position={positionX,positionY}, target=target, speed=0.25, max_range=999, force=obj.ent.force} end -- Add Quatron (Return the amount added) -- function RCL.addQuatron(obj, amount, level) if EI.energy(obj) > 0 then EI.mixQuatron(obj, amount, level) else obj.energyCharge = amount obj.energyLevel = level end return amount end
require("sources/patterns/observer") ScreenWidth = 1920 ScreenHeigth = 1080 Enemy = {} Enemy.__index = Enemy setmetatable(Enemy, Observer) function Enemy:new(size, speed, player_pos, asteroid, x, y) local enemy = {} setmetatable(enemy, Enemy) local half = size / 2 if x == nil or y == nil then local pos = Chose({x = love.math.random(0 - half, ScreenWidth + half), y = Chose(0 - half, ScreenHeigth + half)}, {x = Chose(0 - half, ScreenWidth + half), y = love.math.random(0 - half, ScreenHeigth + half)}) enemy.x = pos.x enemy.y = pos.y else enemy.x = x enemy.y = y end local speeds = Trajectory({x = enemy.x, y = enemy.y}, player_pos, speed) enemy.xspeed = speeds.x enemy.yspeed = speeds.y enemy.size = size enemy.half = half enemy.asteroid = asteroid enemy.rotation = love.math.random(0, 359) enemy.rspeed = speed/50 return enemy end function Enemy:update(dt) self.x = self.x + self.xspeed * dt self.y = self.y + self.yspeed * dt if self.rotation ~= 360 then self.rotation = self.rotation + self.rspeed * dt else self.rotation = 0 end end function Enemy:draw() love.graphics.draw(self.asteroid, self.x, self.y, math.rad(self.rotation), 1, 1, self.half, self.half) -- love.graphics.print(tostring(self), self.x - self.size, self.y - self.size) -- for debug purposes end function Enemy:isOutOfScreen() local res = false if self.x - self.half > ScreenWidth or self.y - self.half > ScreenHeigth then res = true elseif self.x + self.half < 0 or self.y + self.half < 0 then res = true end return res end
local discordia = require('discordia') local client = discordia.Client() client:on('ready', function() print('Logged in as '.. client.user.username) end) client:on('messageCreate', function(message) if message.content == '!ping' then message.channel:send('Pong!') end end) client:run('Bot INSERT_TOKEN_HERE')
--[[ Sequence to sequence model with attention. ]] local Seq2Seq, parent = torch.class('Seq2Seq', 'Model') local options = { { '-word_vec_size', 0, [[Shared word embedding size. If set, this overrides `-src_word_vec_size` and `-tgt_word_vec_size`.]], { valid = onmt.utils.ExtendedCmdLine.isUInt(), structural = 0 } }, { '-src_word_vec_size', '500', [[Comma-separated list of source embedding sizes: `word[,feat1[,feat2[,...] ] ]`.]], { structural = 0 } }, { '-tgt_word_vec_size', '500', [[Comma-separated list of target embedding sizes: `word[,feat1[,feat2[,...] ] ]`.]], { structural = 0 } }, { '-pre_word_vecs_enc', '', [[Path to pretrained word embeddings on the encoder side serialized as a Torch tensor.]], { valid = onmt.utils.ExtendedCmdLine.fileNullOrExists, init_only = true } }, { '-pre_word_vecs_dec', '', [[Path to pretrained word embeddings on the decoder side serialized as a Torch tensor.]], { valid = onmt.utils.ExtendedCmdLine.fileNullOrExists, init_only = true } }, { '-fix_word_vecs_enc', 0, [[Fix word embeddings on the encoder side.]], { enum = {0, 1}, structural = 1 } }, { '-fix_word_vecs_dec', 0, [[Fix word embeddings on the decoder side.]], { enum = {0, 1}, structural = 1 } }, { '-feat_merge', 'concat', [[Merge action for the features embeddings.]], { enum = {'concat', 'sum'}, structural = 0 } }, { '-feat_vec_exponent', 0.7, [[When features embedding sizes are not set and using `-feat_merge concat`, their dimension will be set to `N^feat_vec_exponent` where `N` is the number of values the feature takes.]], { structural = 0 } }, { '-feat_vec_size', 20, [[When features embedding sizes are not set and using `-feat_merge sum`, this is the common embedding size of the features]], { valid = onmt.utils.ExtendedCmdLine.isUInt(), structural = 0 } } } function Seq2Seq.declareOpts(cmd) cmd:setCmdLineOptions(options, Seq2Seq.modelName()) onmt.Encoder.declareOpts(cmd) onmt.Decoder.declareOpts(cmd) onmt.Factory.declareOpts(cmd) end function Seq2Seq:__init(args, dicts, verbose) parent.__init(self, args) onmt.utils.Table.merge(self.args, onmt.utils.ExtendedCmdLine.getModuleOpts(args, options)) self.args.uneven_batches = args.uneven_batches self.models.encoder = onmt.Factory.buildWordEncoder(args, dicts.src, verbose) self.models.decoder = onmt.Factory.buildWordDecoder(args, dicts.tgt, verbose) self.criterion = onmt.ParallelClassNLLCriterion(onmt.Factory.getOutputSizes(dicts.tgt)) end function Seq2Seq.load(args, models, dicts, isReplica) local self = torch.factory('Seq2Seq')() parent.__init(self, args) onmt.utils.Table.merge(self.args, onmt.utils.ExtendedCmdLine.getModuleOpts(args, options)) self.args.uneven_batches = args.uneven_batches self.models.encoder = onmt.Factory.loadEncoder(models.encoder, isReplica) self.models.decoder = onmt.Factory.loadDecoder(models.decoder, isReplica) self.criterion = onmt.ParallelClassNLLCriterion(onmt.Factory.getOutputSizes(dicts.tgt)) return self end -- Returns model name. function Seq2Seq.modelName() return 'Sequence to Sequence with Attention' end -- Returns expected dataMode. function Seq2Seq.dataType() return 'bitext' end function Seq2Seq:returnIndividualLosses(enable) if not self.models.decoder.returnIndividualLosses then _G.logger:info('Current Seq2Seq model does not support training with sample_w_ppl option') return false else self.models.decoder:returnIndividualLosses(enable) end return true end function Seq2Seq:enableProfiling() _G.profiler.addHook(self.models.encoder, 'encoder') _G.profiler.addHook(self.models.decoder, 'decoder') _G.profiler.addHook(self.models.decoder.modules[2], 'generator') _G.profiler.addHook(self.criterion, 'criterion') end function Seq2Seq:getOutput(batch) return batch.targetOutput end function Seq2Seq:maskPadding(batch) if self.args.uneven_batches then self.models.encoder:maskPadding() if batch.uneven then self.models.decoder:maskPadding(batch.sourceSize, batch.sourceLength) else self.models.decoder:maskPadding() end end end function Seq2Seq:forwardComputeLoss(batch) self:maskPadding(batch) local encoderStates, context = self.models.encoder:forward(batch) return self.models.decoder:computeLoss(batch, encoderStates, context, self.criterion) end function Seq2Seq:trainNetwork(batch, dryRun) self:maskPadding(batch) local encStates, context = self.models.encoder:forward(batch) local decOutputs = self.models.decoder:forward(batch, encStates, context) if dryRun then decOutputs = onmt.utils.Tensor.recursiveClone(decOutputs) end local encGradStatesOut, gradContext, loss, indvLoss = self.models.decoder:backward(batch, decOutputs, self.criterion) self.models.encoder:backward(batch, encGradStatesOut, gradContext) return loss, indvLoss end return Seq2Seq
--------------------------------------------------------------------------------------------------- -- -= Map =- --------------------------------------------------------------------------------------------------- -- Import the other classes TILED_LOADER_PATH = TILED_LOADER_PATH or ({...})[1]:gsub("[%.\\/][Mm]ap$", "") .. '.' local Tile = require( TILED_LOADER_PATH .. "Tile") local TileSet = require( TILED_LOADER_PATH .. "TileSet") local TileLayer = require( TILED_LOADER_PATH .. "TileLayer") local Object = require( TILED_LOADER_PATH .. "Object") local ObjectLayer = require( TILED_LOADER_PATH .. "ObjectLayer") -- Localize some functions so they are faster local pairs = pairs local ipairs = ipairs local assert = assert local love = love local table = table local ceil = math.ceil local floor = math.floor -- Make our map class local Map = {} Map.__index = Map -- Returns a new map function Map:new(name, width, height, tileWidth, tileHeight, orientation, properties) -- Our map local map = {} -- Public: map.name = name or "Unnamed Nap" -- Name of the map map.width = width or 0 -- Width of the map in tiles map.height = height or 0 -- Height of the map in tiles map.tileWidth = tileWidth or 0 -- Width in pixels of each tile map.tileHeight = tileHeight or 0 -- Height in pixels of each tile map.orientation = orientation or "orthogonal" -- Type of map. "orthogonal" or "isometric" map.properties = properties or {} -- Properties of the map set by Tiled map.useSpriteBatch = false -- If true then tile layers are rendered with sprite batches. map.offsetX = 0 -- X offset the map map.offsetY = 0 -- Y offset of the map map.tileLayers = {} -- Tile layers indexed by name map.objectLayers = {} -- Object layers indexed by name map.tilesets = {} -- Tilesets indexed by name map.tiles = {} -- Tiles indexed by id map.tl = map.tileLayers -- A shortcut to tileLayers map.ol = map.objectLayers -- A shortcut to objectLayers map.drawList = {} -- Draws the items in order from 1 to n. map.drawRange = {} -- Limits the drawing of tiles and objects. [1]:x [2]:y [3]:width [4]:height map.drawObjects = true -- If true then object layers will be drawn -- Private: map._widestTile = 0 -- The widest tile on the map. map._highestTile = 0 -- The tallest tile on the map. map._tileRange = {} -- The range of drawn tiles. [1]:x [2]:y [3]:width [4]:height map._previousTileRange = {} -- The previous _tileRange. If this changed then we redraw sprite batches. map._specialRedraw = true -- If true then the map needs to redraw sprite batches. map._forceSpecialRedraw = false -- If true then the next special redraw is forced map._previousUseSpriteBatch = false -- The previous _useSpiteBatch. If this changed then we redraw sprite batches. map._tileClipboard = nil -- The value that stored for TileLayer:tileCopy() and TileLayer:tilePaste() -- Return the new map return setmetatable(map, Map) end -- Creates a new tileset and adds it to the map. The map will then auto-update its tiles. function Map:newTileSet(img, name, tilew, tileh, width, height, firstgid, space, marg, tprop) assert(name, "Map:newTileSet - The name parameter is invalid") self.tilesets[name] = TileSet:new(img, name, tilew, tileh, width, height, firstgid, space, marg, tprop) self:updateTiles() return self.tilesets[name] end -- Creates a new TileLayer and adds it to the map. The last parameter is the place in the draw order -- If draw isn't specified, it will be created as the highest drawable. function Map:newTileLayer(name, opacity, prop, draw) assert(name, "Map:newTileLayer - The name parameter is invalid") self.tl[name] = TileLayer:new(self, name, opacity, prop) table.insert(self.drawList, draw or #self.drawList + 1, self.tl[name]) return self.tl[name] end -- Creates a new ObjectLayer and inserts it into the map function Map:newObjectLayer(name, color, opacity, prop, draw) assert(name, "Map:newObjectLayer - The name parameter is invalid") self.ol[name] = ObjectLayer:new(self, name, color, opacity, prop) table.insert(self.drawList, draw or #self.drawList + 1, self.tl[name]) return self.ol[name] end -- Cuts tiles out of tilesets and stores them in the tiles tables under their id -- Call this after the tilesets are set up function Map:updateTiles() self.tiles = {} self.widestTile = 0 self.highestTile = 0 for _, ts in pairs(self.tilesets) do if ts.tileWidth > self.widestTile then self.widestTile = ts.tileWidth end if ts.tileHeight > self.highestTile then self.highestTile = ts.tileHeight end for id, val in pairs(ts:getTiles()) do self.tiles[id] = val end end end -- Forces the map to redraw the sprite batches. function Map:forceRedraw() self._specialRedraw = true self._forceSpecialRedraw = true end -- Draws each item in drawList. By default, drawList is simply an array of all the layers' -- draw functions in the order they appear in Tiled. You can manipulate drawList however you like. -- Items in drawList can either be functions or tables with a draw() function. function Map:draw() -- Update the tile range self:_updateTileRange() -- This actually draws the map local vtype for i,v in ipairs(self.drawList) do vtype = type(v) if vtype == "table" then assert(v.draw, "Map:draw() - A table in drawList does not have a draw() function") v:draw() elseif vtype == "function" then v() end end end -- Returns the draw position of the item contained in drawList. function Map:drawPosition(item) local pos for k, v in ipairs(self.drawList) do if v == item then pos = k end end return pos end -- Turns an isometric location into a world location. The unit length for isometric tiles is always -- the map's tileHeight. This is both for width and height. function Map:fromIso(x, y) x, y = x or 0, y or 0 local h, tw, th = self.height, self.tileWidth, self.tileHeight return ((x-y)/th + h - 1)*tw/2, (x+y)/2 end -- Turns a world location into an isometric location function Map:toIso(a, b) a, b = a or 0, b or 0 local h, tw, th = self.height, self.tileWidth, self.tileHeight local x, y x = b - (h-1)*th/2 + (a*th)/tw y = 2*b - x return x, y end -- Sets the draw range function Map:setDrawRange(x,y,w,h) self.drawRange[1], self.drawRange[2], self.drawRange[3], self.drawRange[4] = x, y, w, h end -- Gets the draw range function Map:getDrawRange() return self.drawRange[1], self.drawRange[2], self.drawRange[3], self.drawRange[4] end -- Automatically sets the draw range to fit the display function Map:autoDrawRange(tx, ty, scale, pad) tx, ty, scale, pad = tx or 0, ty or 0, scale or 1, pad or 0 if scale > 0.001 then self:setDrawRange(-tx-pad,-ty-pad,love.graphics.getWidth()/scale+pad*2, love.graphics.getHeight()/scale+pad*2) end end -- A short-hand to retreive tiles from a layer's tileData. function Map:__call(layerName, x, y) return self.tileLayers.tileData(x,y) end ---------------------------------------------------------------------------------------------------- -- Private Functions ---------------------------------------------------------------------------------------------------- -- This is an internal function used to update the map's _tileRange, _previousTileRange, and -- _specialRedraw function Map:_updateTileRange() -- Offset to make sure we can always draw the highest and widest tile local heightOffset = self.highestTile - self.tileHeight local widthOffset = self.widestTile - self.tileWidth -- Set the previous tile range for i=1,4 do self._previousTileRange[i] = self._tileRange[i] end -- Get the draw range. We will replace these values with the tile range. local x1, y1, x2, y2 = self.drawRange[1], self.drawRange[2], self.drawRange[3], self.drawRange[4] -- Calculate the _tileRange for orthogonal tiles if self.orientation == "orthogonal" then -- Limit the drawing range. We must make sure we can draw the tiles that are bigger -- than the self's tileWidth and tileHeight. if x1 and y1 and x2 and y2 then x2 = ceil((x1+x2)/self.tileWidth) y2 = ceil((y1+y2+heightOffset)/self.tileHeight) x1 = floor((x1-widthOffset)/self.tileWidth) y1 = floor(y1/self.tileHeight) -- Make sure that we stay within the boundry of the map x1 = x1 > 0 and x1 or 0 y1 = y1 > 0 and y1 or 0 x2 = x2 < self.width-1 and x2 or self.width-1 y2 = y2 < self.height-1 and y2 or self.height-1 else -- If the drawing range isn't defined then we draw all the tiles x1, y1, x2, y2 = 1, 1, self.width, self.height end -- Calculate the _tileRange for isometric tiles. else -- If the drawRange is set if x1 and y1 and x2 and y2 then x1, y1 = self:toIso(x1-self.widestTile,y1) x1, y1 = ceil(x1/self.tileHeight), ceil(y1/self.tileHeight)-1 x2 = ceil((x2+self.widestTile)/self.tileWidth) y2 = ceil((y2+heightOffset)/self.tileHeight) -- else draw everything else x1 = 0 y1 = 0 x2 = self.width-1 y2 = self.height-1 end end -- Assign the new values to the tile range local tr, ptr = self._tileRange, self._previousTileRange tr[1], tr[2], tr[3], tr[4] = x1, y1, x2, y2 -- If the tile range or useSpriteBatch is different than the last frame then we need to update sprite batches. self._specialRedraw = self.useSpriteBatch ~= self._previousUseSpriteBatch or self._forceSpecialRedraw or tr[1] ~= ptr[1] or tr[2] ~= ptr[2] or tr[3] ~= ptr[3] or tr[4] ~= ptr[4] -- Set the previous useSpritebatch self._previousUseSpriteBatch = self.useSpriteBatch -- Reset the forced special redraw self._forceSpecialRedraw = false end -- Returns the Map class return Map --[[Copyright (c) 2011 Casey Baxter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.--]]
object_tangible_quest_talus_selonian_food_container_03 = object_tangible_quest_shared_talus_selonian_food_container_03:new { } ObjectTemplates:addTemplate(object_tangible_quest_talus_selonian_food_container_03, "object/tangible/quest/talus_selonian_food_container_03.iff")
return {'litouwen','litouwer','litouws','litouwse','litanie','liter','literaat','literair','literarisch','literator','literatuur','literatuurbeschouwing','literatuurcriticus','literatuurfestival','literatuurgeschiedenis','literatuurhistoricus','literatuurkritiek','literatuurliefhebber','literatuurlijst','literatuurmap','literatuuronderwijs','literatuuronderzoek','literatuuropgave','literatuuropvatting','literatuuroverzicht','literatuurprijs','literatuurprofessor','literatuursociologie','literatuurstudie','literatuurtheorie','literatuurverwijzing','literatuurwetenschap','literatuurwetenschappelijk','literatuurwetenschapper','literfles','literglas','litermaat','literpak','literprijs','lithium','litho','lithochromie','lithograaf','lithograferen','lithografie','lithografisch','lithosfeer','litigieus','litotes','litteken','littekenvorming','littekenweefsel','litterair','litterator','litteratuur','litteratuurgeschiedenis','liturg','liturgie','liturgieboek','liturgiek','liturgisch','literatuurboek','lith','littenseradiel','lita','lit','litjens','littooij','littel','litjes','litouwers','litanieen','literaire','literatoren','literaturen','literatuurbesprekingen','literatuurgeschiedenissen','literatuurhistorici','literatuurliefhebbers','literatuurlijsten','literatuurmappen','literatuuronderzoeken','literatuuronderzoekje','literatuurreferenties','literatuurverwijzingen','literatuurwetenschappen','literatuurwetenschappers','literflessen','literglazen','liters','litertje','litertjes','lithos','lithografeerde','lithografeert','lithografen','lithografieen','lithografische','litigieuze','littekenen','littekens','litteraire','litteratoren','litteraturen','liturgen','liturgieen','liturgische','literarische','literaten','literatuurbeschouwingen','literatuurcritici','literatuurkritieken','literatuurprijzen','literatuurstudies','litermaten','literatuuropgaven','literatuuroverzichten','literatuurwetenschappelijke','littekenweefsels','litas','literatuuropvattingen','literairs','liturgieboekje','literatuurboeken','literatuurlijstje','literpakken','liturgieboekjes','literatuurfestivals','literflesjes','literatuurlijstjes','literflesje','lithse'}
return { [1] = {level=1,need_exp=0,clothes_attrs={0,0,0,0,0,0,0,0,0,0,},}, [2] = {level=2,need_exp=100,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [3] = {level=3,need_exp=200,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [4] = {level=4,need_exp=300,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [5] = {level=5,need_exp=400,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [6] = {level=6,need_exp=500,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [7] = {level=7,need_exp=700,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [8] = {level=8,need_exp=900,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [9] = {level=9,need_exp=1100,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [10] = {level=10,need_exp=1300,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [11] = {level=11,need_exp=1500,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [12] = {level=12,need_exp=2000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [13] = {level=13,need_exp=2500,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [14] = {level=14,need_exp=3000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [15] = {level=15,need_exp=3500,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [16] = {level=16,need_exp=4000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [17] = {level=17,need_exp=4500,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [18] = {level=18,need_exp=5000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [19] = {level=19,need_exp=5500,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [20] = {level=20,need_exp=6000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [21] = {level=21,need_exp=6500,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [22] = {level=22,need_exp=7000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [23] = {level=23,need_exp=7500,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [24] = {level=24,need_exp=8000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [25] = {level=25,need_exp=8500,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [26] = {level=26,need_exp=9000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [27] = {level=27,need_exp=9500,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [28] = {level=28,need_exp=10000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [29] = {level=29,need_exp=11000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [30] = {level=30,need_exp=12000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [31] = {level=31,need_exp=13000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [32] = {level=32,need_exp=14000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [33] = {level=33,need_exp=15000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [34] = {level=34,need_exp=17000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [35] = {level=35,need_exp=19000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [36] = {level=36,need_exp=21000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [37] = {level=37,need_exp=23000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [38] = {level=38,need_exp=25000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [39] = {level=39,need_exp=28000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [40] = {level=40,need_exp=31000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [41] = {level=41,need_exp=34000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [42] = {level=42,need_exp=37000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [43] = {level=43,need_exp=40000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [44] = {level=44,need_exp=45000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [45] = {level=45,need_exp=50000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [46] = {level=46,need_exp=55000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [47] = {level=47,need_exp=60000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [48] = {level=48,need_exp=65000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [49] = {level=49,need_exp=70000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [50] = {level=50,need_exp=75000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [51] = {level=51,need_exp=80000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [52] = {level=52,need_exp=85000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [53] = {level=53,need_exp=90000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [54] = {level=54,need_exp=95000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [55] = {level=55,need_exp=100000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [56] = {level=56,need_exp=105000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [57] = {level=57,need_exp=110000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [58] = {level=58,need_exp=115000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [59] = {level=59,need_exp=120000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [60] = {level=60,need_exp=125000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [61] = {level=61,need_exp=130000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [62] = {level=62,need_exp=135000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [63] = {level=63,need_exp=140000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [64] = {level=64,need_exp=145000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [65] = {level=65,need_exp=150000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [66] = {level=66,need_exp=155000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [67] = {level=67,need_exp=160000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [68] = {level=68,need_exp=165000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [69] = {level=69,need_exp=170000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [70] = {level=70,need_exp=175000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [71] = {level=71,need_exp=180000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [72] = {level=72,need_exp=185000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [73] = {level=73,need_exp=190000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [74] = {level=74,need_exp=195000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [75] = {level=75,need_exp=200000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [76] = {level=76,need_exp=205000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [77] = {level=77,need_exp=210000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [78] = {level=78,need_exp=215000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [79] = {level=79,need_exp=220000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [80] = {level=80,need_exp=225000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [81] = {level=81,need_exp=230000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [82] = {level=82,need_exp=235000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [83] = {level=83,need_exp=240000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [84] = {level=84,need_exp=245000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [85] = {level=85,need_exp=250000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [86] = {level=86,need_exp=255000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [87] = {level=87,need_exp=260000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [88] = {level=88,need_exp=265000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [89] = {level=89,need_exp=270000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [90] = {level=90,need_exp=275000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [91] = {level=91,need_exp=280000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [92] = {level=92,need_exp=285000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [93] = {level=93,need_exp=290000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [94] = {level=94,need_exp=295000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [95] = {level=95,need_exp=300000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [96] = {level=96,need_exp=305000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [97] = {level=97,need_exp=310000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [98] = {level=98,need_exp=315000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, [99] = {level=99,need_exp=320000,clothes_attrs={1,1,1,1,1,0,0,0,0,0,},}, [100] = {level=100,need_exp=325000,clothes_attrs={0,0,0,0,0,1,1,1,1,1,},}, }
local PLUGIN = PLUGIN PLUGIN.name = "Item Hotkeys" PLUGIN.author = "verne" PLUGIN.desc = "Allows for use of hotkeys to be used for pre-defined item usage." ix.util.Include("cl_plugin.lua") ix.util.Include("sh_hotkeyitems.lua") local playerMeta = FindMetaTable("Player") local charMeta = ix.meta.character or {} ix.char.RegisterVar("hotkeys", { field = "hotkeys", fieldType = ix.type.string, default = {}, bNoDisplay = true, }) netstream.Hook("ixHotkeyChange", function(client, hotkey, value) client:GetCharacter():SetHotkey(hotkey, value) end) if (CLIENT) then netstream.Hook("ixHotkeyItemUpdate", function(hotkeyindex) local hotkeyitem = ix.option.Get("Hotkey" .. hotkeyindex, "nil") for i = 1, 4 do if ix.option.Get("Hotkey" .. i, "nil") == hotkeyitem then ix.option.Set("Hotkey" .. i, "nil") end end end) end function charMeta:GetHotkeyItemName(hotkeyindex) local hotkeys = self:GetHotkeys() return hotkeys[hotkeyindex] end function charMeta:SetHotkey(hotkeyindex, item) local hotkeys = self:GetHotkeys() hotkeys[hotkeyindex] = item self:SetHotkeys(hotkeys) end function charMeta:ClearHotkeys() local emptyhotkeys = {} self:SetHotkeys(emptyhotkeys) end function playerMeta:ActivateHotkey(hotkeyindex) local client = self local char = self:GetCharacter() local inv = char:GetInventory() local item = inv:HasItem(char:GetHotkeyItemName(hotkeyindex)) local info, action --items shouldnt be overlapping blackscreens if self:GetNetVar("ix_noMenuAllowed") then return end if item then for k, v in pairs(PLUGIN.hotkeyitems) do if item.uniqueID == k then info = item.functions[v] action = v end end end if (info and info.OnCanRun and info.OnCanRun(item) != false) then ix.item.PerformInventoryAction(client, action, item.id, inv.id) if !inv:HasItem(char:GetHotkeyItemName(hotkeyindex)) then netstream.Start(client, "ixHotkeyItemUpdate", hotkeyindex) end end end function PLUGIN:ShowHelp(client) client:ActivateHotkey(1) end function PLUGIN:ShowTeam(client) client:ActivateHotkey(2) end function PLUGIN:ShowSpare1(client) client:ActivateHotkey(3) end function PLUGIN:ShowSpare2(client) client:ActivateHotkey(4) end ix.option.Add("Hotkey1", ix.type.array, "nil", { category = "_hotkeys", bNetworked = true, populate = function() local entries = { ["nil"] = "None" } for k, v in pairs(PLUGIN.hotkeyitems) do local itemTable = ix.item.list[k] local name = itemTable.name local item = LocalPlayer():GetCharacter():GetInventory():HasItem(k) if item then if item.name then entries[k] = name else continue end end end -- Check if only the nil key is present if table.Count(entries) == 1 then ix.option.Set("Hotkey1", "nil") end return entries end, OnChanged = function(oldValue, newValue) netstream.Start("ixHotkeyChange", 1, newValue) end }) ix.option.Add("Hotkey2", ix.type.array, "nil", { category = "_hotkeys", bNetworked = true, populate = function() local entries = { ["nil"] = "None" } for k, v in pairs(PLUGIN.hotkeyitems) do local itemTable = ix.item.list[k] local name = itemTable.name local item = LocalPlayer():GetCharacter():GetInventory():HasItem(k) if item then if item.name then entries[k] = name else continue end end end -- Check if only the nil key is present if table.Count(entries) == 1 then ix.option.Set("Hotkey2", "nil") end return entries end, OnChanged = function(oldValue, newValue) netstream.Start("ixHotkeyChange", 2, newValue) end }) ix.option.Add("Hotkey3", ix.type.array, "nil", { category = "_hotkeys", bNetworked = true, populate = function() local entries = { ["nil"] = "None" } for k, v in pairs(PLUGIN.hotkeyitems) do local itemTable = ix.item.list[k] local name = itemTable.name local item = LocalPlayer():GetCharacter():GetInventory():HasItem(k) if item then if item.name then entries[k] = name else continue end end end -- Check if only the nil key is present if table.Count(entries) == 1 then ix.option.Set("Hotkey3", "nil") end return entries end, OnChanged = function(oldValue, newValue) netstream.Start("ixHotkeyChange", 3, newValue) end }) ix.option.Add("Hotkey4", ix.type.array, "nil", { category = "_hotkeys", bNetworked = true, populate = function() local entries = { ["nil"] = "None" } for k, v in pairs(PLUGIN.hotkeyitems) do local itemTable = ix.item.list[k] local name = itemTable.name local item = LocalPlayer():GetCharacter():GetInventory():HasItem(k) if item then if item.name then entries[k] = name else continue end end end -- Check if only the nil key is present if table.Count(entries) == 1 then ix.option.Set("Hotkey4", "nil") end return entries end, OnChanged = function(oldValue, newValue) netstream.Start("ixHotkeyChange", 4, newValue) end })
VH_HookLib = {} -- Custom hook system -- VH_HookLib.HookPriority = { -- Lowest is first, Highest is last -- If you are planning on disabling the hook, use lowest Lowest = 1, Low = 2, Normal = 3, High = 4, Highest = 5 } VH_HookLib.Hooks = {} function VH_HookLib.runHook(HookType, CanDisable, ...) if not VH_HookLib.Hooks[HookType] then hook.Run(HookType, ...) return end local ReturnValue, Disabled = nil for a, b in pairs(VH_HookLib.HookPriority) do if VH_HookLib.Hooks[HookType][b] then if Disabled and CanDisable then break end for c, d in pairs(VH_HookLib.Hooks[HookType][b]) do local TValue, TDisabled = d(...) if TempReturnValue ~= nil then ReturnValue = TValue end if TDisabled ~= nil then Disabled = TDisabled end if Disabled and CanDisable then break end end end end return ReturnValue, Disabled end function VH_HookLib.removeHook(HookType, Priority, Key) if VH_HookLib.Hooks[HookType] and VH_HookLib.Hooks[HookType][Priority] and VH_HookLib.Hooks[HookType][Priority][Key] then VH_HookLib.Hooks[HookType][Priority][Key] = nil end end function VH_HookLib.addHook(HookType, Key, Callback) VH_HookLib.addHook(HookType, VH_HookLib.HookPriority.Normal, Key, Callback) end function VH_HookLib.addHook(HookType, Priority, Key, Callback) VH_HookLib.Hooks[HookType] = VH_HookLib.Hooks[HookType] or {} VH_HookLib.Hooks[HookType][Priority] = VH_HookLib.Hooks[HookType][Priority] or {} VH_HookLib.Hooks[HookType][Priority][Key] = Callback end -- Convert default hooks -- local DefHooks = { { Key = "PlayerSay", CanDisable = true, Disable = "" }, { Key = "PlayerInitialSpawn" } } local HookAdd = hook.Add function hook.Add(HookType, Key, Callback, HookLib) if VH_HookLib.Hooks[HookType] and not HookLib then debug.Trace() print("VH_HookLib.addHook(" .. HookType .. ", " .. Key .. ", CALLBACK)") VH_HookLib.addHook(HookType, Key, Callback) else HookAdd(HookType, Key, Callback) end end local HookTable = hook.GetTable() for a, b in ipairs(DefHooks) do if HookTable[b.Key] then for c, d in pairs(HookTable[b.Key]) do VH_HookLib.addHook(b.Key, c, d) hook.Remove(b.Key, c) end end hook.Add(b.Key, "HookLib_" .. b.Key, function(...) local ReturnValue, Disabled = VH_HookLib.runHook(b.Key, b.CanDisable, ...) if Disabled then return b.Disable else return ReturnValue end end, true) end
require("moonsc").import_tags() -- Test that states are exited in exit order (children before parents with -- reverse doc order used to break ties before the executable content in the -- transitions. event1, event2, event3, event4 should be raised in that -- order when s01p is exited return _scxml{ initial="s0", _state{ id="s0", initial="s01p", _parallel{ id="s01p", -- this should be the third event raised _onexit{ _raise{ event="event3" }}, -- this should be the fourth event raised _transition{ target="s02", _raise{ event="event4" }}, _state{ id="s01p1", -- this should be the second event raised _onexit{ _raise{ event="event2" }}, }, _state{ id="s01p2", -- this should be the first event raised _onexit{ _raise{ event="event1" }}, }, }, _state{ id="s02", _transition{ event="event1", target="s03" }, _transition{ event="*", target="fail" }, }, _state{ id="s03", _transition{ event="event2", target="s04" }, _transition{ event="*", target="fail" }, }, _state{ id="s04", _transition{ event="event3", target="s05" }, _transition{ event="*", target="fail" }, }, _state{ id="s05", _transition{ event="event4", target="pass" }, _transition{ event="*", target="fail" }, }, }, _final{id='pass'}, _final{id='fail'}, }
return {'urologie','urologisch','uroloog','uroscopie','urologen','urologische'}
-- require('mobdebug').start() io.stdout:setvbuf('no') local path = require 'pl.path' package.path = package.path .. ';' .. path.normpath(path.join(arg[0], '../?.lua')) local emu = require 'emu' local args = {...} local dir = table.remove(args, 1) -- local dir = '/home/cpup/code/lua/cc-emu/dev' dir = path.normpath(path.join(path.currentdir(), dir)) emu(dir, unpack(args, 1, select('#', ...) - 1))
local tester = torch.Tester() local function aliasMultinomial() local n_class = 10000 local probs = torch.Tensor(n_class):uniform(0,1) -- uniform: 均匀抽样 --print("probs: ", probs) probs:div(probs:sum()) local a = torch.Timer() local state = torch.multinomialAliasSetup(probs) print("AliasMultinomial setup in "..a:time().real.." seconds(hot)") a:reset() state = torch.multinomialAliasSetup(probs, state) print("AliasMultinomial setup in "..a:time().real.." seconds(cold)") a:reset() tester:assert(state[1]:min() >= 0, "Index ="..state[1]:min().."alias indices has an index below or equal to 0") tester:assert(state[1]:max() <= n_class, state[1]:max().." alias indices has an index exceeding num_class") local output = torch.LongTensor(1000000) torch.multinomialAlias(output, state) local n_samples = output:nElement() print("AliasMultinomial draw "..n_samples.." elements from "..n_class.." classes ".."in "..a:time().real.." seconds") local counts = torch.Tensor(n_class):zero() mult_output = torch.multinomial(probs, n_samples, true) print("Multinomial draw "..n_samples.." elements from "..n_class.." classes ".." in "..a:time().real.." seconds") tester:assert(output:min() > 0, "sampled indices has an index below or equal to 0") tester:assert(output:max() <= n_class, "indices has an index exceeding num_class") output:apply(function(x) counts[x] = counts[x] + 1 end) a:reset() counts:div(counts:sum()) tester:assert(state[1]:min() >= 0, "Index ="..state[1]:min().."alias indices has an index below or equal to 0") tester:assert(state[1]:max() <= n_class, state[1]:max().." alias indices has an index exceeding num_class") tester:eq(probs, counts, 0.001, "probs and counts should be approximately equal") end tester:add(aliasMultinomial) tester:run()
--init.lua --tools mod for BFD. --dofile(minetest.get_modpath("tools").."/custom_tools.lua") minetest.register_craft({ type = "toolrepair", additional_wear = -0.02, }) --tool rod defs minetest.register_craftitem("tools:stick", { description = "Wooden Stick", inventory_image = "tool_stick.png", }) -- chisel, for randomising the statues minetest.register_craftitem("tools:chisel", { description = "Chisel", stack_max = 1, inventory_image = "tool_chisel.png", }) -- get string from wool minetest.register_craft({ output = 'farming:string 9', recipe = { {'group:wool'} } }) -- tool rod crafts minetest.register_craft({ output = 'tools:stick 16', recipe = { {'group:wood'}, } }) -- ingot crafts minetest.register_craft({ type = "cooking", output = "tools:steel_ingot", recipe = "ores:iron_lump", }) minetest.register_craft({ type = "cooking", output = "tools:tin_ingot", recipe = "ores:tin_lump", }) minetest.register_craft({ type = "cooking", output = "tools:copper_ingot", recipe = "ores:copper_lump", }) minetest.register_craft({ output = 'tools:bronze_ingot 2', recipe = { {'tools:copper_ingot', 'tools:copper_ingot'}, {'tools:copper_ingot', 'tools:tin_ingot'}, } }) minetest.register_craft({ type = "cooking", output = "tools:lead_ingot", recipe = "ores:lead_lump", }) minetest.register_craft({ type = "cooking", output = "tools:silver_ingot", recipe = "ores:silver_lump", }) minetest.register_craft({ type = "cooking", output = "tools:gold_ingot", recipe = "ores:gold_lump", }) -- ingot defs minetest.register_craftitem("tools:steel_ingot", { description = "Steel Ingot", inventory_image = "tools_steel_ingot.png", }) minetest.register_craftitem("tools:tin_ingot", { description = "Tin Ingot", inventory_image = "tools_tin_ingot.png", }) minetest.register_craftitem("tools:copper_ingot", { description = "Copper Ingot", inventory_image = "tools_copper_ingot.png", }) minetest.register_craftitem("tools:bronze_ingot", { description = "Bronze Ingot", inventory_image = "tools_bronze_ingot.png", }) minetest.register_craftitem("tools:lead_ingot", { description = "Lead Ingot", inventory_image = "tools_lead_ingot.png", }) minetest.register_craftitem("tools:silver_ingot", { description = "Silver Ingot", inventory_image = "tools_silver_ingot.png", }) minetest.register_craftitem("tools:gold_ingot", { description = "Silver Ingot", inventory_image = "tools_gold_ingot.png", }) -- air sword! minetest.register_tool("tools:sword_air", { description = "Air Sword", inventory_image = "tool_air_sword.png", tool_capabilities = { full_punch_interval = 0.01, max_drop_level = 0, groupcaps = { snappy = {times={[1]=0.05, [2]=0.005, [3]=0.0005}, uses = 1337, maxlevel=1}, }, damage_groups = {fleshy=1000000, immortal=10000000}, } }) --basic wooden tools, upgrades can only be applied to iron and beyond; stone cannot have them either. minetest.register_tool("tools:pick_wood", { description = "Wooden Pickaxe", inventory_image = "tool_woodpick.png", tool_capabilities = { full_punch_interval = 2.3, max_drop_level = 0, groupcaps={ cracky = {times={[3]=3}, uses=1, maxlevel=1}, }, damage_groups = {fleshy=1}, } }) minetest.register_tool("tools:shovel_wood", { description = "Wooden Shovel", inventory_image = "tool_woodshovel.png^[transformR90", tool_capabilities = { full_punch_interval = 2.3, max_drop_level = 0, groupcaps = { crumbly = {times={[1]=6.2, [2]=3.1, [3]=1.55}, uses=12, maxlevel=1}, }, damage_groups = {fleshy=1}, } }) minetest.register_tool("tools:axe_wood", { description = "Wooden Axe", inventory_image = "tool_woodaxe.png", tool_capabilities = { full_punch_interval = 2.3, max_drop_level = 0, groupcaps = { choppy = {times={[2]=9.8, [3]=4.9}, uses = 8, maxlevel=1}, }, damage_groups = {fleshy=2}, } }) minetest.register_tool("tools:sword_wood", { description = "Wooden Sword", inventory_image = "tool_woodsword.png", tool_capabilities = { full_punch_interval = 2.3, max_drop_level = 0, groupcaps = { snappy={times={[2]=0.5, [3]=0.25}, uses=10, maxlevel=1}, }, damage_groups = {fleshy=2}, } }) -- wooden tool crafts minetest.register_craft({ output = 'tools:pick_wood', recipe = { {'group:wood', 'group:wood', 'group:wood'}, {'', 'tools:stick', ''}, {'', 'tools:stick', ''}, } }) minetest.register_craft({ output = 'tools:shovel_wood', recipe = { {'', 'group:wood', ''}, {'', 'tools:stick', ''}, {'', 'tools:stick', ''}, } }) minetest.register_craft({ output = 'tools:sword_wood', recipe = { {'', 'group:wood', ''}, {'', 'group:wood', ''}, {'', 'tools:stick', ''}, } }) minetest.register_craft({ output = 'tools:axe_wood', recipe = { {'group:wood', 'group:wood'}, {'group:wood', 'tools:stick'}, {'', 'tools:stick'}, } }) -- stone tool defs minetest.register_tool("tools:pick_stone", { description = "Stone Pickaxe", inventory_image = "tool_stonepick.png", tool_capabilities = { full_punch_interval = 3.4, max_drop_level = 0, groupcaps={ cracky = {times={[3]=1.5}, uses=12, maxlevel=1}, }, damage_groups = {fleshy=2}, } }) minetest.register_tool("tools:shovel_stone", { description = "Stone Shovel", inventory_image = "tool_stoneshovel.png^[transformR90", tool_capabilities = { full_punch_interval = 3.1, max_drop_level = 0, groupcaps={ crumbly = {times={[1]=3.1, [2]=1.55, [3]=0.77}, uses=23, maxlevel=1}, }, damage_groups = {fleshy=2}, } }) minetest.register_tool("tools:axe_stone", { description = "Stone Axe", inventory_image = "tool_stoneaxe.png", tool_capabilities = { full_punch_interval = 2.8, max_drop_level = 0, groupcaps={ choppy = {times={[1]=9.8, [2]=4.2, [3]=2.1}, uses = 24, maxlevel=1}, }, damage_groups= {fleshy=3}, } }) minetest.register_tool("tools:sword_stone", { description = "Stone Sword", inventory_image = "tool_stonesword.png", tool_capabilities = { full_punch_interval = 4.1, max_drop_level = 0, groupcaps = { snappy={times={[1]=0.6, [2]=0.3, [3]=0.15}, uses=17, maxlevel=1}, }, damage_groups = {fleshy=5}, } }) -- stone tool crafts minetest.register_craft({ output = 'tools:pick_stone', recipe = { {'group:stone', 'group:stone', 'group:stone'}, {'', 'tools:stick', ''}, {'', 'tools:stick', ''}, } }) minetest.register_craft({ output = 'tools:shovel_stone', recipe = { {'', 'group:stone', ''}, {'', 'tools:stick', ''}, {'', 'tools:stick', ''}, } }) minetest.register_craft({ output = 'tools:axe_stone', recipe = { {'group:stone', 'group:stone', ''}, {'group:stone', 'tools:stick', ''}, {'', 'tools:stick', ''}, } }) minetest.register_craft({ output = 'tools:sword_stone', recipe = { {'group:stone'}, {'group:stone'}, {'tools:stick'}, } }) -- steel tools (regular) minetest.register_tool("tools:pick_steel", { description = "Steel Pickaxe", inventory_image = "tool_steelpick.png", tool_capabilities = { full_punch_interval = 2.05, max_drop_level = 0, groupcaps = { cracky = {times={[1]=3.7, [2]=1.85, [3]=0.92}, uses=34, maxlevel=1}, }, damage_groups = {fleshy=4}, } }) minetest.register_tool("tools:shovel_steel", { description = "Steel Shovel", inventory_image = "tool_steelshovel.png^[transformR90", tool_capabilities = { full_punch_interval = 2.05, max_drop_level = 0, groupcaps = { crumbly = {times={[1]=1.55, [2]=0.77, [3]=0.385}, uses = 36, maxlevel=1}, }, damage_groups = {fleshy=3}, } }) minetest.register_tool("tools:axe_steel", { description = "Steel Axe", inventory_image = "tool_steelaxe.png", tool_capabilities = { full_punch_interval = 2.05, max_drop_level = 0, groupcaps = { choppy = {times={[1]=4.2, [2]=2.1, [3]=1.05}, uses = 42, maxlevel=1}, }, damage_groups = {fleshy=5}, } }) minetest.register_tool("tools:sword_steel", { description = "Steel Sword", inventory_image = "tool_steelsword.png", tool_capabilities = { full_punch_interval = 1.78, max_drop_level = 0, groupcaps = { snappy = {times={[1]=0.3, [2]=0.15, [3]=0.075}, uses = 32, maxlevel=1}, }, damage_groups = {fleshy = 7}, } }) -- steel tool crafts (fuck me, i'm tired of this repetitive shit when it comes to working on tools. minetest.register_craft({ output = 'tools:pick_steel', recipe = { {'tools:steel_ingot', 'tools:steel_ingot', 'tools:steel_ingot'}, {'', 'tools:stick', ''}, {'', 'tools:stick', ''}, } }) minetest.register_craft({ output = 'tools:shovel_steel', recipe = { {'tools:steel_ingot'}, {'tools:stick'}, {'tools:stick'}, } }) minetest.register_craft({ output = 'tools:axe_steel', recipe = { {'tools:steel_ingot', 'tools:steel_ingot', ''}, {'tools:steel_ingot', 'tools:stick', ''}, {'', 'tools:stick', ''}, } }) minetest.register_craft({ output = 'tools:sword_steel', recipe = { {'tools:steel_ingot'}, {'tools:steel_ingot'}, {'tools:stick'}, } }) -- steel super tools minetest.register_tool("tools:steel_hammer", { description = "Steel Dighammer", groups = {sledge=1}, inventory_image = "tools_steel_hammer.png", tool_capabilities = { full_punch_interval = 4.1, max_drop_level=0, groupcaps={ cracky = {times={[1]=3.7*2, [2]=1.85*2, [3]=0.92*2}, uses=34, maxlevel=1}, }, damage_groups = {fleshy=4}, }, }) minetest.register_craft({ output = "tools:steel_hammer", recipe = { {"tools:steel_ingot", "tools:steel_ingot","tools:steel_ingot"}, {"tools:steel_ingot", "tools:steel_ingot","tools:steel_ingot"}, {"", "tools:stick",""} } }) minetest.register_tool("tools:steel_sickle", { description = "Steel Sickle", groups = {lumberaxe=1}, inventory_image = "tools_steel_sickle.png", tool_capabilities = { full_punch_interval = 2.34, max_drop_level=0, groupcaps = { snappy = {times={[1]=0.3, [2]=0.15, [3]=0.075}, uses = 36, maxlevel=1}, }, damage_groups = {fleshy=6}, }, }) minetest.register_craft({ output = "tools:steel_sickle", recipe = { {'tools:steel_ingot', 'tools:steel_ingot', 'tools:steel_ingot'}, {'tools:steel_ingot', '', 'tools:steel_ingot'}, {'', '', 'tools:stick'}, } }) minetest.register_tool("tools:steel_battleaxe", { description = "Steel Battle Axe", inventory_image = "tools_steel_battleaxe.png", tool_capabilities = { full_punch_interval = 2.05*2, max_drop_level = 0, groupcaps = { choppy = {times={[1]=4.2*2, [2]=2.1*2, [3]=1.05*2}, uses = 42*2, maxlevel=1}, }, damage_groups = {fleshy=9}, }, }) minetest.register_craft({ output = 'tools:steel_battleaxe', recipe = { {'tools:axe_steel', 'farming:string', 'tools:axe_steel'}, {'', 'tools:stick', ''}, } }) minetest.register_tool("tools:steel_dirt_mover", { description = "Steel Dirt Mover", groups = {sledge=1}, inventory_image = "tools_steel_dirt_mover.png", tool_capabilities = { full_punch_interval = 2.55, max_drop_level = 0, groupcaps = { crumbly = {times={[1]=1.55*2, [2]=0.77*2, [3]=0.385*2}, uses = 40, maxlevel=1}, }, damage_groups = {fleshy=3}, }, }) minetest.register_craft({ output = "tools:steel_dirt_mover", recipe = { {'tools:steel_ingot', 'tools:steel_ingot', 'tools:steel_ingot'}, {'tools:steel_ingot', 'tools:stick', 'tools:steel_ingot'}, {'', 'tools:stick', ''}, } }) -- tin tools minetest.register_tool("tools:pick_tin", { description = "Tin Pickaxe", inventory_image = "tool_tinpick.png", tool_capabilities = { full_punch_interval = 2.05, max_drop_level = 0, groupcaps = { cracky = {times={[1]=3.7*1.2, [2]=1.85*1.2, [3]=0.92*1.2}, uses=52, maxlevel=1}, }, damage_groups = {fleshy=4}, } }) minetest.register_tool("tools:shovel_tin", { description = "Tin Shovel", inventory_image = "tool_tinshovel.png", tool_capabilities = { full_punch_interval = 2.05, max_drop_level = 0, groupcaps = { crumbly = {times={[1]=1.55*1.2, [2]=0.77*1.2, [3]=0.385*1.2}, uses = 56, maxlevel=1}, }, damage_groups = {fleshy=4}, } }) minetest.register_tool("tools:axe_tin", { description = "Tin Axe", inventory_image = "tool_tinaxe.png", tool_capabilities = { full_punch_interval = 2.3, max_drop_level = 0, groupcaps = { choppy = {times={[1]=4.2*1.2, [2]=2.1*1.2, [3]=1.05*1.2}, uses =62, maxlevel=1}, }, damage_groups = {fleshy=4}, } }) minetest.register_tool("tools:sword_tin", { description = "Tin Sword", inventory_image = "tool_tinsword.png", tool_capabilities = { full_punch_interval = 2.3, max_drop_level = 0, groupcaps = { snappy = {times={[1]=0.3*1.2, [2]=0.15*1.2, [3]=0.075*1.2}, uses = 42, maxlevel=1}, }, damage_groups = {fleshy = 6}, } }) -- tin tool crafts (again, this is seriously boring and repetitive, trust me.) minetest.register_craft({ output = 'tools:pick_tin', recipe = { {'tools:tin_ingot', 'tools:tin_ingot', 'tools:tin_ingot'}, {'', 'tools:stick', ''}, {'', 'tools:stick', ''}, } }) minetest.register_craft({ output = 'tools:shovel_tin', recipe = { {'tools:tin_ingot'}, {'tools:stick'}, {'tools:stick'}, } }) minetest.register_craft({ output = 'tools:axe_tin', recipe = { {'tools:tin_ingot', 'tools:tin_ingot'}, {'tools:tin_ingot', 'tools:stick'}, {'', 'tools:stick'}, } }) minetest.register_craft({ output = 'tools:sword_tin', recipe = { {'tools:tin_ingot'}, {'tools:tin_ingot'}, {'tools:stick'}, } }) -- bronze tools; mergin that ingots minetest.register_tool("tools:pick_bronze", { description = "Bronze Pickaxe", inventory_image = "tool_bronzepick.png", tool_capabilities = { full_punch_interval = 1.67, max_drop_level = 0, groupcaps = { cracky = {times={[1]=3.7, [2]=1.85, [3]=0.92}, uses=64, maxlevel=1}, }, damage_groups = {fleshy=4}, } }) minetest.register_tool("tools:shovel_bronze", { description = "Bronze Shovel", inventory_image = "tool_bronzehovel.png^[transformR90", tool_capabilities = { full_punch_interval = 1.67, max_drop_level = 0, groupcaps = { crumbly = {times={[1]=1.55, [2]=0.77, [3]=0.385}, uses = 66, maxlevel=1}, }, damage_groups = {fleshy=4}, } }) minetest.register_tool("tools:axe_bronze", { description = "Bronze Axe", inventory_image = "tool_bronzeaxe.png", tool_capabilities = { full_punch_interval = 1.67, max_drop_level = 0, groupcaps = { choppy = {times={[1]=4.2, [2]=2.1, [3]=1.05}, uses = 42, maxlevel=1}, }, damage_groups = {fleshy=5}, } }) minetest.register_tool("tools:sword_bronze", { description = "Bronze Sword", inventory_image = "tool_bronzesword.png", tool_capabilities = { full_punch_interval = 1.78, max_drop_level = 0, groupcaps = { snappy = {times={[1]=0.3, [2]=0.15, [3]=0.075}, uses = 32, maxlevel=1}, }, damage_groups = {fleshy = 6}, } }) -- bronze tool crafting (it is very easy to bypass steel and go staight to bronze) -- remind me to nerf herd this! minetest.register_craft({ output = 'tools:pick_bronze', recipe = { {'tools:bronze_ingot', 'tools:bronze_ingot', 'tools:bronze_ingot'}, {'', 'tools:stick', ''}, {'', 'tools:stick', ''}, } }) minetest.register_craft({ output = 'tools:shovel_bronze', recipe = { {'tools:bronze_ingot'}, {'tools:stick'}, {'tools:stick'}, } }) minetest.register_craft({ output = 'tools:axe_bronze', recipe = { {'tools:bronze_ingot', 'tools:bronze_ingot'}, {'tools:bronze_ingot', 'tools:stick'}, {'', 'tools:stick'}, } }) minetest.register_craft({ output = 'tools:sword_bronze', recipe = { {'tools:bronze_ingot'}, {'tools:bronze_ingot'}, {'tools:stick'}, } }) -- bronze extra tools minetest.register_tool("tools:bronze_hammer", { description = "Bronze Dighammer", groups = {sledge=1}, inventory_image = "tools_bronze_hammer.png", tool_capabilities = { full_punch_interval = 4.1, max_drop_level=0, groupcaps={ cracky = {times={[1]=3.7*2, [2]=1.85*2, [3]=0.92*2}, uses=34, maxlevel=1}, }, damage_groups = {fleshy=4}, }, }) minetest.register_craft({ output = "tools:bronze_hammer", recipe = { {"tools:bronze_ingot", "tools:bronze_ingot","tools:bronze_ingot"}, {"tools:bronze_ingot", "tools:bronze_ingot","tools:bronze_ingot"}, {"", "tools:stick",""} } }) minetest.register_tool("tools:bronze_sickle", { description = "Bronze Sickle", groups = {lumberaxe=1}, inventory_image = "tools_bronze_sickle.png", tool_capabilities = { full_punch_interval = 2.34, max_drop_level=0, groupcaps = { snappy = {times={[1]=0.3*2, [2]=0.15*2, [3]=0.075*2}, uses = 36, maxlevel=1}, }, damage_groups = {fleshy=6}, }, }) minetest.register_craft({ output = "tools:bronze_sickle", recipe = { {'tools:bronze_ingot', 'tools:bronze_ingot', 'tools:bronze_ingot'}, {'tools:bronze_ingot', '', 'tools:bronze_ingot'}, {'', '', 'tools:stick'}, } }) minetest.register_tool("tools:bronze_battleaxe", { description = "Bronze Battle Axe", inventory_image = "tools_steel_battleaxe.png", tool_capabilities = { full_punch_interval = 2.05*2, max_drop_level = 0, groupcaps = { choppy = {times={[1]=4.2*2, [2]=2.1*2, [3]=1.05*2}, uses = 42*2, maxlevel=1}, }, damage_groups = {fleshy=9}, }, }) minetest.register_craft({ output = 'tools:bronze_battleaxe', recipe = { {'tools:axe_bronze', 'farming:string', 'tools:axe_bronze'}, {'', 'tools:stick', ''}, } }) minetest.register_tool("tools:bronze_dirt_mover", { description = "Bronze Dirt Mover", groups = {sledge=1}, inventory_image = "tools_bronze_dirt_mover.png", tool_capabilities = { full_punch_interval = 2.55, max_drop_level = 0, groupcaps = { crumbly = {times={[1]=1.55*2, [2]=0.77*2, [3]=0.385*2}, uses = 40, maxlevel=1}, }, damage_groups = {fleshy=3}, }, }) minetest.register_craft({ output = "tools:steel_dirt_mover", recipe = { {'tools:steel_ingot', 'tools:steel_ingot', 'tools:steel_ingot'}, {'tools:steel_ingot', 'tools:stick', 'tools:steel_ingot'}, {'', 'tools:stick', ''}, } }) -- mese stuff --mese pick minetest.register_tool("tools:pick_mese", { description = "Mese Pickaxe", inventory_image = "tool_mesepick.png", tool_capabilities = { full_punch_interval = 1.67, max_drop_level = 0, groupcaps = { cracky = {times={[1]=1.85, [2]=0.92, [3]=0.46}, uses=128, maxlevel=1}, hardness = {times={[1]=6, [2]=3, [3]=1.5}, uses=64, maxlevel=1}, }, damage_groups = {fleshy=7}, } }) minetest.register_tool("tools:shovel_mese", { description = "Mese Shovel", inventory_image = "tool_meseshovel.png^[transformR90", tool_capabilities = { full_punch_interval = 1.67, max_drop_level = 0, groupcaps = { crumbly = {times={[1]=0.77, [2]=0.385, [3]=0.192}, uses = 122, maxlevel=1}, }, damage_groups = {fleshy=5}, } }) minetest.register_tool("tools:axe_mese", { description = "Mese Axe", inventory_image = "tool_meseaxe.png", tool_capabilities = { full_punch_interval = 1.67, max_drop_level = 0, groupcaps = { choppy = {times={[1]=2.1, [2]=1.05, [3]=0.525}, uses = 42, maxlevel=1}, }, damage_groups = {fleshy=8}, }, }) minetest.register_tool("tools:sword_mese", { description = "Mese Sword", inventory_image = "tool_mesesword.png", tool_capabilities = { full_punch_interval = 1.78, max_drop_level = 0, groupcaps = { snappy = {times={[1]=0.15, [2]=0.075, [3]=0.0375}, uses = 32, maxlevel=1}, }, damage_groups = {fleshy = 12}, }, }) -- mese tool crafting minetest.register_craft({ output = 'tools:pick_mese', recipe = { {'ores:mese_crystal', 'ores:mese_crystal', 'ores:mese_crystal'}, {'', 'tools:stick', ''}, {'', 'tools:stick', ''}, } }) minetest.register_craft({ output = 'tools:shovel_mese', recipe = { {'ores:mese_crystal'}, {'tools:stick'}, {'tools:stick'}, } }) minetest.register_craft({ output = 'tools:axe_mese', recipe = { {'ores:mese_crystal', 'ores:mese_crystal'}, {'ores:mese_crystal', 'tools:stick'}, {'', 'tools:stick'}, } }) minetest.register_craft({ output = 'tools:sword_mese', recipe = { {'ores:mese_crystal'}, {'ores:mese_crystal'}, {'tools:stick'}, } })
local opts = { noremap = true, silent = true } -- Shorten function name local keymap = vim.api.nvim_set_keymap -- Set <Leader> key --vim.g.mapleader = "," --Remap space as leader key keymap("", "<Space>", "<Nop>", opts) vim.g.mapleader = " " vim.g.maplocalleader = " " keymap("", ",", "<leader>", { silent = true }) -- Modes -- Short-name Affected modes Help page Vimscript equivalent -- '' Normal, Visual, Select, Operator-pending mapmode-nvo :map -- 'n' Normal mapmode-n :nmap -- 'v' Visual and Select mapmode-v :vmap -- 's' Select mapmode-s :smap -- 'x' Visual mapmode-x :xmap -- 'o' Operator-pending mapmode-o :omap -- '!' Insert and Command-line mapmode-ic :map! -- 'i' Insert mapmode-i :imap -- 'l' Insert, Command-line, Lang-Arg mapmode-l :lmap -- 'c' Command-line mapmode-c :cmap -- 't' Terminal mapmode-t :tmap -- Normal -- -- Disable going into command-line window keymap("n", "q:", "<Nop>", opts) -- Change j and k to move through wrapped lines keymap("n", "j", "gj", opts) keymap("n", "k", "gk", opts) -- Jump to tag in a new split keymap("n", "<C-\\>", "<C-w>v<C-]>", opts) -- Toggle spelling keymap("n", "<leader>sp", ":setlocal spell!<CR>", opts) -- Rebuild .spl file from 'spellfile' keymap("n", "<leader>sP", ":mkspell! " .. vim.fn.stdpath "config" .. "/spell/dictionary.utf-8.add<CR>", opts) -- Clear Search highlighting when hitting 'return' -- This unsets the 'last search pattern' register keymap("n", "<CR>", ":noh<CR><CR>", opts) -- Toggle [i]nvisible characters keymap("n", "<leader>i", ":set list!<CR>", opts) -- Make zO recursively open whatever fold we're in, even if it's partially open. keymap("n", "z0", "zcz0", opts) -- Save with <C-s> keymap("n", "<C-s>", ":silent update<CR>", opts) keymap("i", "<C-s>", "<Esc>:silent update<CR>", opts) keymap("v", "<C-s>", "<Esc>:silent update<CR>gv", opts) -- Remove all trailing whitespace by pressing <leader>ww -- uses mark 'z' keymap("n", "<leader>ww", [[mz:let _s=@/<Bar>:%s/\s\+$//e<Bar>:let @/=_s<Bar><CR>`z]], opts) -- Reload init.lua keymap("n", "<leader>sv", ":ReloadConfig<CR>", opts) -- Toggle Numbers vim.cmd [[ function! NumberToggle() if(&relativenumber == 1 && &number == 1) setlocal nonumber setlocal norelativenumber elseif (&number == 1) setlocal relativenumber else setlocal number endif endfunc ]] keymap("n", "<leader>n", ":call NumberToggle()<CR>", opts) -- "Uppercase word" mapping -- -- This mapping allows you to press <c-u> in insert mode to convert the current -- word to uppercase. It's handy when you're writing names of constants and -- don't want to use Capslock. -- -- To use it you type the name of the constant in lowercase. While your -- cursor is at the end of the word, press <c-u> to uppercase it, and then -- continue happily on your way: -- -- cursor -- v -- max_connections_allowed| -- <c-u> -- MAX_CONNECTIONS_ALLOWED| -- ^ -- cursor -- -- It works by exiting out of insert mode using gUiw to uppercase inside the -- current word, then gi to enter insert mode at the end of the word. keymap("i", "<C-u>", "<Esc>gUiwgi", opts) -- because completion breaks <C-u> keymap("i", "<C-g><C-u>", "<Esc>gUiwgi", opts) -- Formatting keymap("n", "Q", "gqip", opts) keymap("v", "Q", "gq", opts) -- Toggle Wrap keymap("n", "<leader>W", ":set wrap!<CR>", opts) -- highlight last inserted text keymap("n", "gV", "`[v`]", opts) -- Better window navigation -- keymap("n", "<C-h>", "<C-w>h", opts) -- keymap("n", "<C-j>", "<C-w>j", opts) -- keymap("n", "<C-k>", "<C-w>k", opts) -- keymap("n", "<C-l>", "<C-w>l", opts) keymap("n", "<leader>e", ":Lex 30<cr>", opts) -- Resize with arrows keymap("n", "<C-Up>", ":resize +2<CR>", opts) keymap("n", "<C-Down>", ":resize -2<CR>", opts) keymap("n", "<C-Left>", ":vertical resize -2<CR>", opts) keymap("n", "<C-Right>", ":vertical resize +2<CR>", opts) -- Navigate buffers keymap("n", "<S-l>", ":bnext<CR>", opts) keymap("n", "<S-h>", ":bprevious<CR>", opts) -- Visual -- -- Stay in indent mode keymap("v", "<", "<gv", opts) keymap("v", ">", ">gv", opts) -- Move text up and down keymap("v", "<A-j>", ":m .+1<CR>==", opts) keymap("v", "<A-k>", ":m .-2<CR>==", opts) keymap("v", "p", '"_dP', opts) -- Visual Block -- -- Move text up and down keymap("x", "J", ":move '>+1<CR>gv-gv", opts) keymap("x", "K", ":move '<-2<CR>gv-gv", opts) keymap("x", "<A-j>", ":move '>+1<CR>gv-gv", opts) keymap("x", "<A-k>", ":move '<-2<CR>gv-gv", opts)
local call = {} local mt = {} function mt.__call(self, bus) if not self.timeout then self.timeout = -1 end return bus:call(self.name, self.path, self.interface, self.member, self.timeout, self.args) end mt.__index = { set = function(self, name, path, interface, member, timeout, args) self.name = name self.path = path self.interface = interface self.member = member self.args = args self.timeout = timeout end } function call.new() local obj = {} setmetatable(obj, mt) return obj end return call
local util = require("prosesitter/util") local log = require("prosesitter/log") local state = require("prosesitter/state") local defaults = require("prosesitter/config/defaults") local Issue = require("prosesitter/linter/issues").Issue local M = {} M.url = "set in start_server function" function M.setup_binairy() vim.fn.mkdir(util.plugin_path, "p") local install_script = [=====[ set -e GREEN='\033[0;32m' NC='\033[0m' # No Color tmp="/tmp/prosesitter" mkdir -p $tmp mkdir -p languagetool url="https://languagetool.org/download/LanguageTool-stable.zip" printf "${GREEN}downloading languagetool${NC}\n" curl --location --output "$tmp/langtool.zip" $url unzip -q "$tmp/langtool.zip" -d languagetool # get languagetool-server.jar and its dependencies out of the version specific # folder into one we can depend on mv languagetool/*/* languagetool printf "${GREEN}done installing languagetool, restart nvim for changes to take effect${NC}\n" ]=====] local ok_msg = "[prosesitter] installed language tool" local err_msg = "[prosesitter] could not setup language tool" util:shell_in_new_window(install_script, ok_msg, err_msg) end function M.setup_cfg() local exists = 1 if vim.fn.filereadable(util.plugin_path .. "/langtool.cfg") ~= exists then local file = io.open(util.plugin_path .. "/langtool.cfg", "w") if file == nil then print("fatal error: could not open/create fresh LanguageTool config") end file:write(defaults.langtool_cfg) file:flush() file:close() end end local function mark_rdy_if_responding(on_event) local on_exit = function(text) if not state.langtool_running then if text ~= nil then if string.starts(text, '{"software":{"name":"LanguageTool"') then state.langtool_running = true for buf in state:attached() do on_event:lint_everything(buf) end end end end end local async = require("prosesitter/linter/check/async_cmd") local do_check = function() if not M.langtool_running then local args = M:curl_args("") async.dispatch_with_stdin("hi", "curl", args, on_exit) end end for timeout = 0, 15, 1 do vim.defer_fn(do_check, timeout * 1000) end end -- using depedency injection here (on_event) to break -- dependency loop function M.start_server(on_event, cfg) local on_exit = function() M.langtool_running = false end M.url = "http://localhost:" .. cfg.langtool_port .. "/v2/check" local res = vim.fn.jobstart({ "java", "-cp", cfg.langtool_bin, "org.languagetool.server.HTTPServer", "--config", cfg.langtool_cfg, "--port", cfg.langtool_port, }, { on_exit = on_exit, }) if res > 0 then mark_rdy_if_responding(on_event) else error("could not start language server using path: " .. cfg.langtool_bin) log.error("could not start language server using path: " .. cfg.langtool_bin) end end local id_to_severity = { CAPITALIZATION = "error", COLLOCATIONS = "warning", CONFUSED_WORDS = "warning", COMPOUNDING = "warning", CREATIVE_WRITING = "suggestion", -- not active by default GRAMMAR = "error", MISC = "warning", NONSTANDARD_PHRASES = "warning", PLAIN_ENGLISH = "suggestion", -- not active by default TYPOS = "error", PUNCTUATION = "warning", REDUNDANCY = "suggestion", SEMANTICS = "warning", STYLE = "suggestion", -- disabled by us TEXT_ANALYSIS = "suggestion", -- not active by default TYPOGRAPHY = "warning", CASING = "error", WIKIPEDIA = "suggestion", --not active by default } function M.to_issue(problem, start_col, end_col) local issue = Issue.new() issue.msg = problem.message issue.severity = id_to_severity[problem.rule.category.id] issue.full_source = problem.rule.category.name..": "..problem.rule.id issue.replacements = problem.replacements issue.start_col = start_col issue.end_col = end_col return issue end function M:curl_args(disabled_rules) return { "--no-progress-meter", "--data-urlencode", "language=en-US", "--data-urlencode", "disabledCategories=STYLE", "--data-urlencode", "disabledRules="..disabled_rules, "--data-urlencode", "text@-", self.url, } end function M.add_spans(json) local problems = vim.fn.json_decode(json)["matches"] for _, res in ipairs(problems) do res.Span = { res.offset + 1, res.offset + res.length } end return problems end return M
local nodeStruct = {} function nodeStruct.decodeNodes(children) local res = {} for i, data in ipairs(children or {}) do local node = nodeStruct.decode(data) if node then table.insert(res, node) end end return res end function nodeStruct.decode(data) if data.__name == "node" then local res = { _type = "node" } res[1] = data.x res[2] = data.y return res end end function nodeStruct.encode(node) local res = {} res.__name = "node" res.x = node[1] res.y = node[2] return res end return nodeStruct
local basePath = (...):gsub('[^%.]+$', '') local Button = require(basePath .. "Button") local ToggleButton = Button:extend() function ToggleButton.release(self, dontFire, mx, my, isKeyboard) self.isPressed = false if not dontFire then self.isChecked = not self.isChecked if self.releaseFunc then self:releaseFunc(mx, my, isKeyboard) end end self.theme[self.themeType].release(self, dontFire) end return ToggleButton
--local ipairs = ipairs local util = { } function util.find_on_screen(s, n) for _, c in ipairs(s.clients) do if string.match(c.class, n) then return c end end return nil end return util
object_building_kashyyyk_frn_medal_display_case = object_building_kashyyyk_shared_frn_medal_display_case:new { } ObjectTemplates:addTemplate(object_building_kashyyyk_frn_medal_display_case, "object/building/kashyyyk/frn_medal_display_case.iff")
-- MUD container local json = require("cjson") local yang = require("mud.yang") local _M = {} local ietf_mud_type = yang.util.subClass("ietf_mud_type", yang.basic_types.container) ietf_mud_type_mt = { __index = ietf_mud_type } function ietf_mud_type:create(nodeName, mandatory) local new_inst = yang.basic_types.container:create(nodeName, mandatory) -- additional step: add the type name new_inst.typeName = "ietf-mud:mud" setmetatable(new_inst, ietf_mud_type_mt) new_inst:add_definition() return new_inst end function ietf_mud_type:add_definition() local c = yang.basic_types.container:create('ietf-mud:mud') c:add_node(yang.basic_types.uint8:create('mud-version', 'mud-version')) c:add_node(yang.basic_types.inet_uri:create('mud-url', 'mud-url', true)) c:add_node(yang.basic_types.date_and_time:create('last-update')) c:add_node(yang.basic_types.inet_uri:create('mud-signature', false)) c:add_node(yang.basic_types.uint8:create('cache-validity', false)) c:add_node(yang.basic_types.boolean:create('is-supported')) c:add_node(yang.basic_types.string:create('systeminfo', false)) c:add_node(yang.basic_types.string:create('mfg-name', false)) c:add_node(yang.basic_types.string:create('model-name', false)) c:add_node(yang.basic_types.string:create('firmware-rev', false)) c:add_node(yang.basic_types.inet_uri:create('documentation', false)) c:add_node(yang.basic_types.notimplemented:create('extensions', false)) local from_device_policy = yang.basic_types.container:create('from-device-policy') local access_lists = yang.basic_types.container:create('access-lists') local access_lists_list = yang.basic_types.list:create('access-list') -- todo: references access_lists_list:add_list_node(yang.basic_types.string:create('name')) access_lists:add_node(access_lists_list) -- this seems to be a difference between the example and the definition from_device_policy:add_node(access_lists) c:add_node(from_device_policy) local to_device_policy = yang.basic_types.container:create('to-device-policy') local access_lists = yang.basic_types.container:create('access-lists') local access_lists_list = yang.basic_types.list:create('access-list') -- todo: references access_lists_list:add_list_node(yang.basic_types.string:create('name')) access_lists:add_node(access_lists_list) -- this seems to be a difference between the example and the definition to_device_policy:add_node(access_lists) c:add_node(to_device_policy) -- it's a presence container, so we *replace* the base node list instead of adding to it self.yang_nodes = c.yang_nodes for i,n in pairs(self.yang_nodes) do n:setParent(self) end end -- class ietf_mud_type local mud_container = yang.util.subClass("mud_container", yang.basic_types.container) mud_container_mt = { __index = mud_container } function mud_container:create(nodeName, mandatory) local new_inst = yang.basic_types.container:create(nodeName, mandatory) new_inst.typeName = "mud_container" setmetatable(new_inst, mud_container_mt) new_inst:add_definition() return new_inst end function mud_container:add_definition() self:add_node(ietf_mud_type:create('ietf-mud:mud', true)) self:add_node(yang.complex_types.ietf_access_control_list:create('ietf-access-control-list:acls', true)) end -- mud_container local mud = {} mud_mt = { __index = mud } -- create an empty mud container function mud:create() local new_inst = {} setmetatable(new_inst, mud_mt) -- default values and types go here new_inst.mud_container = mud_container:create('mud-container', true) return new_inst end function mud:parseJSON(json_str, file_name) local json_data, err = json.decode(json_str); if json_data == nil then error(err) end --local result = self.mud_container:fromData_noerror(yang.util.deepcopy(json_data)) local result = self.mud_container:fromData_noerror(json_data) if json_data['ietf-mud:mud'] == nil then if file_name == nil then file_name = "<unknown>" end error("Top-level node 'ietf-mud:mud' not found in " .. file_name) end end -- parse from json file function mud:parseFile(json_file_name) local file, err = io.open(json_file_name) if file == nil then error(err) end local contents = file:read( "*a" ) io.close( file ) self:parseJSON(contents) end function mud:get_mud_url() return yang.findSingleNode(self.mud_container, "/ietf-mud:mud/mud-url"):getValue() end function mud:get_last_update() return yang.findSingleNode(self.mud_container, "/ietf-mud:mud/last-update"):getValue() end function mud:get_cache_validity() return yang.findSingleNode(self.mud_container, "/ietf-mud:mud/cache-validity"):getValue() end function mud:get_is_supported() return yang.findSingleNode(self.mud_container, "/ietf-mud:mud/is-supported"):getValue() end function mud:get_systeminfo() return yang.findSingleNode(self.mud_container, "/ietf-mud:mud/systeminfo"):getValue() end function mud:get_acls() return yang.findSingleNode(self.mud_container, "/ietf-access-control-list:acls/acl"):getValue() end function mud:get_from_device_policy_acls() return yang.findSingleNode(self.mud_container, "/ietf-mud:mud/from-device-policy/access-lists/access-list"):getValue() end function mud:get_to_device_policy_acls() return yang.findSingleNode(self.mud_container, "/ietf-mud:mud/to-device-policy/access-lists/access-list"):getValue() end _M.mud = mud return _M
NUM_VALUES_OUT = 1024 * 41 function receive(message) if(message.type == "fake_sensor_value") then --- print highest delay from publication to this stage processing_delay = calculate_time_diff(message.time_sec, message.time_nsec) --testbed_log_integer("processing_delay", processing_delay) store[#store+1] = {message.value, message.num_values} collected_values = collected_values + message.num_values if message.time_sec < min_sec or (message.time_sec == min_sec and message.time_nsec < min_nsec) then min_sec = message.time_sec min_nsec = message.time_nsec end if(collected_values >= NUM_VALUES_OUT) then sum = 0 for i, value in pairs(store) do sum = sum + value[1]*value[2] end local pub = Publication.new( "type", "fake_sensor_value", "value", sum / collected_values, "aggregation_level", "building", "num_values", collected_values, "time_sec", min_sec, "time_nsec", min_nsec ) pub["building"] = location_info["building"] publish(pub) reset_collection_state() end end if(message.type == "init") then print("INIT Aggregator") location_info = {} location_count = 0 reset_collection_state() publish( Publication.new( "type", "label_get", "node_id", node_id, "key", "building" ) ) publish( Publication.new( "type", "label_get", "node_id", node_id, "key", "floor" ) ) publish( Publication.new( "type", "label_get", "node_id", node_id, "key", "wing" ) ) publish( Publication.new( "type", "label_get", "node_id", node_id, "key", "access_1" ) ) publish( Publication.new( "type", "label_get", "node_id", node_id, "key", "room" ) ) end if(message.type == "label_response") then print("LABEL Response "..message.key.." - "..message.value) if(not location_info[message.key]) then location_count = location_count + 1 end location_info[message.key] = message.value if(location_count == 5) then print("READY Aggregator") subscription = {type="fake_sensor_value"} subscription["building"] = location_info["building"] subscription["aggregation_level"] = "node" subscribe(subscription) end end end function reset_collection_state() collected_values = 0 store = {} min_sec = 0x7FFFFFFF min_nsec = 0x7FFFFFFF end
---------------------------------------- -- Campaign global ---------------------------------------- require("scripts/globals/teleports") ---------------------------------------- -- ------------------------------------------------------------------- -- getMedalRank() -- Returns the numerical Campaign Medal of the player. -- ------------------------------------------------------------------- function getMedalRank(player) local rank = 0 local medals = { 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943 } while (player:hasKeyItem(medals[rank + 1]) == true) do rank = rank + 1 end return rank end -- ------------------------------------------------------------------- -- get[nation]NotesItem() -- Returns the item ID and cost of the Allied Notes indexed item -- (the same value as that used by the vendor event) -- Format: -- ListName_AN_item[optionID] = itemID -- ItemName -- ListName_AN_price[optionID] = cost -- ItemName -- ------------------------------------------------------------------- function getSandOriaNotesItem(i) local SandOria_AN = { [2] = {id = 15754, price = 980}, -- Sprinter's Shoes [258] = {id = 5428, price = 10}, -- Scroll of Instant Retrace [514] = {id = 14584, price = 1500}, -- Iron Ram jack coat [770] = {id = 14587, price = 1500}, -- Pilgrim Tunica [1026] = {id = 16172, price = 4500}, -- Iron Ram Shield [1282] = {id = 15841, price = 5000}, -- Recall Ring: Jugner [1538] = {id = 15842, price = 5000}, -- Recall Ring: Pashow [1794] = {id = 15843, price = 5000}, -- Recall Ring: Meriphataud [2050] = {id = 10116, price = 2000}, -- Cipher: Valaineral -- Stars Service [18] = {id = 14581, price = 15000}, -- Iron Ram Chainmain [274] = {id = 15005, price = 10500}, -- Iron Ram Mufflers [530] = {id = 15749, price = 10500}, -- Iron Ram Sollerets [786] = {id = 16141, price = 10500}, -- Iron Ram Helm [1042] = {id = 16312, price = 10500}, -- Iron Ram Breeches -- Emblems Service [34] = {id = 16312, price = 30000}, -- Iron Ram Horn [290] = {id = 16312, price = 30000}, -- Iron Ram Lance [546] = {id = 16312, price = 30000}, -- Iron Ram Pick [802] = {id = 16312, price = 60000}, -- Iron Ram Sallet [1058] = {id = 16312, price = 60000}, -- Iron Ram Dastanas -- Wings Service [50] = {id = 15755, price = 75000}, -- Iron Ram Greaves [306] = {id = 16315, price = 75000}, -- Iron Ram Hose -- Medals Service [66] = {id = 15844, price = 45000}, -- Patronus Ring [322] = {id = 15966, price = 45000}, -- Fox Earring [578] = {id = 15961, price = 45000}, -- Temple Earring [834] = {id = 15934, price = 45000}, -- Crimson Belt [1090] = {id = 19041, price = 45000}, -- Rose Strap [1346] = {id = 15488, price = 112500}, -- Iron Ram Hauberk [1602] = {id = 11356, price = 15000}, -- Royal Guard Livery -- Medal of Altana [82] = {id = 17684, price = 150000}, -- Griffinclaw [338] = {id = 11636, price = 75000} -- Royal Knight Sigil Ring } local item = SandOria_AN[i] return item.id, item.price end function getBastokNotesItem(i) local Bastok_AN = { [2] = {id = 15754, price = 980}, -- Sprinter's Shoes [258] = {id = 5428, price = 10}, -- Scroll of Instant Retrace [514] = {id = 14585, price = 1500}, -- Fourth Tunica [770] = {id = 14587, price = 1500}, -- Pilgrim Tunica [1026] = {id = 18727, price = 4500}, -- Fourth Gun [1282] = {id = 15841, price = 5000}, -- Recall Ring: Jugner [1538] = {id = 15842, price = 5000}, -- Recall Ring: Pashow [1794] = {id = 15843, price = 5000}, -- Recall Ring: Meriphataud [2050] = {id = 10116, price = 2000}, -- Cipher: Valaineral -- Stars Service [18] = {id = 14582, price = 15000}, -- Fourth Cuirass [274] = {id = 15006, price = 10500}, -- Fourth Gauntlets [530] = {id = 15750, price = 10500}, -- Fourth Sabatons [786] = {id = 16142, price = 10500}, -- Fourth Armet [1042] = {id = 16313, price = 10500}, -- Fourth Cuisses -- Emblems Service [34] = {id = 18494, price = 30000}, -- Fourth Toporok [290] = {id = 18854, price = 30000}, -- Fourth Mace [546] = {id = 18946, price = 30000}, -- Fourth Zaghnal [802] = {id = 16147, price = 60000}, -- Fourth Haube [1058] = {id = 15010, price = 60000}, -- Fourth Hentzes -- Wings Service [50] = {id = 15756, price = 75000}, -- Fourth Schuhs [306] = {id = 16316, price = 75000}, -- Fourth Schoss -- Medals Service [66] = {id = 16291, price = 45000}, -- Shield Collar [322] = {id = 18734, price = 45000}, -- Sturm's Report [578] = {id = 18735, price = 45000}, -- Sonia's Plectrum [834] = {id = 16292, price = 45000}, -- Bull Necklace [1090] = {id = 16258, price = 45000}, -- Arrestor Mantle [1346] = {id = 14589, price = 112500}, -- Fourth Division Brunne [1602] = {id = 11357, price = 15000}, -- Mythril Musketeer Livery -- Medal of Altana [82] = {id = 17685, price = 150000}, -- Lex Talionis [338] = {id = 11545, price = 75000} -- Fourth Mantle } local item = Bastok_AN[i] return item.id, item.price end function getWindurstNotesItem(i) local Windurst_AN = { [2] = {id = 15754, price = 980}, -- Sprinter's Shoes [258] = {id = 5428, price = 10}, -- Scroll of Instant Retrace [514] = {id = 14586, price = 1500}, -- Cobra Tunica [770] = {id = 14587, price = 1500}, -- Pilgrim Tunica [1026] = {id = 19150, price = 4500}, -- Cobra CLaymore [1282] = {id = 15841, price = 5000}, -- Recall Ring: Jugner [1538] = {id = 15842, price = 5000}, -- Recall Ring: Pashow [1794] = {id = 15843, price = 5000}, -- Recall Ring: Meriphataud [2050] = {id = 10116, price = 2000}, -- Cipher: Valaineral -- Stars Service [18] = {id = 14583, price = 15000}, -- Cobra Coat [274] = {id = 15007, price = 10500}, -- Cobra Cuffs [530] = {id = 15751, price = 10500}, -- Cobra Pigaches [786] = {id = 16143, price = 10500}, -- Cobra Hat [1042] = {id = 16314, price = 10500}, -- Cobra Slops -- Emblems Service [34] = {id = 18756, price = 30000}, -- Cobra Unit Baghnakhs [290] = {id = 19100, price = 30000}, -- Cobra Unit Knife [546] = {id = 18728, price = 30000}, -- Cobra Unit Bow [802] = {id = 16149, price = 60000}, -- Cobra Unit Cloche [1058] = {id = 15011, price = 60000}, -- Cobra Unit Mittens -- Wings Service [50] = {id = 15757, price = 75000}, -- Cobra Unit Leggings [306] = {id = 16317, price = 75000}, -- Cobra Unit Subligar [580] = {id = 15758, price = 75000}, -- Cobra Unit Crackows [1001] = {id = 16318, price = 75000}, -- Cobra Unit Trews -- Medals Service [66] = {id = 15935, price = 45000}, -- Capricornian Rope [322] = {id = 15936, price = 45000}, -- Earthly Belt [578] = {id = 16293, price = 45000}, -- Cougar Pendant [834] = {id = 16294, price = 45000}, -- Crocodile Collar [1090] = {id = 19041, price = 45000}, -- Ariesian Grip [1346] = {id = 19042, price = 112500}, -- Cobra Unit Harness [1602] = {id = 11358, price = 15000}, -- Patriarch Protector Livery -- Medal of Altana [82] = {id = 17684, price = 150000}, -- Samudra [338] = {id = 11636, price = 75000} -- Mercenary Major Charm } local item = Windurst_AN[i] return item.id, item.price end -- ------------------------------------------------------------------- -- getSigilTimeStamp(player) -- This is for the time-stamp telling player what day/time the -- effect will last until, NOT the actual status effect duration. -- ------------------------------------------------------------------- function getSigilTimeStamp(player) local timeStamp = 0 -- zero'd till math is done. -- TODO: calculate time stamp for menu display of when it wears off return timeStamp end -- TODO: -- Past nation teleport
local cmdheight = 2 local indent = 2 local vScrolloff = 4 local hScrolloff = 10 vim.cmd('syntax enable') vim.cmd('syntax on') vim.cmd('filetype plugin indent on') vim.o.updatetime = 250 vim.o.cmdheight = cmdheight vim.o.winheight = cmdheight vim.o.winminheight = cmdheight vim.o.winminwidth = cmdheight * 2 vim.o.autowrite = true vim.o.ignorecase = true vim.o.smartcase = true vim.o.timeoutlen = 400 vim.o.hidden = true vim.o.backup = false vim.o.shiftround = true vim.o.splitbelow = true vim.o.splitright = true vim.o.showmode = false vim.o.termguicolors = true vim.o.scrolloff = hScrolloff vim.o.sidescrolloff = vScrolloff vim.o.fileformats = 'unix,mac,dos' vim.o.completeopt = 'menuone,noselect' vim.o.wildmode = 'longest:list:full' vim.o.shortmess = vim.o.shortmess .. 'c' vim.o.spellsuggest = 'fast,12' vim.o.spelloptions = 'camel' vim.o.undodir = rv.undoDir vim.o.undofile = true vim.bo.undofile = true vim.o.mouse = 'nv' -- "n-v-c-sm:block,i-ci-ve:ver25,r-cr-o:hor20" -- local cur = 'n-v-c-sm:block-Cursor,i:ver100-iCursor,n-v-c-sm:blinkon0' -- vim.o.guicursor=cur vim.b.swapfile = false vim.bo.swapfile = false vim.bo.tabstop = indent vim.bo.shiftwidth = indent vim.bo.expandtab = true vim.bo.smartindent = true vim.o.numberwidth = 3 vim.wo.cursorline = true vim.wo.number = true vim.wo.relativenumber = true vim.wo.signcolumn = 'yes:2' vim.wo.wrap = false vim.wo.foldmethod = 'expr' vim.wo.foldexpr = 'nvim_treesitter#foldexpr()' vim.wo.foldcolumn = '0' vim.wo.foldenable = false -- A few custom commands that don't make me feel my -- inability to let go of the shift key in time too much. vim.cmd('command Q quit') vim.cmd('command Wq write | quit') local clipName local clipProvCopy local clipProvPaste local clipCache if rv.isWindows then vim.cmd([[ let &shell = has('win32') ? 'powershell' : 'pwsh' set shellquote= shellpipe=\| shellxquote= set shellcmdflag=-NoLogo\ -NoProfile\ -ExecutionPolicy\ RemoteSigned\ -Command set shellredir=\|\ Out-File\ -Encoding\ UTF8 ]]) end if rv.isWsl or rv.isWindows then clipName = 'windows-clipboard' clipProvCopy = { 'clip.exe' } clipProvPaste = { 'pbpaste.exe', '--lf' } clipCache = 1 elseif rv.isMacOs then clipName = 'macos-clipboard' clipProvCopy = { 'pbcopy' } clipProvPaste = { 'pbpaste' } clipCache = 0 end if clipProvCopy then vim.g.clipboard = { name = clipName, copy = { ['+'] = clipProvCopy, ['*'] = clipProvCopy }, paste = { ['+'] = clipProvPaste, ['*'] = clipProvPaste }, cache_enabled = clipCache, } end
Locales['de'] = { ['storm_leave'] = "Du bist aus dem Sturm herausgekommen", ['storm_inside'] = "Du bist in den Sturm eingetreten", ['storm_created'] = "Der Sturm mit dem Namen von wurde erfolgreich erstellt", ['storm_notcreated'] = "Der Sturm wurde nicht erstellt, stellen Sie sicher, dass Sie den Befehl richtig schreiben", ['storm_notfound'] = "Es gibt keinen Sturm mit diesem Namen" }
--[[ MTA Role Play (mta-rp.pl) Autorzy poniższego kodu: - Patryk Adamowicz <patrykadam.dev@gmail.com> Discord: PatrykAdam#1293 Link do githuba: https://github.com/PatrykAdam/mtarp --]] local screenX, screenY = guiGetScreenSize() local scaleX, scaleY = math.max(0.6, (screenX / 1920)), math.max(0.6, (screenY / 1080)) local hud = {} local playerDamage = {} function hud.start() hud.box = {} hud.box[1] = {W = 109 * scaleX, H = 94 * scaleX, X = screenX - 341 * scaleX, Y = 20 * scaleX, color = {37, 37, 37, 150}} hud.box[2] = {W = 216 * scaleX, H = 94 * scaleX, X = hud.box[1].X + hud.box[1].W + 1, Y = hud.box[1].Y, color = {37, 37, 37, 150}} hud.box[3] = {W = 73 * scaleX, H = 42 * scaleX, X = hud.box[1].X, Y = hud.box[1].Y + hud.box[1].H + 1, color = {37, 37, 37, 150}} hud.box[4] = {W = 73 * scaleX, H = 42 * scaleX, X = hud.box[3].X + hud.box[3].W + 1, Y = hud.box[3].Y, color = {37, 37, 37, 150}} hud.box[5] = {W = 177 * scaleX, H = 42 * scaleX, X = hud.box[4].X + hud.box[4].W + 1, Y = hud.box[3].Y, color = {37, 37, 37, 150}} hud.box[6] = {W = 2 * scaleX, H = 94 * scaleX, X = hud.box[1].X - 2 * scaleX, Y = hud.box[1].Y, color = {163, 162, 160, 255}} hud.box[7] = {W = 2 * scaleX, H = 42 * scaleX, X = hud.box[3].X - 2 * scaleX, Y = hud.box[3].Y, color = {163, 162, 160, 255}} hud.icon = {} hud.icon[1] = {W = 25 * scaleX, H = 24 * scaleX, X = hud.box[3].X + 5 * scaleX, Y = hud.box[3].Y + (hud.box[3].H - 24 * scaleX)/2, image = 'assets/hud_hp.png'} hud.icon[2] = {W = 28 * scaleX, H = 28 * scaleX, X = hud.box[4].X + 5 * scaleX, Y = hud.box[4].Y + (hud.box[4].H - 28 * scaleX)/2, image = 'assets/hud_armor.png'} hud.font = {} hud.font[1] = dxCreateFont( "assets/Lato-Light.ttf", 15 * scaleX ) hud.font[2] = dxCreateFont( "assets/Lato-Light.ttf", 12 * scaleX ) hud.active = getElementData(localPlayer, "player:logged") end addEventHandler( "onClientResourceStart", resourceRoot, hud.start ) function hud.draw() if hud.active and getElementData(localPlayer, "player:logged") and not getElementData(localPlayer, "busTravel") then for i, v in ipairs(hud.box) do dxDrawRectangle( v.X, v.Y, v.W, v.H, (playerDamage[localPlayer] and playerDamage[localPlayer] + 2000 > getTickCount() and i == 3) and tocolor(255, 0, 0, 150) or tocolor(unpack(v.color)) ) end for i, v in ipairs(hud.icon) do dxDrawImage( v.X, v.Y, v.W, v.H, v.image ) end local handgun = getElementData(localPlayer, "weapon:handgun" ) if handgun then local hslot = getSlotFromWeapon( handgun ) if hslot then dxDrawText( getPedAmmoInClip(localPlayer, hslot).."/"..getPedTotalAmmo(localPlayer, hslot) - getPedAmmoInClip(localPlayer, hslot), hud.box[1].X, hud.box[1].Y, hud.box[1].X + hud.box[1].W, hud.box[1].Y + 30 * scaleX, tocolor(163, 162, 160), 1.0, hud.font[1], "center", "bottom" ) end end local long = getElementData(localPlayer, "weapon:long" ) if long then local lslot = getSlotFromWeapon( long ) if lslot then dxDrawText( getPedAmmoInClip(localPlayer, lslot).."/"..getPedTotalAmmo(localPlayer, lslot) - getPedAmmoInClip(localPlayer, lslot), hud.box[2].X, hud.box[2].Y, hud.box[2].X + hud.box[2].W, hud.box[2].Y + 30 * scaleX, tocolor(163, 162, 160), 1.0, hud.font[1], "center", "bottom" ) end end dxDrawText( math.floor(getElementData( localPlayer, "player:health")), hud.box[3].X + hud.icon[1].W + 5 * scaleX, hud.box[3].Y, hud.box[3].X + hud.box[3].W, hud.box[3].Y + hud.box[3].H, tocolor(163, 162, 160), 1.0, hud.font[2], "center", "center" ) dxDrawText( getPedArmor( localPlayer ), hud.box[4].X + hud.icon[2].W + 5 * scaleX, hud.box[4].Y, hud.box[4].X + hud.box[4].W, hud.box[4].Y + hud.box[4].H, tocolor(163, 162, 160), 1.0, hud.font[2], "center", "center" ) dxDrawText( "$", hud.box[5].X + 5 * scaleX, hud.box[5].Y, 0, hud.box[5].Y + hud.box[5].H, tocolor(163, 162, 160), 1.0, hud.font[1], "left", "center" ) dxDrawText( moneyFormat(getElementData(localPlayer, "player:money")), hud.box[5].X + 30 * scaleX, hud.box[5].Y, hud.box[5].X + hud.box[5].W, hud.box[5].Y + hud.box[5].H, tocolor(163, 162, 160), 1.0, hud.font[1], "center", "center") dxDrawImage( hud.box[1].X, hud.box[1].Y + 30 * scaleX - (handgun and 0 or 15 * scaleX), hud.box[1].W, hud.box[1].H - 30 * scaleX, "assets/".. (handgun == false and 0 or handgun) ..".png" ) dxDrawImage( hud.box[2].X, hud.box[2].Y + 30 * scaleX - (long and 0 or 15 * scaleX), hud.box[2].W, hud.box[2].H - 30 * scaleX, "assets/".. (long == false and "0l" or long) ..".png" ) end end addEventHandler( "onClientRender", root, hud.draw ) function showHUD(boolean) if type(boolean) == 'boolean' then hud.active = boolean return end hud.active = false end addEvent('showHUD', true) addEventHandler( 'showHUD', localPlayer, showHUD ) function damage(x, y, z, loss) if loss < 1 then return end if getElementType( source ) == "player" then local time = getTickCount() playerDamage[source] = time end end addEventHandler( "onClientPlayerDamage", root, damage ) function moneyFormat(amount) local formatted = amount while true do formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2') if (k==0) then break end end return formatted end
pawns = {}; pawns.settings = {}; pawns.settings["update_flags"]= {}; pawns.settings["attack_anything"] = false; pawns.settings["max_party_icons"] = 7; pawns.settings["party_icons_size"] = 12; pawns.settings["max_number_buff"] = 50; pawns.settings["shorten_number_of_buffs"] = 4; pawns.settings["update_flags"]["updateName"] = true; pawns.settings["update_flags"]["updateAlive"] = true; pawns.settings["update_flags"]["updateHP"] = true; pawns.settings["update_flags"]["updateClass"] = true; pawns.settings["update_flags"]["updateMP"] = true; pawns.settings["update_flags"]["updateLastHP"] = true; pawns.settings["update_flags"]["updateRace"] = true; pawns.settings["update_flags"]["updateLevel"] = true; pawns.funcs["pawn_buff_resolution"] = function( ID ) return GetIdName( ID ) end -- meta index races I properly don't need to do this but we will see pawns.settings["races_list"] = {"RACE_HUMAN","RACE_ELF","RACE_DWARF"}; --The race ID's from the objects out of the object list pawns.settings["races_types"] = {RACE_HUMAN = 0, RACE_ELF = 1, RACE_DWARF = 2}; pawns.settings["races_default"] = pawns.settings["races_types"]["RACE_HUMAN"]; -- if in another MMO you have only 1 class set the to 1 pawns.settings["max_number_classes_activ"] = 2; pawns.settings["max_number_classes_total"] = 3; -- meta index classes pawns.settings["class_list"] = {"CLASS_NONE","CLASS_WARRIOR","CLASS_SCOUT", "CLASS_ROGUE","CLASS_MAGE","CLASS_PRIEST", "CLASS_KNIGHT","CLASS_WARDEN","CLASS_DRUID", "CLASS_WARLOCK","CLASS_CHAMPION"}; --The class ID's from the objects the object list pawns.settings["class_types"] = {CLASS_NONE = -1,CLASS_WARRIOR = 1,CLASS_SCOUT = 2, CLASS_ROGUE = 3,CLASS_MAGE = 4,CLASS_PRIEST = 5, CLASS_KNIGHT = 6,CLASS_WARDEN = 7,CLASS_DRUID = 8, CLASS_WARLOCK = 9, CLASS_CHAMPION = 10} -- meta index nodes pawns.settings["nodes_list"] = {"NTYPE_WOOD","NTYPE_ORE","NTYPE_HERB"}; pawns.settings["nodes_type"] = {NTYPE_WOOD = 1,NTYPE_ORE = 2,NTYPE_HERB = 3}; -- can be others in games like DP we have 3 the total number will be the length of the table "energy_list" pawns.settings["max_number_energys_activ"] = 2; pawns.settings["energy_list"] = {"mana","rage","energy","focus"} pawns.settings["armor_map"] = { [pawns.settings["class_types"].CLASS_NONE] = "none", [pawns.settings["class_types"].CLASS_WARRIOR] = "chain", [pawns.settings["class_types"].CLASS_SCOUT] = "leather", [pawns.settings["class_types"].CLASS_ROGUE] = "leather", [pawns.settings["class_types"].CLASS_MAGE] = "cloth", [pawns.settings["class_types"].CLASS_PRIEST] = "cloth", [pawns.settings["class_types"].CLASS_KNIGHT] = "chain", [pawns.settings["class_types"].CLASS_WARDEN] = "chain", [pawns.settings["class_types"].CLASS_DRUID] = "cloth", [pawns.settings["class_types"].CLASS_WARLOCK] = "cloth", [pawns.settings["class_types"].CLASS_CHAMPION] = "chain", } pawns.settings["classEnergyMap"] = { [pawns.settings["class_types"].CLASS_NONE] = "none", [pawns.settings["class_types"].CLASS_WARRIOR] = "rage", [pawns.settings["class_types"].CLASS_SCOUT] = "focus", [pawns.settings["class_types"].CLASS_ROGUE] = "energy", [pawns.settings["class_types"].CLASS_MAGE] = "mana", [pawns.settings["class_types"].CLASS_PRIEST] = "mana", [pawns.settings["class_types"].CLASS_KNIGHT] = "mana", [pawns.settings["class_types"].CLASS_WARDEN] = "mana", [pawns.settings["class_types"].CLASS_DRUID] = "mana", [pawns.settings["class_types"].CLASS_WARLOCK] = "focus", [pawns.settings["class_types"].CLASS_CHAMPION] = "rage", } PT_NONE = 0; PT_PLAYER = 1; PT_MONSTER = 2; -- we can use SIGEL in other games for special event drops PT_SIGIL = 3; PT_NPC = 4; PT_NODE = 4; ATTACKABLE_MASK_PLAYER = 0x10000; ATTACKABLE_MASK_MONSTER = 0x20000; ATTACKABLE_MASK_CLICKABLE = 0x1000; AGGRESSIVE_MASK_MONSTER = 0x100000; pawns.funcs["pawn_init_all_classes"] = function() local activ_classes = pawns.settings["max_number_classes_activ"]; local default_class = pawns.settings["class_types"]["CLASS_NONE"]; local class_table = {}; for i = 1, activ_classes do class_table[i] = default_class; end return class_table; end pawns.funcs["init_all_levels"] = function() local number_of_levels = pawns.settings["max_number_classes_activ"]; local level_table = {}; for i = 1, number_of_levels do level_table = 1; end end pawns.funcs["init_all_activ_energys"] = function() local number_of_levels = pawns.settings["max_number_classes_activ"]; local power_table = {}; for i = 1, number_of_levels * 2 do power_table[i] = 1000; end return power_table; end pawns.funcs["init_zero_activ_energy"] = function (ActivEnergys) for key, value in pairs(ActivEnergys) do ActivEnergys[key] = 0; end return ActivEnergys; end pawns.funcs["init_all_energys"] = function() local enys = pawns.settings["energy_list"]; local powers = {}; local size = #enys; for i = 1, size * 2 do if(i%2 == 0)then powers["Max"..enys[i]] = 0; else powers[enys[i]] = 0 end end return powers; end pawns.funcs["pawn_eval_updates"]= function(self) --if( self.Alive ==nil or self.HP == nil or self.MaxHP == nil or self.MP == nil or self.MaxMP == nil or -- self.MP2 == nil or self.MaxMP2 == nil or self.Name == nil or -- self.Level == nil or self.Level2 == nil or self.TargetPtr == nil or -- self.X == nil or self.Y == nil or self.Z == nil or self.Attackable == nil ) then return false; end pawns.funcs["pawn_eval_id"] = function(tmp,self) if self.Id == -1 then -- First time. Get it. self.Id = tmp if self.Id > 999999 then self.Id = 0 end elseif self.Id >= PLAYERID_MIN and self.Id <= PLAYERID_MAX then -- player ids can change if tmp >= PLAYERID_MIN and tmp <= PLAYERID_MAX then self.Id = tmp end else -- see if it changed if tmp ~= self.Id then -- Id changed. Pawn no longer valid self.Id = 0 self.Type = 0 self.Name = "<UNKNOWN>" end end end pawns.funcs["pawn_eval_target_icon"] = function(attackableFlag) if bitAnd(attackableFlag,0x10) then return true; else return false; end end pawns.funcs["pawn_eval_alive"] = function(alive) return not bitAnd(alive, 8); end pawns.funcs["pawn_eval_lootable"] = function( tmp ) return bitAnd(tmp, 0x4); end pawns.funcs["pawn_eval_mounted"] = function( attackableFlag ) return bitAnd(attackableFlag, 0x10000000); end pawns.funcs["pawn_eval_inparty"] = function( attackableFlag ) return bitAnd(attackableFlag,0x80000000); end pawns.funcs["pawn_eval_aggressive_and_attackable"] = function( attackableFlag, self ) if( bitAnd(attackableFlag, ATTACKABLE_MASK_MONSTER) and bitAnd(attackableFlag, ATTACKABLE_MASK_CLICKABLE) ) then self.Attackable = true; else self.Attackable = false; end if( bitAnd(attackableFlag, AGGRESSIVE_MASK_MONSTER) ) then self.Aggressive = true; else self.Aggressive = false; end end pawns.funcs["pawn_eval_swim"] = function( tmp ) if (tmp == 3 or tmp == 4)then return true else return false; end end
--[[ module: BusinessLookUp author: DylanYang time: 2021-02-24 16:17:57 idea: advance: ]] local EJBService = require("patterns.j2ee.businessDelegate.EJBService") local JMSService = require("patterns.j2ee.businessDelegate.JMSService") local _M = Class("BusinessLookUp") local public = _M.public function public:GetBusinessService(serviceType) if string.upper(serviceType) == "EJB" then return EJBService.new() else return JMSService.new() end end return _M
local next, assert, pairs, type, tostring, setmetatable, baseMt, _instances, _classes, _class = next, assert, pairs, type, tostring, setmetatable, {}, setmetatable({},{__mode = 'k'}), setmetatable({},{__mode = 'k'}) local function assert_call_from_class(class, method) assert(_classes[class], ('Wrong method call. Expected class:%s.'):format(method)) end; local function assert_call_from_instance(instance, method) assert(_instances[instance], ('Wrong method call. Expected instance:%s.'):format(method)) end local function bind(f, v) return function(...) return f(v, ...) end end local default_filter = function() return true end local function deep_copy(t, dest, aType) t = t or {}; local r = dest or {}; for k,v in pairs(t) do if aType ~= nil and type(v) == aType then r[k] = (type(v) == 'table') and ((_classes[v] or _instances[v]) and v or deep_copy(v)) or v elseif aType == nil then r[k] = (type(v) == 'table') and k~= '__index' and ((_classes[v] or _instances[v]) and v or deep_copy(v)) or v end; end return r end local function instantiate(call_init,self,...) assert_call_from_class(self, 'new(...) or class(...)'); local instance = {class = self}; _instances[instance] = tostring(instance); deep_copy(self, instance, 'table') instance.__index, instance.__subclasses, instance.__instances, instance.mixins = nil, nil, nil, nil; setmetatable(instance,self); if call_init and self.init then if type(self.init) == 'table' then deep_copy(self.init, instance) else self.init(instance, ...) end end; return instance end local function extend(self, name, extra_params) assert_call_from_class(self, 'extend(...)'); local heir = {}; _classes[heir] = tostring(heir); self.__subclasses[heir] = true; deep_copy(extra_params, deep_copy(self, heir)) heir.name, heir.__index, heir.super, heir.mixins = extra_params and extra_params.name or name, heir, self, {}; return setmetatable(heir,self) end baseMt = { __call = function (self,...) return self:new(...) end, __tostring = function(self,...) if _instances[self] then return ("instance of '%s' (%s)"):format(rawget(self.class,'name') or '?', _instances[self]) end; return _classes[self] and ("class '%s' (%s)"):format(rawget(self,'name') or '?', _classes[self]) or self end }; _classes[baseMt] = tostring(baseMt); setmetatable(baseMt, {__tostring = baseMt.__tostring}) class = {isClass = function(t) return not not _classes[t] end, isInstance = function(t) return not not _instances[t] end} _class = function(name, attr) local c = deep_copy(attr); _classes[c] = tostring(c) c.name, c.__tostring, c.__call, c.new, c.create, c.extend, c.__index, c.mixins, c.__instances, c.__subclasses = name or c.name, baseMt.__tostring, baseMt.__call, bind(instantiate, true), bind(instantiate, false), extend, c, setmetatable({},{__mode = 'k'}), setmetatable({},{__mode = 'k'}), setmetatable({},{__mode = 'k'}) c.subclasses = function(self, filter, ...) assert_call_from_class(self, 'subclasses(class)'); filter = filter or default_filter; local subclasses = {}; for class in pairs(_classes) do if class ~= baseMt and class:subclassOf(self) and filter(class,...) then subclasses[#subclasses + 1] = class end end; return subclasses end c.instances = function(self, filter, ...) assert_call_from_class(self, 'instances(class)'); filter = filter or default_filter; local instances = {}; for instance in pairs(_instances) do if instance:instanceOf(self) and filter(instance, ...) then instances[#instances + 1] = instance end end; return instances end c.subclassOf = function(self, superclass) assert_call_from_class(self, 'subclassOf(superclass)'); assert(class.isClass(superclass), 'Wrong argument given to method "subclassOf()". Expected a class.'); local super = self.super; while super do if super == superclass then return true end; super = super.super end; return false end c.classOf = function(self, subclass) assert_call_from_class(self, 'classOf(subclass)'); assert(class.isClass(subclass), 'Wrong argument given to method "classOf()". Expected a class.'); return subclass:subclassOf(self) end c.instanceOf = function(self, fromclass) assert_call_from_instance(self, 'instanceOf(class)'); assert(class.isClass(fromclass), 'Wrong argument given to method "instanceOf()". Expected a class.'); return ((self.class == fromclass) or (self.class:subclassOf(fromclass))) end c.cast = function(self, toclass) assert_call_from_instance(self, 'instanceOf(class)'); assert(class.isClass(toclass), 'Wrong argument given to method "cast()". Expected a class.'); setmetatable(self, toclass); self.class = toclass; return self end c.with = function(self,...) assert_call_from_class(self, 'with(mixin)'); for _, mixin in ipairs({...}) do assert(self.mixins[mixin] ~= true, ('Attempted to include a mixin which was already included in %s'):format(tostring(self))); self.mixins[mixin] = true; deep_copy(mixin, self, 'function') end return self end c.includes = function(self, mixin) assert_call_from_class(self,'includes(mixin)'); return not not (self.mixins[mixin] or (self.super and self.super:includes(mixin))) end c.without = function(self, ...) assert_call_from_class(self, 'without(mixin)'); for _, mixin in ipairs({...}) do assert(self.mixins[mixin] == true, ('Attempted to remove a mixin which is not included in %s'):format(tostring(self))); local classes = self:subclasses(); classes[#classes + 1] = self for _, class in ipairs(classes) do for method_name, method in pairs(mixin) do if type(method) == 'function' then class[method_name] = nil end end end; self.mixins[mixin] = nil end; return self end; return setmetatable(c, baseMt) end class._DESCRIPTION = '30 lines library for object orientation in Lua'; class._VERSION = '30log v1.2.0'; class._URL = 'http://github.com/Yonaba/30log'; class._LICENSE = 'MIT LICENSE <http://www.opensource.org/licenses/mit-license.php>' return setmetatable(class,{__call = function(_,...) return _class(...) end })
local config = require("config") local servers = require("servers") local json = require("json") local strategyPA = require("strategyPA") local status = { config = config.get_runtime(), strategyPA = strategyPA.get_data() } local statusJson = json.encode( status ) ngx.say( statusJson )
local function init() local plugins = { -- packer 'packer', -- lsp 'lsp', 'treesitter', 'compe', 'compe_tabnine', -- telescope 'telescope', -- git 'gitsigns', 'git_worktree', -- theme 'tokyonight', -- window 'lualine', -- utils 'floaterm', 'hardtime', 'zettel', } for _, plug in ipairs(plugins) do require(string.format('TheAltF4Stream.plugins.%s', plug)).init() end end return { init = init, }
-- init mqtt client with keepalive timer 120sec m = mqtt.Client("foo", 120, "", "") m:on("connect", function(con) print ("connected") end) m:on("offline", function(con) print ("offline") end) -- on publish message receive event m:on("message", function(conn, topic, data) print(topic .. ":" .. data) ledmate.push_msg(data, data) end) m:connect("149.210.234.62", 3344, 0, function(conn) print("connected") m:subscribe("/ledmate", 0, function(conn) print("subscribe success") end) end)
--*********************************************************** --** THE INDIE STONE ** --*********************************************************** require "ISUI/ISModalRichText" ---@class ISModsNagPanel : ISPanelJoypad ISModsNagPanel = ISPanelJoypad:derive("ISModsNagPanel") local FONT_HGT_SMALL = getTextManager():getFontHeight(UIFont.Small) local FONT_HGT_TITLE = getTextManager():getFontHeight(UIFont.Title) function ISModsNagPanel:createChildren() local btnWid = 100 local btnHgt = math.max(25, FONT_HGT_SMALL + 3 * 2) local padY = 10 self.textureX = 10 self.textureY = 10 + FONT_HGT_TITLE + 10 self.textureW = self.texture:getWidth() self.textureH = self.texture:getHeight() local x = self.textureX + self.textureW local y = self.textureY self.richText = ISRichTextPanel:new(x, y, self.width - x, self.height - padY - btnHgt - padY - y) self.richText.background = false self.richText.autosetheight = false self.richText.clip = true self.richText.marginRight = self.richText.marginLeft self:addChild(self.richText) self.richText:addScrollBars() self.richText:setText(getText("UI_ModsNagPanel_Text")) self.richText:paginate() self.ok = ISButton:new((self:getWidth() / 2) - btnWid / 2, self:getHeight() - padY - btnHgt, btnWid, btnHgt, getText("UI_Ok"), self, self.onOK) self.ok.anchorTop = false self.ok.anchorBottom = true self.ok:initialise() self.ok:instantiate() -- self.ok.borderColor = {r=1, g=1, b=1, a=0.1} self:addChild(self.ok) end function ISModsNagPanel:render() ISPanelJoypad.render(self) self:drawTextCentre(getText("UI_ModsNagPanel_Title"), self.width / 2, 10, 1, 1, 1, 1, UIFont.Title); self:drawTextureScaledAspect(self.texture, self.textureX, self.textureY, self.textureW, self.textureH, 1, 1, 1, 1) end function ISModsNagPanel:onGainJoypadFocus(joypadData) ISPanelJoypad.onGainJoypadFocus(self, joypadData) self:setISButtonForA(self.ok) end function ISModsNagPanel:onOK(button, x, y) self:setVisible(false) self:removeFromUIManager() ModSelector.instance:setVisible(true, self.joyfocus) end function ISModsNagPanel:new(x, y, width, height) local o = ISPanelJoypad.new(self, x, y, width, height) o.backgroundColor.a = 0.9 o.texture = getTexture("spiffoWarning.png") return o end
data:extend({ { type = "container", name = "nuclear-fission-reactor-chest-15", icon = "__UraniumPowerRemastered__/graphics/icons/reactor-port-icon.png", flags = {"placeable-neutral", "placeable-player", "not-blueprintable", "not-deconstructable"}, max_health = 200, corpse = "small-remnants", open_sound = { filename = "__base__/sound/metallic-chest-open.ogg", volume=0.65 }, close_sound = { filename = "__base__/sound/metallic-chest-close.ogg", volume = 0.7 }, minable = {hardness = 0.2, mining_time = 1}, resistances = { { type = "fire", percent = 90 } }, collision_box = {{-0.35, -0.35}, {0.35, 0.35}}, selection_box = {{-0.5, -0.5}, {0.5, 0.5}}, picture = { filename = "__UraniumPowerRemastered__/graphics/entity/reactor-port/prototype-reactor-port.png", priority = "extra-high", width = 63, height = 44, shift = {0.375, -0.1875} }, inventory_size = 15 }, { type = "container", name = "nuclear-fission-reactor-chest-25", icon = "__UraniumPowerRemastered__/graphics/icons/reactor-port-icon.png", flags = {"placeable-neutral", "placeable-player", "not-blueprintable", "not-deconstructable"}, max_health = 200, corpse = "small-remnants", open_sound = { filename = "__base__/sound/metallic-chest-open.ogg", volume=0.65 }, close_sound = { filename = "__base__/sound/metallic-chest-close.ogg", volume = 0.7 }, minable = {hardness = 0.2, mining_time = 1}, resistances = { { type = "fire", percent = 90 } }, collision_box = {{-0.35, -0.35}, {0.35, 0.35}}, selection_box = {{-0.5, -0.5}, {0.5, 0.5}}, picture = { filename = "__UraniumPowerRemastered__/graphics/entity/reactor-port/prototype-reactor-port.png", priority = "extra-high", width = 63, height = 44, shift = {0.375, -0.1875} }, inventory_size = 25 } })
SWEP.PrintName = "Handcuffs" SWEP.Author = "TheAsian EggrollMaker" SWEP.Contact = "theasianeggrollmaker@gmail.com" SWEP.Purpose = "To handcuff suspects." SWEP.Instructions = "Left Click: Handcuff suspect.\nRight Click: Release handcuffed suspect." SWEP.Base = "weapon_base" SWEP.UseHands = true SWEP.Category = "Eggroll's Police System" SWEP.Slot = 1 SWEP.SlotPos = 2 SWEP.Spawnable = true SWEP.Primary.ClipSize = -1 SWEP.Primary.DefaultClip = -1 SWEP.Primary.Ammo = "none" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Ammo = "none" SWEP.DrawAmmo = false function SWEP:Initialize( ) self:SetHoldType( "normal" ) end
-- vim: st=4 sts=4 sw=4 et: local cjson = require "cjson.safe" local new_tab = require "table.new" local lrucache = require "resty.lrucache" local resty_lock = require "resty.lock" local tablepool do local pok pok, tablepool = pcall(require, "tablepool") if not pok then -- fallback for OpenResty < 1.15.8.1 tablepool = { fetch = function(_, narr, nrec) return new_tab(narr, nrec) end, release = function(_, _, _) -- nop (obj will be subject to GC) end, } end end local now = ngx.now local min = math.min local ceil = math.ceil local fmt = string.format local sub = string.sub local find = string.find local type = type local xpcall = xpcall local traceback = debug.traceback local error = error local tostring = tostring local tonumber = tonumber local thread_spawn = ngx.thread.spawn local thread_wait = ngx.thread.wait local setmetatable = setmetatable local shared = ngx.shared local ngx_log = ngx.log local WARN = ngx.WARN local ERR = ngx.ERR local CACHE_MISS_SENTINEL_LRU = {} local LOCK_KEY_PREFIX = "lua-resty-mlcache:lock:" local LRU_INSTANCES = setmetatable({}, { __mode = "v" }) local SHM_SET_DEFAULT_TRIES = 3 local BULK_DEFAULT_CONCURRENCY = 3 local TYPES_LOOKUP = { number = 1, boolean = 2, string = 3, table = 4, } local SHM_FLAGS = { stale = 0x00000001, } local marshallers = { shm_value = function(str_value, value_type, at, ttl) return fmt("%d:%f:%f:%s", value_type, at, ttl, str_value) end, shm_nil = function(at, ttl) return fmt("0:%f:%f:", at, ttl) end, [1] = function(number) -- number return tostring(number) end, [2] = function(bool) -- boolean return bool and "true" or "false" end, [3] = function(str) -- string return str end, [4] = function(t) -- table local json, err = cjson.encode(t) if not json then return nil, "could not encode table value: " .. err end return json end, } local unmarshallers = { shm_value = function(marshalled) -- split our shm marshalled value by the hard-coded ":" tokens -- "type:at:ttl:value" -- 1:1501831735.052000:0.500000:123 local ttl_last = find(marshalled, ":", 21, true) - 1 local value_type = sub(marshalled, 1, 1) -- n:... local at = sub(marshalled, 3, 19) -- n:1501831160 local ttl = sub(marshalled, 21, ttl_last) local str_value = sub(marshalled, ttl_last + 2) return str_value, tonumber(value_type), tonumber(at), tonumber(ttl) end, [0] = function() -- nil return nil end, [1] = function(str) -- number return tonumber(str) end, [2] = function(str) -- boolean return str == "true" end, [3] = function(str) -- string return str end, [4] = function(str) -- table local t, err = cjson.decode(str) if not t then return nil, "could not decode table value: " .. err end return t end, } local function rebuild_lru(self) if self.lru then if self.lru.flush_all then self.lru:flush_all() return end -- fallback for OpenResty < 1.13.6.2 -- Invalidate the entire LRU by GC-ing it. LRU_INSTANCES[self.name] = nil self.lru = nil end -- Several mlcache instances can have the same name and hence, the same -- lru instance. We need to GC such LRU instance when all mlcache instances -- using them are GC'ed. We do this with a weak table. local lru = LRU_INSTANCES[self.name] if not lru then lru = lrucache.new(self.lru_size) LRU_INSTANCES[self.name] = lru end self.lru = lru end local _M = { _VERSION = "2.4.2", _AUTHOR = "Thibault Charbonnier", _LICENSE = "MIT", _URL = "https://github.com/thibaultcha/lua-resty-mlcache", } local mt = { __index = _M } function _M.new(name, shm, opts) if type(name) ~= "string" then error("name must be a string", 2) end if type(shm) ~= "string" then error("shm must be a string", 2) end if opts ~= nil then if type(opts) ~= "table" then error("opts must be a table", 2) end if opts.skip_callback ~= nil and type(opts.skip_callback) ~= "boolean" then error("opts.skip_callback must be a boolean", 2) end if opts.lru_size ~= nil and type(opts.lru_size) ~= "number" then error("opts.lru_size must be a number", 2) end if opts.ttl ~= nil then if type(opts.ttl) ~= "number" then error("opts.ttl must be a number", 2) end if opts.ttl < 0 then error("opts.ttl must be >= 0", 2) end end if opts.neg_ttl ~= nil then if type(opts.neg_ttl) ~= "number" then error("opts.neg_ttl must be a number", 2) end if opts.neg_ttl < 0 then error("opts.neg_ttl must be >= 0", 2) end end if opts.resurrect_ttl ~= nil then if type(opts.resurrect_ttl) ~= "number" then error("opts.resurrect_ttl must be a number", 2) end if opts.resurrect_ttl < 0 then error("opts.resurrect_ttl must be >= 0", 2) end end if opts.resty_lock_opts ~= nil and type(opts.resty_lock_opts) ~= "table" then error("opts.resty_lock_opts must be a table", 2) end if opts.ipc_shm ~= nil and type(opts.ipc_shm) ~= "string" then error("opts.ipc_shm must be a string", 2) end if opts.ipc ~= nil then if opts.ipc_shm then error("cannot specify both of opts.ipc_shm and opts.ipc", 2) end if type(opts.ipc) ~= "table" then error("opts.ipc must be a table", 2) end if type(opts.ipc.register_listeners) ~= "function" then error("opts.ipc.register_listeners must be a function", 2) end if type(opts.ipc.broadcast) ~= "function" then error("opts.ipc.broadcast must be a function", 2) end if opts.ipc.poll ~= nil and type(opts.ipc.poll) ~= "function" then error("opts.ipc.poll must be a function", 2) end end if opts.l1_serializer ~= nil and type(opts.l1_serializer) ~= "function" then error("opts.l1_serializer must be a function", 2) end if opts.shm_set_tries ~= nil then if type(opts.shm_set_tries) ~= "number" then error("opts.shm_set_tries must be a number", 2) end if opts.shm_set_tries < 1 then error("opts.shm_set_tries must be >= 1", 2) end end if opts.shm_miss ~= nil and type(opts.shm_miss) ~= "string" then error("opts.shm_miss must be a string", 2) end if opts.shm_locks ~= nil and type(opts.shm_locks) ~= "string" then error("opts.shm_locks must be a string", 2) end else opts = {} end local dict = shared[shm] if not dict then return nil, "no such lua_shared_dict: " .. shm end local dict_miss if opts.shm_miss then dict_miss = shared[opts.shm_miss] if not dict_miss then return nil, "no such lua_shared_dict for opts.shm_miss: " .. opts.shm_miss end end if opts.shm_locks then local dict_locks = shared[opts.shm_locks] if not dict_locks then return nil, "no such lua_shared_dict for opts.shm_locks: " .. opts.shm_locks end end local self = { name = name, dict = dict, shm = shm, dict_miss = dict_miss, shm_miss = opts.shm_miss, shm_locks = opts.shm_locks or shm, ttl = opts.ttl or 30, neg_ttl = opts.neg_ttl or 5, resurrect_ttl = opts.resurrect_ttl, lru_size = opts.lru_size or 100, resty_lock_opts = opts.resty_lock_opts, l1_serializer = opts.l1_serializer, skip_callback = opts.skip_callback or false, shm_set_tries = opts.shm_set_tries or SHM_SET_DEFAULT_TRIES, debug = opts.debug, } if opts.ipc_shm or opts.ipc then self.events = { ["invalidation"] = { channel = fmt("mlcache:invalidations:%s", name), handler = function(key) self.lru:delete(key) end, }, ["purge"] = { channel = fmt("mlcache:purge:%s", name), handler = function() rebuild_lru(self) end, } } if opts.ipc_shm then local mlcache_ipc = require "resty.mlcache.ipc" local ipc, err = mlcache_ipc.new(opts.ipc_shm, opts.debug) if not ipc then return nil, "failed to initialize mlcache IPC " .. "(could not instantiate mlcache.ipc): " .. err end for _, ev in pairs(self.events) do ipc:subscribe(ev.channel, ev.handler) end self.broadcast = function(channel, data) return ipc:broadcast(channel, data) end self.poll = function(timeout) return ipc:poll(timeout) end self.ipc = ipc else -- opts.ipc local ok, err = opts.ipc.register_listeners(self.events) if not ok and err ~= nil then return nil, "failed to initialize custom IPC " .. "(opts.ipc.register_listeners returned an error): " .. err end self.broadcast = opts.ipc.broadcast self.poll = opts.ipc.poll self.ipc = true end end if opts.lru then self.lru = opts.lru else rebuild_lru(self) end return setmetatable(self, mt) end local function set_lru(self, key, value, ttl, neg_ttl, l1_serializer) if value == nil then ttl = neg_ttl value = CACHE_MISS_SENTINEL_LRU elseif l1_serializer then local ok, err ok, value, err = pcall(l1_serializer, value) if not ok then return nil, "l1_serializer threw an error: " .. value end if err then return nil, err end if value == nil then return nil, "l1_serializer returned a nil value" end end if ttl == 0 then -- indefinite ttl for lua-resty-lrucache is 'nil' ttl = nil end self.lru:set(key, value, ttl) return value end local function marshall_for_shm(value, ttl, neg_ttl) local at = now() if value == nil then return marshallers.shm_nil(at, neg_ttl), nil, true -- is_nil end -- serialize insertion time + Lua types for shm storage local value_type = TYPES_LOOKUP[type(value)] if not marshallers[value_type] then error("cannot cache value of type " .. type(value)) end local str_marshalled, err = marshallers[value_type](value) if not str_marshalled then return nil, "could not serialize value for lua_shared_dict insertion: " .. err end return marshallers.shm_value(str_marshalled, value_type, at, ttl) end local function unmarshall_from_shm(shm_v) local str_serialized, value_type, at, ttl = unmarshallers.shm_value(shm_v) local value, err = unmarshallers[value_type](str_serialized) if err then return nil, err end return value, nil, at, ttl end local function set_shm(self, shm_key, value, ttl, neg_ttl, flags, shm_set_tries, throw_no_mem) local shm_value, err, is_nil = marshall_for_shm(value, ttl, neg_ttl) if not shm_value then return nil, err end local shm = self.shm local dict = self.dict if is_nil then ttl = neg_ttl if self.dict_miss then shm = self.shm_miss dict = self.dict_miss end end -- we will call `set()` N times to work around potential shm fragmentation. -- when the shm is full, it will only evict about 30 to 90 items (via -- LRU), which could lead to a situation where `set()` still does not -- have enough memory to store the cached value, in which case we -- try again to try to trigger more LRU evictions. local tries = 0 local ok, err while tries < shm_set_tries do tries = tries + 1 ok, err = dict:set(shm_key, shm_value, ttl, flags or 0) if ok or err and err ~= "no memory" then break end end if not ok then if err ~= "no memory" or throw_no_mem then return nil, "could not write to lua_shared_dict '" .. shm .. "': " .. err end ngx_log(WARN, "could not write to lua_shared_dict '", shm, "' after ", tries, " tries (no memory), ", "it is either fragmented or cannot allocate more ", "memory, consider increasing 'opts.shm_set_tries'") end return true end local function set_shm_set_lru(self, key, shm_key, value, ttl, neg_ttl, flags, shm_set_tries, l1_serializer, throw_no_mem) local ok, err = set_shm(self, shm_key, value, ttl, neg_ttl, flags, shm_set_tries, throw_no_mem) if not ok then return nil, err end return set_lru(self, key, value, ttl, neg_ttl, l1_serializer) end local function get_shm_set_lru(self, key, shm_key, l1_serializer) local v, shmerr, went_stale = self.dict:get_stale(shm_key) if v == nil and shmerr then -- shmerr can be 'flags' upon successful get_stale() calls, so we -- also check v == nil return nil, "could not read from lua_shared_dict: " .. shmerr end if self.shm_miss and v == nil then -- if we cache misses in another shm, maybe it is there v, shmerr, went_stale = self.dict_miss:get_stale(shm_key) if v == nil and shmerr then -- shmerr can be 'flags' upon successful get_stale() calls, so we -- also check v == nil return nil, "could not read from lua_shared_dict: " .. shmerr end end if v ~= nil then local value, err, at, ttl = unmarshall_from_shm(v) if err then return nil, "could not deserialize value after lua_shared_dict " .. "retrieval: " .. err end if went_stale then return value, nil, went_stale end -- 'shmerr' is 'flags' on :get_stale() success local is_stale = shmerr == SHM_FLAGS.stale local remaining_ttl if ttl == 0 then -- indefinite ttl, keep '0' as it means 'forever' remaining_ttl = 0 else -- compute elapsed time to get remaining ttl for LRU caching remaining_ttl = ttl - (now() - at) if remaining_ttl <= 0 then -- value has less than 1ms of lifetime in the shm, avoid -- setting it in LRU which would be wasteful and could -- indefinitely cache the value when ttl == 0 return value, nil, nil, is_stale end end value, err = set_lru(self, key, value, remaining_ttl, remaining_ttl, l1_serializer) if err then return nil, err end return value, nil, nil, is_stale end end local function check_opts(self, opts) local ttl local neg_ttl local resurrect_ttl local l1_serializer local shm_set_tries local skip_callback if opts ~= nil then if type(opts) ~= "table" then error("opts must be a table", 3) end ttl = opts.ttl if ttl ~= nil then if type(ttl) ~= "number" then error("opts.ttl must be a number", 3) end if ttl < 0 then error("opts.ttl must be >= 0", 3) end end neg_ttl = opts.neg_ttl if neg_ttl ~= nil then if type(neg_ttl) ~= "number" then error("opts.neg_ttl must be a number", 3) end if neg_ttl < 0 then error("opts.neg_ttl must be >= 0", 3) end end resurrect_ttl = opts.resurrect_ttl if resurrect_ttl ~= nil then if type(resurrect_ttl) ~= "number" then error("opts.resurrect_ttl must be a number", 3) end if resurrect_ttl < 0 then error("opts.resurrect_ttl must be >= 0", 3) end end l1_serializer = opts.l1_serializer if l1_serializer ~= nil and type(l1_serializer) ~= "function" then error("opts.l1_serializer must be a function", 3) end shm_set_tries = opts.shm_set_tries if shm_set_tries ~= nil then if type(shm_set_tries) ~= "number" then error("opts.shm_set_tries must be a number", 3) end if shm_set_tries < 1 then error("opts.shm_set_tries must be >= 1", 3) end end skip_callback = opts.skip_callback if skip_callback ~= nil and type(skip_callback) ~= "boolean" then error("opts.skip_callback must be a boolean", 3) end end if not ttl then ttl = self.ttl end if not neg_ttl then neg_ttl = self.neg_ttl end if not resurrect_ttl then resurrect_ttl = self.resurrect_ttl end if not l1_serializer then l1_serializer = self.l1_serializer end if not shm_set_tries then shm_set_tries = self.shm_set_tries end if skip_callback == nil then skip_callback = self.skip_callback end return ttl, neg_ttl, resurrect_ttl, l1_serializer, shm_set_tries, skip_callback end local function unlock_and_ret(lock, res, err, hit_lvl) local ok, lerr = lock:unlock() if not ok and lerr ~= "unlocked" then return nil, "could not unlock callback: " .. lerr end return res, err, hit_lvl end local function run_callback(self, key, shm_key, data, ttl, neg_ttl, went_stale, l1_serializer, resurrect_ttl, shm_set_tries, cb, ...) local lock, err = resty_lock:new(self.shm_locks, self.resty_lock_opts) if not lock then return nil, "could not create lock: " .. err end local elapsed, lerr = lock:lock(LOCK_KEY_PREFIX .. shm_key) if not elapsed and lerr ~= "timeout" then return nil, "could not acquire callback lock: " .. lerr end do -- check for another worker's success at running the callback, but -- do not return data if it is still the same stale value (this is -- possible if the value was still not evicted between the first -- get() and this one) local data2, err, went_stale2, stale2 = get_shm_set_lru(self, key, shm_key, l1_serializer) if err then return unlock_and_ret(lock, nil, err) end if data2 ~= nil and not went_stale2 then -- we got a fresh item from shm: other worker succeeded in running -- the callback if data2 == CACHE_MISS_SENTINEL_LRU then data2 = nil end return unlock_and_ret(lock, data2, nil, stale2 and 4 or 2) end end -- we are either the 1st worker to hold the lock, or -- a subsequent worker whose lock has timed out before the 1st one -- finished to run the callback if lerr == "timeout" then local errmsg = "could not acquire callback lock: timeout" -- no stale data nor desire to resurrect it if not went_stale or not resurrect_ttl then return nil, errmsg end -- do not resurrect the value here (another worker is running the -- callback and will either get the new value, or resurrect it for -- us if the callback fails) ngx_log(WARN, errmsg) -- went_stale is true, hence the value cannot be set in the LRU -- cache, and cannot be CACHE_MISS_SENTINEL_LRU return data, nil, 4 end -- still not in shm, we are the 1st worker to hold the lock, and thus -- responsible for running the callback local pok, perr, err, new_ttl = xpcall(cb, traceback, ...) if not pok then return unlock_and_ret(lock, nil, "callback threw an error: " .. tostring(perr)) end if err then -- callback returned nil + err -- be resilient in case callbacks return wrong error type err = tostring(err) -- no stale data nor desire to resurrect it if not went_stale or not resurrect_ttl then return unlock_and_ret(lock, perr, err) end -- we got 'data' from the shm, even though it is stale -- 1. log as warn that the callback returned an error -- 2. resurrect: insert it back into shm if 'resurrect_ttl' -- 3. signify the staleness with a high hit_lvl of '4' ngx_log(WARN, "callback returned an error (", err, ") but stale ", "value found in shm will be resurrected for ", resurrect_ttl, "s (resurrect_ttl)") local res_data, res_err = set_shm_set_lru(self, key, shm_key, data, resurrect_ttl, resurrect_ttl, SHM_FLAGS.stale, shm_set_tries, l1_serializer) if res_err then ngx_log(WARN, "could not resurrect stale data (", res_err, ")") end if res_data == CACHE_MISS_SENTINEL_LRU then res_data = nil end return unlock_and_ret(lock, res_data, nil, 4) end -- successful callback run returned 'data, nil, new_ttl?' data = perr -- override ttl / neg_ttl if type(new_ttl) == "number" then if new_ttl < 0 then -- bypass cache return unlock_and_ret(lock, data, nil, 3) end if data == nil then neg_ttl = new_ttl else ttl = new_ttl end end data, err = set_shm_set_lru(self, key, shm_key, data, ttl, neg_ttl, nil, shm_set_tries, l1_serializer) if err then return unlock_and_ret(lock, nil, err) end if data == CACHE_MISS_SENTINEL_LRU then data = nil end -- unlock and return return unlock_and_ret(lock, data, nil, 3) end function _M:get(key, opts, cb, ...) if type(key) ~= "string" then error("key must be a string", 2) end -- opts validation local ttl, neg_ttl, resurrect_ttl, l1_serializer, shm_set_tries, skip_callback = check_opts(self, opts) if skip_callback ~= true and type(cb) ~= "function" then error("callback must be a function", 2) end -- worker LRU cache retrieval local data = self.lru:get(key) if data == CACHE_MISS_SENTINEL_LRU then return nil, nil, 1 end if data ~= nil then return data, nil, 1 end -- not in worker's LRU cache, need shm lookup -- restrict this key to the current namespace, so we isolate this -- mlcache instance from potential other instances using the same -- shm local namespaced_key = self.name .. key local err, went_stale, is_stale data, err, went_stale, is_stale = get_shm_set_lru(self, key, namespaced_key, l1_serializer) if err then return nil, err end if data ~= nil and not went_stale then if data == CACHE_MISS_SENTINEL_LRU then data = nil end return data, nil, is_stale and 4 or 2 end -- not in shm either if skip_callback ~= true then -- single worker must execute the callback return run_callback(self, key, namespaced_key, data, ttl, neg_ttl, went_stale, l1_serializer, resurrect_ttl, shm_set_tries, cb, ...) end return nil, nil end do local function run_thread(self, ops, from, to) for i = from, to do local ctx = ops[i] ctx.data, ctx.err, ctx.hit_lvl = run_callback(self, ctx.key, ctx.shm_key, ctx.data, ctx.ttl, ctx.neg_ttl, ctx.went_stale, ctx.l1_serializer, ctx.resurrect_ttl, ctx.shm_set_tries, ctx.cb, ctx.arg) end end local bulk_mt = {} bulk_mt.__index = bulk_mt function _M.new_bulk(n_ops) local bulk = new_tab((n_ops or 2) * 4, 1) -- 4 slots per op bulk.n = 0 return setmetatable(bulk, bulk_mt) end function bulk_mt:add(key, opts, cb, arg) local i = (self.n * 4) + 1 self[i] = key self[i + 1] = opts self[i + 2] = cb self[i + 3] = arg self.n = self.n + 1 end local function bulk_res_iter(res, i) local idx = i * 3 + 1 if idx > res.n then return end i = i + 1 local data = res[idx] local err = res[idx + 1] local hit_lvl = res[idx + 2] return i, data, err, hit_lvl end function _M.each_bulk_res(res) if not res.n then error("res must have res.n field; is this a get_bulk() result?", 2) end return bulk_res_iter, res, 0 end function _M:get_bulk(bulk, opts) if type(bulk) ~= "table" then error("bulk must be a table", 2) end if not bulk.n then error("bulk must have n field", 2) end if opts then if type(opts) ~= "table" then error("opts must be a table", 2) end if opts.concurrency then if type(opts.concurrency) ~= "number" then error("opts.concurrency must be a number", 2) end if opts.concurrency <= 0 then error("opts.concurrency must be > 0", 2) end end if opts.skip_callback ~= nil and type(opts.skip_callback) ~= "boolean" then error("opts.skip_callback must be a boolean", 2) end end local n_bulk = bulk.n * 4 local res = new_tab(n_bulk - n_bulk / 4, 1) local res_idx = 1 -- only used if running L3 callbacks local n_cbs = 0 local cb_ctxs -- bulk -- { "key", opts, cb, arg } -- -- res -- { data, "err", hit_lvl } for i = 1, n_bulk, 4 do local b_key = bulk[i] local b_opts = bulk[i + 1] local b_cb = bulk[i + 2] if type(b_key) ~= "string" then error("key at index " .. i .. " must be a string for operation " .. ceil(i / 4) .. " (got " .. type(b_key) .. ")", 2) end -- worker LRU cache retrieval local data = self.lru:get(b_key) if data ~= nil then if data == CACHE_MISS_SENTINEL_LRU then data = nil end res[res_idx] = data --res[res_idx + 1] = nil res[res_idx + 2] = 1 else local pok, ttl, neg_ttl, resurrect_ttl, l1_serializer, shm_set_tries, skip_callback = pcall(check_opts, self, b_opts) -- override skip_callback from entry level -- with the one set up at bulk level if opts and opts.skip_callback ~= nil then skip_callback = opts.skip_callback end if skip_callback ~= true and type(b_cb) ~= "function" then error("callback at index " .. i + 2 .. " must be a function " .. "for operation " .. ceil(i / 4) .. " (got " .. type(b_cb) .. ")", 2) end if not pok then -- strip the stacktrace local err = ttl:match("mlcache%.lua:%d+:%s(.*)") error("options at index " .. i + 1 .. " for operation " .. ceil(i / 4) .. " are invalid: " .. err, 2) end -- not in worker's LRU cache, need shm lookup -- we will prepare a task for each cache miss local namespaced_key = self.name .. b_key local err, went_stale, is_stale data, err, went_stale, is_stale = get_shm_set_lru(self, b_key, namespaced_key, l1_serializer) if err then --res[res_idx] = nil res[res_idx + 1] = err --res[res_idx + 2] = nil elseif data ~= nil and not went_stale then if data == CACHE_MISS_SENTINEL_LRU then data = nil end res[res_idx] = data --res[res_idx + 1] = nil res[res_idx + 2] = is_stale and 4 or 2 elseif skip_callback ~= true then -- not in shm either, we have to prepare a task to run the -- L3 callback n_cbs = n_cbs + 1 if n_cbs == 1 then cb_ctxs = tablepool.fetch("bulk_cb_ctxs", 1, 0) end local ctx = tablepool.fetch("bulk_cb_ctx", 0, 15) ctx.res_idx = res_idx ctx.cb = b_cb ctx.arg = bulk[i + 3] -- arg ctx.key = b_key ctx.shm_key = namespaced_key ctx.data = data ctx.ttl = ttl ctx.neg_ttl = neg_ttl ctx.went_stale = went_stale ctx.l1_serializer = l1_serializer ctx.resurrect_ttl = resurrect_ttl ctx.shm_set_tries = shm_set_tries ctx.data = data ctx.err = nil ctx.hit_lvl = nil cb_ctxs[n_cbs] = ctx else res[res_idx] = nil res[res_idx + 1] = nil end end res_idx = res_idx + 3 end if n_cbs == 0 then -- no callback to run, all items were in L1/L2 res.n = res_idx - 1 return res end -- some L3 callbacks have to run -- schedule threads as per our concurrency settings -- we will use this thread as well local concurrency if opts then concurrency = opts.concurrency end if not concurrency then concurrency = BULK_DEFAULT_CONCURRENCY end local threads local threads_idx = 0 do -- spawn concurrent threads local thread_size local n_threads = min(n_cbs, concurrency) - 1 if n_threads > 0 then threads = tablepool.fetch("bulk_threads", n_threads, 0) thread_size = ceil(n_cbs / concurrency) end if self.debug then ngx.log(ngx.DEBUG, "spawning ", n_threads, " threads to run ", n_cbs, " callbacks") end local from = 1 local rest = n_cbs for i = 1, n_threads do local to if rest >= thread_size then rest = rest - thread_size to = from + thread_size - 1 else rest = 0 to = from end if self.debug then ngx.log(ngx.DEBUG, "thread ", i, " running callbacks ", from, " to ", to) end threads_idx = threads_idx + 1 threads[i] = thread_spawn(run_thread, self, cb_ctxs, from, to) from = from + thread_size if rest == 0 then break end end if rest > 0 then -- use this thread as one of our concurrent threads local to = from + rest - 1 if self.debug then ngx.log(ngx.DEBUG, "main thread running callbacks ", from, " to ", to) end run_thread(self, cb_ctxs, from, to) end end -- wait for other threads for i = 1, threads_idx do local ok, err = thread_wait(threads[i]) if not ok then -- when thread_wait() fails, we don't get res_idx, and thus -- cannot populate the appropriate res indexes with the -- error ngx_log(ERR, "failed to wait for thread number ", i, ": ", err) end end for i = 1, n_cbs do local ctx = cb_ctxs[i] local ctx_res_idx = ctx.res_idx res[ctx_res_idx] = ctx.data res[ctx_res_idx + 1] = ctx.err res[ctx_res_idx + 2] = ctx.hit_lvl tablepool.release("bulk_cb_ctx", ctx, true) -- no clear tab end tablepool.release("bulk_cb_ctxs", cb_ctxs) if threads then tablepool.release("bulk_threads", threads) end res.n = res_idx - 1 return res end end -- get_bulk() function _M:peek(key, stale) if type(key) ~= "string" then error("key must be a string", 2) end -- restrict this key to the current namespace, so we isolate this -- mlcache instance from potential other instances using the same -- shm local namespaced_key = self.name .. key local v, err, went_stale = self.dict:get_stale(namespaced_key) if v == nil and err then -- err can be 'flags' upon successful get_stale() calls, so we -- also check v == nil return nil, "could not read from lua_shared_dict: " .. err end -- if we specified shm_miss, it might be a negative hit cached -- there if self.dict_miss and v == nil then v, err, went_stale = self.dict_miss:get_stale(namespaced_key) if v == nil and err then -- err can be 'flags' upon successful get_stale() calls, so we -- also check v == nil return nil, "could not read from lua_shared_dict: " .. err end end if went_stale and not stale then return nil end if v ~= nil then local value, err, at, ttl = unmarshall_from_shm(v) if err then return nil, "could not deserialize value after lua_shared_dict " .. "retrieval: " .. err end local remaining_ttl = ttl - (now() - at) return remaining_ttl, nil, value, went_stale end end function _M:set(key, opts, value) if not self.broadcast then error("no ipc to propagate update, specify opts.ipc_shm or opts.ipc", 2) end if type(key) ~= "string" then error("key must be a string", 2) end do -- restrict this key to the current namespace, so we isolate this -- mlcache instance from potential other instances using the same -- shm local ttl, neg_ttl, _, l1_serializer, shm_set_tries, _ = check_opts(self, opts) local namespaced_key = self.name .. key if self.dict_miss then -- since we specified a separate shm for negative caches, we -- must make sure that we clear any value that may have been -- set in the other shm local dict = value == nil and self.dict or self.dict_miss -- TODO: there is a potential race-condition here between this -- :delete() and the subsequent :set() in set_shm() local ok, err = dict:delete(namespaced_key) if not ok then return nil, "could not delete from shm: " .. err end end local _, err = set_shm_set_lru(self, key, namespaced_key, value, ttl, neg_ttl, nil, shm_set_tries, l1_serializer, true) if err then return nil, err end end local _, err = self.broadcast(self.events.invalidation.channel, key) if err then return nil, "could not broadcast update: " .. err end return true end function _M:delete(key) if not self.broadcast then error("no ipc to propagate deletion, specify opts.ipc_shm or opts.ipc", 2) end if type(key) ~= "string" then error("key must be a string", 2) end -- delete from shm first do -- restrict this key to the current namespace, so we isolate this -- mlcache instance from potential other instances using the same -- shm local namespaced_key = self.name .. key local ok, err = self.dict:delete(namespaced_key) if not ok then return nil, "could not delete from shm: " .. err end -- instance uses shm_miss for negative caches, since we don't know -- where the cached value is (is it nil or not?), we must remove it -- from both if self.dict_miss then ok, err = self.dict_miss:delete(namespaced_key) if not ok then return nil, "could not delete from shm: " .. err end end end -- delete from LRU and propagate self.lru:delete(key) local _, err = self.broadcast(self.events.invalidation.channel, key) if err then return nil, "could not broadcast deletion: " .. err end return true end function _M:purge(flush_expired) if not self.broadcast then error("no ipc to propagate purge, specify opts.ipc_shm or opts.ipc", 2) end if not self.lru.flush_all and LRU_INSTANCES[self.name] ~= self.lru then error("cannot purge when using custom LRU cache with " .. "OpenResty < 1.13.6.2", 2) end -- clear shm first self.dict:flush_all() -- clear negative caches shm if specified if self.dict_miss then self.dict_miss:flush_all() end if flush_expired then self.dict:flush_expired() if self.dict_miss then self.dict_miss:flush_expired() end end -- clear LRU content and propagate rebuild_lru(self) local _, err = self.broadcast(self.events.purge.channel, "") if err then return nil, "could not broadcast purge: " .. err end return true end function _M:update(timeout) if not self.poll then error("no polling configured, specify opts.ipc_shm or opts.ipc.poll", 2) end local _, err = self.poll(timeout) if err then return nil, "could not poll ipc events: " .. err end return true end return _M
function serialize_islist (t) local itemcount = 0 local last_type = nil for k,v in pairs(t) do itemcount = itemcount + 1 if last_type == nil then last_type = type(v) end if type(v) ~= last_type or (type(v) ~= "string" and type(v) ~= "number" and type(v) ~= "boolean") then return false end last_type = type(v) end if itemcount ~= #t then return false end return true end function serialize (o, tabs) local result = "" if tabs == nil then tabs = "" end if type(o) == "number" then result = result .. tostring(o) elseif type(o) == "boolean" then result = result .. tostring(o) elseif type(o) == "string" then result = result .. string.format("%q", o) elseif type(o) == "table" and serialize_islist(o) then result = result .. "{" for i,v in ipairs(o) do result = result .. " " .. tostring(v) .. "," end result = result .. "}" elseif type(o) == "table" then if o.dont_serialize_me then return "{}" end result = result .. "{\n" for k,v in pairs(o) do if type(v) ~= "function" then -- make sure that numbered keys are properly are indexified if type(k) == "number" then if type(v) == "number" then result = result .. " " .. tostring(v) .. "," else result = result .. tabs .. " " .. serialize(v, tabs .. " ") .. ",\n" end else result = result .. tabs .. " " .. k .. " = " .. serialize(v, tabs .. " ") .. ",\n" end end end result = result .. tabs .. "}" else print ("ignoring stuff" .. type(o) ) end return result end return serialize
IncludeDirs = {} IncludeDirs["SFML"] = g_WorkspaceFolder .. "/../Third/SFML-2.5.1/include" project "SFML" kind "ConsoleApp" language "C++" cppdialect "C++17" -- Place where build files will be generated location (g_BuildFolder .. "/%{prj.name}") -- Place where compiled binary target targetdir (g_WorkspaceFolder .. "/../bin/%{prj.name}") -- Place where object and other intermediate files objdir (g_WorkspaceFolder .. "/../bin-int/%{prj.name}") -- Specify script files for the project files { g_WorkspaceFolder .. "/%{prj.name}/Source/**.h", g_WorkspaceFolder .. "/%{prj.name}/Source/**.cpp", } -- Window configuration filter "system:windows" -- Specify the include file search path includedirs { g_WorkspaceFolder .. "/%{prj.name}/Source/", "%{IncludeDirs.SFML}" } -- Specify the library file search path libdirs { g_WorkspaceFolder .. "/../Third/SFML-2.5.1/lib/%{cfg.system}/%{cfg.architecture}" } -- Copy dlls prebuildcommands { ("{COPY} \"%{wks.location}../Third/SFML-2.5.1/bin/%{cfg.system}/%{cfg.architecture}/*.dll\" \"%{cfg.buildtarget.directory}\"") } filter { "system:windows", "configurations:Debug" } links { "sfml-system-d.lib", "sfml-window-d.lib", "sfml-graphics-d.lib" } filter { "system:windows", "configurations:Release" } links { "sfml-system.lib","sfml-window.lib", "sfml-graphics.lib" } -- Mac configuration filter "system:macosx" systemversion "10.14" -- 我的Mac版本是10.14.5,低于development target的10.15, 为了避免手动修改,改成10.14 includedirs { g_WorkspaceFolder .. "/%{prj.name}/Source/" }-- Xcode: User Header Search Paths sysincludedirs { "%{IncludeDirs.SFML}" }--Xcode: Header Search Paths links { "sfml-system.framework", "sfml-window.framework", "sfml-graphics.framework", "freetype.framework" } linkoptions { "-F" .. g_WorkspaceFolder .. "/../Third/SFML-2.5.1/lib/%{cfg.system}/Frameworks", "-Xlinker -rpath -Xlinker " .. g_WorkspaceFolder .. "/../Third/SFML-2.5.1/lib/%{cfg.system}/Frameworks" } --syslibdirs { g_WorkspaceFolder .. "/../Third/SFML-2.5.1/lib/%{cfg.system}/Frameworks" } --libdirs { g_WorkspaceFolder .. "/../Third/SFML-2.5.1/lib/%{cfg.system}/Frameworks" } -- runpathdirs -- { -- g_WorkspaceFolder .. "/../bin/%{prj.name}", -- g_WorkspaceFolder .. "/../Third/SFML-2.5.1/lib/%{cfg.system}/Frameworks", -- g_WorkspaceFolder .. "/../Third/SFML-2.5.1/lib/%{cfg.system}/extlibs" -- } -- prebuildcommands -- { -- ("{COPY} \"%{wks.location}/../Third/SFML-2.5.1/lib/%{cfg.system}/Frameworks/sfml-system.framework\" \"%{cfg.buildtarget.directory}\""), -- ("{COPY} \"%{wks.location}/../Third/SFML-2.5.1/lib/%{cfg.system}/Frameworks/sfml-window.framework\" \"%{cfg.buildtarget.directory}\""), -- ("{COPY} \"%{wks.location}/../Third/SFML-2.5.1/lib/%{cfg.system}/Frameworks/sfml-graphics.framework\" \"%{cfg.buildtarget.directory}\""), -- ("{COPY} \"%{wks.location}/../Third/SFML-2.5.1/lib/%{cfg.system}/Frameworks/freetype.framework\" \"%{cfg.buildtarget.directory}\"") -- }
HALO = HALO or {} HALO.VehicleSettings = HALO.VehicleSettings or {} HALO.VehicleSettings["h3scorpionsnow"] = { TrackID = "h3scorpionsnow", TrackTexture = "snowysnowtime/2k/h3sf/s/tread", TrackNormal = "snowysnowtime/2k/h3sf/s/tread_n", TrackPhongTint = "snowysnowtime/2k/phongexp255", TrackDiv = 100, TrackMult = 0.1, LeftTrackSubMatIndex = 10, RightTrackSubMatIndex = 11, }
PathFinding = class("PathFinding") PathFinding.PrioNormal = 1 PathFinding.PrioObstacle = 1000 PathFinding.PrioForbidden = 1000000 PathFinding.Ctor = function (slot0, slot1, slot2, slot3) slot0.cells = slot1 slot0.rows = slot2 slot0.columns = slot3 end PathFinding.Find = function (slot0, slot1, slot2) slot2 = { row = slot2.row, column = slot2.column } if slot0.cells[({ row = slot1.row, column = slot1.column })["row"]][()["column"]] < 0 or slot0.cells[slot2.row][slot2.column] < 0 then return 0, {} else return slot0:_Find(slot1, slot2) end end slot1 = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } } PathFinding._Find = function (slot0, slot1, slot2) slot3 = slot0.PrioForbidden slot4 = {} slot5 = { slot1 } slot6 = {} slot7 = { [slot1.row] = { [slot1.column] = { priority = 0, path = {} } } } while #slot5 > 0 do if table.remove(slot5, 1).row == slot2.row and slot8.column == slot2.column then slot3 = slot7[slot8.row][slot8.column].priority slot4 = slot7[slot8.row][slot8.column].path break end table.insert(slot6, slot8) _.each(slot1, function (slot0) if not (_.any({ row = slot0.row + slot0[1], column = slot0.column + slot0[2] }, function (slot0) return slot0.row == slot0.row and slot0.column == slot0.column end) or _.any(_.any, function (slot0) return slot0.row == slot0.row and slot0.column == slot0.column end)) and slot1.row >= 0 and slot1.row < slot3.rows and slot1.column >= 0 and slot1.column < slot3.columns then if slot4[slot0.row][slot0.column].priority + slot3.cells[slot1.row][slot1.column] < slot3.cells[slot1.row][slot1.column].PrioObstacle then table.insert(Clone(slot3).path, slot1) Clone(slot3).priority = slot4 slot4[slot1.row] = slot4[slot1.row] or {} slot4[slot1.row][slot1.column] = slot5 slot6 = 0 for slot10 = #slot1, 1, -1 do if slot4[slot1[slot10].row][slot1[slot10].column].priority <= slot5.priority then slot6 = slot10 break end end table.insert(slot1, slot6 + 1, slot1) else slot6 = math.min(slot6, slot4) end end end) end if slot0.PrioObstacle <= slot3 then slot8 = 1000000 slot9 = slot0.PrioForbidden for slot13, slot14 in pairs(slot7) do for slot18, slot19 in pairs(slot14) do if slot8 > math.abs(slot2.row - slot13) + math.abs(slot2.column - slot18) or (slot20 == slot8 and slot19.priority < slot9) then slot8 = slot20 slot9 = slot19.priority slot4 = slot19.path end end end end return slot3, slot4 end return PathFinding
local player_langs = {} local translatedChatMessage do local chatMessage = tfm.exec.chatMessage function translatedChatMessage(what, who, ...) if not who then for player in next, player_langs do translatedChatMessage(what, player, ...) end return end local text = player_langs[who][what] if not text then text = "%" .. what .. "%" elseif select("#", ...) > 0 then done, text = pcall(string.format, text, ...) if not done then error(debug.traceback()) end end chatMessage(text, who) end end onEvent("NewPlayer", function(player) player_langs[player] = translations[tfm.get.room.playerList[player].community] end)
ESX = nil TriggerEvent( "esx:getSharedObject", function(obj) ESX = obj end ) RegisterServerEvent("sellOxy") AddEventHandler( "sellOxy", function(itemName) local xPlayer = ESX.GetPlayerFromId(source) local price = 500 local amount = math.random(1, 3) local xItem = xPlayer.getInventoryItem(itemName) -- Player does not have enough of oxy to sell so set it to 1 if xPlayer.getInventoryItem(itemName).count > amount then amount = 1 end -- Player does not have any more oxy if xPlayer.getInventoryItem(itemName).count < 1 then xPlayer.showNotification("~r~You do not have any more oxy to sell!") TriggerClientEvent("endOxyJob", source) return end price = ESX.Math.Round(price * amount) xPlayer.addMoney(price) xPlayer.removeInventoryItem(xItem.name, amount) xPlayer.showNotification( "~g~You sold " .. amount .. " " .. xItem.label .. " for a total of $" .. ESX.Math.GroupDigits(price) ) end ) RegisterNetEvent("startOxyRun") AddEventHandler( "startOxyRun", function() local xPlayer = ESX.GetPlayerFromId(source) xPlayer.addInventoryItem("oxy", 10 - xPlayer.getInventoryItem("oxy").count) end )
return {'ome','omega','omelet','omen','omerta','omer','omeg','omeletten','omes','omegas','omers'}
insulate("documentation on Merchant", function() require "init" require "spec.mocks" require "spec.asserts" require "spec.universe" it("new", function() local printedLines = {} local print = function(string) table.insert(printedLines, string) end local split = function(input) local t={} for str in string.gmatch(input, "([^\n]+)") do table.insert(t, str) end return t end -- tag::basic[] local products = { power = Product:new("Energy Cell"), o2 = Product:new("Oxygen"), } local station = SpaceStation() Station:withStorageRooms(station, { [products.power] = 1000, [products.o2] = 500, }) Station:withMerchant(station, { [products.power] = { buyingPrice = 1, buyingLimit = 420 }, [products.o2] = { sellingPrice = 5, sellingLimit = 42 }, }) station:modifyProductStorage(products.power, 100) station:modifyProductStorage(products.o2, 100) local function printMerchant(station, product) if station:isBuyingProduct(product) then print(string.format( "Station buys a maximum of %d units of %s at a price of %d.", station:getMaxProductBuying(product), product:getName(), station:getProductBuyingPrice(product) )) elseif station:isSellingProduct(product) then print(string.format( "Station sells a maximum of %d units of %s at a price of %d.", station:getMaxProductSelling(product), product:getName(), station:getProductSellingPrice(product) )) end end printMerchant(station, products.power) printMerchant(station, products.o2) -- will print: -- end::basic[] local expected = split([[ -- tag::basic[] -- Station buys a maximum of 320 units of Energy Cell at a price of 1. -- Station sells a maximum of 58 units of Oxygen at a price of 5. -- end::basic[] ]]) table.remove(expected, #expected) table.remove(expected, #expected) table.remove(expected, 1) assert.is_same(#expected, #printedLines) for i=1,#expected do local exp = expected[i]:gsub("^[%s%-]+", "") assert.is_same(exp, printedLines[i]) end end) end)
--=========== Copyright © 2019, Planimeter, All rights reserved. ===========-- -- -- Purpose: Voice HUD -- --==========================================================================-- class "gui.hudvoice" ( "gui.box" ) local hudvoice = gui.hudvoice function hudvoice:hudvoice( parent, name ) gui.box.box( self, parent, name ) end function hudvoice:draw() gui.box.draw( self ) end
minetest.register_on_newplayer(function(player) print("Un nouveau joueur vient de nous rejoindre !") if minetest.setting_getbool("give_initial_stuff") then local pinv = player:get_inventory() minetest.log("action", "Giving initial stuff to player "..player:get_player_name()) pinv:add_item('main', 'default:cobble 99') pinv:add_item('main', 'colored_steel:block_blue 99') pinv:add_item('main', 'default:torch 99') pinv:add_item('main', 'default:cherry_plank 99') pinv:add_item('main', 'bakedclay:magenta 99') pinv:add_item('main', 'moreblocks:all_faces_tree 99') end end)
include "premake5_workspace_files.lua" workspace "udsc2" startproject "tests" workspace_files { ".gitignore", "premake5.lua", "premake5_workspace_files.lua", "tests.runsettings", } configurations { "Debug-Static", "Debug-Shared", "Release-Static", "Release-Shared", } platforms { "Windows-x32", "Windows-x64", } filter "platforms:*-x32" architecture "x32" filter "platforms:*-x64" architecture "x64" filter "platforms:Windows-*" system "windows" outputdir = "%{cfg.buildcfg}-%{cfg.platform}" project "udsc2" location "%{prj.name}" language "C++" cppdialect "C++17" targetdir "bin/%{outputdir}/%{prj.name}" objdir "int/%{outputdir}/%{prj.name}" files { "%{prj.name}/src/**.h", "%{prj.name}/src/**.hpp", "%{prj.name}/src/**.c", "%{prj.name}/src/**.cpp", "%{prj.name}/include/**.h", "%{prj.name}/include/**.hpp", } includedirs { "%{prj.name}/include", "%{prj.name}/src", } defines "UDSC2_BUILD" filter "system:windows" systemversion "latest" filter "configurations:Debug-*" defines "UDSC2_DEBUG" symbols "On" filter "configurations:Release-*" defines "UDSC2_RELEASE" optimize "On" filter "configurations:*-Static" kind "StaticLib" filter "configurations:*-Shared" kind "SharedLib" defines "UDSC2_SHARED" filter "architecture:x32" defines "UDSC2_X32" filter "architecture:x64" defines "UDSC2_X64" filter "toolset:msc-*" buildoptions { "/Zc:__cplusplus", } project "tests" location "%{prj.name}" kind "ConsoleApp" language "C++" cppdialect "C++17" targetdir "bin/%{outputdir}/%{prj.name}" objdir "int/%{outputdir}/%{prj.name}" files { "%{prj.name}/src/**.h", "%{prj.name}/src/**.hpp", "%{prj.name}/src/**.c", "%{prj.name}/src/**.cpp", } includedirs { "%{prj.name}/src", "%{prj.name}/vendor", "udsc2/include", } links { "udsc2" } filter "system:windows" systemversion "latest" filter "configurations:Debug-*" defines "UDSC2_DEBUG" symbols "On" filter "configurations:Release-*" defines "UDSC2_RELEASE" optimize "On" filter "configurations:*-Static" includedirs { "udsc2/src", } filter "configurations:*-Shared" defines "UDSC2_SHARED" filter "architecture:x32" defines "UDSC2_X32" filter "architecture:x64" defines "UDSC2_X64" filter "toolset:msc-*" buildoptions { "/Zc:__cplusplus", } project "sandbox" location "%{prj.name}" kind "ConsoleApp" language "C++" cppdialect "C++17" targetdir "bin/%{outputdir}/%{prj.name}" objdir "int/%{outputdir}/%{prj.name}" files { "%{prj.name}/src/**.h", "%{prj.name}/src/**.hpp", "%{prj.name}/src/**.c", "%{prj.name}/src/**.cpp", } includedirs { "%{prj.name}/src", "udsc2/include", } links { "udsc2", } filter "system:windows" systemversion "latest" filter "configurations:Debug-*" defines "UDSC2_DEBUG" symbols "On" filter "configurations:Release-*" defines "UDSC2_RELEASE" optimize "On" filter "architecture:x32" defines "UDSC2_X32" filter "architecture:x64" defines "UDSC2_X64" filter "toolset:msc-*" buildoptions { "/Zc:__cplusplus", } -- Clean Function -- newaction { trigger = "clean", description = "clean the binaries and intermediates.", execute = function () os.rmdir("./bin") os.rmdir("./int") print("Done.") end }
----------------------------------- -- Area: Northern San d'Oria -- NPC: Vamorcote -- Starts and Finishes Quest: The Setting Sun -- !pos -137.070 10.999 161.855 231 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- require("scripts/globals/quests") require("scripts/globals/settings") local ID = require("scripts/zones/Northern_San_dOria/IDs") ----------------------------------- function onTrade(player, npc, trade) -- "The Setting Sun" conditional script if (player:getQuestStatus(SANDORIA, tpz.quest.id.sandoria.THE_SETTING_SUN) == QUEST_ACCEPTED) then if (trade:hasItemQty(535, 1) and trade:getItemCount() == 1) then player:startEvent (658) end end end function onTrigger(player, npc) -- Look at the "The Setting Sun" quest status and San d'Oria player's fame theSettingSun = player:getQuestStatus(SANDORIA, tpz.quest.id.sandoria.THE_SETTING_SUN) if (theSettingSun == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 5 and player:getQuestStatus(SANDORIA, tpz.quest.id.sandoria.BLACKMAIL) ~= QUEST_COMPLETED) then player:startEvent(654, 0, 535, 535) --The quest is offered to the player. elseif (theSettingSun == QUEST_ACCEPTED) then player:startEvent(655, 0, 0, 535) --The NPC asks if the player got the key.' elseif (theSettingSun == QUEST_COMPLETED and player:needToZone()) then player:startEvent(659) --The quest is already done by the player and the NPC does small talks. else player:startEvent(651) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if (csid == 654 and option == 1) then --Player accepts the quest player:addQuest(SANDORIA, tpz.quest.id.sandoria.THE_SETTING_SUN) elseif (csid == 658) then --The player trades the Engraved Key to the NPC. Here come the rewards! player:tradeComplete() player:addGil(GIL_RATE*10000) player:messageSpecial(ID.text.GIL_OBTAINED, GIL_RATE*10000) player:addFame(SANDORIA, 30) player:completeQuest(SANDORIA, tpz.quest.id.sandoria.THE_SETTING_SUN) end end
local t = setmetatable({}, { __add = function(a, b) if b > 200 then for j=1,10 do end return b+3 elseif b > 100 then return b+2 else return b+1 end end }) local function f(t, i) do return t+i end -- Force large frame with unassigned slots below mm. do local a,b,c,d,e,f,g,h,i,j,k end end local x = 0 for i=1,300 do x = f(t, i) end assert(x == 303)
-- Notas disponíveis de R$ 100,00; R$ 50,00; R$ 20,00 e R$ 10,00 -- Entregar o menor número de notas cedulas = {100, 50, 20, 10} function saque(valor) local result = {} result[100] = math.floor(valor/cedulas[1]) -- valor restante para ser dividido pelas notas seguintes na tabela valor = valor%cedulas[1] result[50] = math.floor(valor/cedulas[2]) valor = valor%cedulas[2] result[20] = math.floor(valor/cedulas[3]) valor = valor%cedulas[3] result[10] = math.floor(valor/cedulas[4]) return result end
local utils = require("utils") -- Patterns of root folder local root_markers = { '.git', 'mvnw', 'gradlew', 'Config', -- Amazon } local root_dir = require('jdtls.setup').find_root(root_markers) -- Project root directory local jdtls_home = '$XDG_DATA_HOME/nvim/lsp_servers/jdtls' local jdtls_workspace = utils.path.concat('$XDG_CACHE_HOME/jdtls-workspace', vim.fn.fnamemodify(root_dir, ":p:h:t")) -- Create jdtls_workspace if it doesn't exist utils.path.safe_path(jdtls_workspace) --- MARK: Setup bundles local jdtls_bundles = {} -- Setup debugger vim.list_extend(jdtls_bundles, utils.path.java.java_debug_jars) vim.list_extend(jdtls_bundles, utils.path.java.vscode_java_test_jars) -- MARK: Setup Commands local jdtls_cmd = { 'java', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Dlog.protocol=true', '-Dlog.level=ALL', '-Xms1g', '--add-modules=ALL-SYSTEM', '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', } -- Setup Lombok support; must in front of `-jar` if utils.path.java.lombok_jars then vim.list_extend(jdtls_cmd, { "-javaagent:" .. utils.path.java.lombok_jars[1], -- "-Xbootclasspath/a:" .. utils.path.java.lombok_jars[1], }) end vim.list_extend(jdtls_cmd, { '-jar', vim.fn.glob(utils.path.concat(jdtls_home, 'plugins/org.eclipse.equinox.launcher_*.jar')), '-configuration', vim.fn.glob(utils.path.concat(jdtls_home, '/config_' .. utils.get_os())), '-data', vim.fn.glob(jdtls_workspace), }) -- See `:help vim.lsp.start_client` for an overview of the supported `config` options. return { -- The command that starts the lanjuage server -- See: https://github.com/eclipse/eclipse.jdt.ls#running-from-the-command-line cmd = jdtls_cmd, root_dir = root_dir, -- Here you can configure eclipse.jdt.ls specific settings -- See https://github.com/eclipse/eclipse.jdt.ls/wiki/Running-the-JAVA-LS-server-from-the-command-line#initialize-request -- for a list of options settings = { java = { signatureHelp = { enabled = true }; codeGeneration = { toString = { template = "${object.className}{${member.name()}=${member.value}, ${otherMembers}}", }, }, sources = { organizeImports = { starThreshold = 9999, staticStarThreshold = 9999, }, }, }, }, -- Language server `initializationOptions` -- You need to extend the `bundles` with paths to jar files -- if you want to use additional eclipse.jdt.ls plugins. -- -- See https://github.com/mfussenegger/nvim-jdtls#java-debug-installation -- -- If you don't plan on using the debugger or other eclipse.jdt.ls plugins you can remove this init_options = { bundles = jdtls_bundles }, }
-- a crude constriction escape simulator local niters = 10000 local mons = { [1]="ball python", [5]="naga", [10]="naga_warrior", [15]="greater_naga", [23]="tentacled_monstrosity" } for hd,mon in pairs(mons) do crawl.stderr(string.format("Against %s HD %d", mon, hd)) crawl.stderr("| str | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |") for str = 3, 27, 3 do local line = string.format("| %02d |", str) for turns = 1, 8 do local escape = 0 for i = 1, niters do if crawl.roll_dice(4+turns, 8 + crawl.div_rand_round(str, 4)) >= crawl.roll_dice(5, 8 + crawl.div_rand_round(hd, 4)) then escape = escape + 1 end end line = line .. string.format(" %5.1f |", escape * 100 / niters) end crawl.stderr(line) end crawl.stderr("") end
--[[------------------------------------------------------------------------- You are free to use, distribute and change this module, as long as you keep this text here - and/or credit me: Made by Fillipuster :D ---------------------------------------------------------------------------]] CLASSICADVERT = CLASSICADVERT or {} --[[------------------------------------------------------------------------- CLASSIC ADVERT CONFIG ---------------------------------------------------------------------------]] -- The prefix before the adverted text (but after the sending player's name). CLASSICADVERT.chatPrefix = "[Advert]" -- The color of the text in the advert (Originally yellow). CLASSICADVERT.advertTextColor = Color( 255, 255, 0, 255 ) -- The failure message id the players fails to provide text for the advert. CLASSICADVERT.failMessage = "You need to provide text for your advert." -- The chat command for adverts. (A "/" is added at the front automatically.) CLASSICADVERT.chatCommand = "ad" -- Please, do not use "/advert" as it is used for the new advert system in DarkRP. -- The F1 (help menu) description of the advert command. CLASSICADVERT.commandDescription = "Message all players on the server." -- The delay (in seconds) between players being able to advert. CLASSICADVERT.commandDelay = 3 --[[------------------------------------------------------------------------- END OF CONFIG ---------------------------------------------------------------------------]] DarkRP.declareChatCommand{ command = CLASSICADVERT.chatCommand, description = CLASSICADVERT.commandDescription, delay = CLASSICADVERT.commandDelay }
object_tangible_storyteller_event_props_pr_ommni_box_nosnap = object_tangible_storyteller_event_props_shared_pr_ommni_box_nosnap:new { } ObjectTemplates:addTemplate(object_tangible_storyteller_event_props_pr_ommni_box_nosnap, "object/tangible/storyteller/event_props/pr_ommni_box_nosnap.iff")
INVALID_RP_NAMES = {}; function GM.GatherInvalidNames ( ) /* http.Get(URL_INVALID_RP_NAMES, "", function ( results ) for k, v in pairs(string.Explode("\n", string.lower(results))) do table.insert(INVALID_RP_NAMES, string.Explode(" ", string.Trim(v))); end end); */ end function GM.IsValidPartialName ( name ) if (string.len(name) < 3) then return false; end if (string.len(name) >= 16) then return false; end local name = string.lower(name); local numDashes = 0; for i = 1, string.len(name) do local validLetter = false; local curChar = string.sub(name, i, i); if (curChar == "-") then numDashes = numDashes + 1; if (numDashes > 1) then return false; end end for k, v in pairs(VALID_NAME_CHARACTERS) do if (curChar == v) then validLetter = true; break; end end if (!validLetter) then Msg("bad char") return false; end end /* for k, v in pairs(INVALID_RP_NAMES) do if (#v == 1) then if (string.sub(v[1], 0, 1) == "^") then if (string.sub(name, 0, string.len(v[1]) - 1) == string.sub(v[1], 2)) then return false; end elseif (string.find(name, v[1])) then return false; end end end */ return true; end function GM.IsValidName ( first, last, skipFirstLast ) local first = string.lower(first); local last = string.lower(last); if (!skipFirstLast) then if (!GAMEMODE.IsValidPartialName(first)) then return false; end if (!GAMEMODE.IsValidPartialName(last)) then return false; end end if (first == "john" && last == "doe") then return false end /* for k, v in pairs(INVALID_RP_NAMES) do if (#v > 1) then if (first == v[1] && last == v[2]) then return false; end end end */ return true; end
att.PrintName = "Extended Barrel" att.Icon = Material("snowysnowtime/2k/ico/h3/smg_sil.png") att.Description = "Suppressor attachment often used by special forces." att.Desc_Pros = { } att.Desc_Cons = { } att.SortOrder = 997 att.Slot = "barrel_smgho" att.Override_MuzzleEffect = "astw2_halo_spv3_muzzle_DMR" att.Override_MuzzleEffectAttachment = "1" att.Mult_ShootVol = 1.1 att.Mult_Recoil = 0.9 att.Mult_Range = 1.5 att.Mult_Precision = 0.9 att.Mult_SightTime = 1.2 att.Mult_SightedSpeedMult = 0.8 att.Add_BarrelLength = 8 att.AttachSound = "attch/snow/halo/h3/x_button.wav" att.DetachSound = "attch/snow/halo/h3/b_button.wav" att.ActivateElements = {"v3_barrel"}
function range(i, j) local t = {} for n = i, j, i<j and 1 or -1 do t[#t+1] = n end return t end function expand_ranges(rspec) local ptn = "([-+]?%d+)%s?-%s?([-+]?%d+)" local t = {} for v in string.gmatch(rspec, '[^,]+') do local s, e = v:match(ptn) if s == nil then t[#t+1] = tonumber(v) else for i, n in ipairs(range(tonumber(s), tonumber(e))) do t[#t+1] = n end end end return t end local ranges = "-6,-3--1,3-5,7-11,14,15,17-20" print(table.concat(expand_ranges(ranges), ', '))
local fiber = require('fiber') local config = require('config') local client = require('http.client').new() local json = require('json') local logger = require('log') local M = {} M.queue = require('queue') M.transport = { finder = { sid = nil, fb = nil }, sender = { sid = nil, fb = nil }, tunnel = fiber.channel(1), } M.client_opts = { ['headers'] = { ['User-Agent'] = config.shipper.user_agent, ['X-Auth-Token'] = config.shipper.token, ['Content-Type'] = 'application/json', } } -- Check if module can start function M.can_start() local queue_status = M.queue ~= nil local shipper_status = config.shipper.enable == true return (queue_status and shipper_status) end -- Pack task before send to app function M.serialize(task) return { task_id = task['task_id'], queue = task['tube'], data = task[3] } end -- Taking the new task from the channel and send it to external app function M.sender_worker() local webhook = config.shipper.webhook_url local options = M.client_opts local queue = M.queue -- Save fiber session id M.transport.sender.sid = M.queue.identify() while true do if M.transport.tunnel:is_empty() then logger.debug('Sender: channel is empty') fiber.sleep(config.shipper.delay) else local task = M.transport.tunnel:get(0) logger.debug('Sender: received new task') local success, push_err = pcall(function() return client:post(webhook, json.encode(task), options) end) if success then local tube_name = task['tube'] -- Before call ack need to apply finder's session to prevent error 'Task was not taken' queue.identify(M.transport.finder.sid) local ok, resp = pcall(function() return M.queue.tube[tube_name]:ack(task['task_id']) end) if ok then logger.info('Sender: task %s#%s has been shipped', task['task_id'], task['tube']) else logger.error('Sender: failed to ack task, %s', tostring(resp)) end else logger.error('Sender: failed to shipped task: ' .. tostring(push_err)) end fiber.sleep(config.shipper.delay) end end end -- Iterating over tubes, find new task and pass it to the sender_worker function M.finder_worker() local queue = M.queue M.transport.finder.sid = queue.identify() while true do queue.identify(M.transport.finder.sid) for tube_name, _ in pairs(queue.tube) do local success, item = pcall(function() return queue.tube[tube_name]:take(0) end) if success and item ~= nil then local task = M.serialize(item) task['tube'] = tube_name M.transport.tunnel:put(task) logger.verbose('Finder: found new task') else logger.verbose('Finder: waiting for new task...') end end fiber.sleep(config.shipper.delay) end end -- Run shipper function M.start() if M.can_start() then -- Start workers local finder = M.transport.finder finder.fb = fiber.create(M.finder_worker) finder.fb:name('finder') local sender = M.transport.sender sender.fb = fiber.create(M.sender_worker) sender.fb:name('sender') return true else logger.error('Failed to start workers') return false end end -- Stop shipper function M.stop() local finder = M.transport.finder local sender = M.transport.sender for fib in pairs({finder, sender}) do fib.fb:kill(); end end return M
local insert = table.insert if mods['aai-industry'] then insert(data.raw.locomotive['locomotive-mk2'].burner.fuel_categories, 'processed-chemical') insert(data.raw.locomotive['locomotive-mk3'].burner.fuel_categories, 'processed-chemical') insert(data.raw.locomotive['locomotive-mk4'].burner.fuel_categories, 'processed-chemical') end
-------------------- -- For Detoxed <3 -- -------------------- local Detoxed = LibStub("AceAddon-3.0"):NewAddon("Detoxed", "AceEvent-3.0", "AceConsole-3.0", "AceTimer-3.0") local InCombatLockdown = _G["InCombatLockdown"] local PlaySoundFile = _G["PlaySoundFile"] local random = math.random local pictures = { [[Interface\AddOns\Detoxed\Media\cat.tga]], [[Interface\AddOns\Detoxed\Media\cat2.tga]], [[Interface\AddOns\Detoxed\Media\cat3.tga]], } local sounds = { [[Interface\AddOns\Detoxed\Media\CatMeow2.ogg]], [[Interface\AddOns\Detoxed\Media\KittenMeow.ogg]], } function Detoxed:ShowFrame() PlaySoundFile(sounds[random(1, #sounds)]) self.frame.bg:SetTexture(pictures[random(1, #pictures)]) self.frame:Show() end function Detoxed:OnDisable() self:CancelAllTimers() end function Detoxed:OnEnable() self:ScheduleTimer(function() self:ShowFrame() self:ScheduleTimer(function() self.frame:Hide() end, random(1, 10)) self.displayTimer = self:ScheduleRepeatingTimer(function() local toShow = random(1, 100) if toShow > 50 and not InCombatLockdown() then self:ShowFrame() self:ScheduleTimer(function() self.frame:Hide() end, random(1, 10)) end end, 120) end, random(10, 30)) end function Detoxed:OnInitialize() -- create the frame self.frame = CreateFrame("Frame", "DetoxedFrame", UIParent) self.frame:SetResizable(false) self.frame:SetClampedToScreen(true) self.frame:ClearAllPoints() self.frame:SetPoint("CENTER") self.frame:SetSize(512, 512) self.frame.bg = self.frame:CreateTexture(nil, "BACKGROUND") self.frame.bg:SetPoint("CENTER") self.frame.bg:SetSize(512, 512) self.frame:Hide() end
local reload = require("nvim-reload") reload.pre_reload_hook = function() end
-- FormattedCountdown v1.0 obs = obslua source_name = "" total_seconds = 0 cur_seconds = 0 format_text = "" last_text = "" stop_text = "" activated = false hotkey_id = obs.OBS_INVALID_HOTKEY_ID -- Function to set the time text function set_time_text() local seconds = math.floor(cur_seconds % 60) local total_minutes = math.floor(cur_seconds / 60) local minutes = math.floor(total_minutes % 60) local hours = math.floor(total_minutes / 60) -- Format text local text = string.gsub(format_text, "$h", hours > 9 and hours or "0" .. hours) text = string.gsub(text, "$m", minutes > 9 and minutes or "0" .. minutes) text = string.gsub(text, "$s", seconds > 9 and seconds or "0" .. seconds) if cur_seconds < 1 then text = stop_text end if text ~= last_text then local source = obs.obs_get_source_by_name(source_name) if source ~= nil then local settings = obs.obs_data_create() obs.obs_data_set_string(settings, "text", text) obs.obs_source_update(source, settings) obs.obs_data_release(settings) obs.obs_source_release(source) end end last_text = text end function timer_callback() cur_seconds = cur_seconds - 1 if cur_seconds < 0 then obs.remove_current_callback() cur_seconds = 0 end set_time_text() end function activate(activating) if activated == activating then return end activated = activating if activating then cur_seconds = total_seconds set_time_text() obs.timer_add(timer_callback, 1000) else obs.timer_remove(timer_callback) end end -- Called when a source is activated/deactivated function activate_signal(cd, activating) local source = obs.calldata_source(cd, "source") if source ~= nil then local name = obs.obs_source_get_name(source) if (name == source_name) then activate(activating) end end end function source_activated(cd) activate_signal(cd, true) end function source_deactivated(cd) activate_signal(cd, false) end function reset(pressed) if not pressed then return end activate(false) local source = obs.obs_get_source_by_name(source_name) if source ~= nil then local active = obs.obs_source_active(source) obs.obs_source_release(source) activate(active) end end function reset_button_clicked(props, p) reset(true) return false end ---------------------------------------------------------- -- A function named script_properties defines the properties that the user can change for -- the entire script module itself function script_properties() local props = obs.obs_properties_create() obs.obs_properties_add_int(props, "duration", "Duration (seconds)", 1, 3600000, 1) obs.obs_properties_add_text(props, "format_text", "Output Format", obs.OBS_TEXT_DEFAULT) local p = obs.obs_properties_add_list(props, "source", "Text Source", obs.OBS_COMBO_TYPE_EDITABLE, obs.OBS_COMBO_FORMAT_STRING) local sources = obs.obs_enum_sources() if sources ~= nil then for _, source in ipairs(sources) do source_id = obs.obs_source_get_id(source) if source_id == "text_gdiplus" or source_id == "text_ft2_source" then local name = obs.obs_source_get_name(source) obs.obs_property_list_add_string(p, name, name) end end end obs.source_list_release(sources) obs.obs_properties_add_text(props, "stop_text", "Final Text", obs.OBS_TEXT_DEFAULT) obs.obs_properties_add_button(props, "reset_button", "Reset Timer", reset_button_clicked) return props end -- A function named script_description returns the description shown to the user function script_description() return "Sets a text source to act as a countdown timer when the source is active.\n\n" .. "Output Format: $h = hours, $m = minutes, $s = seconds\n\n" .. "-----\n\n" .. "Originally made by Jim - improved by Genesis (v1.0)" end -- A function named script_update will be called when settings are changed function script_update(settings) activate(false) total_seconds = obs.obs_data_get_int(settings, "duration") format_text = obs.obs_data_get_string(settings, "format_text") source_name = obs.obs_data_get_string(settings, "source") stop_text = obs.obs_data_get_string(settings, "stop_text") reset(true) end -- A function named script_defaults will be called to set the default settings function script_defaults(settings) obs.obs_data_set_default_int(settings, "duration", 300) obs.obs_data_set_default_string(settings, "format_text", "$h:$m:$s") obs.obs_data_set_default_string(settings, "stop_text", "Starting soon (tm)") end -- A function named script_save will be called when the script is saved -- -- NOTE: This function is usually used for saving extra data (such as in this case, a -- hotkey's save data). Settings set via the properties are saved automatically. function script_save(settings) local hotkey_save_array = obs.obs_hotkey_save(hotkey_id) obs.obs_data_set_array(settings, "reset_hotkey", hotkey_save_array) obs.obs_data_array_release(hotkey_save_array) end -- a function named script_load will be called on startup function script_load(settings) -- Connect hotkey and activation/deactivation signal callbacks -- -- NOTE: These particular script callbacks do not necessarily have to be disconnected, as -- callbacks will automatically destroy themselves if the script is unloaded. So there's -- no real need to manually disconnect callbacks that are intended to last until the -- script is unloaded. local sh = obs.obs_get_signal_handler() obs.signal_handler_connect(sh, "source_activate", source_activated) obs.signal_handler_connect(sh, "source_deactivate", source_deactivated) hotkey_id = obs.obs_hotkey_register_frontend("reset_timer_thingy", "Reset Timer", reset) local hotkey_save_array = obs.obs_data_get_array(settings, "reset_hotkey") obs.obs_hotkey_load(hotkey_id, hotkey_save_array) obs.obs_data_array_release(hotkey_save_array) end