content
stringlengths
5
1.05M
--[[ -- -- Copyright (c) 2013-2017 Wilson Kazuo Mizutani -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to -- deal in the Software without restriction, including without limitation the -- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -- sell copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE -- --]] --- A module-packing feature for more comfortable `require`-ing -- @module lux.pack local packs = {} local pack_meta = {} function pack_meta:__index (name) return require(self.__name.."."..name) end return function (name) local pack = packs[name] if not pack then pack = setmetatable({ __name = name }, pack_meta) packs[name] = pack end return pack end
--[[ Copyright 2019 Teverse @File core/server/characterController.lua @Author(s) Jay --]] local controller = {} controller.defaultSpeed = 50 controller.characters = {} controller.chat = nil update = function(client, cameraDirection) local totalForce = vector3() local moved = false for i, pressed in pairs(controller.characters[client].keys) do if pressed then moved=true totalForce = totalForce + (cameraDirection * controller.keyBinds[i]) end end if moved then --controller.characters[client].character:applyImpulse(totalForce * 10) local f = totalForce*10 f.y = controller.characters[client].character.velocity.y local lv = vector3(f.x, 0, f.z) if lv ~= vector3(0,0,0) then controller.characters[client].character.rotation = quaternion:setLookRotation(lv) end controller.characters[client].character.velocity = f end return moved end engine.networking.clients:clientConnected(function (client) wait(1) print("spawning", client.id) local char = engine.construct("block", workspace, { name = client.id, size = vector3(3, 4, 1.5), colour = colour:random(), position = vector3(0, 20, 0), static = false, rollingFriction = 1.5, spinningFriction = 1.5, friction = 1.5, linearDamping = 0.5, -- mesh = "primitive:sphere", angularFactor = vector3(0, 0, 0) }) --engine.networking:toAllClients("characterSpawned", client.id) local fallen = false char:changed(function(property, value) if property == "position" and not fallen then -- This should probably not be hard coded like this if value.y < -50 then fallen=true print("Player fell: ", client.name) char.static = true wait(.1) engine.tween:begin(char, 1, {position = vector3(0,10,10), rotation=quaternion(0,0,0,1)}, "inOutQuad") wait(1.2) char.static = false fallen = false else local v = char.velocity v.y=0 v = v:normal() --print(v) -- char.rotation = quaternion:setLookRotation(v) end end end) controller.characters[client] = { updating=false, character = char, keys = {false,false,false,false}, speed = controller.defaultSpeed } end) engine.networking.clients:clientDisconnected(function (client) wait(1) if controller.characters[client] then controller.characters[client].character:destroy() controller.characters[client] = nil end end) controller.keyBinds = { vector3( 0, 0, 1), --w vector3( 0, 0, -1), --s vector3( 1, 0, 0), --a vector3(-1, 0, 0) -- d } engine.networking:bind( "characterSetInputStarted", function( client, direction, cameraDirection ) if not controller.characters[client] then return end cameraDirection = quaternion:setEuler(0, cameraDirection:getEuler().y + math.rad(180), 0) if direction == 5 then controller.characters[client].character:applyImpulse(0,300,0) return nil elseif controller.characters[client].keys[direction] == nil then return nil end controller.characters[client].keys[direction] = true if not controller.characters[client].updating then controller.characters[client].updating = true engine.graphics:frameDrawn(function() if not update(client, cameraDirection) then controller.characters[client].updating =false self:disconnect() -- no input from user. end end) end end) engine.networking:bind( "characterSetInputEnded", function( client, direction ) if not controller.characters[client] then return end if controller.characters[client].keys[direction] == nil then return end controller.characters[client].keys[direction] = false end) return controller
local ESM = Narci_EquipmentSetManager; --defined in EquipmentSetManager.lua local IconPresets = {}; IconPresets.tank = { 951819, --Shield_draenorcrafted_d_02_b_alliance 951820, --Shield_draenorcrafted_d_02_b_horde 2398168, --Inv_shield_1h_bloodelfguard_d_01 }; IconPresets.healer = { 460955, --Priest_icon_innewill 215433, --spell_priest_chakra 537099, --Spell_priest_angelicbulwark 135913, --Spell_holy_greaterheal 135930, --Spell_holy_lesserheal02 }; IconPresets.pvp = { 236335, --Achievement_arena_3v3_6 236328, --Achievement_arena_2v2_6 236340, --Achievement_arena_5v5_4 236357, --Achievement_bg_kill_carrier_opposing_flagroom 236349, --Achievement_bg_captureflag_eos 236320, --Ability_wintergrasp_rank1 458242, --Trade_archaeology_generalbeauregardslaststand }; IconPresets.dungeon = { 236387, --Achievement_bg_winab_underxminutes 2011140, --Achievement_dungeon_skycapnkragg 2011149, --Achievement_dungeon_toldagor 1518644, --Inv_misc_diachest03 136180, --Spell Disruption 525134, --Inv_relics_hourglass [Keystone] 236353, --Achievement_bg_grab_cap_flagunderxseconds } local function GetRandomIcon(subclass) local IconCategory = IconPresets[subclass]; return ( IconCategory[ math.random( #IconCategory ) ] ); end --[[ --Dev Tool local IconNames = {}; local IconNames_LowerCase = {}; local SetTimer = C_Timer.After; local find = string.find; IconNames = GetLooseMacroIcons(); local index = 1; local totalMatches = 0; local isConsecutive = false; local isMatch = false; local totalIcon = #IconNames; local function ConvertToLowerCase() local strlower = string.lower; for i = 1, #IconNames do IconNames_LowerCase[i] = strlower(IconNames[i]); end end ConvertToLowerCase(); local function ResetFlags() print("Found ".. totalMatches .. "matches.") index = 1; totalMatches = 0; isConsecutive = false; isMatch = false; end local function PrintIcons(name) --Ability_ClassName_SpellName if index <= totalIcon then isMatch = find(IconNames_LowerCase[index], name, 9) if isMatch then print("|cFFFFD100"..index .."|r ".. IconNames[index]); totalMatches = totalMatches + 1; isConsecutive = true; end if isConsecutive and (not isMatch) then print("|cffff5050"..index .."|r ".. IconNames[index]); --Irregular print("Searching ended.") ResetFlags(); return; end index = index + 1; SetTimer(0, function() PrintIcons(name) end); else print("Searching completed."); ResetFlags(); end end function SearchIconsByClassName(ClassName) local name = strlower(ClassName); PrintIcons(name); end --]] ---------------------------------------------------------- local staticIcons = {}; --exclude passive spell local usedIcons = {}; --usedIcons = staticIcons∪recently used icons local excludedIcons = { --Reset 132296, --DH: Double Jump 132301, --Rogue: Fleet Footed }; local function IsUniqueIcon(icon) if not icon then return false; end; local isUnique = not usedIcons[icon]; usedIcons[icon] = true; return isUnique; end local function GetStaticIcons() local numTab = GetNumSpellTabs(); local spellID; local icon; for i = 2, numTab do local _, _, tabOffset, numEntries = GetSpellTabInfo(i); --1:General 2:Current Spec for j = (tabOffset + 1) , (tabOffset + numEntries) do _, spellID = GetSpellBookItemInfo(j, "spell"); if spellID and (not IsPassiveSpell(spellID) ) then icon = GetSpellBookItemTexture(j, "spell"); staticIcons[icon] = true; end end end for i = 1, #excludedIcons do staticIcons[ excludedIcons[i] ] = true; end return staticIcons end local GetEquipmentSetInfo = C_EquipmentSet.GetEquipmentSetInfo; local function LoadEquipmentSetIcons() local SetIDs = C_EquipmentSet.GetEquipmentSetIDs() or {}; for i = 1, #SetIDs do local _, iconFileID = GetEquipmentSetInfo(SetIDs[i]); usedIcons[iconFileID] = true; end end local function GetSelectedPvpTalentIcons() local talentIDs = C_SpecializationInfo.GetAllSelectedPvpTalentIDs(); --Return talentID if talentIDs and #talentIDs > 1 then local icons = {}; for i = 2, #talentIDs do local _, _, icon = GetPvpTalentInfoByID(talentIDs[i]); tinsert(icons, icon); end return icons; else return false; end end local GetInventoryItemTexture = GetInventoryItemTexture; local GetInventoryItemQuality = GetInventoryItemQuality; local DoesItemExist = C_Item.DoesItemExist; local function GenerateIcons() --Passive talent only local icons, names = {}, {}; local MaxTiers = GetMaxTalentTier(); --based on the character's level local talentGroup = GetActiveSpecGroup(); local talentID, icon, spellID, name; local IsPassiveSpell = IsPassiveSpell; --from Inventory local itemLocation = ItemLocation:CreateFromEquipmentSlot(16); --Main Hand if DoesItemExist(itemLocation) then icon = C_Item.GetItemIcon(itemLocation); if IsUniqueIcon(icon) then name = C_Item.GetItemName(itemLocation); tinsert(icons, icon); tinsert(names, name); end end itemLocation = ItemLocation:CreateFromEquipmentSlot(15) --INVSLOT_BACK if DoesItemExist(itemLocation) then local quality = C_Item.GetItemQuality(itemLocation) if quality == 5 or quality == 6 then --Legendary & Artifact icon = C_Item.GetItemIcon(itemLocation); end if IsUniqueIcon(icon) then name = C_Item.GetItemName(itemLocation); tinsert(icons, icon); tinsert(names, name); end end --from spell book local GetSpellBookItemTexture = GetSpellBookItemTexture; local GetSpellBookItemInfo = GetSpellBookItemInfo; local _, _, tabOffset, numEntries = GetSpellTabInfo(2) --1:General 2:Current Spec for i = (tabOffset + numEntries) , tabOffset + 1 , -1 do --Passive spell sits in the back _, spellID = GetSpellBookItemInfo(i, "spell"); if spellID and IsPassiveSpell(spellID) then icon = GetSpellBookItemTexture(i, "spell"); if IsUniqueIcon(icon) then tinsert(icons, icon); name = GetSpellBookItemName(i, "spell"); tinsert(names, name); end else --break; end end --Regular talent tree if talentGroup then local column; for tier = 1, MaxTiers do _, column = GetTalentTierInfo(tier, talentGroup); if column then talentID, name, icon, _, _, spellID = GetTalentInfo(tier, column, talentGroup); if spellID and IsPassiveSpell(spellID) and IsUniqueIcon(icon) then tinsert(icons, icon); tinsert(names, name); end end end end --PvP talents local talentIDs = C_SpecializationInfo.GetAllSelectedPvpTalentIDs(); --Return talentID if talentIDs and #talentIDs > 1 then for i = 2, #talentIDs do _, name, icon, _, _, spellID = GetPvpTalentInfoByID(talentIDs[i]); if spellID and IsPassiveSpell(spellID) and IsUniqueIcon(icon) then tinsert(icons, icon); tinsert(names, name); end end end itemLocation = ItemLocation:CreateFromEquipmentSlot(17); --INVSLOT_OFFHAND if DoesItemExist(itemLocation) then if #icons < 2 then icon = C_Item.GetItemIcon(itemLocation); if IsUniqueIcon(icon) then name = C_Item.GetItemName(itemLocation); tinsert(icons, icon); tinsert(names, name); end end end return icons, names; end local function GetPassiveSpellIcons() --from spell book local GetSpellBookItemTexture = GetSpellBookItemTexture; local GetSpellBookItemInfo = GetSpellBookItemInfo; local spellID; local icons = {}; local icon; local _, _, tabOffset, numEntries = GetSpellTabInfo(2) --1:General 2:Current Spec for i = (tabOffset + numEntries) , tabOffset + 1 , -1 do --Passive spell sits in the back _, spellID = GetSpellBookItemInfo(i, "spell"); if spellID and IsPassiveSpell(spellID) then icon = GetSpellBookItemTexture(i, "spell"); if IsUniqueIcon(icon) then tinsert(icons, icon); end else --break; end end return icons; end local GetEquipmentSetIDByName = C_EquipmentSet.GetEquipmentSetID; local function ConvertToUniqueName(setName) setName = setName or ""; local newName = setName; local index = 2; while (GetEquipmentSetIDByName(newName) and index <= 10) do newName = setName..index; index = index + 1 end return newName; end function ESM:GetCurrentSpecializationNameAndIcons() LoadEquipmentSetIcons(); local currentSpec = GetSpecialization() or 1; local _, currentSpecName, _, specIcon, role = GetSpecializationInfo(currentSpec); local roleName; currentSpecName = ConvertToUniqueName(currentSpecName); if role == "TANK" then subclass = "tank"; roleName = TANK; elseif role == "HEALER" then subclass = "healer"; roleName = HEALER; else --"DAMAGER" and else subclass = "pvp"; roleName = DAMAGER; end local roleIcon = GetRandomIcon(subclass); local dungeonIcon = GetRandomIcon("dungeon"); local pvpIcon = GetRandomIcon("pvp"); local spellIcons, spellNames = GenerateIcons(); --table C_Timer.After(0.2, function() wipe(usedIcons); usedIcons = GetStaticIcons(); end) return currentSpecName, specIcon, roleIcon, dungeonIcon, pvpIcon, spellIcons, roleName, spellNames; end ---------------------------------------------------------- local function CreateIconSelector() local row, column = 4, 3; local size = 48; local Selector = Narci_EquipmentSetIconSelector; Selector:SetSize(size * column, size * row); Selector.row, Selector.column = row, column; ESM.IconSelector = Selector; --Crreate icon buttons local button; local buttons = {}; local icons = {}; for i = 1 , (row * column) do button = CreateFrame("Button", nil, Selector, "NarciEquipmentSetIconTemplate"); if i == 1 then button:SetPoint("BOTTOMLEFT", Selector, "BOTTOMLEFT", 0, 0); --Start from bottom-left elseif i % column == 1 then button:SetPoint("BOTTOM", buttons[i - column], "TOP", 0, 0); --New row else button:SetPoint("LEFT", buttons[i - 1], "RIGHT", 0, 0); end tinsert(icons, button.Icon); tinsert(buttons, button); end Selector.icons = icons; Selector.buttons = buttons; end ---------------------------------------------------------- local SetManger = CreateFrame("Frame"); SetManger:RegisterEvent("PLAYER_ENTERING_WORLD") SetManger:SetScript("OnEvent", function(self) self:UnregisterEvent("PLAYER_ENTERING_WORLD"); C_Timer.After(2, function() usedIcons = GetStaticIcons(); LoadEquipmentSetIcons() CreateIconSelector(); end) end)
--- @class GFile --- This is the file object. It used used primarily to read or write binary data from files. --- The object is returned by file.Open. local GFile = {} --- Dumps the file changes to disk and closes the file handle which makes the handle useless. function GFile:Close() end --- Returns whether the File object has reached the end of file or not. --- @return boolean @Whether the file has reached end or not. function GFile:EndOfFile() end --- Dumps the file changes to disk and saves the file. function GFile:Flush() end --- Reads the specified amount of chars and returns them as a binary string. --- @param length number @Reads the specified amount of chars. --- @return string function GFile:Read(length) end --- Reads one byte of the file and returns whether that byte was not 0. --- @return boolean @val function GFile:ReadBool() end --- Reads one unsigned 8-bit integer from the file. --- @return number @The unsigned 8-bit integer from the file. function GFile:ReadByte() end --- Reads 8 bytes from the file converts them to a double and returns them. --- @return number @value function GFile:ReadDouble() end --- Reads 4 bytes from the file converts them to a float and returns them. --- @return number @The read value function GFile:ReadFloat() end --- Returns the contents of the file from the current position up until the end of the current line. --- ℹ **NOTE**: This function will look specifically for `Line Feed` characters `\n` and will **completely ignore `Carriage Return` characters** `\r`. --- ℹ **NOTE**: This function will not return more than 8192 characters. --- @return string @The string of data from the read line. function GFile:ReadLine() end --- Reads a signed 32-bit integer from the file. --- @return number @A signed 32-bit integer function GFile:ReadLong() end --- Reads a signed 16-bit integer from the file. --- @return number @int16 function GFile:ReadShort() end --- Reads a unsigned 32-bit integer from the file. --- @return number @An unsigned 32-bit integer function GFile:ReadULong() end --- Reads a unsigned 16-bit integer from the file. --- @return number @The 16-bit integer function GFile:ReadUShort() end --- Sets the file pointer to the specified position. --- @param pos number @Pointer position. function GFile:Seek(pos) end --- Returns the size of the file in bytes. --- @return number function GFile:Size() end --- Moves the file pointer by the specified amount of chars. --- @param amount number @The amount of chars to skip, can be negative to skip backwards. --- @return number @amount function GFile:Skip(amount) end --- Returns the current position of the file pointer. --- @return number @pos function GFile:Tell() end --- Writes the given string into the file. --- @param data string @Binary data to write to the file. function GFile:Write(data) end --- Writes a boolean value to the file as one **byte**. --- @param bool boolean @The bool to be written to the file. function GFile:WriteBool(bool) end --- Write an 8-bit unsigned integer to the file. --- @param uint8 number @The 8-bit unsigned integer to be written to the file. function GFile:WriteByte(uint8) end --- Writes a 8byte floating point double to the file. --- @param double number @The double to be written to the file. function GFile:WriteDouble(double) end --- Writes a 4byte float to the file. --- @param float number @The float to be written to the file. function GFile:WriteFloat(float) end --- Writes a 32-bit signed integer to the file. --- @param int32 number @The 32-bit signed integer to be written to the file. function GFile:WriteLong(int32) end --- Writes a 16-bit signed integer to the file. --- @param int16 number @The 16-bit signed integer to be written to the file. function GFile:WriteShort(int16) end --- Writes an unsigned 32-bit integer to the file. --- @param uint32 number @The unsigned 32-bit integer to be written to the file. function GFile:WriteULong(uint32) end --- Writes an unsigned 16-bit integer to the file. --- @param uint16 number @The unsigned 16-bit integer to the file. function GFile:WriteUShort(uint16) end
-- Remember to use the cop group or this won't work -- K > Admin > Add Group > User ID > cop local Tunnel = module("vrp", "lib/Tunnel") local Proxy = module("vrp", "lib/Proxy") vRP = Proxy.getInterface("vRP") vRPclient = Tunnel.getInterface("vRP","vRP_bank") local banks = { ["fleeca"] = { position = { ['x'] = 147.04908752441, ['y'] = -1044.9448242188, ['z'] = 29.36802482605 }, reward = 10000 + math.random(100000,200000), nameofbank = "Fleeca Bank", lastrobbed = 0 }, ["fleeca2"] = { position = { ['x'] = -2957.6674804688, ['y'] = 481.45776367188, ['z'] = 15.697026252747 }, reward = 10000 + math.random(100000,200000), nameofbank = "Fleeca Bank (Highway)", lastrobbed = 0 }, ["blainecounty"] = { position = { ['x'] = -107.06505584717, ['y'] = 6474.8012695313, ['z'] = 31.62670135498 }, reward = 10000 + math.random(100000,200000), nameofbank = "Blaine County Savings", lastrobbed = 0 } --["fleeca3"] = { --position = { ['x'] = -1212.2568359375, ['y'] = -336.128295898438, ['z'] = 36.7907638549805 }, --reward = 30000 + math.random(100000,200000), --nameofbank = "Fleeca Bank (Vinewood Hills)", --lastrobbed = 0 --}, --["fleeca4"] = { --position = { ['x'] = -354.452575683594, ['y'] = -53.8204879760742, ['z'] = 48.0463104248047 }, --reward = 30000 + math.random(100000,200000), --nameofbank = "Fleeca Bank (Burton)", --lastrobbed = 0 --}, --["fleeca5"] = { --position = { ['x'] = 309.967376708984, ['y'] = -283.033660888672, ['z'] = 53.1745223999023 }, --reward = 30000 + math.random(100000,200000), --nameofbank = "Fleeca Bank (Alta)", --lastrobbed = 0 --}, --["fleeca6"] = { --position = { ['x'] = 1176.86865234375, ['y'] = 2711.91357421875, ['z'] = 38.097785949707 }, --reward = 30000 + math.random(100000,200000), --nameofbank = "Fleeca Bank (Desert)", --lastrobbed = 0 --}, --["pacific"] = { --position = { ['x'] = 255.001098632813, ['y'] = 225.855895996094, ['z'] = 101.005694274902 }, --reward = 60000 + math.random(100000,200000), --nameofbank = "Pacific Standard PDB (Downtown Vinewood)", --lastrobbed = 0 --} } local robbers = {} function get3DDistance(x1, y1, z1, x2, y2, z2) return math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2) + math.pow(z1 - z2, 2)) end AddEventHandler("playerDropped", function() if(robbers[source])then local wtf = robbers[source] local wtf2 = banks[wtf].nameofbank robbers[source] = nil TriggerClientEvent('chatMessage', -1, 'NEWS', {255, 0, 0}, "Robbery was cancelled at: ^2" ..wtf2.."Reason: [Disconnected]") end end) RegisterServerEvent('es_bank:toofar') AddEventHandler('es_bank:toofar', function(robb) if(robbers[source])then TriggerClientEvent('es_bank:toofarlocal', source) robbers[source] = nil TriggerClientEvent('chatMessage', -1, 'NEWS', {255, 0, 0}, "Robbery was cancelled at: ^2" .. banks[robb].nameofbank) end end) RegisterServerEvent('es_bank:playerdied') AddEventHandler('es_bank:playerdied', function(robb) if(robbers[source])then TriggerClientEvent('es_bank:playerdiedlocal', source) robbers[source] = nil TriggerClientEvent('chatMessage', -1, 'NEWS', {255, 0, 0}, "Robbery was cancelled at: ^2" .. banks[robb].nameofbank) end end) RegisterServerEvent('es_bank:rob') AddEventHandler('es_bank:rob', function(robb) local user_id = vRP.getUserId({source}) local player = vRP.getUserSource({user_id}) local cops = vRP.getUsersByGroup({"cop"}) -- remember to use the cop group or this won't work - K > Admin > Add Group > User ID > cop if vRP.hasGroup({user_id,"cop"}) then vRPclient.notify(player,{"~r~Cops can't rob banks."}) else if #cops >= 2 then -- change 2 to the minimum amount online necessary if banks[robb] then local bank = banks[robb] if (os.time() - bank.lastrobbed) < 600 and bank.lastrobbed ~= 0 then TriggerClientEvent('chatMessage', player, 'ROBBERY', {255, 0, 0}, "This has already been robbed recently. Please wait another: ^2" .. (1200 - (os.time() - bank.lastrobbed)) .. "^0 seconds.") return end TriggerClientEvent('chatMessage', -1, 'NEWS', {255, 0, 0}, "Robbery in progress at ^2" .. bank.nameofbank) TriggerClientEvent('chatMessage', player, 'SYSTEM', {255, 0, 0}, "You started a robbery at: ^2" .. bank.nameofbank .. "^0, do not get too far away from this point!") TriggerClientEvent('chatMessage', player, 'SYSTEM', {255, 0, 0}, "Hold the fort for ^1 12 ^0minutes and the money is yours!") TriggerClientEvent('es_bank:currentlyrobbing', player, robb) banks[robb].lastrobbed = os.time() robbers[player] = robb local savedSource = player SetTimeout(720000, function() if(robbers[savedSource])then if(user_id)then vRP.giveInventoryItem({user_id,"dirty_money",bank.reward,true}) TriggerClientEvent('chatMessage', -1, 'NEWS', {255, 0, 0}, "Robbery is over at: ^2" .. bank.nameofbank .. "^0!") TriggerClientEvent('es_bank:robberycomplete', savedSource, bank.reward) end end end) end else vRPclient.notify(player,{"~r~Not enough cops online."}) end end end)
-- MIT License Copyright (c) 2021 Evgeni Chasnovski ---@brief [[ --- Custom minimal and fast Lua module which implements --- [base16](http://chriskempson.com/projects/base16/) color scheme (with --- Copyright (C) 2012 Chris Kempson) adapated for modern Neovim 0.5 Lua --- plugins. Extra features: --- - Configurable automatic support of cterm colors (see |highlight-cterm|). --- - Opinionated palette generator based only on background and foreground --- colors. --- --- # Setup --- --- This module needs a setup with `require('mini.base16').setup({})` (replace --- `{}` with your `config` table). It will create global Lua table --- `MiniBase16` which you can use for scripting or manually (with --- `:lua MiniBase16.*`). --- --- Default `config`: --- <code> --- { --- -- Table with names from `base00` to `base0F` and values being strings of HEX --- -- colors with format "#RRGGBB". NOTE: this should be explicitly supplied in --- -- `setup()`. --- palette = nil, --- --- -- Whether to support cterm colors. Can be boolean, `nil` (same as `false`), --- -- or table with cterm colors. See `setup()` documentation for more --- -- information. --- use_cterm = nil, --- } --- </code> --- Example: --- <code> --- require('mini.base16').setup({ --- palette = { --- base00 = '#112641', --- base01 = '#3a475e', --- base02 = '#606b81', --- base03 = '#8691a7', --- base04 = '#d5dc81', --- base05 = '#e2e98f', --- base06 = '#eff69c', --- base07 = '#fcffaa', --- base08 = '#ffcfa0', --- base09 = '#cc7e46', --- base0A = '#46a436', --- base0B = '#9ff895', --- base0C = '#ca6ecf', --- base0D = '#42f7ff', --- base0E = '#ffc4ff', --- base0F = '#00a5c5', --- }, --- use_cterm = true, --- }) --- </code> --- # Notes --- 1. This module is used for creating plugin's official colorscheme named --- `minischeme` (see |mini.nvim|). --- 2. Using `setup()` doesn't actually create a |colorscheme|. It basically --- creates a coordinated set of |highlight|s. To create your own theme: --- - Put "myscheme.lua" file (name after your chosen theme name) inside --- any "colors" directory reachable from 'runtimepath' ("colors" inside --- your Neovim config directory is usually enough). --- - Inside "myscheme.lua" call `require('mini.base16').setup()` with your --- palette and only after that set |g:colors_name| to "myscheme". --- ---@brief ]] ---@tag MiniBase16 mini.base16 -- Module and its helper local MiniBase16 = {} local H = {} --- Module setup --- --- Setup is done by applying base16 palette to enable colorscheme. Highlight --- groups make an extended set from original --- [base16-vim](https://github.com/chriskempson/base16-vim/) plugin. It is a --- good idea to have `config.palette` respect the original [styling --- principles](https://github.com/chriskempson/base16/blob/master/styling.md). --- --- By default only 'gui highlighting' (see |highlight-gui| and --- |termguicolors|) is supported. To support 'cterm highlighting' (see --- |highlight-cterm|) supply `config.use_cterm` argument in one of the formats: --- - `true` to auto-generate from `palette` (as closest colors). --- - Table with similar structure to `palette` but having terminal colors --- (integers from 0 to 255) instead of hex strings. --- ---@param config table: Module config table. ---@usage `require('mini.base16').setup({})` (replace `{}` with your `config` table; `config.palette` should be a table with colors) function MiniBase16.setup(config) -- Export module _G.MiniBase16 = MiniBase16 -- Setup config config = H.setup_config(config) -- Apply config H.apply_config(config) end MiniBase16.config = { -- Table with names from `base00` to `base0F` and values being strings of HEX -- colors with format "#RRGGBB". NOTE: this should be explicitly supplied in -- `setup()`. palette = nil, -- Whether to support cterm colors. Can be boolean, `nil` (same as `false`), -- or table with cterm colors. See `setup()` documentation for more -- information. use_cterm = nil, } --- Create 'mini' palette --- --- Create base16 palette based on the HEX (string '#RRGGBB') colors of main background and --- foreground with optional setting of accent chroma (see details). --- --- # Algorithm design --- - Main operating color space is --- [CIELCh(uv)](https://en.wikipedia.org/wiki/CIELUV#Cylindrical_representation_(CIELCh)) --- which is a cylindrical representation of a perceptually uniform CIELUV --- color space. It defines color by three values: lightness L (values from 0 --- to 100), chroma (positive values), and hue (circular values from 0 to 360 --- degress). Useful converting tool: https://www.easyrgb.com/en/convert.php --- - There are four important lightness values: background, foreground, focus --- (around the middle of background and foreground, leaning towards --- foreground), and edge (extreme lightness closest to foreground). --- - First four colors have the same chroma and hue as `background` but --- lightness progresses from background towards focus. --- - Second four colors have the same chroma and hue as `foreground` but --- lightness progresses from foreground towards edge in such a way that --- 'base05' color is main foreground color. --- - The rest eight colors are accent colors which are created in pairs --- - Each pair has same hue from set of hues 'most different' to --- background and foreground hues (if respective chorma is positive). --- - All colors have the same chroma equal to `accent_chroma` (if not --- provided, chroma of foreground is used, as they will appear next --- to each other). Note: this means that in case of low foreground --- chroma, it is a good idea to set `accent_chroma` manually. --- Values from 30 (low chorma) to 80 (high chroma) are common. --- - Within pair there is base lightness (equal to foreground --- lightness) and alternative (equal to focus lightness). Base --- lightness goes to colors which will be used more frequently in --- code: base08 (variables), base0B (strings), base0D (functions), --- base0E (keywords). --- How exactly accent colors are mapped to base16 palette is a result of --- trial and error. One rule of thumb was: colors within one hue pair should --- be more often seen next to each other. This is because it is easier to --- distinguish them and seems to be more visually appealing. That is why --- `base0D` and `base0F` have same hues because they usually represent --- functions and delimiter (brackets included). --- ---@param background string: Background HEX color (formatted as `#RRGGBB`). ---@param foreground string: Foreground HEX color (formatted as `#RRGGBB`). ---@param accent_chroma number: Optional positive number (usually between 0 and 100). Default: chroma of foreground color. ---@return table: Table with base16 palette. ---@usage `local palette = require('mini.base16').mini_palette('#112641', '#e2e98f', 75)` ---@usage `require('mini.base16').setup({palette = palette})` function MiniBase16.mini_palette(background, foreground, accent_chroma) H.validate_hex(background, 'background') H.validate_hex(foreground, 'foreground') if accent_chroma and not (type(accent_chroma) == 'number' and accent_chroma >= 0) then error('(mini.base16) `accent_chroma` should be a positive number or `nil`.') end local bg, fg = H.hex2lch(background), H.hex2lch(foreground) accent_chroma = accent_chroma or fg.c local palette = {} -- Target lightness values -- Justification for skewness towards foreground in focus is mainly because -- it will be paired with foreground lightness and used for text. local focus_l = 0.4 * bg.l + 0.6 * fg.l local edge_l = fg.l > 50 and 99 or 1 -- Background colors local bg_step = (focus_l - bg.l) / 3 palette[1] = { l = bg.l + 0 * bg_step, c = bg.c, h = bg.h } palette[2] = { l = bg.l + 1 * bg_step, c = bg.c, h = bg.h } palette[3] = { l = bg.l + 2 * bg_step, c = bg.c, h = bg.h } palette[4] = { l = bg.l + 3 * bg_step, c = bg.c, h = bg.h } -- Foreground colors Possible negative value of `palette[5].l` will be -- handled in future conversion to hex. local fg_step = (edge_l - fg.l) / 2 palette[5] = { l = fg.l - 1 * fg_step, c = fg.c, h = fg.h } palette[6] = { l = fg.l + 0 * fg_step, c = fg.c, h = fg.h } palette[7] = { l = fg.l + 1 * fg_step, c = fg.c, h = fg.h } palette[8] = { l = fg.l + 2 * fg_step, c = fg.c, h = fg.h } -- Accent colors ---- Only try to avoid color if it has positive chroma, because with zero ---- chroma hue is meaningless (as in polar coordinates) local present_hues = {} if bg.c > 0 then table.insert(present_hues, bg.h) end if fg.c > 0 then table.insert(present_hues, fg.h) end local hues = H.make_different_hues(present_hues, 4) -- stylua: ignore start palette[9] = { l = fg.l, c = accent_chroma, h = hues[1] } palette[10] = { l = focus_l, c = accent_chroma, h = hues[1] } palette[11] = { l = focus_l, c = accent_chroma, h = hues[2] } palette[12] = { l = fg.l, c = accent_chroma, h = hues[2] } palette[13] = { l = focus_l, c = accent_chroma, h = hues[4] } palette[14] = { l = fg.l, c = accent_chroma, h = hues[3] } palette[15] = { l = fg.l, c = accent_chroma, h = hues[4] } palette[16] = { l = focus_l, c = accent_chroma, h = hues[3] } -- stylua: ignore end -- Convert to base16 palette local base16_palette = {} for i, lch in ipairs(palette) do local name = H.base16_names[i] -- It is ensured in `lch2hex` that only valid HEX values are produced base16_palette[name] = H.lch2hex(lch) end return base16_palette end --- Converts palette with RGB colors to terminal colors --- --- Useful for caching `use_cterm` variable to increase speed. --- ---@param palette table: Table with base16 palette (same as in `MiniBase16.config.palette`). ---@return table: Table with base16 palette using |highlight-cterm|. function MiniBase16.rgb_palette_to_cterm_palette(palette) H.validate_base16_palette(palette, 'palette') -- Create cterm palette only when it is needed to decrease load time H.ensure_cterm_palette() return vim.tbl_map(function(hex) return H.nearest_rgb_id(H.hex2rgb(hex), H.cterm_palette) end, palette) end -- Helpers ---- Module default config H.default_config = MiniBase16.config ---- Settings function H.setup_config(config) -- General idea: if some table elements are not present in user-supplied -- `config`, take them from default config vim.validate({ config = { config, 'table', true } }) config = vim.tbl_deep_extend('force', H.default_config, config or {}) -- Validate settings H.validate_base16_palette(config.palette, 'config.palette') H.validate_use_cterm(config.use_cterm, 'config.use_cterm') return config end function H.apply_config(config) MiniBase16.config = config H.apply_palette(config.palette, config.use_cterm) end ---- Validators H.base16_names = { 'base00', 'base01', 'base02', 'base03', 'base04', 'base05', 'base06', 'base07', 'base08', 'base09', 'base0A', 'base0B', 'base0C', 'base0D', 'base0E', 'base0F', } function H.validate_base16_palette(x, x_name) if type(x) ~= 'table' then error(string.format('(mini.base16) `%s` is not a table.', x_name)) end for _, color_name in pairs(H.base16_names) do local c = x[color_name] if c == nil then local msg = string.format('(mini.base16) `%s` does not have value %s.', x_name, color_name) error(msg) end H.validate_hex(c, string.format('config.palette[%s]', color_name)) end return true end function H.validate_use_cterm(x, x_name) if not x or type(x) == 'boolean' then return true end if type(x) ~= 'table' then local msg = string.format('(mini.base16) `%s` should be boolean or table with cterm colors.', x_name) error(msg) end for _, color_name in pairs(H.base16_names) do local c = x[color_name] if c == nil then local msg = string.format('(mini.base16) `%s` does not have value %s.', x_name, color_name) error(msg) end if not (type(c) == 'number' and 0 <= c and c <= 255) then local msg = string.format('(mini.base16) `%s.%s` is not a cterm color.', x_name, color_name) error(msg) end end return true end function H.validate_hex(x, x_name) local is_hex = type(x) == 'string' and x:len() == 7 and x:sub(1, 1) == '#' and (tonumber(x:sub(2), 16) ~= nil) if not is_hex then local msg = string.format('(mini.base16) `%s` is not a HEX color (string "#RRGGBB").', x_name) error(msg) end return true end ---- Highlighting function H.apply_palette(palette, use_cterm) -- Prepare highlighting application. Notes: -- - Clear current highlight only if other theme was loaded previously. -- - No need to `syntax reset` because *all* syntax groups are defined later. if vim.g.colors_name then vim.cmd([[highlight clear]]) end -- As this doesn't create colorscheme, don't store any name. Not doing it -- might cause some issues with `syntax on`. vim.g.colors_name = nil local p, hi if use_cterm then p, hi = H.make_compound_palette(palette, use_cterm), H.highlight_both else p, hi = palette, H.highlight_gui end -- stylua: ignore start -- Builtin highlighting groups. Some groups which are missing in 'base16-vim' -- are added based on groups to which they are linked. hi('ColorColumn', {fg=nil, bg=p.base01, attr=nil, sp=nil}) hi('Conceal', {fg=p.base0D, bg=p.base00, attr=nil, sp=nil}) hi('Cursor', {fg=p.base00, bg=p.base05, attr=nil, sp=nil}) hi('CursorColumn', {fg=nil, bg=p.base01, attr=nil, sp=nil}) hi('CursorIM', {fg=p.base00, bg=p.base05, attr=nil, sp=nil}) hi('CursorLine', {fg=nil, bg=p.base01, attr=nil, sp=nil}) hi('CursorLineNr', {fg=p.base04, bg=p.base01, attr=nil, sp=nil}) hi('DiffAdd', {fg=p.base0B, bg=p.base01, attr=nil, sp=nil}) hi('DiffChange', {fg=p.base03, bg=p.base01, attr=nil, sp=nil}) hi('DiffDelete', {fg=p.base08, bg=p.base01, attr=nil, sp=nil}) hi('DiffText', {fg=p.base0D, bg=p.base01, attr=nil, sp=nil}) hi('Directory', {fg=p.base0D, bg=nil, attr=nil, sp=nil}) hi('EndOfBuffer', {fg=p.base03, bg=nil, attr=nil, sp=nil}) hi('ErrorMsg', {fg=p.base08, bg=p.base00, attr=nil, sp=nil}) hi('FoldColumn', {fg=p.base0C, bg=p.base01, attr=nil, sp=nil}) hi('Folded', {fg=p.base03, bg=p.base01, attr=nil, sp=nil}) hi('IncSearch', {fg=p.base01, bg=p.base09, attr=nil, sp=nil}) hi('LineNr', {fg=p.base03, bg=p.base01, attr=nil, sp=nil}) ---- Slight difference from base16, where `bg=base03` is used. This makes ---- it possible to comfortably see this highlighting in comments. hi('MatchParen', {fg=nil, bg=p.base02, attr=nil, sp=nil}) hi('ModeMsg', {fg=p.base0B, bg=nil, attr=nil, sp=nil}) hi('MoreMsg', {fg=p.base0B, bg=nil, attr=nil, sp=nil}) hi('MsgArea', {fg=p.base05, bg=p.base00, attr=nil, sp=nil}) hi('MsgSeparator', {fg=p.base04, bg=p.base02, attr=nil, sp=nil}) hi('NonText', {fg=p.base03, bg=nil, attr=nil, sp=nil}) hi('Normal', {fg=p.base05, bg=p.base00, attr=nil, sp=nil}) hi('NormalFloat', {fg=p.base05, bg=p.base01, attr=nil, sp=nil}) hi('NormalNC', {fg=p.base05, bg=p.base00, attr=nil, sp=nil}) hi('PMenu', {fg=p.base05, bg=p.base01, attr=nil, sp=nil}) hi('PMenuSbar', {fg=nil, bg=p.base02, attr=nil, sp=nil}) hi('PMenuSel', {fg=p.base01, bg=p.base05, attr=nil, sp=nil}) hi('PMenuThumb', {fg=nil, bg=p.base07, attr=nil, sp=nil}) hi('Question', {fg=p.base0D, bg=nil, attr=nil, sp=nil}) hi('QuickFixLine', {fg=nil, bg=p.base01, attr=nil, sp=nil}) hi('Search', {fg=p.base01, bg=p.base0A, attr=nil, sp=nil}) hi('SignColumn', {fg=p.base03, bg=p.base01, attr=nil, sp=nil}) hi('SpecialKey', {fg=p.base03, bg=nil, attr=nil, sp=nil}) hi('SpellBad', {fg=nil, bg=nil, attr='undercurl', sp=p.base08}) hi('SpellCap', {fg=nil, bg=nil, attr='undercurl', sp=p.base0D}) hi('SpellLocal', {fg=nil, bg=nil, attr='undercurl', sp=p.base0C}) hi('SpellRare', {fg=nil, bg=nil, attr='undercurl', sp=p.base0E}) hi('StatusLine', {fg=p.base04, bg=p.base02, attr=nil, sp=nil}) hi('StatusLineNC', {fg=p.base03, bg=p.base01, attr=nil, sp=nil}) hi('Substitute', {fg=p.base01, bg=p.base0A, attr=nil, sp=nil}) hi('TabLine', {fg=p.base03, bg=p.base01, attr=nil, sp=nil}) hi('TabLineFill', {fg=p.base03, bg=p.base01, attr=nil, sp=nil}) hi('TabLineSel', {fg=p.base0B, bg=p.base01, attr=nil, sp=nil}) hi('TermCursor', {fg=nil, bg=nil, attr='reverse', sp=nil}) hi('TermCursorNC', {fg=nil, bg=nil, attr='reverse', sp=nil}) hi('Title', {fg=p.base0D, bg=nil, attr=nil, sp=nil}) hi('VertSplit', {fg=p.base02, bg=p.base02, attr=nil, sp=nil}) hi('Visual', {fg=nil, bg=p.base02, attr=nil, sp=nil}) hi('VisualNOS', {fg=p.base08, bg=nil, attr=nil, sp=nil}) hi('WarningMsg', {fg=p.base08, bg=nil, attr=nil, sp=nil}) hi('Whitespace', {fg=p.base03, bg=nil, attr=nil, sp=nil}) hi('WildMenu', {fg=p.base08, bg=p.base0A, attr=nil, sp=nil}) hi('lCursor', {fg=p.base00, bg=p.base05, attr=nil, sp=nil}) -- Standard syntax (affects treesitter) hi('Boolean', {fg=p.base09, bg=nil, attr=nil, sp=nil}) hi('Character', {fg=p.base08, bg=nil, attr=nil, sp=nil}) hi('Comment', {fg=p.base03, bg=nil, attr=nil, sp=nil}) hi('Conditional', {fg=p.base0E, bg=nil, attr=nil, sp=nil}) hi('Constant', {fg=p.base09, bg=nil, attr=nil, sp=nil}) hi('Debug', {fg=p.base08, bg=nil, attr=nil, sp=nil}) hi('Define', {fg=p.base0E, bg=nil, attr=nil, sp=nil}) hi('Delimiter', {fg=p.base0F, bg=nil, attr=nil, sp=nil}) hi('Error', {fg=p.base00, bg=p.base08, attr=nil, sp=nil}) hi('Exception', {fg=p.base08, bg=nil, attr=nil, sp=nil}) hi('Float', {fg=p.base09, bg=nil, attr=nil, sp=nil}) hi('Function', {fg=p.base0D, bg=nil, attr=nil, sp=nil}) hi('Identifier', {fg=p.base08, bg=nil, attr=nil, sp=nil}) hi('Ignore', {fg=p.base0C, bg=nil, attr=nil, sp=nil}) hi('Include', {fg=p.base0D, bg=nil, attr=nil, sp=nil}) hi('Keyword', {fg=p.base0E, bg=nil, attr=nil, sp=nil}) hi('Label', {fg=p.base0A, bg=nil, attr=nil, sp=nil}) hi('Macro', {fg=p.base08, bg=nil, attr=nil, sp=nil}) hi('Number', {fg=p.base09, bg=nil, attr=nil, sp=nil}) hi('Operator', {fg=p.base05, bg=nil, attr=nil, sp=nil}) hi('PreCondit', {fg=p.base0A, bg=nil, attr=nil, sp=nil}) hi('PreProc', {fg=p.base0A, bg=nil, attr=nil, sp=nil}) hi('Repeat', {fg=p.base0A, bg=nil, attr=nil, sp=nil}) hi('Special', {fg=p.base0C, bg=nil, attr=nil, sp=nil}) hi('SpecialChar', {fg=p.base0F, bg=nil, attr=nil, sp=nil}) hi('SpecialComment', {fg=p.base0C, bg=nil, attr=nil, sp=nil}) hi('Statement', {fg=p.base08, bg=nil, attr=nil, sp=nil}) hi('StorageClass', {fg=p.base0A, bg=nil, attr=nil, sp=nil}) hi('String', {fg=p.base0B, bg=nil, attr=nil, sp=nil}) hi('Structure', {fg=p.base0E, bg=nil, attr=nil, sp=nil}) hi('Tag', {fg=p.base0A, bg=nil, attr=nil, sp=nil}) hi('Todo', {fg=p.base0A, bg=p.base01, attr=nil, sp=nil}) hi('Type', {fg=p.base0A, bg=nil, attr=nil, sp=nil}) hi('Typedef', {fg=p.base0A, bg=nil, attr=nil, sp=nil}) hi('Underlined', {fg=p.base08, bg=nil, attr=nil, sp=nil}) -- Other from 'base16-vim' hi('Bold', {fg=nil, bg=nil, attr='bold', sp=nil}) hi('Italic', {fg=nil, bg=nil, attr=nil, sp=nil}) hi('TooLong', {fg=p.base08, bg=nil, attr=nil, sp=nil}) hi('Underlined', {fg=p.base08, bg=nil, attr=nil, sp=nil}) -- Git diff hi('DiffAdded', {fg=p.base0B, bg=p.base00, attr=nil, sp=nil}) hi('DiffFile', {fg=p.base08, bg=p.base00, attr=nil, sp=nil}) hi('DiffLine', {fg=p.base0D, bg=p.base00, attr=nil, sp=nil}) hi('DiffNewFile', {fg=p.base0B, bg=p.base00, attr=nil, sp=nil}) hi('DiffRemoved', {fg=p.base08, bg=p.base00, attr=nil, sp=nil}) -- Git commit hi('gitcommitBranch', {fg=p.base09, bg=nil, attr='bold', sp=nil}) hi('gitcommitComment', {fg=p.base03, bg=nil, attr=nil, sp=nil}) hi('gitcommitDiscarded', {fg=p.base03, bg=nil, attr=nil, sp=nil}) hi('gitcommitDiscardedFile', {fg=p.base08, bg=nil, attr='bold', sp=nil}) hi('gitcommitDiscardedType', {fg=p.base0D, bg=nil, attr=nil, sp=nil}) hi('gitcommitHeader', {fg=p.base0E, bg=nil, attr=nil, sp=nil}) hi('gitcommitOverflow', {fg=p.base08, bg=nil, attr=nil, sp=nil}) hi('gitcommitSelected', {fg=p.base03, bg=nil, attr=nil, sp=nil}) hi('gitcommitSelectedFile', {fg=p.base0B, bg=nil, attr='bold', sp=nil}) hi('gitcommitSelectedType', {fg=p.base0D, bg=nil, attr=nil, sp=nil}) hi('gitcommitSummary', {fg=p.base0B, bg=nil, attr=nil, sp=nil}) hi('gitcommitUnmergedFile', {fg=p.base08, bg=nil, attr='bold', sp=nil}) hi('gitcommitUnmergedType', {fg=p.base0D, bg=nil, attr=nil, sp=nil}) hi('gitcommitUntracked', {fg=p.base03, bg=nil, attr=nil, sp=nil}) hi('gitcommitUntrackedFile', {fg=p.base0A, bg=nil, attr=nil, sp=nil}) -- Built-in diagnostic if vim.fn.has("nvim-0.6.0") == 1 then hi('DiagnosticError', {fg=p.base08, bg=p.base00, attr=nil, sp=nil}) hi('DiagnosticHint', {fg=p.base0D, bg=p.base00, attr=nil, sp=nil}) hi('DiagnosticInfo', {fg=p.base0C, bg=p.base00, attr=nil, sp=nil}) hi('DiagnosticWarn', {fg=p.base0E, bg=p.base00, attr=nil, sp=nil}) hi('DiagnosticFloatingError', {fg=p.base08, bg=p.base01, attr=nil, sp=nil}) hi('DiagnosticFloatingHint', {fg=p.base0D, bg=p.base01, attr=nil, sp=nil}) hi('DiagnosticFloatingInfo', {fg=p.base0C, bg=p.base01, attr=nil, sp=nil}) hi('DiagnosticFloatingWarn', {fg=p.base0E, bg=p.base01, attr=nil, sp=nil}) hi('DiagnosticSignError', {fg=p.base08, bg=p.base01, attr=nil, sp=nil}) hi('DiagnosticSignHint', {fg=p.base0D, bg=p.base01, attr=nil, sp=nil}) hi('DiagnosticSignInfo', {fg=p.base0C, bg=p.base01, attr=nil, sp=nil}) hi('DiagnosticSignWarn', {fg=p.base0E, bg=p.base01, attr=nil, sp=nil}) hi('DiagnosticUnderlineError', {fg=nil, bg=nil, attr='underline', sp=p.base08}) hi('DiagnosticUnderlineHint', {fg=nil, bg=nil, attr='underline', sp=p.base0D}) hi('DiagnosticUnderlineInfo', {fg=nil, bg=nil, attr='underline', sp=p.base0C}) hi('DiagnosticUnderlineWarn', {fg=nil, bg=nil, attr='underline', sp=p.base0E}) else hi('LspDiagnosticsDefaultError', {fg=p.base08, bg=p.base00, attr=nil, sp=nil}) hi('LspDiagnosticsDefaultHint', {fg=p.base0D, bg=p.base00, attr=nil, sp=nil}) hi('LspDiagnosticsDefaultInformation', {fg=p.base0C, bg=p.base00, attr=nil, sp=nil}) hi('LspDiagnosticsDefaultWarning', {fg=p.base0E, bg=p.base00, attr=nil, sp=nil}) hi('LspDiagnosticsFloatingError', {fg=p.base08, bg=p.base01, attr=nil, sp=nil}) hi('LspDiagnosticsFloatingHint', {fg=p.base0D, bg=p.base01, attr=nil, sp=nil}) hi('LspDiagnosticsFloatingInformation', {fg=p.base0C, bg=p.base01, attr=nil, sp=nil}) hi('LspDiagnosticsFloatingWarning', {fg=p.base0E, bg=p.base01, attr=nil, sp=nil}) hi('LspDiagnosticsSignError', {fg=p.base08, bg=p.base01, attr=nil, sp=nil}) hi('LspDiagnosticsSignHint', {fg=p.base0D, bg=p.base01, attr=nil, sp=nil}) hi('LspDiagnosticsSignInformation', {fg=p.base0C, bg=p.base01, attr=nil, sp=nil}) hi('LspDiagnosticsSignWarning', {fg=p.base0E, bg=p.base01, attr=nil, sp=nil}) hi('LspDiagnosticsUnderlineError', {fg=nil, bg=nil, attr='underline', sp=p.base08}) hi('LspDiagnosticsUnderlineHint', {fg=nil, bg=nil, attr='underline', sp=p.base0D}) hi('LspDiagnosticsUnderlineInformation', {fg=nil, bg=nil, attr='underline', sp=p.base0C}) hi('LspDiagnosticsUnderlineWarning', {fg=nil, bg=nil, attr='underline', sp=p.base0E}) end -- Plugins ---- 'mini' hi('MiniCompletionActiveParameter', {fg=nil, bg=nil, attr='underline', sp=nil}) hi('MiniCursorword', {fg=nil, bg=nil, attr='underline', sp=nil}) hi('MiniJump', {fg=nil, bg=nil, attr='undercurl', sp=p.base0E}) hi('MiniStarterCurrent', {fg=nil, bg=nil, attr=nil, sp=nil}) hi('MiniStarterFooter', {fg=p.base0D, bg=nil, attr=nil, sp=nil}) hi('MiniStarterHeader', {fg=p.base0D, bg=nil, attr=nil, sp=nil}) hi('MiniStarterInactive', {fg=p.base03, bg=nil, attr=nil, sp=nil}) hi('MiniStarterItem', {fg=p.base05, bg=nil, attr=nil, sp=nil}) hi('MiniStarterItemBullet', {fg=p.base0F, bg=nil, attr=nil, sp=nil}) hi('MiniStarterItemPrefix', {fg=p.base08, bg=nil, attr=nil, sp=nil}) hi('MiniStarterSection', {fg=p.base0F, bg=nil, attr=nil, sp=nil}) hi('MiniStarterQuery', {fg=p.base0B, bg=nil, attr=nil, sp=nil}) hi('MiniStatuslineDevinfo', {fg=p.base04, bg=p.base02, attr=nil, sp=nil}) hi('MiniStatuslineFileinfo', {fg=p.base04, bg=p.base02, attr=nil, sp=nil}) hi('MiniStatuslineFilename', {fg=p.base03, bg=p.base01, attr=nil, sp=nil}) hi('MiniStatuslineInactive', {fg=p.base03, bg=p.base01, attr=nil, sp=nil}) hi('MiniStatuslineModeCommand', {fg=p.base00, bg=p.base08, attr='bold', sp=nil}) hi('MiniStatuslineModeInsert', {fg=p.base00, bg=p.base0D, attr='bold', sp=nil}) hi('MiniStatuslineModeNormal', {fg=p.base00, bg=p.base05, attr='bold', sp=nil}) hi('MiniStatuslineModeOther', {fg=p.base00, bg=p.base03, attr='bold', sp=nil}) hi('MiniStatuslineModeReplace', {fg=p.base00, bg=p.base0E, attr='bold', sp=nil}) hi('MiniStatuslineModeVisual', {fg=p.base00, bg=p.base0B, attr='bold', sp=nil}) hi('MiniSurround', {fg=p.base01, bg=p.base09, attr=nil, sp=nil}) hi('MiniTablineCurrent', {fg=p.base05, bg=p.base02, attr='bold', sp=nil}) hi('MiniTablineFill', {fg=nil, bg=nil, attr=nil, sp=nil}) hi('MiniTablineHidden', {fg=p.base04, bg=p.base01, attr=nil, sp=nil}) hi('MiniTablineModifiedCurrent', {fg=p.base02, bg=p.base05, attr='bold', sp=nil}) hi('MiniTablineModifiedHidden', {fg=p.base01, bg=p.base04, attr=nil, sp=nil}) hi('MiniTablineModifiedVisible', {fg=p.base02, bg=p.base04, attr='bold', sp=nil}) hi('MiniTablineVisible', {fg=p.base05, bg=p.base01, attr='bold', sp=nil}) hi('MiniTrailspace', {fg=p.base00, bg=p.base08, attr=nil, sp=nil}) ---- kyazdani42/nvim-tree.lua (only unlinked highlight groups) hi('NvimTreeExecFile', { fg=p.base0B, bg=nil, attr='bold', sp=nil }) hi('NvimTreeFolderIcon', { fg=p.base03, bg=nil, attr=nil, sp=nil }) hi('NvimTreeGitDeleted', { fg=p.base08, bg=nil, attr=nil, sp=nil }) hi('NvimTreeGitDirty', { fg=p.base08, bg=nil, attr=nil, sp=nil }) hi('NvimTreeGitMerge', { fg=p.base0C, bg=nil, attr=nil, sp=nil }) hi('NvimTreeGitNew', { fg=p.base0D, bg=nil, attr=nil, sp=nil }) hi('NvimTreeGitRenamed', { fg=p.base0E, bg=nil, attr=nil, sp=nil }) hi('NvimTreeGitStaged', { fg=p.base0B, bg=nil, attr=nil, sp=nil }) hi('NvimTreeImageFile', { fg=p.base0E, bg=nil, attr='bold', sp=nil }) hi('NvimTreeIndentMarker', { fg=p.base03, bg=nil, attr=nil, sp=nil }) hi('NvimTreeOpenedFile', { fg=p.base0B, bg=nil, attr='bold', sp=nil }) hi('NvimTreeRootFolder', { fg=p.base0E, bg=nil, attr=nil, sp=nil }) hi('NvimTreeSpecialFile', { fg=p.base0D, bg=nil, attr='bold,underline', sp=nil }) hi('NvimTreeSymlink', { fg=p.base0F, bg=nil, attr='bold', sp=nil }) hi('NvimTreeWindowPicker', { fg=p.base05, bg=p.base01, attr="bold", sp=nil }) ---- lewis6991/gitsigns.nvim hi('GitSignsAdd', {fg=p.base0B, bg=p.base01, attr=nil, sp=nil}) hi('GitSignsChange', {fg=p.base03, bg=p.base01, attr=nil, sp=nil}) hi('GitSignsDelete', {fg=p.base08, bg=p.base01, attr=nil, sp=nil}) ---- nvim-telescope/telescope.nvim hi('TelescopeBorder', {fg=p.base0F, bg=nil, attr=nil, sp=nil}) -- as in 'Delimiter' hi('TelescopeMatching', {fg=p.base0A, bg=nil, attr=nil, sp=nil}) -- as in 'Search' hi('TelescopeMultiSelection', {fg=nil, bg=p.base01, attr='bold', sp=nil}) hi('TelescopeSelection', {fg=nil, bg=p.base01, attr='bold', sp=nil}) ---- folke/which-key.nvim hi('WhichKey', {fg=p.base0D, bg=nil, attr=nil, sp=nil}) hi('WhichKeyDesc', {fg=p.base05, bg=nil, attr=nil, sp=nil}) hi('WhichKeyFloat', {fg=p.base05, bg=p.base01, attr=nil, sp=nil}) hi('WhichKeyGroup', {fg=p.base0E, bg=nil, attr=nil, sp=nil}) hi('WhichKeySeparator', {fg=p.base0B, bg=p.base01, attr=nil, sp=nil}) hi('WhichKeyValue', {fg=p.base03, bg=nil, attr=nil, sp=nil}) -- stylua: ignore end -- Terminal colors vim.g.terminal_color_0 = palette.base00 vim.g.terminal_color_1 = palette.base08 vim.g.terminal_color_2 = palette.base0B vim.g.terminal_color_3 = palette.base0A vim.g.terminal_color_4 = palette.base0D vim.g.terminal_color_5 = palette.base0E vim.g.terminal_color_6 = palette.base0C vim.g.terminal_color_7 = palette.base05 vim.g.terminal_color_8 = palette.base03 vim.g.terminal_color_9 = palette.base08 vim.g.terminal_color_10 = palette.base0B vim.g.terminal_color_11 = palette.base0A vim.g.terminal_color_12 = palette.base0D vim.g.terminal_color_13 = palette.base0E vim.g.terminal_color_14 = palette.base0C vim.g.terminal_color_15 = palette.base07 vim.g.terminal_color_background = vim.g.terminal_color_0 vim.g.terminal_color_foreground = vim.g.terminal_color_5 if vim.o.background == 'light' then vim.g.terminal_color_background = vim.g.terminal_color_7 vim.g.terminal_color_foreground = vim.g.terminal_color_2 end end function H.highlight_gui(group, args) -- NOTE: using `string.format` instead of gradually growing string with `..` -- is faster. Crude estimate for this particular case: whole colorscheme -- loading decreased from ~3.6ms to ~3.0ms, i.e. by about 20%. local command = string.format( [[highlight %s guifg=%s guibg=%s gui=%s guisp=%s]], group, args.fg or 'NONE', args.bg or 'NONE', args.attr or 'NONE', args.sp or 'NONE' ) vim.cmd(command) end function H.highlight_both(group, args) local command = string.format( [[highlight %s guifg=%s ctermfg=%s guibg=%s ctermbg=%s gui=%s cterm=%s guisp=%s]], group, args.fg and args.fg.gui or 'NONE', args.fg and args.fg.cterm or 'NONE', args.bg and args.bg.gui or 'NONE', args.bg and args.bg.cterm or 'NONE', args.attr or 'NONE', args.attr or 'NONE', args.sp and args.sp.gui or 'NONE' ) vim.cmd(command) end ---- Compound (gui and cterm) palette function H.make_compound_palette(palette, use_cterm) local cterm_table = use_cterm if type(use_cterm) == 'boolean' then cterm_table = MiniBase16.rgb_palette_to_cterm_palette(palette) end local res = {} for name, _ in pairs(palette) do res[name] = { gui = palette[name], cterm = cterm_table[name] } end return res end ---- Optimal scales ---- Make a set of equally spaced hues which are as different to present hues ---- as possible function H.make_different_hues(present_hues, n) local max_offset = math.floor(360 / n + 0.5) local dist, best_dist = nil, -math.huge local best_hues, new_hues for offset = 0, max_offset - 1, 1 do new_hues = H.make_hue_scale(n, offset) -- Compute distance as usual 'minimum distance' between two sets dist = H.dist_circle_set(new_hues, present_hues) -- Decide if it is the best if dist > best_dist then best_hues, best_dist = new_hues, dist end end return best_hues end function H.make_hue_scale(n, offset) local step = math.floor(360 / n + 0.5) local res = {} for i = 0, n - 1, 1 do table.insert(res, (offset + i * step) % 360) end return res end ---- Terminal colors ---- Sources: ---- - https://github.com/shawncplus/Vim-toCterm/blob/master/lib/Xterm.php ---- - https://gist.github.com/MicahElliott/719710 -- stylua: ignore start H.cterm_first16 = { { r = 0, g = 0, b = 0 }, { r = 205, g = 0, b = 0 }, { r = 0, g = 205, b = 0 }, { r = 205, g = 205, b = 0 }, { r = 0, g = 0, b = 238 }, { r = 205, g = 0, b = 205 }, { r = 0, g = 205, b = 205 }, { r = 229, g = 229, b = 229 }, { r = 127, g = 127, b = 127 }, { r = 255, g = 0, b = 0 }, { r = 0, g = 255, b = 0 }, { r = 255, g = 255, b = 0 }, { r = 92, g = 92, b = 255 }, { r = 255, g = 0, b = 255 }, { r = 0, g = 255, b = 255 }, { r = 255, g = 255, b = 255 }, } -- stylua: ignore end H.cterm_basis = { 0, 95, 135, 175, 215, 255 } function H.cterm2rgb(i) if i < 16 then return H.cterm_first16[i + 1] end if 16 <= i and i <= 231 then i = i - 16 local r = H.cterm_basis[math.floor(i / 36) % 6 + 1] local g = H.cterm_basis[math.floor(i / 6) % 6 + 1] local b = H.cterm_basis[i % 6 + 1] return { r = r, g = g, b = b } end if 232 <= i and i <= 255 then local c = 8 + (i - 232) * 10 return { r = c, g = c, b = c } end end function H.ensure_cterm_palette() if H.cterm_palette then return end H.cterm_palette = {} for i = 0, 255 do H.cterm_palette[i] = H.cterm2rgb(i) end end ---- Color conversion ---- Source: https://www.easyrgb.com/en/math.php ---- Accuracy is usually around 2-3 decimal digits, which should be fine ------ HEX <-> CIELCh(uv) function H.hex2lch(hex) local res = hex for _, f in pairs({ H.hex2rgb, H.rgb2xyz, H.xyz2luv, H.luv2lch }) do res = f(res) end return res end function H.lch2hex(lch) local res = lch for _, f in pairs({ H.lch2luv, H.luv2xyz, H.xyz2rgb, H.rgb2hex }) do res = f(res) end return res end ------ HEX <-> RGB function H.hex2rgb(hex) local dec = tonumber(hex:sub(2), 16) local b = math.fmod(dec, 256) local g = math.fmod((dec - b) / 256, 256) local r = math.floor(dec / 65536) return { r = r, g = g, b = b } end function H.rgb2hex(rgb) -- Round and trim values local t = vim.tbl_map(function(x) x = math.min(math.max(x, 0), 255) return math.floor(x + 0.5) end, rgb) return '#' .. string.format('%02x', t.r) .. string.format('%02x', t.g) .. string.format('%02x', t.b) end ------ RGB <-> XYZ function H.rgb2xyz(rgb) local t = vim.tbl_map(function(c) c = c / 255 if c > 0.04045 then c = ((c + 0.055) / 1.055) ^ 2.4 else c = c / 12.92 end return 100 * c end, rgb) -- Source of better matrix: http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html local x = 0.41246 * t.r + 0.35757 * t.g + 0.18043 * t.b local y = 0.21267 * t.r + 0.71515 * t.g + 0.07217 * t.b local z = 0.01933 * t.r + 0.11919 * t.g + 0.95030 * t.b return { x = x, y = y, z = z } end function H.xyz2rgb(xyz) -- Source of better matrix: http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html -- stylua: ignore start local r = 3.24045 * xyz.x - 1.53713 * xyz.y - 0.49853 * xyz.z local g = -0.96927 * xyz.x + 1.87601 * xyz.y + 0.04155 * xyz.z local b = 0.05564 * xyz.x - 0.20403 * xyz.y + 1.05722 * xyz.z -- stylua: ignore end return vim.tbl_map(function(c) c = c / 100 if c > 0.0031308 then c = 1.055 * (c ^ (1 / 2.4)) - 0.055 else c = 12.92 * c end return 255 * c end, { r = r, g = g, b = b, }) end ------ XYZ <-> CIELuv -------- Using white reference for D65 and 2 degress H.ref_u = (4 * 95.047) / (95.047 + (15 * 100) + (3 * 108.883)) H.ref_v = (9 * 100) / (95.047 + (15 * 100) + (3 * 108.883)) function H.xyz2luv(xyz) local x, y, z = xyz.x, xyz.y, xyz.z if x + y + z == 0 then return { l = 0, u = 0, v = 0 } end local var_u = 4 * x / (x + 15 * y + 3 * z) local var_v = 9 * y / (x + 15 * y + 3 * z) local var_y = y / 100 if var_y > 0.008856 then var_y = var_y ^ (1 / 3) else var_y = (7.787 * var_y) + (16 / 116) end local l = (116 * var_y) - 16 local u = 13 * l * (var_u - H.ref_u) local v = 13 * l * (var_v - H.ref_v) return { l = l, u = u, v = v } end function H.luv2xyz(luv) if luv.l == 0 then return { x = 0, y = 0, z = 0 } end local var_y = (luv.l + 16) / 116 if var_y ^ 3 > 0.008856 then var_y = var_y ^ 3 else var_y = (var_y - 16 / 116) / 7.787 end local var_u = luv.u / (13 * luv.l) + H.ref_u local var_v = luv.v / (13 * luv.l) + H.ref_v local y = var_y * 100 local x = -(9 * y * var_u) / ((var_u - 4) * var_v - var_u * var_v) local z = (9 * y - 15 * var_v * y - var_v * x) / (3 * var_v) return { x = x, y = y, z = z } end ------ CIELuv <-> CIELCh(uv) H.tau = 2 * math.pi function H.luv2lch(luv) local c = math.sqrt(luv.u ^ 2 + luv.v ^ 2) local h if c == 0 then h = 0 else -- Convert [-pi, pi] radians to [0, 360] degrees h = (math.atan2(luv.v, luv.u) % H.tau) * 360 / H.tau end return { l = luv.l, c = c, h = h } end function H.lch2luv(lch) local angle = lch.h * H.tau / 360 local u = lch.c * math.cos(angle) local v = lch.c * math.sin(angle) return { l = lch.l, u = u, v = v } end ---- Distances function H.dist_circle(x, y) local d = math.abs(x - y) % 360 return d > 180 and (360 - d) or d end function H.dist_circle_set(set1, set2) -- Minimum distance between all pairs local dist = math.huge local d for _, x in pairs(set1) do for _, y in pairs(set2) do d = H.dist_circle(x, y) if dist > d then dist = d end end end return dist end function H.nearest_rgb_id(rgb_target, rgb_palette) local best_dist = math.huge local best_id, dist for id, rgb in pairs(rgb_palette) do dist = math.abs(rgb_target.r - rgb.r) + math.abs(rgb_target.g - rgb.g) + math.abs(rgb_target.b - rgb.b) if dist < best_dist then best_id, best_dist = id, dist end end return best_id end return MiniBase16
local event = require "event" local network = require "network" local pipes = require "pipes" local component = require "component" local args = {...} local chanel = args[1] local AUTH = 0 local ENCRYPTED = 1 local TEXT = 2 local AUTHOK = 3 local passwdf = io.open("/etc/passwd","r") local pwHmac, pwHash = string.unpack("c16c32", component.data.decode64(passwdf:read("*a"))) passwdf:close() local pty, mi, mo, si, so = pipes.openPty() local shpid local chellengeKey = component.data.random(16) local authResponse = component.data.sha256(pwHash, chellengeKey) local key = authResponse:sub(1,16) local handlers = {} local function encryptedSend(data) local iv = component.data.random(16) network.tcp.send(chanel, string.pack("Bc16", ENCRYPTED, iv) .. component.data.encrypt(data, key, iv)) end handlers[AUTH] = function(data) if data == authResponse then shpid = os.spawnp("/bin/sh.lua", si, so, so) encryptedSend(string.pack("B", AUTHOK)) else network.tcp.close(chanel) os.exit() end end handlers[ENCRYPTED] = function(data) local iv, rs = string.unpack("c16", data) local d = component.data.decrypt(data:sub(rs), key, iv) if not d then network.tcp.close(chanel) os.exit() end local ptype, n = string.unpack("B", d) handlers[ptype](d:sub(n)) end handlers[TEXT] = function(data) mo:write(data) os.sleep(0) end network.tcp.send(chanel, string.pack("Bc16c16", AUTH, pwHmac, chellengeKey)) local function handleTcp() while true do while mi.remaining() > 0 do local data = mi:read(math.min(mi.remaining(), 7000)) encryptedSend(string.pack("B", TEXT) .. data) end local e = {event.pull()} --Note: if some text arrives it may require some poke to react if e[1] then if e[1] == "tcp" then if e[2] == "message" and e[3] == chanel then local ptype, n = string.unpack("B", e[4]) if not handlers[ptype] then network.tcp.close(chanel) os.exit() end handlers[ptype](e[4]:sub(n)) elseif e[2] == "close" and e[3] == chanel then return end elseif e[1] == "kill" and e[2] == shpid then network.tcp.close(chanel) return end end end end handleTcp()
--*********************************************************** --** ROBERT JOHNSON ** --*********************************************************** require "TimedActions/ISBaseTimedAction" ---@class ISShovelAction : ISBaseTimedAction ISShovelAction = ISBaseTimedAction:derive("ISShovelAction"); function ISShovelAction:isValid() self.plant:updateFromIsoObject() return self.plant:getIsoObject() ~= nil end function ISShovelAction:waitToStart() self.character:faceThisObject(self.plant:getObject()) return self.character:shouldBeTurning() end function ISShovelAction:update() self.item:setJobDelta(self:getJobDelta()); self.character:faceThisObject(self.plant:getObject()) self.character:setMetabolicTarget(Metabolics.DiggingSpade); end function ISShovelAction:start() self.item:setJobType(getText("ContextMenu_Remove")); self.item:setJobDelta(0.0); if self.plant:getSquare() then self.sound = getSoundManager():PlayWorldSound("Shoveling", self.plant:getSquare(), 0, 10, 1, true); end local anim = ISFarmingMenu.getShovelAnim(self.character:getPrimaryHandItem()) self:setActionAnim(anim) end function ISShovelAction:stop() if self.sound and self.sound:isPlaying() then self.sound:stop(); end ISBaseTimedAction.stop(self); self.item:setJobDelta(0.0); end function ISShovelAction:perform() if self.sound and self.sound:isPlaying() then self.sound:stop(); end self.item:getContainer():setDrawDirty(true); self.item:setJobDelta(0.0); local sq = self.plant:getSquare() local args = { x = sq:getX(), y = sq:getY(), z = sq:getZ() } CFarmingSystem.instance:sendCommand(self.character, 'removePlant', args) ISBaseTimedAction.perform(self); end function ISShovelAction:new (character, item, plant, time) local o = {} setmetatable(o, self) self.__index = self o.character = character; o.item = item; o.plant = plant; o.stopOnWalk = true; o.stopOnRun = true; o.maxTime = time; o.caloriesModifier = 4; return o end
local M = {} function M.setup() local opts = { silent = true, noremap = true } vim.api.nvim_set_keymap( 'n', '<space>h', '<cmd>lua require"harpoon.ui".toggle_quick_menu()<CR>', opts ) vim.cmd [[ autocmd FileType harpoon nnoremap <buffer> q :q<cr> ]] -- vim.api.nvim_buf_set_keymap(buf, 'n', 'q', ':q', { -- silent = true, -- noremap = true, -- nowait = true, -- }) end function M.config() require('harpoon').setup {} end return M
local spec = require('cmp.utils.spec') local context = require('cmp.context') describe('context', function() before_each(spec.before) describe('new', function() it('middle of text', function() vim.fn.setline('1', 'function! s:name() abort') vim.bo.filetype = 'vim' vim.fn.execute('normal! fm') local ctx = context.new() assert.are.equal(ctx.filetype, 'vim') assert.are.equal(ctx.cursor.row, 1) assert.are.equal(ctx.cursor.col, 15) assert.are.equal(ctx.cursor_line, 'function! s:name() abort') end) it('tab indent', function() vim.fn.setline('1', '\t\tab') vim.bo.filetype = 'vim' vim.fn.execute('normal! fb') local ctx = context.new() assert.are.equal(ctx.filetype, 'vim') assert.are.equal(ctx.cursor.row, 1) assert.are.equal(ctx.cursor.col, 4) assert.are.equal(ctx.cursor_line, '\t\tab') end) end) end)
--[[-------------------------------------------------- GUI Editor client settings.lua manages the gui editor settings (loading / saving / interface) --]]-------------------------------------------------- Settings = { gui = {}, default = { --guieditor_tutorial_completed = {value = false, type = "boolean"}, --guieditor_tutorial_version = {value = "1.0", type = "string"}, guieditor_update_check = {value = true, type = "boolean"}, snapping = {value = true, type = "boolean"}, snapping_precision = {value = 3, type = "number"}, snapping_influence = {value = 300, type = "number"}, snapping_recommended = {value = 10, type = "number"}, position_code_movement_warning = {value = true, type = "boolean"}, load_code_parse_calculations = {value = true, type = "boolean"}, -- either implement these or add them to the depreciated list --screen_output_type = {value = false, type = "boolean"} --child_output_type = {value = false, type = "boolean"} }, loaded = { }, } Settings.areaColourPacked = {Settings.areaColour, Settings.areaColour, Settings.areaColour, Settings.areaColour} gDeprecatedSettings = {child_output_type = true, screen_output_type = true, guieditor_tutorial_version = true, guieditor_tutorial_completed = true} function Settings.setup() if Settings.gui.wndMain then return end Settings.loadFile() Settings.createGUI() Snapping.updateValues() end --[[-------------------------------------------------- GUI things below --]]-------------------------------------------------- function Settings.createGUI() Settings.gui.wndMain = guiCreateWindow((gScreen.x - 280) / 2, (gScreen.y - 280) / 2, 280, 280, "Settings", false) guiWindowSetSizable(Settings.gui.wndMain, false) guiWindowTitlebarButtonAdd(Settings.gui.wndMain, "Cancel", "right", Settings.closeGUI) guiWindowTitlebarButtonAdd(Settings.gui.wndMain, "Save", "left", Settings.saveGUI) --[[-------------------------------------------------- update --]]-------------------------------------------------- Settings.gui.chkUpdateCheck = guiCreateCheckBox(20, 30, 230, 20, "Automatically check for updates", toBool(Settings.loaded.guieditor_update_check.value), false, Settings.gui.wndMain) Settings.gui.lblUpdateCheckCrush = guiCreateLabel(250, 30, 20, 20, "<<", false, Settings.gui.wndMain) setRolloverColour(Settings.gui.lblUpdateCheckCrush, gColours.primary, gColours.defaultLabel) Settings.gui.lblUpdateHelp = guiCreateLabel(20, 25, 0, 30, "Let the GUI Editor automatically check\nfor updates when it starts.", false, Settings.gui.wndMain) guiLabelSetVerticalAlign(Settings.gui.lblUpdateHelp, "center") setCrushToggle(Settings.gui.lblUpdateCheckCrush, 250, 230, Settings.gui.chkUpdateCheck, Settings.gui.lblUpdateHelp) Settings.gui.imgUpdateAreaLeft = guiCreateStaticImage(10, 25, 1, 30, "images/dot_white.png", false, Settings.gui.wndMain) Settings.gui.imgUpdateAreaTop = guiCreateStaticImage(10, 25, 260, 1, "images/dot_white.png", false, Settings.gui.wndMain) Settings.gui.imgUpdateAreaBottom = guiCreateStaticImage(10, 55, 260, 1, "images/dot_white.png", false, Settings.gui.wndMain) guiSetProperty(Settings.gui.imgUpdateAreaLeft, "ImageColours", string.format("tl:FF%s tr:FF%s bl:FF%s br:FF%s", unpack(gAreaColours.primaryPacked))) guiSetProperty(Settings.gui.imgUpdateAreaTop, "ImageColours", string.format("tl:FF%s tr:00%s bl:FF%s br:00%s", unpack(gAreaColours.primaryPacked))) guiSetProperty(Settings.gui.imgUpdateAreaBottom, "ImageColours", string.format("tl:FF%s tr:00%s bl:FF%s br:00%s", unpack(gAreaColours.primaryPacked))) --[[-------------------------------------------------- snapping --]]-------------------------------------------------- Settings.gui.chkSnapping = guiCreateCheckBox(20, 70, 230, 20, "Enable snapping", toBool(Settings.loaded.snapping.value), false, Settings.gui.wndMain) Settings.gui.lblSnappingCrush = guiCreateLabel(250, 70, 20, 20, "<<", false, Settings.gui.wndMain) setRolloverColour(Settings.gui.lblSnappingCrush, gColours.primary, gColours.defaultLabel) Settings.gui.lblSnappingHelp = guiCreateLabel(20, 65, 0, 30, "Let an element being moved 'snap' to\nthe edges of nearby elements.", false, Settings.gui.wndMain) guiLabelSetVerticalAlign(Settings.gui.lblSnappingHelp, "center") setCrushToggle(Settings.gui.lblSnappingCrush, 250, 230, Settings.gui.chkSnapping, Settings.gui.lblSnappingHelp) addEventHandler("onClientGUIClick", Settings.gui.chkSnapping, function(button, state) if button == "left" and state == "up" then if guiCheckBoxGetSelected(Settings.gui.chkSnapping) then guiSetEnabled(Settings.gui.lblSnappingPrecision, true) guiSetEnabled(Settings.gui.lblSnappingInfluence, true) guiSetEnabled(Settings.gui.lblSnappingOffset, true) else guiSetEnabled(Settings.gui.lblSnappingPrecision, false) guiSetEnabled(Settings.gui.lblSnappingInfluence, false) guiSetEnabled(Settings.gui.lblSnappingOffset, false) end end end , false) -- precision Settings.gui.lblSnappingPrecision = guiCreateLabel(20, 95, 230, 30, "", false, Settings.gui.wndMain) Settings.gui.lblSnappingPrecisionDescription = guiCreateLabel(0, 5, 60, 20, "Precision: ", false, Settings.gui.lblSnappingPrecision) Settings.gui.lblSnappingPrecisionEdit = guiCreateEdit(70, 5, 100, 20, tostring(Settings.loaded.snapping_precision.value), false, Settings.gui.lblSnappingPrecision) setElementData(Settings.gui.lblSnappingPrecisionEdit, "guieditor:filter", gFilters.numberInt) --Settings.gui.lblSnappingPrecisionDefault = guiCreateLabel(175, 5, 30, 20, "Default", false, Settings.gui.lblSnappingPrecision) --guiSetFont(Settings.gui.lblSnappingPrecisionDefault, "default-small") --guiLabelSetVerticalAlign(Settings.gui.lblSnappingPrecisionDefault, "center") --setRolloverColour(Settings.gui.lblSnappingPrecisionDefault, gColours.primary, gColours.defaultLabel) Settings.gui.lblSnappingPrecisionCrush = guiCreateLabel(250, 100, 20, 20, "<<", false, Settings.gui.wndMain) setRolloverColour(Settings.gui.lblSnappingPrecisionCrush, gColours.primary, gColours.defaultLabel) Settings.gui.lblSnappingPrecisionHelp = guiCreateLabel(20, 95, 0, 30, "The pixel distance from an edge an\nelement needs to be before it 'snaps'.", false, Settings.gui.wndMain) guiLabelSetVerticalAlign(Settings.gui.lblSnappingPrecisionHelp, "center") setCrushToggle(Settings.gui.lblSnappingPrecisionCrush, 250, 230, Settings.gui.lblSnappingPrecision, Settings.gui.lblSnappingPrecisionHelp) Settings.gui.imgSnappingPrecisionReset = guiCreateStaticImage(190, 8, 14, 14, "images/reset.png", false, Settings.gui.lblSnappingPrecision) Settings.gui.lblSnappingPrecisionReset = guiCreateLabel(180, 2, 34, 30, "reset to default", false, Settings.gui.lblSnappingPrecision) guiSetFont(Settings.gui.lblSnappingPrecisionReset, "default-small") guiSetColour(Settings.gui.lblSnappingPrecisionReset, unpack(gColours.primary)) guiLabelSetVerticalAlign(Settings.gui.lblSnappingPrecisionReset, "top") guiLabelSetHorizontalAlign(Settings.gui.lblSnappingPrecisionReset, "center", true) guiSetVisible(Settings.gui.lblSnappingPrecisionReset, false) addEventHandler("onClientMouseEnter", Settings.gui.imgSnappingPrecisionReset, function() guiSetVisible(Settings.gui.lblSnappingPrecisionReset, true) guiSetVisible(Settings.gui.imgSnappingPrecisionReset, false) end, false) addEventHandler("onClientMouseLeave", Settings.gui.lblSnappingPrecisionReset, function() guiSetVisible(Settings.gui.lblSnappingPrecisionReset, false) guiSetVisible(Settings.gui.imgSnappingPrecisionReset, true) end, false) addEventHandler("onClientGUIClick", Settings.gui.lblSnappingPrecisionReset, function() guiSetText(Settings.gui.lblSnappingPrecisionEdit, tostring(Settings.default.snapping_precision.value)) end, false) -- influence Settings.gui.lblSnappingInfluence = guiCreateLabel(20, 125, 230, 30, "", false, Settings.gui.wndMain) Settings.gui.lblSnappingInfluenceDescription = guiCreateLabel(0, 5, 60, 20, "Influence: ", false, Settings.gui.lblSnappingInfluence) Settings.gui.lblSnappingInfluenceEdit = guiCreateEdit(70, 5, 100, 20, tostring(Settings.loaded.snapping_influence.value), false, Settings.gui.lblSnappingInfluence) setElementData(Settings.gui.lblSnappingInfluenceEdit, "guieditor:filter", gFilters.numberInt) Settings.gui.lblSnappingInfluenceCrush = guiCreateLabel(250, 130, 20, 20, "<<", false, Settings.gui.wndMain) setRolloverColour(Settings.gui.lblSnappingInfluenceCrush, gColours.primary, gColours.defaultLabel) Settings.gui.lblSnappingInfluenceHelp = guiCreateLabel(20, 125, 0, 30, "Only elements within this distance\ncan be snapped to.", false, Settings.gui.wndMain) guiLabelSetVerticalAlign(Settings.gui.lblSnappingInfluenceHelp, "center") setCrushToggle(Settings.gui.lblSnappingInfluenceCrush, 250, 230, Settings.gui.lblSnappingInfluence, Settings.gui.lblSnappingInfluenceHelp) Settings.gui.imgSnappingInfluenceReset = guiCreateStaticImage(190, 8, 14, 14, "images/reset.png", false, Settings.gui.lblSnappingInfluence) Settings.gui.lblSnappingInfluenceReset = guiCreateLabel(180, 2, 34, 30, "reset to default", false, Settings.gui.lblSnappingInfluence) guiSetFont(Settings.gui.lblSnappingInfluenceReset, "default-small") guiSetColour(Settings.gui.lblSnappingInfluenceReset, unpack(gColours.primary)) guiLabelSetVerticalAlign(Settings.gui.lblSnappingInfluenceReset, "top") guiLabelSetHorizontalAlign(Settings.gui.lblSnappingInfluenceReset, "center", true) guiSetVisible(Settings.gui.lblSnappingInfluenceReset, false) addEventHandler("onClientMouseEnter", Settings.gui.imgSnappingInfluenceReset, function() guiSetVisible(Settings.gui.lblSnappingInfluenceReset, true) guiSetVisible(Settings.gui.imgSnappingInfluenceReset, false) end, false) addEventHandler("onClientMouseLeave", Settings.gui.lblSnappingInfluenceReset, function() guiSetVisible(Settings.gui.lblSnappingInfluenceReset, false) guiSetVisible(Settings.gui.imgSnappingInfluenceReset, true) end, false) addEventHandler("onClientGUIClick", Settings.gui.lblSnappingInfluenceReset, function() guiSetText(Settings.gui.lblSnappingInfluenceEdit, tostring(Settings.default.snapping_influence.value)) end, false) -- offset Settings.gui.lblSnappingOffset = guiCreateLabel(20, 155, 230, 30, "", false, Settings.gui.wndMain) Settings.gui.lblSnappingOffsetDescription = guiCreateLabel(0, 5, 60, 20, "Offset: ", false, Settings.gui.lblSnappingOffset) Settings.gui.lblSnappingOffsetEdit = guiCreateEdit(70, 5, 100, 20, tostring(Settings.loaded.snapping_recommended.value), false, Settings.gui.lblSnappingOffset) setElementData(Settings.gui.lblSnappingOffsetEdit, "guieditor:filter", gFilters.numberInt) Settings.gui.lblSnappingOffsetCrush = guiCreateLabel(250, 160, 20, 20, "<<", false, Settings.gui.wndMain) setRolloverColour(Settings.gui.lblSnappingOffsetCrush, gColours.primary, gColours.defaultLabel) Settings.gui.lblSnappingOffsetHelp = guiCreateLabel(20, 155, 0, 30, "Add additional snap points this far\nfrom the egdes of elements.", false, Settings.gui.wndMain) guiLabelSetVerticalAlign(Settings.gui.lblSnappingOffsetHelp, "center") setCrushToggle(Settings.gui.lblSnappingOffsetCrush, 250, 230, Settings.gui.lblSnappingOffset, Settings.gui.lblSnappingOffsetHelp) Settings.gui.imgSnappingOffsetReset = guiCreateStaticImage(190, 8, 14, 14, "images/reset.png", false, Settings.gui.lblSnappingOffset) Settings.gui.lblSnappingOffsetReset = guiCreateLabel(180, 2, 34, 30, "reset to default", false, Settings.gui.lblSnappingOffset) guiSetFont(Settings.gui.lblSnappingOffsetReset, "default-small") guiSetColour(Settings.gui.lblSnappingOffsetReset, unpack(gColours.primary)) guiLabelSetVerticalAlign(Settings.gui.lblSnappingOffsetReset, "top") guiLabelSetHorizontalAlign(Settings.gui.lblSnappingOffsetReset, "center", true) guiSetVisible(Settings.gui.lblSnappingOffsetReset, false) addEventHandler("onClientMouseEnter", Settings.gui.imgSnappingOffsetReset, function() guiSetVisible(Settings.gui.lblSnappingOffsetReset, true) guiSetVisible(Settings.gui.imgSnappingOffsetReset, false) end, false) addEventHandler("onClientMouseLeave", Settings.gui.lblSnappingOffsetReset, function() guiSetVisible(Settings.gui.lblSnappingOffsetReset, false) guiSetVisible(Settings.gui.imgSnappingOffsetReset, true) end, false) addEventHandler("onClientGUIClick", Settings.gui.lblSnappingOffsetReset, function() guiSetText(Settings.gui.lblSnappingOffsetEdit, tostring(Settings.default.snapping_recommended.value)) end, false) if toBool(Settings.loaded.snapping.value) then guiSetEnabled(Settings.gui.lblSnappingPrecision, true) guiSetEnabled(Settings.gui.lblSnappingInfluence, true) guiSetEnabled(Settings.gui.lblSnappingOffset, true) else guiSetEnabled(Settings.gui.lblSnappingPrecision, false) guiSetEnabled(Settings.gui.lblSnappingInfluence, false) guiSetEnabled(Settings.gui.lblSnappingOffset, false) end Settings.gui.imgSnappingAreaLeft = guiCreateStaticImage(10, 65, 1, 120, "images/dot_white.png", false, Settings.gui.wndMain) Settings.gui.imgSnappingAreaTop = guiCreateStaticImage(10, 65, 260, 1, "images/dot_white.png", false, Settings.gui.wndMain) Settings.gui.imgSnappingAreaBottom = guiCreateStaticImage(10, 185, 260, 1, "images/dot_white.png", false, Settings.gui.wndMain) guiSetProperty(Settings.gui.imgSnappingAreaLeft, "ImageColours", string.format("tl:FF%s tr:FF%s bl:FF%s br:FF%s", unpack(gAreaColours.primaryPacked))) guiSetProperty(Settings.gui.imgSnappingAreaTop, "ImageColours", string.format("tl:FF%s tr:00%s bl:FF%s br:00%s", unpack(gAreaColours.primaryPacked))) guiSetProperty(Settings.gui.imgSnappingAreaBottom, "ImageColours", string.format("tl:FF%s tr:00%s bl:FF%s br:00%s", unpack(gAreaColours.primaryPacked))) --[[-------------------------------------------------- position code movement warning --]]-------------------------------------------------- Settings.gui.chkPositionCodeMovementWarning = guiCreateCheckBox(20, 200, 230, 20, "Enable position code move warning", toBool(Settings.loaded.position_code_movement_warning.value), false, Settings.gui.wndMain) Settings.gui.lblPositionCodeMovementWarningCrush = guiCreateLabel(250, 200, 20, 20, "<<", false, Settings.gui.wndMain) setRolloverColour(Settings.gui.lblPositionCodeMovementWarningCrush, gColours.primary, gColours.defaultLabel) Settings.gui.lblPositionCodeMovementWarningHelp = guiCreateLabel(20, 195, 0, 30, "Show a warning when trying to move\nan element that uses position code.", false, Settings.gui.wndMain) guiLabelSetVerticalAlign(Settings.gui.lblPositionCodeMovementWarningHelp, "center") setCrushToggle(Settings.gui.lblPositionCodeMovementWarningCrush, 250, 230, Settings.gui.chkPositionCodeMovementWarning, Settings.gui.lblPositionCodeMovementWarningHelp) Settings.gui.imgPositionCodeAreaLeft = guiCreateStaticImage(10, 195, 1, 30, "images/dot_white.png", false, Settings.gui.wndMain) Settings.gui.imgPositionCodeAreaTop = guiCreateStaticImage(10, 195, 260, 1, "images/dot_white.png", false, Settings.gui.wndMain) Settings.gui.imgPositionCodeAreaBottom = guiCreateStaticImage(10, 225, 260, 1, "images/dot_white.png", false, Settings.gui.wndMain) guiSetProperty(Settings.gui.imgPositionCodeAreaLeft, "ImageColours", string.format("tl:FF%s tr:FF%s bl:FF%s br:FF%s", unpack(gAreaColours.primaryPacked))) guiSetProperty(Settings.gui.imgPositionCodeAreaTop, "ImageColours", string.format("tl:FF%s tr:00%s bl:FF%s br:00%s", unpack(gAreaColours.primaryPacked))) guiSetProperty(Settings.gui.imgPositionCodeAreaBottom, "ImageColours", string.format("tl:FF%s tr:00%s bl:FF%s br:00%s", unpack(gAreaColours.primaryPacked))) --[[-------------------------------------------------- load code calculations --]]-------------------------------------------------- Settings.gui.chkLoadCodeCalculations = guiCreateCheckBox(20, 240, 230, 20, "Load code position calculations", toBool(Settings.loaded.load_code_parse_calculations.value), false, Settings.gui.wndMain) Settings.gui.lblLoadCodeCalculationsCrush = guiCreateLabel(250, 240, 20, 20, "<<", false, Settings.gui.wndMain) setRolloverColour(Settings.gui.lblLoadCodeCalculationsCrush, gColours.primary, gColours.defaultLabel) Settings.gui.lblLoadCodeCalculationsHelp = guiCreateLabel(20, 235, 0, 30, "Attempt to parse position calculations \nwhen loading code. 'Help' for more info.", false, Settings.gui.wndMain) guiLabelSetVerticalAlign(Settings.gui.lblLoadCodeCalculationsHelp, "center") --guiSetFont(Settings.gui.lblLoadCodeCalculationsHelp, "default-small") setCrushToggle(Settings.gui.lblLoadCodeCalculationsCrush, 250, 230, Settings.gui.chkLoadCodeCalculations, Settings.gui.lblLoadCodeCalculationsHelp) Settings.gui.imgLoadCodeAreaLeft = guiCreateStaticImage(10, 235, 1, 30, "images/dot_white.png", false, Settings.gui.wndMain) Settings.gui.imgLoadCodeAreaTop = guiCreateStaticImage(10, 235, 260, 1, "images/dot_white.png", false, Settings.gui.wndMain) Settings.gui.imgLoadCodeAreaBottom = guiCreateStaticImage(10, 265, 260, 1, "images/dot_white.png", false, Settings.gui.wndMain) guiSetProperty(Settings.gui.imgLoadCodeAreaLeft, "ImageColours", string.format("tl:FF%s tr:FF%s bl:FF%s br:FF%s", unpack(gAreaColours.primaryPacked))) guiSetProperty(Settings.gui.imgLoadCodeAreaTop, "ImageColours", string.format("tl:FF%s tr:00%s bl:FF%s br:00%s", unpack(gAreaColours.primaryPacked))) guiSetProperty(Settings.gui.imgLoadCodeAreaBottom, "ImageColours", string.format("tl:FF%s tr:00%s bl:FF%s br:00%s", unpack(gAreaColours.primaryPacked))) guiSetVisible(Settings.gui.wndMain, false) doOnChildren(Settings.gui.wndMain, setElementData, "guieditor.internal:noLoad", true) --setElementData(Settings.gui.wndMain, "guieditor.internal:noLoad", true) end function Settings.closeGUI() guiSetVisible(Settings.gui.wndMain, false) guiCheckBoxSetSelected(Settings.gui.chkUpdateCheck, toBool(Settings.loaded.guieditor_update_check.value)) guiCheckBoxSetSelected(Settings.gui.chkSnapping, toBool(Settings.loaded.snapping.value)) guiSetText(Settings.gui.lblSnappingPrecisionEdit, tostring(Settings.loaded.snapping_precision.value)) guiSetText(Settings.gui.lblSnappingInfluenceEdit, tostring(Settings.loaded.snapping_influence.value)) guiSetText(Settings.gui.lblSnappingOffsetEdit, tostring(Settings.loaded.snapping_recommended.value)) guiCheckBoxSetSelected(Settings.gui.chkLoadCodeCalculations, toBool(Settings.loaded.load_code_parse_calculations.value)) Snapping.updateValues() end function Settings.openGUI() guiSetVisible(Settings.gui.lblSnappingPrecisionReset, false) guiSetVisible(Settings.gui.imgSnappingPrecisionReset, true) guiSetVisible(Settings.gui.lblSnappingInfluenceReset, false) guiSetVisible(Settings.gui.imgSnappingInfluenceReset, true) guiSetVisible(Settings.gui.lblSnappingOffsetReset, false) guiSetVisible(Settings.gui.imgSnappingOffsetReset, true) guiSetVisible(Settings.gui.wndMain, true) guiBringToFront(Settings.gui.wndMain, true) end function Settings.saveGUI() Settings.loaded.guieditor_update_check.value = guiCheckBoxGetSelected(Settings.gui.chkUpdateCheck) Settings.loaded.snapping.value = guiCheckBoxGetSelected(Settings.gui.chkSnapping) Settings.loaded.snapping_precision.value = tonumber(guiGetText(Settings.gui.lblSnappingPrecisionEdit)) Settings.loaded.snapping_influence.value = tonumber(guiGetText(Settings.gui.lblSnappingInfluenceEdit)) Settings.loaded.snapping_recommended.value = tonumber(guiGetText(Settings.gui.lblSnappingOffsetEdit)) Settings.loaded.position_code_movement_warning.value = guiCheckBoxGetSelected(Settings.gui.chkPositionCodeMovementWarning) Settings.loaded.load_code_parse_calculations.value = guiCheckBoxGetSelected(Settings.gui.chkLoadCodeCalculations) Settings.saveFile() Settings.closeGUI() ContextBar.add("Settings saved") end function Settings.saveFile() local file = xmlLoadFile("settings.xml") if not file then Settings.createFile() file = xmlLoadFile("settings.xml") if not file then return end end -- old version, make it conform to new layout if xmlNodeGetName(file) == "settings" then xmlNodeSetName(file, "guieditor") end -- remove nodes that are sitting below the base guieditor (previously settings) node -- they now exist within \guieditor\settings instead for i,node in ipairs(xmlNodeGetChildren(file)) do local value = xmlNodeGetValue(node) if Settings.default[xmlNodeGetName(node)] then xmlDestroyNode(node) end end local base = getChild(file, "settings", 0) if base then for name, setting in pairs(Settings.loaded) do local node = getChild(base, tostring(name), 0) if node then xmlNodeSetValue(node, tostring(setting.value)) else outputDebug("Failed to save GUI Editor '"..tostring(name).."' setting.") end end end xmlSaveFile(file) xmlUnloadFile(file) return end function Settings.createFile() local file = xmlLoadFile("settings.xml") if not file then file = xmlCreateFile("settings.xml", "guieditor") if file then outputDebug("Created GUI Editor settings file successfully.") else outputDebug("Could not create GUI Editor settings file (Uh oh!)") return end end local base = xmlCreateChild(file, "settings") if base then for name, setting in pairs(Settings.default) do local node = xmlCreateChild(base, tostring(name)) if node then xmlNodeSetValue(node, tostring(setting.value)) else outputDebug("Failed to create GUI Editor '"..tostring(name).."' setting.") end end end xmlSaveFile(file) xmlUnloadFile(file) return end function getChild(parent, name, index) local child = xmlFindChild(parent, name, index) if not child then child = xmlCreateChild(parent, name) end return child end function Settings.loadFile() local file = xmlLoadFile("settings.xml") if not file then outputDebug("Couldnt find GUI Editor settings file. Creating...") Settings.createFile() file = xmlLoadFile("settings.xml") end if file then local base -- old version if xmlNodeGetName(file) == "settings" then base = file -- new version elseif xmlNodeGetName(file) == "guieditor" then base = getChild(file, "settings", 0) end if base then for i,node in ipairs(xmlNodeGetChildren(base)) do local value = xmlNodeGetValue(node) if value and xmlNodeGetName(node) ~= "settings" then local name = xmlNodeGetName(node) -- silly side effect of having shitty settings to begin with -- redirect deprecated names onto their new counterparts name = checkOutdatedNodes(node) if not gDeprecatedSettings[name] then local formatted = formatValue(value, name) if formatted ~= nil then Settings.loaded[name] = {} Settings.loaded[name].value = formatted Settings.loaded[name].type = Settings.default[name].type else outputDebug("Failed to load GUI Editor '"..name.."' setting. Using default...") Settings.loaded[name] = {} Settings.loaded[name].value = Settings.default[name].value Settings.loaded[name].type = Settings.default[name].type end else xmlDestroyNode(node) end end end for name, setting in pairs(Settings.default) do if not Settings.loaded[name] then outputDebug("Couldn't find GUI Editor '"..name.."' setting. Using default...") Settings.loaded[name] = {} Settings.loaded[name].value = setting.value Settings.loaded[name].type = setting.type end end else outputDebug("Couldn't find GUI Editor settings node. Using defaults...") for name, setting in pairs(Settings.default) do Settings.loaded[name] = {} Settings.loaded[name].value = setting.value Settings.loaded[name].type = setting.type end end xmlSaveFile(file) xmlUnloadFile(file) else outputDebug("Failed to load GUI Editor settings. Using defaults...") for name, setting in pairs(Settings.default) do Settings.loaded[name] = {} Settings.loaded[name].value = setting.value Settings.loaded[name].type = setting.type end end Settings.saveFile() return end function formatValue(value, name) if name and Settings.default[name] then if Settings.default[name].type == "string" then return tostring(value) elseif Settings.default[name].type == "number" then return tonumber(value) elseif Settings.default[name].type == "boolean" then return loadstring("return "..tostring(value))() end end return nil end function checkOutdatedNodes(node) local name = xmlNodeGetName(node) if name == "tutorial" then xmlDestroyNode(node) outputDebug("Destroying deprecated GUI Editor settings node '"..name.."'.", "SETTINGS") return "guieditor_tutorial_completed" elseif name == "tutorialversion" then xmlDestroyNode(node) outputDebug("Destroying deprecated GUI Editor settings node '"..name.."'.", "SETTINGS") return "guieditor_tutorial_version" elseif name == "updatecheck" then xmlDestroyNode(node) outputDebug("Destroying deprecated GUI Editor settings node '"..name.."'.", "SETTINGS") return "guieditor_update_check" end return name end
local boo = { value = 7, compute= function(self, i) return self.value*i+1 end } print(boo:compute(3) + boo:compute(7))
fs_animation={} fs_ease={} fs_ease["사인인"] = function(a) return pini.Anim.EaseSineIn(a) end fs_ease["사인아웃"] = function(a) return pini.Anim.EaseSineOut(a) end fs_ease["사인인아웃"] = function(a) return pini.Anim.EaseSineInOut(a) end fs_ease["바운스인"] = function(a) return pini.Anim.EaseBounceIn(a) end fs_ease["바운스아웃"] = function(a) return pini.Anim.EaseBounceOut(a) end fs_ease["바운스인아웃"] = function(a) return pini.Anim.EaseBounceInOut(a) end fs_ease["백인"] = function(a) return pini.Anim.EaseBackIn(a) end fs_ease["백아웃"] = function(a) return pini.Anim.EaseBackOut(a) end fs_ease["백인아웃"] = function(a) return pini.Anim.EaseBackInOut(a) end fs_ease["엘라스틱인"] = function(a) return pini.Anim.EaseElasticIn(a) end fs_ease["엘라스틱아웃"] = function(a) return pini.Anim.EaseElasticOut(a) end fs_ease["엘라스틱인아웃"] = function(a) return pini.Anim.EaseElasticInOut(a) end local function posStrToPt(pos) local winSize = {width=WIN_WIDTH,height=WIN_HEIGHT}--cc.Director:getInstance():getVisibleSize() local pos = pos:explode(",") --if OnPreview then return tonumber(pos[1] or 0),tonumber(pos[2] or 0) --else -- return tonumber(pos[1] or 0),winSize.height-tonumber(pos[2] or 0) --end end fs_animation["이동"] = { "위치=\"0,0\" 시간=\"1\" 가속=\"\" ", function(vm,node) local pos = vm:ARGU("애니메이션","위치","0,0") local sec = vm:ARGU("애니메이션","시간",1) local ease = vm:ARGU("애니메이션","가속","") local rep = vm:ARGU("애니메이션","지속","아니오") local legacy = vm:ARGU("애니메이션","레거시","아니오") legacy = legacy == "예" local parent = nil if not legacy then parent = node.parent end local x,y = posStrToPt(pos) local action = pini.Anim.MoveTo(sec,x,y,parent) if fs_ease[ease] then action = fs_ease[ease](action) end action:run(node) end } fs_animation["회전"] = { "각도=\"90\" 시간=\"1\" 가속=\"\" ", function(vm,node) local rot = vm:ARGU("애니메이션","각도",0) local sec = vm:ARGU("애니메이션","시간",1) local ease = vm:ARGU("애니메이션","가속","") local rep = vm:ARGU("애니메이션","지속","아니오") local action = pini.Anim.RotateTo(sec,rot) if fs_ease[ease] then action = fs_ease[ease](action) end if rep == "예" then --action = cc.Repeat:create(action,999) end action:run(node) end } fs_animation["크기"] = { "크기=\"100,100\" 시간=\"1\" 가속=\"\" ", function(vm,node) local size = vm:ARGU("애니메이션","크기","100,100") local sec = vm:ARGU("애니메이션","시간",1) local ease = vm:ARGU("애니메이션","가속","") local rep = vm:ARGU("애니메이션","지속","아니오") local size = size:explode(",") local action = pini.Anim.ScaleTo(sec,tonumber(size[1]),tonumber(size[2])) if fs_ease[ease] then action = fs_ease[ease](action) end if rep == "예" then --action = cc.RepeatForever:create(action) end action:run(node) end } fs_animation["점프"] = { "위치=\"100,0\" 횟수=\"1\" 높이=\"50\" 시간=\"1\" 가속=\"\"", function(vm,node) local pos = vm:ARGU("애니메이션","위치","0,0") local count = vm:ARGU("애니메이션","횟수",0) local height = vm:ARGU("애니메이션","높이",0) local sec = vm:ARGU("애니메이션","시간",1) local ease = vm:ARGU("애니메이션","가속","") local x,y = posStrToPt(pos) local action = pini.Anim.JumpTo(sec,x,y,height,count) if fs_ease[ease] then action = fs_ease[ease](action) end if rep == "예" then --action = cc.RepeatForever:create(action) end action:run(node) end } fs_animation["투명"] = { "투명도=\"1\" 시간=\"1\" 가속=\"\"", function(vm,node) local fade1 = vm:ARGU("애니메이션","투명",nil) local fade2 = vm:ARGU("애니메이션","투명도",nil) local sec = vm:ARGU("애니메이션","시간",1) local ease = vm:ARGU("애니메이션","가속","") local fade = ((tonumber(fade1) or tonumber(fade2)) or 1) local action = pini.Anim.FadeTo(sec,fade) if fs_ease[ease] then action = fs_ease[ease](action) end if rep == "예" then --action = cc.RepeatForever:create(action) end action:run(node) end } fs_animation["블링크"] = { "횟수=\"5\" 시간=\"1\" 가속=\"\"", function(vm,node) local count = vm:ARGU("애니메이션","횟수",1) local sec = vm:ARGU("애니메이션","시간",1) local ease = vm:ARGU("애니메이션","가속","") local action = pini.Anim.Blink(sec,count) if fs_ease[ease] then action = fs_ease[ease](action) end if rep == "예" then --action = cc.RepeatForever:create(action) end action:run(node) end } fs_animation["색상"] = { "색상=\"255,255,255\" 시간=\"1\" 가속=\"\"", function(vm,node) local color = vm:ARGU("애니메이션","색상","255,255,255") local sec = vm:ARGU("애니메이션","시간",1) local ease = vm:ARGU("애니메이션","가속","") color = color:explode(",") local action = pini.Anim.TintTo(sec,tonumber(color[1] or 255), tonumber(color[2] or 255), tonumber(color[3] or 255)) if fs_ease[ease] then action = fs_ease[ease](action) end if rep == "예" then --action = cc.RepeatForever:create(action) end action:run(node) end } fs_animation["상하흔들기"] = { "폭=\"50\" 횟수=\"1\" 시간=\"1\" 가속=\"\"", function(vm,node) local width = vm:ARGU("애니메이션","폭",1) local count = vm:ARGU("애니메이션","횟수",1) local sec = vm:ARGU("애니메이션","시간",1) local ease = vm:ARGU("애니메이션","가속","") local action = nil for i=1,count,1 do local a = pini.Anim.Sequence( pini.Anim.MoveBy(sec/(4*count),0,width/2), pini.Anim.MoveBy(sec/(4*count),0,-width/2), pini.Anim.MoveBy(sec/(4*count),0,-width/2), pini.Anim.MoveBy(sec/(4*count),0,width/2) ) if action then action = pini.Anim.Sequence(action,a) else action = a end end if fs_ease[ease] then action = fs_ease[ease](action) end if rep == "예" then --action = cc.RepeatForever:create(action) end action:run(node) end } fs_animation["좌우흔들기"] = { "폭=\"50\" 횟수=\"1\" 시간=\"1\" 가속=\"\"", function(vm,node) local width = vm:ARGU("애니메이션","폭",1) local count = vm:ARGU("애니메이션","횟수",1) local sec = vm:ARGU("애니메이션","시간",1) local ease = vm:ARGU("애니메이션","가속","") local action = nil for i=1,count,1 do local a = pini.Anim.Sequence( pini.Anim.MoveBy(sec/(4*count),width/2,0), pini.Anim.MoveBy(sec/(4*count),-width/2,0), pini.Anim.MoveBy(sec/(4*count),-width/2,0), pini.Anim.MoveBy(sec/(4*count),width/2,0) ) if action then action = pini.Anim.Sequence(action,a) else action = a end end if fs_ease[ease] then action = fs_ease[ease](action) end if rep == "예" then --action = cc.RepeatForever:create(action) end action:run(node) end } fs_animation["떨림"] = { "폭=\"4\" 시간=\"1\" 가속=\"\"", function(vm,node) local width = vm:ARGU("애니메이션","폭",1) local sec = vm:ARGU("애니메이션","시간",1) local ease = vm:ARGU("애니메이션","가속","") local actions = {} local x,y = node:position() if node.isRunnVibe then return end node.isRunnVibe = true pini.Timer(pini:GetUUID(),0,function(t) t.userdata.delta = t.userdata.delta + t.dt local node = pini:FindNode(t.userdata.nodeId) if node then if node:ActiveActions() > 0 then return ; end if node.onAnim == true then local dx = math.random()*t.userdata.width - t.userdata.width/2 local dy = math.random()*t.userdata.width - t.userdata.width/2 node:setPosition(dx+t.userdata.x,dy+t.userdata.y) if t.userdata.delta > t.userdata.sec then t:stop() node:setPosition(t.userdata.x,t.userdata.y) node.isRunnVibe = nil end else t:stop() node:setPosition(t.userdata.x,t.userdata.y) node.isRunnVibe = nil end end end,true,nil,{ x=x, y=y, nodeId=node.id, width=width, delta=0, sec=tonumber(sec) or 1 }):run() end } fs_animation["걷기"] = { "폭=\"40\" 횟수=\"5\" 확대=\"1.3,1.3\" 시간=\"1\" 가속=\"\"", function(vm,node) local width = vm:ARGU("애니메이션","폭",1) local count = vm:ARGU("애니메이션","횟수",1) local sec = vm:ARGU("애니메이션","시간",1) local ease = vm:ARGU("애니메이션","가속","") local scale = vm:ARGU("애니메이션","확대","") local action = nil for i=1,count,1 do local a = pini.Anim.Sequence( pini.Anim.MoveBy(sec/(2*count),0,width/2), pini.Anim.MoveBy(sec/(2*count),0,-width/2) ) if action then action = pini.Anim.Sequence(action,a) else action = a end end scale = scale:explode(",") action = pini.Anim.Spawn( pini.Anim.ScaleBy(sec,tonumber(scale[1]) or 1.0,tonumber(scale[2])or 1.0), action ) if fs_ease[ease] then action = fs_ease[ease](action) end if rep == "예" then --action = cc.RepeatForever:create(action) end action:run(node) end } fs_animation["스프라이트"] = { "스프라이트=\"이미지이름\" 시작=\"0\" 끝=\"5\" 프레임시간=\"0.1\" 반복=\"0\"", function(vm,node) local name = vm:ARGU("애니메이션","스프라이트","") local start = vm:ARGU("애니메이션","시작",1) local _end = vm:ARGU("애니메이션","끝",1) local sec = vm:ARGU("애니메이션","프레임시간",0.1) local loop = vm:ARGU("애니메이션","반복","0") if name:len() == 0 then return end start = tonumber(start) _end = tonumber(_end) loop = tonumber(loop) sec = tonumber(sec) local beforeTexName = node:getTextureName() local length = math.abs(start-_end) + 1 local isReverse = start > _end if loop == 0 then length = nil end pini.Timer(pini:GetUUID(),sec,function(t) local idx = t.userdata.idx local name = t.userdata.name local start = t.userdata.start local _end = t.userdata._end local isReverse = t.userdata.isReverse local node = pini:FindNode(t.userdata.nodeId) if node and node.onAnim == true and node:getTextureName() == t.userdata.beforeTexName then node:setSprite(name .. tostring(idx) .. ".png") if isReverse then idx = idx - 1 if idx < _end then idx = start end else idx = idx + 1 if idx > _end then idx = start end end t.userdata.idx = idx t.userdata.beforeTexName = node:getTextureName() else t:stop() end end,true,length,{ beforeTexName = beforeTexName, idx = start, name = name, isReverse = isReverse, start = start, _end = _end, nodeId = node.id, }):run() end } --[[ @애니메이션 아이디 : #1 이동 10 10 #2 크기 10 10 #0 멈춤 1 #0 멈춤 1 # ]]
----------------------------------- -- Area: Heavens Tower -- NPC: Celebratory Chest -- Type: Merchant NPC -- !pos -7.600 0.249 25.239 242 ----------------------------------- local ID = require("scripts/zones/Windurst_Walls/IDs") require("scripts/globals/shop") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) tpz.shop.celebratory(player) player:messageSpecial(ID.text.CELEBRATORY_GOODS) end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
local t = Def.ActorFrame {}; t[#t+1] = StandardDecorationFromFileOptional("Header","Header"); t[#t+1] = StandardDecorationFromFileOptional("Footer","Footer"); t[#t+1] = StandardDecorationFromFileOptional("StyleIcon","StyleIcon"); return t
local BasePlugin = require "kong.plugins.base_plugin" local URLRewriter = BasePlugin:extend() URLRewriter.PRIORITY = 700 function URLRewriter:new() URLRewriter.super.new(self, "url-rewriter") end function resolveUrlParams(requestParams, url) for paramValue in requestParams do local requestParamValue = ngx.ctx.router_matches.uri_captures[paramValue] -- local upstreamUrl = ngx.ctx.upstream_url -- ngx.log(ngx.NOTICE, ngx.ctx.router_matches.uri_captures) url = url:gsub("<" .. paramValue .. ">", requestParamValue) url = "test/" .. url end return url end function getRequestUrlParams(url) return string.gmatch(url, "<(.-)>") end function URLRewriter:access(config) URLRewriter.super.access(self) requestParams = getRequestUrlParams(config.url) --ngx.ctx.upstream_url = replaceHost(ngx.ctx.upstream_url, newHost) ngx.var.upstream_uri = resolveUrlParams(requestParams, config.url) ngx.print("-------- TESTING -------------") end return URLRewriter
-- Use Include 'prosody-posix-ldap.cfg.lua' from prosody.cfg.lua to include this file authentication = 'ldap2' -- Indicate that we want to use LDAP for authentication storage = 'ldap' -- Indicate that we want to use LDAP for roster/vcard storage ldap = { hostname = 'localhost', -- LDAP server location bind_dn = 'cn=Manager,dc=example,dc=com', -- Bind DN for LDAP authentication (optional if anonymous bind is supported) bind_password = 'prosody', -- Bind password (optional if anonymous bind is supported) user = { basedn = 'ou=Users,dc=example,dc=com', -- The base DN where user records can be found filter = '(&(objectClass=posixAccount)(!(uid=seven)))', -- Filter expression to find user records under basedn usernamefield = 'uid', -- The field that contains the user's ID (this will be the username portion of the JID) namefield = 'cn', -- The field that contains the user's full name (this will be the alias found in the roster) }, groups = { basedn = 'ou=Groups,dc=example,dc=com', -- The base DN where group records can be found memberfield = 'memberUid', -- The field that contains user ID records for this group (each member must have a corresponding entry under the user basedn with the same value in usernamefield) namefield = 'cn', -- The field that contains the group's name (used for matching groups in LDAP to group definitions below) { name = 'everyone', -- The group name that will be seen in users' rosters cn = 'Everyone', -- This field's key *must* match ldap.groups.namefield! It's the name of the LDAP group this definition represents admin = false, -- (Optional) A boolean flag that indicates whether members of this group should be considered administrators. }, { name = 'admin', cn = 'Admin', admin = true, }, }, vcard_format = { displayname = 'cn', -- Consult the vCard configuration section in the README nickname = 'uid', photo = { type = 'image/jpeg', binval = 'jpegPhoto', }, telephone = { work = { voice = true, number = 'telephoneNumber', }, }, }, }
function func(a) print(a) end
-- ----------------------------------------------------------------------------- -- Parse -- ----------------------------------------------------------------------------- describe('Pipe.parse', function() spec('ruleName', function() assert.are.equal('Pipe', parse.Expr('(1, 2) >> y()').ruleName) assert.are.equal('Pipe', parse.Expr('2 >> y()').ruleName) end) end) -- ----------------------------------------------------------------------------- -- Compile -- ----------------------------------------------------------------------------- describe('Pipe.compile', function() spec('expr pipes', function() assert.run( 6, compile.Block([[ function sum(a, b, c) { return a + b + c } return (1, 2, 3) >> sum() ]]) ) end) spec('param pipes', function() assert.run( 6, compile.Block([[ function sum(a, b, c) { return a + b + c } return (1, 2) >> sum(3) ]]) ) end) end)
Weapon.PrettyName = "SMG1" Weapon.WeaponID = "weapon_smg1" Weapon.DamageMultiplier = 1 Weapon.WeaponType = WEAPON_PRIMARY
require"lanesutils" local SCUDP = require"sc_comm_loop.scudp" local SCTCP = require"sc_comm_loop.sctcp" local SCFFI = require"sc_comm_loop.scinternal" local SCCOMMLOOP = {} local numsccomm = 0 function SCCOMMLOOP:init(types,options,linda) print"SCCOMMLOOP init" numsccomm = numsccomm + 1 assert(not self.inited) if types == "udp" then self.type = types self.sc = SCUDP self.sc:init(options,linda, numsccomm) self.inited = true elseif types == "internal" then if not jit then prerror("must run luajit for internal server"); return end self.type = types self.sc = SCFFI local res = self.sc:init(options,linda) self.inited = res if not res then self.sc = nil end elseif types == "tcp" then self.type = types self.sc = SCTCP local res = self.sc:init(options,linda, numsccomm) self.inited = res if not res then self.sc = nil end else error("server type "..types.." not implemented") end end function SCCOMMLOOP:close() if self.sc then self.sc:close() end self.sc = nil self.inited = nil end function SCCOMMLOOP:send(msg) if self.sc then self.sc:send(msg) end end function SCCOMMLOOP:status() self:send(toOSC({"/status",{1}})) end function SCCOMMLOOP:sync(id) self:send(toOSC({"/sync",{id or 1}})) end function SCCOMMLOOP:dumpOSC(doit) local val= doit and 1 or 0 self:send(toOSC({"/dumpOSC",{val}})) end function SCCOMMLOOP:dumpTree(withvalues) withvalues=withvalues or true local p= withvalues and 1 or 0 self:send(toOSC({"/g_dumpTree",{0,p}})) end function SCCOMMLOOP:quit() idlelinda:set("statusSC") --delete self:send(toOSC({"/quit",{}})) end return SCCOMMLOOP
--Kozmo-ダーク・ローズ Hero inferno function c93302689.initial_effect(c) --search local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(93302689,0)) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e1:SetCountLimit(1,93302689) e1:SetTarget(c93302689.thtg) e1:SetOperation(c93302689.thop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e2) --add setcode local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e4:SetCode(EFFECT_ADD_SETCODE) e4:SetValue(0x3008) c:RegisterEffect(e4) local e5=e4:Clone() e4:SetValue(0x08) c:RegisterEffect(e5) --become material local e02=Effect.CreateEffect(c) e02:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e02:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e02:SetCode(EVENT_BE_MATERIAL) e02:SetCondition(c93302689.condition) --e02:SetTarget(c20721930.target) e02:SetOperation(c93302689.operation) c:RegisterEffect(e02) end --material effect function c93302689.con(e) return not Duel.IsPlayerAffectedByEffect(e:GetHandlerPlayer(),69832741) end function c93302689.condition(e,tp,eg,ep,ev,re,r,rp) return ((r==REASON_FUSION) or (e:GetHandler():GetSummonType()==SUMMON_TYPE_SPECIAL)) end function c93302689.operation(e,tp,eg,ep,ev,re,r,rp) local rc=eg:GetFirst() while rc do if rc:GetFlagEffect(93302689)==0 then --to hand local e4=Effect.CreateEffect(e:GetHandler()) e4:SetDescription(aux.Stringid(20366274,1)) e4:SetCategory(CATEGORY_DESTROY) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e4:SetCode(EVENT_BATTLE_START) e4:SetCondition(c93302689.descon) e4:SetTarget(c93302689.destg) e4:SetOperation(c93302689.desop) rc:RegisterEffect(e4,true) rc:RegisterFlagEffect(93302689,RESET_EVENT+0x1fe0000,0,1) end rc=eg:GetNext() end end function c93302689.descon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local bc=c:GetBattleTarget() local mRn = Duel.GetFieldGroupCount(e:GetHandlerPlayer(),0,LOCATION_MZONE) local mEn = Duel.GetFieldGroupCount(e:GetHandlerPlayer(),LOCATION_MZONE,0) return bc and (mRn >= mEn)--and bc:GetSummonType()==SUMMON_TYPE_SPECIAL end function c93302689.destg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_DESTROY,e:GetHandler():GetBattleTarget(),1,0,0) end function c93302689.desop(e,tp,eg,ep,ev,re,r,rp) local bc=e:GetHandler():GetBattleTarget() if bc:IsRelateToBattle() then Duel.Destroy(bc,REASON_EFFECT) end end function c93302689.filter(c) return c:IsSetCard(0xa5) and c:IsType(TYPE_QUICKPLAY) and c:IsAbleToHand() end function c93302689.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c93302689.filter,tp,LOCATION_GRAVE,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_GRAVE) end function c93302689.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c93302689.filter,tp,LOCATION_GRAVE,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end
local M = {} local formatters_by_ft = {} local null_ls = require "null-ls" local services = require "lsp.null-ls.services" local Log = require "core.log" local function list_names(formatters, options) options = options or {} local filter = options.filter or "supported" return vim.tbl_keys(formatters[filter]) end function M.list_supported_names(filetype) if not formatters_by_ft[filetype] then return {} end return list_names(formatters_by_ft[filetype], { filter = "supported" }) end function M.list_unsupported_names(filetype) if not formatters_by_ft[filetype] then return {} end return list_names(formatters_by_ft[filetype], { filter = "unsupported" }) end function M.list_available(filetype) local formatters = {} for _, provider in pairs(null_ls.builtins.formatting) do -- TODO: Add support for wildcard filetypes if vim.tbl_contains(provider.filetypes or {}, filetype) then table.insert(formatters, provider.name) end end return formatters end function M.list_configured(formatter_configs) local formatters, errors = {}, {} for _, fmt_config in ipairs(formatter_configs) do local formatter = null_ls.builtins.formatting[fmt_config.exe] if not formatter then Log:error("Not a valid formatter: " .. fmt_config.exe) errors[fmt_config.exe] = {} -- Add data here when necessary else local formatter_cmd = services.find_command(formatter._opts.command) if not formatter_cmd then Log:warn("Not found: " .. formatter._opts.command) errors[fmt_config.exe] = {} -- Add data here when necessary else Log:debug("Using formatter: " .. formatter_cmd) formatters[fmt_config.exe] = formatter.with { command = formatter_cmd, extra_args = fmt_config.args } end end end return { supported = formatters, unsupported = errors } end function M.setup(filetype, options) if not lvim.lang[filetype] or (formatters_by_ft[filetype] and not options.force_reload) then return end formatters_by_ft[filetype] = M.list_configured(lvim.lang[filetype].formatters) null_ls.register { sources = formatters_by_ft[filetype].supported } end return M
local playsession = { {"amadey18", {550495}}, {"FailedSoul", {4781}}, {"kaimix", {302704}}, {"tykak", {81675}}, {"NerZurg", {1257}}, {"exabyte", {58391}}, {"iceskaarj", {549644}}, {"Order", {541083}}, {"Factorian12321", {419457}}, {"lintaba", {40929}}, {"cogito123", {26396}}, {"WiktorSPL", {4390}}, {"tyce1234", {362031}}, {"GarretShadow", {235423}}, {"gespenstdermaschine", {11374}}, {"McSafety", {113057}}, {"Tomy52499", {245943}}, {"MasjazZ", {205761}}, {"AurelienG", {286069}}, {"okan009", {308267}}, {"TiTaN", {290623}}, {"rixon316", {414}}, {"TXL_PLAYZ", {833}}, {"Silicon", {552}}, {"aniche", {128648}}, {"Creator_Zhang", {231317}}, {"Atoms", {200730}}, {"MovingMike", {139099}}, {"ronnaldy", {34111}}, {"mar123322", {103042}}, {"Tommy17", {10554}} } return playsession
--- -- C Display = {} --- funktionslos function Display.DbgDestroyAllOrnamentalItemsRegions() end --- funktionslos function Display.DbgDumpLoopCounters() end --- funktionslos function Display.DbgSetCalcVisibilityBits() end --- funktionslos function Display.DbgSetDepthBias32() end --- setzt model parameter, um licht und vertexcolor für die anzeige zu nutzen. -- für bewegliche entities wenig brauchbar, da die farbe beim weg und hinbewegen der kamera aktualisiert wird. function Display.DbgSetModelTerrainColorPortions(modelname, lightcolor, vertexcolor) end --- funktionslos function Display.DbgShadowMapGetLightBBox() end --- Gibt die Distanz zwischen der Kamera und _id zurück. function Display.GetDistanceToCamera(_id) end --- !!! democopy -- Kopiert die Nebelparameter. function Display.GfxSetCloneFogParams(_targetGFX, _sourceGFX) end --- !!! democopy -- Kopiert die Lichtparameter. function Display.GfxSetCloneLightParams(_targetGFX, _sourceGFX) end --- !!! democopy -- Kopiert die Regenparameter. function Display.GfxSetCloneRainEffectStatus(_targetGFX, _sourceGFX) end --- !!! democopy -- Kopiert die SkyBox. function Display.GfxSetCloneSkyBox(_targetGFX, _sourceGFX) end --- !!! democopy -- Kopiert den Schneeuntergrundparameter. function Display.GfxSetCloneSnowEffectStatus(_targetGFX, _sourceGFX) end --- !!! democopy -- Kopiert die Schneeeparameter. function Display.GfxSetCloneSnowStatus(_targetGFX, _sourceGFX) end --- Setzt die Nebelparameter. -- _transS,_transE: Zeitpunkt für Änderung: 0.0-1.0 -- _flag: Nebel an? -- _r,_g,_b: Nebelfarbe -- _fogS,_fogE: Entfernung des Nebels (normal irgendwas bei 2000-30000) function Display.GfxSetSetFogParams(_gfx, _transS, _transE, _flag, _r, _g, _b, _fogS, _fogE) end --- Setzt die Lichtparameter. -- _transS,_transE: Zeitpunkt für Änderung: 0.0-1.0 -- _posX,_posY,_posZ: Position der Lichtquelle (Sonne) -- _lanR,_lanG,_lanB: Überall gleiche Beleuchtung (Ambient/Umgebung) -- _sunR,_sunG,_sunB: Licht der Sonne (Diffuse) function Display.GfxSetSetLightParams(_gfx, _transS, _transE, _posX, _posY, _posZ, _lanR, _lanG, _lanB, _sunR, _sunG, _sunB) end --- Setzt die Regenparameter. -- _transS,_transE: Zeitpunkt für Änderung: 0.0-1.0 function Display.GfxSetSetRainEffectStatus(_gfx, _transS, _transE, _flag) end --- Setzt die SkyBox (Himmel) (Nur in Cutscenes und Briefing sichtbar). -- _transS,_transE: Zeitpunkt für Änderung: 0.0-1.0 -- _skyBox: "YSkyBox0"...{1-7} Empfehlung: 1->Schnee,4->Regen,rest->Normal function Display.GfxSetSetSkyBox(_gfx, _transS, _transE, _skyBox) end --- Setzt die Schneebodenefektparameter. -- _transS,_transE: Zeitpunkt für Änderung: 0.0-1.0 function Display.GfxSetSetSnowEffectStatus(_gfx, _transS, _transE, _flag) end --- Setzt die Schneeparameter (Niederschlag). -- _transS,_transE: Zeitpunkt für Änderung: 0.0-1.0 function Display.GfxSetSetSnowStatus(_gfx, _transS, _transE, _flag) end --- Stellt die Ursprünglichen Spielerfarben wieder her. function Display.InitializePlayerColors() end --- Lädt alle Modelle (neu). function Display.LoadAllModels() end --- Shared Bool z.B. g_UseShadowMap (siehe effects fx Dateien) aber wirkungslos? function Display.ModifySharedBoolEffectParameterByName(_name, _value) end --- Lädt die Terraintexturen neu. function Display.ReloadAllTerrainTextures() end --- !!! democopy -- Lädt einen Grafikeffekt neu. function Display.ReloadEffect(_eff) end --- ??? function Display.SetDaylightFP() end --- Setzt verschiedene Anzeigeoptionen: -- _opt: string -- DoodadsNoMovement -- Snow -- NoPixelShader (! eventuell nicht rückgängig) -- RenderIceReflections -- UseShadowMapPlanar -- OrnamentalItemsNoMovement -- ShadowMapATI -- _flag: 1/0/-1 (toggle) function Display.SetEffectOption(_opt, _flag) end --- Setzt die minimale und maximale Sichtweite (alles was weiter weg ist, ist schwarz) -- 0,0 stellt die Default Werte wieder her function Display.SetFarClipPlaneMinAndMax(_min, _max) end --- funktionslos function Display.SetFogColor() end --- funktionslos function Display.SetFogStartAndEnd() end --- Ändert die Helligkeit/Kontrast. -- _brightness,_contrast,_gamma: Relativ zu 1 (also 1.xxx) function Display.SetGammaRamp(_brightness, _contrast, _gamma, _flag) end --- funktionslos function Display.SetGlobalLightAmbient() end --- funktionslos function Display.SetGlobalLightDiffuse() end --- funktionslos function Display.SetGlobalLightDirection() end --- Setzt den Eisstatus (0.0-1.0). -- (Wenn Display.SetIceStatusIsCalculateFromSnowStatus aus ist) function Display.SetIceStatus(_status) end --- !!! democopy -- Setzt die Berechnungswerte für den Eisstatus: iceS = _fac*snowS+_off function Display.SetIceStatusCalculationCoefficients(_fac, _off) end --- Setzt, ob das Eis Automatisch oder Manuell verändert wird. -- _flag 1/0 function Display.SetIceStatusIsCalculateFromSnowStatus(_flag) end --- Setzt die Spielerfarbe. (Normal _playerId==_playerColor) function Display.SetPlayerColorMapping(_playerId, _playerColor) end --- Setzt, ob Eis Refklektionen angezeigt werden sollen (Grafikoption) -- _flag 1/0 bzw. -1 für Toggle function Display.SetProgramOptionRenderIceReflections(_flag) end --- Setzt, ob Okklusion angezeigt werden soll (Grafikoption) -- _flag 1/0 bzw. -1 für Toggle function Display.SetProgramOptionRenderOcclusionEffect() end --- Setzt, ob Schatten angezeigt werden sollen (Grafikoption) -- _flag 1/0 bzw. -1 für Toggle function Display.SetProgramOptionRenderShadows() end --- Aktiviert bzw. deaktivert das Anzeigen von Decals (dazu zählen DecalsAtomics; DecalsDoodads; DecalsSelections und DecalsShadows) -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderDecals(_flag) end --- Zeigt den Untergrund von Gebäuden an. -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderDecalsAtomics(_flag) end --- Aktiviert bzw. deaktivert das Anzeigen von DecalsDoodads (alle XD_PlantDecals) -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderDecalsDoodads(_flag) end --- Aktiviert bzw. deaktivert das Anzeigen der blauben Selektionskreise -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderDecalsSelections(_flag) end --- Aktiviert bzw. deaktivert das Anzeigen von Schatten -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderDecalsShadows(_flag) end --- Aktiviert bzw. deaktivert das Anzeigen von Effekten; bei Deaktivieren wird nur das Model gesetzt, aber der Effekt bleibt statisch -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderEffects(_flag) end --- funktionslos? function Display.SetRenderFog() end --- Aktiviert bzw. deaktivert das Anzeigen des Fog Of Wars (gesamte Map wird aufgedeckt) -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderFogOfWar(_flag) end --- Zeigt Unsichtbare Objekte an (XD_ScriptEntity) -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderInvisibleObjects(_flag) end --- Aktiviert bzw. deaktivert das Anzeigen der gesamten Texturen (sonst alles schwarz) -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderLandscape(_flag) end --- Aktiviert bzw. deaktivert das Anzeigen der Landscape Debug Info (weiße Punkte auf der Map = blocking; grün = begehbares Blocking; ansonsten kein Blocking) -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderLandscapeDebugInfo(_flag) end --- Aktiviert bzw. deaktivert das Anzeigen des Fog Of Wars (gesamte Map wird aufgedeckt) -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderLandscapeFogOfWar(_flag) end --- Texturen anzeigen -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderLandscapeTerrain(_flag) end --- stückweise texturen anzeigen -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderLandscapeTerrainLayers1(_flag) end --- stückweise texturen anzeigen -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderLandscapeTerrainLayers2(_flag) end --- stückweise texturen anzeigen -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderLandscapeTerrainLayers3(_flag) end --- Aktiviert bzw. deaktivert das Anzeigen von Wasser -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderLandscapeWater(_flag) end --- Aktiviert oder deaktiviert das Anzeigen von Models -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderObjects(_flag) end --- Aktiviert oder deaktiviert das Anzeigen von allen Models welche Alpha Blending unterstützen (siehe Models.xml) -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderObjectsAlphaBlendPass(_flag) end --- Verändert die Bäume? -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderObjectsAlphaTestPass(_flag) end --- Aktiviert oder deaktiviert das Anzeigen von allen Models welche Alpha Blending nicht unterstützen (siehe Models.xml) -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderObjectsNonAlpha(_flag) end --- Aktiviert oder deaktiviert das Anzeigen von Partikeleffekten bei allen Models (z.B. Rauch aus Gebäuden; Feuereffekte; Gischt bei Wasserfällen) -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderParticles(_flag) end --- Aktiviert oder deaktiviert das Anzeigen von Schatten -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderShadows(_flag) end --- Aktiviert oder deaktiviert das Anzeigen des Siedlerhimmels (wichtig bei Briefings und Cutscenes) -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderSky(_flag) end --- Aktiviert oder deaktiviert das Anzeigen der Texturen -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderTerrain(_flag) end --- Aktiviert oder deaktiviert das Anzeigen des yCommandAcks Models bei gegebenen Laufbefehlen -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderUpdateMorphAnim(_flag) end --- Aktiviert oder deaktiviert das Updaten von Partikeleffekten -- (bei Deaktivieren frieren diese Effekte ein bzw. verschwinden, wenn die Kamera nicht darauf gerichtet ist) -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderUpdateParticles(_flag) end --- Aktiviert oder deaktiviert die GFX-Sets. -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderUseGfxSets(_flag) end --- ändert die Rotation von Ornamtental Items Models (siehe Models.xml) -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderUseOrnamentalItemsSystem(_flag) end --- Aktiviert bzw. deaktivert das Anzeigen von Wasser -- _flag 1/0 bzw. -1 für Toggle function Display.SetRenderWater(_flag) end --- Setzt die Z-Position der SkyBox function Display.SetSkyBoxZOffset(_z) end --- funktionslos; besser Display.GfxSetSetSnowEffectStatus function Display.SetSnowStatus() end --- funktionslos (leider) function Display.SetSnowStatusVelocity() end --- Aktiviert oder deaktiviert das Anzeigen der Okklusion (Siedler werden in Spielerfarbe hinter Gebäuden angezeigt) -- _flag 1/0 bzw. -1 für Toggle function Display.SetUserOptionRenderOcclusionEffect(_flag) end --- Aktiviert oder deaktiviert das Anzeigen von Schatten -- _flag 1/0 bzw. -1 für Toggle function Display.SetUserOptionRenderShadowMapSize(_flag) end --- Schaltet zwischen hoher und niedriger Terrainqualität um -- _flag 1/0 bzw. -1 für Toggle function Display.SetUserOptionRenderTerrainQuality(_flag) end --- Aktiviert oder deaktiviert das Anzeigen von Schatten -- _flag 1/0 bzw. -1 für Toggle function Display.ShadowsSetMethod(_flag) end --- ??? interne Funktion; gesetzter Wert wird vermutlich sofort wieder überschrieben -> funktionslos function Display.SynchronizerSetNumberOfFrames(_number) end
local playsession = { {"MatoPlayz", {26897}}, {"cawsey21", {6931}}, {"okan009", {686}}, {"itinker", {16915}}, {"sirvorlon", {3826}}, {"boogi310", {1515}}, {"DuaneOli4", {6881}}, {"Menander", {1441801}}, {"Kissthisangel", {243521}}, {"busterwoods", {1329575}}, {"bobeyzilla", {939208}}, {"illiander42", {848300}}, {"Cowlord", {12032}}, {"POWXJASON", {4285}}, {"Hoob", {256493}}, {"tkrauze", {62928}}, {"saneman", {3489}}, {"mr__meeseeks", {4327}}, {"Poo76765", {1055780}}, {"kyethebuilder", {23790}}, {"piescorch", {600195}}, {"LLopes", {29206}}, {"hasannuh", {1880}}, {"ronnaldy", {8707}}, {"poatao", {35711}}, {"Hitman451", {387516}}, {"Factorian12321", {283293}} } return playsession
function post() if session:isLogged() then http:redirect("/") return end if app.Captcha.Enabled then if not captcha:verify(http.postValues["g-recaptcha-response"]) then session:setFlash("validationError", "Invalid captcha answer") http:redirect("/subtopic/register") return end end if db:singleQuery("SELECT name FROM accounts WHERE email = ?", http.postValues.email) ~= nil then session:setFlash("validationError", "Email already in use by another user") http:redirect("/subtopic/register") return end if db:singleQuery("SELECT name FROM accounts WHERE name = ?", http.postValues["account-name"]) ~= nil then session:setFlash("validationError", "Account name already in use by another user") http:redirect("/subtopic/register") return end if not validator:validate("IsEmail", http.postValues.email) then session:setFlash("validationError", "Invalid email format") http:redirect("/subtopic/register") return end if not validator:validate("IsAlphanumeric", http.postValues["account-name"]) or validator:validate("IsNull", http.postValues["account-name"]) then session:setFlash("validationError", "Invalid account name format. Only letters (A-Z) and numbers (0-9) allowed") http:redirect("/subtopic/register") return end if string.len(http.postValues["account-name"]) > 16 or string.len(http.postValues["account-name"]) < 4 then session:setFlash("validationError", "Invalid account name length. Account name must be 4 - 16 characters long") http:redirect("/subtopic/register") return end if string.len(http.postValues["password"]) > 32 or string.len(http.postValues["password"]) < 8 then session:setFlash("validationError", "Invalid password length. Password must be 8 - 32 characters long") http:redirect("/subtopic/register") return end local id = db:execute( "INSERT INTO accounts (name, password, premdays, email, creation) VALUES (?, ?, ?, ?, ?)", http.postValues["account-name"], crypto:sha1(http.postValues["password"]), 10, http.postValues["email"], os.time() ) db:execute("INSERT INTO castro_accounts (account_id) VALUES (?)", id) session:setFlash("success", "Account created. You can now sign in") http:redirect("/subtopic/login") end
-- Tab for weapons-related interaction. local WeaponCheatsTab = {} local Logger = require("utility/logger") local Widget = require("utility/widget") local Style = require("ui/style") local Layout = require("ui/layout") local State = require("ui/state") local Glossary = require("data/glossary") local ItemHandler = require("handler/item") local EquipmentHandler = require("handler/equipment") function WeaponCheatsTab:SetState(element, value, ltype) local set = value if not set then element.Value = element.Default else element.Value = Widget.ParseRawIntoView(set, ltype) end -- Set current value and "last read" property. element.Read = element.Value end function WeaponCheatsTab:SetModifier(element, modtype, ltype) if not Widget.CheckValue(element, ltype) then return end local itemdata = self.state.ItemData local calctype = Glossary.Calculation.Additive local value = Widget.ParseViewIntoRaw(element.Value, ltype) self.handler.item:SetModifier(itemdata, modtype, calctype, value) -- Set "last read" value to match newly-updated value. element.Read = element.Value end function WeaponCheatsTab:AddModifier(element, modtype, ltype) if not Widget.CheckValue(element, ltype) then return end local itemdata = self.state.ItemData local calctype = Glossary.Calculation.Additive local delta = element.Value - element.Read local value = Widget.ParseViewIntoRaw(delta, ltype) self.handler.item:AddModifier(itemdata, modtype, calctype, value) -- Set "last read" value to match newly-updated value. element.Read = element.Value end function WeaponCheatsTab:DoModifier(layout) local Callable = self.SetModifier if layout.Method == "Add" then Callable = self.AddModifier end Callable(self, self.state[layout.Name], Glossary.Stats[layout.Name], layout.Type) if layout.Copy then self.state[layout.Copy].Value = self.state[layout.Name].Value Callable(self, self.state[layout.Copy], Glossary.Stats[layout.Copy], layout.Type) end end function WeaponCheatsTab:DoModifiers() if not self.state.ItemData then return end for _, section in ipairs(Layout.WeaponsTab.Sections) do for _, column in ipairs(section) do for _, layout in ipairs(column) do if layout.Type ~= "Skip" then self:DoModifier(layout) end end end end end function WeaponCheatsTab:Inspect() local slot = "Weapon" local id = self.state.SlotSelect local stats = {} self.logger:Info("InspectWeapon: " .. slot .. id + 1) self.state.ItemData = self.handler.equipment:GetItemDataInSlot(slot, id) if self.state.ItemData then stats = self.handler.item:Inspect(self.state.ItemData) end for _, section in ipairs(Layout.WeaponsTab.Sections) do for _, column in ipairs(section) do for _, layout in ipairs(column) do -- Disgusting nested for loops. if layout.Type ~= "Skip" then self:SetState(self.state[layout.Name], stats[Glossary.Stats[layout.Name]], layout.Type) if layout.Copy then self:SetState(self.state[layout.Copy], stats[Glossary.Stats[layout.Copy]], layout.Type) end end end end end end function WeaponCheatsTab:BuildDisplay() Widget.Spacing() Widget.Text("Modify weapons in your equip slots:") Widget.Text(" - Pick and edit properties from power, tech or smart weapons.") Widget.Spacing() end function WeaponCheatsTab:BuildSelect() Widget.Separator() Widget.Spacing() Widget.Text("1. Select Slot") Widget.Text(" - Choose slot then load item values.") self.state.SlotSelect = Widget.Combo("##WeaponSlot", self.state.SlotSelect, self.state.SlotOptions, nil, Style.Size.WeaponsTab.Text.Width) Widget.SameLine(Style.Size.WeaponsTab.Text.Width + Style.Size.SmallColSpacer) if (Widget.Button("Load")) then self:Inspect() end Widget.Spacing() end function WeaponCheatsTab:BuildModifierFromLayout(elem, maxcol) if not elem.Type then return end if elem.Type == "Float" then self.state[elem.Name].Value = Widget.InputFloat( elem.Display, self.state[elem.Name].Value, 1, 100, "%.4f", Style.Size.WeaponsTab.Float[maxcol].Width, self.state[elem.Name].Value ~= self.state[elem.Name].Read ) elseif elem.Type == "Boolean" then self.state[elem.Name].Value = Widget.Checkbox( elem.Display, self.state[elem.Name].Value, self.state[elem.Name].Value ~= self.state[elem.Name].Read ) else Widget.Dummy(1, 19) end end function WeaponCheatsTab:BuildBasicModifiers() local ncols = 2 Widget.Separator() Widget.Spacing() Widget.Text("2. Basic Modifiers") Widget.Text(" - Set weapon flags.") Widget.Text(" - Edit generic weapon attributes or values.") Widget.Columns(ncols) for col = 1, ncols do Widget.BeginGroup() for _, element in ipairs(Layout.WeaponsTab.Basic[col]) do self:BuildModifierFromLayout(element, ncols) end Widget.EndGroup() Widget.NextColumn() end Widget.Columns(1) Widget.Spacing() end function WeaponCheatsTab:BuildComplexModifiers() local ncols = 3 Widget.Separator() Widget.Spacing() Widget.Text("3. Advanced Modifiers") Widget.Text(" - Mix and match archetypical mods.") Widget.Columns(ncols) for col = 1, ncols do Widget.BeginGroup() for _, element in ipairs(Layout.WeaponsTab.Advanced[col]) do self:BuildModifierFromLayout(element, ncols) end Widget.EndGroup() Widget.NextColumn() end Widget.Columns(1) Widget.Spacing() end function WeaponCheatsTab:BuildDoModifiers() Widget.Separator() Widget.Spacing() if (Widget.Button("Save Modifiers", Style.Size.WeaponsTab.Button.Width, Style.Size.WeaponsTab.Button.Height)) then self:DoModifiers() end Widget.Spacing() end function WeaponCheatsTab:Build() if (Widget.BeginTabItem("Weapon")) then self:BuildDisplay() self:BuildSelect() self:BuildBasicModifiers() self:BuildComplexModifiers() self:BuildDoModifiers() Widget.Separator() Widget.EndTabItem() end end function WeaponCheatsTab:New() local I = {} setmetatable(I, self) self.__index = self I.module = "WeaponCheats" I.logger = Logger:New(I.module) I.state = State.WeaponsTab I.handler = { item = ItemHandler:New(), equipment = EquipmentHandler:New() } return I end return WeaponCheatsTab
json = require "json" utils = require "utils" -- Insert json folder path here, required for getTrackInfo local jsonPath = "./plugins" -- default should be correct if countryCodes.json is inside plugins folder local contentPath = "./assetto/content" -- depends on assetto server location -- these are lua hooks related to the manager itself, for help please view lua_readme.md! -- there are some example functions here to give you an idea of what is possible, feel free to write your own! -- if you do and think other people would be interested in them consider making a pull request at https://github.com/JustaPenguin/assetto-server-manager -- called when any event (including championships/race weekends) is started (for championships this is called AFTER onChampionshipEventStart) function onEventStart(encodedRaceConfig, encodedServerOpts, encodedEntryList) -- Decode block, you probably shouldn't touch these! local raceConfig = json.decode(encodedRaceConfig) local serverOpts = json.decode(encodedServerOpts) local entryList = json.decode(encodedEntryList) -- Uncomment these lines and run the function (start any event) to print out the structure of each object. --print("Race Config:", utils.dump(raceConfig)) --print("Server Options:", utils.dump(serverOpts)) --print("Entry List:", utils.dump(entryList)) -- Function block NOTE: this hook BLOCKS, make sure your functions don't loop forever! -- Uncomment this line to set Weather API On -- in order to use the weatherAPI you need to get a free API key from https://openweathermap.org/ raceConfig, serverOpts = getWeatherForTrack(raceConfig, serverOpts, "get-an-api-key-from-https://openweathermap.org/") -- Encode block, you probably shouldn't touch these either! return json.encode(entryList), json.encode(serverOpts), json.encode(raceConfig) end -- called when any NON CHAMPIONSHIP/RACE WEEKEND event is scheduled function onEventSchedule(encodedRace) -- Decode block, you probably shouldn't touch these! local race = json.decode(encodedRace) -- Uncomment these lines and run the function (start any event) to print out the structure of each object. --print("Race:", utils.dump(race)) -- Function block NOTE: this hook BLOCKS, make sure your functions don't loop forever! -- Encode block, you probably shouldn't touch these either! return json.encode(race) end -- called when any RACE WEEKEND event is scheduled function onRaceWeekendEventSchedule(encodedRaceWeekendSession, encodedRaceWeekend) -- Decode block, you probably shouldn't touch these! local session = json.decode(encodedRaceWeekendSession) local raceWeekend = json.decode(encodedRaceWeekend) -- Uncomment these lines and run the function (start any event) to print out the structure of each object. --print("Race Weekend Session:", utils.dump(session)) --print("Race Weekend:", utils.dump(raceWeekend)) -- Function block NOTE: this hook BLOCKS, make sure your functions don't loop forever! -- Encode block, you probably shouldn't touch these either! return json.encode(raceWeekend), json.encode(session) end function getWeatherForTrack(raceConfig, serverOpts, apiKey) if apiKey == "get-an-api-key-from-https://openweathermap.org/" then print("events.lua: No API key is set, could not activate weather API") return raceConfig, serverOpts end -- Getting location from track_ui.json, make sure to set jsonPath and contentPath location = getTrackInfo(raceConfig) -- if you want to manually set the location for tracks without location info uncomment this line and set the location, you can download a city list here: http://bulk.openweathermap.org/sample/ -- location = "Manchester,uk" if location == nil then --Set location manually if no trackinfo is found location = "Manchester,UK" end return weatherAPI(raceConfig, serverOpts, apiKey) end -- get track location from his ui.json file, set dynamic weather on if a location is found -- if not, use weather in custom race config function getTrackInfo(raceConfig) local track = raceConfig["Track"] local layout = raceConfig["TrackLayout"] local trackPath = contentPath .. "/tracks/" .. track .. "/ui/" .. layout local encodedTrackJson = utils.jsonOpen(trackPath, "ui_track.json") local trackJson success = pcall(function() trackJson = json.decode(encodedTrackJson) end) if not success then print("events.lua: Couldn't decode track UI file: ", trackPath .. "/ui_track.json. Falling back to manual setting") return nil end countryFull = trackJson["country"] city = trackJson["city"] local encodedCountryCodes = utils.jsonOpen(jsonPath, "countryCodes.json") local countryCodes = json.decode(encodedCountryCodes) if city == nil or countryFull == nil then print("events.lua: No country/city found in track UI file, falling back to manual setting") return nil end if countryCodes[countryFull] == nil then print("events.lua: Location was found in track UI file (" .. city .. ", " .. countryFull .. "). But was not found in countryCodes.json, please update! Falling back to manual setting") return nil end location = city .. "," .. countryCodes[countryFull] return location end -- weather API function weatherAPI(raceConfig, serverOpts, apiKey) -- set the weather based on the current weather at 'location' local body, status = httpRequest("http://api.openweathermap.org/data/2.5/weather?q=" .. location .. "&APPID=" .. apiKey, "GET", "") -- If location not found in openWeatherMap, stop the function and use weather configured in web manager if status >= 400 then print("events.lua: Weather API HTTP request returned status ", status, ". Weather API deactivated") return raceConfig, serverOpts end local weatherData = json.decode(body) -- wind speed, from m/s to km/h raceConfig["WindBaseSpeedMin"] = math.floor(weatherData["wind"]["speed"] * 3.6) raceConfig["WindBaseSpeedMax"] = raceConfig["WindBaseSpeedMin"] + 2 -- wind angle raceConfig["WindBaseDirection"] = weatherData["wind"]["deg"] raceConfig["WindVariationDirection"] = 5 -- there should only be one weather, but we'll apply to all just in case for name, weather in pairs(raceConfig["Weather"]) do -- ambient temp, from Kelvin to Degrees Celcius weather["BaseTemperatureAmbient"] = math.floor(weatherData["main"]["temp"] - 273) weather["VariationAmbient"] = 0 -- road temp if weatherData["dt"] > weatherData["sys"]["sunrise"] and weatherData["dt"] < weatherData["sys"]["sunset"] then -- the sun is up, base road temp should be a bit higher than ambient weather["BaseTemperatureRoad"] = 4 else -- sun is down, base road temp is lower than ambient (large assumption, definitely wrong, please improve!) weather["BaseTemperatureRoad"] = 0 end weather["VariationRoad"] = 1 -- weather codes can be found here: https://openweathermap.org/weather-conditions local w = weatherData["weather"][1]["id"] if raceConfig["IsSol"] == 1 then -- with sol (recommended) -- set time of day weather["CMWFUseCustomTime"] = 1 weather["CMWFXTime"] = 0 weather["CMWFXUseCustomDate"] = 1 weather["CMWFXDateUnModified"] = weatherData["dt"] weather["CMWFXDate"] = weatherData["dt"] - (3600 * 5 * weather["CMWFXTimeMulti"]) -- don't ask -- force time 5 hour before sunset (18000) to prevent night --weather["CMWFXDate"] = (weatherData["sys"]["sunset"] - 18000) + (weatherData["timezone"]) - (3600 * 5 * weather["CMWFXTimeMulti"]) -- don't ask -- set graphics (comment this and uncomment the block bellow for no rain) if w == 800 then weather["CMGraphics"] = "sol_01_CLear"; weather["CMWFXType"] = 15; elseif w == 801 then weather["CMGraphics"] = "sol_02_Few Clouds"; weather["CMWFXType"] = 16 elseif w == 802 then weather["CMGraphics"] = "sol_03_Scattered Clouds"; weather["CMWFXType"] = 17 --Do not uncomment elseif w == then weather["CMGraphics"] = "sol_04_Windy"; weather["CMWFXType"] = 31 --no real weather for windy elseif w == 803 then weather["CMGraphics"] = "sol_05_Broken Clouds"; weather["CMWFXType"] = 18 elseif w == 804 then weather["CMGraphics"] = "sol_06_Overcast"; weather["CMWFXType"] = 19 elseif w == 701 then weather["CMGraphics"] = "sol_11_Mist"; weather["CMWFXType"] = 21 elseif w == 741 then weather["CMGraphics"] = "sol_12_Fog"; weather["CMWFXType"] = 20 elseif w == 721 then weather["CMGraphics"] = "sol_21_Haze"; weather["CMWFXType"] = 23 elseif w == 731 then weather["CMGraphics"] = "sol_22_Dust"; weather["CMWFXType"] = 25 elseif w == 751 then weather["CMGraphics"] = "sol_23_Sand"; weather["CMWFXType"] = 24 elseif w == 711 then weather["CMGraphics"] = "sol_24_Smoke"; weather["CMWFXType"] = 22 elseif w == 300 then weather["CMGraphics"] = "sol_31_Light Drizzle"; weather["CMWFXType"] = 3 elseif w == 301 then weather["CMGraphics"] = "sol_32_Drizzle"; weather["CMWFXType"] = 4 elseif w >= 302 and w <= 321 then weather["CMGraphics"] = "sol_33_Heavy Drizzle"; weather["CMWFXType"] = 5 elseif w == 500 then weather["CMGraphics"] = "sol_34_Light Rain"; weather["CMWFXType"] = 6 elseif w == 501 then weather["CMGraphics"] = "sol_35_Rain"; weather["CMWFXType"] = 7 elseif w >= 502 and w <= 531 then weather["CMGraphics"] = "sol_36_Heavy Rain"; weather["CMWFXType"] = 8 elseif w == 200 or w == 210 or w == 230 then weather["CMGraphics"] = "sol_41_Light Thunderstorm"; weather["CMWFXType"] = 0 elseif w == 201 or w == 211 or w == 231 then weather["CMGraphics"] = "sol_42_Thunderstorm"; weather["CMWFXType"] = 1 elseif w == 202 or w == 212 or w == 221 or w == 232 then weather["CMGraphics"] = "sol_43_Heavy Thunderstorm"; weather["CMWFXType"] = 2 elseif w == 771 then weather["CMGraphics"] = "sol_44_Squalls"; weather["CMWFXType"] = 26 elseif w == 781 then weather["CMGraphics"] = "sol_45_Tornado"; weather["CMWFXType"] = 27 --Do not uncomment elseif w == then weather["CMGraphics"] = "sol_46_Hurricane"; weather["CMWFXType"] = 28 --no real weather for hurricane elseif w == 600 or w == 620 then weather["CMGraphics"] = "sol_51_Light Snow"; weather["CMWFXType"] = 9 elseif w == 601 or w == 621 then weather["CMGraphics"] = "sol_52_Snow"; weather["CMWFXType"] = 10 elseif w == 602 or w == 622 then weather["CMGraphics"] = "sol_53_Heavy Snow"; weather["CMWFXType"] = 11 elseif w == 611 or w == 615 then weather["CMGraphics"] = "sol_54_Light Sleet"; weather["CMWFXType"] = 12 elseif w == 612 or w == 616 then weather["CMGraphics"] = "sol_55_Sleet"; weather["CMWFXType"] = 13 elseif w == 613 then weather["CMGraphics"] = "sol_56_Heavy Sleet"; weather["CMWFXType"] = 14 --Do not uncomment elseif w == then weather["CMGraphics"] = "sol_57_Hail"; weather["CMWFXType"] = 32 --no real weather for hail end -- set graphics no rain (comment the block above and uncomment this one for no rain) --if w == 800 then weather["CMGraphics"] = "sol_01_CLear"; weather["CMWFXType"] = 15; --elseif w == 801 then weather["CMGraphics"] = "sol_02_Few Clouds"; weather["CMWFXType"] = 16 --elseif w == 802 then weather["CMGraphics"] = "sol_03_Scattered Clouds"; weather["CMWFXType"] = 17 --Do not uncomment elseif w == then weather["CMGraphics"] = "sol_04_Windy"; weather["CMWFXType"] = 31 --no real weather for windy --elseif w == 803 then weather["CMGraphics"] = "sol_05_Broken Clouds"; weather["CMWFXType"] = 18 --elseif w == 804 then weather["CMGraphics"] = "sol_06_Overcast"; weather["CMWFXType"] = 19 --elseif w == 701 then weather["CMGraphics"] = "sol_11_Mist"; weather["CMWFXType"] = 21 --elseif w == 741 then weather["CMGraphics"] = "sol_12_Fog"; weather["CMWFXType"] = 20 --elseif w == 721 then weather["CMGraphics"] = "sol_21_Haze"; weather["CMWFXType"] = 23 --elseif w == 731 then weather["CMGraphics"] = "sol_22_Dust"; weather["CMWFXType"] = 25 --elseif w == 751 then weather["CMGraphics"] = "sol_23_Sand"; weather["CMWFXType"] = 24 --elseif w == 711 then weather["CMGraphics"] = "sol_24_Smoke"; weather["CMWFXType"] = 22 --elseif w == 300 then weather["CMGraphics"] = "sol_05_Broken Clouds"; weather["CMWFXType"] = 18 --elseif w == 301 then weather["CMGraphics"] = "sol_06_Overcast"; weather["CMWFXType"] = 19 --elseif w >= 302 and w <= 321 then weather["CMGraphics"] = "sol_24_Smoke"; weather["CMWFXType"] = 22 --elseif w == 500 then weather["CMGraphics"] = "sol_05_Broken Clouds"; weather["CMWFXType"] = 18 --elseif w == 501 then weather["CMGraphics"] = "sol_06_Overcast"; weather["CMWFXType"] = 19 --elseif w >= 502 and w <= 531 then weather["CMGraphics"] = "sol_24_Smoke"; weather["CMWFXType"] = 22 --elseif w == 200 or w == 210 or w == 230 then weather["CMGraphics"] = "sol_06_Overcast"; weather["CMWFXType"] = 19 --elseif w == 201 or w == 211 or w == 231 then weather["CMGraphics"] = "sol_24_Smoke"; weather["CMWFXType"] = 22 --elseif w == 202 or w == 212 or w == 221 or w == 232 then weather["CMGraphics"] = "sol_24_Smoke"; weather["CMWFXType"] = 22 --elseif w == 771 then weather["CMGraphics"] = "sol_44_Squalls"; weather["CMWFXType"] = 26 --elseif w == 781 then weather["CMGraphics"] = "sol_24_Smoke"; weather["CMWFXType"] = 22 --Do not uncomment elseif w == then weather["CMGraphics"] = "sol_46_Hurricane"; weather["CMWFXType"] = 28 --no real weather for hurricane --elseif w == 600 or w == 620 then weather["CMGraphics"] = "sol_05_Broken Clouds"; weather["CMWFXType"] = 18 --elseif w == 601 or w == 621 then weather["CMGraphics"] = "sol_12_Fog"; weather["CMWFXType"] = 20 --elseif w == 602 or w == 622 then weather["CMGraphics"] = "sol_24_Smoke"; weather["CMWFXType"] = 22 --elseif w == 611 or w == 615 then weather["CMGraphics"] = "sol_05_Broken Clouds"; weather["CMWFXType"] = 18 --elseif w == 612 or w == 616 then weather["CMGraphics"] = "sol_12_Fog"; weather["CMWFXType"] = 20 --elseif w == 613 then weather["CMGraphics"] = "sol_06_Overcast"; weather["CMWFXType"] = 19 --Do not uncomment elseif w == then weather["CMGraphics"] = "sol_57_Hail"; weather["CMWFXType"] = 32 --no real weather for hail --end weather["Graphics"] = weather["CMGraphics"] .. "_type=" .. weather["CMWFXType"] .. "_time=0_mult=" .. weather["CMWFXTimeMulti"] .. "_start=" .. weather["CMWFXDate"] else -- without Sol (not recommended) -- you could set sun angle from time of day here, I'm not going to though (just use Sol) -- set graphics if w == 800 then weather["Graphics"] = "3_clear" elseif w == 801 then weather["Graphics"] = "4_mid_clear" elseif w == 802 then weather["Graphics"] = "5_light_clouds" elseif w == 803 then weather["Graphics"] = "6_mid_clouds" elseif w == 804 then weather["Graphics"] = "7_heavy_clouds" elseif w == 741 then weather["Graphics"] = "2_light_fog" end end end -- Add text to server name to indicate this has been done serverOpts["Name"] = serverOpts["Name"] .. " | Weather Live From " .. weatherData["name"] return raceConfig, serverOpts end --{ Response json from openweathermap looks like this -- "coord": { -- "lon": -0.13, -- "lat": 51.51 -- }, -- "weather": [{ -- "id": 803, -- "main": "Clouds", -- "description": "broken clouds", -- "icon": "04d" -- }], -- "base": "stations", -- "main": { -- "temp": 281.13, -- "pressure": 998, -- "humidity": 66, -- "temp_min": 280.15, -- "temp_max": 282.15 -- }, -- "visibility": 10000, -- "wind": { -- "speed": 3.1, -- "deg": 240 -- }, -- "rain": {}, -- "clouds": { -- "all": 67 -- }, -- "dt": 1573656582, -- "sys": { -- "type": 1, -- "id": 1414, -- "country": "GB", -- "sunrise": 1573629270, -- "sunset": 1573661710 -- }, -- "timezone": 0, -- "id": 2643743, -- "name": "London", -- "cod": 200 --}
local View = {} function View:Start(data) self.view = SGK.UIReference.Setup(self.gameObject); CS.UGUIClickEventListener.Get(self.view.root.bg.commitBtn.gameObject).onClick = function () DialogStack.Pop() end CS.UGUIClickEventListener.Get(self.view.root.mask.gameObject).onClick = function () DialogStack.Pop() end self:initView(data) end function View:initView(data) self.allQuestCfg=module.QuestModule.GetCfg() self.friendCfg=data.data self.npcCfg=data.npcCfg local stageNum = module.ItemModule.GetItemCount(self.friendCfg.stage_item) local buffid = StringSplit(self.friendCfg.quest_buff,"|") self.view.root.bg.LvUpBefore[CS.UGUISpriteSelector].index=stageNum-1 self.view.root.bg.LvUpAfter[CS.UGUISpriteSelector].index=stageNum for j,v in pairs(self.allQuestCfg) do if v.id ==tonumber(buffid[stageNum+1]) then self.view.root.bg.effect.Text[UI.Text].text=v.raw.name break end end end function View:OnDestory() end function View:listEvent() return { } end function View:onEvent(event,data) end return View;
local Badge = require "widgets/badge" local UIAnim = require "widgets/uianim" local HealthBadge = Class(Badge, function(self, owner) Badge._ctor(self, "health", owner) self.sanityarrow = self.underNumber:AddChild(UIAnim()) self.sanityarrow:GetAnimState():SetBank("sanity_arrow") self.sanityarrow:GetAnimState():SetBuild("sanity_arrow") self.sanityarrow:GetAnimState():PlayAnimation("neutral") self.sanityarrow:SetClickable(false) self.topperanim = self.underNumber:AddChild(UIAnim()) self.topperanim:GetAnimState():SetBank("effigy_topper") self.topperanim:GetAnimState():SetBuild("effigy_topper") self.topperanim:GetAnimState():PlayAnimation("anim") self.topperanim:SetClickable(false) self:StartUpdating() end) function HealthBadge:SetPercent(val, max, penaltypercent) Badge.SetPercent(self, val, max) penaltypercent = penaltypercent or 0 self.topperanim:GetAnimState():SetPercent("anim", penaltypercent) end function HealthBadge:OnUpdate(dt) local down = self.owner.components.temperature:IsFreezing() or self.owner.components.hunger:IsStarving() or self.owner.components.health.takingfiredamage local anim = down and "arrow_loop_decrease_most" or "neutral" if anim and self.arrowdir ~= anim then self.arrowdir = anim self.sanityarrow:GetAnimState():PlayAnimation(anim, true) end end return HealthBadge
--[[ © 2021 Tony Ferguson, do not share, re-distribute or modify without permission of its author ( devultj@gmail.com - Tony Ferguson, http://www.tferguson.co.uk/ ) ]] local function registerAll() for sClass, tData in pairs( scripted_ents.GetList() ) do if string.find( sClass, "_base" ) then continue end local tEntityData = tData.t if tEntityData.IsBag or tEntityData.IsDrill or tEntityData.IsMask then print("[dHeists-ItemStore] Registered dHeists item: " .. sClass ) itemstore.config.CustomItems[ sClass ] = { tEntityData.PrintName, "", dHeists.config.itemStoreStackableItem } end end end --[[ itemStore addon support ]] dHeists.addonSupport:register { name = "itemStore", addonCallback = function() return itemstore ~= nil end, callback = function() if dHeists.config.itemStoreDisabled == true then return end registerAll() itemstore.items.Load() end }
----------------------------------- -- Area: Nashmau -- NPC: Chichiroon -- Standard Merchant NPC ----------------------------------- local ID = require("scripts/zones/Nashmau/IDs") require("scripts/globals/shop") function onTrade(player, npc, trade) end function onTrigger(player, npc) local stock = { 5497, 99224, -- Bolter's Die 5498, 85500, -- Caster's Die 5499, 97350, -- Courser's Die 5500, 100650, -- Blitzer's Die 5501, 109440, -- Tactician's Die 5502, 116568, -- Allies' Die 5503, 96250, -- Miser's Die 5504, 95800, -- Companion's Die 5505, 123744, -- Avenger's Die 6368, 69288, -- Geomancer Die 6369, 73920, -- Rune Fencer Die } player:showText(npc, ID.text.CHICHIROON_SHOP_DIALOG) tpz.shop.general(player, stock) end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
function start() local ip = loadfile("/bin/ip.lua") local fs = require "filesystem" local text = require "text" print("\x1b[32m>>\x1b[39m Configure network") if not fs.exists("/etc/netctl") then print("\x1b[31m!!\x1b[39m /etc/netctl DOES NOT EXIST!") return end for line in io.lines("/etc/netctl") do if line == "auto" then for m in component.list("modem") do ip("oc", "add", m) end elseif line:sub(1,1) ~= "#" and #line > 0 then ip(table.unpack(text.tokenize(line))) end end end
-- -- -- -- -- -- -- Function Locals -- -- -- -- -- -- -- local setmetatable, pairs, type = setmetatable, pairs, type local encode, decode, url_encode = json.encode, json.decode, json.url_encode local concat = table.concat local find, sub, tostring = string.find, string.sub, tostring local http = require("ssl.https") local ltn12 = require("ltn12") -- -- -- -- -- -- -- -- -- (Meta)tables and states -- -- -- -- -- -- -- -- -- Slack = {} Slack.__index = {} local function New(apikey, verifiedOnly) -- Safety apikey = apikey or '' verifiedOnly = verifiedOnly == nil and true or verifiedOnly -- Define local self = {} -- Defaults self.apikey = apikey self.verifiedOnly = verifiedOnly -- Meta setmetatable(self, Slack) -- Return return self end -- -- -- -- -- -- -- Static Locals -- -- -- -- -- -- -- local commandMetadata = { ['users'] = { ['list'] = { false, {} } }, ['channels'] = { ['history'] = { true, {} }, ['mark'] = { true, {} }, ['list'] = { true, {} } }, ['files'] = { -- ['upload'] = { true, {} }, ['list'] = { true, {} } }, ['im'] = { ['history'] = { true, {} }, ['list'] = { false, {} } }, ['groups'] = { ['history'] = { true, {} }, ['list'] = { true, {} } }, ['search'] = { ['all'] = { true, {} }, ['files'] = { true, {} }, ['messages'] = { true, {} } }, ['chat'] = { ['postMessage'] = { true, { ['username'] = 'ConnorBot', ['icon_emoji'] = ':octocat:' } } }, ['auth'] = { ['test'] = { false, {} } } } local instances = {} local tokens = {} -- -- -- -- -- -- -- -- Static Functions -- -- -- -- -- -- -- -- function Slack.GetInstance(apikey, verifiedOnly) local instances = instances if instances[apikey] ~= nil then return instances[apikey] end local instance = New(apikey, verifiedOnly == nil and true or verifiedOnly) instances[apikey] = instance return instance end function Slack.GetTokenInstance(token) local tokens = tokens if tokens[token] ~= nil then return Slack.GetInstance(tokens[token]) end for k, v in pairs(instances) do if v.verifiedOnly then return v end end end function Slack.InstallToken(token, apikey) tokens[token] = apikey end function Slack.HasError(response) return response == nil or type(response) ~= 'table' or response.ok ~= true end -- -- -- -- -- -- -- -- Utility Functions -- -- -- -- -- -- -- -- local function split(txt, del, pattern) del = del or "\r*\n\r*" pattern = pattern == nil and true or false local pieces, cnt, a, b, c = {}, 1, 0, 1 while a do a, c = find(txt, del, b, not pattern) if not a or not c then break end pieces[cnt] = sub(txt, b, a - 1) cnt = cnt + 1 b = c + 1 end pieces[cnt] = sub(txt, b) return pieces end local function commandify(command) return command, split(command, '.', false) end local function command_supported(command) local current, i = commandMetadata, 1 while i <= #command do if current == nil or #current > 0 then return false end current = current[command[i]] i = i + 1 end return current ~= nil and #current == 2 end local function requires_payload(command) local current, i = commandMetadata, 1 while i <= #command do current = current[command[i]] i = i + 1 end return { current[1], current[2] } end local function prepare(self, command) local command, commandified = commandify(command) if not command_supported(commandified) then return end local data = {} local payload = requires_payload(commandified) if payload[1] then data = payload[2] end return SlackPayload.New(self, command, data) end local function special_encode(data) local str, first = '', true for k, v in pairs(data) do if not first then str = str .. '&' end if type(v) == 'table' then str = str .. k .. '=' .. encode(v) else str = str .. k .. '=' .. url_encode(tostring(v)) end first = false end return str end local function send(self, payload) local data = special_encode(payload.data) local result = {} local res, code, headers, status = http.request { url = 'https://slack.com/api/' .. payload.command .. '?token=' .. self.apikey .. '&' .. data, sink = ltn12.sink.table(result) } return decode(concat(result)) end -- -- -- -- -- -- -- -- Instance Functions -- -- -- -- -- -- -- -- function Slack.__index:Prepare(command) return prepare(self, command) end function Slack.__index:Send(payload) return send(self, payload) end function Slack.__index:Utilities() if self.utilities == nil then self.utilities = SlackUtilities.New(self) end return self.utilities end function Slack.__index:Message(message, channel, from, to, icon_emoji, icon_url) message = self:Prepare('chat.postMessage'):Message(message):Channel(channel) if from ~= nil then message:From(from) end if to ~= nil then message:To(to) end if icon_emoji ~= nil then message:Emoji(icon_emoji) elseif icon_url ~= nil then message:Icon(icon_url) end return message end
return {[1]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="%1% to %2% Base Off Hand Physical Damage"}}},stats={[1]="off_hand_local_minimum_added_physical_damage",[2]="off_hand_local_maximum_added_physical_damage"}},[2]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="%1% to %2% Added Physical Damage per 15 Armour or Evasion Rating on Shield"}}},stats={[1]="off_hand_minimum_added_physical_damage_per_15_shield_armour_and_evasion_rating",[2]="off_hand_maximum_added_physical_damage_per_15_shield_armour_and_evasion_rating"}},[3]={lang={English={[1]={[1]={k="milliseconds_to_seconds_2dp",v=1},limit={[1]={[1]="#",[2]="#"}},text="Base Off Hand Attack time is %1% seconds"}}},stats={[1]="off_hand_base_weapon_attack_duration_ms"}},[4]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="Deals %1% to %2% Physical Damage"}}},stats={[1]="global_minimum_added_physical_damage",[2]="global_maximum_added_physical_damage"}},[5]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="Deals %1% to %2% Fire Damage"}}},stats={[1]="global_minimum_added_fire_damage",[2]="global_maximum_added_fire_damage"}},[6]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="Deals %1% to %2% Cold Damage"}}},stats={[1]="global_minimum_added_cold_damage",[2]="global_maximum_added_cold_damage"}},[7]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="Deals %1% to %2% Lightning Damage"}}},stats={[1]="global_minimum_added_lightning_damage",[2]="global_maximum_added_lightning_damage"}},[8]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="Deals %1% to %2% Chaos Damage"}}},stats={[1]="global_minimum_added_chaos_damage",[2]="global_maximum_added_chaos_damage"}},[9]={lang={English={[1]={[1]={k="multiplicative_permyriad_damage_modifier",v=1},limit={[1]={[1]="#",[2]="#"}},text="Deals %1%%% of Base Attack Damage"}}},stats={[1]="active_skill_attack_damage_final_permyriad"}},[10]={lang={English={[1]={[1]={k="multiplicative_permyriad_damage_modifier",v=1},limit={[1]={[1]="#",[2]="#"}},text="Deals %1%%% of Base Damage"}}},stats={[1]="active_skill_base_attack_damage_final_+permyriad"}},[11]={lang={English={[1]={[1]={k="multiplicative_damage_modifier",v=1},limit={[1]={[1]="#",[2]="#"}},text="Deals %1%%% of Damage"}}},stats={[1]="active_skill_damage_+%_final"}},[12]={lang={English={[1]={[1]={k="multiplicative_damage_modifier",v=1},limit={[1]={[1]="#",[2]="#"}},text="Deals %1%%% of Physical Damage"}}},stats={[1]="active_skill_physical_damage_+%_final"}},[13]={lang={English={[1]={[1]={k="multiplicative_damage_modifier",v=1},limit={[1]={[1]="#",[2]="#"}},text="Deals %1%%% of Attack Damage"}}},stats={[1]="active_skill_attack_damage_+%_final"}},[14]={lang={English={[1]={[1]={k="multiplicative_damage_modifier",v=1},limit={[1]={[1]="#",[2]="#"}},text="When Dual Wielding, Deals %1%%% Damage from each Weapon combined"}}},stats={[1]="cleave_damage_+%_final_while_dual_wielding"}},[15]={lang={English={[1]={[1]={k="multiplicative_damage_modifier",v=1},limit={[1]={[1]="#",[2]="#"}},text="Minions deal %1%%% of Damage"}}},stats={[1]="active_skill_minion_damage_+%_final"}},[16]={lang={English={[1]={[1]={k="multiplicative_damage_modifier",v=1},limit={[1]={[1]="#",[2]="#"}},text="Minions deal %1%%% of Physical Damage"}}},stats={[1]="active_skill_minion_physical_damage_+%_final"}},[17]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Physical Damage per Frenzy Charge"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Physical Damage per Frenzy Charge"}}},stats={[1]="physical_damage_+%_per_frenzy_charge"}},[18]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Maximum %1% Raised Zombie"},[2]={limit={[1]={[1]=2,[2]="#"}},text="Maximum %1% Raised Zombies"}}},stats={[1]="base_number_of_zombies_allowed"}},[19]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Maximum %1% Raised Spectre"},[2]={limit={[1]={[1]=2,[2]="#"}},text="Maximum %1% Raised Spectres"}}},stats={[1]="base_number_of_spectres_allowed"}},[20]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Maximum %1% Summoned Skeleton"},[2]={limit={[1]={[1]=1,[2]="#"}},text="Maximum %1% Summoned Skeletons"}}},stats={[1]="base_number_of_skeletons_allowed"}},[21]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Maximum %1% Summoned Raging Spirit"},[2]={limit={[1]={[1]=1,[2]="#"}},text="Maximum %1% Summoned Raging Spirits"}}},stats={[1]="base_number_of_raging_spirits_allowed"}},[22]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Area of Effect"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Area of Effect"}}},stats={[1]="base_aura_area_of_effect_+%"}},[23]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Aura effect"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Aura effect"}}},stats={[1]="aura_effect_+%"}},[24]={lang={English={[1]={[1]={k="milliseconds_to_seconds_2dp",v=1},limit={[1]={[1]="#",[2]="#"}},text="Base duration is %1% seconds"}}},stats={[1]="base_skill_effect_duration"}},[25]={lang={English={[1]={[1]={k="milliseconds_to_seconds_2dp",v=1},limit={[1]={[1]="#",[2]="#"}},text="Base secondary duration is %1% seconds"}}},stats={[1]="base_secondary_skill_effect_duration"}},[26]={lang={English={[1]={[1]={k="milliseconds_to_seconds_2dp",v=1},limit={[1]={[1]="#",[2]="#"}},text="Additional %1% seconds Base Duration per extra corpse Consumed"}}},stats={[1]="offering_skill_effect_duration_per_corpse"}},[27]={lang={English={[1]={[1]={k="milliseconds_to_seconds_2dp",v=1},limit={[1]={[1]="#",[2]="#"}},text="%1$+d seconds to Buff Duration per Endurance Charge removed"}}},stats={[1]="base_buff_duration_ms_+_per_removable_endurance_charge"}},[28]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Buff and Debuff Duration"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Buff and Debuff Duration"}}},stats={[1]="buff_duration_+%"}},[29]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Minions have %1% base maximum Life"}}},stats={[1]="display_minion_base_maximum_life"}},[30]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% more Area Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% less Area Damage"}}},stats={[1]="active_skill_area_damage_+%_final"}},[31]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Spell Repeats once"},[2]={limit={[1]={[1]=2,[2]="#"}},text="Spell Repeats %1% times"}}},stats={[1]="base_spell_repeat_count"}},[32]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Maximum %1% Summoned Golem"},[2]={limit={[1]={[1]=2,[2]="#"}},text="Maximum %1% Summoned Golems"}}},stats={[1]="base_number_of_golems_allowed"}},[33]={lang={English={[1]={limit={[1]={[1]=0,[2]=0},[2]={[1]=0,[2]=1},[3]={[1]=0,[2]=0}},text="Summons a Totem which uses this Skill"},[2]={limit={[1]={[1]=0,[2]=0},[2]={[1]=0,[2]=1},[3]={[1]=0,[2]=0}},text="Summons a Ballista Totem which uses this Skill"},[3]={limit={[1]={[1]=0,[2]=0},[2]={[1]=2,[2]="#"},[3]={[1]=0,[2]=0}},text="Summons %1% Totems which use this Skill"},[4]={limit={[1]={[1]=0,[2]=0},[2]={[1]=2,[2]="#"},[3]={[1]=0,[2]=0}},text="Summons %1% Ballista Totems which use this Skill"}}},stats={[1]="is_totem",[2]="number_of_totems_to_summon",[3]="is_ranged_attack_totem"}},[34]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="%1$+d to maximum number of Summoned Ballista Totems"}}},stats={[1]="attack_skills_additional_ballista_totems_allowed"}},[35]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="%1$+d to maximum number of Summoned Totems"}}},stats={[1]="base_number_of_totems_allowed"}},[36]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="%1$+d to Accuracy Rating"}}},stats={[1]="accuracy_rating"}},[37]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Accuracy Rating"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Accuracy Rating"}}},stats={[1]="accuracy_rating_+%"}},[38]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% more Attack Damage with Two Handed Weapons"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% less Attack Damage with Two Handed Weapons"}}},stats={[1]="active_skill_attack_damage_+%_final_with_two_handed_weapon"}},[39]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% more Attack Speed with Two Handed Weapons"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% less Attack Speed with Two Handed Weapons"}}},stats={[1]="active_skill_attack_speed_+%_final_with_two_handed_weapon"}},[40]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% more Poison Duration"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% less Poison Duration"}}},stats={[1]="active_skill_poison_duration_+%_final"}},[41]={lang={English={[1]={[1]={k="divide_by_one_hundred",v=1},limit={[1]={[1]="#",[2]="#"}},text="%1$+d%% to Critical Strike Chance"}}},stats={[1]="additional_base_critical_strike_chance"}},[42]={lang={English={[1]={[1]={k="milliseconds_to_seconds_2dp_if_required",v=1},limit={[1]={[1]="#",[2]="#"}},text="%1$+d seconds to Attack Time"}}},stats={[1]="additional_weapon_base_attack_time_ms"}},[43]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Increases and Reductions to Cast Speed also apply to this Skill's Activation frequency"}}},stats={[1]="additive_cast_speed_modifiers_apply_to_sigil_repeat_frequency"}},[44]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Increases and Reductions to Mine Duration also apply to this Skill's Buff Duration"}}},stats={[1]="additive_mine_duration_modifiers_apply_to_buff_effect_duration"}},[45]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Area Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Area Damage"}}},stats={[1]="area_damage_+%"}},[46]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Area of Effect while Dead"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Area of Effect while Dead"}}},stats={[1]="area_of_effect_+%_while_dead"}},[47]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="%1% to %2% Added Chaos Damage"}}},stats={[1]="attack_minimum_added_chaos_damage",[2]="attack_maximum_added_chaos_damage"}},[48]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="%1% to %2% Added Cold Damage"}}},stats={[1]="attack_minimum_added_cold_damage",[2]="attack_maximum_added_cold_damage"}},[49]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="%1% to %2% Added Fire Damage"}}},stats={[1]="attack_minimum_added_fire_damage",[2]="attack_maximum_added_fire_damage"}},[50]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="%1% to %2% Added Lightning Damage"}}},stats={[1]="attack_minimum_added_lightning_damage",[2]="attack_maximum_added_lightning_damage"}},[51]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="%1% to %2% Added Attack Physical Damage"}}},stats={[1]="attack_minimum_added_physical_damage",[2]="attack_maximum_added_physical_damage"}},[52]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Attack Speed"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Attack Speed"}}},stats={[1]="attack_speed_+%"}},[53]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Attack Speed"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Attack Speed"}}},stats={[1]="attack_speed_+%_granted_from_skill"}},[54]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Aura Area of Effect"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Aura Area of Effect"}}},stats={[1]="base_aura_area_of_effect_+%"}},[55]={lang={English={[1]={[1]={k="milliseconds_to_seconds_2dp",v=1},limit={[1]={[1]=1,[2]="#"}},text="Hits Enemies every %1% Seconds"}}},stats={[1]="base_blade_vortex_hit_rate_ms"}},[56]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Cast Speed"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Cast Speed"}}},stats={[1]="base_cast_speed_+%"}},[57]={lang={English={[1]={[1]={k="reminderstring",v="ReminderTextFreeze"},limit={[1]={[1]="#",[2]="#"},[2]={[1]=1,[2]="#"}},text="Always Freezes Enemies on Hit"},[2]={[1]={k="reminderstring",v="ReminderTextFreeze"},limit={[1]={[1]=1,[2]=99},[2]={[1]=0,[2]=0}},text="%1%%% chance to Freeze"}}},stats={[1]="base_chance_to_freeze_%",[2]="always_freeze"}},[58]={lang={English={[1]={[1]={k="reminderstring",v="ReminderTextIgnite"},limit={[1]={[1]=1,[2]=99}},text="%1%%% chance to Ignite"},[2]={[1]={k="reminderstring",v="ReminderTextIgnite"},limit={[1]={[1]=100,[2]="#"}},text="Always Ignite"}}},stats={[1]="base_chance_to_ignite_%"}},[59]={lang={English={[1]={[1]={k="reminderstring",v="ReminderTextShock"},limit={[1]={[1]=1,[2]=99}},text="%1%%% chance to Shock"},[2]={[1]={k="reminderstring",v="ReminderTextShock"},limit={[1]={[1]=100,[2]="#"}},text="Always Shock"}}},stats={[1]="base_chance_to_shock_%"}},[60]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="%1$+d%% to Critical Strike Multiplier"}}},stats={[1]="base_critical_strike_multiplier_+"}},[61]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Curse Duration"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Curse Duration"}}},stats={[1]="base_curse_duration_+%"}},[62]={lang={English={[1]={[1]={k="reminderstring",v="ReminderTextKnockback"},limit={[1]={[1]=1,[2]="#"}},text="%1%%% chance to Knock Enemies Back on hit"}}},stats={[1]="base_global_chance_to_knockback_%"}},[63]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Rarity of Items Dropped by Slain Enemies"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Rarity of Items Dropped by Slain Enemies"}}},stats={[1]="base_killed_monster_dropped_item_rarity_+%"}},[64]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1$+d Life gained for each Enemy hit by your Attacks"}}},stats={[1]="base_life_gain_per_target"}},[65]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% reduced Mana Cost"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% increased Mana Cost"}}},stats={[1]="base_mana_cost_-%"}},[66]={lang={English={[1]={[1]={k="milliseconds_to_seconds_2dp",v=1},limit={[1]={[1]="#",[2]="#"}},text="Base Mine Detonation Time is %1% seconds"}}},stats={[1]="base_mine_detonation_time_ms"}},[67]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Fires an additional Arrow"},[2]={limit={[1]={[1]=2,[2]="#"}},text="Fires %1% additional Arrows"}}},stats={[1]="base_number_of_additional_arrows"}},[68]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Maximum %1% Summoned Sentinel of Purity"},[2]={limit={[1]={[1]=2,[2]="#"}},text="Maximum %1% Summoned Sentinels of Purity"}}},stats={[1]="base_number_of_champions_of_light_allowed"}},[69]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Maximum %1% Summoned Holy Relic"},[2]={limit={[1]={[1]="#",[2]="#"}},text="Maximum %1% Summoned Holy Relics"}}},stats={[1]="base_number_of_relics_allowed"}},[70]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% of Physical Damage Converted to Lightning Damage"}}},stats={[1]="base_physical_damage_%_to_convert_to_lightning"}},[71]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Poison Duration"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Poison Duration"}}},stats={[1]="base_poison_duration_+%"}},[72]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Projectile Speed"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Projectile Speed"}}},stats={[1]="base_projectile_speed_+%"}},[73]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Penetrates %1%%% Cold Resistance"}}},stats={[1]="base_reduce_enemy_cold_resistance_%"}},[74]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Penetrates %1%%% Fire Resistance"}}},stats={[1]="base_reduce_enemy_fire_resistance_%"}},[75]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Penetrates %1%%% Lightning Resistance"}}},stats={[1]="base_reduce_enemy_lightning_resistance_%"}},[76]={lang={English={[1]={[1]={k="milliseconds_to_seconds",v=1},limit={[1]={[1]="#",[2]="#"}},text="Activates every %1% seconds while Attached"}}},stats={[1]="base_sigil_repeat_frequency_ms"}},[77]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Area of Effect"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Area of Effect"}}},stats={[1]="base_skill_area_of_effect_+%"}},[78]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Stun Duration on Enemies"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Stun Duration on Enemies"}}},stats={[1]="base_stun_duration_+%"}},[79]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Spend Life instead of Mana"}}},stats={[1]="base_use_life_in_place_of_mana"}},[80]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Lose %1% Rage per second"}}},stats={[1]="berserk_base_rage_loss_per_second"}},[81]={lang={English={[1]={[1]={k="reminderstring",v="ReminderTextLingeringBlades"},limit={[1]={[1]=1,[2]=1}},text="Leaves a Lingering Blade in the ground for every Volley"},[2]={[1]={k="reminderstring",v="ReminderTextLingeringBlades"},limit={[1]={[1]="#",[2]="#"}},text="Leaves a Lingering Blade in the ground for every %1% Volleys"}}},stats={[1]="bladefall_blade_left_in_ground_for_every_X_volleys"}},[82]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="1 Volley"},[2]={limit={[1]={[1]=2,[2]="#"}},text="%1% Volleys"}}},stats={[1]="bladefall_number_of_volleys"}},[83]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Leaves %1%%% more Lingering Blades in the ground if you don't Cast this Spell yourself"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="Leaves %1%%% fewer Lingering Blades in the ground if you don't Cast this Spell yourself"}}},stats={[1]="blades_left_in_ground_+%_final_if_not_hand_cast"}},[84]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Blinding duration"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Blinding duration"}}},stats={[1]="blind_duration_+%"}},[85]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Burning Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Burning Damage"}}},stats={[1]="burn_damage_+%"}},[86]={lang={English={[1]={[1]={k="reminderstring",v="ReminderTextFortify"},limit={[1]={[1]=100,[2]="#"}},text="Grants Fortify on Melee hit"},[2]={[1]={k="reminderstring",v="ReminderTextFortify"},limit={[1]={[1]=1,[2]=99}},text="%1%%% chance to Fortify on Melee hit"}}},stats={[1]="chance_to_fortify_on_melee_hit_+%"}},[87]={lang={English={[1]={limit={[1]={[1]=1,[2]=99}},text="%1%%% chance to gain a Frenzy Charge on Killing a Frozen Enemy"},[2]={limit={[1]={[1]=100,[2]="#"}},text="Gain a Frenzy Charge on Killing a Frozen Enemy"}}},stats={[1]="chance_to_gain_frenzy_charge_on_killing_frozen_enemy_%"}},[88]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Chaos Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Chaos Damage"}}},stats={[1]="chaos_damage_+%"}},[89]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Chill Duration on Enemies"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Chill Duration on Enemies"}}},stats={[1]="chill_duration_+%"}},[90]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Chill Effect on Enemies"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Chill Effect on Enemies"}}},stats={[1]="chill_effect_+%"}},[91]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Gain %1%%% of Cold Damage as Extra Fire Damage"}}},stats={[1]="cold_damage_%_to_add_as_fire"}},[92]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Cold Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Cold Damage"}}},stats={[1]="cold_damage_+%"}},[93]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Maximum of %1% Geysers at a time"}}},stats={[1]="corpse_erruption_base_maximum_number_of_geyers"}},[94]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Critical Strike Chance"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Critical Strike Chance"}}},stats={[1]="critical_strike_chance_+%"}},[95]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Damage over Time"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Damage over Time"}}},stats={[1]="damage_over_time_+%"}},[96]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Damage"}}},stats={[1]="damage_+%"}},[97]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Damage with Hits against Frozen Enemies"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Damage with Hits against Frozen Enemies"}}},stats={[1]="damage_+%_vs_frozen_enemies"}},[98]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Increases and Reductions to Cast Speed also apply to Projectile Frequency"}}},stats={[1]="display_frost_fury_additive_cast_speed_modifiers_apply_to_fire_speed"}},[99]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Damages %1% nearby Enemies when you gain Stages"}}},stats={[1]="divine_tempest_base_number_of_nearby_enemies_to_zap"}},[100]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Elemental Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Elemental Damage"}}},stats={[1]="elemental_damage_+%"}},[101]={lang={English={[1]={[1]={k="reminderstring",v="ReminderTextLingeringBlades"},limit={[1]={[1]=1,[2]=1}},text="Leaves a Lingering Blade in the ground for every Projectile fired"},[2]={[1]={k="reminderstring",v="ReminderTextLingeringBlades"},limit={[1]={[1]="#",[2]="#"}},text="Leaves a Lingering Blade in the ground for every %1% Projectiles fired"}}},stats={[1]="ethereal_knives_blade_left_in_ground_for_every_X_projectiles"}},[102]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Fire Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Fire Damage"}}},stats={[1]="fire_damage_+%"}},[103]={lang={English={[1]={[1]={k="reminderstring",v="ReminderTextFortify"},limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Fortify duration"},[2]={[1]={k="negate",v=1},[2]={k="reminderstring",v="ReminderTextFortify"},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Fortify duration"}}},stats={[1]="fortify_duration_+%"}},[104]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Freeze Duration on Enemies"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Freeze Duration on Enemies"}}},stats={[1]="freeze_duration_+%"}},[105]={lang={English={[1]={[1]={k="reminderstring",v="ReminderTextBlind"},limit={[1]={[1]="#",[2]="#"}},text="%1%%% chance to Blind enemies on hit"}}},stats={[1]="global_chance_to_blind_on_hit_%"}},[106]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="Adds %1% to %2% Chaos Damage"}}},stats={[1]="global_minimum_added_chaos_damage",[2]="global_maximum_added_chaos_damage"}},[107]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="Adds %1% to %2% Cold Damage"}}},stats={[1]="global_minimum_added_cold_damage",[2]="global_maximum_added_cold_damage"}},[108]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="Adds %1% to %2% Fire Damage"}}},stats={[1]="global_minimum_added_fire_damage",[2]="global_maximum_added_fire_damage"}},[109]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="Adds %1% to %2% Lightning Damage"}}},stats={[1]="global_minimum_added_lightning_damage",[2]="global_maximum_added_lightning_damage"}},[110]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="Adds %1% to %2% Physical Damage"}}},stats={[1]="global_minimum_added_physical_damage",[2]="global_maximum_added_physical_damage"}},[111]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% reduced Enemy Block Chance"}}},stats={[1]="global_reduce_enemy_block_%"}},[112]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Ignite Duration on Enemies"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Ignite Duration on Enemies"}}},stats={[1]="ignite_duration_+%"}},[113]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Projectile changes direction %1% times"}}},stats={[1]="kinetic_wand_base_number_of_zig_zags"}},[114]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Knockback Distance"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Knockback Distance"}}},stats={[1]="knockback_distance_+%"}},[115]={lang={English={[1]={[1]={k="divide_by_one_hundred",v=1},[2]={k="reminderstring",v="ReminderTextLifeLeech"},limit={[1]={[1]=1,[2]="#"}},text="%1%%% of Damage Leeched as Life"}}},stats={[1]="life_leech_from_any_damage_permyriad"}},[116]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Lightning Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Lightning Damage"}}},stats={[1]="lightning_damage_+%"}},[117]={lang={English={[1]={[1]={k="milliseconds_to_seconds_2dp",v=1},limit={[1]={[1]="#",[2]="#"}},text="Strikes every %1% seconds"}}},stats={[1]="lightning_tower_trap_base_interval_duration_ms"}},[118]={lang={English={[1]={[1]={k="divide_by_one_hundred",v=1},[2]={k="reminderstring",v="ReminderTextManaLeech"},limit={[1]={[1]=1,[2]="#"}},text="%1%%% of Damage Leeched as Mana"}}},stats={[1]="mana_leech_from_any_damage_permyriad"}},[119]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Melee Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Melee Damage"}}},stats={[1]="melee_damage_+%"}},[120]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Melee Damage against Bleeding Enemies"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Melee Damage against Bleeding Enemies"}}},stats={[1]="melee_damage_vs_bleeding_enemies_+%"}},[121]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Melee Physical Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Melee Physical Damage"}}},stats={[1]="melee_physical_damage_+%"}},[122]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Mine Detonation Area of Effect"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Mine Detonation Area of Effect"}}},stats={[1]="mine_detonation_radius_+%"}},[123]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Mines have %1%%% increased Detonation Speed"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="Mines have %1%%% reduced Detonation Speed"}}},stats={[1]="mine_detonation_speed_+%"}},[124]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Mine duration"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Mine duration"}}},stats={[1]="mine_duration_+%"}},[125]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Mine Throwing Speed"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Mine Throwing Speed"}}},stats={[1]="mine_laying_speed_+%"}},[126]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Aura effect"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Aura effect"}}},stats={[1]="non_curse_aura_effect_+%"}},[127]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Fires an additional Projectile"},[2]={limit={[1]={[1]=2,[2]="#"}},text="Fires %1% additional Projectiles"}}},stats={[1]="number_of_additional_projectiles"}},[128]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Chains %1$+d Times"}}},stats={[1]="number_of_chains"}},[129]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Can have up to %1% additional Remote Mine placed at a time"},[2]={limit={[1]={[1]="#",[2]="#"}},text="Can have up to %1% additional Remote Mines placed at a time"}}},stats={[1]="number_of_additional_remote_mines_allowed"}},[130]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Can have up to %1% additional Trap placed at a time"},[2]={limit={[1]={[1]="#",[2]="#"}},text="Can have up to %1% additional Traps placed at a time"}}},stats={[1]="number_of_additional_traps_allowed"}},[131]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Throw up to 1 additional Trap"},[2]={limit={[1]={[1]="#",[2]="#"}},text="Throw up to %1% additional Traps"}}},stats={[1]="number_of_additional_traps_to_throw"}},[132]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Maximum %1% Animated Weapon"},[2]={limit={[1]={[1]=2,[2]="#"}},text="Maximum %1% Animated Weapons"}}},stats={[1]="number_of_animated_weapons_allowed"}},[133]={lang={English={[1]={[1]={k="milliseconds_to_seconds_2dp",v=1},limit={[1]={[1]=1000,[2]=1000}},text="Strikes every %1% second"},[2]={[1]={k="milliseconds_to_seconds_2dp",v=1},limit={[1]={[1]="#",[2]="#"}},text="Strikes every %1% seconds"}}},stats={[1]="orb_of_storms_base_bolt_frequency_ms"}},[134]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="If this Skill Ignites an Enemy, it also inflicts a Burning Debuff\nDebuff deals Fire Damage per second equal to %1%%% of Ignite Damage per second"}}},stats={[1]="base_additional_burning_debuff_%_of_ignite_damage"}},[135]={lang={English={[1]={[1]={k="milliseconds_to_seconds",v=1},limit={[1]={[1]="#",[2]="#"}},text="Releases waves every %1% seconds"}}},stats={[1]="phys_cascade_trap_base_interval_duration_ms"}},[136]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Gain %1%%% of Physical Damage as Extra Fire Damage"}}},stats={[1]="physical_damage_%_to_add_as_fire"}},[137]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Gain %1%%% of Physical Damage as Extra Lightning Damage"}}},stats={[1]="physical_damage_%_to_add_as_lightning"}},[138]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Physical Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Physical Damage"}}},stats={[1]="physical_damage_+%"}},[139]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Cooldown Recovery Speed for throwing Traps"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Cooldown Recovery Speed for throwing Traps"}}},stats={[1]="placing_traps_cooldown_recovery_+%"}},[140]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Projectiles Pierce an additional Target"},[2]={limit={[1]={[1]=2,[2]="#"}},text="Projectiles Pierce %1% additional Targets"}}},stats={[1]="projectile_base_number_of_targets_to_pierce"}},[141]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Projectile Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Projectile Damage"}}},stats={[1]="projectile_damage_+%"}},[142]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Projectiles Split towards %1% targets"}}},stats={[1]="projectile_number_to_split"}},[143]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Projectiles Fork"}}},stats={[1]="projectiles_fork"}},[144]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]=0,[2]=0}},text="Projectiles Return to you after hitting targets"},[2]={limit={[1]={[1]=0,[2]=0},[2]={[1]="#",[2]="#"}},text="Projectiles Return to you at end of flight"},[3]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="Projectiles Return to you"}}},stats={[1]="projectiles_return",[2]="projectiles_return_if_no_hit_object"}},[145]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"},[2]={[1]="#",[2]="#"}},text="%1%%% of Damage from Hits is taken from the Buff before your Life or Energy Shield\nBuff can take %2% Damage"}}},stats={[1]="quick_guard_damage_absorbed_%",[2]="quick_guard_damage_absorb_limit"}},[146]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Fires an additional sequence of arrows"},[2]={limit={[1]={[1]=2,[2]="#"}},text="Fires %1% additional sequences of arrows"}}},stats={[1]="rain_of_arrows_additional_sequences"}},[147]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% reduced Enemy chance to Dodge"}}},stats={[1]="reduce_enemy_dodge_%"}},[148]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Shock Duration on Enemies"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Shock Duration on Enemies"}}},stats={[1]="shock_duration_+%"}},[149]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% of Cold Damage Converted to Fire Damage"}}},stats={[1]="skill_cold_damage_%_to_convert_to_fire"}},[150]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Skill Effect Duration"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Skill Effect Duration"}}},stats={[1]="skill_effect_duration_+%"}},[151]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% of Physical Damage Converted to Lightning Damage"}}},stats={[1]="skill_physical_damage_%_to_convert_to_lightning"}},[152]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Spell Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Spell Damage"}}},stats={[1]="spell_damage_+%"}},[153]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="%1% maximum Beam Targets"}}},stats={[1]="static_strike_number_of_beam_targets"}},[154]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% more Trap Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% less Trap Damage"}}},stats={[1]="support_trap_damage_+%_final"}},[155]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Fires %1% secondary Projectile"},[2]={limit={[1]={[1]=2,[2]="#"}},text="Fires %1% secondary Projectiles"}}},stats={[1]="tornado_shot_num_of_secondary_projectiles"}},[156]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Trap Damage"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Trap Damage"}}},stats={[1]="trap_damage_+%"}},[157]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Trap duration"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Trap duration"}}},stats={[1]="trap_duration_+%"}},[158]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Trap Throwing Speed"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Trap Throwing Speed"}}},stats={[1]="trap_throwing_speed_+%"}},[159]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Trap Trigger Area of Effect"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Trap Trigger Area of Effect"}}},stats={[1]="trap_trigger_radius_+%"}},[160]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="Spawns corpses with Level %1%"}}},stats={[1]="unearth_base_corpse_level"}},[161]={lang={English={[1]={[1]={k="milliseconds_to_seconds_2dp",v=1},limit={[1]={[1]=1000,[2]=1000}},text="Strikes an Enemy every %1% second"},[2]={[1]={k="milliseconds_to_seconds_2dp",v=1},limit={[1]={[1]="#",[2]="#"}},text="Strikes an Enemy every %1% seconds"}}},stats={[1]="vaal_storm_call_base_delay_ms"}},[162]={lang={English={[1]={limit={[1]={[1]=1,[2]=1}},text="Consumes up to 1 corpse"},[2]={limit={[1]={[1]="#",[2]="#"}},text="Consumes up to %1% corpses"}}},stats={[1]="volatile_dead_base_number_of_corpses_to_consume"}},[163]={lang={English={[1]={limit={[1]={[1]="#",[2]="#"}},text="Maximum of %1% Orbs at a time"}}},stats={[1]="volatile_dead_max_cores_allowed"}},[164]={lang={English={[1]={limit={[1]={[1]=1,[2]="#"}},text="%1%%% increased Elemental Damage with Weapons"},[2]={[1]={k="negate",v=1},limit={[1]={[1]="#",[2]=-1}},text="%1%%% reduced Elemental Damage with Weapons"}}},stats={[1]="weapon_elemental_damage_+%"}},["accuracy_rating"]=36,["accuracy_rating_+%"]=37,["active_skill_area_damage_+%_final"]=30,["active_skill_attack_damage_+%_final"]=13,["active_skill_attack_damage_+%_final_with_two_handed_weapon"]=38,["active_skill_attack_damage_final_permyriad"]=9,["active_skill_attack_speed_+%_final_with_two_handed_weapon"]=39,["active_skill_base_attack_damage_final_+permyriad"]=10,["active_skill_damage_+%_final"]=11,["active_skill_minion_damage_+%_final"]=15,["active_skill_minion_physical_damage_+%_final"]=16,["active_skill_physical_damage_+%_final"]=12,["active_skill_poison_duration_+%_final"]=40,["additional_base_critical_strike_chance"]=41,["additional_weapon_base_attack_time_ms"]=42,["additive_cast_speed_modifiers_apply_to_sigil_repeat_frequency"]=43,["additive_mine_duration_modifiers_apply_to_buff_effect_duration"]=44,["always_freeze"]=57,["area_damage_+%"]=45,["area_of_effect_+%_while_dead"]=46,["attack_maximum_added_chaos_damage"]=47,["attack_maximum_added_cold_damage"]=48,["attack_maximum_added_fire_damage"]=49,["attack_maximum_added_lightning_damage"]=50,["attack_maximum_added_physical_damage"]=51,["attack_minimum_added_chaos_damage"]=47,["attack_minimum_added_cold_damage"]=48,["attack_minimum_added_fire_damage"]=49,["attack_minimum_added_lightning_damage"]=50,["attack_minimum_added_physical_damage"]=51,["attack_skills_additional_ballista_totems_allowed"]=34,["attack_speed_+%"]=52,["attack_speed_+%_granted_from_skill"]=53,["aura_effect_+%"]=23,["base_additional_burning_debuff_%_of_ignite_damage"]=134,["base_aura_area_of_effect_+%"]=54,["base_blade_vortex_hit_rate_ms"]=55,["base_buff_duration_ms_+_per_removable_endurance_charge"]=27,["base_cast_speed_+%"]=56,["base_chance_to_freeze_%"]=57,["base_chance_to_ignite_%"]=58,["base_chance_to_shock_%"]=59,["base_critical_strike_multiplier_+"]=60,["base_curse_duration_+%"]=61,["base_global_chance_to_knockback_%"]=62,["base_killed_monster_dropped_item_rarity_+%"]=63,["base_life_gain_per_target"]=64,["base_mana_cost_-%"]=65,["base_mine_detonation_time_ms"]=66,["base_number_of_additional_arrows"]=67,["base_number_of_champions_of_light_allowed"]=68,["base_number_of_golems_allowed"]=32,["base_number_of_raging_spirits_allowed"]=21,["base_number_of_relics_allowed"]=69,["base_number_of_skeletons_allowed"]=20,["base_number_of_spectres_allowed"]=19,["base_number_of_totems_allowed"]=35,["base_number_of_zombies_allowed"]=18,["base_physical_damage_%_to_convert_to_lightning"]=70,["base_poison_duration_+%"]=71,["base_projectile_speed_+%"]=72,["base_reduce_enemy_cold_resistance_%"]=73,["base_reduce_enemy_fire_resistance_%"]=74,["base_reduce_enemy_lightning_resistance_%"]=75,["base_secondary_skill_effect_duration"]=25,["base_sigil_repeat_frequency_ms"]=76,["base_skill_area_of_effect_+%"]=77,["base_skill_effect_duration"]=24,["base_spell_repeat_count"]=31,["base_stun_duration_+%"]=78,["base_use_life_in_place_of_mana"]=79,["berserk_base_rage_loss_per_second"]=80,["bladefall_blade_left_in_ground_for_every_X_volleys"]=81,["bladefall_number_of_volleys"]=82,["blades_left_in_ground_+%_final_if_not_hand_cast"]=83,["blind_duration_+%"]=84,["buff_duration_+%"]=28,["burn_damage_+%"]=85,["chance_to_fortify_on_melee_hit_+%"]=86,["chance_to_gain_frenzy_charge_on_killing_frozen_enemy_%"]=87,["chaos_damage_+%"]=88,["chill_duration_+%"]=89,["chill_effect_+%"]=90,["cleave_damage_+%_final_while_dual_wielding"]=14,["cold_damage_%_to_add_as_fire"]=91,["cold_damage_+%"]=92,["corpse_erruption_base_maximum_number_of_geyers"]=93,["critical_strike_chance_+%"]=94,["damage_+%"]=96,["damage_+%_vs_frozen_enemies"]=97,["damage_over_time_+%"]=95,["display_frost_fury_additive_cast_speed_modifiers_apply_to_fire_speed"]=98,["display_minion_base_maximum_life"]=29,["divine_tempest_base_number_of_nearby_enemies_to_zap"]=99,["elemental_damage_+%"]=100,["ethereal_knives_blade_left_in_ground_for_every_X_projectiles"]=101,["fire_damage_+%"]=102,["fortify_duration_+%"]=103,["freeze_duration_+%"]=104,["global_chance_to_blind_on_hit_%"]=105,["global_maximum_added_chaos_damage"]=106,["global_maximum_added_cold_damage"]=107,["global_maximum_added_fire_damage"]=108,["global_maximum_added_lightning_damage"]=109,["global_maximum_added_physical_damage"]=110,["global_minimum_added_chaos_damage"]=106,["global_minimum_added_cold_damage"]=107,["global_minimum_added_fire_damage"]=108,["global_minimum_added_lightning_damage"]=109,["global_minimum_added_physical_damage"]=110,["global_reduce_enemy_block_%"]=111,["ignite_duration_+%"]=112,["is_ranged_attack_totem"]=33,["is_totem"]=33,["kinetic_wand_base_number_of_zig_zags"]=113,["knockback_distance_+%"]=114,["life_leech_from_any_damage_permyriad"]=115,["lightning_damage_+%"]=116,["lightning_tower_trap_base_interval_duration_ms"]=117,["mana_leech_from_any_damage_permyriad"]=118,["melee_damage_+%"]=119,["melee_damage_vs_bleeding_enemies_+%"]=120,["melee_physical_damage_+%"]=121,["mine_detonation_radius_+%"]=122,["mine_detonation_speed_+%"]=123,["mine_duration_+%"]=124,["mine_laying_speed_+%"]=125,["non_curse_aura_effect_+%"]=126,["number_of_additional_projectiles"]=127,["number_of_additional_remote_mines_allowed"]=129,["number_of_additional_traps_allowed"]=130,["number_of_additional_traps_to_throw"]=131,["number_of_animated_weapons_allowed"]=132,["number_of_chains"]=128,["number_of_totems_to_summon"]=33,["off_hand_base_weapon_attack_duration_ms"]=3,["off_hand_local_maximum_added_physical_damage"]=1,["off_hand_local_minimum_added_physical_damage"]=1,["off_hand_maximum_added_physical_damage_per_15_shield_armour_and_evasion_rating"]=2,["off_hand_minimum_added_physical_damage_per_15_shield_armour_and_evasion_rating"]=2,["offering_skill_effect_duration_per_corpse"]=26,["orb_of_storms_base_bolt_frequency_ms"]=133,parent="gem_stat_descriptions",["phys_cascade_trap_base_interval_duration_ms"]=135,["physical_damage_%_to_add_as_fire"]=136,["physical_damage_%_to_add_as_lightning"]=137,["physical_damage_+%"]=138,["physical_damage_+%_per_frenzy_charge"]=17,["placing_traps_cooldown_recovery_+%"]=139,["projectile_base_number_of_targets_to_pierce"]=140,["projectile_damage_+%"]=141,["projectile_number_to_split"]=142,["projectiles_fork"]=143,["projectiles_return"]=144,["projectiles_return_if_no_hit_object"]=144,["quick_guard_damage_absorb_limit"]=145,["quick_guard_damage_absorbed_%"]=145,["rain_of_arrows_additional_sequences"]=146,["reduce_enemy_dodge_%"]=147,["shock_duration_+%"]=148,["skill_cold_damage_%_to_convert_to_fire"]=149,["skill_effect_duration_+%"]=150,["skill_physical_damage_%_to_convert_to_lightning"]=151,["spell_damage_+%"]=152,["static_strike_number_of_beam_targets"]=153,["support_trap_damage_+%_final"]=154,["tornado_shot_num_of_secondary_projectiles"]=155,["trap_damage_+%"]=156,["trap_duration_+%"]=157,["trap_throwing_speed_+%"]=158,["trap_trigger_radius_+%"]=159,["unearth_base_corpse_level"]=160,["vaal_storm_call_base_delay_ms"]=161,["volatile_dead_base_number_of_corpses_to_consume"]=162,["volatile_dead_max_cores_allowed"]=163,["weapon_elemental_damage_+%"]=164}
local BasePlugin = require "kong.plugins.base_plugin" local constants = require "kong.constants" local meta = require "kong.meta" local http = require "resty.http" local cjson = require "cjson.safe" local multipart = require "multipart" local kong = kong local tostring = tostring local concat = table.concat local pairs = pairs local lower = string.lower local find = string.find local type = type local ngx = ngx local encode_base64 = ngx.encode_base64 local get_body_data = ngx.req.get_body_data local get_uri_args = ngx.req.get_uri_args local get_headers = ngx.req.get_headers local read_body = ngx.req.read_body local ngx_log = ngx.log local var = ngx.var local header = ngx.header local server_header = meta._SERVER_TOKENS local SERVER = meta._NAME .. "/" .. meta._VERSION local function log(...) ngx_log(ngx.ERR, "[openwhisk] ", ...) end local function get_request_body() read_body() return get_body_data() end local function retrieve_parameters() read_body() local content_type = var.content_type if content_type then content_type = lower(content_type) if find(content_type, "multipart/form-data", nil, true) or var.request_method == "GET" then return kong.table.merge( get_uri_args(), multipart(get_body_data(), content_type):get_all()) end if find(content_type, "application/json", nil, true) then local json, err = cjson.decode(get_body_data()) if err then return nil, err end return kong.table.merge(get_uri_args(), json) end end if var.request_method == "GET" then return get_uri_args() end return kong.table.merge(get_uri_args(), kong.request.get_body()) end local function send(status, content, headers) if not headers["Content-Length"] then headers["Content-Length"] = #content end if kong.configuration.enabled_headers[constants.HEADERS.VIA] then headers[constants.HEADERS.VIA] = server_header end return kong.response.exit(status, content, headers) end local function flush(ctx) ctx = ctx or ngx.ctx local response = ctx.delayed_response return send(response.status_code, response.content, response.headers) end local OpenWhisk = BasePlugin:extend() OpenWhisk.PRIORITY = 1000 -- create a table with characters that would be omitted from allowed origins expression local escaped_chars = {} escaped_chars["."] = "%." escaped_chars["*"] = ".+" -- add a fallback option for unknown char setmetatable(escaped_chars, { __index = function(table, key) return key end } ) local function is_allowed_origin(origin, allowed_origins) -- if the route does not have allowed origins configured it's not necessary to validate it if #allowed_origins == 0 then return true end -- if the request does not have an Origin header configured, reject the request if origin == nil then return false end -- if the request has an Origin header and the route has "allowed_origins" configured, check the origin local is_origin_valid = false for index = 1, #allowed_origins do -- format the allowed origin like a regular expression for checking that the origin matches with it local expression = "^" for i = 1, #allowed_origins[index] do local char_index = allowed_origins[index]:sub(i,i) local scaped_char = escaped_chars[char_index] expression = expression .. scaped_char end -- if * (.+) exists in allowed origins, the origin will be valid if expression == ".+" then is_origin_valid = true break end -- remove the protocol from origin value origin = origin:gsub("https?://", "") -- if the matched value is not nil, the origin will be valid if string.match(origin, expression) ~= nil then is_origin_valid = true break end end return is_origin_valid end function OpenWhisk:new() OpenWhisk.super.new(self, "openwhisk") end function OpenWhisk:access(config) OpenWhisk.super.access(self) -- Check allowed methods local method = kong.request.get_method() local method_match = false for i = 1, #config.methods do if config.methods[i] == method then method_match = true break end end if not method_match then return kong.response.exit(405, { code = 405001, message = "The HTTP method used is not allowed in this endpoint." }) end -- check allowed origin local origin = kong.request.get_header("origin") if not is_allowed_origin(origin, config.allowed_origins) then return kong.response.exit(405, { code = 403001, message = "You do not have enough permissions to perform this action." }) end -- Get parameters local body, err if config.raw_function then body = {} else body, err = retrieve_parameters() end if err then return kong.response.exit(400, { code = 400002, message = "Validation error", detail = { body = err } }) end -- Append environment data if config.environment ~= nil then body['_environment'] = config.environment end -- Append extra data for the request if config.parameters ~= nil then body['_parameters'] = config.parameters end if config.raw_function then body['headers'] = get_headers() body['body'] = get_request_body() body['path'] = kong.request.get_path_with_query() end -- Get x-auth-token local authorization_header = get_headers()["x-auth-token"] if authorization_header and not config.raw_function then body['token'] = authorization_header end -- Invoke action local basic_auth if config.service_token ~= nil then basic_auth = "Basic " .. encode_base64(config.service_token) end -- Blocking local blocking = (body['_blocking'] == nil) local client = http.new() client:set_timeout(config.timeout) local ok, err = client:connect(config.host, config.port) if not ok then kong.log.err(err) return kong.response.exit(503, { code = 503001, message = "It's not you, it's us, our service is down." }) end if config.https then local ok, err = client:ssl_handshake(false, config.host, config.https_verify) if not ok then kong.log.err(err) return kong.response.exit(501, { code = 500001, message = "It's not you, it's us, we have experienced a error on our side." }) end end body["_blocking"] = nil local res, err = client:request { method = "POST", path = concat { config.path, "/actions/", config.action, "?blocking=", tostring(blocking), "&result=", tostring(config.result), "&timeout=", config.timeout }, body = cjson.encode(body), headers = { ["Content-Type"] = "application/json", ["Authorization"] = basic_auth } } if not res then kong.log.err(err) return kong.response.exit(501, { code = 500001, message = "It's not you, it's us, we have experienced a error on our side." }) end local response_status = res.status local response_content = res:read_body() ok, err = client:set_keepalive(config.keepalive) if not ok then log("could not keepalive connection: ", err) end -- Prepare response for downstream if not config.raw_function then for key, value in pairs(res.headers) do header[key] = value end end header.Server = SERVER if config.raw_function then local response_json = cjson.decode(response_content) if response_json.status_code ~= nil then response_status = response_json.status_code end if response_json.headers ~= nil then for key, value in pairs(response_json.headers) do header[key] = value end end if response_json.body ~= nil then response_content = response_json.body end end local ctx = ngx.ctx if ctx.delay_response and not ctx.delayed_response then ctx.delayed_response = { status_code = response_status, content = response_content, headers = header, } ctx.delayed_response_callback = flush return end return send(response_status, response_content, header) end return OpenWhisk
function onSay(player, words, param) local hasAccess = player:getGroup():getAccess() local players = Game.getPlayers() local playerCount = Game.getPlayerCount() player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, playerCount .. " players online.") local i = 0 local msg = "" for k, targetPlayer in ipairs(players) do if hasAccess or not targetPlayer:isInGhostMode() then if i > 0 then msg = msg .. ", " end msg = msg .. targetPlayer:getName() .. " [" .. targetPlayer:getLevel() .. "]" i = i + 1 end if i == 10 then if k == playerCount then msg = msg .. "." else msg = msg .. "," end player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, msg) msg = "" i = 0 end end if i > 0 then msg = msg .. "." player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, msg) end return false end
fx_version 'cerulean' game 'gta5' author 'Andreww z7rwastaken <andreww@shadowct.eu>' description 'Scaffold for your TypeScript FiveM resource, replace this with your resource description.' version '1.0.0' name 'ad-scaffold' client_scripts { 'dist/client/*.bundle.js' } server_scripts { 'dist/server/*.bundle.js' }
require "ISUI/ISUIElement" ---@class ISPanel : ISUIElement ISPanel = ISUIElement:derive("ISPanel"); --************************************************************************-- --** ISPanel:initialise --** --************************************************************************-- function ISPanel:initialise() ISUIElement.initialise(self); end function ISPanel:noBackground() self.background = false; end function ISPanel:close() self:setVisible(false); end --************************************************************************-- --** ISPanel:render --** --************************************************************************-- function ISPanel:prerender() if self.background then self:drawRectStatic(0, 0, self.width, self.height, self.backgroundColor.a, self.backgroundColor.r, self.backgroundColor.g, self.backgroundColor.b); self:drawRectBorderStatic(0, 0, self.width, self.height, self.borderColor.a, self.borderColor.r, self.borderColor.g, self.borderColor.b); end end function ISPanel:onMouseUp(x, y) if not self.moveWithMouse then return; end if not self:getIsVisible() then return; end self.moving = false; if ISMouseDrag.tabPanel then ISMouseDrag.tabPanel:onMouseUp(x,y); end ISMouseDrag.dragView = nil; end function ISPanel:onMouseUpOutside(x, y) if not self.moveWithMouse then return; end if not self:getIsVisible() then return; end self.moving = false; ISMouseDrag.dragView = nil; end function ISPanel:onMouseDown(x, y) if not self.moveWithMouse then return true; end if not self:getIsVisible() then return; end if not self:isMouseOver() then return -- this happens with setCapture(true) end self.downX = x; self.downY = y; self.moving = true; self:bringToTop(); end function ISPanel:onMouseMoveOutside(dx, dy) if not self.moveWithMouse then return; end self.mouseOver = false; if self.moving then if self.parent then self.parent:setX(self.parent.x + dx); self.parent:setY(self.parent.y + dy); else self:setX(self.x + dx); self:setY(self.y + dy); self:bringToTop(); end end end function ISPanel:onMouseMove(dx, dy) if not self.moveWithMouse then return; end self.mouseOver = true; if self.moving then if self.parent then self.parent:setX(self.parent.x + dx); self.parent:setY(self.parent.y + dy); else self:setX(self.x + dx); self:setY(self.y + dy); self:bringToTop(); end --ISMouseDrag.dragView = self; end end --************************************************************************-- --** ISPanel:new --** --************************************************************************-- function ISPanel:new (x, y, width, height) local o = {} --o.data = {} o = ISUIElement:new(x, y, width, height); setmetatable(o, self) self.__index = self o.x = x; o.y = y; o.background = true; o.backgroundColor = {r=0, g=0, b=0, a=0.5}; o.borderColor = {r=0.4, g=0.4, b=0.4, a=1}; o.width = width; o.height = height; o.anchorLeft = true; o.anchorRight = false; o.anchorTop = true; o.anchorBottom = false; o.moveWithMouse = false; return o end
-- --The MIT License (MIT) --Copyright (c) 2014 CoolDark -- --See LICENSE file -- addCommandHandler ( "pm", function ( player, cmd, id, ... ) local tableText = { ... } local text = table.concat ( tableText, " " ) if player ~= g_Players[tonumber ( id )] then if g_Players[tonumber ( id )] ~= nil then outputChatBox ( "#F2F200Message to #08F200".. getPlayerName (g_Players[tonumber (id)]) .." #F2F200: " .. text, player, 255, 255, 255, true ) outputChatBox ( "#F2F200Message from #08F200".. getPlayerName ( player ) .." #F2F200: " .. text, g_Players[tonumber (id)], 255, 255, 255, true ) else outputChatBox ( "#F20010[Syntax]: /pm id text", player, 255, 255, 255, true ) end else outputChatBox ( "#F20010You can not write yourself", player, 255, 255, 255, true ) end end ) addCommandHandler ( "pay", function ( player, cmd, id, amount ) if tonumber ( amount ) then if (tonumber ( amount ) > 0 and getPlayerMoney( player ) >= tonumber( amount ) ) then if player ~= g_Players[tonumber (id)] then if g_Players[tonumber ( id )] ~= nil then takePlayerMoney ( player, amount ) outputChatBox ( "#F2F200You paid #08F200".. getPlayerName (g_Players[tonumber (id)]) .." #F2F200: " .. amount .. "$", player, 255, 255, 255, true ) givePlayerMoney ( g_Players[tonumber (id)], amount ) outputChatBox ( "#F2F200You got money from #08F200".. getPlayerName ( player ) .." #F2F200: " .. amount .. "$", g_Players[tonumber (id)], 255, 255, 255, true ) else outputChatBox ( "#F20010[Syntax]: /pay id amount", player, 255, 255, 255, true ) end else outputChatBox ( "#F20010You can not pay yourself", player, 255, 255, 255, true ) end else outputChatBox ( "#F20010You do not have enough money", player, 255, 255, 255, true ) end else outputChatBox ( "#F20010[Syntax]: /pay id amount", player, 255, 255, 255, true ) end end )
local map = require 'utils.map' require("zen-mode").setup{ window = { options = { number = false, relativenumber = false, cursorline = false } } } map('n', '<leader>z', ':ZenMode<cr>')
local RechargePreroItem = class(CommonGameLayer, false); RechargePreroItem.s_controls = { item = 1, bg = 2, }; RechargePreroItem.ctor = function(self, data) super(self, require(RechargeViewPath.."rechargePreroItem") ); self:setSize(170, 140); self.m_data = data; self.m_item = self:findViewById(self.s_controls.item); self.m_bg = self:findViewById(self.s_controls.bg); self:showContent(); end RechargePreroItem.dtor = function(self) ImageCache.getInstance():cleanRef(self); end RechargePreroItem.showContent = function(self) ImageCache.getInstance():request(self.m_data.item_icon, self, self.onUpdateHeadImage); self.m_item:getChildByName("info"):setText(self.m_data.item_name); end RechargePreroItem.onUpdateHeadImage = function(self, url, imagePath) if not url or not imagePath then return; end self.m_bg:setFile(imagePath); end RechargePreroItem.s_controlConfig = { [RechargePreroItem.s_controls.item] = {"item"}, [RechargePreroItem.s_controls.bg] = {"item", "bg"}, }; return RechargePreroItem;
function love.load() end local init=require "init" local version=init.version local alg=require "alg.alg_basic" local inspect=require "inspect" local functions, my_functions=require("alg.functions")() local ffi=require "ffi" local networks=require"network" ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --These are just printing function wrappers for printing to debug. the love print function does not implicitly cast to string so print3 is like a regular print function ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- local function print1(obj) love.graphics.print(inspect(obj)) end local function print2(obj) love.graphics.print(obj) end local function print3(obj) love.graphics.print(tostring(obj)) end ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --just demonstrating some different syntax for defining User created functions (things can get confusing so best choose a syntax and stick with it. Just demoing the versatility and freedom) functions.User{functions.linear, 'g1'} --a simple renaming of a default function (the original remains. Had we used a name already in use for a user defined function the user defined function would be overwritten. Overwriting the default functions is not possible nor is ambiguity possible) my_functions{function(x) return x^2 end, function(x) return 2*x end, 'g2'} local g3=functions.New{math.sqrt, function(x) return .5/math.sqrt(x) end, 'g3'} local two=functions.User{function(x) return 2 end, function(x) return 0 end, 'two'}--we can store the function in a local variable (it will still be stored in the typical table also) functions.User{function(x) return 3 end, function(x) return 0 end, 'three'} functions.New{two*functions.linear, 'g4'}--we can perform algebra with the functions to make new functions!!! local g5=my_functions{my_functions.three*functions.User.g2, 'g5'} local F=alg.New_Function{{functions.User.g1, functions.New.g2, g3, my_functions.g4, g5}} local structure=alg{new='matrix', {{0,0,0,0,0},{.1,0,0,0,0},{.25,2.9,1,0,0},{.3,3.14,0,1,0},{.5,41.2,0,0,1}}}--just one way to make a matrix. There's a much lower level way and another utility function alg.New_Matrix local A=networks{structure, F, ninputs=1, noutputs=3, nhidden=1}--you can make the first arguments named as well (see network class for details) --[[--just a demo for showing how some fancier functions that want further parameters can be defined local alpha=1 local temp=function(x) if x<0 then return alpha*(math.exp(x)-1) else return x end end local elu1=functions.New{temp, function(x) if x<0 then return temp(x)+alpha else return 1 end end, 'elu1'} local elu2=my_functions{temp, function(x) if x<0 then return temp(x)+alpha else return 1 end end, 'elu2'} ]] --[[--here we have the computation that goes on when A(X) is called written out completely X=alg.Square_Matrix_Vector{A[1], X}--if we could we'd overwrite X to save time managing memory, but with matrix multiplication you need to keep values on hand until the end of the calculation so here we just reassign the pointer to X and let the old memory of X get picked up by GC alg.Vector_Function{F, X, A.ninputs, A.ninputs+A.nhidden-1, overwrite=true}--overwite just means that we get rid of the values of X during the operation X=alg.Square_Matrix_Vector{A[1], X} alg.Vector_Function{F, X, overwrite=true} ]] A:Add_Node{nil, {A:Hidden(0)}, in_weights={.5}, out_weights={1.377, .3}}--adds a new memory node connected to the first (at this line the only) hidden node A.memories[1][0]=.15651 A:Add_Node{keep_memories=true} A:Add_Node{{A:Input(0)}, {A:Hidden(0), A:Output(2)}, functions.relu, {.314}, {.367, .52}}--add a node that is connected to the first input, first hidden and last ouput with weights given (so won't delete connection between first input and current hidden node) --an empty call sees ins as nil and will simply make a memory in/out pair with connection weight 1 --A:Add_Link{in_node=A:Input(0), out_node=A:Hidden(0), weight=.5} --add a link from the the input of the first memory to the first hidden node with weight .5 (named arguments optional) --local mem1in, mem1out=A:Memory(0) --get the indices of the in/out pair for the first memory node --local X=alg{new='vector', function() return 1 end, length=A.ninputs}--X is to be the input. We are going to feed 1 to all the inputs of network A. demonstrating vectors can be generated wil functions (functions can take index input to generate vector values based on position) local X=alg{new='vector', {1}}--an identical (cleaner in this case) way to do what's just above --[[ c=alg.Square_Matrix_Vector{A.structure, X} alg.Vector_Function{F, c, A.ninputs, A.ninputs+A.nhidden-1, overwrite=true} c=alg.Square_Matrix_Vector{A.structure, c} alg.Vector_Function{F, c, A.ninputs, A.ninputs+A.nhidden-1, overwrite=true} c=alg.Square_Matrix_Vector{A.structure, c} alg.Vector_Function{F, c, overwrite=true}]] --local output=A(X)--simple syntax. A is the network, X is the input. Call A like the function it is (using metamethod __call to intepret A as a function) c=A(X) function love.draw() --print3(P)--uncomment to see the adjacency matrix --print3(X)--What an input in this example looks like --print3(mem1in..', '..mem1out..'\n') --print3(A.activations[1][A:Hidden(1)].derivative(120561))--new hidden relu node has in fact been added and we can see it's proper derivative evaluated --print3(A.size) print3(c) end
----------------------------------------------------------------------------------------------------------------------- -- RedFlat simple line desktop widget -- ----------------------------------------------------------------------------------------------------------------------- -- Multi monitoring widget ----------------------------------------------------------------------------------------------------------------------- -- Grab environment ----------------------------------------------------------------------------------------------------------------------- local setmetatable = setmetatable local string = string local wibox = require("wibox") local beautiful = require("beautiful") local timer = require("gears.timer") local redutil = require("redflat.util") local svgbox = require("redflat.gauge.svgbox") local textbox = require("redflat.desktop.common.textbox") -- Initialize tables for module ----------------------------------------------------------------------------------------------------------------------- local sline = { mt = {} } -- Generate default theme vars ----------------------------------------------------------------------------------------------------------------------- local function default_style() local style = { lbox = { draw = "by_left", width = 50 }, rbox = { draw = "by_right", width = 50 }, digits = 3, icon = nil, iwidth = 120, unit = { { "B", -1 }, { "KB", 1024 }, { "MB", 1024^2 }, { "GB", 1024^3 } }, color = { main = "#b1222b", wibox = "#161616", gray = "#404040" } } return redutil.table.merge(style, redutil.table.check(beautiful, "desktop.singleline") or {}) end local default_args = { timeout = 60, sensors = {} } -- Create a new widget ----------------------------------------------------------------------------------------------------------------------- function sline.new(args, style) -- Initialize vars -------------------------------------------------------------------------------- local dwidget = {} args = redutil.table.merge(default_args, args or {}) style = redutil.table.merge(default_style(), style or {}) dwidget.style = style -- Initialize layouts -------------------------------------------------------------------------------- dwidget.item = {} dwidget.icon = {} dwidget.area = wibox.layout.align.horizontal() local mid = wibox.layout.flex.horizontal() -- construct line for i, _ in ipairs(args.sensors) do dwidget.item[i] = textbox("", style.rbox) if style.icon then dwidget.icon[i] = svgbox(style.icon) end local boxlayout = wibox.widget({ textbox(string.upper(args.sensors[i].name or "mon"), style.lbox), style.icon and { nil, dwidget.icon[i], nil, expand = "outside", layout = wibox.layout.align.horizontal }, dwidget.item[i], forced_width = style.iwidth, layout = wibox.layout.align.horizontal }) if i == 1 then dwidget.area:set_left(boxlayout) else local space = wibox.layout.align.horizontal() space:set_right(boxlayout) mid:add(space) end end dwidget.area:set_middle(mid) -- Update info function -------------------------------------------------------------------------------- local function set_raw_state(state, crit, i) local text_color = crit and state[1] > crit and style.color.main or style.color.gray local txt = redutil.text.dformat(state[2] or state[1], style.unit, style.digits) dwidget.item[i]:set_text(txt) dwidget.item[i]:set_color(text_color) if dwidget.icon[i] then local icon_color = state.off and style.color.gray or style.color.main dwidget.icon[i]:set_color(icon_color) end end local function item_hadnler(crit, i) return function(state) set_raw_state(state, crit, i) end end local function update() for i, sens in ipairs(args.sensors) do local crit = sens.crit if sens.meter_function then local state = sens.meter_function(sens.args) set_raw_state(state, crit, i) else sens.async_function(item_hadnler(crit, i)) end end end -- Set update timer -------------------------------------------------------------------------------- local t = timer({ timeout = args.timeout }) t:connect_signal("timeout", update) t:start() t:emit_signal("timeout") -------------------------------------------------------------------------------- return dwidget end -- Config metatable to call module as function ----------------------------------------------------------------------------------------------------------------------- function sline.mt:__call(...) return sline.new(...) end return setmetatable(sline, sline.mt)
---@type PresetData local p = Classes.PresetData Data.Presets = { Start = { Battlemage = p:Create("Battlemage", "Class_Battlemage_Start", "Class_Battlemage", "Class_Battlemage_Start_Undead"), Cleric = p:Create("Cleric", "Class_Cleric_Start", "Class_Cleric", "Class_Cleric_Start_Undead"), Enchanter = p:Create("Enchanter", "Class_Enchanter_Start", "Class_Enchanter", "Class_Enchanter_Start_Undead"), Fighter = p:Create("Fighter", "Class_Fighter_Start", "Class_Fighter", "Class_Fighter_Start_Undead"), Inquisitor = p:Create("Inquisitor", "Class_Inquisitor_Start", "Class_Inquisitor", "Class_Inquisitor_Start_Undead"), Knight = p:Create("Knight", "Class_Knight_Start", "Class_Knight", "Class_Knight_Start_Undead"), Metamorph = p:Create("Metamorph", "Class_Metamorph_Start", "Class_Metamorph", "Class_Metamorph_Start_Undead"), Ranger = p:Create("Ranger", "Class_Ranger_Start", "Class_Ranger", "Class_Ranger_Start_Undead"), Rogue = p:Create("Rogue", "Class_Rogue_Start", "Class_Rogue", "Class_Rogue_Start_Undead"), Shadowblade = p:Create("Shadowblade", "Class_Shadowblade_Start", "Class_Shadowblade", "Class_Shadowblade_Start_Undead"), Conjurer = p:Create("Conjurer", "Class_Conjurer_Start", "Class_Conjurer", "Class_Conjurer_Start_Undead"), Wayfarer = p:Create("Wayfarer", "Class_Wayfarer_Start", "Class_Wayfarer", "Class_Wayfarer_Start_Undead"), Witch = p:Create("Witch", "Class_Witch_Start", "Class_Witch", "Class_Witch_Start_Undead"), Wizard = p:Create("Wizard", "Class_Wizard_Start", "Class_Wizard", "Class_Wizard_Start_Undead"), }, Act2 = { Battlemage = p:Create("Battlemage_Act2", "Class_Battlemage_Act2", "Class_Battlemage_Act2"), Cleric = p:Create("Cleric_Act2", "Class_Cleric_Act2", "Class_Cleric_Act2"), Enchanter = p:Create("Enchanter_Act2", "Class_Enchanter_Act2", "Class_Enchanter_Act2"), Fighter = p:Create("Fighter_Act2", "Class_Fighter_Act2", "Class_Fighter_Act2"), Inquisitor = p:Create("Inquisitor_Act2", "Class_Inquisitor_Act2", "Class_Inquisitor_Act2"), Knight = p:Create("Knight_Act2", "Class_Knight_Act2", "Class_Knight_Act2"), Metamorph = p:Create("Metamorph_Act2", "Class_Metamorph_Act2", "Class_Metamorph_Act2"), Ranger = p:Create("Ranger_Act2", "Class_Ranger_Act2", "Class_Ranger_Act2"), Rogue = p:Create("Rogue_Act2", "Class_Rogue_Act2", "Class_Rogue_Act2"), Shadowblade = p:Create("Shadowblade_Act2", "Class_Shadowblade_Act2", "Class_Shadowblade_Act2"), Conjurer = p:Create("Conjurer_Act2", "Class_Conjurer_Act2", "Class_Conjurer_Act2"), Wayfarer = p:Create("Wayfarer_Act2", "Class_Wayfarer_Act2", "Class_Wayfarer_Act2"), Witch = p:Create("Witch_Act2", "Class_Witch_Act2", "Class_Witch_Act2"), Wizard = p:Create("Wizard_Act2", "Class_Wizard_Act2", "Class_Wizard_Act2"), }, Preview = { Battlemage = p:Create("Battlemage", "Class_Battlemage", "Class_Battlemage_Act2", "", true), Cleric = p:Create("Cleric", "Class_Cleric", "Class_Cleric_Act2", "", true), Enchanter = p:Create("Enchanter", "Class_Enchanter", "Class_Enchanter_Act2", "", true), Fighter = p:Create("Fighter", "Class_Fighter", "Class_Fighter_Act2", "", true), Inquisitor = p:Create("Inquisitor", "Class_Inquisitor", "Class_Inquisitor_Act2", "", true), Knight = p:Create("Knight", "Class_Knight", "Class_Knight_Act2", "", true), Metamorph = p:Create("Metamorph", "Class_Metamorph", "Class_Metamorph_Act2", "", true), Ranger = p:Create("Ranger", "Class_Ranger", "Class_Ranger_Act2", "", true), Rogue = p:Create("Rogue", "Class_Rogue", "Class_Rogue_Act2", "", true), Shadowblade = p:Create("Shadowblade", "Class_Shadowblade", "Class_Shadowblade_Act2", "", true), Conjurer = p:Create("Conjurer", "Class_Conjurer", "Class_Conjurer_Act2", "", true), Wayfarer = p:Create("Wayfarer", "Class_Wayfarer", "Class_Wayfarer_Act2", "", true), Witch = p:Create("Witch", "Class_Witch", "Class_Witch_Act2", "", true), Wizard = p:Create("Wizard", "Class_Wizard", "Class_Wizard_Act2", "", true), } } ---@param group string Start|Act2|Preview ---@param id string The preset's ClassType value. ---@param data PresetData function Data.AddPreset(group, id, data) if Data.Presets[group] == nil then Data.Presets[group] = {} end Data.Presets[group][id] = data end
require("mineunit") mineunit("core") mineunit("player") describe("CNC API", function() fixture("default") fixture("basic_materials") fixture("digilines") sourcefile("init") -- Our player Sam will be helping, he promised to place some nodes local Sam = Player("Sam") -- Construct test world with CNC machines world.clear() local pos = {x=3,y=2,z=1} local node = {name = "technic:cnc_mk2", param2 = 0} world.place_node(pos, table.copy(node), Sam) minetest.get_meta(pos):set_string("channel", "ch1") local action = minetest.registered_nodes["technic:cnc_mk2"].digilines.effector.action local program = "stick" local size = 1 it("handles invalid messages", function() -- This is meant to only check simple crashes action(pos, table.copy(node), "ch1", nil) action(pos, table.copy(node), "ch1", 0) action(pos, table.copy(node), "ch1", true) action(pos, table.copy(node), "ch1", false) action(pos, table.copy(node), "ch1", {}) action(pos, table.copy(node), "ch1", "") action(pos, table.copy(node), "ch1", math.huge) action(pos, table.copy(node), "ch1", {size=true,program={}}) action(pos, table.copy(node), "", nil) action(pos, table.copy(node), "", 0) action(pos, table.copy(node), "", true) action(pos, table.copy(node), "", false) action(pos, table.copy(node), "", {}) action(pos, table.copy(node), "", "") action(pos, table.copy(node), "", math.huge) action(pos, table.copy(node), "", {size=true,program={}}) end) it("sets program and size", function() action(pos, table.copy(node), "ch1", { program = "cylinder", size = 1 }) local meta = minetest.get_meta(pos) assert.equals("cylinder", meta:get("program")) assert.equals(1, meta:get_int("size")) end) it("disables machine", function() action(pos, table.copy(node), "ch1", "disable") local meta = minetest.get_meta(pos) assert.is_false(technic_cnc.is_enabled(meta)) end) it("enables machine", function() action(pos, table.copy(node), "ch1", "enable") local meta = minetest.get_meta(pos) assert.is_true(technic_cnc.is_enabled(meta)) end) it("returns programs", function() local count = #digilines._msg_log action(pos, table.copy(node), "ch1", "programs") assert.equals(count + 1, #digilines._msg_log) local response = digilines._msg_log[#digilines._msg_log] assert.is_table(response) assert.is_table(response.msg) assert.equals("ch1", response.channel) assert.not_nil(response.msg.sphere) end) end)
newTalentType{ type="thief/thief", name = "thief", description = "Standard thief abilities" } newTalent{ name = "Pick Pockets", type = {"thief/thief", 1}, info = "Liberate items from the confines of pockets", mode = "activated", -- Naw, allow pick pockets while Hide is on, I like that tactic -- on_pre_use = function(self, t) -- if self:attr("never_move") then return false end -- return true -- end, } newTalent{ name = "Sap", short_name = "Sap", type = {"thief/thief", 1}, info = "Render unsuspecting target unconscious with a blow to the head", mode = "activated", } newTalent{ name = "Backstab", short_name = "Backstab", type = {"thief/thief", 1}, info = "Attack an unsupecting foe from behind", mode = "activated", }
local util = require("spec.util") local script = require("cyan.script") describe("script", function() describe("load", function() it("should load a script from a given path", function() local dirname = util.write_tmp_dir(finally, { ["foo.lua"] = [[print("foo")]], }) local ok, err = script.load(dirname .. util.path_sep .. "foo.lua", {}) assert.truthy(ok) assert.is_nil(err) end) it("should return nil, err if a script couldn't be loaded", function() local ok, err = script.load("foo.lua", {}) assert.falsy(ok) assert.is.string(err) end) it("should report when a .tl script has type errors", function() local scriptname = "foo.tl" local dirname = util.write_tmp_dir(finally, { [scriptname] = [[local x: integer = 1.2]], }) local ok, err = script.load(dirname .. util.path_sep .. scriptname, {}) assert.falsy(ok) assert.is.table(err) end) end) end)
local vector_meta = global_metatable("vector") local quat_meta = global_metatable("quaternion") local transform_meta = global_metatable("transformation") function IsTransformation(v) return type(v) == "table" and v.pos and v.rot end function MakeTransformation(t) setmetatable(t.pos, vector_meta) setmetatable(t.rot, quat_meta) return setmetatable(t, transform_meta) end function Transformation(pos, rot) return MakeTransformation { pos = pos, rot = rot } end function transform_meta:__unserialize(data) local x, y, z, i, j, k, r = data:match("([-0-9.]*);([-0-9.]*);([-0-9.]*);([-0-9.]*);([-0-9.]*);([-0-9.]*);([-0-9.]*)") self.pos = Vector(tonumber(x), tonumber(y), tonumber(z)) self.rot = Quaternion(tonumber(i), tonumber(j), tonumber(k), tonumber(r)) return self end function transform_meta:__serialize() return table.concat(self.pos, ";") .. ";" .. table.concat(self.rot, ";") end function transform_meta:Clone() return MakeTransformation {pos = vector_meta.Clone(self.pos), rot = quat_meta.Clone(self.rot)} end local TransformStr = TransformStr function transform_meta:__tostring() return TransformStr(self) end local TransformToLocalPoint = TransformToLocalPoint local TransformToLocalTransform = TransformToLocalTransform local TransformToLocalVec = TransformToLocalVec local TransformToParentPoint = TransformToParentPoint local TransformToParentTransform = TransformToParentTransform local TransformToParentVec = TransformToParentVec function transform_meta.__add(a, b) if not IsTransformation(b) then if IsVector(b) then b = Transformation(b, QUAT_ZERO) elseif IsQuaternion(b) then b = Transformation(VEC_ZERO, b) end end return MakeTransformation(TransformToParentTransform(a, b)) end function transform_meta:ToLocal(o) if IsTransformation(o) then return MakeTransformation(TransformToLocalTransform(self, o)) else return MakeVector(TransformToLocalPoint(self, o)) end end function transform_meta:ToLocalDir(o) return MakeVector(TransformToLocalVec(self, o)) end function transform_meta:ToGlobal(o) if IsTransformation(o) then return MakeTransformation(TransformToParentTransform(self, o)) else return MakeVector(TransformToParentPoint(self, o)) end end function transform_meta:ToGlobalDir(o) return MakeVector(TransformToParentVec(self, o)) end function transform_meta:Raycast(dist, mul, radius, rejectTransparent) local dir = TransformToParentVec(self, VEC_FORWARD) if mul then vector_meta.Mul(dir, mul) end local hit, dist2, normal, shape = QueryRaycast(self.pos, dir, dist, radius, rejectTransparent) return { hit = hit, dist = dist2, normal = normal, shape = shape, hitpos = vector_meta.__add(self.pos, vector_meta.Mul(dir, hit and dist2 or dist)) } end
-------------------------------------------------------------------------------- -- LAYOUTS -- SINTAX: -- { -- name = "App name" ou { "App name", "App name" } -- title = "Window title" (optional) -- func = function(index, win) -- COMMANDS -- end -- }, -- -- It searches for application "name" and call "func" for each window object -------------------------------------------------------------------------------- local layouts = { { name = {"Emacs"}, func = function(index, win) win:moveToScreen(monitor_1, false, true) end }, { name = {"Slack"}, func = function(index, win) if (#hs.screen.allScreens() > 1) then -- first space on 2nd monitor spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[2]:spaces()[1]) win:moveToScreen(monitor_2, false, true) else -- first empty space spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[1]:spaces()[3]) end hsm.windows.moveTopLeft(win) end }, { name = {"Microsoft Outlook"}, func = function(index, win) if (#hs.screen.allScreens() > 1) then spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[2]:spaces()[1]) win:moveToScreen(monitor_2, false, true) else -- first empty space spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[1]:spaces()[3]) end hsm.windows.moveBottomRight(win) end }, { name = {"Todoist"}, func = function(index, win) if (#hs.screen.allScreens() > 1) then win:moveToScreen(monitor_2, false, true) end hsm.windows.moveTopRight(win) end }, { name = {"Remember The Milk"}, func = function(index, win) if (#hs.screen.allScreens() > 1) then win:moveToScreen(monitor_2, false, true) end hsm.windows.moveTopRight(win) end }, { name = "Adium", title = "Contacts", func = function(index, win) if (#hs.screen.allScreens() > 1) then -- second space on 1st monitor spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[1]:spaces()[2]) end hsm.windows.moveTopLeft(win) end }, { name = {"GIMP"}, func = function(index, win) -- third space on 1st monitor spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[1]:spaces()[3]) end }, } return layouts
--[[ 3p8_collector_pizza Uses: It is a pizza box! Todo: ]] AddCSLuaFile() ENT.Base = "3p8_collector" ENT.HeldObject = "3p8_pizza" ENT.ItemName = "Pizza Box" ENT.ItemModel = "models/props_c17/consolebox01a.mdl" --money printer model xD ENT.Material = "models/items/boxsniperrounds" ENT.MaxCount = 3 ENT.Health = 100
local eonz = require 'eonz' local table = eonz.pf.table local string = eonz.pf.string local Production = require 'eonz.lexer.production' local Grammar = eonz.class "eonz::lexer::Grammar" do function Grammar.new(productions, opt) for i, prod in ipairs(productions) do if getmetatable(prod) ~= Production then local id, alts, opt = eonz.table.unpack(prod) -- use any key-value pairs defined directly in -- the production table as arguments to the -- production options table opt = table.merge({}, prod, opt or {}) for i in ipairs(prod) do opt[i] = nil end productions[i] = Production(id, alts, opt) end end return setmetatable({ _productions = productions or {} }, Grammar) end function Grammar:production_for(id) for i, prod in ipairs(self:productions()) do if prod:id(id) then return prod end end return nil end function Grammar:productions() return self._productions end function Grammar:add(production) table.insert(self._productions, production) end end return Grammar
function halve(a) return a/2 end function double(a) return a*2 end function isEven(a) return a%2 == 0 end function ethiopian(x, y) local result = 0 while (x >= 1) do if not isEven(x) then result = result + y end x = math.floor(halve(x)) y = double(y) end return result; end print(ethiopian(17, 34))
local sk1 = hslk_ability_ring({ Name = "月神强击", Art = "ReplaceableTextures\\PassiveButtons\\PASBTNTrueShot.blp", TargetArt = "Abilities\\Spells\\NightElf\\TrueshotAura\\TrueshotAura.mdl", Area = { 600 }, Hotkey = "E", race = "human", _ring = { attr = { attack_green = "+90", aim = "+20" }, }, }) hslk_hero({ Name = "白虎女祭祀", Propernames = "米拉", Ubertip = hcolor.sky("特性:典雅之月") .. "|n" .. hcolor.grey("侍奉月神的骑白虎女弓手,在月光的照耀下优雅游击战斗"), Art = "ReplaceableTextures\\CommandButtons\\BTNPriestessOfTheMoon.blp", file = "units\\nightelf\\HeroMoonPriestess\\HeroMoonPriestess", unitSound = "HeroMoonPriestess", movetp = "foot", moveHeight = 0.00, spd = 290, -- 移动速度 rangeN1 = 600, -- 攻击范围 dmgplus1 = 21, -- 基础攻击 weapTp1 = CONST_WEAPON_TYPE.missile.value, -- 攻击类型 weapType1 = nil, -- 攻击类型 Missileart_1 = "Abilities\\Weapons\\MoonPriestessMissile\\MoonPriestessMissile.mdl", -- 箭矢 cool1 = 1.7, -- 攻击周期 backSw1 = 0.7, -- 攻击后摇 dmgpt1 = 0.3, -- 攻击前摇 modelScale = 1.00, scale = 2.25, Primary = "INT", STR = 22, AGI = 30, INT = 30, STRplus = 2.1, AGIplus = 2.5, INTplus = 2.5, race = "human", heroAbilList = "", goldcost = 0, lumbercost = 0, fused = 0, abilList = string.implode(",", { "AInv", sk1._id }), _feature = "典雅之月", })
-- Evaluate performance of trained model. -- -- Yujia Li, 10/2015 -- require 'lfs' babi_data = require 'babi_data' seq_data = require 'seq_data' eval_util = require 'eval_util' ggnn = require '../ggnn' cmd = torch.CmdLine() cmd:option('-modeldir', '', 'Path to the root model output directory.') cmd:option('-mb', 10, 'Size of the minibatch, this should not affect the final performance.') cmd:option('-nthreads', 1, 'Number of threads to use.') cmd:option('-datafile', '', 'Path to the data file to evaluate on') opt = cmd:parse(arg) d = torch.load(opt.modeldir .. '/params') opt.nsteps = d.nsteps opt.annotationdim = d.annotationdim opt.mode = d.mode print('') print(opt) print('') torch.setnumthreads(opt.nthreads) test_data = babi_data.load_graphs_from_file(opt.datafile) uniform_length = babi_data.targets_are_uniform_length(test_data) if uniform_length then print('Sequences are of the same length') else print('Sequence lengths are not uniform') end test_data = babi_data.data_list_to_standard_data_seq(test_data, opt.annotationdim) seq_data.add_end_node(test_data, false) n_tasks = #test_data total_err = 0 total_count = 0 for task_id=1,n_tasks do local timer = torch.Timer() if lfs.attributes(opt.modeldir .. '/' .. task_id .. '/model_best') ~= nil then model_file = opt.modeldir .. '/' .. task_id .. '/model_best' elseif lfs.attributes(opt.modeldir .. '/' .. task_id .. '/model_end') ~= nil then model_file = opt.modeldir .. '/' .. task_id .. '/model_end' else error('No model_best nor model_end available for task ' .. task_id) end print('Loading model from ' .. model_file) if opt.mode == 'seqnode' then net = ggnn.load_node_selection_seq_ggnn_from_file(model_file) elseif opt.mode == 'shareprop_seqnode' then net = ggnn.load_node_selection_seq_share_prop_ggnn_from_file(model_file) else error('Unknown mode ' .. opt.mode .. '.') end w, _ = net:getParameters() print('#parameters: ' .. w:nElement()) if uniform_length then err_rate, err, total = eval_util.eval_seq_classification(net, test_data[task_id], opt.mb, opt.nsteps) else err_rate, err, total = eval_util.eval_seq_classification_per_example(net, test_data[task_id], opt.nsteps) end print(string.format('Task %d error rate: %d/%d=%.4f [%.2fs]', task_id, err, total, err_rate, timer:time().real)) total_err = total_err + err total_count = total_count + total end print('======================') print(string.format('Total error rate: %d/%d=%.4f', total_err, total_count, total_err / total_count))
-- -- luaunit.lua -- -- Description: A unit testing framework -- Homepage: http://phil.freehackers.org/luaunit/ -- Initial author: Ryu, Gwang (http://www.gpgstudy.com/gpgiki/LuaUnit) -- Lot of improvements by Philippe Fremy <phil@freehackers.org> -- More improvements by Ryan P. <rjpcomputing@gmail.com> -- Further improvements by J. 'KwirkyJ' Smith <kwirkyj.smith0@gmail.com> -- Version: 3.0 -- License: X11 License, see LICENSE.txt ---- SETUP ------------------------------------------------------------------- -- lua 5.2+ deprecates unpack in favor of table.unpack unpack = table.unpack or unpack -- lua 5.2+ deprecates/removes loadstring() for load() loadstring = loadstring or load -- Some people like assertEquals( actual, expected ) -- and some people prefer assertEquals( expected, actual ). -- Set to false for the former. local USE_EXPECTED_ACTUAL = false local DELTA_TOLERANCE = 1e-12 local VERBOSITY = 1 local classrunner = require 'luaunit.classrunner' local assertive = require 'assertive' --local StringBuffer = require 'lua_stringbuffer' local toString = require('moretables')['tostring'] local strsplit = require('luaunit.lib.stringsplit')['split'] ---- HELPER FUNCTIONS -------------------------------------------------------- ---Wrapper for tostring to differentiate string types. -- @param v Value to convert to string. -- @return {String} tostring(v) iff not already a string; -- else '<v>'. local function wrapValue(v) if type(v) == 'string' then return "'"..v.."'" end return toString(v) end --[[ -- Order of testing local function __genOrderedIndex( t ) local orderedIndex = {} for key,_ in pairs(t) do table.insert( orderedIndex, key ) end -- assumption: only numbers and strings can be keys (values in orderedI) -- if same type, use '<' -- else, numbers come first local function comp(a,b) if type(a) == type(b) then return a < b elseif type(a) == 'number' then return true else return false end end table.sort( orderedIndex, comp ) return orderedIndex end ---Equivalent of the next() function of table iteration, but returns the -- keys in the alphabetic order. We use a temporary ordered key table that -- is stored in the table being iterated. local function orderedNext(t, state) --print("orderedNext: state = "..tostring(state) ) if state == nil then -- the first time, generate the index t.__orderedIndex = __genOrderedIndex( t ) local key = t.__orderedIndex[1] return key, t[key] end -- fetch the next value local key = nil for i = 1,#t.__orderedIndex do if t.__orderedIndex[i] == state then key = t.__orderedIndex[i+1] end end if key then return key, t[key] end -- no more value to return, cleanup t.__orderedIndex = nil return end ---Iterator function to go over a table in predictable sequence (alphabetic) ; -- called in the same manner as pairs(). orderedPairs = function(t) -- filling forward definition; is local return orderedNext, t, nil end --]] --[[ ---Removes some information from stacktrace to be relevant to the tests. local function strip_luaunit_stack(stack_trace) local stack_list = strsplit( "\n", stack_trace ) local strip_end = nil for i = #stack_list,1,-1 do -- a bit rude but it works ! if string.find(stack_list[i],"[C]: in function `xpcall'",0,true) then strip_end = i - 2 end end if strip_end then table.setn( stack_list, strip_end ) end local stack_trace = table.concat( stack_list, "\n" ) return stack_trace end --]] ---Trim a string like -- 'test_file.lua:125: assertion failed!\n' to -- 'assertion failed!' -- @param s {String} -- @error Raised if s is not a {String}. -- @return {String} local function trimErrMsg(s) assert (type(s) == 'string', 's must be a string!') s = s:gsub('^%s*(.-)%s*$', '%1') -- remove whitspace return s:gsub('.*:%d+: (.-)', '%1') -- assuming ':%d+: ' is the line num end ---- ASSERT ROUTINES --------------------------------------------------------- ---Register all the asserts to the global namespace with both -- camelCase and underscore_lowercase options: -- e.g., assertError(f, ...) and assert_error(f, ...). -- assertAlmostEquals -- assertError -- assertEquals -- assertNotEquals -- assert<Type> (for all standard types) -- assertNot<Type> (for all standard types) for k,v in pairs(assertive) do if type(k) == 'string' and string.sub(k, 1, 6) == 'assert' then _G[k] = v _G[k:gsub('(%u)', '_%1'):lower()] = v end end ---- LUAUNIT CLASS ----------------------------------------------------------- local LuaUnit = { _VERSION = "3.0.0" } --[[ ---Get the current verbosity level. -- LuaUnit:getVerbosity() --@return {Number} >= 0. local function getVerbosity(self) return VERBOSITY end LuaUnit.getVerbosity = getVerbosity LuaUnit.get_verbosity = getVerbosity ---Set the verbosity of output. -- LuaUnit:setVerbosity(1) -- @param lvl {number} If > 0 there will be verbose output (default of 0). local function setVerbosity(self, lvl) lvl = lvl or 0 assert(type(lvl) == 'number', 'Verbosity must be a number') self.result.verbosity = lvl VERBOSITY = lvl assertive:setVerbosity(lvl) end LuaUnit.setVerbosity = setVerbosity LuaUnit.set_verbosity = setVerbosity LuaUnit.SetVerbosity = setVerbosity --]] --[[ ---Get the current verbosity level. -- LuaUnit:getDeltaTolerance() --@return {Number} >= 0. local function getDeltaTolerance(self) return DELTA_TOLERANCE end LuaUnit.getDeltaTolerance = getDeltaTolerance LuaUnit.get_delta_tolerance = getDeltaTolerance ---Set the default maximum delta in assertAlmostEquals. -- LuaUnit:setDefaultTolerance(1e-7) -- @param n {Number} (default of 1e-12). local function setDeltaTolerance(self, n) n = n or 1e-12 assert(type(DELTA_TOLERANCE) == 'number', 'must be number') DELTA_TOLERANCE = n assertive:setDelta(n) end LuaUnit.setDeltaTolerance = setDeltaTolerance LuaUnit.set_delta_tolerance = setDeltaTolerance --]] --[[ ---Set the inner variable to configure param order in assert[Not]Equals. -- LuaUnit:setExpectedActual(true) -- @param b {Boolean} (default of true). local function setExpectedActual(self, b) -- I know self is unused, and YOU know self is unused, -- but the 'self' variable makes the 'self-modifying colon' sensible. if type(b) ~= 'boolean' then b = true end b = b end LuaUnit.setExpectedActual = setExpectedActual LuaUnit.set_expected_actual = setExpectedActual --]] local function runAllTests(runners) local runsum, failsum, byesum, failslist = 0, 0, 0, {} for _, runner in ipairs(runners) do runner:run() local runcount, fails, byecount = runner:getResults() runsum = runsum + runcount failsum = failsum + #fails byesum = byesum + byecount if #fails > 0 then failslist[#failslist+1] = {runner:getName(), fails} end end return runsum, failsum, byesum, failslist end local function printFailures(faillist, verbosity) if #faillist == 0 then return end print('=========================================================') print('Failed tests:\n-------------') local classname, fails, methodname, message, stack for i=1, #faillist do classname, fails = faillist[i][1], faillist[i][2] for j=1, #fails do methodname, message, stack = fails[j][1], fails[j][2], fails[j][3] print('>>> ' .. classname .. ':' .. methodname) print(message) print('stack traceback:') print(stack) end end end local function printFinalSummary(total, failed, byes) local s, ratio print('=========================================================') if total == 0 or failed == 0 then ratio = 1 else ratio = ((total-failed) / total) end s = string.format('Success: %0.0f%%\t(%d/%d)', 100*ratio, total-failed, total) if byes > 0 then s = string.format('%s\t(skipped: %d)', s, byes) end print(s) end ---Run a test suite. -- LuaUnit:run([{arg | ...}]) -- LuaUnit:run('TestClass', 'SomeTestClass', ...) -- @param arg {Table} Optional (recommended) parameter to pass command- -- line arguments; used to specify test classes: -- in test_file.lua: `LuaUnit:run(arg)` -- in shell: `$ lua test_file.lua TestClass1 TestClass2` -- @param ... {String[, String]} Optional Sequence of strings that match -- 'class names' in your test file, e.g. TestToto1; -- TODO: alternatively, Class:Method names, e.g. TestToto1:test_kansas LuaUnit.run = function(self, ...) local args, runners = {...}, {} if args[1] and type(args[1]) == 'table' then args = args[1] -- assumes is the passed-through arg table end if #args > 0 then for _,v in ipairs(args) do if type(_G[v]) == 'table' then runners[#runners + 1] = classrunner.new(v) end end else for k,v in pairs(_G) do if type(v) == "table" and (string.sub(k, 1, 4) == "Test" or string.sub(k, 1, 4) == "test") then runners[#runners + 1] = classrunner.new(k) end end end local runsum, failsum, byesum, failslist = runAllTests(runners) printFailures(failslist) printFinalSummary(runsum, failsum, byesum) end LuaUnit.Run = LuaUnit.run -- alias -- register below routines to verify correctness --LuaUnit._strsplit = strsplit LuaUnit._toString = toString LuaUnit._wrapValue = wrapValue LuaUnit._trimErrMsg = trimErrMsg return LuaUnit
-- ======= Copyright (c) 2003-2012, Unknown Worlds Entertainment, Inc. All rights reserved. ===== -- -- lua\ArmsLab.lua -- -- Created by: Charlie Cleveland (charlie@unknownworlds.com) -- -- ========= For more information, visit us at http://www.unknownworlds.com ===================== Script.Load("lua/Mixins/ClientModelMixin.lua") Script.Load("lua/LiveMixin.lua") Script.Load("lua/PointGiverMixin.lua") Script.Load("lua/AchievementGiverMixin.lua") Script.Load("lua/GameEffectsMixin.lua") Script.Load("lua/SelectableMixin.lua") Script.Load("lua/FlinchMixin.lua") Script.Load("lua/LOSMixin.lua") Script.Load("lua/TeamMixin.lua") Script.Load("lua/CorrodeMixin.lua") Script.Load("lua/ConstructMixin.lua") Script.Load("lua/ResearchMixin.lua") Script.Load("lua/RecycleMixin.lua") Script.Load("lua/CombatMixin.lua") Script.Load("lua/CommanderGlowMixin.lua") Script.Load("lua/ScriptActor.lua") Script.Load("lua/RagdollMixin.lua") Script.Load("lua/NanoShieldMixin.lua") Script.Load("lua/ObstacleMixin.lua") Script.Load("lua/WeldableMixin.lua") Script.Load("lua/UnitStatusMixin.lua") Script.Load("lua/DissolveMixin.lua") Script.Load("lua/GhostStructureMixin.lua") Script.Load("lua/PowerConsumerMixin.lua") Script.Load("lua/MapBlipMixin.lua") Script.Load("lua/VortexAbleMixin.lua") Script.Load("lua/InfestationTrackerMixin.lua") Script.Load("lua/ParasiteMixin.lua") class 'ArmsLab' (ScriptActor) ArmsLab.kMapName = "armslab" ArmsLab.kModelName = PrecacheAsset("models/marine/arms_lab/arms_lab.model") local kAnimationGraph = PrecacheAsset("models/marine/arms_lab/arms_lab.animation_graph") local kHaloCinematic = PrecacheAsset("cinematics/marine/arms_lab/arms_lab_holo.cinematic") local kHaloAttachPoint = "ArmsLab_hologram" local networkVars = { } AddMixinNetworkVars(BaseModelMixin, networkVars) AddMixinNetworkVars(ClientModelMixin, networkVars) AddMixinNetworkVars(LiveMixin, networkVars) AddMixinNetworkVars(GameEffectsMixin, networkVars) AddMixinNetworkVars(FlinchMixin, networkVars) AddMixinNetworkVars(TeamMixin, networkVars) AddMixinNetworkVars(LOSMixin, networkVars) AddMixinNetworkVars(CorrodeMixin, networkVars) AddMixinNetworkVars(ConstructMixin, networkVars) AddMixinNetworkVars(ResearchMixin, networkVars) AddMixinNetworkVars(RecycleMixin, networkVars) AddMixinNetworkVars(CombatMixin, networkVars) AddMixinNetworkVars(NanoShieldMixin, networkVars) AddMixinNetworkVars(ObstacleMixin, networkVars) AddMixinNetworkVars(DissolveMixin, networkVars) AddMixinNetworkVars(GhostStructureMixin, networkVars) AddMixinNetworkVars(PowerConsumerMixin, networkVars) AddMixinNetworkVars(VortexAbleMixin, networkVars) AddMixinNetworkVars(SelectableMixin, networkVars) AddMixinNetworkVars(ParasiteMixin, networkVars) function ArmsLab:OnCreate() ScriptActor.OnCreate(self) InitMixin(self, BaseModelMixin) InitMixin(self, ClientModelMixin) InitMixin(self, LiveMixin) InitMixin(self, GameEffectsMixin) InitMixin(self, FlinchMixin) InitMixin(self, TeamMixin) InitMixin(self, PointGiverMixin) InitMixin(self, AchievementGiverMixin) InitMixin(self, SelectableMixin) InitMixin(self, EntityChangeMixin) InitMixin(self, LOSMixin) InitMixin(self, CorrodeMixin) InitMixin(self, ConstructMixin) InitMixin(self, ResearchMixin) InitMixin(self, RecycleMixin) InitMixin(self, CombatMixin) InitMixin(self, RagdollMixin) InitMixin(self, ObstacleMixin) InitMixin(self, DissolveMixin) InitMixin(self, GhostStructureMixin) InitMixin(self, VortexAbleMixin) InitMixin(self, PowerConsumerMixin) InitMixin(self, ParasiteMixin) if Client then InitMixin(self, CommanderGlowMixin) self.deployed = false end self:SetLagCompensated(false) self:SetPhysicsType(PhysicsType.Kinematic) self:SetPhysicsGroup(PhysicsGroup.BigStructuresGroup) end function ArmsLab:OnInitialized() ScriptActor.OnInitialized(self) InitMixin(self, WeldableMixin) InitMixin(self, NanoShieldMixin) if Server then -- This Mixin must be inited inside this OnInitialized() function. if not HasMixin(self, "MapBlip") then InitMixin(self, MapBlipMixin) end InitMixin(self, StaticTargetMixin) InitMixin(self, InfestationTrackerMixin) elseif Client then InitMixin(self, UnitStatusMixin) InitMixin(self, HiveVisionMixin) end self:SetModel(ArmsLab.kModelName, kAnimationGraph) end function ArmsLab:GetReceivesStructuralDamage() return true end function ArmsLab:GetDamagedAlertId() return kTechId.MarineAlertStructureUnderAttack end function ArmsLab:GetTechButtons(techId) return { kTechId.SentryArmorTech, kTechId.SentryDamageTech, kTechId.ShieldRechargeTech, kTechId.ShieldCapacityTech, kTechId.None, kTechId.None, kTechId.None, kTechId.None } end if Client then function ArmsLab:OnTag(tagName) PROFILE("ArmsLab:OnTag") if tagName == "deploy_end" then self.deployed = true end end function ArmsLab:OnUpdateRender() if not self.haloCinematic then self.haloCinematic = Client.CreateCinematic(RenderScene.Zone_Default) self.haloCinematic:SetCinematic(kHaloCinematic) self.haloCinematic:SetParent(self) self.haloCinematic:SetAttachPoint(self:GetAttachPointIndex(kHaloAttachPoint)) self.haloCinematic:SetCoords(Coords.GetIdentity()) self.haloCinematic:SetRepeatStyle(Cinematic.Repeat_Endless) end self.haloCinematic:SetIsVisible(self.deployed and self:GetIsPowered()) end end function ArmsLab:OnDestroy() ScriptActor.OnDestroy(self) if Client and self.haloCinematic then Client.DestroyCinematic(self.haloCinematic) self.haloCinematic = nil end end function ArmsLab:GetRequiresPower() return true end Shared.LinkClassToMap("ArmsLab", ArmsLab.kMapName, networkVars)
require 'olua.lexer' module(..., package.seeall) local result local recursivelyunparse local recursivelyunparsebinop local function emit(s) result[#result + 1] = s end local typetable = { chunk = function(ast) for _, statement in ipairs(ast) do recursivelyunparse(statement) end end, doend = function(ast) emit("do") recursivelyunparse(ast.chunk) emit("end") end, ifelseend = function(ast) for i, condition in ipairs(ast) do if (i == 1) then emit("if") recursivelyunparse(condition.condition) emit("then") else if condition.condition then emit("elseif") recursivelyunparse(condition.condition) emit("then") else emit("else") end end recursivelyunparse(condition.chunk) end emit("end") end, forend = function(ast) emit("for") recursivelyunparse(ast.var) emit("=") recursivelyunparse(ast.low) emit(",") recursivelyunparse(ast.high) if ast.step then emit(",") recursivelyunparse(ast.step) end emit("do") recursivelyunparse(ast.chunk) emit("end") end, forinend = function(ast) emit("for") recursivelyunparse(ast.var) emit("in") recursivelyunparse(ast.iterator) emit("do") recursivelyunparse(ast.chunk) emit("end") end, whiledoend = function(ast) emit("while") recursivelyunparse(ast.condition) emit("do") recursivelyunparse(ast.chunk) emit("end") end, repeatuntil = function(ast) emit("repeat") recursivelyunparse(ast.chunk) emit("until") recursivelyunparse(ast.condition) end, ["return"] = function(ast) emit("return") if ast.value then recursivelyunparse(ast.value) end end, ["break"] = function(ast) emit("break") end, functioncall = function(ast) recursivelyunparse(ast.value) emit("(") recursivelyunparse(ast.args) emit(")") end, functiondef = function(ast) if not ast.name then emit("(") end emit("function") if ast.name then recursivelyunparse(ast.name) end emit("(") recursivelyunparse(ast.args) emit(")") recursivelyunparse(ast.chunk) emit("end") if not ast.name then emit(")") end end, assignment = function(ast) recursivelyunparse(ast.left) if ast.right then emit("=") recursivelyunparse(ast.right) end end, list = function(ast) for i = 1, #ast do local exp = ast[i] if (i > 1) then emit(",") end recursivelyunparse(exp) end end, tableliteral = function(ast) emit("{") for i = 1, #ast do local entry = ast[i] if (i > 1) then emit(",") end if entry.key then if (entry.key.type == "identifier") then emit(entry.key) else emit("[") recursivelyunparse(entry.key) emit("]") end emit("=") end recursivelyunparse(entry.value) end emit("}") end, binop = function(ast) recursivelyunparsebinop(ast.left, ast.precedence) emit(ast.operator) recursivelyunparsebinop(ast.right, ast.precedence) end, unop = function(ast) emit(ast.operator) recursivelyunparsebinop(ast.value, ast.precedence) end, deref = function(ast) recursivelyunparse(ast.left) emit("[") recursivelyunparse(ast.right) emit("]") end, ["local"] = function(ast) emit("local") recursivelyunparse(ast.value) end, leaf = function(ast) emit(ast.value) end, olua_methodcall = function(ast) emit("[object=") recursivelyunparse(ast.object) emit(" selector=") emit(ast.selector) emit(" args={") for i = 1, #ast.args do if (i > 1) then emit(",") end recursivelyunparse(ast.args[i]) end emit("}]") end } recursivelyunparsebinop = function(ast, thisprecedence) if (ast.type == "binop") and (not ast.precedence or not thisprecedence or (ast.precedence < thisprecedence)) then emit("(") recursivelyunparse(ast) emit(")") else recursivelyunparse(ast) end end recursivelyunparse = function(ast) local t = typetable[ast.type] if not t then error("Unknown AST node type "..ast.type) end t(ast) end local needsspace = { string = true, number = true, identifier = true, keyword = true } local function unparser(self, ast) result = {} recursivelyunparse(ast) local line = 1 local lasttype = nil local s = {} for _, t in ipairs(result) do if type(t) == "string" then local isstring = t:find("^[%w_]*$") if needsspace[lasttype] and isstring then s[#s+1] = " " end s[#s+1] = t if isstring then lasttype = "string" else lasttype = nil end else if t.line then while (line < t.line) do s[#s+1] = "\n" line = line + 1 lasttype = nil end end if needsspace[lasttype] and needsspace[t.type] then s[#s+1] = " " end s[#s+1] = t.text lasttype = t.type end end return table.concat(s) end getmetatable(getfenv(1)).__call = unparser
return Component.create("DrawableCircle", {"radius", "fill", "ox", "oy"})
RESOURCES_BASE_PATH = "GuardioesDeArda/Lupa/Resources/"; instanceEnum = { default = "default", am = "am", ad = "ad", fokd = "fokd", rako = "rako", stairs = "stairs", woe = "woe", harrow = "harrow", remm = "remm", pel = "pel", }; instances = { [instanceEnum.am] = { name = "Asakâd-mazal", thumbnail = RESOURCES_BASE_PATH .. "am_thumb.tga", }, [instanceEnum.ad] = { name = "Amdân Dammul", thumbnail = RESOURCES_BASE_PATH .. "ad_thumb.tga", }, [instanceEnum.fokd] = { name = "The Fall of Khazad-dûm", thumbnail = RESOURCES_BASE_PATH .. "fokd_thumb.tga", }, [instanceEnum.stairs] = { name = "Shakalush, the Stair Battle", thumbnail = RESOURCES_BASE_PATH .. "stairs_thumb.tga", }, [instanceEnum.woe] = { name = "Woe of the Willow", thumbnail = RESOURCES_BASE_PATH .. "woe_thumb.tga", }, [instanceEnum.harrow] = { name = "The Harrowing of Morgul", thumbnail = RESOURCES_BASE_PATH .. "harrow_thumb.tga", }, [instanceEnum.remm] = { name = "The Remmorchant", thumbnail = RESOURCES_BASE_PATH .. "remm_thumb.tga", }, [instanceEnum.pel] = { name = "Retaking Pelargir", thumbnail = RESOURCES_BASE_PATH .. "pel_thumb.tga", }, [instanceEnum.default] = { name = "Default Call", thumbnail = RESOURCES_BASE_PATH .. "default_thumb.tga", }, };
picList = {} picIndex = 1 mon = peripheral.wrap("left") mon.setCursorPos(1,1) mon.write("< 1 >") mon.setCursorPos(1,2) mon.write(" SET") mon.setCursorPos(1,3) mon.write(" PLAY") function ShowPicture(pic) for i=0,3,1 do rs.setBundledOutput("top",bit.brshift(pic,i*4)) rs.setBundledOutput("back",bit.blshift(1,i)) rs.setBundledOutput("back",0) end end while true do event, side, xPos, yPos = os.pullEvent("monitor_touch") if yPos == 1 then if xPos == 1 and picIndex > 1 then picIndex = picIndex - 1 mon.setCursorPos(4,1) mon.write(picIndex) end if xPos == 7 and picIndex < 16 then picIndex = picIndex + 1 mon.setCursorPos(4,1) mon.write(picIndex) end end if yPos == 2 then picList[picIndex] = rs.getBundledInput("right") end if yPos == 3 then ShowPicture(picList[picIndex]) end end
local mod = getfenv(1) assert(mod) local self = getfenv(1) function OnCombat(Unit, _, mTarget) self[tostring(Unit)] = { shock = math.random(2, 6), chain = math.random(10, 15), summon_phase = 1, isHeroic = (mTarget:IsPlayer() and mTarget:IsHeroic()) } Unit:RegisterAIUpdateEvent(1000) local say_text = math.random(1, 3) if(say_text == 1) then Unit:SendChatMessage(14, 0, "Hrrmm.. Time to.. hrrm.. make my move.") Unit:PlaySoundToSet(10503) elseif(say_text == 2) then Unit:SendChatMessage(14, 0, "Nice pets..hrm.. Yes!") Unit:PlaySoundToSet(10504) else Unit:SendChatMessage(14, 0, "Nice pets have.. weapons. No so...nice.") Unit:PlaySoundToSet(10505) end end function OnWipe(Unit) Unit:RemoveAIUpdateEvent() self[tostring(Unit)] = nil end function OnTargetKill(Unit) local say_text = math.random(1, 2) if(say_text == 1) then Unit:SendChatMessage(14, 0, "Death.. meeting life is..") Unit:PlaySoundToSet(10506) else Unit:SendChatMessage(14, 0, "Uhn... Be free..") Unit:PlaySoundToSet(10507) end end function OnDeath(Unit) Unit:SendChatMessage(14, 0, "No more life... hrm. No more pain.") Unit:PlaySoundToSet(10508) end function AIUpdate(Unit) if(Unit:IsCasting()) then return end if(Unit:GetNextTarget() == nil) then Unit:WipeThreatList() return end local vars = self[tostring(Unit)] vars.shock = vars.shock -1 vars.chain = vars.chain - 1 if(vars.chain <= 0) then local target = Unit:GetRandomEnemy() if(vars.isHeroic) then Unit:FullCastSpellOnTarget(15659, target) else Unit:FullCastSpellOnTarget(15305, target) end vars.chain = math.random(10, 20) elseif(vars.shock <=0) then local target = Unit:GetRandomEnemy() local spelltocast = math.random(4) if(spelltocast == 1) then if(vars.isHeroic) then Unit:FullCastSpellOnTarget(38135, target) else Unit:FullCastSpellOnTarget(33534, target) end elseif(spelltocast == 2) then if(vars.isHeroic) then Unit:FullCastSpellOnTarget(15616, target) else Unit:FullCastSpellOnTarget(15039, target) end elseif(spelltocast == 3) then if(vars.isHeroic) then Unit:FullCastSpellOnTarget(21401, target) else Unit:FullCastSpellOnTarget(12548, target) end else if(vars.isHeroic) then Unit:FullCastSpellOnTarget(38136, target) else Unit:FullCastSpellOnTarget(33620, target) end end vars.shock = math.random(5,15) else local hp = Unit:GetHealthPct() local asummon = vars.summon_phase if((hp <= 90 and asummon == 1) or (hp <= 55 and asummon == 2) or (hp <= 10 and asummon == 3)) then local summon_spells = {33538, 33537, 33539, 33540} local angle = 0 for i = 1,4 do local radius = math.random(5, 10) local x = Unit:GetX()+math.cos(math.rad(angle))*radius local y = Unit:GetY()+math.sin(math.rad(angle))*radius Unit:CastSpellAoF(x, y, Unit:GetZ(), summon_spells[i]) angle = angle+90 end Unit:SendChatMessage(14, 0, "I have pets of my own!") Unit:PlaySoundToSet(10502) vars.summon_phase = vars.summon_phase + 1 end end end RegisterUnitEvent(18472, 1, "OnCombat") RegisterUnitEvent(18472, 2, "OnWipe") RegisterUnitEvent(18472, 3, "OnTargetKill") RegisterUnitEvent(18472, 4, "OnDeath") RegisterUnitEvent(18472, 21, "AIUpdate") function Elemental_Cast(Unit, spell) Unit:FullCastSpell(spell) end function Elemental_OnSpawn(Unit) local entry = Unit:GetEntry() if(entry == 19205) then Unit:RegisterLuaEvent(Elemental_Cast, math.random(7, 15)*1000, 0, 38138) elseif(entry == 19203) then Unit:RegisterLuaEvent(Elemental_Cast, math.random(7, 15)*1000, 0, 38141) elseif(entry == 19204) then Unit:RegisterLuaEvent(Elemental_Cast, math.random(7, 15)*1000, 0, 38142) else Unit:RegisterLuaEvent(Elemental_Cast, math.random(7, 15)*1000, 0, 38143) end local creator = Unit:GetCreator() if(creator) then Unit:AttackReaction(creator:GetNextTarget(), 1, 0) else Unit:AttackReaction(Unit:GetRandomEnemy(), 1, 0) end end function Elemental_OnWipe(Unit) Unit:RemoveLuaEvents() Unit:Despawn(1000, 0) end RegisterUnitEvent(19205, 18, "Elemental_OnSpawn") RegisterUnitEvent(19205, 2, "Elemental_OnWipe") RegisterUnitEvent(19203, 18, "Elemental_OnSpawn") RegisterUnitEvent(19203, 2, "Elemental_OnWipe") RegisterUnitEvent(19204, 18, "Elemental_OnSpawn") RegisterUnitEvent(19204, 2, "Elemental_OnWipe") RegisterUnitEvent(19206, 18, "Elemental_OnSpawn") RegisterUnitEvent(19206, 2, "Elemental_OnWipe")
local custom_lib = require("__Constructron-Continued__.script.custom_lib") local ctron = require("__Constructron-Continued__.script.constructron") local Spidertron_Pathfinder = require("__Constructron-Continued__.script.Spidertron-pathfinder") local cmd = require("__Constructron-Continued__.script.command_functions") ctron.pathfinder = Spidertron_Pathfinder local init = function() ctron.ensure_globals() Spidertron_Pathfinder.init_globals() end script.on_init(init) script.on_configuration_changed(init) -- Possibly do this at a 10x lower frequency or controlled by a mod setting script.on_nth_tick(1, (function(event) if event.tick % 600 == 0 then ctron.setup_constructrons() elseif event.tick % 20 == 0 then ctron.add_entities_to_chunks("deconstruction") elseif event.tick % 20 == 5 then ctron.add_entities_to_chunks("ghost") elseif event.tick % 20 == 10 then ctron.add_entities_to_chunks("upgrade") elseif event.tick % 20 == 15 then ctron.add_entities_to_chunks("repair") end end)) -- main worker script.on_nth_tick(60, ctron.process_job_queue) -- cleanup script.on_nth_tick(54000, (function(event) ctron.perform_surface_cleanup(event) Spidertron_Pathfinder.check_pathfinder_requests_timeout() end)) local ev = defines.events script.on_event(ev.on_script_path_request_finished, (function(event) Spidertron_Pathfinder.on_script_path_request_finished(event) end)) -- ToDo check if upgrade, built and deconstruct can be handled by the same logic, possibly a common processing function with 2 different preprocessors/wrappers for each event if required script.on_event({ev.on_built_entity, ev.script_raised_built, ev.on_robot_built_entity}, ctron.on_built_entity) script.on_event(ev.on_post_entity_died, ctron.on_post_entity_died) script.on_event(ev.on_marked_for_deconstruction, ctron.on_entity_marked_for_deconstruction) script.on_event(ev.on_marked_for_upgrade, ctron.on_marked_for_upgrade) script.on_event(ev.on_entity_damaged, ctron.on_entity_damaged, { {filter = "final-health", comparison = ">", value = 0, mode = "and"}, {filter = "robot-with-logistics-interface", invert = true, mode = "and"}, {filter = "vehicle", invert = true, mode = "and"}, {filter = "rolling-stock", invert = true, mode = "and"}, {filter = "type", type = "character", invert = true, mode = "and"}, {filter = "type", type = "fish", invert = true, mode = "and"} }) script.on_event(ev.on_surface_created, ctron.on_surface_created) script.on_event(ev.on_surface_deleted, ctron.on_surface_deleted) script.on_event(ev.on_entity_cloned, ctron.on_entity_cloned) script.on_event({ev.on_entity_destroyed, ev.script_raised_destroy}, ctron.on_entity_destroyed) script.on_event(ev.on_runtime_mod_setting_changed, ctron.mod_settings_changed) ------------------------------------------------------------------------------- local function reset(player, parameters) log("control:reset") log("by player:" .. player.name) log("parameters: " .. serpent.block(parameters)) if parameters[1] == "recall" then cmd.recall_ctrons() end if parameters[1] == "entities" then cmd.reload_entities() elseif parameters[1] == "settings" then cmd.reset_settings() elseif parameters[1] == "all" then -- Clear jobs/queues/entities game.print('Clear jobs/queues/entities') global.job_bundles = {} cmd.clear_queues() -- Clear supporting globals game.print('Clear supporting globals') global.ignored_entities = {} global.allowed_items = {} -- Clear and reacquire Constructrons & Stations cmd.reload_entities() cmd.reload_ctron_status() cmd.reload_ctron_color() -- Recall Ctrons game.print('Recall Ctrons') cmd.recall_ctrons() -- Clear Constructron inventory cmd.clear_ctron_inventory() -- Reacquire Construction jobs game.print('Reacquire Construction jobs') cmd.reacquire_construction_jobs() -- Reacquire Deconstruction jobs game.print('Reacquire Deconstruction jobs') cmd.reacquire_deconstruction_jobs() -- Reacquire Upgrade jobs game.print('Reacquire Upgrade jobs') cmd.reacquire_upgrade_jobs() else game.print('Command parameter does not exist.') cmd.help_text() end end local function clear(player, parameters) log("control:clear") log("by player:" .. player.name) log("parameters: " .. serpent.block(parameters)) if parameters[1] == "all" then game.print('All jobs, queued jobs and unprocessed entities cleared.') cmd.clear_queues() cmd.reload_ctron_status() cmd.reload_ctron_color() global.job_bundles = {} cmd.recall_ctrons() elseif parameters[1] == "inventory" then cmd.clear_ctron_inventory() else game.print('Command parameter does not exist.') cmd.help_text() end end local function enable(player, parameters) log("control:enable") log("by player:" .. player.name) log("parameters: " .. serpent.block(parameters)) if parameters[1] == "construction" then global.construction_job_toggle = true settings.global["construct_jobs"] = {value = true} cmd.reacquire_construction_jobs() game.print('Construction jobs enabled.') elseif parameters[1] == "rebuild" then global.rebuild_job_toggle = true settings.global["rebuild_jobs"] = {value = true} game.print('Rebuild jobs enabled.') elseif parameters[1] == "deconstruction" then global.deconstruction_job_toggle = true settings.global["deconstruct_jobs"] = {value = true} cmd.reacquire_deconstruction_jobs() game.print('Deconstruction jobs enabled.') elseif parameters[1] == "ground_deconstruction" then global.ground_decon_job_toggle = true settings.global["decon_ground_items"] = {value = true} game.print('items-on-ground deconstruction enabled.') elseif parameters[1] == "upgrade" then global.upgrade_job_toggle = true settings.global["upgrade_jobs"] = {value = true} cmd.reacquire_upgrade_jobs() game.print('Upgrade jobs enabled.') elseif parameters[1] == "repair" then global.repair_job_toggle = true settings.global["repair_jobs"] = {value = true} game.print('Repair jobs enabled.') elseif parameters[1] == "debug" then global.debug_toggle = true settings.global["constructron-debug-enabled"] = {value = true} game.print('Debug view enabled.') elseif parameters[1] == "landfill" then global.landfill_job_toggle = true settings.global["allow_landfill"] = {value = true} game.print('Landfill enabled.') else game.print('Command parameter does not exist.') cmd.help_text() end end local function disable(player, parameters) log("control:disable") log("by player:" .. player.name) log("parameters: " .. serpent.block(parameters)) if parameters[1] == "construction" then global.construction_job_toggle = false settings.global["construct_jobs"] = {value = false} game.print('Construction jobs disabled.') elseif parameters[1] == "rebuild" then global.rebuild_job_toggle = false settings.global["rebuild_jobs"] = {value = false} game.print('Rebuild jobs disabled.') elseif parameters[1] == "deconstruction" then global.deconstruction_job_toggle = false settings.global["deconstruct_jobs"] = {value = false} game.print('Deconstruction jobs disabled.') elseif parameters[1] == "ground_deconstruction" then global.ground_decon_job_toggle = false settings.global["decon_ground_items"] = {value = false} game.print('items-on-ground deconstruction disabled.') elseif parameters[1] == "upgrade" then global.upgrade_job_toggle = false settings.global["upgrade_jobs"] = {value = false} game.print('Upgrade jobs disabled.') elseif parameters[1] == "repair" then global.repair_job_toggle = false settings.global["repair_jobs"] = {value = false} game.print('Repair jobs disabled.') elseif parameters[1] == "debug" then global.debug_toggle = false settings.global["constructron-debug-enabled"] = {value = false} game.print('Debug view disabled.') elseif parameters[1] == "landfill" then global.landfill_job_toggle = false settings.global["allow_landfill"] = {value = false} game.print('Landfill disabled.') else game.print('Command parameter does not exist.') cmd.help_text() end end local function stats(player, _ ) local stats = cmd.stats() log(serpent.block(stats)) if stats and player then for k,v in pairs(stats) do player.print(k .. ": " .. tostring(v)) end end return stats end local function help(player, parameters) log("control:help") log("by player:" .. player.name) log("parameters: " .. serpent.block(parameters)) cmd.help_text() end --===========================================================================-- -- commands & interfaces --===========================================================================-- local ctron_commands = { help = help, reset = reset, clear = clear, enable = enable, disable = disable, stats = stats } ------------------------------------------------------------------------------- -- commands ------------------------------------------------------------------------------- commands.add_command( "ctron", "/ctron reset", function(param) log("/ctron " .. (param.parameter or "")) if param.parameter then local player = game.players[param.player_index] local params = custom_lib.string_split(param.parameter, " ") local command = table.remove(params, 1) if command and ctron_commands[command] then ctron_commands[command](player,params) else game.print('Command parameter does not exist.') help(player,{param.parameter}) end end end ) ------------------------------------------------------------------------------- --- game interfaces ------------------------------------------------------------------------------- remote.add_interface("ctron_interface", ctron_commands)
local function sizeOf(n) if n < 0x100 then return 1 elseif n < 0x10000 then return 2 elseif n < 0x1000000 then return 3 elseif n < 0x100000000 then return 4 end end return sizeOf
require("scene.lua"); require("utils.lua"); require("rrpgScene_TouchNav.lua"); require("rrpgScene_InertialMov.lua"); require("rrpgScene_MovementHistory.lua"); require("rrpgScene_Undo.dlua"); require("rrpgScene_UserDrawingDetails.lua"); --[[ PLUGIN para fazer user drawings ]]-- local SETTINGS_CATEGORY = "settings"; local QT_AMOSTRAS = 4; local PRECISAO = 1.0 / 200.0; local PRECISAO_CELULA = 1 / 10.0; local GERACOES_ALGORITMO_GENETICO = 30; local TAMANHO_MAXIMO_POPULACAO = 100; local function calcularDimensaoAlgoritmoGenetico(amostras, campo1, campo2) local delimitadores = {}; local individuos = {}; local populacaoAtual = {}; local function testarIndividuo(valor) local h = individuos[valor]; if h ~= nil then return h; end; h = {}; h.valor = valor; local pontos = 0.0; if valor > 0 then for i = 1, #delimitadores, 1 do for j = i + 1, #delimitadores, 1 do local distancia = math.abs(delimitadores[j] - delimitadores[i]); if distancia > PRECISAO then local qtCelulas = distancia / valor; local qtCelulasInteiroMaisPerto = math.floor(qtCelulas + 0.5); local difParaNumeroInteiroMaixProximo = math.abs(qtCelulasInteiroMaisPerto - qtCelulas); assert(difParaNumeroInteiroMaixProximo >= 0.0); assert(difParaNumeroInteiroMaixProximo <= 1.0); local fator = (1 - difParaNumeroInteiroMaixProximo); pontos = pontos + fator * fator; end; end; end; end; h.pontos = pontos; individuos[valor] = h; return h; end; local function ordenarPopulacaoAtual() table.sort(populacaoAtual, function (a, b) return a.pontos > b.pontos; end) end; local function prepararParaExecucao() for i = 1, #amostras, 1 do delimitadores[#delimitadores + 1] = amostras[i][campo1]; delimitadores[#delimitadores + 1] = amostras[i][campo2]; end; end; local function inicializarPopulacaoInicial() for i = 1, #amostras, 1 do populacaoAtual[#populacaoAtual + 1] = testarIndividuo(math.abs(amostras[i][campo2] - amostras[i][campo1])); end; end; local function gerarNovaPopulacao() local novaPopulacao = {}; for i = 1, #populacaoAtual, 1 do for j = 1 + 1, #populacaoAtual, 1 do local resultadoDoCruzamento = (populacaoAtual[i].valor + populacaoAtual[j].valor) / 2; if math.random(1, 100) <= 50 then -- Mutação genética local valorMutante = math.abs(resultadoDoCruzamento * (math.random(1, 100) / 100.0)); if math.random(1, 2) == 1 then resultadoDoCruzamento = resultadoDoCruzamento + valorMutante; else resultadoDoCruzamento = resultadoDoCruzamento - valorMutante; end; end; if resultadoDoCruzamento >= PRECISAO then novaPopulacao[#novaPopulacao + 1] = testarIndividuo(resultadoDoCruzamento); end; if #novaPopulacao > TAMANHO_MAXIMO_POPULACAO then break; end; end; if #novaPopulacao > TAMANHO_MAXIMO_POPULACAO then break; end; end; -- Aceitar os melhores individuos da última geração for i = 1, math.min(#populacaoAtual, 3) do novaPopulacao[#novaPopulacao + 1] = populacaoAtual[i] ; end; return novaPopulacao; end; prepararParaExecucao(); inicializarPopulacaoInicial(); ordenarPopulacaoAtual(); local geracaoAtual = 0; while geracaoAtual < GERACOES_ALGORITMO_GENETICO do geracaoAtual = geracaoAtual + 1; local novaPopulacao = gerarNovaPopulacao(); populacaoAtual = novaPopulacao; ordenarPopulacaoAtual(); end; assert(#populacaoAtual > 0); return populacaoAtual[1].valor; end; local function calcularOffsetAlgoritmoGenetico(amostras, campo1, campo2, oldWorldSize, newWorldSize, cellCount) local delimitadores = {}; local individuos = {}; local populacaoAtual = {}; local scale = newWorldSize / oldWorldSize; local newCellSize = newWorldSize / cellCount; local function testarIndividuo(valor) local h = individuos[valor]; if h ~= nil then return h; end; h = {}; h.valor = valor; local pontos = 0.0; for i = 1, #delimitadores, 1 do local distancia = math.abs(delimitadores[i] - valor); local qtCelulas = distancia / newCellSize; local qtCelulasInteiroMaisPerto = math.floor(qtCelulas + 0.5); local difParaNumeroInteiroMaixProximo = math.abs(qtCelulasInteiroMaisPerto - qtCelulas); assert(difParaNumeroInteiroMaixProximo >= 0.0); assert(difParaNumeroInteiroMaixProximo <= 1.0); local fator = (1 - difParaNumeroInteiroMaixProximo); pontos = pontos + fator * fator; end; h.pontos = pontos; individuos[valor] = h; return h; end; local function ordenarPopulacaoAtual() table.sort(populacaoAtual, function (a, b) return a.pontos > b.pontos; end) end; local function prepararParaExecucao() for i = 1, #amostras, 1 do delimitadores[#delimitadores + 1] = amostras[i][campo1] * scale; delimitadores[#delimitadores + 1] = amostras[i][campo2] * scale; end; end; local function inicializarPopulacaoInicial() local MAX_LOOP = 100; populacaoAtual[#populacaoAtual + 1] = testarIndividuo(0); for i = 1, MAX_LOOP, 1 do local factor = (i * 1.0) / (MAX_LOOP + 1.0); populacaoAtual[#populacaoAtual + 1] = testarIndividuo(factor * newCellSize); populacaoAtual[#populacaoAtual + 1] = testarIndividuo(-factor * newCellSize); end; end; local function gerarNovaPopulacao() local novaPopulacao = {}; for i = 1, #populacaoAtual, 1 do for j = 1 + 1, #populacaoAtual, 1 do local resultadoDoCruzamento = (populacaoAtual[i].valor + populacaoAtual[j].valor) / 2; if math.random(1, 100) <= 50 then -- Mutação genética local valorMutante = math.abs(resultadoDoCruzamento * (math.random(1, 100) / 100.0)); if math.random(1, 2) == 1 then resultadoDoCruzamento = resultadoDoCruzamento + valorMutante; else resultadoDoCruzamento = resultadoDoCruzamento - valorMutante; end; end; if resultadoDoCruzamento >= PRECISAO then novaPopulacao[#novaPopulacao + 1] = testarIndividuo(resultadoDoCruzamento); end; if #novaPopulacao > TAMANHO_MAXIMO_POPULACAO then break; end; end; if #novaPopulacao > TAMANHO_MAXIMO_POPULACAO then break; end; end; -- Aceitar os melhores individuos da última geração for i = 1, math.min(#populacaoAtual, 3) do novaPopulacao[#novaPopulacao + 1] = populacaoAtual[i] ; end; return novaPopulacao; end; prepararParaExecucao(); inicializarPopulacaoInicial(); ordenarPopulacaoAtual(); local geracaoAtual = 0; while geracaoAtual < GERACOES_ALGORITMO_GENETICO do geracaoAtual = geracaoAtual + 1; local novaPopulacao = gerarNovaPopulacao(); populacaoAtual = novaPopulacao; ordenarPopulacaoAtual(); end; assert(#populacaoAtual > 0); return populacaoAtual[1].valor; end; SceneLib.registerPlugin( function (scene, attachment) require("rrpgScene_ShapesMaker.dlua"); scene.viewport:setupToolCategory(SETTINGS_CATEGORY, lang("scene.toolcategory.settings"), -2); local installed = false; local btn_viewAsPlayer; local possuiaGridAntes = nil; local shapeMaker = nil; local realCellWidth = nil local realCellHeight = nil; local amostras = {}; local frmInstrucao = nil; local processarAmostras = nil; local function updateGridSizes() realCellWidth = scene.grid.cellSize; realCellHeight = scene.grid.cellSize; end; updateGridSizes(); local function pararDesenhoGrid() amostras[#amostras + 1] = shapeMaker:getWorldBounds(); if #amostras >= QT_AMOSTRAS then processarAmostras(); end; end; processarAmostras = function() assert(amostras ~= nil); assert(#amostras > 0); updateGridSizes(); local larguraCelula = calcularDimensaoAlgoritmoGenetico(amostras, "left", "right"); local alturaCelula = calcularDimensaoAlgoritmoGenetico(amostras, "top", "bottom"); local novaQtCelulasX = math.floor((scene.worldWidth / larguraCelula) / PRECISAO_CELULA + 0.5) * PRECISAO_CELULA local novaQtCelulasY = math.floor((scene.worldHeight / alturaCelula) / PRECISAO_CELULA + 0.5) * PRECISAO_CELULA novaQtCelulasX = math.max(math.min(novaQtCelulasX, 500), PRECISAO_CELULA); novaQtCelulasY = math.max(math.min(novaQtCelulasY, 500), PRECISAO_CELULA); local novaLarguraGrid = novaQtCelulasX * realCellWidth; local novaAlturaGrid = novaQtCelulasY * realCellHeight; local novoOffsetX = calcularOffsetAlgoritmoGenetico(amostras, "left", "right", scene.worldWidth, novaLarguraGrid, novaQtCelulasX); local novoOffsetY = calcularOffsetAlgoritmoGenetico(amostras, "top", "bottom", scene.worldHeight, novaAlturaGrid, novaQtCelulasY); SC3UNDO_Capture(scene, function() scene.worldWidth = novaLarguraGrid; scene.worldHeight = novaAlturaGrid; scene.grid.offsetX = novoOffsetX; scene.grid.offsetY = novoOffsetY; scene.grid.drawGrid = true; end); possuiaGridAntes = true; amostras = {}; end; local function createShapeMaker() assert(shapeMaker == nil); shapeMaker = SHAPEMaker_New(scene, SHAPE_RECTANGLE); shapeMaker.autoDraw = true; shapeMaker.onStop = pararDesenhoGrid; shapeMaker.fillColor = "#FF000030"; shapeMaker.strokeColor = "null" --shapeMaker.strokeColor = "#FF000040"; shapeMaker.snapToGrid = false; shapeMaker.strokeSize = 0.05 * scene.grid.cellSize; shapeMaker:start(); end; local function installTools() btn_viewAsPlayer = scene.viewport:addToolButton(SETTINGS_CATEGORY, lang("scene.Synchronize.menu"), "/icos/Synchronize.png", 10, {selectable=true, defaultOfCategory=false}, function() possuiaGridAntes = scene.grid.drawGrid; scene.grid.drawGrid = false; if frmInstrucao == nil then frmInstrucao = GUI.newForm("frmSynchronizeGrid"); end; scene.viewport:showForm(frmInstrucao, {placement="topLeft"}); createShapeMaker(); amostras = {} end, function() scene.grid.drawGrid = possuiaGridAntes; amostras = {} if frmInstrucao ~= nil then scene.viewport:closeForm(frmInstrucao); end; if shapeMaker ~= nil then shapeMaker:abort(); shapeMaker = nil; end; end, function() scene.isViewingAsGM = not scene.isViewingAsGM; end); end; local function uninstallTools() scene.viewport:removeToolButton(btn_viewAsPlayer); end; local function captureGMStateChanged() if scene.isGM and not installed then installed = true; installTools(); elseif not scene.isGM and installed then installed = false; uninstallTools(); scene.viewport:closeForm(frmInstrucao); end; if installed then scene.viewport:checkToolButton(btn_viewAsPlayer, not scene.isViewingAsGM); end; end; scene:listen("onGMStateChange", captureGMStateChanged); captureGMStateChanged(); end);
local helpers = require "helpers" local function refresh_acl() ngx.log(ngx.INFO, "REFRESHING") local client = helpers.apiclient("http://app:5000") local acl = client.get("/acl") if client and acl then helpers.update_acl(acl) end end ngx.timer.at(0, refresh_acl) ngx.timer.every(10, refresh_acl)
-- 房间管理器 local M = {} function M:init() self.tbl = {} end function M:get(id) return self.tbl[id] end function M:add(obj) self.tbl[obj.id] = obj end function M:remove(obj) self.tbl[obj.id] = nil end return M
-- copy all globals into locals, some locals are prefixed with a G to reduce name clashes local coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,Gload,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require=coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require local export,lookup,set_env=require("wetgenes"):export("export","lookup","set_env") -- base modules local mime=require("mime") local wjson=require("wetgenes.json") local wstr=require("wetgenes.string") local whtml=require("wetgenes.html") --pagecake base modules local sys=require("wetgenes.www.any.sys") local dat=require("wetgenes.www.any.data") local users=require("wetgenes.www.any.users") local stash=require("wetgenes.www.any.stash") local img=require("wetgenes.www.any.img") local oauth=require("wetgenes.www.any.oauth") local fetch=require("wetgenes.www.any.fetch") local cache=require("wetgenes.www.any.cache") --pagecake mods local d_sess =require("dumid.sess") local d_users=require("dumid.users") -- debug functions local dprint=function(...)print(wstr.dump(...))end local log=require("wetgenes.www.any.log").log --module local M={ modname=(...) } ; package.loaded[M.modname]=M M.export=export M.bearer=function(srv) local url="https://api.twitter.com/oauth2/token" local ret=cache.get(srv,url) if ret then return ret end local secret=srv.opts("twitter","secret") or "secret" local key=srv.opts("twitter","key") or "key" local sk64=oauth.b64(oauth.esc(key)..":"..oauth.esc(secret)) local headers={ ["Authorization"] = "Basic "..sk64, ["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8", } local ret=fetch.post(url,headers,"grant_type=client_credentials") local j=wjson.decode(ret.body) -- dprint(ret) local ret if j.token_type=="bearer" then ret=j.access_token end if ret then cache.put(srv,url,ret) end return ret end M.search=function(srv,opts) local headers={ ["Authorization"]="Bearer "..M.bearer(srv), } -- build url from opts local url="https://api.twitter.com/1.1/search/tweets.json" local t={url,"?"} for n,v in pairs(opts) do t[#t+1]=n t[#t+1]="=" t[#t+1]=oauth.esc(v) t[#t+1]="&" end t[#t]=nil -- remove trailing & or ? then build url string url=table.concat(t) local ret=fetch.get(url,headers) local j if ret.body then j=wjson.decode(ret.body) end return j end --[=[ module("port.twitter") -- -- make a twat update -- -- it.user -- the user (must be a twitter user) -- it.text -- 140 characters -- function post(srv,it) --TODO--NOW-- local it=it or {} -- check it is a twitter user before going further if not lookup(it,"user","cache","authentication","twitter","secret") then return end local v={} v.oauth_timestamp , v.oauth_nonce = oauth.time_nonce("sekrit") v.oauth_consumer_key = srv.opts("twitter","key") v.oauth_signature_method="HMAC-SHA1" v.oauth_version="1.0" v.oauth_token=lookup(it,"user","cache","authentication","twitter","token") v.status=it.text local o={} o.post="POST" o.url="http://api.twitter.com/1/statuses/update.json" v.tok_secret=lookup(it,"user","cache","authentication","twitter","secret") o.api_secret=srv.opts("twitter","secret") local k,q = oauth.build(v,o) local b={} for _,n in pairs({"status"}) do b[n]=v[n] v[n]=nil end v.oauth_signature=k local vals={} for ii,iv in pairs(b) do vals[#vals+1]=oauth.esc(ii).."="..oauth.esc(iv) end local q=table.concat(vals,"&") local auths={} for ii,iv in pairs(v) do auths[#auths+1]=oauth.esc(ii).."=\""..oauth.esc(iv).."\"" end local got=fetch.post(o.url.."?"..q, { ["Authorization"]="OAuth "..table.concat(auths,", "), ["Content-Type"]="x-www-form-urlencoded; charset=utf-8", },q) -- get from internets end ]=]
if settings.startup["enable-reactorinterface"] and settings.startup["enable-reactorinterface"].value == true then require("prototypes/reactorinterface") end if settings.startup["enable-tesla"] and settings.startup["enable-tesla"].value == true then require("prototypes/TeslaTurret") end if settings.startup["enable-usefulequipment"] and settings.startup["enable-usefulequipment"].value == true then require("prototypes/useful_equipment.equipment") require("prototypes/useful_equipment.item") require("prototypes/useful_equipment.recipe") require("prototypes/useful_equipment.technology") end
-- bless this library, my god local class = require('pl.class') local MAX_FLOORS = 16 ---- "Abstract" Elevator ---- local Elevator = class() function Elevator:_init(numFloors) if not numFloors or numFloors < 1 or numFloors > MAX_FLOORS then error("numFloors must be defined and between 1 and 16!") end self.numFloors = numFloors self.currentFloor = 0 end function Elevator:__tostring() return string.format("Elevator -- %d/%d", self.currentFloor, self.numFloors) end -- Moves the elevator up by the specified number of blocks function Elevator:moveUp(blocks) error("method moveUp() must be overriden!") end -- Moves the elevator down by the specified number of blocks function Elevator:moveDown(blocks) error("method moveDown() must be overriden!") end -- Stops the elevator in its current position and holds it function Elevator:halt() error("method halt() must be overriden!") end -- Allows the elevator to move towards its natural positon (usually downward) function Elevator:release() error("method release() must be overriden!") end ---- GantryElevator ---- local GantryElevator = class(Elevator) function GantryElevator:_init(numFloors, maxRPM) self:super(numFloors) if not maxRPM or maxRPM < -256 or maxRPM > 256 then error("maxRPM must be defined and between -256 and 256!") end self.maxRPM = maxRPM end function GantryElevator:__tostring() return string.format("GantryElevator -- %d/%d @%dRPM", self.currentFloor, self.numFloors, self.maxRPM) end ---- Module ---- return { Elevator = Elevator, GantryElevator = GantryElevator }
surface.CreateFont("LoadingDownloads", { font = "Coolvetica", size = 20, weight = 500, blursize = 0, scanlines = 0, antialias = true, underline = false, italic = false, strikeout = false, symbol = false, rotary = false, shadow = false, additive = false, outline = false, }) PANEL.Base = "Panel" function PANEL:Init() self.Icon = vgui.Create("DImage", self) self.Icon:SetImage("icon16/page_white_magnify") self.lblNumToDownload = vgui.Create("DLabel", self) self.lblNumToDownload:SetContentAlignment(4) self.lblNumToDownload:SetFont("LoadingDownloads") self.Files = {} self.FilesToDownload = {} end function PANEL:PerformLayout() self:SetSize(150, 20) self.Icon:SetPos(0, 0) self.Icon:SizeToContents() self.Icon:CenterVertical() self.lblNumToDownload:StretchToParent(25, 0, 0, 0) end function PANEL:SetText(txt) self.TypeName = txt end function PANEL:SetIcon(txt) self.IconTexture = txt self.Icon:SetImage(txt) end function PANEL:SetSpeed(s) self.Speed = s end function PANEL:AddFile(filename) local iReturn = 0 local exists = file.Exists(filename, "MOD") if exists then self.Files[#self.Files + 1] = filename else self.FilesToDownload[#self.FilesToDownload + 1] = filename iReturn = 1 end self:UpdateCounts() return iReturn end -- If the filename is in our list, move it to downloaded. function PANEL:Downloaded(filename) for k, v in pairs(self.FilesToDownload) do if v == filename then self.FilesToDownload[k] = nil self.Files[#self.Files + 1] = v end end self:UpdateCounts() end function PANEL:MakeRunner(filename) for k, v in pairs(self.FilesToDownload) do -- Fix the filename v = string.gsub(v, "\\", "/") if v == filename then return self:GetParent():AddRunner(self.IconTexture, self.Speed) end end end function PANEL:ShouldBeVisible() return #self.FilesToDownload > 0 end function PANEL:UpdateCounts() local cnt = #self.FilesToDownload self.lblNumToDownload:SetText(string.format("%i %s", cnt, self.TypeName)) if cnt == 0 then self:SetVisible(false) end end function PANEL:Clean() self.Files = {} self.FilesToDownload = {} self:UpdateCounts() end
local playsession = { {"mewmew", {76636}}, {"Giatros", {50823}}, {"zbirka", {637}}, {"aledeludx", {51595}}, {"AcidWizard", {38533}}, {"Dinnopum", {859}}, {"Howolf", {2358}}, {"Arin", {4733}} } return playsession
--------------------------------------------------------------------------------------------------- -- Client Lua Script for RaidCore Addon on WildStar Game. -- -- Copyright (C) 2015 RaidCore --------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- -- Description: -- Elemental Pair after the Logic wings. --------------------------------------------------------------------------------------------------- local Apollo = require "Apollo" local GameLib = require "GameLib" local Unit = require "Unit" local core = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:GetAddon("RaidCore") local mod = core:NewEncounter("EpLogicLife", 52, 98, 119) if not mod then return end ---------------------------------------------------------------------------------------------------- -- Registering combat. ---------------------------------------------------------------------------------------------------- mod:RegisterTrigMob(core.E.TRIGGER_ALL, { "Mnemesis", "Visceralus" }) mod:RegisterEnglishLocale({ -- Unit names. ["Essence of Life"] = "Essence of Life", ["Essence of Logic"] = "Essence of Logic", ["Alphanumeric Hash"] = "Alphanumeric Hash", ["Life Force"] = "Life Force", ["Wild Brambles"] = "Wild Brambles", ["Mnemesis"] = "Mnemesis", ["Visceralus"] = "Visceralus", -- Datachron messages. ["Time to die, sapients!"] = "Time to die, sapients!", -- Cast. ["Blinding Light"] = "Blinding Light", ["Defragment"] = "Defragment", -- Timer bars. ["Next defragment"] = "Next defragment", ["Next thorns"] = "Next thorns", ["Avatus incoming"] = "Avatus incoming", ["Enrage"] = "Enrage", -- Message bars. ["SPREAD"] = "SPREAD", ["No-Healing Debuff!"] = "No-Healing Debuff!", ["SNAKE ON YOU!"] = "SNAKE ON YOU!", ["SNAKE ON %s!"] = "SNAKE ON %s!", ["MARKER North"] = "North", ["MARKER South"] = "South", ["MARKER East"] = "East", ["MARKER West"] = "West", }) mod:RegisterFrenchLocale({ -- Unit names. ["Essence of Life"] = "Essence de vie", ["Essence of Logic"] = "Essence de logique", ["Alphanumeric Hash"] = "Alphanumeric Hash", ["Life Force"] = "Force vitale", ["Wild Brambles"] = "Ronces sauvages", ["Mnemesis"] = "Mnémésis", ["Visceralus"] = "Visceralus", -- Datachron messages. ["Time to die, sapients!"] = "Maintenant c'est l'heure de mourir, misérables !", -- Cast. ["Blinding Light"] = "Lumière aveuglante", ["Defragment"] = "Défragmentation", -- Timer bars. ["Next defragment"] = "Prochaine defragmentation", ["Next thorns"] = "Prochaine épine", ["Avatus incoming"] = "Avatus arrivé", ["Enrage"] = "Enrage", -- Message bars. ["SPREAD"] = "SEPAREZ-VOUS", ["No-Healing Debuff!"] = "No-Healing Debuff!", ["SNAKE ON YOU!"] = "SERPENT SUR VOUS!", ["SNAKE ON %s!"] = "SERPENT SUR %s!", ["MARKER North"] = "Nord", ["MARKER South"] = "Sud", ["MARKER East"] = "Est", ["MARKER West"] = "Ouest", }) mod:RegisterGermanLocale({ -- Unit names. ["Essence of Life"] = "Lebensessenz", ["Essence of Logic"] = "Logikessenz", ["Alphanumeric Hash"] = "Alphanumerische Raute", ["Life Force"] = "Lebenskraft", ["Mnemesis"] = "Mnemesis", ["Visceralus"] = "Viszeralus", -- Datachron messages. -- Cast. ["Blinding Light"] = "Blendendes Licht", ["Defragment"] = "Defragmentieren", -- Timer bars. -- Message bars. ["MARKER North"] = "N", ["MARKER South"] = "S", ["MARKER East"] = "O", ["MARKER West"] = "W", }) -- Default settings. mod:RegisterDefaultSetting("SoundSnakeOnYou") mod:RegisterDefaultSetting("SoundSnakeOnOther") mod:RegisterDefaultSetting("SoundNoHealDebuff") mod:RegisterDefaultSetting("SoundBlindingLight") mod:RegisterDefaultSetting("SoundDefrag") mod:RegisterDefaultSetting("SoundEnrageCountDown") mod:RegisterDefaultSetting("OtherSnakePlayerMarkers") mod:RegisterDefaultSetting("OtherNoHealDebuffPlayerMarkers") mod:RegisterDefaultSetting("OtherRootedPlayersMarkers") mod:RegisterDefaultSetting("OtherDirectionMarkers") mod:RegisterDefaultSetting("LineTetrisBlocks") mod:RegisterDefaultSetting("LineLifeOrbs") mod:RegisterDefaultSetting("LineCleaveVisceralus") mod:RegisterDefaultSetting("PolygonDefrag") -- Timers default configs. mod:RegisterDefaultTimerBarConfigs({ ["DEFRAG"] = { sColor = "xkcdAlgaeGreen" }, ["THORNS"] = { sColor = "xkcdAlgaeGreen" }, ["AVATUS_INCOMING"] = { sColor = "xkcdAmethyst" }, ["ENRAGE"] = { sColor = "xkcdBloodRed" }, }) --------------------------------------------------------------------------------------------------- -- Constants. --------------------------------------------------------------------------------------------------- local DEBUFF__SNAKE_SNACK = 74570 local DEBUFF__THORNS = 75031 local DEBUFF__LIFE_FORCE_SHACKLE = 74366 local MID_POSITIONS = { ["north"] = { x = 9741.53, y = -518, z = 17823.81 }, ["west"] = { x = 9691.53, y = -518, z = 17873.81 }, ["south"] = { x = 9741.53, y = -518, z = 17923.81 }, ["east"] = { x = 9791.53, y = -518, z = 17873.81 }, } ---------------------------------------------------------------------------------------------------- -- Locals. ---------------------------------------------------------------------------------------------------- local GetGameTime = GameLib.GetGameTime local GetUnitById = GameLib.GetUnitById local GetPlayerUnit = GameLib.GetPlayerUnit local bIsMidPhase = false local nLastThornsTime --------------------------------------------------------------------------------------------------- -- Encounter description. --------------------------------------------------------------------------------------------------- function mod:OnBossEnable() bIsMidPhase = false nLastThornsTime = 0 mod:AddTimerBar("DEFRAG", "Next defragment", 21, mod:GetSetting("SoundDefrag")) mod:AddTimerBar("AVATUS_INCOMING", "Avatus incoming", 480, mod:GetSetting("SoundEnrageCountDown")) end function mod:OnDatachron(sMessage) if self.L["Time to die, sapients!"] == sMessage then mod:RemoveTimerBar("AVATUS_INCOMING") mod:AddTimerBar("ENRAGE", "Enrage", 34) end end function mod:OnDebuffAdd(nId, nSpellId, nStack, fTimeRemaining) local tUnit = GetUnitById(nId) if DEBUFF__SNAKE_SNACK == nSpellId then local sName = tUnit:GetName() if tUnit == GetPlayerUnit() then mod:AddMsg("SNAKE", "SNAKE ON YOU!", 5, mod:GetSetting("SoundSnakeOnYou") and "RunAway") else mod:AddMsg("SNAKE", self.L["SNAKE ON %s!"]:format(sName), 5, mod:GetSetting("SoundSnakeOnOther") and "Info") end if mod:GetSetting("OtherSnakePlayerMarkers") then core:AddPicture(("SNAKE_TARGET_%d"):format(nId), nId, "Crosshair", 40, nil, nil, nil, "red") end elseif DEBUFF__LIFE_FORCE_SHACKLE == nSpellId then if mod:GetSetting("OtherNoHealDebuffPlayerMarkers") then mod:AddSpell2Dispel(nId, DEBUFF__LIFE_FORCE_SHACKLE) end if tUnit == GetPlayerUnit() then mod:AddMsg("NOHEAL", "No-Healing Debuff!", 5, mod:GetSetting("SoundNoHealDebuff") and "Alarm") end elseif DEBUFF__THORNS == nSpellId then if mod:GetSetting("OtherRootedPlayersMarkers") then mod:AddSpell2Dispel(nId, DEBUFF__THORNS) end end end function mod:OnDebuffRemove(nId, nSpellId) if DEBUFF__SNAKE_SNACK == nSpellId then core:RemovePicture(("SNAKE_TARGET_%d"):format(nId)) elseif DEBUFF__LIFE_FORCE_SHACKLE == nSpellId then mod:RemoveSpell2Dispel(nId, DEBUFF__LIFE_FORCE_SHACKLE) elseif DEBUFF__THORNS == nSpellId then mod:RemoveSpell2Dispel(nId, DEBUFF__THORNS) end end function mod:OnUnitCreated(nId, tUnit, sName) local nHealth = tUnit:GetHealth() local nCurrentTime = GetGameTime() if sName == self.L["Visceralus"] then if nHealth then core:AddUnit(tUnit) core:WatchUnit(tUnit, core.E.TRACK_CASTS) if mod:GetSetting("LineCleaveVisceralus") then core:AddSimpleLine("Visc1", nId, 0, 25, 0, 4, "blue", 10) core:AddSimpleLine("Visc2", nId, 0, 25, 72, 4, "green", 20) core:AddSimpleLine("Visc3", nId, 0, 25, 144, 4, "green", 20) core:AddSimpleLine("Visc4", nId, 0, 25, 216, 4, "green", 20) core:AddSimpleLine("Visc5", nId, 0, 25, 288, 4, "green", 20) end end elseif sName == self.L["Mnemesis"] then if nHealth then core:WatchUnit(tUnit, core.E.TRACK_CASTS) core:AddUnit(tUnit) end elseif sName == self.L["Essence of Life"] then core:AddUnit(tUnit) if not bIsMidPhase then bIsMidPhase = true if mod:GetSetting("OtherDirectionMarkers") then core:SetWorldMarker("NORTH", self.L["MARKER North"], MID_POSITIONS["north"]) core:SetWorldMarker("EAST", self.L["MARKER East"], MID_POSITIONS["east"]) core:SetWorldMarker("SOUTH", self.L["MARKER South"], MID_POSITIONS["south"]) core:SetWorldMarker("WEST", self.L["MARKER West"], MID_POSITIONS["west"]) end core:RemoveTimerBar("DEFRAG") core:RemoveTimerBar("THORNS") end elseif sName == self.L["Essence of Logic"] then core:AddUnit(tUnit) elseif sName == self.L["Alphanumeric Hash"] then if mod:GetSetting("LineTetrisBlocks") then core:AddSimpleLine(nId, nId, 0, 20, 0, 10, "red") end elseif sName == self.L["Life Force"] and mod:GetSetting("LineLifeOrbs") then core:AddSimpleLine(nId, tUnit, nil, 15, nil, 3, "Blue") elseif sName == self.L["Wild Brambles"] then if nLastThornsTime + 5 < nCurrentTime then nLastThornsTime = nCurrentTime mod:AddTimerBar("THORNS", "Next thorns", 30) end end end function mod:OnUnitDestroyed(nId, tUnit, sName) if sName == self.L["Essence of Logic"] then bIsMidPhase = false core:ResetWorldMarkers() end end function mod:OnCastStart(nId, sCastName, nCastEndTime, sName) local tUnit = GetUnitById(nId) if self.L["Visceralus"] == sName then if self.L["Blinding Light"] == sCastName then if self:GetDistanceBetweenUnits(tUnit, GetPlayerUnit()) < 33 then mod:AddMsg("BLIND", "Blinding Light", 5, mod:GetSetting("SoundBlindingLight") and "Beware") end end elseif self.L["Mnemesis"] == sName then if self.L["Defragment"] == sCastName then mod:AddMsg("DEFRAG", "SPREAD", 3, mod:GetSetting("SoundDefrag") and "Alarm") mod:AddTimerBar("DEFRAG", "Next defragment", 50, mod:GetSetting("SoundDefrag")) if mod:GetSetting("PolygonDefrag") then core:AddPolygon("DEFRAG_SQUARE", GetPlayerUnit():GetId(), 13, 0, 4, "xkcdBloodOrange", 4) local nRepeatingTimerId = self:ScheduleRepeatingTimer(function(tMnemesisUnit) local square = core:GetPolygon("DEFRAG_SQUARE") local bIsMOO = tMnemesisUnit:IsInCCState(Unit.CodeEnumCCState.Vulnerability) if square and bIsMOO then square:SetColor("8000ff00") end end, 1, tUnit) self:ScheduleTimer(function(SquareRepeatingTimerId) core:RemovePolygon("DEFRAG_SQUARE") self:CancelTimer(SquareRepeatingTimerId) end, 10, nRepeatingTimerId) end end end end
require 'torch' -- torch require 'image' -- for color transforms require 'nn' -- provides a normalization operator require 'xlua' -- xlua provides useful tools, like progress bars require 'optim' -- an optimization package, for online and batch methods require 'cunn' dofile './csv.lua' ---------------------------------------------------------------------- print '==> loading model' modelpath = './logs/pseudolabels/model.net' model = torch.load(modelpath) model:evaluate() ---------------------------------------------------------------------- print '==> loading dataset' dofile 'provider.lua' provider = torch.load('provider.t7') print('==> testing on test set:') -- classes classes = {'1','2','3','4','5','6','7','8','9','0'} -- making prediction and write to csv separator = ',' -- optional; use if not a comma csv = Csv("predictions.csv", "w", separator) csv:write({"Id","Prediction"}) -- write header bs = 25 for i = 1,provider.testData:size(), bs do -- disp progress xlua.progress(i, provider.testData:size()) -- get new sample local outputs = model:forward(provider.testData.data:narrow(1,i,bs):cuda()) -- test sample local pred, idx = torch.max(outputs,2) for j =1,bs do csv:write({i+j-1,idx[j][1]}) -- write each data row end end csv:close()
-- Require all common stage_intro modules (used across various scripts in game project) -- that define globals and don't return a module table -- Equivalent to engine/common.lua but for stage_intro cartridge. -- Usage: add require("common_stage_intro") at the top of each of your stage_intro main scripts -- (along with "engine/common") and in bustedhelper_stage_intro -- currently, content is same as common_ingame as we need to move character a little to place it -- properly for camera -- we may replace character with a proxy character with full custom physics for the "falling on ground" -- intro later require("engine/core/vector_ext_angle") -- character motion require("engine/core/table_helper") -- merge (to add the visual_stage_intro_addon and visual_menu_addon) -- we need sprite flags to draw grass on top of the rest require("data/sprite_flags") -- just kept for the scripted player character fall (there is no real physics so we could also get -- around using actual motion states) require("ingame/playercharacter_enums") --[[#pico8 --#if unity -- see explanations in common_ingame.lua require("ordered_require_stage_intro") --#endif --#pico8]]
-- -- Created by IntelliJ IDEA. -- User: macbookair -- Date: 30/03/17 -- Time: 19:07 -- To change this template use File | Settings | File Templates. -- local dateTime = { } function dateTime:newDateTime(options) local newDateTime = {} setmetatable(newDateTime, {__index=dateTime}) newDateTime._nativeObject = NativeInterface:newDateTime(options) return newDateTime end return dateTime
DefineClass.ShiftsBuilding = { __parents = { "Building"}, properties = { { template = true,id = "active_shift", name = T(738, "Single Active shift"), default = 0, category = "ShiftsBuilding", editor = "number"}, { template = true,id = "closed_shifts_persist", name = T(739, "Persisted closed shift"), no_edit = true, editor = "text", default = ""}, }, max_shifts = 3, closed_shifts = false,-- per shift current_shift = false, } local shift_names = { T(740, "Start Shift Enabled 1"), T(741, "Start Shift Enabled 2"), T(742, "Start Shift Enabled 3"), } for i = 1, ShiftsBuilding.max_shifts do assert(shift_names[i]) table.insert(ShiftsBuilding.properties, { template = true, id = "enabled_shift_" .. i, name = shift_names[i], default = true, category = "ShiftsBuilding", editor = "bool"}) end function ShiftsBuilding:Init() self.closed_shifts = {} end function ShiftsBuilding:GameInit() for i = 1, self.max_shifts do if (not self["enabled_shift_" .. i]) or (self.active_shift > 0 and self.active_shift ~= i) then self.closed_shifts[i] = true end end self:InitPersistShifts() for i = 1, self.max_shifts do if self.closed_shifts[i] then self:CloseShift(i) end end self.city:AddToLabel("ShiftsBuilding", self) self:SetWorkshift(CurrentWorkshift) end function ShiftsBuilding:RemoveFromShiftsBuildingLabel() self.city:RemoveFromLabel("ShiftsBuilding", self) self.RemoveFromShiftsBuildingLabel = __empty_function__ end function ShiftsBuilding:OnDestroyed() self:RemoveFromShiftsBuildingLabel() end function ShiftsBuilding:Done() self:RemoveFromShiftsBuildingLabel() end function ShiftsBuilding:GetUnitsInShifts() return empty_table end function OnMsg.NewWorkshift(workshift) for _, city in ipairs(Cities) do city:ForEachLabelObject("ShiftsBuilding", "SetWorkshift", workshift) end end function ShiftsBuilding:SetWorkshift(workshift) if self.destroyed then return end self:OnChangeWorkshift(self.current_shift, workshift) self.current_shift = workshift self:SetWorkplaceWorking() self:UpdateAttachedSigns() self:UpdateNotWorkingBuildingsNotification() end function ShiftsBuilding:UpdateAttachedSigns() end function ShiftsBuilding:InitPersistShifts() local shift = self.closed_shifts_persist if shift ~= "" then local idx = 1 for closed in string.gmatch(shift, "[0-9]") do if closed == "1" then self.closed_shifts[idx] = true else self.closed_shifts[idx] = false end idx = idx + 1 end end end function OnMsg.SaveMap() local exec = function(building) local persist_shifts = "" for j=1, building.max_shifts do persist_shifts = persist_shifts..(building:IsClosedShift(j) and "1" or "0") end building.closed_shifts_persist = persist_shifts end MapForEach("map","ShiftsBuilding", exec) end function ShiftsBuilding:SetWorkplaceWorking() local shift = self.active_shift > 0 and self.active_shift or self.current_shift if self.closed_shifts[shift] then self:OnSetWorkplaceWorking() self:UpdateWorking(false) else self:OnSetWorkplaceWorking() self:UpdateWorking() end end function ShiftsBuilding:OnChangeWorkshift(old_shift, new_shift) end function ShiftsBuilding:OnSetWorkplaceWorking() self:UpdateConsumption() end function ShiftsBuilding:GetWorkNotPermittedReason() local is_work_permitted = self.active_shift > 0 or not self:IsClosedShift(self.current_shift) if not is_work_permitted then return "InactiveWorkshift" end return Building.GetWorkNotPermittedReason(self) end function ShiftsBuilding:OnSetUIWorking(work) Building.OnSetUIWorking(self, work) if work and self:AreAllShiftsClosed()then self:OpenShift(2) end end function ShiftsBuilding:IsClosedShift(shift) return self.closed_shifts[shift] end function ShiftsBuilding:IsShiftUIActive(shift) return self.current_shift==shift end function ShiftsBuilding:AreAllShiftsClosed() for idx = 1, self.max_shifts do if not self.closed_shifts[idx] then return false end end return true end function ShiftsBuilding:CloseShift(shift) self.closed_shifts[shift] = true if self:AreAllShiftsClosed() then self:SetUIWorking(false) end if shift == self.current_shift then self:UpdateWorking() self:UpdateConsumption() end if self.active_shift > 0 or self.current_shift then self:UpdateAttachedSigns() end end function ShiftsBuilding:MoveWorkers(from_shift, to_shift) end function ShiftsBuilding:OpenShift(shift) local all_closed = self:AreAllShiftsClosed() local prev_active if self.active_shift > 0 then prev_active = self.active_shift self.closed_shifts[self.active_shift] = true self.active_shift = shift end self.closed_shifts[shift] = false if self.active_shift > 0 then self:MoveWorkers(prev_active, shift) end if all_closed then self:SetUIWorking(true) end if shift == self.current_shift or self.active_shift > 0 then self:UpdateWorking() self:UpdateConsumption() end self:UpdateAttachedSigns() end function ShiftsBuilding:ToggleShift(shift) if self:IsClosedShift(shift) then self:OpenShift(shift) else self:CloseShift(shift) end ObjModified(self) end function ShiftsBuilding:ShouldShowNotWorkingNotification() return not self:IsClosedShift(self.current_shift) and Building.ShouldShowNotWorkingNotification(self) end
function trunc(x) return x>=0 and math.floor(x) or math.ceil(x) end buffer = "" function readint() if buffer == "" then buffer = io.read("*line") end local num, buffer0 = string.match(buffer, '^([%-%d]*)(.*)') buffer = buffer0 return tonumber(num) end function stdinsep() if buffer == "" then buffer = io.read("*line") end if buffer ~= nil then buffer = string.gsub(buffer, '^%s*', "") end end function go0 (tab, a, b) local m = trunc((a + b) / 2) if a == m then if tab[a + 1] == m then return b else return a end end local i = a local j = b while i < j do local e = tab[i + 1] if e < m then i = i + 1 else j = j - 1 tab[i + 1] = tab[j + 1] tab[j + 1] = e end end if i < m then return go0(tab, a, m) else return go0(tab, m, b) end end function plus_petit0 (tab, len) return go0(tab, 0, len) end local len = 0 len = readint() stdinsep() local tab = {} for i = 0, len - 1 do local tmp = 0 tmp = readint() stdinsep() tab[i + 1] = tmp end io.write(plus_petit0(tab, len))
------------------------------------------------------------------------------ -- -- This file is part of the Corona game engine. -- For overview and more information on licensing please refer to README.md -- Home page: https://github.com/coronalabs/corona -- Contact: support@coronalabs.com -- ------------------------------------------------------------------------------ ---- Amend an app's Info.plist with CoronaSDK specific items. -- add $pwd/../../shared/resource to lua module lookup path package.path = package.path .. ";" .. arg[0]:match("(.+)/") .. "/../../shared/resource/?.lua" local json = require "json" local srcAssets = arg[1] local appBundleFile = arg[2] local deviceType = arg[3] or "iphone" local function osExecute(...) print("osExecute: ".. ...) return os.execute(...) end -- Double quote a string escaping backslashes and any double quotes local function quoteString( str ) str = str:gsub('\\', '\\\\') str = str:gsub('"', '\\"') return "\"" .. str .. "\"" end -- defaults local targetDevice = nil -- default is in CoronaPlistSupport -- Get the current build id from the environment (if set) local corona_build_id = os.getenv("CORONA_BUILD_ID") -- init options local options = { appBundleFile = quoteString( appBundleFile ), dstDir = dstDir, bundleversion = bundleversion, signingIdentity = signingIdentity, sdkRoot = sdkRoot, targetDevice = targetDevice, targetPlatform = "iOS", verbose = verbose, corona_build_id = corona_build_id, } local function fileExists( filename ) local f = io.open( filename, "r" ) if ( f ) then io.close( f ) end return ( nil ~= f ) end local customSettingsFile = srcAssets .. "/build.settings" if ( fileExists( customSettingsFile ) ) then local customSettings, msg = loadfile( customSettingsFile ) if ( customSettings ) then local status, msg = pcall( customSettings ) if status then print( "Using additional build settings from: " .. customSettingsFile ) options.settings = _G.settings else print( "Error: Errors found in build.settings file:" ) print( "\t".. msg ) os.exit(1) end else print( "Error: Could not load build.settings file:" ) print( "\t".. msg ) os.exit(1) end end -- define modifyPlist() local CoronaPListSupport = require("CoronaPListSupport") CoronaPListSupport.modifyPlist( options ) --[[ -- build.settings (if loaded and successfully executed, creates a global settings table) local settings = _G.settings if settings then -- cross-platform settings local orientation = settings.orientation if orientation then local defaultOrientation = orientation.default local supported = {} if defaultOrientation then local key = "UIInterfaceOrientation" local value = "UIInterfaceOrientationPortrait" if "landscape" == defaultOrientation or "landscapeRight" == defaultOrientation then value = "UIInterfaceOrientationLandscapeRight" elseif "landscapeLeft" == defaultOrientation then value = "UIInterfaceOrientationLandscapeLeft" end table.insert( supported, value ) osExecute( "defaults write '"..appBundleFile.."/Info' " .. key .. " "..value ) end osExecute( "defaults delete '"..appBundleFile.."/Info' ContentOrientation" ) local contentOrientation = orientation.content if contentOrientation then local value if "landscape" == contentOrientation or "landscapeRight" == contentOrientation then value = "UIInterfaceOrientationLandscapeRight" elseif "landscapeLeft" == contentOrientation then value = "UIInterfaceOrientationLandscapeLeft" elseif "portrait" == contentOrientation then value = "UIInterfaceOrientationPortrait" end if value then osExecute( "defaults write '"..appBundleFile.."/Info' ContentOrientation "..value ) end end osExecute( "defaults delete '"..appBundleFile.."/Info' CoronaViewSupportedInterfaceOrientations" ) local supportedOrientations = orientation.supported if supportedOrientations then local toUIInterfaceOrientations = { landscape = "UIInterfaceOrientationLandscapeRight", landscapeRight = "UIInterfaceOrientationLandscapeRight", landscapeLeft = "UIInterfaceOrientationLandscapeLeft", portrait = "UIInterfaceOrientationPortrait", portraitUpsideDown = "UIInterfaceOrientationPortraitUpsideDown", } for _,v in ipairs( supportedOrientations ) do local value = toUIInterfaceOrientations[v] if value then -- Add only unique values local found for _,elem in ipairs( supported ) do if elem == value then found = true break end end if not found then table.insert( supported, value ) end end end end -- insert escape quotes between each element local supportedValue = table.concat( supported, "\" \"" ) -- escape supportedValue on both ends osExecute( "defaults write '"..appBundleFile.."/Info' CoronaViewSupportedInterfaceOrientations -array ".. quoteString( supportedValue ) ) end -- add'l custom plist settings specific to iPhone -- defaults write is inadequate to write nested arrays and dictionaries local buildSettingsPlist = nil if deviceType == "iphone" then buildSettingsPlist = settings.iphone and settings.iphone.plist elseif deviceType == "mac" then buildSettingsPlist = settings.mac and settings.mac.plist end if buildSettingsPlist then print("Adding custom plist settings: ".. json.encode(buildSettingsPlist)) local infoPlistFile = appBundleFile .. "/Info.plist" local tmpJSONFile = os.tmpname() .. ".json" -- Convert the Info.plist to JSON and read it in osExecute( "plutil -convert json -o '"..tmpJSONFile.."' '"..infoPlistFile.."'") local jsonFP = io.open(tmpJSONFile, "r") if jsonFP ~= nil then local jsonDataStr = jsonFP:read("*a") jsonFP:close() infoPlist, errorMsg = json.decode( jsonDataStr ); if infoPlist == nil then print("Failed to load "..infoPlistFile..": "..errorMsg) os.exit(1) end end -- infoPlist now contains a Lua table representing the Info.plist print("================================") print("buildSettingsPlist: "..json.encode(buildSettingsPlist)) print("infoPlist: "..json.encode(infoPlist)) print("================================") for k, v in pairs(buildSettingsPlist) do print("Extra plist setting '"..k.."': "..tostring(v)) infoPlist[k] = v end print("infoPlist: "..json.encode(infoPlist, {indent = true})) local outFP, errorString = io.open( tmpJSONFile, "w" ) if outFP ~= nil then outFP:write( json.encode(infoPlist, {indent = true}) ) outFP:close() -- Convert the JSON plist into an XML plist osExecute("plutil -convert xml1 -o '"..infoPlistFile.."' '"..tmpJSONFile.."'") osExecute("cat '"..infoPlistFile.."'") end end end --]]
local playsession = { {"Gerkiz", {7171}}, {"rlidwka", {14203}}, {"tobot", {1171}}, {"realDonaldTrump", {47679}}, {"ChinaNumba1", {8189}}, {"Siphon098", {5748}} } return playsession
function mytransform(rec, offset) --rec['age'] = rec['age'] + offset rec['age'] = rec['age'] + 2 aerospike:update(rec) end
local helpers = require('test.gs_helpers') local clear = helpers.clear local exec_lua = helpers.exec_lua local edit = helpers.edit local eq = helpers.eq local setup_test_repo = helpers.setup_test_repo local cleanup = helpers.cleanup local command = helpers.command local test_config = helpers.test_config local match_debug_messages = helpers.match_debug_messages local p = helpers.p local setup_gitsigns = helpers.setup_gitsigns local test_file = helpers.test_file local git = helpers.git local get_buf_name = helpers.curbufmeths.get_name local it = helpers.it(it) describe('index_watcher', function() before_each(function() clear() -- Make gitisigns available exec_lua('package.path = ...', package.path) end) after_each(function() cleanup() end) it('can follow moved files', function() setup_test_repo() setup_gitsigns(test_config) edit(test_file) match_debug_messages { "run_job: git --no-pager --version", 'attach(1): Attaching (trigger=BufRead)', p"run_job: git .* config user.name", "run_job: git --no-pager rev-parse --show-toplevel --absolute-git-dir --abbrev-ref HEAD", p('run_job: git .* ls%-files .* '..test_file), 'watch_index(1): Watching index', p'run_job: git .* show :0:dummy.txt', 'update(1): updates: 1, jobs: 5', } command('Gitsigns clear_debug') git{'mv', test_file, test_file..'2'} match_debug_messages { 'watcher_cb(1): Index update', 'run_job: git --no-pager rev-parse --show-toplevel --absolute-git-dir --abbrev-ref HEAD', p('run_job: git .* ls%-files .* '..test_file), p'run_job: git .* diff %-%-name%-status %-C %-%-cached', 'handle_moved(1): File moved to dummy.txt2', p('run_job: git .* ls%-files .* '..test_file..'2'), p'run_job: git .* show :0:dummy.txt2', 'update(1): updates: 2, jobs: 10' } eq(test_file..'2', get_buf_name()) command('Gitsigns clear_debug') git{'mv', test_file..'2', test_file..'3'} match_debug_messages { 'watcher_cb(1): Index update', 'run_job: git --no-pager rev-parse --show-toplevel --absolute-git-dir --abbrev-ref HEAD', p('run_job: git .* ls%-files .* '..test_file..'2'), p'run_job: git .* diff %-%-name%-status %-C %-%-cached', 'handle_moved(1): File moved to dummy.txt3', p('run_job: git .* ls%-files .* '..test_file..'3'), p'run_job: git .* show :0:dummy.txt3', 'update(1): updates: 3, jobs: 15' } eq(test_file..'3', get_buf_name()) command('Gitsigns clear_debug') git{'mv', test_file..'3', test_file} match_debug_messages { 'watcher_cb(1): Index update', 'run_job: git --no-pager rev-parse --show-toplevel --absolute-git-dir --abbrev-ref HEAD', p('run_job: git .* ls%-files .* '..test_file..'3'), p'run_job: git .* diff %-%-name%-status %-C %-%-cached', p('run_job: git .* ls%-files .* '..test_file), 'handle_moved(1): Moved file reset', p('run_job: git .* ls%-files .* '..test_file), p'run_job: git .* show :0:dummy.txt', 'update(1): updates: 4, jobs: 21' } eq(test_file, get_buf_name()) end) end)
-- Copyright 2021 Kafka-Tarantool-Loader -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. --- --- Created by ashitov. --- DateTime: 6/16/20 10:12 AM --- local checks = require('checks') local error_repository = require('app.messages.error_repository') local log = require('log') local json = require('json') local tnt_kafka = require('kafka') local fiber = require('fiber') local clock = require('clock') local deserialize_transform = require('app.handlers.callback.kafka_msg_deserialize_transformation') local insert_transform = require('app.handlers.callback.kafka_msg_insert_transformation') local stat_insert_transform = require('app.handlers.callback.kafka_statistic_insert_transformation') local callback_transform = require('app.handlers.callback.kafka_callback_transformation') local error_transform = require('app.handlers.callback.kafka_error_handler_transformation') local commit_transfrom = require('app.handlers.callback.kafka_msg_commit_transformation') --- Consumer --- --- local function readonlytable(table) return setmetatable({}, { __index = table, __newindex = function(table, key, value) error("Attempt to modify read-only table") end, -- __metatable = false, __type = 'kafka_consumer' }); end local kafka_consumer = {} kafka_consumer.__index = kafka_consumer kafka_consumer.__call = function (cls, ...) return cls.new(...) end local function kafka_consumer_init (builder) checks('table') local err local self = setmetatable({}, kafka_consumer) self.broker = builder.broker self.options = builder.options self.default_topic_options = builder.default_topic_options self.error_callback = builder.error_callback self.log_callback = builder.log_callback self.rebalance_callback = builder.rebalance_callback self.consumer, err = tnt_kafka.Consumer.create({ brokers = self.broker, -- brokers for bootstrap options = self.options, -- options for librdkafka error_callback = self.error_callback, -- optional callback for errors log_callback = self.log_callback, -- optional callback for logs and debug messages rebalance_callback = self.rebalance_callback, -- optional callback for rebalance messages default_topic_options = self.default_topic_options }) self.subscribe_callbacks = {} self.unsubscribe_callbacks = {} if err ~= nil then return false, err end return true, self end function kafka_consumer.pause(self,topics) checks('table','table') log.info("INFO: consumer try to pause topics " .. table.concat(topics,',')) local err = self.consumer:pause(topics) if err ~= nil then return false,err end log.info("INFO: consumer paused topics " .. table.concat(topics,',')) return true, nil end function kafka_consumer.resume(self,topics) checks('table', 'table') log.info("INFO: consumer try to resume topics " .. table.concat(topics,',')) local err = self.consumer:resume(topics) if err ~= nil then return false, err end log.info("INFO: consumer resumed topics " .. table.concat(topics,',')) return true, nil end function kafka_consumer.subscribe(self,topics) checks('table', 'table') log.info("INFO: consumer subscribing to " .. table.concat(topics,',')) local err = self.consumer:subscribe(topics) if err ~= nil then return false,err end log.info("INFO: consumer subscribed to " .. table.concat(topics,',')) return true, nil end function kafka_consumer.unsubscribe(self,topics) checks('table', 'table') log.info("INFO: consumer unsubscribing from " .. table.concat(topics,',')) local err = self.consumer:unsubscribe(topics) if err ~= nil then return false, err end log.info("INFO: consumer unsubscribed from " .. table.concat(topics,',')) return true, nil end function kafka_consumer.close(self) checks('table') log.info("INFO: closing consumer") local res,err = pcall(self.consumer.close,self.consumer) self = nil return res,err end function kafka_consumer.commit(self,message) checks('table', 'userdata') local err = self.consumer:store_offset(message) if err ~= nil then return false, err end return true, nil end function kafka_consumer.commit_sync(self) checks('table') local err = self.consumer:commit_sync() if err ~= nil then return false, err end return true, nil end function kafka_consumer.commit_async(self) checks('table') local err = self.consumer:commit_async() if err ~= nil then return false, err end return true, nil end function kafka_consumer.get_message_channel(self) checks('table') local out, err = self.consumer:output() if err ~= nil then return false, err end return true, out end function kafka_consumer.poll_messages(self, amount) checks('table', 'number') local is_out_created,out = self:get_message_channel() if not is_out_created then return false, out end local msg_cnt = 0 local result = {} local timeout = amount / 1000000 while msg_cnt < amount do if out:is_closed() then return true,{result = result, amount = msg_cnt} end local msg = out:get(timeout) if msg ~= nil then msg_cnt = msg_cnt + 1 table.insert(result, msg) else return true,{result = result, amount = msg_cnt} end end return true,{result = result, amount = msg_cnt} end function kafka_consumer.init_poll_msg_fiber(process_function, kafka_stat_space_name, kafka_stat_space_insert_function ) checks('function','?string','?function') if kafka_stat_space_name ~= nil then if box.space[kafka_stat_space_name] == nil then return false, string.format("ERROR: %s space does not exists",kafka_stat_space_name) end if kafka_stat_space_insert_function == nil then return false, string.format("ERROR: function %s not registered in adg_kafka_connector role.", kafka_stat_space_insert_function) end end local is_out_created,out = self:get_message_channel() if not is_out_created then return false, out end local poll_fiber = fiber.new ( function() while true do if out.is_closed() then return end local msg = out:get(0.5) if msg ~= nil then process_function(msg) local topic_name = msg:topic() local partition_name = msg:partition() if kafka_stat_space_name ~= nil and kafka_stat_space_insert_function ~= nil then kafka_stat_space_insert_function(kafka_stat_space_name,topic_name,partition_name) end fiber.yield() end end end ) poll_fiber:name("kafka_polling_fiber") end function kafka_consumer.init_poll_msg_fiber(self) local is_out_created,out = self:get_message_channel() if not is_out_created then return false, out end local e_t = error_transform.init(100) local error_ch = e_t:get_result_channel() local d_t = deserialize_transform.init(100,out,error_ch) local deserialized = d_t:get_result_channel() local i_t = insert_transform.init(100,deserialized,error_ch) -- buffer local inserted = i_t:get_result_channel() local c_t = commit_transfrom.init(100, inserted, error_ch,self) local committed = c_t:get_result_channel() local s_i_t = stat_insert_transform.init(100, committed, error_ch) -- buffer? local inserted_with_alert = s_i_t:get_result_channel() local cb_t = callback_transform.init(100, inserted_with_alert, error_ch) end --- Builder --- --- local kafka_consumer_builder = {} kafka_consumer_builder.__index = kafka_consumer_builder kafka_consumer_builder.__type = 'kafka_consumer_builder' kafka_consumer_builder.__call = function (cls, ...) return cls.new(...) end function kafka_consumer_builder.init(broker) checks('string') local self = setmetatable({}, kafka_consumer_builder) self.broker = broker self.options = {["group.id"] = "tnt_consumer"} self.default_topic_options = {} self.error_callback = nil self.log_callback = nil self.rebalance_callback = nil return self end local function set_options_type(self,options,where) if next(options) == nil then error("Options must be non empty table") end for k,v in pairs(options) do if type(k) ~= 'string' then error("Options key " .. k .. " must be string") end if type(v) ~= 'string' then error("Options value " .. k .. ':' .. v .. " must be string") end self[where][k] = v end return self end function kafka_consumer_builder.set_options(self,options) checks('kafka_consumer_builder','table') if options ~= nil and next(options) ~= nil then return set_options_type(self,options,'options') else return self end end function kafka_consumer_builder.set_default_topic_options(self,options) checks('kafka_consumer_builder','table') return set_options_type(self,options,'default_topic_options') end function kafka_consumer_builder.set_error_callback(self, error_callback) checks('kafka_consumer_builder','function') self.error_callback = error_callback return self end function kafka_consumer_builder.set_log_callback(self, log_callback) checks('kafka_consumer_builder','function') self.log_callback = log_callback return self end function kafka_consumer_builder.set_rebalance_callback(self, rebalance_callback) checks('kafka_consumer_builder','function') self.rebalance_callback = rebalance_callback return self end function kafka_consumer_builder.build(self) checks('kafka_consumer_builder') return kafka_consumer_init(self) end return kafka_consumer_builder
----------------------------------- -- Area: Windurst Waters -- NPC: Funpo-Shipo -- Type: Standard NPC -- !pos -44.091 -4.499 41.728 238 ----------------------------------- require("scripts/globals/quests") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) local WildcatWindurst = player:getCharVar("WildcatWindurst") if (player:getQuestStatus(WINDURST, tpz.quest.id.windurst.LURE_OF_THE_WILDCAT) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst, 13) == false) then player:startEvent(938) else player:startEvent(576) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if (csid == 938) then player:setMaskBit(player:getCharVar("WildcatWindurst"), "WildcatWindurst", 13, true) end end
-------------------------------------------------------------------------------- -- КСАУП - Комплексная Система АвтоУправления поездом -------------------------------------------------------------------------------- Metrostroi.DefineSystem("KSAUP") TRAIN_SYSTEM.DontAccelerateSimulation = true function TRAIN_SYSTEM:Initialize() self.TriggerNames = { } self.Triggers = {} self.Choose = 0 self.Train:LoadSystem("R25p","Relay","KPD-110E", { in_cabin_alt4 = true }) end function TRAIN_SYSTEM:ClientInitialize() end if TURBOSTROI then return end function TRAIN_SYSTEM:Inputs() return { "Press" } end if CLIENT then function TRAIN_SYSTEM:ClientThink() end end function TRAIN_SYSTEM:UpdateUPO() for k,v in pairs(self.Train.WagonList) do if v.UPO then v.UPO:SetStations(self.Line,self.FirstStation,self.LastStation,v == self.Train) end v:OnButtonPress("RouteNumberUpdate",self.RouteNumber) end end function TRAIN_SYSTEM:Trigger(name,nosnd) end function TRAIN_SYSTEM:Think(dT) local Train = self.Train local Autodrive = Train.Autodrive if Train.VB.Value > 0.5 and Train.Battery.Voltage > 55 then for k,v in pairs(self.TriggerNames) do if Train[v] and (Train[v].Value > 0.5) ~= self.Triggers[v] then if Train[v].Value > 0.5 then self:Trigger(v) end --print(v,self.Train[v].Value > 0.5) self.Triggers[v] = Train[v].Value > 0.5 end end end if self.Timer and CurTime() - self.Timer > 0 then self.Timer = nil self.Choose = 0 end --self.FirstStation = Metrostroi.EndStations[Train.Announcer.AnnMap][self.Line] and Metrostroi.EndStations[Train.Announcer.AnnMap][self.Line][self.ChoosedFStation or 1] or 0 --self.LastStation = Metrostroi.EndStations[Train.Announcer.AnnMap][self.Line] and Metrostroi.EndStations[Train.Announcer.AnnMap][self.Line][self.ChoosedLStation or 1] or 0 if self.Train.VZD.Value > 0 and not self.VZD then self.Train.ADoorDisable:TriggerInput("Set",0) Autodrive.OnStation = false Autodrive.AutodriveReset = false Autodrive.AutodriveEnabled = false self.VZD = true end if self.Train.VZD.Value == 0 and self.VZD then self.VZD = false end if Autodrive.AutodriveReset then self.Train:TriggerInput("KVControllerAutodriveSet",0) Autodrive.NoAcceleration = nil Train:WriteCell(8,0) Train:WriteCell(29,0) Autodrive.AutodriveEnabled = false Autodrive.OnStation = false Autodrive.AutodriveReset = false Autodrive.KVPos = 0 end local AVDisable = (Train.VAutodrive.Value < 0.5 or Train.VBA.Value < 0.5 or Train.RC2.Value < 0.5 or Train.VU.Value < 0.5 or Train.Panel["SD"] < 0.5) if Train.VAutodrive.Value > 0.5 and not Autodrive.AutodriveEnabled and not Autodrive.AutodriveReset and not AVDisable then Autodrive:Enable() elseif Autodrive.AutodriveEnabled and AVDisable then Autodrive:Disable() end if Autodrive.AutodriveEnabled then Autodrive:BoardAutodrive() end --end if Autodrive.RealControllerPosition ~= self.Train.KV.RealControllerPosition then local dX = self.Train.UPO.Distance --RunConsoleCommand("say",self.Train.KV.RealControllerPosition,dX,self.Train.UPO.Station,(Metrostroi.TrainPositions[self.Train] and Metrostroi.TrainPositions[self.Train][1]) and Metrostroi.TrainPositions[self.Train][1].path.id or "unk",math.floor(self.Train.RheostatController.Position+0.5)) --file.Append("puav.txt",Format("%d\t%s\t%d\t%s\t%d\n",self.Train.KV.RealControllerPosition,dX,self.Train.UPO.Station,(Metrostroi.TrainPositions[self.Train] and Metrostroi.TrainPositions[self.Train][1]) and Metrostroi.TrainPositions[self.Train][1].path.id or "unk",math.floor(self.Train.RheostatController.Position+0.5))) Autodrive.RealControllerPosition = self.Train.KV.RealControllerPosition end self.Time = self.Time or CurTime() if (CurTime() - self.Time) > 0.1 then self.Time = CurTime() Train:SetPackedBool("KSAUP:Work",Autodrive.AutodriveEnabled and Train.Panel["V1"] > 0) Train:SetPackedBool("KSAUP:AutodriveEngage",Autodrive.KVPos and Autodrive.KVPos ~= 0 and Train.Panel["V1"] > 0) end end
-- This file is used to track and simplify dealing with all enumerations -- currently implemented in packets enumerations = {} enumerations.ai = { CANCEL = 0, ACTIVATE = 1, COMBAT = 2, ESCORT = 3, FOLLOW = 4, TRAVEL = 5, WANDER = 6 } enumerations.aiPrintableAction = { CANCEL = "cancelling current AI", ACTIVATE = "activating", COMBAT = "initiating combat with", ESCORT = "escorting", FOLLOW = "following", TRAVEL = "travelling to", WANDER = "wandering" } enumerations.container = { SET = 0, ADD = 1, REMOVE = 2 } enumerations.containerSub = { NONE = 0, DRAG = 1, DROP = 2, TAKE_ALL = 3, REPLY_TO_REQUEST = 4 } enumerations.faction = { RANK = 0, EXPULSION = 1, REPUTATION = 2 } enumerations.inventory = { SET = 0, ADD = 1, REMOVE = 2 } enumerations.journal = { ENTRY = 0, INDEX = 1 } enumerations.log = { VERBOSE = 0, INFO = 1, WARN = 2, ERROR = 3, FATAL = 4 } enumerations.miscellaneous = { MARK_LOCATION = 0, SELECTED_SPELL = 1 } enumerations.objectCategories = { PLAYER = 0, ACTOR = 1, PLACED_OBJECT = 2 } enumerations.packetOrigin = { CLIENT_GAMEPLAY = 0, CLIENT_CONSOLE = 1, CLIENT_DIALOGUE = 2, CLIENT_SCRIPT_LOCAL = 3, CLIENT_SCRIPT_GLOBAL = 4, SERVER_SCRIPT = 5 } enumerations.recordType = { ARMOR = 0, BOOK = 1, CLOTHING = 2, CREATURE = 3, ENCHANTMENT = 4, MISCELLANEOUS = 5, NPC = 6, POTION = 7, SPELL = 8, WEAPON = 9 } enumerations.resurrect = { REGULAR = 0, IMPERIAL_SHRINE = 1, TRIBUNAL_TEMPLE = 2 } enumerations.spellbook = { SET = 0, ADD = 1, REMOVE = 2 } return enumerations
local present, nvimtree = pcall(require, 'nvim-tree') if not present then return end nvimtree.setup({ update_cwd = true, diagnostics = { enable = true, icons = { hint = '', info = '', warning = '', error = '', }, }, actions = { open_file = { quit_on_open = false, }, }, view = { -- width of the window, can be either a number (columns) or a string in `%` width = 25, -- side of the tree, can be one of 'left' | 'right' | 'top' | 'bottom' side = 'left', -- if true the tree will resize itself after opening a file }, renderer = { highlight_git = true, root_folder_modifier = ':t', highlight_opened_files = 'all', indent_markers = { enable = false, }, special_files = { 'README.md', 'Makefile', 'MAKEFILE', 'package.json', '.env', }, icons = { show = { file = true, folder = true, folder_arrow = true, git = false, }, glyphs = { default = '', symlink = '', folder = { open = '', default = '', -- default = '', -- open = '', empty = '', empty_open = '', symlink = '', symlink_open = '', }, }, }, }, filters = { dotfiles = false, custom = { '.git', '.cache', 'node_modules', '_build', 'deps', 'priv', }, }, git = { ignore = false, }, }) -- Quit Neovim If NvimTree is last buffer vim.api.nvim_create_autocmd('BufEnter', { nested = true, callback = function() if vim.fn.winnr('$') == 1 and vim.fn.bufname() == ('NvimTree_' .. vim.fn.tabpagenr()) then vim.cmd('quit') end end, })
local class = require('middleclass') local HasSignals = require('HasSignals') local LocalSettings = class('LocalSettings'):include(HasSignals) local cjson = require('cjson') local function savename() return cc.FileUtils:getInstance():getWritablePath() .. '.LocalSettings' end local function saveCreateRoomConfigName() return cc.FileUtils:getInstance():getWritablePath() .. '.CreateRoomConfig' end local function saveExpressConfigName() return cc.FileUtils:getInstance():getWritablePath() .. '.ExpressConfig' end local function saveCreateRecordConfigName() return cc.FileUtils:getInstance():getWritablePath() .. '.CreateRecordConfig' end local function saveCreateDetailedRecordConfigName() return cc.FileUtils:getInstance():getWritablePath() .. '.CreateDetailedRecordConfig' end local function saveGroupConfigName() return cc.FileUtils:getInstance():getWritablePath() .. '.GroupConifg' end local roomConfig = {} local recordConfig={} local detailedRecordConfig={} local groupConfig = {} local expressConfig = {} local function merge(dst, src) for k,v in pairs(src) do if type(dst[k]) == 'table' and type(v) == 'table' then merge(dst[k], v) else dst[k] = v end end end function LocalSettings:initialize() HasSignals.initialize(self) local fu = cc.FileUtils:getInstance() local s = fu:getStringFromFile(savename()) local devinfo = require('devinfo') local defaults = { language = select(1, devinfo.locale()), auth = { methods={}, gesture={} } } self.values = defaults if #s > 2 then local loaded = cjson.decode(s) merge(self.values, loaded) end if io.exists(saveCreateRoomConfigName()) then local s = fu:getStringFromFile(saveCreateRoomConfigName()) if #s > 2 then local loaded = cjson.decode(s) merge(roomConfig, loaded) end end if io.exists(saveExpressConfigName()) then local s = fu:getStringFromFile(saveExpressConfigName()) if #s > 2 then local loaded = cjson.decode(s) merge(expressConfig, loaded) end end if io.exists(saveGroupConfigName()) then local s = fu:getStringFromFile(saveGroupConfigName()) if #s > 2 then local loaded = cjson.decode(s) merge(groupConfig, loaded) end end local fu_record=cc.FileUtils:getInstance() local s_record=fu_record:getStringFromFile(saveCreateRecordConfigName()) if #s_record > 2 then local loaded_record = cjson.decode(s_record) merge(recordConfig, loaded_record) end local fu_DRecord=cc.FileUtils:getInstance() local s_DRecord=fu_DRecord:getStringFromFile(saveCreateDetailedRecordConfigName()) if #s_DRecord > 2 then local loaded_DRecord = cjson.decode(s_DRecord) merge(detailedRecordConfig, loaded_DRecord) end end function LocalSettings:get(key) return self.values[key] end function LocalSettings:set(key, value,dontSave) self.values[key] = value if not dontSave then self:save() end end function LocalSettings:setRoomConfig(key, value) roomConfig[key] = value self:saveCreateRoomConfig() end function LocalSettings:getRoomConfig(key) return roomConfig[key] end function LocalSettings:save() local f = io.open(savename(), 'wb') f:write(cjson.encode(self.values)) f:close() end --==============================-- --desc: 保存创建房间时的配置 --time:2017-07-04 05:26:25 --@return --==============================---- function LocalSettings:saveCreateRoomConfig() local f = io.open(saveCreateRoomConfigName(), 'wb') f:write(cjson.encode(roomConfig)) f:close() end function LocalSettings:setEffectFlag(flag) self.effectOn = flag self.emitter:emit('effectSettingChg') end function LocalSettings:setMusicFlag(flag) self.musicOn = flag self.emitter:emit('musicSettingChg') end --====================================-- --desc:保存每一轮的数据 --time:2017-07-06 --====================================-- function LocalSettings:getRecordConfig(key) return recordConfig[key] end function LocalSettings:getRecordTable() return recordConfig end function LocalSettings:setRecordTable() self:saveCreateRecordConfig() end function LocalSettings:setRecordConfig(t) table.insert(recordConfig,t) if recordConfig[11]~=nil then table.remove(recordConfig,1) end self:setRecordTable() end function LocalSettings:saveCreateRecordConfig() local r = io.open(saveCreateRecordConfigName(), 'wb') r:write(cjson.encode(recordConfig)) r:close() end --===========================================-- --desc:保存每一轮的战绩详情 --time:2017-07-07 --===========================================-- function LocalSettings:getDetailedRecordConfig(key) return detailedRecordConfig[key] end function LocalSettings:getDetailedRecordConfigTable() local key = 0 for _, v in ipairs(recordConfig) do local tb = {} local round = v.round for i = 1, round do table.insert(tb, detailedRecordConfig[i + key]) end key = key + round -- dump(round) v.records = tb --dump(v) end return recordConfig end --保存每一局的战绩 function LocalSettings:setDetailedRecordConfig(t) table.insert(detailedRecordConfig,t) if detailedRecordConfig[11]~=nil then table.remove(detailedRecordConfig,1) end self:saveCreateDetailedRecordConfig() end function LocalSettings:saveCreateDetailedRecordConfig() local dr = io.open(saveCreateDetailedRecordConfigName(), 'wb') dr:write(cjson.encode(detailedRecordConfig)) dr:close() end ------------------------------------------------------------------------------------------------------------------------------------------------- function LocalSettings:setGroupConfig(key, value) if not key then return end if value == nil then return end groupConfig[key] = value self:saveGroupConfig() end function LocalSettings:getGroupConfig(key) if not key then return end return groupConfig[key] end function LocalSettings:saveGroupConfig() local r = io.open(saveGroupConfigName(), 'wb') r:write(cjson.encode(groupConfig)) r:close() end ------------------------------------------------------------------------------------------------------------------------------------------------- -- 魔法表情 function LocalSettings:setExpressConfig(key, value) expressConfig[key] = value self:saveExpressConfig() end function LocalSettings:getExpressConfig(key) return expressConfig[key] end function LocalSettings:saveExpressConfig() local f = io.open(saveExpressConfigName(), 'wb') f:write(cjson.encode(expressConfig)) f:close() end return LocalSettings
require "lunit" module(..., lunit.testcase, package.seeall) function test() local net = require "luanode.net" local common = dofile("common.lua") -- Makes sure that remoteAddress is available even after the socket has disconnected -- socket:address is not available though local server = net.createServer(function(self, cnx) process.nextTick(function() assert(cnx:remoteAddress()) assert(not cnx:address()) end) cnx:destroy() self:close() end) server:listen(common.PORT) server:on("listening", function() local client = net.createConnection(common.PORT) client:on("connect", function(self) self:destroy() end) end) process:loop() end
local meta = FindMetaTable( "Entity" ); function meta:IsTerminal() return self:GetClass() == "nss_terminal"; end function GM:MapHasTerminals() local etab = ents.FindByClass( "nss_terminal" ); if( #etab == 0 ) then return false end for _, v in pairs( etab ) do if( v:MapCreationID() >= 0 ) then return true; end end return false; end local widget_mapedit_move = { Base = "widget_axis", Setup = function( self, ent, rotate ) self:SetParent( ent ); local a, b = ent:GetRotatedAABB( ent:OBBMins(), ent:OBBMaxs() ); self:SetLocalPos( ( a + b ) / 2 ) self:SetLocalAngles( Angle( 0, 0, 0 ) ) local EntName = "widget_axis_arrow" if ( rotate ) then EntName = "widget_axis_disc" end self.ArrowX = ents.Create( EntName ) self.ArrowX:SetParent( self ) self.ArrowX:SetColor( Color( 255, 0, 0, 255 ) ) self.ArrowX:Spawn() self.ArrowX:SetLocalPos( Vector( 0, 0, 0 ) ) self.ArrowX:SetLocalAngles( Vector( 1, 0, 0 ):Angle() ) self.ArrowX:SetAxisIndex( 1 ) self.ArrowX:SetSize( 64 ); self.ArrowY = ents.Create( EntName ) self.ArrowY:SetParent( self ) self.ArrowY:SetColor( Color( 0, 230, 50, 255 ) ) self.ArrowY:Spawn() self.ArrowY:SetLocalPos( Vector( 0, 0, 0 ) ) self.ArrowY:SetLocalAngles( Vector( 0, 1, 0 ):Angle() ) self.ArrowY:SetAxisIndex( 2 ) self.ArrowY:SetSize( 64 ); self.ArrowZ = ents.Create( EntName ) self.ArrowZ:SetParent( self ) self.ArrowZ:SetColor( Color( 50, 100, 255, 255 ) ) self.ArrowZ:Spawn() self.ArrowZ:SetLocalPos( Vector( 0, 0, 0 ) ) self.ArrowZ:SetLocalAngles( Vector( 0.01, 0, 1 ):Angle() ) -- bugged self.ArrowZ:SetAxisIndex( 3 ) self.ArrowZ:SetSize( 64 ); end, OnArrowDragged = function( self, num, dist, ply, mv ) -- Prediction doesn't work properly yet.. because of the confusion with the bone moving, and the parenting, Agh. if ( CLIENT ) then return end if( !ply:IsSuperAdmin() ) then return end local ent = self:GetParent() if ( !IsValid( ent ) ) then return end local v = Vector( 0, 0, 0 ) if ( num == 1 ) then v.x = -dist end if ( num == 2 ) then v.y = -dist end if ( num == 3 ) then v.z = dist end local ang = ent:GetAngles(); if( self.Rotate == 1 ) then ang:RotateAroundAxis( ang:Forward(), -v.x ); ang:RotateAroundAxis( ang:Right(), v.y ); ang:RotateAroundAxis( ang:Up(), v.z ); ent:SetAngles( ang ); else local newPos = ent:GetPos() + ang:Forward() * -v.x + ang:Right() * v.y + ang:Up() * v.z; local trace = { }; trace.start = newPos; trace.endpos = trace.start; trace.filter = ent; local a, b = ent:GetRotatedAABB( ent:OBBMins(), ent:OBBMaxs() ); trace.mins = a; trace.maxs = b; local tr = util.TraceHull( trace ); if( !tr.HitWorld ) then ent:SetPos( newPos ); end end end } scripted_ents.Register( widget_mapedit_move, "widget_mapedit_move" );
-- This file is under copyright, and is bound to the agreement stated in the EULA. -- Any 3rd party content has been used as either public domain or with permission. -- © Copyright 2016-2017 Aritz Beobide-Cardinal All rights reserved. -- TODO: STOP MESSING WITH APP.Tiles and do the stuff properly!! local APP = ARCPhone.NewAppObject() APP.Name = "Contacts" APP.Author = "ARitz Cracker" APP.Purpose = "Contacts app for ARCPhone" APP.FlatIconName = "users-social-symbol" APP.Number = "0000000001" APP.ContactOptionNames = {} APP.ContactOptionFuncs = {} APP.ContactOptionArgs = {} local ARCPHONE_CONTACT_NUMBER = 1 local ARCPHONE_CONTACT_NAME = 2 function APP:AddContactOption(name,func,...) local dothing = true for i=1,#self.ContactOptionNames do if self.ContactOptionNames[i] == name then dothing = false end end if dothing then i = #self.ContactOptionNames + 1 self.ContactOptionNames[i] = name self.ContactOptionFuncs[i] = func self.ContactOptionArgs[i] = {...} end end function APP:RemoveContactOption(name) key = table.RemoveByValue( self.ContactOptionNames,name) if key then table.remove( self.ContactOptionFuncs, key ) table.remove( self.ContactOptionArgs, key ) end end function APP:SelectContact(tileid) if self.AttachFunc then local result = {name=self.Disk[tileid][ARCPHONE_CONTACT_NAME],number=self.Disk[tileid][ARCPHONE_CONTACT_NUMBER]} if (#self.AttachFuncArgs == 0) then self.AttachFunc(result) else self.AttachFunc(unpack(self.AttachFuncArgs),result) end self.Phone:OpenApp(self.AttachFuncApp) self:Close() return end self:ResetCurPos() self.Home = false table.Empty(self.Tiles) self.Tiles[1] = ARCPhone.NewAppTile(self) self.Tiles[1].ID = 1 self.Tiles[1].x = 8 self.Tiles[1].y = 42 self.Tiles[1].w = 122 self.Tiles[1].h = 28 self.Tiles[1].color = self.Phone.Settings.Personalization.CL_01_MainColour self.Tiles[1].ContactEditable = true if file.Exists(ARCPhone.ROOTDIR.."/contactphotos/"..self.Disk[tileid][ARCPHONE_CONTACT_NUMBER]..".dat","DATA") then self.ProfilePics[1] = Material("../data/" .. ARCPhone.ROOTDIR.."/contactphotos/"..self.Disk[tileid][ARCPHONE_CONTACT_NUMBER]..".jpg") end self.Tiles[1].drawfunc = function(tile,x,y) surface.SetDrawColor(255,255,255,255) if (tile.App.ProfilePics[tileid]) then surface.SetMaterial(tile.App.ProfilePics[tileid]) else surface.SetMaterial(tile.App.ProfilePics[0]) end surface.DrawTexturedRect( x + 2, y + 2, 24, 24 ) draw.SimpleText(tile.App.Disk[tileid][ARCPHONE_CONTACT_NAME], "ARCPhone", x + 28, y+tile.h*0.5, self.Phone.Settings.Personalization.CL_03_MainText, TEXT_ALIGN_LEFT,TEXT_ALIGN_BOTTOM) draw.SimpleText(tile.App.Disk[tileid][ARCPHONE_CONTACT_NUMBER], "ARCPhone", x + 28, y+tile.h*0.5, self.Phone.Settings.Personalization.CL_03_MainText, TEXT_ALIGN_LEFT,TEXT_ALIGN_TOP) end local len = #self.ContactOptionNames + 1 for i=2,len do self.Tiles[i] = ARCPhone.NewAppTile(self) self.Tiles[i].ID = i self.Tiles[i].x = 8 self.Tiles[i].y = 42 + i*22 self.Tiles[i].w = 122 self.Tiles[i].h = 18 self.Tiles[i].color = self.Phone.Settings.Personalization.CL_03_SecondaryColour self.Tiles[i].drawfunc = function(tile,x,y) draw.SimpleText(self.ContactOptionNames[i-1], "ARCPhone", x+tile.w*0.5, y+tile.h*0.5, self.Phone.Settings.Personalization.CL_05_SecondaryText, TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) end self.Tiles[i].OnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_04_SecondaryPressed end self.Tiles[i].OnUnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_03_SecondaryColour if #tile.App.ContactOptionArgs[i-1] > 0 then tile.App.ContactOptionFuncs[i-1](unpack(tile.App.ContactOptionArgs[i-1]),tile.App.Disk[tileid][ARCPHONE_CONTACT_NUMBER]) else tile.App.ContactOptionFuncs[i-1](tile.App.Disk[tileid][ARCPHONE_CONTACT_NUMBER]) end end end --[[ self.Tiles[1].OnPressed = function(app) self.Tiles[1].color = Color(0,0,255,128) end self.Tiles[1].OnUnPressed = function(app) self.Tiles[1].color = Color(0,0,255,255) ARCPhone.PhoneSys:AddMsgBox("Coming soon!","Todo: contact options screen","info") end ]] end function APP:ForegroundThink() end function APP:GetNameFromNumber(number) local result = "Unknown" local len = #self.Disk for i=1,len do if (self.Disk[i][ARCPHONE_CONTACT_NUMBER] == number) then result = self.Disk[i][ARCPHONE_CONTACT_NAME] break end end return result end function APP:GetDiskIDFromNumber(number) local result = 0 local len = #self.Disk for i=1,len do if (self.Disk[i][ARCPHONE_CONTACT_NUMBER] == number) then result = i break end end return result end function APP:PhoneStart() self.Options[2] = {} self.Options[2].text = "Edit" self.Options[2].func = function(app) if app.Tiles[app.SelectedAppTile].ContactEditable then app:EditContact(app.SelectedAppTile) else ARCPhone.PhoneSys:AddMsgBox("Cannot edit","You cannot edit this icon because it's not a contact entry","report-symbol") end end self.Options[2].args = {self} self.ProfilePics = {} self.ProfilePics[0] = Material("../data/" .. ARCPhone.ROOTDIR .. "/contactphotos/0000000000.jpg") local len = #self.Disk for i=1,len do if file.Exists(ARCPhone.ROOTDIR.."/contactphotos/"..self.Disk[i][ARCPHONE_CONTACT_NUMBER]..".dat","DATA") then self.ProfilePics[i] = ARCLib.MaterialFromTxt(ARCPhone.ROOTDIR.."/contactphotos/"..self.Disk[i][ARCPHONE_CONTACT_NUMBER]..".dat","jpg"); end end end function APP:Init() self:ResetCurPos() self.Home = true; self.Tiles = {} table.Empty(self.ProfilePics) self.ProfilePics[0] = Material("../data/" .. ARCPhone.ROOTDIR .. "/contactphotos/0000000000.jpg") local len = #self.Disk for i=1,len do self.Tiles[i] = ARCPhone.NewAppTile(self) self.Tiles[i].ID = i self.Tiles[i].x = 8 self.Tiles[i].y = 10 + i*32 self.Tiles[i].w = 122 self.Tiles[i].h = 28 self.Tiles[i].color = self.Phone.Settings.Personalization.CL_01_MainColour self.Tiles[i].ContactEditable = true if file.Exists(ARCPhone.ROOTDIR.."/contactphotos/"..self.Disk[i][ARCPHONE_CONTACT_NUMBER]..".jpg","DATA") then self.ProfilePics[i] = Material("../data/" .. ARCPhone.ROOTDIR .. "/contactphotos/"..self.Disk[i][ARCPHONE_CONTACT_NUMBER]..".jpg") end self.Tiles[i].drawfunc = function(tile,x,y) surface.SetDrawColor(255,255,255,255) if (tile.App.ProfilePics[i]) then surface.SetMaterial(tile.App.ProfilePics[i]) else surface.SetMaterial(tile.App.ProfilePics[0]) end surface.DrawTexturedRect( x + 2, y + 2, 24, 24 ) surface.SetDrawColor(ARCLib.ConvertColor(self.Phone.Settings.Personalization.CL_03_MainText)) draw.SimpleText(tile.App.Disk[i][ARCPHONE_CONTACT_NAME], "ARCPhone", x + 28, y+tile.h*0.5, self.Phone.Settings.Personalization.CL_03_MainText, TEXT_ALIGN_LEFT,TEXT_ALIGN_BOTTOM) draw.SimpleText(tile.App.Disk[i][ARCPHONE_CONTACT_NUMBER], "ARCPhone", x + 28, y+tile.h*0.5, self.Phone.Settings.Personalization.CL_03_MainText, TEXT_ALIGN_LEFT,TEXT_ALIGN_TOP) end self.Tiles[i].OnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_02_MainPressed end self.Tiles[i].OnUnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_01_MainColour tile.App:SelectContact(i) end end len = len + 1 self.Tiles[len] = ARCPhone.NewAppTile(self) self.Tiles[len].ID = len self.Tiles[len].x = 8 self.Tiles[len].y = 10 + len*32 self.Tiles[len].w = 122 self.Tiles[len].h = 28 self.Tiles[len].color = self.Phone.Settings.Personalization.CL_03_SecondaryColour self.Tiles[len].drawfunc = function(tile,x,y) draw.SimpleText("**New contact**", "ARCPhone", x+tile.w*0.5, y+tile.h*0.5, self.Phone.Settings.Personalization.CL_05_SecondaryText, TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) end self.Tiles[len].OnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_04_SecondaryPressed end self.Tiles[len].OnUnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_03_SecondaryColour tile.App:EditContact(0) end len = len + 1 self.Tiles[len] = ARCPhone.NewAppTile(self) self.Tiles[len].ID = len self.Tiles[len].x = 8 self.Tiles[len].y = 10 + len*32 self.Tiles[len].w = 122 self.Tiles[len].h = 28 self.Tiles[len].color = self.Phone.Settings.Personalization.CL_03_SecondaryColour self.Tiles[len].drawfunc = function(tile,x,y) draw.SimpleText("**People near by**", "ARCPhone", x+tile.w*0.5, y+tile.h*0.5, self.Phone.Settings.Personalization.CL_05_SecondaryText, TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) end self.Tiles[len].OnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_04_SecondaryPressed end self.Tiles[len].OnUnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_03_SecondaryColour if tile.App.Phone.Reception < 15 then tile.App.Phone:AddMsgBox("No signal","You do not have enough reception to perform this operation","warning-sign") else tile.App.Phone:SetLoading(-1) tile.App:SendText("f") end -- end end --APP:Init() function APP:OnText(timestamp,data) self.Home = false self:ResetCurPos() self.Tiles = {} self.Phone:SetLoading(-2) local numbers = string.Explode(" ",data) local len = #numbers for i=1,len do local number = numbers[i] local name = ARCPhone.GetPlayerFromPhoneNumber(number):Nick() self.Tiles[i] = ARCPhone.NewAppTile(self) self.Tiles[i].ID = i self.Tiles[i].x = 8 self.Tiles[i].y = 10 + i*32 self.Tiles[i].w = 122 self.Tiles[i].h = 28 self.Tiles[i].color = self.Phone.Settings.Personalization.CL_01_MainColour self.Tiles[i].ContactEditable = true self.Tiles[i].drawfunc = function(tile,x,y) surface.SetDrawColor(255,255,255,255) surface.SetMaterial(tile.App.ProfilePics[0]) surface.DrawTexturedRect( x + 2, y + 2, 24, 24 ) surface.SetDrawColor(ARCLib.ConvertColor(self.Phone.Settings.Personalization.CL_03_MainText)) draw.SimpleText(name, "ARCPhone", x + 28, y+tile.h*0.5, self.Phone.Settings.Personalization.CL_03_MainText, TEXT_ALIGN_LEFT,TEXT_ALIGN_BOTTOM) draw.SimpleText(number, "ARCPhone", x + 28, y+tile.h*0.5, self.Phone.Settings.Personalization.CL_03_MainText, TEXT_ALIGN_LEFT,TEXT_ALIGN_TOP) end self.Tiles[i].OnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_02_MainPressed end self.Tiles[i].OnUnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_01_MainColour local len = #tile.App.Disk + 1 tile.App.Disk[len] = {} tile.App.Disk[len][ARCPHONE_CONTACT_NAME] = name tile.App.Disk[len][ARCPHONE_CONTACT_NUMBER] = number tile.App:SelectContact(len) end end end function APP:EditContact(tileid) self:ResetCurPos() self.Home = false self.Tiles = {} self.Tiles[1] = ARCPhone.NewAppTile(self) self.Tiles[1].ID = 1 self.Tiles[1].x = 8 self.Tiles[1].y = 24 self.Tiles[1].w = 24 self.Tiles[1].h = 24 self.Tiles[1].TextureNoresize = true self.Tiles[1].color = color_white if self.ProfilePics[tileid] then self.Tiles[1].mat = self.ProfilePics[tileid] else self.Tiles[1].mat = self.ProfilePics[0] end self.Tiles[1].OnPressed = function(tile) tile.color = Color(255,255,255,128) end self.Tiles[1].OnUnPressed = function(tile) tile.color = color_white tile.App.Phone:AddMsgBox("Coming soon!","You cannot change contact photos yet") end if (tileid > 0) then self.Tiles[2] = ARCPhone.NewAppTextInputTile(self,self.Disk[tileid][ARCPHONE_CONTACT_NAME],false,118) self.Tiles[3] = ARCPhone.NewAppTextInputTile(self,self.Disk[tileid][ARCPHONE_CONTACT_NUMBER],false,118) else self.Tiles[2] = ARCPhone.NewAppTextInputTile(self,"",false,118) self.Tiles[3] = ARCPhone.NewAppTextInputTile(self,"",false,118) end self.Tiles[2].ID = 2 self.Tiles[3].ID = 3 self.Tiles[2]:SetPlaceholder("Contact Name") self.Tiles[3]:SetPlaceholder("Insert Number") self.Tiles[2].SingleLine = true self.Tiles[3].SingleLine = true self.Tiles[2].y = 24 self.Tiles[2].w = 92 self.Tiles[2].x = 34 self.Tiles[2].color = self.Phone.Settings.Personalization.CL_09_QuaternaryColour self.Tiles[3].y = 42 self.Tiles[3].w = 92 self.Tiles[3].x = 34 self.Tiles[3].color = self.Phone.Settings.Personalization.CL_09_QuaternaryColour self.Tiles[4] = ARCPhone.NewAppTile(self) self.Tiles[4].ID = 4 self.Tiles[4].x = 8 self.Tiles[4].y = 194 self.Tiles[4].w = 122 self.Tiles[4].h = 18 self.Tiles[4].color = self.Phone.Settings.Personalization.CL_09_QuaternaryColour self.Tiles[4].OnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_10_QuaternaryPressed end self.Tiles[4].OnUnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_09_QuaternaryColour if (tileid > 0) then table.remove(tile.App.Disk,tileid) end tile.App:SaveData() tile.App:Init() end self.Tiles[4].drawfunc = function(tile,x,y) draw.SimpleText( "Delete", "ARCPhone", x+tile.w*0.5, y+tile.h*0.5, self.Phone.Settings.Personalization.CL_11_QuaternaryText, TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) end self.Tiles[5] = ARCPhone.NewAppTile(self) self.Tiles[5].ID = 5 self.Tiles[5].x = 8 self.Tiles[5].y = 218 self.Tiles[5].w = 122 self.Tiles[5].h = 18 self.Tiles[5].color = self.Phone.Settings.Personalization.CL_01_MainColour self.Tiles[5].OnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_02_MainPressed end self.Tiles[5].OnUnPressed = function(tile) tile.color = self.Phone.Settings.Personalization.CL_01_MainColour if (ARCPhone.IsValidPhoneNumber(tile.App.Tiles[3].TextInput)) then if (tileid > 0) then tile.App.Disk[tileid][ARCPHONE_CONTACT_NAME] = tile.App.Tiles[2].TextInput tile.App.Disk[tileid][ARCPHONE_CONTACT_NUMBER] = tile.App.Tiles[3].TextInput else local len = #tile.App.Disk + 1 tile.App.Disk[len] = {} tile.App.Disk[len][ARCPHONE_CONTACT_NAME] = tile.App.Tiles[2].TextInput tile.App.Disk[len][ARCPHONE_CONTACT_NUMBER] = tile.App.Tiles[3].TextInput end tile.App:SaveData() tile.App:Init() else tile.App.Phone:AddMsgBox("Cannot save","the number you have entered is invalid.","report-symbol") end end self.Tiles[5].drawfunc = function(tile,x,y) draw.SimpleText( "Save", "ARCPhone", x+tile.w*0.5, y+tile.h*0.5, self.Phone.Settings.Personalization.CL_03_MainText, TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER) end end function APP:OnBack() if self.Home then if self.AttachFunc then self.Phone:OpenApp(self.AttachFuncApp,true,false) self:Close() else self:Close() end else self:Init() end end function APP:ChooseContact(app,func,...) self.AttachFunc = func self.AttachFuncArgs = {...} --[[ for i=1,#self.AttachFuncArgs do MsgN("i => "..tostring(self.AttachFuncArgs[i])) end ]] self.AttachFuncApp = app end function APP:OnClose() self.AttachFunc = nil self.AttachFuncArgs = nil self.AttachFuncApp = nil end ARCPhone.RegisterApp(APP,"contacts")
local JSON = require("App42-Lua-API.JSON") local App42Exception = require("App42-Lua-API.App42Exception") local App42ExceptionRequest = {} function App42ExceptionRequest:buildInternalExceptionRequest(exceptionString) local app42Exception = App42Exception:new() app42Exception:setMessage(exceptionString) app42Exception:setAppErrorCode("null") app42Exception:setHttpErrorCode("null") app42Exception:setDetails("null") return app42Exception end function App42ExceptionRequest:buildExceptionRequest(exceptionString) local app42Exception = App42Exception:new() local jsonObj = JSON:decode(exceptionString) local jsonObjApp42 = jsonObj.app42Fault app42Exception:setMessage(jsonObjApp42.message) app42Exception:setAppErrorCode(jsonObjApp42.appErrorCode) app42Exception:setHttpErrorCode(jsonObjApp42.httpErrorCode) app42Exception:setDetails(jsonObjApp42.details) return app42Exception end return App42ExceptionRequest
-------------------------------------------------------------------------- -- Consistent-Hashing balancer -- -- This balancer implements a consistent-hashing algorithm based on the -- Ketama algorithm. -- -- This load balancer is designed to make sure that every time a load -- balancer object is built, it is built the same, no matter the order the -- process is done. -- -- __NOTE:__ This documentation only described the altered user -- methods/properties, see the `user properties` from the `balancer_base` -- for a complete overview. -- -- @author Vinicius Mignot -- @copyright 2020 Kong Inc. All rights reserved. -- @license Apache 2.0 local balancer_base = require "resty.dns.balancer.base" local xxhash32 = require "luaxxhash" local floor = math.floor local ngx_log = ngx.log local ngx_CRIT = ngx.CRIT local ngx_DEBUG = ngx.DEBUG local ngx_ERR = ngx.ERR local table_sort = table.sort -- constants local DEFAULT_CONTINUUM_SIZE = 1000 local MAX_CONTINUUM_SIZE = 2^32 local MIN_CONTINUUM_SIZE = 1000 local SERVER_POINTS = 160 -- number of points when all targets have same weight local SEP = " " -- string separator to be used when hashing hostnames local _M = {} local consistent_hashing = {} -- returns the index a value will point to in a generic continuum, based on -- continuum size local function get_continuum_index(value, points) return ((xxhash32(tostring(value)) % points) + 1) end -- hosts and addresses must be sorted lexically before adding to the continuum, -- so they are added always in the same order. This makes sure that collisions -- will be treated always the same way. local function sort_hosts_and_addresses(balancer) if type(balancer) ~= "table" then error("balancer must be a table") end if balancer.hosts == nil then return end table_sort(balancer.hosts, function(a, b) local ta = tostring(a.hostname) local tb = tostring(b.hostname) return ta < tb or (ta == tb and tonumber(a.port) < tonumber(b.port)) end) for _, host in ipairs(balancer.hosts) do table_sort(host.addresses, function(a, b) return (tostring(a.ip) .. ":" .. tostring(a.port)) < (tostring(b.ip) .. ":" .. tostring(b.port)) end) end end --- Adds a host to the balancer. -- This function checks if there is enough points to add more hosts and -- then call the base class's `addHost()`. -- see `addHost()` from the `balancer_base` for more details. function consistent_hashing:addHost(hostname, port, weight) local host_count = #self.hosts + 1 if (host_count * SERVER_POINTS) >= self.points then ngx_log(ngx_ERR, self.log_prefix, "consistent hashing balancer requires ", "more entries to be able to add the number of hosts requested, ", "please increase the wheel size") return nil, "not enough free slots to add more hosts" end self.super.addHost(self, hostname, port, weight) return self end --- Actually adds the addresses to the continuum. -- This function should not be called directly, as it will called by -- `addHost()` after adding the new host. -- This function makes sure the continuum will be built identically every -- time, no matter the order the hosts are added. function consistent_hashing:afterHostUpdate(host) local points = self.points local new_continuum = {} local total_weight = self.weight local host_count = #self.hosts local total_collision = 0 sort_hosts_and_addresses(self) for weight, address, h in self:addressIter() do local addr_prop = weight / total_weight local entries = floor(addr_prop * host_count * SERVER_POINTS) if weight > 0 and entries == 0 then entries = 1 -- every address with weight > 0 must have at least one entry end local port = address.port and ":" .. tostring(address.port) or "" local i = 1 while i <= entries do local name = tostring(address.ip) .. ":" .. port .. SEP .. tostring(i) local index = get_continuum_index(name, points) if new_continuum[index] == nil then new_continuum[index] = address else entries = entries + 1 -- move the problem forward total_collision = total_collision + 1 end i = i + 1 if i > self.points then -- this should happen only if there are an awful amount of hosts with -- low relative weight. ngx_log(ngx_CRIT, "consistent hashing balancer requires more entries ", "to add the number of hosts requested, please increase the ", "wheel size") return end end end ngx_log(ngx_DEBUG, self.log_prefix, "continuum of size ", self.points, " updated with ", total_collision, " collisions") self.continuum = new_continuum end --- Gets an IP/port/hostname combo for the value to hash -- This function will hash the `valueToHash` param and use it as an index -- in the continuum. It will return the address that is at the hashed -- value or the first one found going counter-clockwise in the continuum. -- @param cacheOnly If truthy, no dns lookups will be done, only cache. -- @param handle the `handle` returned by a previous call to `getPeer`. -- This will retain some state over retries. See also `setAddressStatus`. -- @param valueToHash value for consistent hashing. Please note that this -- value will be hashed, so no need to hash it prior to calling this -- function. -- @return `ip + port + hostheader` + `handle`, or `nil+error` function consistent_hashing:getPeer(cacheOnly, handle, valueToHash) ngx_log(ngx_DEBUG, self.log_prefix, "trying to get peer with value to hash: [", valueToHash, "]") if not self.healthy then return nil, balancer_base.errors.ERR_BALANCER_UNHEALTHY end if handle then -- existing handle, so it's a retry handle.retryCount = handle.retryCount + 1 else -- no handle, so this is a first try handle = self:getHandle() -- no GC specific handler needed handle.retryCount = 0 end if not handle.hashValue then if not valueToHash then error("can't getPeer with no value to hash", 2) end handle.hashValue = get_continuum_index(valueToHash, self.points) end local address local index = handle.hashValue local ip, port, hostname while (index - 1) ~= handle.hashValue do if index == 0 then index = self.points end address = self.continuum[index] if address ~= nil and address.available and not address.disabled then ip, port, hostname = address:getPeer(cacheOnly) if ip then -- success, update handle handle.address = address return ip, port, hostname, handle elseif port == balancer_base.errors.ERR_DNS_UPDATED then -- we just need to retry the same index, no change for 'pointer', just -- in case of dns updates, we need to check our health again. if not self.healthy then return nil, balancer_base.errors.ERR_BALANCER_UNHEALTHY end elseif port == balancer_base.errors.ERR_ADDRESS_UNAVAILABLE then ngx_log(ngx_DEBUG, self.log_prefix, "found address but it was unavailable. ", " trying next one.") else -- an unknown error occured return nil, port end end index = index - 1 end return nil, balancer_base.errors.ERR_NO_PEERS_AVAILABLE end --- Creates a new balancer. -- -- The balancer is based on a wheel (continuum) with a number of points -- between MIN_CONTINUUM_SIZE and MAX_CONTINUUM_SIZE points. Key points -- will be assigned to addresses based on their IP and port. The number -- of points each address will be assigned is proportional to their weight. -- -- The options table has the following fields, additional to the ones from -- the `balancer_base`: -- -- - `hosts` (optional) containing hostnames, ports, and weights. If -- omitted, ports and weights default respectively to 80 and 10. The list -- will be sorted before being added, so the order of entry is -- deterministic. -- - `wheelSize` (optional) for total number of positions in the -- continuum. If omitted `DEFAULT_CONTINUUM_SIZE` is used. It is important -- to have enough indices to fit all addresses entries, keep in mind that -- each address will use 160 entries in the continuum (more or less, -- proportional to its weight, but the total points will always be -- `160 * addresses`). Consider the maximum number of targets expected, as -- new hosts can be dynamically added, and DNS renewals might yield -- larger record sets. The `wheelSize` cannot be altered, the object has -- to built again to change this value. On a similar note, making it too -- big will have a performance impact to get peers from the continuum, as -- the values will be too dispersed among them. -- @param opts table with options -- @return new balancer object or nil+error function _M.new(opts) assert(type(opts) == "table", "Expected an options table, but got: "..type(opts)) if not opts.log_prefix then opts.log_prefix = "hash-lb" end local self = assert(balancer_base.new(opts)) self.continuum = {} self.points = (opts.wheelSize and opts.wheelSize >= MIN_CONTINUUM_SIZE and opts.wheelSize <= MAX_CONTINUUM_SIZE) and opts.wheelSize or DEFAULT_CONTINUUM_SIZE -- inject overridden methods for name, method in pairs(consistent_hashing) do self[name] = method end for _, host in ipairs(opts.hosts or {}) do local new_host = type(host) == "table" and host or { name = host } local ok, err = self:addHost(new_host.name, new_host.port, new_host.weight) if not ok then return ok, "Failed creating a balancer: " .. tostring(err) end end ngx_log(ngx_DEBUG, self.log_prefix, "consistent_hashing balancer created") return self end -------------------------------------------------------------------------------- -- for testing only function consistent_hashing:_get_continuum() return self.continuum end function consistent_hashing:_hit_all() for _, address in pairs(self.continuum) do if address.host then address:getPeer() end end end return _M
-------------------------------- -- @module TileMapAtlas -- @extend AtlasNode -------------------------------- -- @function [parent=#TileMapAtlas] initWithTileFile -- @param self -- @param #string str -- @param #string str -- @param #int int -- @param #int int -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#TileMapAtlas] releaseMap -- @param self -------------------------------- -- @function [parent=#TileMapAtlas] getTGAInfo -- @param self -- @return sImageTGA#sImageTGA ret (return value: cc.sImageTGA) -------------------------------- -- @function [parent=#TileMapAtlas] getTileAt -- @param self -- @param #point_table point -- @return color3B_table#color3B_table ret (return value: color3B_table) -------------------------------- -- @function [parent=#TileMapAtlas] setTile -- @param self -- @param #color3B_table color3b -- @param #point_table point -------------------------------- -- @function [parent=#TileMapAtlas] setTGAInfo -- @param self -- @param #cc.sImageTGA simagetga -------------------------------- -- @function [parent=#TileMapAtlas] create -- @param self -- @param #string str -- @param #string str -- @param #int int -- @param #int int -- @return TileMapAtlas#TileMapAtlas ret (return value: cc.TileMapAtlas) -------------------------------- -- @function [parent=#TileMapAtlas] TileMapAtlas -- @param self return nil
local library = require("CoronaLibrary") -- Create library local lib = library:new{name = "plugin.teads", publisherId = "com.coronalabs", version = 1} -- Default implementations local function defaultFunction() print("WARNING: The '" .. lib.name .. "' library is not available on this platform.") end -- Stub functions lib.init = defaultFunction lib.load = defaultFunction lib.isLoaded = defaultFunction lib.show = defaultFunction return lib
local st = {} function st:draw() State.menu:draw() end local hot function st:update(dt) love.graphics.setFont(Font[80]) gui.group.push{grow = 'down', pos = {20,20}, size={WIDTH-40,30}} gui.Label{text = "panoptes", align = "center", size={nil,80}} love.graphics.setFont(Font[40]) gui.Label{text = "", align = "center", size={nil,30}} love.graphics.setFont(Font[40]) gui.Label{text = "A game by vrld", align = "center"} love.graphics.setFont(Font[20]) gui.Label{text = "Made in 48 hours for the 31st ludum dare", align = "center"} gui.Label{text = "themed: entire game on one screen", align = "center"} love.graphics.setFont(Font[25]) gui.Label{text = "Made with LOVE (love2d.org)", align = "center"} gui.Label{text = "Font: Silkscreen by Jason Kotte (kotte.org)", align = "center"} gui.Label{text = "", align = "center", size={nil,50}} love.graphics.setFont(Font[40]) gui.Label{text = "Shout out goes to", align = "center"} love.graphics.setFont(Font[25]) gui.Label{text = "cappel:nord, fysx, headchant, steven colling", align = "center"} gui.Label{text = "bartbes, bmelts, rude, slime", align = "center"} gui.Label{text = "and all the lovers out there", align = "center"} gui.group.pop{} love.graphics.setFont(Font[30]) gui.group.push{grow = 'right', pos = {WIDTH-210,HEIGHT-70}, size={190,50}} if gui.Button{text = 'Back'} then GS.pop() end gui.group.pop{} local h = gui.mouse.getHot() if h ~= hot and h ~= nil then Sound.static.btn:play() end hot = h end function st:keypressed(key) if key == 'escape' then GS.pop() end end return st
-- game_reset [game_session_key_prefix] local keys = redis.call('KEYS', KEYS[1] .. '*') for i=#keys,1,-1 do if keys[i]:find("players") then table.remove(keys, i) end end return redis.call('DEL', unpack(keys))
-- By calling atan2 we receive the radian rotation angle between the player.x pos and player.y pos and entity.y and entity.x function entityToPlayerAngle(entity) local px = player:getX() local py = player:getY() return math.atan2(py - entity.y, px - entity.x) end -- Distance formula which will be then used to determine the distance between player and the entity -- We will find if distance is very low, it will be considered a collision. function distanceBetween(x1, y1, x2, y2) return math.sqrt( (x2 - x1)^2 + (y2 - y1)^2 ) end -- By calling atan2 we receive the radian rotation angle between the weaponPos X, weaponPos Y and mouseY and mouseX function weaponMouseAngle() return math.atan2(love.mouse.getY() - weapons.holding.posY, love.mouse.getX() - weapons.holding.posX) end function lerp(a,b,t) return (1-t)*a + t*b end
print 'remove 2' for i = 1,5 do print('-------',i) local mytable = {10,20,30,40} print(table.remove(mytable,i)) for k,v in ipairs(mytable) do print (k,v) end end print 'remove 1' do local mytable = {10,20,30,40} local x repeat x = table.remove(mytable) print(x) until(not x) end print 'sort' do local mytable = {59,60,73,11,8,74,3,65,60,23} table.sort(mytable) print(table.concat(mytable,',')) end