content
stringlengths
5
1.05M
--- === plugins.microsoftteams.application.manager === --- --- Registers Microsoft Teams with the Core Application Manager if installed. local require = require local application = require "hs.application" local infoForBundleID = application.infoForBundleID local plugin = { id = "microsoftteams.application.manager", group = "microsoftteams", dependencies = { ["core.application.manager"] = "manager", } } function plugin.init(deps) local bundleID = "com.microsoft.teams" if infoForBundleID(bundleID) then deps.manager.registerApplication({ bundleID = bundleID, displayName = "Microsoft Teams", }) end end return plugin
require("import") -- the import fn import("cpp11_strongly_typed_enumerations") -- import lib -- catch "undefined" global variables local env = _ENV -- Lua 5.2 if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) function enumCheck(actual, expected) if not (actual == expected) then error("Enum value mismatch. Expected: "..expected.." Actual: "..actual) end return expected + 1 end --val = 0 --val = enumCheck(cpp11_strongly_typed_enumerations.cpp11_strongly_typed_enumerations.Enum1_Val1, val) local val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val1, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val2, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val3, 13) val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val4, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val5a, 13) val = enumCheck(cpp11_strongly_typed_enumerations.Enum1_Val6a, val) val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val1, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val2, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val3, 23) val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val4, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val5b, 23) val = enumCheck(cpp11_strongly_typed_enumerations.Enum2_Val6b, val) val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Val1, val) val = enumCheck(cpp11_strongly_typed_enumerations.Val2, val) val = enumCheck(cpp11_strongly_typed_enumerations.Val3, 43) val = enumCheck(cpp11_strongly_typed_enumerations.Val4, val) val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Enum5_Val1, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum5_Val2, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum5_Val3, 53) val = enumCheck(cpp11_strongly_typed_enumerations.Enum5_Val4, val) val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Enum6_Val1, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum6_Val2, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum6_Val3, 63) val = enumCheck(cpp11_strongly_typed_enumerations.Enum6_Val4, val) val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Enum7td_Val1, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum7td_Val2, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum7td_Val3, 73) val = enumCheck(cpp11_strongly_typed_enumerations.Enum7td_Val4, val) val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Enum8_Val1, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum8_Val2, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum8_Val3, 83) val = enumCheck(cpp11_strongly_typed_enumerations.Enum8_Val4, val) val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Enum10_Val1, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum10_Val2, val) val = enumCheck(cpp11_strongly_typed_enumerations.Enum10_Val3, 103) val = enumCheck(cpp11_strongly_typed_enumerations.Enum10_Val4, val) val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum12_Val1, 1121) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum12_Val2, 1122) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum12_Val3, val) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum12_Val4, val) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum12_Val5c, 1121) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum12_Val6c, val) val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Val1, 1131) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Val2, 1132) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Val3, val) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Val4, val) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Val5d, 1131) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Val6d, val) val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum14_Val1, 1141) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum14_Val2, 1142) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum14_Val3, val) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum14_Val4, val) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum14_Val5e, 1141) val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Enum14_Val6e, val) -- Requires nested class support to work --val = 0 --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val1, 3121) --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val2, 3122) --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val3, val) --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val4, val) --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val5f, 3121) --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val6f, val) -- --val = 0 --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Val1, 3131) --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Val2, 3132) --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Val3, val) --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Val4, val) -- --val = 0 --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum14_Val1, 3141) --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum14_Val2, 3142) --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum14_Val3, val) --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum14_Val4, val) --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum14_Val5g, 3141) --val = enumCheck(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum14_Val6g, val) val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum12_Val1, 2121) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum12_Val2, 2122) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum12_Val3, val) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum12_Val4, val) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum12_Val5h, 2121) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum12_Val6h, val) val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Val1, 2131) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Val2, 2132) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Val3, val) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Val4, val) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Val5i, 2131) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Val6i, val) val = 0 val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum14_Val1, 2141) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum14_Val2, 2142) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum14_Val3, val) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum14_Val4, val) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum14_Val5j, 2141) val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Enum14_Val6j, val) -- Requires nested class support to work --val = 0 --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Enum12_Val1, 4121) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Enum12_Val2, 4122) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Enum12_Val3, val) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Enum12_Val4, val) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Enum12_Val5k, 4121) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Enum12_Val6k, val) -- --val = 0 --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Val1, 4131) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Val2, 4132) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Val3, val) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Val4, val) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Val5l, 4131) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Val6l, val) -- --val = 0 --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Enum14_Val1, 4141) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Enum14_Val2, 4142) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Enum14_Val3, val) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Enum14_Val4, val) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Enum14_Val5m, 4141) --val = enumCheck(cpp11_strongly_typed_enumerations.Class2.Struct1.Enum14_Val6m, val) class1 = cpp11_strongly_typed_enumerations.Class1() enumCheck(class1:class1Test1(cpp11_strongly_typed_enumerations.Enum1_Val5a), 13) enumCheck(class1:class1Test2(cpp11_strongly_typed_enumerations.Class1.Enum12_Val5c), 1121) --enumCheck(class1:class1Test3(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val5f), 3121) enumCheck(cpp11_strongly_typed_enumerations.globalTest1(cpp11_strongly_typed_enumerations.Enum1_Val5a), 13) enumCheck(cpp11_strongly_typed_enumerations.globalTest2(cpp11_strongly_typed_enumerations.Class1.Enum12_Val5c), 1121) --enumCheck(globalTest3(cpp11_strongly_typed_enumerations.Class1.Struct1.Enum12_Val5f), 3121)
function processRequest(url, requestHeaders, cookies, hostname) local query = urlParser.parse(url).query if not query.username then return false end local result = exports.dpCore:getUserAccount(query.username) if not result then result = { error = "User not found" } end return { data = toJSON(result), headers = { ["Access-Control-Allow-Origin"] = "*", ["Access-Control-Allow-Methods"] = "GET,PUT,POST,DELETE,OPTIONS", ["Access-Control-Allow-Headers"] = "X-Requested-With,Content-Type,Cache-Control", } } end
local function bottleneck() if remote.interfaces["Bottleneck"] and remote.interfaces["Bottleneck"]["blacklist_name"] then remote.call("Bottleneck", "blacklist_name", "liquify2-liquifier") end end script.on_init(bottleneck); script.on_load(bottleneck);
Citizen.CreateThread(function() while true do Citizen.Wait(0) if NetworkIsSessionStarted() then TriggerServerEvent("Queue:playerActivated") return end end end)
-- lodr helper: erase lodr from the arg array local alreadyRan = false local target = require("z_lodrSupport.target") return function() if not alreadyRan then alreadyRan = true arg[0] = target local argc = #arg for i=1,argc do arg[i] = arg[i+1] end end end
---@type ModuleA local a ---@type string local num num = a.module_scoped_var
--Keep traders from bringing blood, ichor, or goo with their caravans. local my_entity=df.historical_entity.find(df.global.ui.civ_id) local sText=" " local k=0 local v=1 for x,y in pairs(df.global.world.entities.all) do my_entity=y k=0 while k < #my_entity.resources.misc_mat.extracts.mat_index do v=my_entity.resources.misc_mat.extracts.mat_type[k] sText=dfhack.matinfo.decode(v,my_entity.resources.misc_mat.extracts.mat_index[k]) if (sText==nil) then --LIQUID barrels my_entity.resources.misc_mat.extracts.mat_type:erase(k) my_entity.resources.misc_mat.extracts.mat_index:erase(k) k=k-1 else if(sText.material.id=="BLOOD") then my_entity.resources.misc_mat.extracts.mat_type:erase(k) my_entity.resources.misc_mat.extracts.mat_index:erase(k) k=k-1 end if(sText.material.id=="ICHOR") then my_entity.resources.misc_mat.extracts.mat_type:erase(k) my_entity.resources.misc_mat.extracts.mat_index:erase(k) k=k-1 end if(sText.material.id=="GOO") then my_entity.resources.misc_mat.extracts.mat_type:erase(k) my_entity.resources.misc_mat.extracts.mat_index:erase(k) k=k-1 end --VENOM --POISON --FLUID --MILK --EXTRACT end k=k+1 end end
module(..., package.seeall) NODE = { title="@JavaScript (Prototype for Javascript Pages)", prototype="@Text_Config", category="_prototypes", actions=[[js="javascript.js"]], permissions = [[allow(all_users, "js")]], content=[[ The content of this page is ignored but it's fields are inherited by some of the other pages of this wiki.]], http_cache_control = "max-age=3600", http_expires = "2", }
local Peg = require "espalier:espalier/peg" local subGrammar = require "espalier:espalier/subgrammar" local fragments = require "orb:orb/fragments" local Twig = require "orb:orb/metas/twig" local table_str = [[ table ← WS* handle* WS* row+ row ← WS* pipe cell (!table-end pipe cell)* table-end cell ← (!table-end !pipe 1)+ pipe ← "|" `table-end` ← (pipe / hline / double-row)* line-end hline ← "~" double-row ← "\\" WS ← " "+ line-end ← (block-sep / "\n" / -1) block-sep ← "\n\n" "\n"* ]] table_str = table_str .. fragments.handle .. fragments.symbol local table_grammar = Peg(table_str, {Twig}) return subGrammar(table_grammar, nil, "table-nomatch")
-- Raid Debuffs general options local L = LibStub("AceLocale-3.0"):GetLocale("Grid2Options") local RDO = Grid2Options.RDO local options = {} RDO.OPTIONS_GENERAL = options function RDO:InitGeneralOptions() Grid2Options:MakeStatusTitleOptions( RDO.statuses[1], options) end -- separate content from title options.separator0 = { type = "description", order = 9, name = "\n" } -- raid-debuffs statuses do local statusColor = { type = "color", width = "full", name = function(info) return RDO.statusesNames[info.arg] end, hasAlpha = true, get = function(info) local c = RDO.statuses[info.arg].dbx.color1 return c.r, c.g, c.b, c.a end, set = function(info, r,g,b,a) local c = RDO.statuses[info.arg].dbx.color1 c.r, c.g, c.b, c.a = r, g, b, a end, hidden = function(info) return info.arg>#RDO.statuses end } local meta = { __index = statusColor } options.status1 = setmetatable( { order = 10 , arg=1 }, meta ) options.status2 = setmetatable( { order = 11 , arg=2 }, meta ) options.status3 = setmetatable( { order = 12 , arg=3 }, meta ) options.status4 = setmetatable( { order = 13 , arg=4 }, meta ) options.status5 = setmetatable( { order = 14 , arg=5 }, meta ) end options.newStatus = { type = "execute", order = 50, width = "half", name = L["New"], desc = L["New Status"], func = function(info) local name = string.format("raid-debuffs%d", #RDO.statuses+1) Grid2:DbSetValue( "statuses", name, {type = "raid-debuffs", debuffs={}, color1 = {r=1,g=.5,b=1,a=1}} ) Grid2.setupFunc["raid-debuffs"]( name, Grid2:DbGetValue("statuses", name) ) RDO:LoadStatuses() end, hidden = function() return #RDO.statuses>=5 end } options.deleteStatus = { type = "execute", order = 51, width = "half", name = L["Delete"], desc = L["Delete last status"], func = function(info) local status = RDO.statuses[#RDO.statuses] options[status.name] = nil Grid2:DbSetValue( "statuses", status.name, nil) Grid2:UnregisterStatus( status ) RDO:LoadStatuses() end, confirm = function(info) return string.format( L["Are your sure you want to delete %s status ?"], RDO.statusesNames[#RDO.statuses] ) end, disabled = function() local status = RDO.statuses[#RDO.statuses] return status.enabled or next(status.dbx.debuffs) or RDO.auto_enabled end, hidden = function() return #RDO.statuses<=1 end, } -- debuffs autodetection do local function AddToTooltip(tooltip) tooltip:AddDoubleLine( L["RaidDebuffs Autodetection"], L["Enabled"], 255,255,255, 255,255,0) end options.autodetect = { type = "group", order = 100, name = L["Debuffs Autodetection"], inline= true, args = { autoenable = { type = "toggle", order = 1, name = L["Enable Autodetection"], desc = L["Enable Zones and Debuffs autodetection"], get = function() return RDO.auto_enabled end, set = function(_, v) RDO:SetAutodetect(v) if not v then RDO:RefreshAdvancedOptions() end Grid2.tooltipFunc["RaidDebuffsAuto"] = v and AddToTooltip or nil end, }, autostatus = { type = "select", order = 2, name = L["Assigned to"], desc = L["Assign autodetected raid debuffs to the specified status"], get = function () return RDO.db.profile.auto_status or 1 end, set = function (_, v) local status = RDO.statuses[v] if status then RDO.db.profile.auto_status = v>1 and v or nil RDO:RefreshAutodetect() end end, values = RDO.statusesNames, disabled = function() return RDO.auto_enabled end } } } end -- enabled/disable modules do local modules = {} options.modules= { type = "multiselect", name = L["Enabled raid debuffs modules"], order = 150, get = function(info,key) return RDO.db.profile.enabledModules[key] ~= nil end, set = function(_,module,state) RDO.db.profile.enabledModules[module] = state or nil for instance in pairs(RDO.RDDB[module]) do if state then RDO:EnableInstanceAllDebuffs(module,instance) else RDO:DisableInstanceAllDebuffs(instance) end end RDO:UpdateZoneSpells() RDO:RefreshAdvancedOptions() end, values = function() wipe(modules) for name in pairs(RDO.RDDB) do if name ~= "[Custom Debuffs]" then modules[name] = L[name] end end return modules end, disabled = function() return RDO.auto_enabled end } end -- encounter journal if not Grid2.isClassic then options.header3 = { type = "header", order = 52, name = "" } options.difficulty = { type = "select", order = 200, name = L["Encounter Journal difficulty"], desc = L["Default difficulty for Encounter Journal links"], get = function () return RDO.db.profile.defaultEJ_difficulty or 14 end, set = function (_, v) RDO.db.profile.defaultEJ_difficulty = v end, values = { [14] = PLAYER_DIFFICULTY1, -- Normal [15] = PLAYER_DIFFICULTY2, -- Heroic [16] = PLAYER_DIFFICULTY6, -- Mythic [17] = PLAYER_DIFFICULTY3 -- LFR }, } end
local M = {} M.config = function() require'telescope'.setup{ extensions = { fzf = { fuzzy = true, override_generic_sorter = true, override_file_sorter = true, }, }, } require'telescope'.load_extension'fzf' local map = vim.api.nvim_set_keymap local opts = {noremap = true, silent = true} map('n', ']g', '<Cmd>lua require"telescope.builtin".live_grep()<CR>', opts) map('n', ']f', '<Cmd>lua require"telescope.builtin".find_files()<CR>', opts) map('n', ']h', '<Cmd>lua require"telescope.builtin".help_tags()<CR>', opts) end return M
-- Dependencies local Playable = require("engine.Playable") -- Repeater class local Repeater = Playable:derive("Repeater") -- Constructor function Repeater:Repeater(period, callback) self:Playable() -- Superclass constructor self.period = period -- Repetition period self.callback = callback -- Callback function end -- Updates repeater function Repeater:update(delta) if Playable.update(self, delta) and self.time > self.period then self.time = self.time % self.period self.callback() end end return Repeater
local function LogAndTsay(str) ulx.logString("[HSNotice] " .. str) ulx.tsay(NULL, "[HSNotice] " .. str) end function HSNotice.JoinAlert(pl) local str = "플레이어[" .. (pl:Nick() or "{UNKNOWN}") .. "] 님께서 게임에 참여하셨습니다. (" .. pl:IPAddress() .. ")" LogAndTsay(str) end hook.Remove("PlayerInitialSpawn", "HSNotice.JoinAlert", HSNotice.JoinAlert) hook.Add("PlayerInitialSpawn", "HSNotice.JoinAlert", HSNotice.JoinAlert)
----------------------------------- -- -- Zone: Lower_Jeuno (245) -- ----------------------------------- local ID = require("scripts/zones/Lower_Jeuno/IDs") require("scripts/zones/Lower_Jeuno/globals") require("scripts/globals/conquest") require("scripts/globals/keyitems") require("scripts/globals/missions") require("scripts/globals/pathfind") require("scripts/globals/settings") require("scripts/globals/chocobo") require("scripts/globals/status") ----------------------------------- function onInitialize(zone) zone:registerRegion(1, 23, 0, -43, 44, 7, -39) -- Inside Tenshodo HQ tpz.chocobo.initZone(zone) end function onZoneIn(player, prevZone) local cs = -1 local month = tonumber(os.date("%m")) local day = tonumber(os.date("%d")) -- Retail start/end dates vary, I am going with Dec 5th through Jan 5th. if (month == 12 and day >= 5) or (month == 1 and day <= 5) then player:ChangeMusic(0, 239) player:ChangeMusic(1, 239) -- No need for an 'else' to change it back outside these dates as a re-zone will handle that. end -- MOG HOUSE EXIT if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then player:setPos(41.2, -5, 84, 85) if player:getMainJob() ~= player:getCharVar("PlayerMainJob") and player:getGMLevel() == 0 then cs = 30004 end player:setCharVar("PlayerMainJob", 0) elseif player:getCurrentMission(COP) == tpz.mission.id.cop.TENDING_AGED_WOUNDS and player:getCharVar("PromathiaStatus") == 0 then player:setCharVar("PromathiaStatus", 1) cs = 70 elseif ENABLE_ACP == 1 and player:getCurrentMission(ACP) == tpz.mission.id.acp.A_CRYSTALLINE_PROPHECY and player:getMainLvl() >=10 then cs = 10094 end return cs end function onConquestUpdate(zone, updatetype) tpz.conq.onConquestUpdate(zone, updatetype) end function onRegionEnter(player, region) if region:GetRegionID() == 1 then if player:getCurrentMission(ZILART) == tpz.mission.id.zilart.AWAKENING and player:getCharVar("ZilartStatus") < 2 then player:startEvent(20) end end end function onGameHour(zone) local VanadielHour = VanadielHour() local playerOnQuestId = GetServerVariable("[JEUNO]CommService") local playerOnQuest = GetPlayerByID(playerOnQuestId) -- Community Service Quest -- 7AM: it's daytime. turn off all the lights if VanadielHour == 7 then for i=0, 11 do local lamp = GetNPCByID(ID.npc.STREETLAMP_OFFSET + i) lamp:setAnimation(tpz.anim.CLOSE_DOOR) end -- 8PM: make quest available -- notify anyone in zone with membership card that zauko is recruiting elseif VanadielHour == 18 then SetServerVariable("[JEUNO]CommService", 0) local players = zone:getPlayers() for name, player in pairs(players) do if player:hasKeyItem(tpz.ki.LAMP_LIGHTERS_MEMBERSHIP_CARD) then player:messageSpecial(ID.text.ZAUKO_IS_RECRUITING) end end -- 9PM: notify the person on the quest that they can begin lighting lamps elseif VanadielHour == 21 then local playerOnQuest = GetPlayerByID(GetServerVariable("[JEUNO]CommService")) if playerOnQuest then playerOnQuest:startEvent(114) end -- 1AM: if nobody has accepted the quest yet, NPC Vhana Ehgaklywha takes up the task -- she starts near Zauko and paths all the way to the Rolanberry exit. -- tpz.path.flag.WALLHACK because she gets stuck on some terrain otherwise. elseif VanadielHour == 1 then if playerOnQuestId == 0 then local npc = GetNPCByID(ID.npc.VHANA_EHGAKLYWHA) npc:clearPath() npc:setStatus(0) npc:initNpcAi() npc:setPos(tpz.path.first(LOWER_JEUNO.lampPath)) npc:pathThrough(tpz.path.fromStart(LOWER_JEUNO.lampPath), bit.bor(tpz.path.flag.RUN, tpz.path.flag.WALLHACK)) end end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if csid == 30004 and option == 0 then player:setHomePoint() player:messageSpecial(ID.text.HOMEPOINT_SET) elseif csid == 20 then player:addCharVar("ZilartStatus", 2) elseif csid == 10094 then player:completeMission(ACP, tpz.mission.id.acp.A_CRYSTALLINE_PROPHECY) player:addMission(ACP, tpz.mission.id.acp.THE_ECHO_AWAKENS) end end
local Class = require "hump.class" local Vector = require "hump.vector" local BaseObject = require "toys/baseObject" Rectangle = Class{__includes = BaseObject} function Rectangle:init(world, mapObject) -- calculate values from map object self.width, self.height = mapObject.width, mapObject.height local xSpawn, ySpawn = mapObject.x + (self.width / 2), mapObject.y + (self.height / 2) local bodyType = self:checkStaticBool(mapObject.properties.static) self.body = love.physics.newBody(world, xSpawn, ySpawn, bodyType) self.body:setUserData({ type = "rectangle", collisionSfxFolder = mapObject.properties.collisionSfxFolder or "generic" }) self.shape = love.physics.newRectangleShape(0, 0, self.width, self.height) self.fixture = love.physics.newFixture(self.body, self.shape); self.fixture:setFriction(0.9) self.color = {1, 0.2, 0.7} local centre = Vector(self.body:getPosition()) -- get the rotation point (top left corner) local rotationPoint = Vector(centre.x - self.width/2, centre.y - self.height/2) -- move to be around rotation point centre = centre - rotationPoint -- rotate local new = centre:rotated(math.rad(mapObject.rotation)) -- move point back centre = new + rotationPoint self.body:setPosition(centre:unpack()) self.body:setAngle(math.rad(mapObject.rotation)) if mapObject.properties.texturePath then self.image = love.graphics.newImage(mapObject.properties.texturePath) end -- check if we're important to the camera self.cameraDistance = mapObject.properties.cameraDistance self.cameraFocus = mapObject.properties.cameraFocus end function Rectangle:getPosition() return self.body:getPosition() end function Rectangle:draw() self:drawRectangleObject(self) end return Rectangle
local items = __pointers__.items local entities = __pointers__.entities for i=1,#items do local item = items:at(i) local speed = 5.0 local dir = vec2.normalize(vec2.new(400, 300) - item.pos) * speed item.vel = dir end
local Module = {} return Module
local LabelID = {} LabelAll = 0 addEvent("doCreateLabel", true) addEventHandler("doCreateLabel", root, function(text, color, x, y, z, dis, dimens, font, size) create3DTextLabel(text, color, x, y, z, dis, dimens, font, size) end) addEvent("doRemoveLabel", true) addEventHandler("doRemoveLabel", root, function(id) delete3DTextLabel(id) end) addEvent("doUpdateLabel", true) addEventHandler("doUpdateLabel", root, function(i, t, c, x, y, z, d, f, g, s) update3DTextLabel(i, t, c, x, y, z, d, f, g, s) end) addEvent("doAttachLabel", true) addEventHandler("doAttachLabel", root, function(i, e, x, y, z, d) attach3DTextLabelToElement(i, e, x, y, z, d) end) addEvent("doDetachLabel", true) addEventHandler("doDetachLabel", root, function(i) detach3DTextLabel(i) end) function create3DTextLabel(text, color, x, y, z, dis, dimens, font, size) --def 150 if not text then return false end if not color then color = tocolor(255, 255, 255, 255) end if not x or x == "x" then x = getElementPosition(localPlayer) end if not y or y == "x" then _, y = getElementPosition(localPlayer) end if not z or z == "x" then _, _, z = getElementPosition(localPlayer) end if not dis or not tonumber(dis) then dis = 150 end if not dimens or not tonumber(dimens) then dimens = -1 end if not font then font = "default-bold" end if not size or not tonumber(size) or tonumber(size) <= 0 then size = 1 end --LabelAll = id LabelAll = LabelAll + 1 color = string.format("%x", color) local alpha = string.sub(color, 1, 2) color = "0x"..color LabelID[LabelAll] = {} LabelID[LabelAll]["PosX"] = tonumber(x) LabelID[LabelAll]["PosY"] = tonumber(y) LabelID[LabelAll]["PosZ"] = tonumber(z) LabelID[LabelAll]["Text"] = text LabelID[LabelAll]["Dist"] = tonumber(dis) LabelID[LabelAll]["Colr"] = tonumber(color) LabelID[LabelAll]["Alph"] = tostring(alpha) LabelID[LabelAll]["Enbl"] = true LabelID[LabelAll]["Dimn"] = tonumber(dimens) LabelID[LabelAll]["BDim"] = false LabelID[LabelAll]["Attc"] = false LabelID[LabelAll]["AttX"] = 0 LabelID[LabelAll]["AttY"] = 0 LabelID[LabelAll]["AttZ"] = 0 LabelID[LabelAll]["Font"] = font LabelID[LabelAll]["Size"] = tonumber(size) if LabelID[LabelAll]["Dimn"] and LabelID[LabelAll]["Dimn"] >= 0 then LabelID[LabelAll]["BDim"] = true end showLabel(LabelAll) triggerServerEvent("addLabels", root, LabelAll) return LabelAll end function delete3DTextLabel(id) if not LabelID[id] then return false end LabelID[id]["Enbl"] = false end function update3DTextLabel(id, text, color, x, y, z, dist, dimens, font, size) if not LabelID[id] then return false end if not text then return false end if not color then color = LabelID[id]["Colr"] end if not x or not tonumber(x) then x = LabelID[id]["PosX"] end if not y or not tonumber(y) then y = LabelID[id]["PosY"] end if not z or not tonumber(z) then z = LabelID[id]["PosZ"] end if not dist or not tonumber(dist) then dist = LabelID[id]["Dist"] end if not dimens or not tonumber(dimens) then dimens = LabelID[LabelAll]["Dimn"] end if not font then font = LabelID[id]["Font"] end if not size or not tonumber(size) or tonumber(size) <= 0 then size = LabelID[LabelAll]["Size"] end color = string.format("%x", color) local alpha = string.sub(color, 1, 2) color = "0x"..color LabelID[id]["Text"] = text LabelID[id]["Colr"] = tonumber(color) LabelID[id]["Alph"] = tostring(alpha) LabelID[id]["PosX"] = x LabelID[id]["PosY"] = y LabelID[id]["PosZ"] = z LabelID[id]["Dist"] = tonumber(dist) LabelID[id]["Dimn"] = tonumber(dimens) LabelID[id]["BDim"] = false LabelID[id]["Font"] = font LabelID[id]["Size"] = tonumber(size) if LabelID[id]["Dimn"] and LabelID[id]["Dimn"] >= 0 then LabelID[id]["BDim"] = true end end function attach3DTextLabelToElement(id, element, x, y, z, dimens) if not LabelID[id] then return false end if not isElement(element) then return false end if not x or not tonumber(x) then x = 0 end if not y or not tonumber(y) then y = 0 end if not z or not tonumber(z) then z = 0 end if not dimens or not tonumber(dimens) then dimens = -1 end LabelID[id]["Attc"] = element LabelID[id]["AttX"] = tonumber(x) LabelID[id]["AttY"] = tonumber(y) LabelID[id]["AttZ"] = tonumber(z) LabelID[id]["Dimn"] = tonumber(dimens) LabelID[id]["BDim"] = false if LabelID[id]["Dimn"] and LabelID[id]["Dimn"] >= 0 then LabelID[id]["BDim"] = true end end function detach3DTextLabel(id) if not LabelID[id] then return false end LabelID[id]["Attc"] = false end function labelFunction(id, x, y, z, text, dis, color, alpha, font, size) if not LabelID[id] then return nil end local NewX,NewY,NewZ = getElementPosition(localPlayer) local distance = getDistanceBetweenPoints3D(x,y,z,NewX,NewY,NewZ) if distance <= dis then local ScX,ScY = getScreenFromWorldPosition(x, y, z+0.95, 0.06) if not ScX then return end dxDrawText(text:gsub("#%x%x%x%x%x%x", ""), ScX+2, ScY-30+2, ScX, ScY-30, tonumber("0x"..alpha.."000000"), math.min(0.3*(dis/distance)*1.4*size,size), font, "center", "bottom", false, false, false) dxDrawText(text:gsub("#%x%x%x%x%x%x", ""), ScX-2, ScY-30+2, ScX, ScY-30, tonumber("0x"..alpha.."000000"), math.min(0.3*(dis/distance)*1.4*size,size), font, "center", "bottom", false, false, false) dxDrawText(text:gsub("#%x%x%x%x%x%x", ""), ScX+2, ScY-30-2, ScX, ScY-30, tonumber("0x"..alpha.."000000"), math.min(0.3*(dis/distance)*1.4*size,size), font, "center", "bottom", false, false, false) dxDrawText(text:gsub("#%x%x%x%x%x%x", ""), ScX-2, ScY-30-2, ScX, ScY-30, tonumber("0x"..alpha.."000000"), math.min(0.3*(dis/distance)*1.4*size,size), font, "center", "bottom", false, false, false) dxDrawText(text, ScX, ScY-30, ScX, ScY-30, color, math.min(0.3*(dis/distance)*1.4*size,size), font, "center", "bottom", false, false, false, true) end end function showLabel(id) if not LabelID[id] then return nil end addEventHandler("onClientRender",getRootElement(), function() if LabelID[id]["BDim"] then if getElementDimension(localPlayer) ~= LabelID[id]["Dimn"] then return 1; end end if not LabelID[id]["Enbl"] then cancelEvent() return 1; end if LabelID[id]["Attc"] ~= false then if not isElement(LabelID[id]["Attc"]) then LabelID[id]["Attc"] = false return 1; end local nx, ny, nz = getElementPosition(LabelID[id]["Attc"]) LabelID[id]["PosX"] = nx+LabelID[id]["AttX"] LabelID[id]["PosY"] = ny+LabelID[id]["AttY"] LabelID[id]["PosZ"] = nz+LabelID[id]["AttZ"] end labelFunction(id, LabelID[id]["PosX"], LabelID[id]["PosY"], LabelID[id]["PosZ"], LabelID[id]["Text"], LabelID[id]["Dist"], LabelID[id]["Colr"], LabelID[id]["Alph"], LabelID[id]["Font"], LabelID[id]["Size"]) end) end --[[addEventHandler("onClientResourceStart", root, function() label = create3DTextLabel("Lost", 0xFFFFFF00, 0, 0, 10, 700, 0) labels = create3DTextLabel("test", 0xFFFFF000, 0, 0, 15, 700, 0) labelz = create3DTextLabel("Fest", 0xFFFFF000, 0, 0, 20, 700, 0) attach3DTextLabelToElement(label, localPlayer or getPedOccupiedVehicle(localPlayer)) setTimer(function() local vx, vy, vz = getElementPosition(localPlayer or getPedOccupiedVehicle(localPlayer)) update3DTextLabel(label, "#FF0000X: #FFFFFF"..string.format("%.4f", vx).."\n#FF0000Y: #FFFFFF"..string.format("%.4f", vy).."\n#FF0000Z: #FFFFFF"..string.format("%.4f", vz)) end, 50, 1000) setTimer(function() detach3DTextLabel(label) end, 52*1000, 1) end)]]
local baton = require 'libs.baton' local controlsA = baton.new { controls = { left = {'key:left', 'axis:leftx-', 'button:dpleft'}, right = {'key:right', 'axis:leftx+', 'button:dpright'}, up = {'key:up', 'axis:lefty-', 'button:dpup'}, down = {'key:down', 'axis:lefty+', 'button:dpdown'}, action = {'key:rctrl', 'button:a'} }, pairs = { move = {'left', 'right', 'up', 'down'} }, joystick = love.joystick.getJoysticks()[1] } local controlsB = baton.new { controls = { left = {'key:a', 'axis:leftx-', 'button:dpleft'}, right = {'key:d', 'axis:leftx+', 'button:dpright'}, up = {'key:w', 'axis:lefty-', 'button:dpup'}, down = {'key:s', 'axis:lefty+', 'button:dpdown'}, action = {'key:space', 'button:a'} }, pairs = { move = {'left', 'right', 'up', 'down'} }, joystick = love.joystick.getJoysticks()[2] } return {controlsA, controlsB}
local IInput = require("api.gui.IInput") local IUiLayer = require("api.gui.IUiLayer") local InputHandler = require("api.gui.InputHandler") local UiTheme = require("api.gui.UiTheme") local VisualAIBlockList = require("mod.visual_ai.api.gui.VisualAIBlockList") local Ui = require("api.Ui") local UiWindow = require("api.gui.UiWindow") local TopicWindow = require("api.gui.TopicWindow") local Draw = require("api.Draw") local I18N = require("api.I18N") local utils = require("mod.visual_ai.internal.utils") local VisualAIConfigureBlockMenu = require("mod.visual_ai.api.gui.VisualAIConfigureBlockMenu") local Gui = require("api.Gui") local VisualAIInsertMenu = class.class("VisualAIInsertMenu", IUiLayer) VisualAIInsertMenu:delegate("input", IInput) function VisualAIInsertMenu:init(title, category_idx, item_id) self.list = VisualAIBlockList:new() self.category_win = TopicWindow:new(1, 1) self.category_text = "" local key_hints = self:make_key_hints() self.win = UiWindow:new(title or "", true, key_hints) self.input = InputHandler:new() self.input:forward_to(self.list) self.input:bind_keys(self:make_keymap()) self.list:set_category(category_idx or 1) if item_id then self.list:select_block(item_id) end self.category_text = I18N.get("visual_ai.gui.menu.category", "visual_ai.gui.category." .. self.list.category) end function VisualAIInsertMenu:make_keymap() return { escape = function() self.canceled = true end, cancel = function() self.canceled = true end } end function VisualAIInsertMenu:make_key_hints() local hints = self.list:make_key_hints() hints[#hints+1] = { action = "ui.key_hint.action.close", key_name = "ui.key_hint.key.cancel", keys = { "cancel", "escape" } } return hints end function VisualAIInsertMenu:on_query() Gui.play_sound("base.pop2") self.canceled = false end function VisualAIInsertMenu:relayout(x, y, width, height) self.width = 400 self.height = 520 self.x, self.y = Ui.params_centered(self.width, self.height) self.y = self.y + 20 self.t = UiTheme.load(self) self.win:relayout(self.x, self.y, self.width, self.height) self.list:relayout(self.x + 15, self.y + 10 + 50, self.width - 20, self.height - 20 - 40 - 30) self.category_win:relayout(self.x + 10 + 50, self.y + 32, self.width - 20 - 100, 40) end function VisualAIInsertMenu:draw() self.win:draw() self.list:draw() self.category_win:draw() Draw.set_font(15) Draw.set_color(0, 0, 0) Draw.text_shadowed(self.category_text, self.category_win.x + self.category_win.width / 2 - Draw.text_width(self.category_text) / 2, self.category_win.y + self.category_win.height / 2 - Draw.text_height() / 2) end local function make_var_defs(block) local values = block.vars local defs = block.proto.vars local result = {} for var_name, def in pairs(defs) do result[#result+1] = { name = var_name, def = def, value = assert(values[var_name]) } end return result end function VisualAIInsertMenu:update(dt) local changed = self.list.changed local canceled = self.canceled local chosen = self.list:update(dt) self.win:update(dt) self.category_win:update(dt) self.canceled = false if changed then self.category_text = I18N.get("visual_ai.gui.menu.category", "visual_ai.gui.category." .. self.list.category) end if chosen then Gui.play_sound("base.ok1") local block = utils.make_block(chosen.block_id) if next(block.proto.vars) then local var_defs = make_var_defs(block) local vars, canceled = VisualAIConfigureBlockMenu:new(block.proto, var_defs):query() if not canceled then block.vars = vars return { last_category = chosen.last_category, block = block }, nil end else return { last_category = chosen.last_category, block = block }, nil end end if canceled then return { last_category = self.list.category }, "canceled" end end return VisualAIInsertMenu
-- require 'tableutils'; loadModule("util/tableutils"); loadModule("util/checkutils"); --[[! \file \brief Este script define funciones auxiliares e iteradores útiles para trabajar con cadenas e caracteres. ]] --! Iterador de palabras separadas por uno o varios separadores (por defecto, espacios) --! Los separadores pueden especificarse como una lista de carácteres (como argumentos separados), --! o pueden ser indicados todos dentro de una sola cadena. ejemplo: --! El iterador irá devolviendo las palabras de las que se compone la cadena de caracteres. --[[! \code{lua} for word in wpairs("hello world", ' ') do print(word); end; -- output: -- hello -- world \endcode ]] --! Otro ejemplo. --[[! \code{lua} for word in wpairs("hi - worl - d", '- ') do print(word); end; --output: -- hi -- worl -- d \endcode ]] function wpairs(text, delimiters) checkArgumentType("wpairs", 2, text, 1, "string"); checkOptionalArgument("wpairs", 2, delimiters, 2, "string"); delimiters = parseOptionalArguments(delimiters, ' '); return string.gmatch(text, "[^" .. delimiters .. "]+"); end; --[[! Igual que wpairs, solo que se itera de derecha a izquierda. ]] function rwpairs(text, delimiters) checkArgumentType("rwpairs", 2, text, 1, "string"); checkOptionalArgumentType("rwpairs", 2, delimiters, 2, "string"); -- separar las palabras y meterlas en una tabla auxiliar. local words = {}; local i = 0; for word in wpairs(text, delimiters) do i = i + 1; words[i] = word; end; -- si no hay ninguna palabra, devolvemos un iterador tonto. if #words == 0 then return function() end, nil, nil; end; -- damos la vuelta a la tabla. local reversed_words = {}; i = 0; for _, word in ripairs(words) do i = i + 1; reversed_words[i] = word; end; -- devolvemos el iterador. return string.gmatch(table.concat(reversed_words, ' '), "[^ ]+"); end;
return { name = "Mage", description = "Mages spend years learning to harness arcane forces to impose their will on the world around them. As scholars, they tend to be less brawny than Warriors and less stout than Clerics. Their powerful spells keep them alive and allow them to wreak havoc... as long as they have the mana to cast them.", abilityTable = { [5] = { spells = { "fireball" } } }, setupPlayer = function(state, player) local mana = state.AttributeFactory:create("mana", 100); player:addAttribute(mana); player.prompt = "[ %health.current%/%health.max% <bold>hp %mana.current%/%mana.max% <bold>mana ]"; end, };
return { ["trail"] = "iz", ["texture filter"] = "doku filtresi", ["show only with active weapon"] = "sadece aktif silah çıkmışken göster", ["parent velocity length"] = "ebeveyn hız büyükluğü", ["equal"] = "eşit", ["owner velocity right"] = "sahip sağ hızı", ["owner velocity length"] = "sahip hız büyüklüğü", ["timerx"] = "zamanlayıcıX", ["shake"] = "sallanma", ["entity class"] = "entity adı", ["load from url"] = "url'den parçaları aç", ["owner velocity forward"] = "sahip hız ileri", ["light"] = "ışık", ["event"] = "olay", ["follow part name"] = "takip edilecek parça adı", ["is crouching"] = "eğiliyor", ["language"] = "dil", ["lock 1"] = "kilit 1", ["find"] = "find (bul)", ["orientation"] = "oryantasyon", ["help"] = "yardım", ["play count"] = "oynatma sayısı (0 sonsuz)", ["generic"] = "generik", ["speed"] = "hız", ["projectile"] = "mermi (projectile)", ["command"] = "komut", ["events"] = "olaylar", ["weapon"] = "silah", ["size"] = "boyut", ["clone"] = "klon", ["has weapon"] = "silahı var", ["load parts"] = "parçaları aç", ["load"] = "aç", ["hide editor"] = "editorü sakla", ["hide entity"] = "entity gizle", ["health lost"] = "can kayıp", ["name"] = "isim", ["particles"] = "parçacık", ["is on ground"] = "yerde", ["loop"] = "dongü", ["above"] = "üzeri", ["reset view"] = "görüşü sıfırla", ["reset eye angles"] = "ğöz açısını sıfırla", ["physics"] = "fizik", ["draw weapon"] = "silahı göster", ["lock 0"] = "kilit 0", ["true"] = "gerçek ", ["position offset"] = "pozisyon çıkıntısı", ["weapon class"] = "silah tipi", ["jiggle"] = "sallantı", ["new file"] = "yeni dosya", ["advanced"] = "gelişmiş", ["color"] = "renk", ["skirt"] = "etek", ["hide weapon"] = "silahı gizle", ["player"] = "oyuncu", ["ammo"] = "cephane", ["parent velocity forward"] = "ebeveyn hız ileri", ["exit"] = "çık", ["alternative bones"] = "alternatif kemikler", ["revert"] = "geri dödür", ["modified"] = "modifiye", ["angle offset"] = "açı çıkıntısı", ["sunbeams"] = "güneş ışını", ["remove"] = "kaldır", ["max pitch"] = "max eğim", ["volume"] = "ses şiddeti", ["ok"] = "tamam", ["ogg"] = "ogg", ["outline"] = "dışçizg", ["invert"] = "çevir", ["holdtype"] = "tutma türü", ["alternative scaling"] = "alternatif büyütme", ["tint color"] = "tint rengi", ["is in noclip"] = "noclipde", ["show editor"] = "editorü göster", ["play on footstep"] = "ayak sesi olarak oynat", ["parent velocity up"] = "ebeveyn yukarı hızı", ["paste"] = "yapıştır", ["wear on server"] = "parçaları sunucuda giy", ["wear parts"] = "parçaları giy", ["toggle focus"] = "focus geçiş", ["toggle basic mode"] = "kolay moda geçis", ["scale"] = "boyut", ["pitch"] = "eğim", ["aim part name"] = "hedef parça adı", ["draw order"] = "görünum mesafesi", ["is under water"] = "su altında", ["view"] = "görüntüle", ["clip"] = "kırpma", ["is voice chatting"] = "mikrafon kullanıyor", ["copy global id"] = "global id kopyala", ["copy"] = "kopyala", ["equal or below"] = "eşit yada altında", ["draw distance"] = "görüş mesafesi", ["hide"] = "sakla", ["position"] = "pozisyon", ["duplicate"] = "kopya yarat", ["editor"] = "düzenleyici ", ["timer"] = "zamanlayıcı", ["is client"] = "client ", ["operators"] = "operatörler", ["edit"] = "duzenle", ["modifiers"] = "modifiyeciler", ["effects"] = "efektler", ["sound"] = "ses", ["owner armor"] = "sahip armoru", ["sound level"] = "ses aşaması", ["equal or above"] = "eşit yada üzerinde", ["enable"] = "etkin hale getir", ["eye angles"] = "göz açısı", ["footstep"] = "ayakbasma", ["fog"] = "sis", ["health"] = "can", ["false"] = "yanlış", ["put parts in submenu"] = "parçaları submenüye koy", ["translation editor"] = "dil editörü", ["min pitch"] = "min eğim", ["material"] = "doku (material)", ["filename:"] = "dosya adı: ", ["group"] = "gurup", ["filter type"] = "filter type (filtre tipi)", ["find simple"] = "find simple (kolay bul)", ["fall apart on death"] = "olünce parçaları düşür", ["font"] = "font", ["fullbright"] = "fullparlak", ["getting started"] = "başlarken", ["affect children only"] = "sadece childreni etkile", ["draw in reflections"] = "yansımalarda çiz", ["is flashlight on"] = "ışığı açık", ["owner entity"] = "sahip varlığı (entity)", ["lock 2"] = "kilit 2", ["save"] = "kaydet", ["pause on hide"] = "saklamada durdur", ["tools"] = "araçlar", ["maybe"] = "belki", ["owner velocity up"] = "sahip yukarı hızı", ["vehicle class"] = "araç tipi", ["spawn as props"] = "prop olarak meydana getir", ["save parts"] = "parçaları kaydet", ["outline alpha"] = "dışçizg alfası", ["parent velocity right"] = "ebeveyn sağ hızı", ["show weapon"] = "silahı göster", ["about"] = "hakkında", ["options"] = "ayarlar", ["show deprecated features"] = "kaldırlılmış özellikleri göster", ["draw shadow"] = "gölgeyi göster", ["parent name"] = "ebeveyn adı", ["alpha"] = "alfa", ["show in firstperson"] = "birinci şahıs (firstperson) da göster", ["examples"] = "örnekler", ["advanced mode"] = "gelişmiş modu", ["stop on hide"] = "saklayınca durdur", ["owner name"] = "sahip adı", ["overlapping"] = "çakışma", ["effect"] = "efekt", ["wear"] = "giy", ["say"] = "söyle", ["sequence name"] = "sekans adı ", ["outline color"] = "dışçizgi rengi", ["other"] = "başka", ["light blend"] = "ışık blend", ["mute footsteps"] = "ayak sesini kapat", ["move speed"] = "ilerleme hızı", ["t pose"] = "t pozu", ["text"] = "yazı", ["model name"] = "model adı", ["owner health"] = "sahip canı", ["toggle camera follow"] = "camera takibine geçiş", ["time"] = "zaman", ["position grid size"] = "pozisyon grid boyutu", ["not equal"] = "eşit değil", ["toggle t pose"] = "t posuna geçiş", }
return { level = 63, need_exp = 140000, clothes_attrs = { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, }, }
local jsonish = require 'jsonish' local t = require 'testhelper' t( jsonish '', nil ) t( jsonish '1', 1 ) t( jsonish 'true', true ) t( jsonish '"hi"', "hi" ) t( jsonish '""', "" ) t( jsonish [["\u0021"]], [[!]] ) t( jsonish [["h\u0021i"]], [[h!i]] ) t( jsonish [["\\u0021"]], [[\u0021]] ) t( jsonish [["h\\u0021i"]], [[h\u0021i]] ) t( jsonish [["\\\u0021"]], [[\!]] ) t( jsonish '{}', {}, t.deepsame ) t( jsonish '{"hello":"world"}', {hello="world"}, t.deepsame ) t( jsonish '[1,2,3]', {1,2,3}, t.deepsame ) t( jsonish '{"hello":{"wor":"ld"}}', {hello={wor="ld"}}, t.deepsame ) t( jsonish '[1,2,[3,4]]', {1,2,{3,4}}, t.deepsame ) t( jsonish '["a","b]","c"]', {"a","b]","c"}, t.deepsame ) t( jsonish '["a","[b","c"]', {"a","[b","c"}, t.deepsame ) t( jsonish '["a","[b","c]"]', {"a","[b","c]"}, t.deepsame ) t( jsonish '["a",["b","c"]]', {"a",{"b","c"}}, t.deepsame ) t( jsonish[[{"a b": true}]], {["a b"]=true}, t.deepsame) t( jsonish '{"hello" :"world"}', {hello="world"}, t.deepsame ) t( jsonish[[{"\"b\"":true}]], {['"b"']=true}, t.deepsame) t( jsonish[[ ["a","b\"]","c"] ]], {"a","b\"]","c"}, t.deepsame ) t.test_embedded_example() t()
do class "FIFO" : namespace "util" : implements "Countable" : from "interfaces" { m_tbl = {}, } setter "GCCB->m_fnGcCB" function Initialize( self ) end function Push( self, var ) self.m_tbl[#self.m_tbl+1] = var end function Pop( self ) assert( #self.m_tbl > 0 ) local r = self:Next() table.remove( self.m_tbl, 1 ) return r end function Next( self ) return self.m_tbl[1] end function Clear( self ) self.m_tbl = {} end function Count( self ) return #self.m_tbl end function __len( self ) return #self.m_tbl end function __GC( self ) self.m_fnGcCB() end end
ENT.Type = "Anim" ENT.Base = "base_gmodentity" ENT.PrintName = "Grenade" ENT.Author = "VurtualRuler98" ENT.Contact = "steam" ENT.Purpose = "Getting more ammo!" ENT.Instructions = "Spawn. Use. Reload." ENT.Category = "Vurtual's base" ENT.Spawnable = false ENT.AdminSpawnable = false ENT.DetFragMagnitude="50" ENT.DetFragRadius="512" ENT.FragClusterSize=50 ENT.FragClusters=20 ENT.FragDamage=25 ENT.SuperFragClusters=0 ENT.SuperFragDamage=0 ENT.SuperFragRadius=0 ENT.DetonateSound="baseexplosioneffect.sound" ENT.BurnTimer=0 ENT.BurnEffectDelay=0.05 ENT.Detonated=false ENT.BurnEffectTimer=0 ENT.PhysFragVelocityMin=3500 ENT.PhysFragVelocityMax=4200 ENT.PhysFragMassMin=30 --TODO get better values ENT.PhysFragMassMax=120 ENT.PhysFragCountMultiplier=1 ENT.IsRemoved=false ENT.MolotovFlames=10 ENT.SmokeScale=100 ENT.CSGasTimer=0 ENT.CSGasEffectDelay=0.3 ENT.LastCough=0 ENT.ShrapnelAmmoType="buckshot" --bad approximation ENT.DetFearVolume=0 ENT.ThrowFearVolume=256 ENT.StartThrowFearVolume=512 ENT.TimeStopped=0 if (CLIENT) then function ENT:Draw() --AddWorldTip( self.Entity:EntIndex(), "ammo", 0.5, self.Entity:GetPos(),self.Entity) self.Entity:DrawModel() end end if (SERVER) then AddCSLuaFile() function ENT:SpawnFunction(ply, tr) if (!tr.HitWorld) then return end local ent = ents.Create("sent_kgreni2_f1") ent:SetPos(tr.HitPos + Vector(0, 0, 15)) ent:Spawn() return ent end function ENT:Initialize() self.Entity:SetModel( "models/weapons/w_f1.mdl") self.Entity:PhysicsInit( SOLID_VPHYSICS) self.Entity:SetMoveType( MOVETYPE_VPHYSICS ) self.Entity:SetSolid( SOLID_VPHYSICS ) self.Entity:SetUseType(SIMPLE_USE) self.Entity:SetCollisionGroup(COLLISION_GROUP_PROJECTILE) local phys = self.Entity:GetPhysicsObject() if (phys:IsValid()) then phys:SetMass(0.6) phys:Wake() end self:CreateFear() end end function ENT:Think() if (not kswep_timestop_check() and self.TimeStopped > 0) then if (not IsValid(self:GetParent()) or self:GetParent():GetClass()~="sent_ksweps_grenadetrap") then self:SetNWFloat("Fuze",CurTime()+self.TimeStopped) end self.TimeStopped=0 end if (kswep_timestop_check() and self.TimeStopped==0 and self:GetNWFloat("Fuze")>0) then self.TimeStopped = (self:GetNWFloat("Fuze")-CurTime()) print(self.TimeStopped) self:SetNWFloat("Fuze",0) end if (self.TimeStopped == 0 and not self.Detonated and self:GetNWFloat("Fuze")>0 and self:GetNWFloat("Fuze")<CurTime()) then self.Detonated=true self:Detonate() end if (IsValid(self.DetFearEnt) and self.DetFearTime<CurTime()) then self.DetFearEnt:Fire("EmitAISound") self.DetFearTime=CurTime()+1 if (self.DetFearThrown) then self.DetFearThrown=false self.DetFearEnt:SetKeyValue("volume",self.ThrowFearVolume) end end self:Think2() end function ENT:Think2() end function ENT:EmitGunSound(snd) if (SERVER) then net.Start("kswep_gunshot") net.WriteEntity(self) net.WriteString(snd) net.Send(player.GetAll()) end end function ENT:Detonate() if (not IsFirstTimePredicted()) then return end self:EmitGunSound(self.DetonateSound) self:EffectGrenadeFrag() self:DetBoom() self:DetFrag() self:AdvanceFear() end function ENT:LookingAtMe(ent) if (ent:IsLineOfSightClear(self)) then local ang=ent:EyeAngles() local ang2=(self:GetPos()-ent:EyePos()) ang2:Normalize() ang2=ang2:Angle() if (math.abs(math.AngleDifference(ang.p,ang2.p))<45 and math.abs(math.AngleDifference(ang.y,ang2.y))<60) then return true end end return false end function ENT:CreateFear() if (SERVER) then if (not IsValid(self:GetParent())) then self.DetFearEnt = ents.Create("ai_sound") local ent=self.DetFearEnt ent:SetPos(self:GetPos()) ent:Spawn() ent:SetParent(self) ent:SetKeyValue("soundtype",8) ent:SetKeyValue("volume",self.StartThrowFearVolume) ent:SetKeyValue("duration",1) ent:Activate() self.DetFearEnt:Fire("EmitAISound") self.DetFearTime=CurTime()+1 self.DetFearThrown=true end end end function ENT:AdvanceFear() if (SERVER and self.DetFearEnt) then self.DetFearThrown=false if (self.DetFearVolume<1) then self.DetFearEnt:Remove() self.DetFearEnt=nil else self.DetFearEnt:SetKeyValue("volume",self.DetFearVolume) end end end function ENT:OnRemove() if (SERVER and IsValid(self.DetFearEnt)) then self.DetFearEnt:Remove() end if (SERVER and IsValid(self.boom)) then self.boom:Remove() end end function ENT:DetFlash() if (SERVER) then for k,v in pairs(ents.FindInSphere(self:GetPos(),1024)) do if (v:IsNPC()) then if (self:LookingAtMe(v) or self:GetPos():Distance(v:GetPos())<128) then v:SetSchedule(SCHED_FLEE_FROM_BEST_SOUND) timer.Simple(1,function() if (IsValid(v)) then v:SetSchedule(SCHED_WAIT_FOR_SCRIPT) end end) timer.Simple(5,function() if (IsValid(v)) then v:SetSchedule(SCHED_FAIL) end end) end end if (v:IsPlayer() and (not v:HasWeapon("kswep_nvg") or not v:GetWeapon("kswep_nvg"):GetNWBool("Active"))) then if (self:LookingAtMe(v) or self:GetPos():Distance(v:GetPos())<128) then v:ScreenFade(SCREENFADE.IN,color_white,1,4.5) v:SetDSP(35,false) local ang=AngleRand() ang.r=0 v:SetEyeAngles(ang) end end end end if (CLIENT) then local dlight=DynamicLight(self:EntIndex()) if (dlight) then dlight.pos=self:GetPos() dlight.r=255 dlight.g=255 dlight.b=255 dlight.brightness=10 dlight.decay=1000 dlight.size=256 dlight.DieTime=CurTime()+0.1 end end end function ENT:ThinkSmokeCS() if (self.BurnTimer>0) then if (CLIENT and self.BurnEffectTimer<CurTime()) then local effectdata=EffectData() effectdata:SetOrigin(self:GetPos()) effectdata:SetStart(self:GetNWVector("SmokeColor")) effectdata:SetAngles(self:GetAngles()) effectdata:SetScale(self.SmokeScale) util.Effect("kswep_csgas",effectdata,true,true) self.BurnEffectTimer=CurTime()+self.BurnEffectDelay end if (SERVER and self.CSGasTimer<CurTime()) then local dmginfo=DamageInfo() dmginfo:SetDamage(1) dmginfo:SetDamageType(DMG_NERVEGAS) if (IsValid(self.Owner)) then dmginfo:SetAttacker(self.Owner) end for k,v in pairs(ents.FindInSphere(self:GetPos(),256)) do if (v:IsPlayer() and v.ksarmor.nervegas<100) then v:TakeDamageInfo(dmginfo) local cough="ambient/voices/cough"..math.random(1,4)..".wav" if (self.LastCough<CurTime()) then v:EmitSound(cough) self.LastCough=math.random(1,4)+CurTime() end elseif (v:IsNPC()) then v:TakeDamageInfo(dmginfo) end end self.CSGasTimer=CurTime()+self.CSGasEffectDelay end if (self.BurnTimer<CurTime() and not self.IsRemoved) then self:StopSound(self.BurnSound) self:EmitSound(self.BurnEndSound) self.IsRemoved=true if (SERVER) then self:Remove() end end end end function ENT:ThinkSmoke() if (self.BurnTimer>0) then if (CLIENT and self.BurnEffectTimer<CurTime()) then local effectdata=EffectData() effectdata:SetOrigin(self:GetPos()) effectdata:SetStart(self:GetNWVector("SmokeColor")) effectdata:SetAngles(self:GetAngles()) effectdata:SetScale(self.SmokeScale) util.Effect("kswep_smoke",effectdata,true,true) self.BurnEffectTimer=CurTime()+self.BurnEffectDelay end if (self.BurnTimer<CurTime() and not self.IsRemoved) then self:StopSound(self.BurnSound) self:EmitSound(self.BurnEndSound) self.IsRemoved=true if (SERVER) then self:Remove() end end end end function ENT:DetConstraints() --basically what siminov stuff does for k,v in pairs(ents.FindInSphere(self:GetPos(),self.DeconstraintRadius)) do if (IsValid(v:GetPhysicsObject()) and constraint.HasConstraints(v)) then for k,v in pairs(constraint.GetTable(v)) do if (v.forcelimit and v.forcelimit>0) then v.Constraint:Remove() end end end end end function ENT:ThinkBurn() if (self.BurnTimer>0) then if (SERVER) then for k,v in pairs(ents.FindInSphere(self:GetPos(),16)) do if ((v:GetClass()=="prop_physics" or v:IsNPC() or v:IsPlayer() or v:IsVehicle()) and not v:IsOnFire()) then v:Ignite(10) end if (IsValid(v:GetPhysicsObject()) and constraint.HasConstraints(v)) then for k,v in pairs(constraint.GetTable(v)) do if (v.forcelimit and v.forcelimit>0) then v.Constraint:Remove() end end end if (v:GetClass()=="sent_vurt_supplybox" or v:GetClass()=="sent_vurt_ammo") then if (SERVER and v.ThermiteAmmoTimer==0) then v:Thermite() end end end end if (CLIENT and self.BurnEffectTimer<CurTime()) then local effectdata=EffectData() effectdata:SetOrigin(self:GetPos()) effectdata:SetMagnitude(3) effectdata:SetScale(1) effectdata:SetRadius(64) util.Effect("ElectricSpark",effectdata,true,true) util.Effect("kswep_thermite",effectdata,true,true) self.BurnEffectTimer=CurTime()+self.BurnEffectDelay end end if (self.BurnTimer>0 and self.BurnTimer<CurTime() and not self.IsRemoved) then self:StopSound(self.BurnSound) self:EmitSound(self.BurnEndSound) self.IsRemoved=true if (SERVER) then self:Remove() end end end function ENT:DetSmokeFOG() local effectdata=EffectData() effectdata:SetOrigin(self:GetPos()) effectdata:SetStart(self:GetNWVector("SmokeColor")) effectdata:SetAngles(self:GetAngles()) util.Effect("kswep_smokefog",effectdata,true,true) end function ENT:DetSmoke() self:SetNWFloat("Fuze",0) self.BurnTimer=self.BurnTime+CurTime() self:EmitSound(self.BurnSound) end function ENT:DetBurn() self:SetNWFloat("Fuze",0) self.BurnTimer=self.BurnTime+CurTime() self:EmitSound(self.BurnSound) end function ENT:DetMolotov() if (SERVER) then for i=1,self.MolotovFlames do local flame=ents.Create("sent_ksweps_molotovflame") flame:SetPos(self:GetPos()+Vector(0,0,2)) flame:SetOwner(self.Owner) flame:Spawn() local phys=flame:GetPhysicsObject() if (IsValid(phys)) then phys:ApplyForceCenter(self:GetVelocity()+Vector(math.Rand(-100,100),math.Rand(-100,100),math.Rand(0,100))) end end end end function ENT:EffectGrenadeFrag() local effectdata=EffectData() effectdata:SetOrigin(self:GetPos()) effectdata:SetScale(1000) util.Effect("cball_bounce",effectdata) util.Effect("ThumperDust",effectdata) end function ENT:EffectRocketBoom() local effectdata=EffectData() effectdata:SetOrigin(self:GetPos()) effectdata:SetScale(1000) util.Effect("HelicopterMegaBomb",effectdata) end function ENT:DetBoom() if (CLIENT) then return end self.boom=ents.Create("env_explosion") local boom=self.boom boom:SetOwner(self) boom:SetPos(self:GetPos()) boom:SetKeyValue("Spawnflags","894") boom:SetKeyValue("iMagnitude",self.DetFragMagnitude) boom:SetKeyValue("iRadiusOverride",self.DetFragRadius) boom:Spawn() boom:Activate() boom:Fire("Explode","",0) end function ENT:DetFrag() local thrower=self:GetOwner() self:SetOwner(NULL) local bullet={ Attacker=thrower, Damage=self.FragDamage, Distance=self.FragRadius, Tracer=0, AmmoType=self.ShrapnelAmmoType, Src=self:GetPos(), Dir=Vector(0,0,1), Spread=Vector(10,10,10), Num=self.FragClusterSize } if (SERVER) then if (GetConVar("kswep_phys"):GetBool()) then local fragger=ents.Create("sent_kbgren_shrapnel") fragger:Spawn() fragger:SetPos(self:GetPos()) bullet.Num=1 local num_bullets=self.FragClusterSize*self.FragClusters*self.PhysFragCountMultiplier self:MakeShrapnel(fragger,bullet,num_bullets) num_bullets=self.FragClusterSize*self.SuperFragClusters*self.PhysFragCountMultiplier bullet.Damage=self.SuperFragDamage self:MakeShrapnel(fragger,bullet,num_bullets) fragger:Activate() self:Remove() else timer.Simple(0.1,function() self:Remove() if (self.FragClusters>0) then for i=1,self.FragClusters do self:FireBullets(bullet) end end if (self.SuperFragClusters>0) then bullet.Damage=self.SuperFragDamage bullet.Distance=self.SuperFragRadius for i=1,self.SuperFragClusters do self:FireBullets(bullet) end end end) end end end function ENT:MakeShrapnel(fragger,bullet,num_bullets) for i=1,num_bullets do local tbl=table.Copy(bullet) tbl.Spread = Vector() tbl.Dir=VectorRand() local shot={} shot.ticks=(GetConVar("kswep_max_flighttime"):GetInt()/engine.TickInterval()) shot.startticks=shot.ticks shot.pos=bullet.Src shot.basevelocity=self.PhysFragVelocityMin shot.mass=math.random(self.PhysFragMassMin,self.PhysFragMassMax) shot.dragvector=tbl.Dir*math.random(self.PhysFragVelocityMin,self.PhysFragVelocityMax) shot.bullet=tbl shot.bc=math.Rand(0.05,0.2) --TODO better estimate shot.dmg=bullet.Damage shot.dist = nil shot.crack=-1 shot.crackpos=shot.pos table.insert(fragger.Shrapnel,shot) end end function ENT:Use(activator,caller,usetype,value) if (IsValid(self:GetParent())) then self:GetParent():Use(activator,caller,usetype,value) end end
--[[ MIT License Copyright (c) 2018 JWRR.COM git clone https://github.com/jwrr/lued.git 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. --]] function lued.display_status_in_lua(lua_mode,dd) local status_line = lued.esc_clear_screen(dd) set_sel_end(0) -- if not g_status_line_on then return end local id = get_fileid() local filename = lued.get_filename() local save_needed = is_modified() local row,col = get_cur_pos() local trow,tcol = get_termsize() local sel_state, sel_sr, sel_sc, sel_er, sel_ec = get_sel() local stay_selected = ((row == sel_er) and (col == sel_ec)) or ((row == sel_sr) and (col == sel_sc)) if (not stay_selected) then set_sel_off() end local mode_str = lua_mode and "LUA MODE" or "ED MODE" g_review_mode = g_review_mode or false if g_review_mode then mode_str = "REVIEW MODE" else mode_str = "EDIT MODE" end local cmd_str = get_last_cmd() or "" cmd_str = string.gsub(cmd_str, "^x", "") cmd_str = string.gsub(cmd_str, "%(.*", "") local max_cmd_len = 20 cmd_str = string.sub(cmd_str,1,max_cmd_len) local pad_len = max_cmd_len - string.len(cmd_str); cmd_str = cmd_str .. string.rep(" ",pad_len) local save_str = save_needed and "*" or " " local stay_selected_int = stay_selected and 1 or 0 status_text = string.format( "%s - %s File (%d) %s%s Line: %d, Col: %d, Sel: %d Cmd: %s - sr=%d sc=%d er=%d ec=%d, staysel=%d", lued.version, mode_str, id, filename, save_str, row, col, sel_state, cmd_str, sel_sr, sel_sc, sel_er, sel_ec, stay_selected_int) status_line = lued.esc_clear_screen(dd) .. string.sub(status_text,1,tcol) .. "\n" if g_status_line_reverse then status_line = lued.esc_rev(status_line) end if dd then -- don't display return status_line end io.write(status_line) end
function lovr.load() shader = lovr.graphics.newShader([[ vec4 position(mat4 projection, mat4 transform, vec4 vertex) { return projection * transform * vertex; } ]], [[ const float gridSize = 25.; const float cellSize = .5; vec4 color(vec4 gcolor, sampler2D image, vec2 uv) { // Distance-based alpha (1. at the middle, 0. at edges) float alpha = 1. - smoothstep(.15, .50, distance(uv, vec2(.5))); // Grid coordinate uv *= gridSize; uv /= cellSize; vec2 c = abs(fract(uv - .5) - .5) / fwidth(uv); float line = clamp(1. - min(c.x, c.y), 0., 1.); vec3 value = mix(vec3(.01, .01, .011), (vec3(.04)), line); return vec4(vec3(value), alpha); } ]], { flags = { highp = true } }) lovr.graphics.setBackgroundColor(.05, .05, .05) end function lovr.draw() lovr.graphics.setShader(shader) lovr.graphics.plane('fill', 0, 0, 0, 25, 25, -math.pi / 2, 1, 0, 0) lovr.graphics.setShader() end
term = {} qA = {} qB = {} answA = {} answB = {} term[1] = math.random(59) + 10; term[2] = math.random(90 - term[1]) + 10; term[3] = math.random(59) + 10 ; term[4] = math.random(90 - term[3]) + 10; for i=1,4 do term[i] = term[i]; end summA = term[1] + term[2]; summB = term[3] + term[4]; qA[1] = term[1] qA[2] = term[1] + math.random(9) qA[3] = term[1] - math.random(9) if (qA[3] < 0) then qA[3] = - qA[3] end qA[4] = term[1] - term[2] if (term[1] < term[2]) then qA[4] = -qA[4] end for i = 1,3 do if(qA[4] == qA[i]) then qA[4] = 0 end end answA = lib.math.random_shuffle(qA) for i = 1,4 do if(answA[i] == term[1]) then indA = i-1 end end qB[1] = term[4] qB[2] = term[4] + math.random(9) qB[3] = term[4] - math.random(9) if (qB[3] < 0) then qB[3] = - qB[3] end qB[4] = term[3] - term[4] if (term[3] < term[4]) then qB[4] = -qB[4] end for i = 1,3 do if(qB[4] == qB[i]) then qB[4] = 0 end end answB = lib.math.random_shuffle(qB) for i = 1,4 do if(answB[i] == term[4]) then indB = i-1 end end
ColorsState = GameState:new() function GameState:getName() return 'colors' end function ColorsState:update(dt) Background:update(dt) AIColors:update(dt) Colors:update(dt) end function ColorsState:draw() Colors:draw() AIColors:draw() end function ColorsState:onMousePressed(mousePosition) if Colors.colorButton:isHovered(mousePosition) then Colors.colorButton:setButtonAsPressed() elseif Colors.rightArrowButton:isHovered(mousePosition) then Colors.rightArrowButton:setButtonAsPressed() elseif Colors.leftArrowButton:isHovered(mousePosition) then Colors.leftArrowButton:setButtonAsPressed() elseif Colors.backButton:isHovered(mousePosition) then Colors.backButton:setButtonAsPressed() Save:updateCurrentColor() end end function ColorsState:onMouseReleased(mousePosition) Colors.colorButton:onMouseReleased() Colors.rightArrowButton:onHovered(mousePosition, function() Colors:nextColor() end) Colors.rightArrowButton:onMouseReleased() Colors.leftArrowButton:onHovered(mousePosition, function() Colors:previousColor() end) Colors.leftArrowButton:onMouseReleased() Colors.backButton:onHovered(mousePosition, function() Save:updateCurrentColor() gameState = MenuState end) Colors.backButton:onMouseReleased() end function ColorsState:onKeyPressed(key) if key == "c" then Save:updateCurrentColor() gameState = MenuState elseif key == "right" then Colors.rightArrowButton:setButtonAsPressed() elseif key == "left" then Colors.leftArrowButton:setButtonAsPressed() end end function ColorsState:onKeyReleased(key) if key == "left" then Colors.leftArrowButton:onMouseReleased() Colors:previousColor() elseif key == "right" then Colors.rightArrowButton:onMouseReleased() Colors:nextColor() end end function ColorsState:onFocus(focus) end
require("impatient") require("plugins") require("functions") require("mappings") require("settings")
local class = require("30log") local Controller = class "Controller" Controller.init = { -- Used here as a filler _do_nothing =function() end, is_bound = false } function Controller:bind_to_handler(--[[handler]]) self.is_bound = true end function Controller:unbind_to_handler(--[[handler]]) self.is_bound = false end function Controller.update(--[[self, dt]]) end return Controller
-- Parameters variables (do not change) obs = obslua distance_file = "" source_name = "" shown = false started = false last_distance = 0.0 threshold = 100 check_time = 2 decay = 5 -- -- This part is providing main functionality -- function visibility_change(visible) -- Get/lock scene and find source in the scene. local current_scene = obs.obs_scene_from_source(obs.obs_frontend_get_current_scene()) scene_item = obs.obs_scene_find_source(current_scene, source_name) -- Set element visibility and release the scene. obs.obs_sceneitem_set_visible(scene_item, visible) obs.obs_scene_release(current_scene) end function show_timer_callback() -- Change visibility of the item and stop the timer obs.remove_current_callback() shown = false visibility_change(false) end function check_timer_callback() -- Read distance file local file = io.open(distance_file, "rb") -- If failed to load file, skip if not file then print("Cannot open file...") return nil end -- Read and parse the file. If failed, skip local content = tonumber(file:read "*a") file:close() if not content then print("Cannot parse value...") return nil end -- Check if current value is >= than threshold. if ((content - last_distance) > 0) and ((content - last_distance) >= threshold) then print(string.format("%02.2f, %02.2f, %02.2f", content, last_distance, threshold)) -- If so, save new threshold last_distance = content -- If element is not yet started if not shown then -- Change element visibility visibility_change(true) shown = true -- Set timer to hide the element obs.timer_add(show_timer_callback, decay) print("Threshold reached!") end else print("Threshold not reached...") end end function start_stop_toggle() -- This function starts/stops whole logic if started then obs.timer_remove(check_timer_callback) started = false print("Logic stopped.") else started = true last_distance = 0.0 obs.timer_add(check_timer_callback, check_time) print("Logic started.") end end -- -- This part is providing configuration parameters for this script -- function script_update(settings) -- Parameters update source_name = obs.obs_data_get_string(settings, "source") decay = obs.obs_data_get_int(settings, "decay") * 1000 threshold = obs.obs_data_get_int(settings, "threshold") distance_file = obs.obs_data_get_string(settings, "file") check_time = obs.obs_data_get_int(settings, "check_time") * 1000 end function script_defaults(settings) -- Parameters defaults obs.obs_data_set_default_int(settings, "decay", 5) obs.obs_data_set_default_string(settings, "threshold", 100) obs.obs_data_set_default_string(settings, "check_time", 2) end function script_properties() -- Setup local props = obs.obs_properties_create() -- Parameters obs.obs_properties_add_text(props, "source", "Source", obs.OBS_TEXT_DEFAULT) obs.obs_properties_add_int(props, "decay", "Decay time", 1, 60, 1) obs.obs_properties_add_int(props, "threshold", "Distance threshold", 100, 1000, 100) obs.obs_properties_add_text(props, "file", "Distance file", obs.OBS_TEXT_DEFAULT) obs.obs_properties_add_int(props, "check_time", "File check time", 1, 10, 1) -- Buttons obs.obs_properties_add_button(props, "button", "Start/Stop", start_stop_toggle) -- Return return props end
---- -- Tests for the xlsxwriter.lua xml writer class. -- -- Copyright 2014, John McNamara, jmcnamara@cpan.org -- require "Test.More" local utility = require "xlsxwriter.utility" local expected local got local caption local tests plan(15) ---- -- Test the utility cell_to_rowcol functions. -- tests = { --row, col, A1 string {0, 0, 'A1'}, {0, 1, 'B1'}, {0, 2, 'C1'}, {0, 9, 'J1'}, {1, 0, 'A2'}, {2, 0, 'A3'}, {9, 0, 'A10'}, {1, 24, 'Y2'}, {7, 25, 'Z8'}, {9, 26, 'AA10'}, {1, 254, 'IU2'}, {1, 255, 'IV2'}, {1, 256, 'IW2'}, {0, 16383, 'XFD1'}, {1048576, 16384, 'XFE1048577'}, } for _, test in ipairs(tests) do got = {utility.cell_to_rowcol(test[3])} expected = {test[1], test[2]} caption = string.format(" \tcell_to_rowcol(%s) -> %d, %d", test[3], test[1], test[2]) eq_array(got, expected, caption) end
local hit_effects = require ("__base__/prototypes/entity/demo-hit-effects.lua") local sounds = require("__base__/prototypes/entity/demo-sounds.lua") local function createHeatGenerator(name, energy_usage, energy_source, recipeEnabled, order) data:extend({ { type = "item", name = name, icon = "__base__/graphics/icons/chemical-plant.png", icon_size = 64, icon_mipmaps = 4, subgroup = "colonists-heat", order = order, place_result = name, stack_size = 20 }, { type = "recipe", name = name, ingredients = { --{"electronic-circuit", 2}, {"pipe", 1}, {"iron-gear-wheel", 1} }, result = name, enabled = recipeEnabled }, { type = "assembling-machine", name = name, crafting_categories = {"colonists-heat-processing"}, fixed_recipe = "colonists-heat", icon = "__base__/graphics/icons/chemical-plant.png", icon_size = 64, icon_mipmaps = 4, flags = {"placeable-neutral","placeable-player", "player-creation"}, minable = {mining_time = 0.1, result = name}, max_health = 300, corpse = "chemical-plant-remnants", dying_explosion = "chemical-plant-explosion", collision_box = {{-0.4, -0.4}, {0.4, 0.4}}, selection_box = {{-0.5, -0.5}, {0.5, 0.5}}, damaged_trigger_effect = hit_effects.entity(), drawing_box = {{-0.5, -1.9}, {0.5, 0.5}}, animation = make_4way_animation_from_spritesheet({ layers = { { filename = "__base__/graphics/entity/chemical-plant/chemical-plant.png", width = 108, height = 148, frame_count = 24, line_length = 12, shift = util.by_pixel(1, -9), scale = 1 / 3, hr_version = { filename = "__base__/graphics/entity/chemical-plant/hr-chemical-plant.png", width = 220, height = 292, frame_count = 24, line_length = 12, shift = util.by_pixel(0.5, -9), scale = 0.5 / 3 } }, { filename = "__base__/graphics/entity/chemical-plant/chemical-plant-shadow.png", width = 154, height = 112, repeat_count = 24, frame_count = 1, shift = util.by_pixel(28, 6), draw_as_shadow = true, scale = 1 /3, hr_version = { filename = "__base__/graphics/entity/chemical-plant/hr-chemical-plant-shadow.png", width = 312, height = 222, repeat_count = 24, frame_count = 1, shift = util.by_pixel(27, 6), draw_as_shadow = true, scale = 0.5 / 3 } } }}), working_visualisations = { { apply_recipe_tint = "primary", north_animation = { filename = "__base__/graphics/entity/chemical-plant/chemical-plant-liquid-north.png", frame_count = 24, line_length = 6, width = 32, height = 24, shift = util.by_pixel(24 / 3, 14 / 3), scale = 1 / 3, hr_version = { filename = "__base__/graphics/entity/chemical-plant/hr-chemical-plant-liquid-north.png", frame_count = 24, line_length = 6, width = 66, height = 44, shift = util.by_pixel(23 / 3, 15 / 3), scale = 0.5 / 3 } }, east_animation = { filename = "__base__/graphics/entity/chemical-plant/chemical-plant-liquid-east.png", frame_count = 24, line_length = 6, width = 36, height = 18, shift = util.by_pixel(0, 22 / 3), scale = 1 / 3, hr_version = { filename = "__base__/graphics/entity/chemical-plant/hr-chemical-plant-liquid-east.png", frame_count = 24, line_length = 6, width = 70, height = 36, shift = util.by_pixel(0, 22 / 3), scale = 0.5 / 3 } }, south_animation = { filename = "__base__/graphics/entity/chemical-plant/chemical-plant-liquid-south.png", frame_count = 24, line_length = 6, width = 34, height = 24, shift = util.by_pixel(0, 16 / 3), scale = 1 / 3, hr_version = { filename = "__base__/graphics/entity/chemical-plant/hr-chemical-plant-liquid-south.png", frame_count = 24, line_length = 6, width = 66, height = 42, shift = util.by_pixel(0, 17 / 3), scale = 0.5 / 3 } }, west_animation = { filename = "__base__/graphics/entity/chemical-plant/chemical-plant-liquid-west.png", frame_count = 24, line_length = 6, width = 38, height = 20, shift = util.by_pixel(-10 / 3, 12 / 3), scale = 1 / 3, hr_version = { filename = "__base__/graphics/entity/chemical-plant/hr-chemical-plant-liquid-west.png", frame_count = 24, line_length = 6, width = 74, height = 36, shift = util.by_pixel(-10 / 3, 13 / 3), scale = 0.5 / 3 } } }, { apply_recipe_tint = "secondary", north_animation = { filename = "__base__/graphics/entity/chemical-plant/chemical-plant-foam-north.png", frame_count = 24, line_length = 6, width = 32, height = 22, shift = util.by_pixel(24 / 3, 14 / 3), scale = 1 / 3, hr_version = { filename = "__base__/graphics/entity/chemical-plant/hr-chemical-plant-foam-north.png", frame_count = 24, line_length = 6, width = 62, height = 42, shift = util.by_pixel(24 / 3, 15 / 3), scale = 0.5 / 3 } }, east_animation = { filename = "__base__/graphics/entity/chemical-plant/chemical-plant-foam-east.png", frame_count = 24, line_length = 6, width = 34, height = 18, shift = util.by_pixel(0, 22 / 3), scale = 1 / 3, hr_version = { filename = "__base__/graphics/entity/chemical-plant/hr-chemical-plant-foam-east.png", frame_count = 24, line_length = 6, width = 68, height = 36, shift = util.by_pixel(0, 22 / 3), scale = 0.5 / 3 } }, south_animation = { filename = "__base__/graphics/entity/chemical-plant/chemical-plant-foam-south.png", frame_count = 24, line_length = 6, width = 32, height = 18, shift = util.by_pixel(0, 18 / 3), scale = 1 / 3, hr_version = { filename = "__base__/graphics/entity/chemical-plant/hr-chemical-plant-foam-south.png", frame_count = 24, line_length = 6, width = 60, height = 40, shift = util.by_pixel(1 / 3, 17 / 3), scale = 0.5 / 3 } }, west_animation = { filename = "__base__/graphics/entity/chemical-plant/chemical-plant-foam-west.png", frame_count = 24, line_length = 6, width = 36, height = 16, shift = util.by_pixel(-10 / 3, 14 / 3), scale = 1 / 3, hr_version = { filename = "__base__/graphics/entity/chemical-plant/hr-chemical-plant-foam-west.png", frame_count = 24, line_length = 6, width = 68, height = 28, shift = util.by_pixel(-9 / 3, 15 / 3), scale = 0.5 / 3 } } }, { apply_recipe_tint = "tertiary", fadeout = true, constant_speed = true, north_position = util.by_pixel_hr(-30 / 3, -161 / 3), east_position = util.by_pixel_hr(29 / 3, -150 / 3), south_position = util.by_pixel_hr(12 / 3, -134 / 3), west_position = util.by_pixel_hr(-32 / 3, -130 / 3), render_layer = "wires", animation = { filename = "__base__/graphics/entity/chemical-plant/chemical-plant-smoke-outer.png", frame_count = 47, line_length = 16, width = 46, height = 94, animation_speed = 0.5, shift = util.by_pixel(-2 / 3, -40 / 3), scale = 1 / 3, hr_version = { filename = "__base__/graphics/entity/chemical-plant/hr-chemical-plant-smoke-outer.png", frame_count = 47, line_length = 16, width = 90, height = 188, animation_speed = 0.5, shift = util.by_pixel(-2 / 3, -40 / 3), scale = 0.5 / 3 } } }, { apply_recipe_tint = "quaternary", fadeout = true, constant_speed = true, north_position = util.by_pixel_hr(-30 / 3, -161 / 3), east_position = util.by_pixel_hr(29 / 3, -150 / 3), south_position = util.by_pixel_hr(12 / 3, -134 / 3), west_position = util.by_pixel_hr(-32 / 3, -130 / 3), render_layer = "wires", animation = { filename = "__base__/graphics/entity/chemical-plant/chemical-plant-smoke-inner.png", frame_count = 47, line_length = 16, width = 20, height = 42, animation_speed = 0.5, shift = util.by_pixel(0, -14 / 3), scale = 1 / 3, hr_version = { filename = "__base__/graphics/entity/chemical-plant/hr-chemical-plant-smoke-inner.png", frame_count = 47, line_length = 16, width = 40, height = 84, animation_speed = 0.5, shift = util.by_pixel(0, -14 / 3), scale = 0.5 / 3 } } } }, vehicle_impact_sound = sounds.generic_impact, open_sound = sounds.machine_open, close_sound = sounds.machine_close, working_sound = { sound = { { filename = "__base__/sound/chemical-plant-1.ogg", volume = 0.5, }, { filename = "__base__/sound/chemical-plant-2.ogg", volume = 0.5, }, { filename = "__base__/sound/chemical-plant-3.ogg", volume = 0.5, } }, --max_sounds_per_type = 3, --idle_sound = { filename = "__base__/sound/idle1.ogg", volume = 0.3 }, apparent_volume = 1.5, fade_in_ticks = 4, fade_out_ticks = 20, }, crafting_speed = 1, energy_source = energy_source, energy_usage = energy_usage, fluid_boxes = { { production_type = "output", pipe_covers = pipecoverspictures(), base_level = 1, pipe_connections = {{ position = {0, 1} }} } }, water_reflection = { pictures = { filename = "__base__/graphics/entity/chemical-plant/chemical-plant-reflection.png", priority = "extra-high", width = 28, height = 36, shift = util.by_pixel(5, 60), variation_count = 4, scale = 5 / 3, }, rotate = false, orientation_to_variation = true } }, }) end createHeatGenerator("colonists-heat-generator", "210kW", { type = "burner", fuel_category = "chemical", effectivity = 1, fuel_inventory_size = 1, emissions_per_minute = 2, smoke = { { name = "smoke", deviation = {0.1, 0.1}, frequency = 5, position = {0.0, -0.8}, starting_vertical_speed = 0.08, starting_frame_deviation = 60 } }}, true, "a[heat]-a[heat-generator]" ) createHeatGenerator("colonists-electric-heat-generator", "210kW", { type = "electric", usage_priority = "secondary-input", }, false, "a[heat]-b[heat-generator]" )
--- Виджет поля ввода -- @module dpUI.DpInput DpInput = {} local inputColors = { dark = "gray", light = "gray_light" } function DpInput.create(properties) if type(properties) ~= "table" then properties = {} end local widget = Input.create(properties) local colorName = inputColors[exports.dpUtils:defaultValue(properties.type, "dark")] if properties.type == "light" then widget.textColor = Colors.color("black", 150) widget.placeholderColor = Colors.color("black", 100) end function widget:updateTheme() self.colors = { normal = Colors.color(colorName), hover = Colors.lighten(colorName, 15), active = Colors.lighten(colorName, 20) } end widget:updateTheme() return widget end
function Struct() local struct = {} struct.__index = struct -- Class information -- local info = debug.getinfo(2, "Sl") local structName = string.split(info.source, "/") -- remove everything before path -- @fixme This doesn't work with Lua 5.1. I'm not sure if it's because of -- the escape character used or what. structName = string.split(structName[#structName], "%.") -- remove '.lua[c|o]' extension structName = structName[1] function struct.__tostring() return string.format("Instantiated in file (%s) on line (%d)", info.source, info.currentline) end -- Factory -- setmetatable(struct, { __call = function (cls, ...) if not cls then Signal.fail(string.format("(%s) is not a struct", structName)) end if type(cls.new) ~= "function" then Signal.fail(string.format("function %s.new() must be implemented", structName)) end local self = {} struct.new(self, ...) return self end, }) return struct end
--[[ ----gui function--------------------------------------------------------------- gui:newWindow(x,y,width,height,screen_address) return window gui:update() ----window function------------------------------------------------------------ window:close() return nil window:setWindowName(name) return window window:setWindowNameColor(color) return window window:setCloseButtonColor(color) return window window:setFrameColor(color) return window window:setCloseButtonCallback(callback) return window --default callback is window:close() window:setMoveability(boolean) return window window:newTabBar() return tabBar window:newButton(x,y,width,height,callback) return button ----tabBar function------------------------------------------------------------ tabBar:newTab(name) --]] local component = require("component") local computer = require("computer") local event = require("event") local text = require("text") local term = require("term") local unicode = require("unicode") local bigfont = require("bigfont") local gpu = component.gpu --公開するのはguiのみ local gui = {} local objects = {} local render = {} render.internal = {} render.internal.cursor = {} local event_handler = {} local cfg = {} --**cfg**---------------------------------------------------------------------- cfg.frame_char = {} cfg.frame_char.window = {{"⣿","⣿","⣿"},{"⡇"," ","⢸"},{"⣇","⣀","⣸"}} cfg.frame_char.close_button = "X" cfg.frame_char.button = {{"⡏","⠉","⢹"},{"⡇"," ","⢸"},{"⣇","⣀","⣸"}} cfg.frame_char.button2 = {{"┏","━","┓"},{"┃"," ","┃"},{"┗","━","┛"}} cfg.frame_char.button3 = {{"⡤","⠤","⢤"},{"⡇"," ","⢸"},{"⠓","⠒","⠚"}} cfg.frame_char.progress = {{"╒","═","╕"},{"│"," ","│"},{"╘","═","╛"}} cfg.frame_char.list = {{"╓","─","╖"},{"║"," ","║"},{"╙","─","╜"}} --cfg.frame_char.scrollBar = {"⇧","┃","⇩","⣿"} --cfg.frame_char.scrollBar = {"↑","│","↓","⣿"} cfg.frame_char.scrollBar = {"┬","│","┴","⣿"} --cfg.frame_char.progress = {{"⢠","⣤","⡄"},{"⡇"," ","⡇"},{"⠘","⠛","⠃"}} cfg.frame_char.bar = "▊" cfg.color = {} cfg.color.std = {} cfg.color.std.foreground = 0xFFFFFF cfg.color.std.background = 0x000000 cfg.color.gui = {} cfg.color.gui.background = 0x000000 cfg.color.window = {} cfg.color.window.frame = 0xFFFFFF cfg.color.window.panel = 0xCCCCCC cfg.color.window.name = 0x000000 cfg.color.window.close_button = 0x000000 cfg.color.tab = {} cfg.color.tab.name = 0x000000 cfg.color.button = {} cfg.color.button.frame = 0x4B4B4B cfg.color.button.panel = 0xC3C3C3 cfg.color.button.text = 0x000000 cfg.color.switch = {} cfg.color.switch.text = {} cfg.color.switch.text.on = {} cfg.color.switch.text.on.foreground = 0x000000 cfg.color.switch.text.on.background = 0xD2D2D2 cfg.color.switch.text.off = {} cfg.color.switch.text.off.foreground = 0x000000 cfg.color.switch.text.off.background = 0xD2D2D2 cfg.color.switch.frame = {} cfg.color.switch.frame.on = {} cfg.color.switch.frame.on.foreground = 0x4B4B4B cfg.color.switch.frame.on.background = 0xD2D2D2 cfg.color.switch.frame.off = {} cfg.color.switch.frame.off.foreground = 0xFFFFFF cfg.color.switch.frame.off.background = 0xD2D2D2 cfg.color.switch.panel = {} cfg.color.switch.panel.on = {} cfg.color.switch.panel.on.foreground = 0xFF0000--無意味 cfg.color.switch.panel.on.background = cfg.color.switch.frame.on.background cfg.color.switch.panel.off = {} cfg.color.switch.panel.off.foreground = 0xFF0000--無意味 cfg.color.switch.panel.off.background = cfg.color.switch.frame.off.background cfg.color.label = {} cfg.color.label.text = {} cfg.color.label.text.foreground = 0x000000 cfg.color.label.text.background = cfg.color.window.panel cfg.color.label.underline = {} cfg.color.label.underline.foreground = 0xFF0000 cfg.color.label.underline.background = cfg.color.window.panel cfg.color.textField = {} cfg.color.textField.text = {} cfg.color.textField.text.foreground = 0xFFFFFF cfg.color.textField.text.background = 0x000000 cfg.color.textField.active = {} cfg.color.textField.active.foreground = 0xFFFFFF cfg.color.textField.active.background = 0xFFB600 cfg.color.list = {} cfg.color.list.name = {} cfg.color.list.element = {} cfg.color.list.element.on = {} cfg.color.list.element.on.foreground = 0x000000 cfg.color.list.element.on.background = 0xFFDB00 --cfg.color.list.element.on.background = 0xFFFFFF cfg.color.list.element.off = {} cfg.color.list.element.off.foreground = 0x0F0F0F cfg.color.list.element.off.background = 0xB4B4B4 cfg.color.list.frame = {} cfg.color.list.frame.foreground = 0x000000 cfg.color.list.frame.background = cfg.color.window.panel cfg.color.list.panel = {} cfg.color.list.panel.foreground = 0x000000 cfg.color.list.panel.background = 0xC3C3C3 cfg.color.progress = {} cfg.color.progress.frame = {} cfg.color.progress.frame.foreground = 0x000000 cfg.color.progress.frame.background = cfg.color.window.panel cfg.color.progress.bar = {} --cfg.color.progress.bar.foreground = 0x0000FF cfg.color.progress.bar.foreground = 0x006DFF cfg.color.progress.bar.background = 0x1E1E1E cfg.color.progress.name = {} cfg.color.progress.name.foreground = 0xFF0000 cfg.color.progress.name.background = cfg.color.window.panel --tier3だと下設定がいいかも -- cfg.color.window = {} -- cfg.color.window.frame = 0xFFFFFF -- cfg.color.window.panel = 0xCCCCCC -- cfg.color.window.name = 0x000000 -- cfg.color.window.close_button = 0x000000 -- cfg.color.tab = {} -- cfg.color.tab.name = 0x000000 -- cfg.color.button = {} -- cfg.color.button.frame = 0xA5A5A5 -- cfg.color.button.panel = 0xC3C3C3 -- cfg.color.button.text = 0x000000 -- cfg.color.switch = {} -- cfg.color.switch.text = {} -- cfg.color.switch.text.on = {} -- cfg.color.switch.text.on.foreground = 0x000000 -- cfg.color.switch.text.on.background = 0xF0F0F0 -- cfg.color.switch.text.off = {} -- cfg.color.switch.text.off.foreground = 0xFFFFFF -- cfg.color.switch.text.off.background = 0x969696 -- cfg.color.switch.frame = {} -- cfg.color.switch.frame.on = {} -- cfg.color.switch.frame.on.foreground = 0xFFFFFF -- cfg.color.switch.frame.on.background = 0xF0F0F0 -- cfg.color.switch.frame.off = {} -- cfg.color.switch.frame.off.foreground = 0xB4B4B4 -- cfg.color.switch.frame.off.background = 0x969696 -- cfg.color.switch.panel = {} -- cfg.color.switch.panel.on = {} -- cfg.color.switch.panel.on.foreground = 0xFF0000--無意味 -- cfg.color.switch.panel.on.background = cfg.color.switch.frame.on.background -- cfg.color.switch.panel.off = {} -- cfg.color.switch.panel.off.foreground = 0xFF0000--無意味 -- cfg.color.switch.panel.off.background = cfg.color.switch.frame.off.background -- cfg.color.label = {} -- cfg.color.label.text = {} -- cfg.color.label.text.foreground = 0x000000 -- cfg.color.label.text.background = cfg.color.window.panel -- cfg.color.label.underline = {} -- cfg.color.label.underline.foreground = 0xFF0000 -- cfg.color.label.underline.background = cfg.color.window.panel -- cfg.color.textField = {} -- cfg.color.textField.text = {} -- cfg.color.textField.text.foreground = 0xFFFFFF -- cfg.color.textField.text.background = 0x000000 -- cfg.color.textField.active = {} -- cfg.color.textField.active.foreground = 0xFFFFFF -- cfg.color.textField.active.background = 0xFFB600 -- cfg.color.list = {} -- cfg.color.list.name = {} -- cfg.color.list.element = {} -- cfg.color.list.element.on = {} -- cfg.color.list.element.on.foreground = 0x000000 -- cfg.color.list.element.on.background = 0xFFDB00 -- --cfg.color.list.element.on.background = 0xFFFFFF -- cfg.color.list.element.off = {} -- cfg.color.list.element.off.foreground = 0x0F0F0F -- cfg.color.list.element.off.background = 0xB4B4B4 -- cfg.color.list.frame = {} -- cfg.color.list.frame.foreground = 0x000000 -- cfg.color.list.frame.background = cfg.color.window.panel -- cfg.color.list.panel = {} -- cfg.color.list.panel.foreground = 0x000000 -- cfg.color.list.panel.background = 0xC3C3C3 -- cfg.color.progress = {} -- cfg.color.progress.frame = {} -- cfg.color.progress.frame.foreground = 0x000000 -- cfg.color.progress.frame.background = cfg.color.window.panel -- cfg.color.progress.bar = {} -- --cfg.color.progress.bar.foreground = 0x0000FF -- cfg.color.progress.bar.foreground = 0x006DFF -- cfg.color.progress.bar.background = 0x1E1E1E -- cfg.color.progress.name = {} -- cfg.color.progress.name.foreground = 0xFF0000 -- cfg.color.progress.name.background = cfg.color.window.panel cfg.default = {} cfg.default.x = 1 cfg.default.y = 1 cfg.default.width = 32 cfg.default.height = 10 --**util functions**----------------------------------------------------------- --点i,jが四角形に内在するか local function isInsideRect(i, j, x, y, width, height) return x <= i and i <= x + width - 1 and y <= j and j <= y + height - 1 end local function isExistActiveTextField(layerGroup) local flag = false for i, object in ipairs(layerGroup) do if object.type == "textField" and object.active then flag = true end end return flag end local function getTopLayer(layerGroup) return layerGroup[#layerGroup] end local function debug(msg,pause) local w, h = gpu.getResolution() render.setColor(cfg.color.std) msg = text.padRight(tostring(msg),w) gpu.set(1,h,msg) if pause then event.pull("touch") end end local function ripairs(t) local function ripairs_it(t,i) i = i - 1 local v = t[i] if v == nil then return v end return i,v end return ripairs_it, t, #t+1 end --**eventhandler**------------------------------------------------------------- function event_handler.event(event_name, screen_address, x , y, button) if event_name then --debug(event_name.." : "..tostring(button)) end local isRightClick = (button == 1) if event_handler[event_name] then event_handler[event_name](screen_address, x, y, isRightClick) else --unknown event end end --反応しない? function event_handler.interrupted(...) debug("interrupted") gui:exit() end function event_handler.touch(screen_address, x, y, isRightClick) if isRightClick or #gui.layer == 0 then return end do--クリックされたwindowをgui.layerの一番最後に持ってくる local window for i, w in ripairs(gui.layer) do if isInsideRect(x, y, w.x, w.y, w.width, w.height) then --既にgui上で最上段にあればスルー if i == #gui.layer then break end window = table.remove(gui.layer, i) break end end if window then window.dirty = true table.insert(gui.layer, window) end end local top = getTopLayer(gui.layer) if not top then return end --上部frameがクリックされたか if isInsideRect(x, y, top.x, top.y, top.width - 3, 1) then if top.moveability then top.move.moving = true top.move.position = x - top.x end --closebuttonがクリックされたか elseif isInsideRect(x, y, top.x + top.width - 2, top.y, 1, 1) then if not top.close_button_callback then top:close() else top.close_button_callback() top:close() end else --buttonが押されたか判断する for i, object in ripairs(top.layer) do if not object.visible then goto continue end local bx, by = object.x + top.x, object.y + top.y local w, h = object.width, object.height if object.type == "button" then --buttonのobjectが --debug(tostring(x)..":"..tostring(y)) if isInsideRect(x, y, bx, by, w, h) then if object.callback then if object.args then object.callback(table.unpack(object.args)) else object.callback() end else --debug("function not be defined") end end elseif object.type == "switch" then if isInsideRect(x, y, bx, by, w, h) then --debug("switch") if object.state == "on" then object.state = "off" else object.state = "on" end object.dirty = true local onoff = object.state if object.callback[onoff] then if object.args[onoff] then object.callback[onoff](table.unpack(object.args[onoff])) else object.callback[onoff]() end end end elseif object.type == "textField" then if isInsideRect(x, y, bx, by, w, h) then --他のテキストフィールドを非アクティブに for j, o in ipairs(top.layer) do if o.type == "textField" and o.active and o ~= object then o.active = false o.dirty = true end end object.active = true local tx, ty = top.x + object.x, top.y + object.y local w = unicode.wlen(object.text) render.internal.cursor.blink = true render.internal.cursor.x = tx + w render.internal.cursor.y = ty object.dirty = true end elseif object.type == "list" then if isInsideRect(x, y, bx + 1, by + 1, w - 2, h - 2) then local pos = y - (object.y + top.y) + object.pos - 1 if object.elements[pos].state == "on" then object.elements[pos].state = "off" object.dirty = true else for i, le in ipairs(object.elements) do le.state = "off" end object.dirty = true object.elements[pos].state = "on" if object.elements[pos].callback then if object.elements[pos].args then local args = object.elements[pos].args object.elements[pos].callback(table.unpack(args)) else object.elements[pos].callback() end end end end end ::continue:: end end end function event_handler.drag(screen_address, x, y, isRightClick) local top = getTopLayer(gui.layer) if top.move.moving and top.moveability then --top:clear() top.x = x - top.move.position top.y = y top.dirty = true -- for i , window in ipairs(gui.layer) do -- window.dirty = true -- end end end function event_handler.drop(screen_address, x, y, isRightClick) local top = getTopLayer(gui.layer) if top.move.moving then top.move.moving = false top.move.position = 0 end end function event_handler.scroll(screen_address, px, py, isUp) local top = getTopLayer(gui.layer) for i, o in ripairs(top.layer) do if o.type ~= "list" then goto continue end local x, y = o.x + top.x, o.y + top.y local width, height = o.width, o.height local ymax = #o.elements - (o.height - 3) if isInsideRect(px, py, x, y, width, height) then if isUp then if o.pos == 1 then goto continue end o.pos = o.pos - 1 o.dirty = true else if o.pos == ymax then goto continue end o.pos = o.pos + 1 o.dirty = true end end ::continue:: end end function event_handler.key_down(screen_address, ch, code) local top = getTopLayer(gui.layer) if not top then return end local activeTextField for i, object in ipairs(top.layer) do if object.type == "textField" and object.active then activeTextField = object break end end if not activeTextField then return end if code == 28 then --enter activeTextField.active = false activeTextField.dirty = true activeTextField.text_buf = activeTextField.text elseif code == 14 then --backspace if unicode.wlen(activeTextField.text) > 0 then activeTextField.text = string.sub(activeTextField.text ,1, #activeTextField.text - 1) activeTextField.dirty = true end elseif code ~= 0 and code ~= 42 then if unicode.wlen(activeTextField.text) < activeTextField.width then activeTextField.text = activeTextField.text..string.char(ch) activeTextField.dirty = true end end end function event_handler.register() event.listen("touch", event_handler.event) event.listen("drag", event_handler.event) event.listen("scroll", event_handler.event) event.listen("drop", event_handler.event) event.listen("key_down", event_handler.event) --event.listen("interrupted",event_handler.event) end function event_handler.ignore() event.ignore("touch" ,event_handler.event) event.ignore("drag", event_handler.event) event.ignore("scroll", event_handler.event) event.ignore("drop", event_handler.event) event.ignore("key_down", event_handler.event) --event.ignore("interrupted",event_handler.event) end --**render**------------------------------------------------------------------- function render.setColor(f_color, b_color) if type(f_color) == "table" then gpu.setForeground(f_color.foreground or cfg.color.std.foreground) gpu.setBackground(f_color.background or cfg.color.std.background) else gpu.setForeground(f_color or cfg.color.std.foreground) gpu.setBackground(b_color or cfg.color.std.background) end end function render.drawFrame(x, y, width, height, char) gpu.set(x, y, char[1][1]) gpu.set(x + width - 1, y, char[1][3]) gpu.set(x, y + height - 1, char[3][1]) gpu.set(x + width - 1, y + height - 1, char[3][3]) gpu.set(x + 1, y, char[1][2]:rep(width - 2)) gpu.set(x+1, y + height - 1, char[3][2]:rep(width - 2)) gpu.set(x, y + 1, char[2][1]:rep(height-2), true) gpu.set(x + width - 1, y + 1, char[2][3]:rep(height-2), true) end function render.drawText(x, y, text, scale) if scale and scale ~= 1 then bigfont.set(x, y, text, scale) else if text and text ~= "" then gpu.set(x, y, text) end end end function render.drawBar(x, y, height) gpu.set(x, y, string.rep(cfg.frame_char.bar, height), true) end function render.drawScrollBar(list) local x, y = list.parent.x + list.x, list.parent.y + list.y local width, height = list.width, list.height x = x + width - 2 gpu.set(x, y, cfg.frame_char.scrollBar[1]) gpu.set(x, y + 1, cfg.frame_char.scrollBar[2]:rep(height - 2), true) gpu.set(x, y + height - 1, cfg.frame_char.scrollBar[3]) local length, pos local maxLength = height - 2 if #list.elements <= maxLength then length = maxLength pos = y + 1 elseif #list.elements > maxLength*2 then length = 1 pos = (list.pos/(#list.elements - (maxLength - 2)))*maxLength pos = list.y + list.parent.y + math.floor(pos) + 1 else length = maxLength - (#list.elements - maxLength) if length < 1 then length = 1 end pos = list.y + list.parent.y + list.pos end gpu.set(x, pos, cfg.frame_char.scrollBar[4]:rep(length), true) end function render.clear(x, y, width, height, color) gpu.setBackground(color) gpu.fill(x, y, width, height, " ") end function render.guiClear() local width, height = gpu.getResolution() gpu.setBackground(gui.background_color) gpu.fill(1, 1, width, height, " ") end --**objects**------------------------------------------------------------------ --functionを毎回作るのはメモリ消費が重いのでprototypeっぽいの objects.prototype = {} objects.prototype.object = {} objects.prototype.window = {} objects.prototype.tabBar = {} objects.prototype.tab = {} objects.prototype.button = {} objects.prototype.switch = {} objects.prototype.progress = {} objects.prototype.label = {} objects.prototype.textField = {} objects.prototype.list = {} --継承っぽいの setmetatable(objects.prototype.window,{__index = objects.prototype.object}) setmetatable(objects.prototype.tabBar,{__index = objects.prototype.object}) setmetatable(objects.prototype.tab ,{__index = objects.prototype.object}) setmetatable(objects.prototype.button,{__index = objects.prototype.object}) setmetatable(objects.prototype.switch,{__index = objects.prototype.object}) setmetatable(objects.prototype.progress, {__index = objects.prototype.object}) setmetatable(objects.prototype.label, {__index = objects.prototype.object}) setmetatable(objects.prototype.textField, {__index = objects.prototype.object}) setmetatable(objects.prototype.list, {__index = objects.prototype.object}) --**object.object**-------------------------------------------------- function objects.prototype.object:enable() if not self.visible then self.visible = true self.dirty = true end return self end function objects.prototype.object:disable() if self.visible then self.dirty = true self.visible = false end return self end function objects.prototype.object:draw() --this method need override end function objects.prototype.object:setPosition(x, y) checkArg(1, x, "number") checkArg(2, y, "number") self.x, self.y = x, y return self end function objects.prototype.object:getPosition() return self.x, self.y end function objects.prototype.object:setScale(width, height) checkArg(1, width, "number") checkArg(2, height, "number") self.width = width self.height = height return self end function objects.prototype.object:getScale() return self.width, self.height end function objects.prototype.object:getType() return self.type end --オブジェクトの雛形クラス function objects.newObject(x,y,width,height) checkArg(1, x, "nil", "number") checkArg(2, y, "nil", "number") checkArg(3, width, "nil", "number") checkArg(4, height, "nil", "number") local object = {} object.x = x or cfg.default.x object.y = y or cfg.default.y object.width = width or cfg.default.width object.height = height or cfg.default.height object.visible = true object.dirty = true object.type = "object" return object end --**object.window**------------------------------------------------------------ --window自体の描画 function objects.prototype.window:draw() local x, y = self.x, self.y local width, height = self.width, self.height local frame_color = self.frame_color local panel_color = self.panel_color local name, name_color = self.name, self.name_color local close_button_color = self.close_button_color --drawFrame render.setColor(frame_color, panel_color) render.drawFrame(x, y, width, height, cfg.frame_char.window) --name if name and name_color then render.setColor(name_color, frame_color) render.drawText(x + 1, y, name) end --drawclosebutton render.setColor(close_button_color, frame_color) render.drawText(x + width - 2, y, cfg.frame_char.close_button) --fill margin render.clear(x + 1, y + 1, width - 2, height - 2, panel_color) end function objects.prototype.window:close() --closeされたwindow以外は再描画する local remove for i, window in ipairs(gui.layer) do window.dirty = true if window == self then remove = i end end table.remove(gui.layer, remove) end function objects.prototype.window:setWindowName(name) checkArg(1, name, "string") self.name = name self.dirty = true return self end function objects.prototype.window:setWindowNameColor(color) checkArg(1, color, "number") self.name_color = color self.dirty = true return self end function objects.prototype.window:setCloseButtonColor(color) checkArg(1, color, "number") self.close_button_color = color self.dirty = true return self end function objects.prototype.window:setFrameColor(color) checkArg(1, color, "number") self.frame_color = color self.dirty = true return self end function objects.prototype.window:setCloseButtonCallback(callback) checkArg(1, callback, "function", "nil") self.close_button_callback = callback return self end function objects.prototype.window:setMoveability(boolean) checkArg(1, boolean, "boolean") self.moveability = boolean return self end --window単位で描画したい時に function objects.prototype.window:update() --レイヤー中で再描画すべきオブジェクトがあるなら全オブジェクトを再描画する local redraw = false if not self.layer or #self.layer == 0 then return end for i, object in ipairs(self.layer) do if object.visible then object:draw() object.dirty = false end end end function objects.prototype.window:newTabBar() local tabBar = objects.newTabBar(self) --barはwindow layerの二番目に挿入する if self.layer[2] and self.layer[2].type == "tabBar" then error("newTabBar") end table.insert(self.layer, 2, tabBar) return tabBar end function objects.prototype.window:newButton(x,y,width,height,callback) local button = objects.newButton(x,y,width,height,callback) button.parent = self button.callback = callback table.insert(self.layer, button) return button end function objects.prototype.window:newSwitch(x, y, width, height, on, off) local switch = objects.newSwitch(x, y, width, height, on, off) switch.parent = self table.insert(self.layer, switch) return switch end function objects.prototype.window:newLabel(x, y, text) local label = objects.newLabel(x, y, text) label.parent = self table.insert(self.layer, label) return label end function objects.prototype.window:newProgress(x,y,width,height) local progress = objects.newProgress(x, y, width, height) progress.parent = self table.insert(self.layer, progress) return progress end function objects.prototype.window:newTextField(x, y, width) local textField = objects.newTextField(x, y, width) textField.parent = self table.insert(self.layer, textField) return textField end function objects.prototype.window:newList(x, y, width, height) local list = objects.newList(x, y, width, height) list.parent = self table.insert(self.layer, list) return list end function objects.newWindow(x,y,width,height,screen_address) local window = objects.newObject(x,y,width,height) window.type = "window" window.moveability = true window.focus = false window.move = {} window.move.moving = false window.move.position = 0 window.screen_address = screen_address window.frame_color = cfg.color.window.frame window.panel_color = cfg.color.window.panel window.name_color = cfg.color.window.name window.close_button_color = cfg.color.window.close_button setmetatable(window,{__index = objects.prototype.window}) --window内部のLayer添字が大きいほど優先される window.layer = {} table.insert(window.layer,window) table.insert(gui.layer,window) return window --[[ window.screen_address window.x window.y window.width window.height window.enable window.moveability window.moving object.dirty window.panel_color window.name_color window.close_button_color window.frame_f_color window.frame_b_color --追加可能 window.name --]] end --**objects.tabBar**----------------------------------------------------------- function objects.prototype.tabBar:draw() if not self.visible then return end --親windowの座標を local parent = self.window local x, y = parent.x, parent.y + 1 local width, height = parent.width, 1 --draw bar gpu.setBackground(parent.frame_color) gpu.fill(x, y, width, height, " ") end function objects.prototype.tabBar:newTab() local tab = objects.newTab(self.window) end function objects.newTabBar(window) local x, y = 0, 0 local width, height = 0, 0 local tabBar = objects.newObject(x, y, width, height) tabBar.type = "tabBar" --親windowへのポインタ的な tabBar.window = window --tabを格納する tabBar.tabs = {} setmetatable(tabBar,{__index = objects.prototype.tabBar}) --objects.prototype.tabBar.__index = objects.prototype.tabBar return tabBar --[[ tabBar.x tabBar.y tabBar.width tabBar.height tabBar.enable tabBar.dirty tabBar.name_color --]] end --**objects.tab**-------------------------------------------------------------- function objects.prototype.tab:setName() -- body end function objects.prototype.tab:draw() end function objects.newTab(window) local x, y = 0, 0 local width, height = 0, 0 local tab = objects.newObject(x, y, 0, 0) tab.type = "tab" tab.window = window tab.layer = {} setmetatable(tabBar, {__index = objects.prototype.tab}) return tab end --**object.button**------------------------------------------------------------ function objects.prototype.button:draw() if not self.visible then return end local x, y = self.x + self.parent.x, self.y + self.parent.y local width, height = self.width, self.height local panel_color, frame_color = self.panel_color, self.frame_color --drawFrame if self.frame_type ~= "none" then render.setColor(frame_color, panel_color) render.drawFrame(x, y, width, height, cfg.frame_char[self.frame_type]) render.clear(x + 1 , y + 1 , width - 2 , height - 2, panel_color) else render.clear(x , y, width, height, panel_color) end --drawText if self.text and self.text ~= "" then local tx, ty = x + self.text_x - 1 , y + self.text_y - 1 render.setColor(self.text_color, panel_color) render.drawText(tx , ty, self.text, self.text_scale) end end function objects.prototype.button:setCallback(callback, ...) checkArg(1, callback, "function", "nil") self.callback = callback self.args = table.pack(...) return self end --0でframeなし1でデフォルト function objects.prototype.button:setFrameType(type) checkArg(1, type, "string") self.frame_type = type self.dirty = true return self end function objects.prototype.button:setText(text) checkArg(1, text, "string") self.text = text self.dirty = true return self end function objects.prototype.button:setTextPosition(x, y) local x, y = tonumber(x), tonumber(y) checkArg(1, x, "number") checkArg(2, y, "number") self.text_x, self.text_y = x, y self.dirty = true return self end function objects.prototype.button:setTextScale(scale) checkArg(1, scale, "number") if type(scale) ~= "number" or self.text_scale == scale then return self end self.text_scale = scale self.dirty = true return self end function objects.prototype.button:setTextColor(color) checkArg(1, color, "number") self.text_color = color self.dirty = true return self end function objects.prototype.button:setPanelColor(color) checkArg(1, color, "number") self.panel_color = color self.dirty = true return self end function objects.prototype.button:setFrameColor(color) checkArg(1, color, "number") self.frame_color = color self.dirty = true return self end function objects.newButton(x, y, width, height, callback) checkArg(1, x, "nil", "number") checkArg(2, y, "nil", "number") checkArg(3, width, "nil", "number") checkArg(4, height, "nil", "number") checkArg(5, callback, "nil", "function") local button = objects.newObject(x, y, width, height) button.type = "button" button.callback = callback button.frame_type = "button" button.text = "" button.text_scale = 1 button.text_x, button.text_y = 2, 2 button.text_color = cfg.color.button.text button.panel_color = cfg.color.button.panel button.frame_color = cfg.color.button.frame setmetatable(button, {__index = objects.prototype.button}) --objects.prototype.button.__index = objects.prototype.button return button end --**object.switch**------------------------------------------------------------ function objects.prototype.switch:draw() local x, y = self.x + self.parent.x, self.y + self.parent.y local width, height = self.width, self.height local state = self.state --render.setColor(self.color.text[self.state]) local panel_color = self.color.panel[state].background if self.frame_type ~= "none" then render.setColor(self.color.frame[state]) if cfg.frame_char[self.frame_type] then render.drawFrame(x, y, width, height, cfg.frame_char[self.frame_type]) else render.drawFrame(x, y, width, height, cfg.frame_char.button) end render.clear(x + 1 , y + 1 , width - 2 , height - 2, panel_color) else render.clear(x , y, width, height, panel_color) end --drawText if self.text and self.text ~= "" then local tx, ty = x + self.text_x - 1 , y + self.text_y - 1 render.setColor(self.color.text[state]) render.drawText(tx , ty, self.text[state], self.text_scale[state]) end end function objects.prototype.switch:getState() return self.state end function objects.prototype.switch:setOnText(text) checkArg(1, text, "string") self.text.on = text self.dirty = true return self end function objects.prototype.switch:setOffText(text) checkArg(1, text, "string") self.text.off = text self.dirty = true return self end function objects.prototype.switch:setTextPosition(x, y) checkArg(1, x, "number") checkArg(2, y, "number") self.x, self.y = x, y self.dirty = true return self end function objects.prototype.switch:setTextOnColor(f_color, b_color) checkArg(1, f_color, "number") checkArg(2, b_color, "number") self.color.text.on.foreground = f_color self.color.text.on.background = b_color self.dirty = true return self end function objects.prototype.switch:setTextOffColor(f_color, b_color) checkArg(1, f_color, "number") checkArg(2, b_color, "number") self.color.text.off.foreground = f_color self.color.text.off.background = b_color self.dirty = true return self end function objects.prototype.switch:setPanelOnColor(f_color, b_color) checkArg(1, f_color, "number") checkArg(2, b_color, "number") self.color.panel.on.foreground = f_color self.color.panel.on.background = b_color self.dirty = true return self end function objects.prototype.switch:setPanelOffColor(f_color, b_color) checkArg(1, f_color, "number") checkArg(2, b_color, "number") self.color.panel.off.foreground = f_color self.color.panel.off.background = b_color self.dirty = true return self end function objects.prototype.switch:setFrameOnColor(f_color, b_color) checkArg(1, f_color, "number") checkArg(2, b_color, "number") self.color.frame.on.foreground = f_color self.color.frame.on.background = b_color self.dirty = true return self end function objects.prototype.switch:setFrameOffColor(f_color, b_color) checkArg(1, f_color, "number") checkArg(2, b_color, "number") self.color.frame.off.foreground = f_color self.color.frame.off.background = b_color self.dirty = true return self end function objects.prototype.switch:setOffCallback(func, ...) checkArg(1, func, "function") self.callback.off = func self.args.off = table.pack(...) return self end function objects.prototype.switch:setOnCallback(func, ...) checkArg(1, func, "function") self.callback.on = func self.args.on = table.pack(...) return self end function objects.prototype.switch:setOnTextScale(scale) checkArg(1, scale, "number") self.text_scale.on = scale self.dirty = true return self end function objects.prototype.switch:setOffTextScale(scale) checkArg(1, scale, "number") self.text_scale.off = scale self.dirty = true return self end function objects.prototype.switch:setFrameType(frame_type) checkArg(1, frame_type, "string") self.frame_type = frame_type self.dirty = true return self end function objects.newSwitch(x, y, width, height, onCallback, offCallback) checkArg(1, x, "nil", "number") checkArg(2, y, "nil", "number") checkArg(3, width, "nil", "number") checkArg(4, height, "nil", "number") checkArg(5, onCallback, "nil", "function") checkArg(6, offCallback, "nil", "function") local switch = objects.newObject(x, y, width, height) switch.type = "switch" switch.state = "off" switch.frame_type = "button" switch.text = {} switch.text_scale = {} switch.text_scale.on = 1 switch.text_scale.off = 1 switch.text_x, switch.text_y = 2, 2 switch.callback = {} switch.callback.on = onCallback switch.callback.off = offCallback switch.args = {} switch.color = {} switch.color.text = {} switch.color.text.on = {} switch.color.text.on.foreground = cfg.color.switch.text.on.foreground switch.color.text.on.background = cfg.color.switch.text.on.background switch.color.text.off = {} switch.color.text.off.foreground = cfg.color.switch.text.off.foreground switch.color.text.off.background = cfg.color.switch.text.off.background switch.color.panel = {} switch.color.panel.on = {} switch.color.panel.on.foreground = cfg.color.switch.panel.on.foreground switch.color.panel.on.background = cfg.color.switch.panel.on.background switch.color.panel.off = {} switch.color.panel.off.foreground = cfg.color.switch.panel.off.foreground switch.color.panel.off.background = cfg.color.switch.panel.off.background switch.color.frame = {} switch.color.frame.on = {} switch.color.frame.on.foreground = cfg.color.switch.frame.on.foreground switch.color.frame.on.background = cfg.color.switch.frame.on.background switch.color.frame.off = {} switch.color.frame.off.foreground = cfg.color.switch.frame.off.foreground switch.color.frame.off.background = cfg.color.switch.frame.off.background setmetatable(switch,{__index = objects.prototype.switch}) return switch end --**object.label**------------------------------------------------------------- function objects.prototype.label:draw() if not self.visible or self.text == "" then return end local x, y = self.x + self.parent.x, self.y + self.parent.y render.setColor(self.color.text) render.drawText(x, y, self.text, self.scale) --underline if self.underline then render.setColor(self.color.underline) local text = string.rep("⠉", self.text:len() * self.scale) render.drawText(x, y + self.scale, text, 1) end end function objects.prototype.label:clear() end function objects.prototype.label:setUnderline(bool) checkArg(1, bool, "boolean", "nil") self.underline = bool self.dirty = true return self end function objects.prototype.label:setScale(scale) checkArg(1, scale, "number") self.scale = scale self.dirty = true return self end function objects.prototype.label:getScale() return self.scale end function objects.prototype.label:setTextColor(f_color, b_color) checkArg(1, f_color, "number", "nil") checkArg(2, b_color, "number", "nil") if f_color then self.color.text.foreground = f_color end if b_color then self.color.text.background = b_color end return self end function objects.prototype.label:setUnderlineColor(f_color, b_color) checkArg(1, f_color, "number", "nil") checkArg(2, b_color, "number", "nil") if f_color then self.color.underline.foreground = f_color end if b_color then self.color.underline.background = b_color end return self end function objects.prototype.label:setText(text) local s = tostring(text) checkArg(1, s, "string") if s and s ~= self.text and s ~= "" then self.text = s self.dirty = true end return self end function objects.prototype.label:getText() return self.text end function objects.newLabel(x, y, text) text = tostring(text) checkArg(1, x, "number") checkArg(2, y, "number") checkArg(3, text, "string", "nil") local label = objects.newObject(x, y, 1, 1) label.type = "text" label.text = text label.underline = false label.scale = 1 label.color = {} label.color.text = {} label.color.underline = {} label.color.underline.foreground = cfg.color.label.underline.foreground label.color.underline.background = cfg.color.label.underline.background label.color.text.foreground = cfg.color.label.text.foreground label.color.text.background = cfg.color.label.text.background setmetatable(label, {__index = objects.prototype.label}) return label end --**object.progress**---------------------------------------------------------- function objects.prototype.progress:draw() local x, y = self.x + self.parent.x, self.y + self.parent.y local width, height = self.width, self.height local bw = math.floor((self.percentage / 100) * (width - 2)) local panel_color = self.color.bar.background if width > 2 and height > 2 then render.setColor(self.color.frame) render.drawFrame(x, y, width, height, cfg.frame_char.progress) render.setColor(self.color.bar) render.clear(x + 1, y + 1, width - 2, height - 2, panel_color) if bw > 0 then for i = 1, bw do render.drawBar(x + i, y + 1, height - 2) end end end if self.name and self.name ~= "" then render.setColor(self.color.name) render.drawText(x + 2, y, self.name) end end function objects.prototype.progress:setProgress(percentage) checkArg(1, percentage, "number") if self.percentage ~= percentage then self.percentage = percentage self.dirty = true end return self end function objects.prototype.progress:setName(name) checkArg(1, name, "string") self.name = name self.dirty = true return self end function objects.prototype.progress:setNameColor(f_color, b_color) checkArg(1, f_color, "number", "nil") checkArg(2, b_color, "number", "nil") if f_color then self.color.name.foreground = f_color end if b_color then self.color.name.background = b_color end end function objects.newProgress(x, y, width, height) checkArg(1, x, "nil", "number") checkArg(2, y, "nil", "number") checkArg(3, width, "nil", "number") checkArg(4, height, "nil", "number") local progress = objects.newObject(x, y, width, height) progress.type = "progress" progress.name = "" progress.percentage = 0 progress.color = {} progress.color.bar = {} progress.color.bar.foreground = cfg.color.progress.bar.foreground progress.color.bar.background = cfg.color.progress.bar.background progress.color.frame = {} progress.color.frame.foreground = cfg.color.progress.frame.foreground progress.color.frame.background = cfg.color.progress.frame.background progress.color.name = {} progress.color.name.foreground = cfg.color.progress.name.foreground progress.color.name.background = cfg.color.progress.name.background setmetatable(progress, {__index = objects.prototype.progress}) return progress end --**object.textField**--------------------------------------------------------- --setScaleの上書き function objects.prototype.textField:setScale(width) checkArg(1, width, "number") self.width = width return self end function objects.prototype.textField:draw() if not self.visible then return end local x, y = self.x + self.parent.x, self.y + self.parent.y local f_col, b_col = self.color.text.foreground, self.color.text.background if self.active then f_col, b_col = self.color.active.foreground, self.color.active.background end local internal_text if unicode.wlen(self.text) > self.width then internal_text = unicode.sub(1, self.width) else internal_text = text.padRight(self.text, self.width) end render.setColor(f_col, b_col) render.drawText(x, y, internal_text) end function objects.prototype.textField:setText(text) checkArg(1, text, "string") self.text = text self.dirty = true textField.text_buf = text return self end function objects.prototype.textField:getText() return self.text_buf end function objects.newTextField(x, y, width) checkArg(1, x, "nil", "number") checkArg(2, y, "nil", "number") checkArg(3, width, "nil", "number") local textField = objects.newObject(x, y, width, 1) textField.type = "textField" textField.text = "" textField.text_buf = "" textField.active = false textField.color = {} textField.color.text = {} textField.color.text.foreground = cfg.color.textField.text.foreground textField.color.text.background = cfg.color.textField.text.background textField.color.active = {} textField.color.active.foreground = cfg.color.textField.active.foreground textField.color.active.background = cfg.color.textField.active.background setmetatable(textField, {__index = objects.prototype.textField}) return textField end --**object.list**-------------------------------------------------------------- function objects.prototype.list:draw() if not self.visible then return end --親windowの座標を local parent = self.parent local x, y = self.x + parent.x, self.y + parent.y local width, height = self.width, self.height --render.setColor() render.setColor(self.color.frame) render.drawFrame(x, y, width, height, cfg.frame_char.list) --drawScrollBar render.drawScrollBar(self) --drawName render.drawText(x + 1, y, self.name) --drawElements local pos = 1 for i = self.pos, #self.elements do local element = self.elements[i] if not element or self.height - 2 < pos then break end local name = text.padRight(element.name, width - 3) name = name:sub(1, width - 3) render.setColor(element.color[element.state]) render.drawText(x + 1, y + pos, name) pos = pos + 1 end end function objects.prototype.list:setName(name) checkArg(1, name, "string") self.name = name self.dirty = true return self end function objects.prototype.list:clearAllElement() self.elements = {} self.dirty = true return self end function objects.prototype.list:getOnElementIndex() for i, el in ipairs(self.elements) do if el.state == "on" then return i end end end function objects.prototype.list:setOnElementColor(index, f_color, b_color) checkArg(1, index, "number") checkArg(2, f_color, "number", "nil") checkArg(3, b_color, "number", "nil") if not self.elements[index] then return end if f_color then self.elements[index].color.on.foreground = f_color end if b_color then self.elements[index].color.on.background = b_color end end function objects.prototype.list:setElementColor(index, state, f_color, b_color) checkArg(1, index, "number") checkArg(2, state, "string") checkArg(3, f_color, "number", "nil") checkArg(4, b_color, "number", "nil") if not self.elements[index] or (state ~= "on" and state ~= "off") then return end f_color = f_color or self.color.element[state].foreground b_color = b_color or self.color.element[state].background self.elements[index].color[state].foreground = f_color self.elements[index].color[state].background = b_color self.dirty = true return self end function objects.prototype.list:addElement(name, callback, ...) checkArg(1, name, "string") checkArg(2, callback, "function", "nil") local element = {} element.state = "off" element.name = name element.callback = callback element.color = {} element.color.on = {} element.color.on.foreground = self.color.element.on.foreground element.color.on.background = self.color.element.on.background element.color.off = {} element.color.off.foreground = self.color.element.off.foreground element.color.off.background = self.color.element.off.background element.args = table.pack(...) table.insert(self.elements, element) return self end function objects.newList(x, y, width, height) checkArg(1, x, "nil", "number") checkArg(2, y, "nil", "number") checkArg(3, width, "nil", "number") checkArg(4, height, "nil", "number") local list = objects.newObject(x, y, width, height) list.type = "list" list.name = "" list.pos = 1 list.elements = {} list.color = {} list.color.element = {} list.color.element.on = {} list.color.element.on.foreground = cfg.color.list.element.on.foreground list.color.element.on.background = cfg.color.list.element.on.background list.color.element.off = {} list.color.element.off.foreground = cfg.color.list.element.off.foreground list.color.element.off.background = cfg.color.list.element.off.background list.color.frame = {} list.color.frame.foreground = cfg.color.list.frame.foreground list.color.frame.background = cfg.color.list.frame.background list.color.panel = {} list.color.panel.foreground = cfg.color.list.panel.foreground list.color.panel.background = cfg.color.list.panel.background setmetatable(list, {__index = objects.prototype.list}) return list end --**gui**---------------------------------------------------------------------- --window単位でのlayer gui.layer = {} -- gui.background_color = cfg.color.gui.background function gui:newWindow(x, y, width, height,screen_address) screen_address = screen_address or component.screen.address local newWindow = objects.newWindow(x, y, width, height, screen_address) event_handler.register() return newWindow end --全windowを描画しなおしたい時に呼ぶ function gui:update() if not self.layer or #self.layer == 0 then gui:exit() end if render.internal.cursor.blink then local cx, cy = render.internal.cursor.x, render.internal.cursor.y render.setColor(0x000000, 0xFFFFFF) term.setCursorBlink(true) term.setCursor(cx, cy) else term.setCursorBlink(false) end local redraw = false for i, window in ipairs(self.layer) do for j, object in ipairs(window.layer) do if object.dirty then redraw = true end end end if not redraw then return end render.guiClear() for i, window in ipairs(self.layer) do window:update() end end function gui:setBackgroundColor(color) checkArg(1, color, "number") gui.background_color = color or gui.background_color end function gui:exit() gui.layer = {} event_handler.ignore() render.setColor(cfg.color.std) term.clear() os.exit() end function gui:init() gui.layer = {} event_handler.ignore() for size = 2, 4 do bigfont.load(size) end end return gui
local K, C, L, _ = select(2, ...):unpack() local format, find, gsub = string.format, string.find, string.gsub local match = string.match local floor, ceil = math.floor, math.ceil local print = print local reverse = string.reverse local tonumber, type = tonumber, type local unpack, select = unpack, select local CreateFrame = CreateFrame local GetCombatRatingBonus = GetCombatRatingBonus local GetSpellInfo = GetSpellInfo local GetNumPartyMembers, GetNumRaidMembers = GetNumPartyMembers, GetNumRaidMembers local UnitStat, UnitAttackPower, UnitBuff = UnitStat, UnitAttackPower, UnitBuff local tinsert, tremove = tinsert, tremove K.Backdrop = {bgFile = C["Media"].Blank, edgeFile = C["Media"].Blizz, edgeSize = 14, insets = {left = 2.5, right = 2.5, top = 2.5, bottom = 2.5}} K.Border = {edgeFile = C["Media"].Blizz, edgeSize = 14} K.BorderBackdrop = {bgFile = C["Media"].Blank} K.PixelBorder = {edgeFile = C["Media"].Blank, edgeSize = K.Mult, insets = {left = K.Mult, right = K.Mult, top = K.Mult, bottom = K.Mult}} K.ShadowBackdrop = {edgeFile = C["Media"].Glow, edgeSize = 3, insets = {left = 5, right = 5, top = 5, bottom = 5}} -- This frame everything in KkthnxUI should be anchored to for Eyefinity support. K.UIParent = CreateFrame("Frame", "KkthnxUIParent", UIParent) K.UIParent:SetFrameLevel(UIParent:GetFrameLevel()) K.UIParent:SetPoint("CENTER", UIParent, "CENTER") K.UIParent:SetSize(UIParent:GetSize()) K.TexCoords = {5/65, 59/64, 5/64, 59/64} K.Print = function(...) print("|cff2eb6ffKkthnxUI|r:", ...) end K.SetFontString = function(parent, fontName, fontHeight, fontStyle) local fs = parent:CreateFontString(nil, "OVERLAY") fs:SetFont(fontName, fontHeight, fontStyle) fs:SetJustifyH("LEFT") fs:SetShadowColor(0, 0, 0) fs:SetShadowOffset((0), -(0)) return fs end K.Comma = function(num) local Left, Number, Right = match(num, "^([^%d]*%d)(%d*)(.-)$") return Left .. reverse(gsub(reverse(Number), "(%d%d%d)", "%1,")) .. Right end -- ShortValue K.ShortValue = function(value) value = tonumber(value) if not value then return "" end if value >= 1e6 then return ("%.1fm"):format(value / 1e6):gsub("%.?0+([km])$", "%1") elseif value >= 1e3 or value <= -1e3 then return ("%.1fk"):format(value / 1e3):gsub("%.?0+([km])$", "%1") else return floor(tostring(value)) end end -- Rounding K.Round = function(number, decimals) if (not decimals) then decimals = 0 end return format(format("%%.%df", decimals), number) end -- RGBToHex Color K.RGBToHex = function(r, g, b) r = r <= 1 and r >= 0 and r or 0 g = g <= 1 and g >= 0 and g or 0 b = b <= 1 and b >= 0 and b or 0 return format("|cff%02x%02x%02x", r * 255, g * 255, b * 255) end K.CheckChat = function(warning) local numParty, numRaid = GetNumPartyMembers(), GetNumRaidMembers() if (numRaid > 0) then if warning and (UnitIsPartyLeader("player")) or (UnitIsRaidOfficer("player")) then return "RAID_WARNING" else return "RAID" end elseif (numParty > 0) then return "PARTY" end return "SAY" end local RoleUpdater = CreateFrame("Frame") local function CheckRole(self, event, unit) if event == "UNIT_AURA" and unit ~= "player" then return end if (K.Class == "PALADIN" and UnitBuff("player", GetSpellInfo(25780))) and GetCombatRatingBonus(CR_DEFENSE_SKILL) > 100 or (K.Class == "WARRIOR" and GetBonusBarOffset() == 2) or (K.Class == "DEATHKNIGHT" and UnitBuff("player", GetSpellInfo(48263))) or (K.Class == "DRUID" and GetBonusBarOffset() == 3) then K.Role = "Tank" else local playerint = select(2, UnitStat("player", 4)) local playeragi = select(2, UnitStat("player", 2)) local base, posBuff, negBuff = UnitAttackPower("player") local playerap = base + posBuff + negBuff if ((playerap > playerint) or (playeragi > playerint)) and not (UnitBuff("player", GetSpellInfo(24858)) or UnitBuff("player", GetSpellInfo(65139))) then K.Role = "Melee" else K.Role = "Caster" end end -- Unregister useless events if event == "PLAYER_ENTERING_WORLD" then if K.Class ~= "WARRIOR" and K.Class ~= "DRUID" then RoleUpdater:UnregisterEvent("UPDATE_BONUS_ACTIONBAR") end RoleUpdater:UnregisterEvent("PLAYER_ENTERING_WORLD") end end RoleUpdater:RegisterEvent("PLAYER_ENTERING_WORLD") RoleUpdater:RegisterEvent("UNIT_AURA") RoleUpdater:RegisterEvent("UPDATE_BONUS_ACTIONBAR") RoleUpdater:RegisterEvent("ACTIVE_TALENT_GROUP_CHANGED") RoleUpdater:RegisterEvent("CHARACTER_POINTS_CHANGED") RoleUpdater:RegisterEvent("UNIT_INVENTORY_CHANGED") RoleUpdater:SetScript("OnEvent", CheckRole) CheckRole() function K.ShortenString(string, numChars, dots) local bytes = string:len() if(bytes <= numChars) then return string else local len, pos = 0, 1 while(pos <= bytes) do len = len + 1 local c = string:byte(pos) if(c > 0 and c <= 127) then pos = pos + 1 elseif(c >= 192 and c <= 223) then pos = pos + 2 elseif(c >= 224 and c <= 239) then pos = pos + 3 elseif(c >= 240 and c <= 247) then pos = pos + 4 end if(len == numChars) then break end end if(len == numChars and pos <= bytes) then return string:sub(1, pos - 1)..(dots and "..." or "") else return string end end end K.RuneColor = { [1] = {r = 0.7, g = 0.1, b = 0.1}, [2] = {r = 0.7, g = 0.1, b = 0.1}, [3] = {r = 0.4, g = 0.8, b = 0.2}, [4] = {r = 0.4, g = 0.8, b = 0.2}, [5] = {r = 0.0, g = 0.6, b = 0.8}, [6] = {r = 0.0, g = 0.6, b = 0.8}, } K.ComboColor = { [1] = {r = 1.0, g = 1.0, b = 1.0}, [2] = {r = 1.0, g = 1.0, b = 1.0}, [3] = {r = 1.0, g = 1.0, b = 1.0}, [4] = {r = 0.9, g = 0.7, b = 0.0}, [5] = {r = 1.0, g = 0.0, b = 0.0}, } K.TimeColors = { [0] = "|cffeeeeee", [1] = "|cffeeeeee", [2] = "|cffeeeeee", [3] = "|cffeeeeee", [4] = "|cfffe0000" } K.TimeFormats = { [0] = {"%dd", "%dd"}, [1] = {"%dh", "%dh"}, [2] = {"%dm", "%dm"}, [3] = {"%ds", "%d"}, [4] = {"%.1fs", "%.1f"} } K.GetTimeInfo = function(s, threshhold) local Day, Hour, Minute = 86400, 3600, 60 local Dayish, Hourish, Minuteish = 3600 * 23.5, 60 * 59.5, 59.5 local HalfDayish, HalfHourish, HalfMinuteish = Day / 2 + 0.5, Hour / 2 + 0.5, Minute / 2 + 0.5 if(s < Minute) then if(s >= threshhold) then return floor(s), 3, 0.51 else return s, 4, 0.051 end elseif(s < Hour) then local Minutes = floor((s / Minute) + 0.5) return ceil(s / Minute), 2, Minutes > 1 and (s - (Minutes * Minute - HalfMinuteish)) or (s - Minuteish) elseif(s < Day) then local Hours = floor((s / Hour) + 0.5) return ceil(s / Hour), 1, Hours > 1 and (s - (Hours * Hour - HalfHourish)) or (s - Hourish) else local Days = floor((s / Day) + 0.5) return ceil(s / Day), 0, Days > 1 and (s - (Days * Day - HalfDayish)) or (s - Dayish) end end K.FormatMoney = function(value) if value >= 1e4 then return format("|cffffd700%dg |r|cffc7c7cf%ds |r|cffeda55f%dc|r", value/1e4, strsub(value, -4) / 1e2, strsub(value, -2)) elseif value >= 1e2 then return format("|cffc7c7cf%ds |r|cffeda55f%dc|r", strsub(value, -4) / 1e2, strsub(value, -2)) else return format("|cffeda55f%dc|r", strsub(value, -2)) end end -- Add time before calling a function local waitTable = {} local waitFrame K.Delay = function(delay, func, ...) if(type(delay) ~= "number" or type(func) ~= "function") then return false end if(waitFrame == nil) then waitFrame = CreateFrame("Frame", "WaitFrame", UIParent) waitFrame:SetScript("onUpdate", function (self, elapse) local count = #waitTable local i = 1 while(i <= count) do local waitRecord = tremove(waitTable,i) local d = tremove(waitRecord,1) local f = tremove(waitRecord,1) local p = tremove(waitRecord,1) if(d > elapse) then tinsert(waitTable, i, {d-elapse, f, p}) i = i + 1 else count = count - 1 f(unpack(p)) end end end) end tinsert(waitTable, {delay, func, {...}}) return true end
local eterna_forest_0 = DoorSlot("eterna_forest","0") local eterna_forest_0_hub = DoorSlotHub("eterna_forest","0",eterna_forest_0) eterna_forest_0:setHubIcon(eterna_forest_0_hub) local eterna_forest_1 = DoorSlot("eterna_forest","1") local eterna_forest_1_hub = DoorSlotHub("eterna_forest","1",eterna_forest_1) eterna_forest_1:setHubIcon(eterna_forest_1_hub) local eterna_forest_2 = DoorSlot("eterna_forest","2") local eterna_forest_2_hub = DoorSlotHub("eterna_forest","2",eterna_forest_2) eterna_forest_2:setHubIcon(eterna_forest_2_hub)
local m = require 'pegparser.parser' local coder = require 'pegparser.coder' local util = require'pegparser.util' g = [[ program <- SKIP head^Err_001 decs block^Err_002 Dot^Err_003 !. head <- PROGRAM^Err_004 Id^Err_005 (LPar ids^Err_006 RPar^Err_007 / !Semi %{Err_008} .)? Semi^Err_009 decs <- labelDecs constDefs typeDefs varDecs procAndFuncDecs ids <- Id (Comma Id)* labelDecs <- (LABEL labels^Err_010 Semi^Err_011)? labels <- label^Err_012 (Comma label^Err_013 / !Semi %{Err_014} .)* label <- UInt constDefs <- (CONST constDef^Err_015 Semi^Err_016 (constDef Semi^Err_017 / !(VAR / TYPE / PROCEDURE / FUNCTION / BEGIN) %{Err_018} .)*)? constDef <- Id Eq^Err_019 const^Err_020 const <- Sign? (UNumber / Id) / String typeDefs <- (TYPE typeDef^Err_021 Semi^Err_022 (typeDef Semi^Err_023 / !(VAR / PROCEDURE / FUNCTION / BEGIN) %{Err_024} .)*)? typeDef <- Id Eq^Err_025 type^Err_026 type <- newType / Id newType <- newOrdinalType / newStructuredType / newPointerType newOrdinalType <- enumType / subrangeType newStructuredType <- PACKED? unpackedStructuredType newPointerType <- Pointer Id^Err_027 enumType <- LPar ids RPar subrangeType <- const DotDot const unpackedStructuredType <- arrayType / recordType / setType / fileType arrayType <- ARRAY LBrack^Err_028 ordinalType^Err_029 (Comma ordinalType^Err_030 / !RBrack %{Err_031} .)* RBrack^Err_032 OF^Err_033 type^Err_034 recordType <- RECORD fieldList END^Err_035 setType <- SET OF^Err_036 ordinalType^Err_037 fileType <- FILE OF^Err_038 type^Err_039 ordinalType <- (newOrdinalType / Id^Err_040)^Err_041 fieldList <- ((fixedPart (Semi variantPart)? / variantPart) Semi?)? fixedPart <- varDec (Semi varDec)* variantPart <- CASE Id (Colon Id)? OF variant (Semi variant)* variant <- consts Colon LPar fieldList RPar consts <- const (Comma const)* varDecs <- (VAR varDec Semi (varDec Semi^Err_042 / !(PROCEDURE / FUNCTION / BEGIN) %{Err_043} .)*)? varDec <- ids Colon type procAndFuncDecs <- ((procDec / funcDec) Semi)* procDec <- procHeading Semi (decs block / Id) procHeading <- PROCEDURE Id^Err_044 (formalParams / !(Semi / RPar) %{Err_045} .)? funcDec <- funcHeading Semi (decs block / Id) funcHeading <- FUNCTION Id^Err_046 (formalParams / !Colon %{Err_047} .)? Colon^Err_048 type^Err_049 formalParams <- LPar formalParamsSection^Err_050 (Semi formalParamsSection^Err_051 / !RPar %{Err_052} .)* RPar^Err_053 formalParamsSection <- (VAR? ids Colon^Err_054 Id^Err_055 / procHeading / funcHeading)^Err_056 block <- BEGIN stmts END^Err_057 stmts <- stmt (Semi stmt / !(UNTIL / END) %{Err_058} .)* stmt <- (label Colon^Err_059)? (simpleStmt / structuredStmt)? simpleStmt <- assignStmt / procStmt / gotoStmt assignStmt <- var Assign expr^Err_060 var <- Id (LBrack expr^Err_061 (Comma expr^Err_062 / !RBrack %{Err_063} .)* RBrack^Err_064 / Dot Id^Err_065 / Pointer)* procStmt <- Id params? params <- LPar (param (Comma param)*)? RPar param <- expr (Colon expr)? (Colon expr)? gotoStmt <- GOTO label^Err_066 structuredStmt <- block / conditionalStmt / repetitiveStmt / withStmt conditionalStmt <- ifStmt / caseStmt ifStmt <- IF expr^Err_067 THEN^Err_068 stmt (ELSE stmt / !(UNTIL / Semi / END / ELSE) %{Err_069} .)? caseStmt <- CASE expr OF caseListElement (Semi caseListElement)* Semi? END caseListElement <- consts Colon stmt repetitiveStmt <- repeatStmt / whileStmt / forStmt repeatStmt <- REPEAT stmts UNTIL^Err_070 expr^Err_071 whileStmt <- WHILE expr^Err_072 DO^Err_073 stmt forStmt <- FOR Id^Err_074 Assign^Err_075 expr^Err_076 (TO / DOWNTO^Err_077)^Err_078 expr^Err_079 DO^Err_080 stmt withStmt <- WITH var^Err_081 (Comma var^Err_082 / !DO %{Err_083} .)* DO^Err_084 stmt expr <- simpleExpr (RelOp simpleExpr^Err_085)? simpleExpr <- Sign? term (AddOp term^Err_086)* term <- factor (MultOp factor^Err_087)* factor <- NOT* (funcCall / var / unsignedConst / setConstructor / LPar expr RPar) unsignedConst <- UNumber / String / Id / NIL funcCall <- Id params setConstructor <- LBrack (memberDesignator (Comma memberDesignator^Err_088 / !RBrack %{Err_089} .)* / !RBrack %{Err_090} .)? RBrack^Err_091 memberDesignator <- expr (DotDot expr^Err_092 / !(RBrack / Comma) %{Err_093} .)? AddOp <- '+' / '-' / OR Assign <- ':=' Dot <- '.' DotDot <- '..' CloseComment <- '*)' / '}' Colon <- ':' Comma <- ',' COMMENT <- OpenComment (!CloseComment .)* CloseComment Eq <- '=' BodyId <- [a-zA-Z0-9] Id <- !Reserved [a-zA-Z] [a-zA-Z0-9]* LBrack <- '[' LPar <- '(' MultOp <- '*' / '/' / DIV / MOD / AND OpenComment <- '(*' / '{' Pointer <- '^' RBrack <- ']' RelOp <- '<=' / '=' / '<>' / '>=' / '>' / '<' / IN RPar <- ')' Semi <- ';' Sign <- '+' / '-' String <- "'" (!"'" .)* "'" UInt <- [0-9]+ UNumber <- UReal / UInt UReal <- [0-9]+ ('.' [0-9]+ ([Ee] ('+' / '-') [0-9]+)? / [Ee] ('+' / '-') [0-9]+) Reserved <- AND / ARRAY / BEGIN / CONST / CASE / DIV / DO / DOWNTO / ELSE / END / FILE / FOR / FUNCTION / GOTO / IF / IN / LABEL / MOD / NIL / NOT / OF / OR / PACKED / PROCEDURE / PROGRAM / RECORD / REPEAT / SET / THEN / TO / TYPE / UNTIL / VAR / WHILE / WITH AND <- [Aa] [Nn] [Dd] !BodyId ARRAY <- [Aa] [Rr] [Rr] [Aa] [Yy] !BodyId BEGIN <- [Bb] [Ee] [Gg] [Ii] [Nn] !BodyId CASE <- [Cc] [Aa] [Ss] [Ee] !BodyId CONST <- [Cc] [Oo] [Nn] [Ss] [Tt] !BodyId DIV <- [Dd] [Ii] [Vv] !BodyId DO <- [Dd] [Oo] !BodyId DOWNTO <- [Dd] [Oo] [Ww] [Nn] [Tt] [Oo] !BodyId ELSE <- [Ee] [Ll] [Ss] [Ee] !BodyId END <- [Ee] [Nn] [Dd] !BodyId FILE <- [Ff] [Ii] [Ll] [Ee] !BodyId FOR <- [Ff] [Oo] [Rr] !BodyId FUNCTION <- [Ff] [Uu] [Nn] [Cc] [Tt] [Ii] [Oo] [Nn] !BodyId GOTO <- [Gg] [Oo] [Tt] [Oo] !BodyId IF <- [Ii] [Ff] !BodyId IN <- [Ii] [Nn] !BodyId LABEL <- [Ll] [Aa] [Bb] [Ee] [Ll] !BodyId MOD <- [Mm] [Oo] [Dd] !BodyId NIL <- [Nn] [Ii] [Ll] !BodyId NOT <- [Nn] [Oo] [Tt] !BodyId OF <- [Oo] [Ff] !BodyId OR <- [Oo] [Rr] !BodyId PACKED <- [Pp] [Aa] [Cc] [Kk] [Ee] [Dd] !BodyId PROCEDURE <- [Pp] [Rr] [Oo] [Cc] [Ee] [Dd] [Uu] [Rr] [Ee] !BodyId PROGRAM <- [Pp] [Rr] [Oo] [Gg] [Rr] [Aa] [Mm] !BodyId RECORD <- [Rr] [Ee] [Cc] [Oo] [Rr] [Dd] !BodyId REPEAT <- [Rr] [Ee] [Pp] [Ee] [Aa] [Tt] !BodyId SET <- [Ss] [Ee] [Tt] !BodyId THEN <- [Tt] [Hh] [Ee] [Nn] !BodyId TO <- [Tt] [Oo] !BodyId TYPE <- [Tt] [Yy] [Pp] [Ee] !BodyId UNTIL <- [Uu] [Nn] [Tt] [Ii] [Ll] !BodyId VAR <- [Vv] [Aa] [Rr] !BodyId WHILE <- [Ww] [Hh] [Ii] [Ll] [Ee] !BodyId WITH <- [Ww] [Ii] [Tt] [Hh] !BodyId SPACE <- [ ] / COMMENT SKIP <- ([ ] / COMMENT)* ]] local g = m.match(g) local p = coder.makeg(g, 'ast') local dir = util.getPath(arg[0]) util.testYes(dir .. '/test/yes/', 'pas', p) util.testNo(dir .. '/test/no/', 'pas', p)
TOOL.Category = "Harbor" TOOL.Name = "Ship Designator" cleanup.Register( "nocollide" ) function TOOL:LeftClick( trace ) if ( !IsValid( trace.Entity ) ) then return end if ( trace.Entity:IsPlayer() ) then return end -- If there's no physics object then we can't constraint it! --if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end if(CLIENT) then return false end if(trace.Entity:IsValid()) then local mass = 0 for _, ent in pairs( constraint.GetAllConstrainedEntities( trace.Entity ) ) do local const = ent:GetPhysicsObject() if(const!=nil)then mass = mass + const:GetVolume() end end local classification = nil if(mass<10000000) then classification = "Speed Boat" elseif(mass<30000000)then classification = "Boat" elseif(mass>30000000)then classification = "Tanker or Warship" end print(mass) local ply = self:GetOwner() ply:PrintMessage( HUD_PRINTTALK,"-----------------------------------------------------") ply:PrintMessage( HUD_PRINTTALK,"WARNING: This tool is a rough estimate only. If you disagree with the clasification please ask for an admin.") ply:PrintMessage( HUD_PRINTTALK,"CLASSIFICATION: " .. classification) ply:PrintMessage( HUD_PRINTTALK,"Please put the corresponding color onto a flag, keeping the main body of your ship your team color.") ply:PrintMessage( HUD_PRINTTALK,"Submarines, planes, and blimps cannot be decided by this tool. Make something that looks the part then ask an admin.") ply:PrintMessage( HUD_PRINTTALK,"ColorTable: ") ply:PrintMessage( HUD_PRINTTALK,"SpeedBoat = Green") ply:PrintMessage( HUD_PRINTTALK,"Boat = Turqiouse") ply:PrintMessage( HUD_PRINTTALK,"Tanker = Yellow") ply:PrintMessage( HUD_PRINTTALK,"Warship = Black") ply:PrintMessage( HUD_PRINTTALK,"-----------------------------------------------------") end return true end
sampleInfo = { CodeName="LDS", ShortName="LDS", LongName="Low Discrepancy Sequences", Description="Low discrepancy sequences", Functions= { { name = "NRooks", progressive = false, randomized = true, cache = false }, { name = "Sobol", progressive = true, randomized = false, cache = false }, { name = "Halton_2_3_Zero", progressive = true, randomized = false, cache = false }, { name = "Halton_2_3", progressive = true, randomized = false, cache = false }, { name = "Halton_5_7", progressive = true, randomized = false, cache = false }, { name = "Halton_13_9", progressive = true, randomized = false, cache = false }, }, }
ardour { ["type"] = "EditorHook", name = "Check if file exists", author = "M. Schott", description = "Import midi file when it exists", } function signals () return LuaSignal.Set():add ({[LuaSignal.LuaTimerDS] = true}) end function factory () -- setup filesystem vars local home_dir = os.getenv ( "HOME" ); local dir_path = ARDOUR.LuaAPI.build_filename(home_dir, "ardour_electron") local melody_file = ARDOUR.LuaAPI.build_filename(dir_path, "melody.mid") local chords_file = ARDOUR.LuaAPI.build_filename(dir_path, "chordsNew.mid") -- midi import function import_midi(_file) local pos = 0 local file = C.StringVector() file:push_back(_file) Editor:do_import (file, Editing.ImportDistinctFiles, Editing.ImportAsTrack, ARDOUR.SrcQuality.SrcBest, ARDOUR.MidiTrackNameSource.SMFTrackName, ARDOUR.MidiTempoMapDisposition.SMFTempoIgnore, pos, ARDOUR.PluginInfo()) local track_no = Session:get_tracks():size() local route = Session:get_remote_nth_route(track_no-1) local new = ARDOUR.LuaAPI.new_plugin(Session, "http://gareus.org/oss/lv2/gmsynth", ARDOUR.PluginType.LV2, ""); route:add_processor_by_index (new, 0, nil, true) -- old = nil new = nil -- explicitly drop references (unless they're local vars) end -- file and path check function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end return function (signal, ref, ...) if file_exists(melody_file) then import_midi(melody_file) -- delete midi file when loaded in session, check for os (substr '/' for unix like os) if (os.getenv( "HOME" ):sub(0,1) == '/') then os.execute("rm " .. melody_file) else os.execute("del " .. melody_file) end end if file_exists(chords_file) then import_midi(chords_file) -- delete midi file when loaded in session, check for os (substr '/' for unix like os) if (os.getenv( "HOME" ):sub(0,1) == '/') then os.execute("rm " .. chords_file) else os.execute("del " .. chords_file) end end end end
-- -- Created by IntelliJ IDEA. -- User: gerry -- Date: 15/02/2017 -- Time: 20:10 -- To change this template use File | Settings | File Templates. -- local setmetatable = setmetatable local ngx = ngx local gw_conf = require "trustbuilder-gateway.configuration" local ngx_escape_uri = ngx.escape_uri local conf,conf_err = gw_conf:new() if not conf then ngx.log(ngx.ERR,conf_err) ngx.exit(500) end local function returnRedirectStatus() if ngx.req.get_headers()["X-Requested-With"] then return 409 else return ngx.HTTP_SEE_OTHER end end local function construct_www_authenticate_header(errorCode) if errorCode then ngx.header["WWW-Authenticate"] = 'Bearer realm="' .. ngx.var.server_name .. '", error=\"' .. errorCode .. '\"' end end local ResponseGenerator = {} ResponseGenerator.__index = ResponseGenerator setmetatable(ResponseGenerator, { __call = function (cls, ...) return cls.new(...) end, }) ResponseGenerator.httpAuthRequired = function(errorCode) construct_www_authenticate_header(errorCode) ngx.exit(ngx.HTTP_UNAUTHORIZED) end ResponseGenerator.httpAccessDenied = function(errorCode) construct_www_authenticate_header(errorCode) ngx.exit(403) end ResponseGenerator.httpBadRequest = function(errorCode) construct_www_authenticate_header(errorCode) ngx.exit(400) end ResponseGenerator.webAppRedirectToLogin = function(operation,principal,extravars) local login_url = conf.login_url ngx.log(ngx.DEBUG, "Redirect to " .. login_url .. " with operation " .. operation) ngx.header["Location"] = login_url .. "?operation=".. operation .. "&ref=" .. ngx_escape_uri(ngx.var.request_uri) if principal then ngx.header["Location"] = ngx.header["Location"] .. "&principal=" .. ngx_escape_uri(principal) end -- Set extra keys if present if extravars then for key,value in pairs(extravars) do ngx.header["Location"] = ngx.header["Location"] .. "&" .. key .. "=" .. value end end ngx.exit(returnRedirectStatus()) end ResponseGenerator.webAccessDenied = function(extravars) local vars = extravars or {} vars.reason = "Deny" ResponseGenerator.webAppRedirectToLogin("error", nil, vars) end return ResponseGenerator
-- credit to atom0s for help with decompiling -- Decompiled using luadec 2.2 rev: for Lua 5.1 from https://github.com/viruscamp/luadec return { Const = { RandomTypeCount = { { 1, 1 }, { 0, 0 }, { 3, 4 }, }, SkipCost = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }, TaskTypeCommon = 4, TaskTypeDepth = 2, TaskTypeLeisure = 3, TaskTypeWelfare = 1, }, QuestionCfg = { { Answer = 2, Id = 1, Option = { "Chicken Chop Rice", "Katsudon", "Omurice", "Sushi" }, Title = "What kind of food does Izuku Midoriya like?", }, { Answer = 1, Id = 2, Option = { "Spicy food", "Sour food", "Salty food", "Sweet Food" }, Title = "What's Katsuki Bakugo's favorite food?", }, { Answer = 3, Id = 3, Option = { "Ramen", "Instant Noodles", "Soba Noodles", "Udon" }, Title = "What kind of food does Shoto Todoroki like?", }, { Answer = 3, Id = 4, Option = { "Department of Heroes", "Department of Management", "Department of Battle", "Department of Support" }, Title = "Which of the following is not a subject studied at U.A. High?", }, { Answer = 3, Id = 5, Option = { "All Might", "Endeavor", "Mt. Lady", "Best Jeanist" }, Title = "Which of the following Pro Heroes didn't graduate from U.A. High?", }, { Answer = 1, Id = 6, Option = { "1 time(s) every 1 year(s)", "1 time(s) every 1 month(s)", "1 time(s) every 3 month(s)", "Twice a Year", }, Title = "How often is the U.A. High Sports Festival held?", }, { Answer = 2, Id = 7, Option = { "Qingzhong City", "Qingqing City", "Hosu City", "Tatooin City" }, Title = "Where was the first baby with a Quirk born?", }, { Answer = 1, Id = 8, Option = { "All Might", "Endeavor", "Naomasa Tsukauchi", "Nezu" }, Title = "Who's known as the Symbol of Peace?", }, { Answer = 2, Id = 9, Option = { "Fluoroscopy", "Homing", "Bullet Crafting", "Deadeye" }, Title = "What's Snipe's Quirk?", }, { Answer = 1, Id = 10, Option = { "Directional Loudspeaker", "Walkman", "Loud speaker", "Heavy Armor" }, Title = "What's the device Present Mic wears around his neck?", }, { Answer = 2, Id = 11, Option = { "Midnight", "Present Mic", "Principal Nezu", "Ectoplasm" }, Title = "During the U.A. High Sports Festival, who is the host partner with the Eraser Head?", }, { Answer = 1, Id = 12, Option = { "Eraser Head", "Red Eye", "Erasure Hero", "Bandage Ninja" }, Title = "What's Shota Aizawa's hero name?", }, { Answer = 2, Id = 13, Option = { "Midnight", "Ectoplasm", "Cementos", "Kamui Woods" }, Title = "Which of the following Pro Heroes can create Clones?", }, { Answer = 4, Id = 14, Option = { "Izuku Midoriya", "Shoto Todoroki", "Fumikage Tokoyami", "Katsuki Bakugo" }, Title = "Who won first place in the U.A. High Sports Festival?", }, { Answer = 3, Id = 15, Option = { "Izuku Midoriya", "Shoto Todoroki", "Katsuki Bakugo", "Tenya Iida" }, Title = "Who wasn't involved in battles during the Hero Killer Incident?", }, { Answer = 1, Id = 16, Option = { "Eijiro Kirishima", "Minoru Mineta", "Tsuyu Asui", "Koji Koda" }, Title = "Which student didn't pass the 1st-semester final exams?", }, { Answer = 1, Id = 17, Option = { "Nana Shimura", "Toshinori Yagi", "Izuku Midoriya", "Gran Torino" }, Title = "Who's the 7th user of One For All?", }, { Answer = 3, Id = 18, Option = { "Rank 4", "Rank 5", "Rank 6", "Rank 7" }, Title = "How many girls are there in U.A. High Class 1-A?", }, { Answer = 3, Id = 19, Option = { "Smartness", "Leadership", "Frog", "Loveliness" }, Title = "What's Tsuyu Asui's Quirk?", }, { Answer = 3, Id = 20, Option = { "2 Departments", "3 Departments", "4 Departments", "5 Departments" }, Title = "How many departments does U.A. High have, currently?", }, }, RuleCfg = { { Idx = 1, TypeList = { 4 } }, { Idx = 2, TypeList = { 1, 3, 4 } }, { Idx = 3, TypeList = { 1, 3, 4 } }, { Idx = 4, TypeList = { 1, 3, 4 } }, { Idx = 5, TypeList = { 1, 3, 4 } }, { Idx = 6, TypeList = { 1, 3, 4 } }, { Idx = 7, TypeList = { 1, 3, 4 } }, { Idx = 8, TypeList = { 1, 3, 4 } }, { Idx = 9, TypeList = { 1, 3, 4 } }, { Idx = 10, TypeList = { 1, 3, 4 } }, }, TaskCfg = { { Desc = "Haha, you've done well today. As the Symbol of Peace, I have a gift for you!", Id = 1, Name = "All Might's Gift", Reward = { { 1001002, 20 }, { 1012110, 1 }, { 1001001, 5000 }, }, Type = 1, }, { Desc = "The students did a great job. Keep up the good work!", Id = 2, Name = "Principal's Reward", Reward = { { 1001002, 20 }, { 1012110, 1 }, { 1001008, 3000 }, }, Type = 1, }, { Desc = "Well, I've collected some great data, thank you!", Id = 3, Name = "Mei Hatsume's Gift", Reward = { { 1001002, 20 }, { 1012110, 1 }, { 1001009, 3000 }, }, Type = 1, }, { Desc = "I've learned a lot since I met you. Thank you for your guidance!", Id = 4, Name = "Izuku Midoriya's Gift", Reward = { { 1001002, 20 }, { 1012110, 1 }, { 1001010, 3000 }, }, Type = 1, }, { Id = 5, Name = "Fun Quiz", Param = { 1 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 6, Name = "Fun Quiz", Param = { 2 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 7, Name = "Fun Quiz", Param = { 3 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 8, Name = "Fun Quiz", Param = { 4 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 9, Name = "Fun Quiz", Param = { 5 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 10, Name = "Fun Quiz", Param = { 6 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 11, Name = "Fun Quiz", Param = { 7 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 12, Name = "Fun Quiz", Param = { 8 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 13, Name = "Fun Quiz", Param = { 9 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 14, Name = "Fun Quiz", Param = { 10 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 15, Name = "Fun Quiz", Param = { 11 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 16, Name = "Fun Quiz", Param = { 12 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 17, Name = "Fun Quiz", Param = { 13 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 18, Name = "Fun Quiz", Param = { 14 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 19, Name = "Fun Quiz", Param = { 15 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 20, Name = "Fun Quiz", Param = { 16 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 21, Name = "Fun Quiz", Param = { 17 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 22, Name = "Fun Quiz", Param = { 18 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 23, Name = "Fun Quiz", Param = { 19 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Id = 24, Name = "Fun Quiz", Param = { 20 }, Reward = { { 1001001, 2000 }, }, ServerApiName = "τ¡öΘóÿ", ToValue = 1, Type = 3, }, { Desc = "Complete 1 Peacekeeping stages in Normal Mode.", GotoName = "σî║σƒƒΣ║ïΣ╗╢", Id = 25, Name = "Peacekeeping", Reward = { { 1001008, 500 }, { 1001001, 2000 }, }, ServerApiName = "µ▓╗σ«ëΣ║ïΣ╗╢µ¼íµò░", ToValue = 1, Type = 4, }, { Desc = "Complete 2 Peacekeeping stages in Normal Mode.", GotoName = "σî║σƒƒΣ║ïΣ╗╢", Id = 26, Name = "Peacekeeping", Reward = { { 1001008, 1000 }, { 1001001, 2000 }, }, ServerApiName = "µ▓╗σ«ëΣ║ïΣ╗╢µ¼íµò░", ToValue = 2, Type = 4, }, { Desc = "Complete 3 Peacekeeping stages in Normal Mode.", GotoName = "σî║σƒƒΣ║ïΣ╗╢", Id = 27, Name = "Peacekeeping", Reward = { { 1001008, 1500 }, { 1001001, 2000 }, }, ServerApiName = "µ▓╗σ«ëΣ║ïΣ╗╢µ¼íµò░", ToValue = 3, Type = 4, }, { Desc = "Complete 1 Peacekeeping stages in Night Ops Mode.", FuncOpen = 15, GotoName = "σî║σƒƒΣ║ïΣ╗╢σñ£µêÿ", Id = 28, Name = "Night Ops", Reward = { { 1001009, 500 }, { 1001001, 2000 }, }, ServerApiName = "µ▓╗σ«ëσñ£µêÿµ¼íµò░", ToValue = 1, Type = 4, }, { Desc = "Complete 2 Peacekeeping stages in Night Ops Mode.", FuncOpen = 15, GotoName = "σî║σƒƒΣ║ïΣ╗╢σñ£µêÿ", Id = 29, Name = "Night Ops", Reward = { { 1001009, 1000 }, { 1001001, 2000 }, }, ServerApiName = "µ▓╗σ«ëσñ£µêÿµ¼íµò░", ToValue = 2, Type = 4, }, { Desc = "Complete 3 Peacekeeping stages in Night Ops Mode.", FuncOpen = 15, GotoName = "σî║σƒƒΣ║ïΣ╗╢σñ£µêÿ", Id = 30, Name = "Night Ops", Reward = { { 1001009, 1500 }, { 1001001, 2000 }, }, ServerApiName = "µ▓╗σ«ëσñ£µêÿµ¼íµò░", ToValue = 3, Type = 4, }, { Desc = "Complete Agency Assessments Floor 1 or above.", FuncOpen = 12, GotoName = "Σ║ïσèíµë\128ΦÇâµá╕", Id = 31, Name = "Agency Assessment", Param = { 2, 1, 100 }, Reward = { { 1001010, 500 }, { 1001001, 2000 }, }, ServerApiName = "ΘÇÜσà│σñºτºÿσóâµ¼íµò\176", ToValue = 1, Type = 4, }, { Desc = "Complete Agency Assessments Floor 2 or above.", FuncOpen = 12, GotoName = "Σ║ïσèíµë\128ΦÇâµá╕", Id = 32, Name = "Agency Assessment", Param = { 2, 2, 100 }, Reward = { { 1001010, 1000 }, { 1001001, 2000 }, }, ServerApiName = "ΘÇÜσà│σñºτºÿσóâµ¼íµò\176", ToValue = 1, Type = 4, }, { Desc = "Complete Agency Assessments Floor 3 or above.", FuncOpen = 12, GotoName = "Σ║ïσèíµë\128ΦÇâµá╕", Id = 33, Name = "Agency Assessment", Param = { 2, 3, 100 }, Reward = { { 1001008, 1000 }, { 1001001, 2000 }, }, ServerApiName = "ΘÇÜσà│σñºτºÿσóâµ¼íµò\176", ToValue = 1, Type = 4, }, { Desc = "Complete Agency Assessments Floor 4 or above.", FuncOpen = 12, GotoName = "Σ║ïσèíµë\128ΦÇâµá╕", Id = 34, Name = "Agency Assessment", Param = { 2, 4, 100 }, Reward = { { 1001010, 1500 }, { 1001001, 2000 }, }, ServerApiName = "ΘÇÜσà│σñºτºÿσóâµ¼íµò\176", ToValue = 1, Type = 4, }, { Desc = "Complete Agency Assessments Floor 5 or above.", FuncOpen = 12, GotoName = "Σ║ïσèíµë\128ΦÇâµá╕", Id = 35, Name = "Agency Assessment", Param = { 2, 5, 100 }, Reward = { { 1001008, 1500 }, { 1001001, 2000 }, }, ServerApiName = "ΘÇÜσà│σñºτºÿσóâµ¼íµò\176", ToValue = 1, Type = 4, }, { Desc = "Participate in 1 Emergency Incidents.", FuncOpen = 31, GotoName = "τ┤ºµ\128ÑΣ║ïΣ╗\182", Id = 36, Name = "Emergency Incidents", Reward = { { 1001008, 500 }, { 1001001, 2000 }, }, ServerApiName = "σ«îµêÉτ┤ºµ\128ÑΣ║ïΣ╗╢µ¼íµò\176", ToValue = 1, Type = 4, }, { Desc = "Participate in 2 Emergency Incidents.", FuncOpen = 31, GotoName = "τ┤ºµ\128ÑΣ║ïΣ╗\182", Id = 37, Name = "Emergency Incidents", Reward = { { 1001008, 1000 }, { 1001001, 2000 }, }, ServerApiName = "σ«îµêÉτ┤ºµ\128ÑΣ║ïΣ╗╢µ¼íµò\176", ToValue = 2, Type = 4, }, { Desc = "Participate in 1 Arena Battles.", FuncOpen = 27, GotoName = "τ½₧µèÇσ£\186", Id = 38, Name = "Arena", Reward = { { 1001009, 500 }, { 1001001, 2000 }, }, ServerApiName = "τ½₧µèÇσ£║σÅéσèáµ¼íµò\176", ToValue = 1, Type = 4, }, { Desc = "Participate in 2 Arena Battles.", FuncOpen = 27, GotoName = "τ½₧µèÇσ£\186", Id = 39, Name = "Arena", Reward = { { 1001009, 1000 }, { 1001001, 2000 }, }, ServerApiName = "τ½₧µèÇσ£║σÅéσèáµ¼íµò\176", ToValue = 2, Type = 4, }, { Desc = "Win a battle in the Arena.", FuncOpen = 27, GotoName = "τ½₧µèÇσ£\186", Id = 40, Name = "Arena", Reward = { { 1001009, 1500 }, { 1001001, 2000 }, }, ServerApiName = "τ½₧µèÇσ£║Φâ£σê⌐µ¼íµò\176", ToValue = 1, Type = 4, }, { Desc = "Complete Supply - Cafeteria 1 times.", FuncOpen = 78, GotoName = "ΦíÑτ╗Ö", Id = 41, Name = "Supplies", Param = { 1 }, Reward = { { 1001008, 700 }, { 1001001, 2000 }, }, ServerApiName = "Φ╡äµ║ɵ£¼Θ\128Üσà│", ToValue = 1, Type = 4, }, { Desc = "Complete Supply - Cafeteria 2 times.", FuncOpen = 78, GotoName = "ΦíÑτ╗Ö", Id = 42, Name = "Supplies", Param = { 1 }, Reward = { { 1001008, 1300 }, { 1001001, 2000 }, }, ServerApiName = "Φ╡äµ║ɵ£¼Θ\128Üσà│", ToValue = 2, Type = 4, }, { Desc = "Complete Supply - Bounty 1 times.", FuncOpen = 77, GotoName = "ΦíÑτ╗Ö", Id = 43, Name = "Supplies", Param = { 2 }, Reward = { { 1001009, 700 }, { 1001001, 2000 }, }, ServerApiName = "Φ╡äµ║ɵ£¼Θ\128Üσà│", ToValue = 1, Type = 4, }, { Desc = "Complete Supply - Bounty 2 times.", FuncOpen = 77, GotoName = "ΦíÑτ╗Ö", Id = 44, Name = "Supplies", Param = { 2 }, Reward = { { 1001009, 1300 }, { 1001001, 2000 }, }, ServerApiName = "Φ╡äµ║ɵ£¼Θ\128Üσà│", ToValue = 2, Type = 4, }, }, Type2Id = { { 1, 2, 3, 4 }, [3] = { 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 }, [4] = { 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44 }, }, }
return {'asamoah','asante'}
-- NoIndex: true -- Adds creation and property data to the GUI element classes, -- as well as GB-specific methods for selecting, deleting, duplicating, dragging, etc --[[ {prop = "", caption = "", class = ""}, prop Target element's property caption Displayed property name class Property type recreate = true Will :delete and GUI.New(...) the target element after applying a value. Necessary for some classes (Slider) that do a lot of internal work with the created values and can't be easily updated. ]]-- local classes = {} -- Frequently-used properties so I only have to type them out once local props = { name = {prop = "name", caption = "Name", class = "Name"}, z = {prop = "z", caption = "Z", class = "Coord_Z"}, x = {prop = "x", caption = "X", class = "Number"}, y = {prop = "y", caption = "Y", class = "Coord_Y"}, w = {prop = "w", caption = "W", class = "Number"}, h = {prop = "h", caption = "H", class = "Number"}, caption = {prop = "caption", caption = "Caption", class = "String"}, font = {prop = "font", caption = "Font", class = "Font"}, font_a = {prop = "font_a", caption = "Cap. Font", class = "Font"}, font_b = {prop = "font_b", caption = "Text Font", class = "Font"}, col_txt = {prop = "col_txt", caption = "Text Color", class = "Color"}, col_fill = {prop = "col_fill", caption = "Fill Color", class = "Color"}, pad = {prop = "pad", caption = "Padding", class = "Number"}, shadow = {prop = "shadow", caption = "Shadow", class = "Boolean"}, } classes.Button = { defaults = {48, 24, "Button"}, creation = {"w", "h", "caption", "", "font", "col_txt", "col_fill"}, properties = { props.name, "", props.z, props.x, props.y, props.w, props.h, "", props.caption, props.font, props.col_txt, props.col_fill, } } classes.Checklist = { defaults = {96, 192, "Checklist", "Option 1,Option 2,Option 3,Option 4"}, creation = {"w", "h", "caption", "optarray", "dir", "pad", "", "font_a", "font_b", "col_txt", "col_fill", "bg", "frame", "shadow", "opt_size", "swap"}, properties = { "1", props.name, "", props.z, props.x, props.y, props.w, props.h, "", props.caption, "", {prop = "optarray", caption = "Options", class = "Table"}, {prop = "dir", caption = "Direction", class = "Direction"}, props.pad, "2", props.font_a, props.font_b, props.col_txt, props.col_fill, {prop = "bg", caption = "Text BG", class = "Color"}, "", {prop = "frame", caption = "Frame", class = "Boolean"}, props.shadow, {prop = "swap", caption = "Swap", class = "Boolean"}, "", {prop = "opt_size", caption = "Opt. Size", class = "Number"}, } } classes.Frame = { defaults = {256, 128}, creation = {"w", "h", "shadow", "fill", "color", "round", "", "text", "txt_indent", "txt_pad", "pad", "bg", "font", "col_txt"}, properties = { "1", props.name, "", props.z, props.x, props.y, props.w, props.h, "", props.shadow, {prop = "fill", caption = "Fill", class = "Boolean"}, {prop = "color", caption = "Frame Color", class = "Color"}, {prop = "bg", caption = "BG Color", class = "Color"}, {prop = "round", caption = "Round", class = "Number"}, "2", {prop = "text", caption = "Text", class = "String"}, {prop = "txt_indent", caption = "Para. Indent", class = "Number"}, {prop = "txt_pad", caption = "Wrap Indent", class = "Number"}, props.pad, props.font, props.col_txt, } } classes.Knob = { defaults = {40, "Knob", 0, 10, 5, 1, true}, creation = {"w", "caption", "min", "max", "default", "inc", "vals", "", "bg", "font_a", "font_b", "col_txt", "col_head", "col_body", "cap_x", "cap_y"}, properties = { "1", props.name, "", props.z, props.x, props.y, props.w, "", props.caption, "", {prop = "min", caption = "Min.", class = "Number", recreate = true}, {prop = "max", caption = "Max.", class = "Number", recreate = true}, {prop = "default", caption = "Default", class = "Number", recreate = true}, {prop = "inc", caption = "Increment", class = "Number", recreate = true}, {prop = "vals", caption = "Show Values", class = "Boolean"}, "2", props.font_a, props.font_b, props.col_txt, {prop = "col_head", caption = "Head", class = "Color"}, {prop = "col_body", caption = "Body", class = "Color"}, "", {prop = "cap_x", caption = "Cap. Offset X", class = "Number"}, {prop = "cap_y", caption = "Cap. Offset Y", class = "Number"}, } } classes.Label = { defaults = {"Label"}, creation = {"caption", "", "shadow", "font", "color", "bg"}, properties = { props.name, "", props.z, props.x, props.y, "", "", "", props.caption, props.font, {prop = "color", caption = "Text Color", class = "Color"}, {prop = "bg", caption = "BG Color", class = "Color"}, props.shadow, } } classes.Listbox = { defaults = {192, 96, "Item 1,Item 2,Item 3,Item 4"}, creation = {"w", "h", "list", "multi", "caption", "pad", "", "cap_bg", "bg", "shadow", "color", "col_fill", "font_a", "font_b"}, properties = { "1", props.name, "", props.z, props.x, props.y, props.w, props.h, "", {prop = "list", caption = "List Items", class = "Table"}, {prop = "multi", caption = "Multi-select", class = "Boolean"}, "", props.caption, "2", props.font_a, {prop = "font_b", caption = "Text Font", class = "Font", recreate = true}, {prop = "color", caption = "Text Color", class = "Color"}, props.col_fill, {prop = "bg", caption = "List BG", class = "Color"}, {prop = "cap_bg", caption = "Caption BG", class = "Color"}, props.shadow, props.pad, } } classes.Menubar = { defaults = { { {title = "Menu 1", options = {}}, {title = "Menu 2", options = {}}, {title = "Menu 3", options = {}}, }, }, creation = {"menus", "w", "h", "pad", "", "font", "col_txt", "col_bg", "col_over"}, properties = { props.name, "", props.z, props.x, props.y, props.w, props.h, "", {prop = "menus", caption = "Menu Titles", class = "Menu_Titles", recreate = true}, "", {prop = "font", caption = "Text Font", class = "Font"}, props.col_txt, {prop = "col_bg", caption = "BG Color", class = "Color"}, {prop = "col_over", caption = "Hover Color", class = "Color"}, {prop = "fullwidth", caption = "Full Width", class = "Boolean", recreate = true}, } } classes.Menubox = { defaults = {128, 20, "Menubox", "!Option 1,#Option 2,>Folder,Option 3,Option 4,<Option 5,,Option 6"}, creation = {"w", "h", "caption", "optarray", "pad", "noarrow", "", "col_txt", "col_cap", "bg", "font_a", "font_b", "align", "retval"}, properties = { "1", props.name, "", props.z, props.x, props.y, props.w, props.h, "", props.caption, {prop = "optarray", caption = "Options", class = "Table"}, {prop = "retval", caption = "Default", class = "Number", recreate = true}, "2", props.font_a, props.font_b, {prop = "col_txt", caption = "Cap. Color", class = "Color"}, {prop = "col_cap", caption = "Text Color", class = "Color"}, {prop = "bg", caption = "BG Color", class = "Color"}, "", props.pad, {prop = "noarrow", caption = "Hide Arrow", class = "Boolean"}, {prop = "align", caption = "Align", class = "Number"}, } } classes.Radio = { defaults = {96, 192, "Checklist", "Option 1,Option 2,Option 3,Option 4"}, creation = {"w", "h", "caption", "optarray", "dir", "pad", "", "font_a", "font_b", "col_txt", "col_fill", "bg", "frame", "shadow", "opt_size", "swap"}, properties = { "1", props.name, "", props.z, props.x, props.y, props.w, props.h, "", props.caption, "", {prop = "optarray", caption = "Options", class = "Table"}, {prop = "dir", caption = "Direction", class = "Direction"}, "2", props.font_a, props.font_b, props.col_txt, props.col_fill, {prop = "bg", caption = "Text BG", class = "Color"}, "", {prop = "frame", caption = "Frame", class = "Boolean"}, props.shadow, {prop = "swap", caption = "Swap", class = "Boolean"}, "", {prop = "opt_size", caption = "Opt. Size", class = "Number"}, } } classes.Slider = { defaults = {96, "Slider", 0, 10, {5}}, creation = {"w", "caption", "min", "max", "defaults", "inc", "dir", "", "font_a", "font_b", "col_txt", "col_fill", "bg", "show_handles", "show_values", "cap_x", "cap_y"}, properties = { "1", props.name, "", props.z, props.x, props.y, props.w, "", "", props.caption, "", {prop = "min", caption = "Min.", class = "Number", recreate = true}, {prop = "max", caption = "Max.", class = "Number", recreate = true}, {prop = "defaults", caption = "Defaults", class = "Table", recreate = true}, {prop = "inc", caption = "Increment", class = "Number", recreate = true}, {prop = "dir", caption = "Direction", class = "Direction", recreate = true}, "2", props.font_a, {prop = "font_b", caption = "Val. Font", class = "Font"}, props.col_txt, props.col_fill, {prop = "bg", caption = "BG Color", class = "Color"}, "", {prop = "show_handles", caption = "Show Handles", class = "Boolean"}, {prop = "show_values", caption = "Show Values", class = "Boolean"}, "", {prop = "cap_x", caption = "Cap. Offset X", class = "Number"}, {prop = "cap_y", caption = "Cap. Offset Y", class = "Number"}, } } classes.Tabs = { defaults = {48, 20, "Tab 1,Tab 2,Tab 3"}, creation = {"tab_w", "tab_h", "optarray", "pad", "", "w", "bg", "col_txt", "col_tab_a", "col_tab_b", "font_a", "font_b"}, properties = { "1", props.name, "", props.z, props.x, props.y, {prop = "w", caption = "W", class = "Number", recreate = true}, "", props.caption, {prop = "optarray", caption = "Options", class = "Table", recreate = true}, {prop = "tab_w", caption = "Tab Width", class = "Number",}, {prop = "tab_h", caption = "Tab Height", class = "Number", recreate = true}, {prop = "pad", caption = "Tab Pad", class = "Number"}, "2", {prop = "font_a", caption = "Active Font", class = "Font"}, {prop = "font_b", caption = "Inact. Font", class = "Font"}, props.col_txt, {prop = "col_tab_a", caption = "Active Color", class = "Color"}, {prop = "col_tab_b", caption = "Inact. Color", class = "Color"}, {prop = "bg", caption = "BG Color", class = "Color"}, {prop = "fullwidth", caption = "Full Width", class = "Boolean", recreate = true}, } } classes.Textbox = { defaults = {96, 20, "Textbox"}, creation = {"w", "h", "caption", "pad", "", "font_a", "font_b", "cap_pos", "color", "bg", "shadow", "undo_limit"}, properties = { "1", props.name, "", props.z, props.x, props.y, props.w, props.h, "", props.caption, {prop = "cap_pos", caption = "Cap. Pos.", class = "Cap_Pos"}, "2", props.font_a, {prop = "font_b", caption = "Text Font", class = "MonoFont"}, {prop = "color", caption = "Text Color", class = "Color"}, {prop = "bg", caption = "Cap. BG", class = "Color"}, props.shadow, props.pad, "", {prop = "undo_limit", caption = "Undo States", class = "Number"}, } } classes.TextEditor = { defaults = {256, 192}, creation = {"w", "h", "text", "caption", "pad", "", "bg", "shadow", "color", "col_fill", "font_a", "font_b", "undo_limit"}, properties = { "1", props.name, "", props.z, props.x, props.y, {prop = "w", caption = "W", class = "Number", recreate = true}, {prop = "h", caption = "H", class = "Number", recreate = true}, "", props.caption, "2", props.font_a, {prop = "font_b", caption = "Text Font", class = "MonoFont"}, {prop = "color", caption = "Text Color", class = "Color"}, props.col_fill, {prop = "cap_bg", caption = "Cap. BG", class = "Color"}, {prop = "bg", caption = "Background", class = "Color"}, "", props.shadow, props.pad, "", {prop = "undo_limit", caption = "Undo States", class = "Number"}, } } -- Store the element data with the element classes, keep a list of classes we can return local ret_classes = {} for class, data in pairs(classes) do GUI[class].GB = data ret_classes[class] = true end return classes
-- Code created by Kwik - Copyright: kwiksher.com {{year}} -- Version: {{vers}} -- Project: {{ProjName}} -- local _M = {} -- local _K = require "Application" -- {{#ultimate}} local imageWidth = {{elW}}/4 local imageHeight = {{elH}} local mX, mY = _K.ultimatePosition({{mX}}, {{mY}} + {{eloffset}}, "{{align}}" ) {{#randX}} local randXStart = _K.ultimatePosition({{randXStart}}) local randXEnd = _K.ultimatePosition({{randXEnd}}) {{/randX}} {{#randY}} local dummy, randYStart = _K.ultimatePosition(0, {{randYStart}}) local dummy, randYEnd = _K.ultimatePosition(0, {{randYEnd}}) {{/randY}} local elFontSize = {{elFontSize}}/4 {{/ultimate}} {{^ultimate}} local imageWidth = {{elW}} local imageHeight = {{elH}} local mX, mY = _K.ultimatePosition({{mX}}, {{mY}} + {{eloffset}}, "{{align}}") {{#randX}} local randXStart = {{randXStart}} local randXEnd = {{randXEnd}} {{/randX}} {{#randY}} local randYStart = {{randYStart}} local randYEnd = {{randYEnd}} {{/randY}} local elFontSize = {{elFontSize}} {{/ultimate}} local oriAlpha = {{oriAlpha}} -- function _M:localVars(UI) {{#isTmplt}} mX, mY = _K.getModel("{{myLName}}", imagePath, UI.dummy) {{/isTmplt}} end -- function _M:localPos(UI) local sceneGroup = UI.scene.view local layer = UI.layer {{#globalVar}} local mVar = {{elVar}} {{/globalVar}} {{^globalVar}} local mVar = UI.{{elVar}} {{/globalVar}} {{#multLayers}} UI.tab{{um}}["{{dois}}"] = {mVar, imageWidth, imageHeight, mX, mY, oriAlpha, {{elFont}}, elFontSize, {{elFontColor}} } {{/multLayers}} {{^multLayers}} local options = { text = mVar, x = mX + imageWidth/2, y = mY, fontSize = elFontSize, font = {{elFont}}, align = "left" } layer.{{myLName}} = display.newText(options) if layer.{{myLName}} == nil then return end layer.{{myLName}}:setFillColor( {{elR}}, {{elG}}, {{elB}} ) layer.{{myLName}}.anchorX = 0.5 layer.{{myLName}}.anchorY = 0.25 _K.repositionAnchor(layer.{{myLName}},0.5,0); {{#randX}} layer.{{myLName}}.x = math.random( randXStart, randXEnd) {{/randX}} {{#randY}} layer.{{myLName}}.y = math.random( randYStart, {{randYEnd}}) {{/randY}} {{#scaleW}} layer.{{myLName}}.xScale = {{scaleW}} {{/scaleW}} {{#scaleH}} layer.{{myLName}}.yScale = {{scaleH}} {{/scaleH}} {{#rotate}} layer.{{myLName}}:rotate({{rotate}} {{/rotate}} layer.{{myLName}}.oriX = layer.{{myLName}}.x layer.{{myLName}}.oriY = layer.{{myLName}}.y layer.{{myLName}}.oriXs = layer.{{myLName}}.xScale layer.{{myLName}}.oriYs = layer.{{myLName}}.yScale layer.{{myLName}}.alpha = oriAlpha layer.{{myLName}}.oldAlpha = oriAlpha sceneGroup:insert( layer.{{myLName}}) sceneGroup.{{myLName}} = layer.{{myLName}} {{/multLayers}} end -- return _M
cflags{ '-Wall', '-Wpedantic', '-Wno-parentheses', '-I $dir', } lib('libpci.a', [[ lib/( init.c access.c generic.c dump.c names.c filter.c names-hash.c names-parse.c names-net.c names-cache.c names-hwdb.c params.c caps.c sysfs.c ) ]]) cc('common.c') exe('lspci', { 'lspci.c', 'ls-vpd.c', 'ls-caps.c', 'ls-caps-vendor.c', 'ls-ecaps.c', 'ls-kernel.c', 'ls-tree.c', 'ls-map.c', 'common.c.o', 'libpci.a', }) file('bin/lspci', '755', '$outdir/lspci') man({'$srcdir/lspci.man'}, '8') exe('setpci', { 'setpci.c', 'common.c.o', 'libpci.a', }) file('bin/setpci', '755', '$outdir/setpci') man({'$srcdir/setpci.man'}, '8') file('share/pci.ids', '644', '$srcdir/pci.ids') man({'$srcdir/pci.ids.man'}, '5') fetch 'git'
----------------------------------------------------------------------------------- local MAJOR, MINOR = "AgiDialogs", 5 local AgiDialogs, OldMinor = LibStub:NewLibrary(MAJOR, MINOR) if ( not AgiDialogs ) then return end -- No Upgrade needed. ----------------------------------------------------------------------------------- local AgiTimers = LibStub("AgiTimers") ----------------------------------------------------------------------------------- local shownDialogsMax = 4 local shownDialogsQueue = {} local shownDialogs = 0 local lastTempDialogName = nil local tmpDialogsI = 0 local function GetTmpDialogName() tmpDialogsI = tmpDialogsI + 1 return "AgiDialogs"..tmpDialogsI end local function DisplayLoop() if ( lastTempDialogName ) then local sp for i=1,shownDialogsMax do sp = getglobal("StaticPopup"..i) if ( sp and not sp._tmpName ) then sp._tmpName = lastTempDialogName sp:HookScript("OnHide", function(self) if ( self._tmpName ) then StaticPopupDialogs[self._tmpName] = nil self._tmpName = nil end shownDialogs = shownDialogs - 1 end) lastTempDialogName = nil return end end else if ( #shownDialogsQueue > 0 and shownDialogs < shownDialogsMax ) then local dialogData = tremove(shownDialogsQueue, 1) local dialogName = dialogData.dialogName or "" local dialogValues = dialogData.values or {} local dialogArg1 = dialogData.arg1 or nil local dialogArg2 = dialogData.arg2 or nil if ( StaticPopupDialogs[dialogName] == nil ) then return end local oriDialog = StaticPopupDialogs[dialogName] local tmpDialogName = GetTmpDialogName() StaticPopupDialogs[tmpDialogName] = {} local tmpDialog = StaticPopupDialogs[tmpDialogName] lastTempDialogName = tmpDialogName shownDialogs = shownDialogs + 1 for k,v in pairs(oriDialog) do tmpDialog[k] = v end for k,v in pairs(dialogValues) do tmpDialog[k] = v end StaticPopup_Show(tmpDialogName, dialogArg1, dialogArg2) end end end AgiTimers:SetInterval(DisplayLoop, 0.1) function AgiDialogs:Show(dialogName, values, arg1, arg2) shownDialogsQueue[#shownDialogsQueue+1] = { dialogName = dialogName, values = values, arg1 = arg1, arg2 = arg2, } end
aurum.carts = {} b.dofile("rail.lua") b.dofile("cart.lua") b.dofile("default_carts.lua")
require("utilfunctions") require("prototypes.item-groups") require("prototypes.parts") require("prototypes.fuel") require("prototypes.inserters.burner-inserter") require("prototypes.inserters.long-inserter") require("prototypes.inserters.fast-inserter") require("prototypes.inserters.stack-inserter") require("prototypes.inserters.filter-inserter") require("prototypes.inserters.stack-filter-inserter") require("prototypes.inserters.short-long-inserter") require("prototypes.inserters.long-short-inserter") require("prototypes.assembling-machines.assembling-machine-1") require("prototypes.assembling-machines.assembling-machine-2") require("prototypes.assembling-machines.assembling-machine-3") require("prototypes.assembling-machines.fuel-assembling-machine") require("prototypes.mining-drill-2") require("prototypes.assembling-machines.oil-refinery") require("prototypes.assembling-machines.chemical-plant") require("prototypes.pumpjack") require("prototypes.lab") require("prototypes.rocket-silo") require("prototypes.locomotive") require("prototypes.alternative-recipe") require("prototypes.electric-technology") require("prototypes.technology") require("prototypes.equipment.equipment") require("prototypes.equipment.energy") require("prototypes.equipment.armor")
local skynet = require "skynet" skynet.start(function() skynet.dispatch("lua", function(session, source, cmd, subcmd, ...) print("test dispatch", session, source, cmd, subcmd) end) end)
return { load="load.lua", doInitSDL=true }
local utils = require('util') local core = require('core') local client = require('rtsp/client') local RtspClient = client.RtspClient local rtspClient = nil local TAG = 'test_rtsp_client' local color = console.color ------------------------------------------------------------------------------- -- MockClientSocket local MockClientSocket = core.Emitter:extend() -- 模拟一个 RTSP 服务端 SDP 串 function MockClientSocket:getSdpString() local sb = utils.StringBuffer:new() sb:append("v=0\r\n") sb:append("o=- 1453439395764824 1 IN IP4 0.0.0.0\r\n") sb:append("s=MPEG Transport Stream, streamed by the Vision.lua Media Server\r\n") sb:append("i=hd.ts\r\n") sb:append("t=0 0\r\n") sb:append("a=type:broadcast\r\n") sb:append("a=control:*\r\n") sb:append("a=range:npt=0-\r\n") sb:append("m=video 0 RTP/AVP 33\r\n") sb:append("c=IN IP4 0.0.0.0\r\n") sb:append("b=AS:5000\r\n") sb:append("a=control:track1\r\n") return sb:toString() end -- 模拟一个 RTSP 服务端 function MockClientSocket:handleRequest(data) if (data:startsWith("OPTIONS")) then local message = "RTSP/1.0 200 OK\r\nCSeq: 1\r\n\r\n" self:writeResponse(message) elseif (data:startsWith("DESCRIBE")) then local message = "RTSP/1.0 200 OK\r\nCSeq: 2\r\nContent-Type: application/sdp\r\n" local sdpString = self:getSdpString() message = message .. "Content-Length: " .. (#sdpString) .. "\r\n" message = message .. "\r\n" .. sdpString self:writeResponse(message) elseif (data:startsWith("SETUP")) then local message = "RTSP/1.0 200 OK\r\nCSeq: 3\r\n\r\n" self:writeResponse(message) elseif (data:startsWith("PLAY")) then local message = "RTSP/1.0 200 OK\r\nCSeq: 4\r\n\r\n" self:writeResponse(message) elseif (data:startsWith("PAUSE")) then local message = "RTSP/1.0 200 OK\r\nCSeq: 5\r\n\r\n" self:writeResponse(message) elseif (data:startsWith("TEARDOWN")) then local message = "RTSP/1.0 200 OK\r\nCSeq: 6\r\n\r\n" self:writeResponse(message) end end function MockClientSocket:writeResponse(data) --console.log('MockClientSocket', 'writeResponse', data) rtspClient:handleData(data) end function MockClientSocket:write(data) setImmediate(function() print(color('boolean') .. data, color()) self:handleRequest(data) end) end function MockClientSocket:destroy() console.log('MockClientSocket', 'destroy') end ------------------------------------------------------------------------------- -- test_rtsp_client local function test_rtsp_client() rtspClient = RtspClient:new() rtspClient:on('close', function(err) print(TAG, 'close', err) end) rtspClient:on('error', function(err) print(TAG, 'error', err) end) local lastState = 0 local timeoutTimer = setTimeout(1000, function () console.log(TAG, "Client timeout! ") rtspClient:close() end) rtspClient:on('state', function(state) print(TAG, color('function') .. 'state = ' .. state, color()) if (state == client.STATE_PLAYING) then rtspClient:sendPAUSE() --rtspClient:sendTEARDOWN() elseif (state == client.STATE_READY) then if (lastState == client.STATE_PLAYING) then rtspClient:sendTEARDOWN() else print(TAG, 'mediaTracks: \n======') console.log(rtspClient.mediaTracks) print("") end elseif (state == client.STATE_INIT) then if (lastState > client.STATE_INIT) then clearTimeout(timeoutTimer) rtspClient:close() end end lastState = state end) local url = "rtsp://127.0.0.1/hd.ts" --local url = "rtsp://192.168.31.64/live.mp4" rtspClient.sdpString = "" rtspClient.urlString = url rtspClient.clientSocket = MockClientSocket:new() rtspClient:sendOPTIONS() end test_rtsp_client()
Sprite = {} -- this sprite just work if all animation sprites are on the same line function Sprite.new(image, start_x, start_y, width, height) local self = {} self.start_x = start_x self.start_y = start_y self.quad_width = width self.quad_height = height self.quad = {} self.image = image self.x_scala = 1 self.y_scala = 1 function self.new_quad() self.quad = love.graphics.newQuad(self.start_x, self.start_y, self.quad_width, self.quad_height, self.image:getDimensions()) end function self.draw(args) args.x = args.x or 1 args.y = args.y or 1 args.x, args.y = self.adjust_position(args.x, args.y) args.x_scala = args.x_scala or args.scala or 1 args.y_scala = args.y_scala or args.scala or 1 args.rot = args.rot or 0 -- PROBLEMS -- if args.x_scala ~= self.x_scala or args.y_scala ~= self.y_scala then -- self.x_scala = args.x_scala -- self.y_scala = args.y_scala -- self.quad_width = self.quad_width * self.x_scala -- self.quad_height = self.quad_height * self.y_scala -- self.start_x = self.start_x * self.x_scala -- self.start_y = self.start_y * self.y_scala -- self.new_quad() -- end love.graphics.draw(self.image, self.quad, args.x, args.y, args.rot, args.x_scala, args.y_scala) end function self.adjust_position(x, y) local image_width = self.quad_width local image_height = self.quad_height x = x - image_width/2 y = y - image_height/2 return x, y end self.new_quad() return self end
local math, string = math, string local wibox = require('wibox') local Container = require('sanity/util/container') local FontIcon = require('sanity/util/fonticon') local markup = require('lain.util.markup') local weather = require('lain.widget.weather') local display = require('sanity/util/display') local dstheme = require('dstheme') local awful = require('awful') local gears = require('gears') local fonticon = FontIcon {} local hi_color = colors.red local lo_color = colors.blue -- https://openweathermap.org/weather-conditions local icon_map = { ['01d'] = '\u{e30d}', ['01n'] = '\u{e32b}', ['02d'] = '\u{e302}', ['02n'] = '\u{e37e}', ['03d'] = '\u{e376}', ['03n'] = '\u{e377}', ['04d'] = '\u{e376}', ['04n'] = '\u{e377}', ['09d'] = '\u{e309}', ['09n'] = '\u{e334}', ['10d'] = '\u{e308}', ['10n'] = '\u{e333}', ['11d'] = '\u{e30f}', ['11n'] = '\u{e338}', ['13d'] = '\u{e30a}', ['13n'] = '\u{e335}', ['50d'] = '\u{e3ae}', ['50n'] = '\u{e35d}', } function temp(value, type) local t = string.format('%d°F', value) if type == 'high' then return markup.fg.color(hi_color, t) elseif type == 'low' then return markup.fg.color(lo_color, t) else return t end end local function show_weather() awful.spawn({'xdg-open', 'https://openweathermap.org/city/'..dstheme.weather_city}) end local lain_weather = weather { APPID = dstheme.weather_key, city_id = dstheme.weather_city, units = 'imperial', showpopup = 'off', settings = function() update_weather(weather_now, widget) end, } local weather_container = Container { widget = wibox.widget { layout = wibox.layout.fixed.horizontal, fonticon, lain_weather.widget, }, buttons = gears.table.join( awful.button({}, 1, show_weather), awful.button({}, 3, show_weather) ), } local bubble = display.bubble(weather_container, true) function update_weather(weather_now, widget) local current_temp = math.floor(weather_now['main']['temp']) local low_temp = math.floor(weather_now['main']['temp_min']) local high_temp = math.floor(weather_now['main']['temp_max']) local temp_feel = math.floor(weather_now["main"]["feels_like"]) local humidity = math.floor(weather_now['main']['humidity']) local icon_id = weather_now['weather'][1]['icon'] local description = weather_now['weather'][1]['description'] local wind_speed = weather_now['wind']['speed'] local fg_color = colors.white local bg_color = colors.background if weather_now['snow'] then fg_color = colors.background bg_color = colors.white elseif weather_now['rain'] then fg_color = colors.background bg_color = colors.blue end widget:set_markup(markup.fg.color(fg_color, temp(current_temp))) weather_container:set_markup( string.format( ' %d°F (%s/%s) \n %d°F feel \n %s mph wind \n %s%% humidity \n %s ', current_temp, temp(high_temp, 'high'), temp(low_temp, 'low'), temp_feel, wind_speed, humidity, description ) ) fonticon:update(icon_map[icon_id], fg_color) bubble.background_container.bg = bg_color end return bubble
-- http://lua-users.org/wiki/FileInputOutput -- Return true if file exists and is readable. function file_exists(path) local file = io.open(path, "rb") if file then file:close() end return file ~= nil end -- get all lines from a file, returns an empty -- list/table if the file does not exist function lines_from(file) if not file_exists(file) then return {} end lines = {} for line in io.lines(file) do lines[#lines + 1] = line end return lines end -- Levenshtein implementation from --https://github.com/kennyledet/Algorithm-Implementations/blob/master/Levenshtein_distance/Lua/Yonaba/levenshtein.lua function matrix(row,col) local m = {} for i = 1,row do m[i] = {} for j=1,col do m[i][j] = 0 end end return m end function levenshtein(strA,strB) local M = matrix(#strA+1,#strB+1) local i,j,cost local row,col = #M,#M[1] for i = 1,row do M[i][1] = i-1 end for j = 1,col do M[1][j] = j-1 end for i = 2,row do for j = 2,col do if (strA:sub(i-1,i-1) == strB:sub(j-1,j-1)) then cost = 0 else cost = 1 end M[i][j] = math.min(M[i-1][j]+1,M[i][j-1]+1,M[i-1][j-1]+cost) end end return M[row][col], M end -- Sorted pair iterator function spairs(t, sortFunction) local keys = {} for k in pairs(t) do table.insert(keys,k) end table.sort(keys, function(a,b) if sortFunction == nil then return t[a] < t[b] else return sortFunction(t,a,b) end end) return coroutine.wrap(function() for k,v in pairs(keys) do coroutine.yield(v,t[v]) end coroutine.yield(nil) end) end function map(t, f) local res = {} for k,v in pairs(t) do table.insert(res,f(v,k,t)) end return res end function maxBy(t,f) local maxVal local maxIndex = 0 for k,v in pairs(t) do local g if type(f) == 'function' then g = f(v) elseif type(f) == 'string' and v[f] ~= nil then g = v[f] else --identity g = v end if maxVal == nil or g > maxVal then maxVal = g maxIndex = k end end return t[maxIndex], maxIndex end function minBy(t,f) local minVal local minIndex = 0 for k,v in pairs(t) do local g if type(f) == 'function' then g = f(v) elseif type(f) == 'string' and v[f] ~= nil then g = v[f] else --identity g = v end if minVal == nil or g < minVal then minVal = g minIndex = k end end return t[minIndex], minIndex end function keyBy(t,f) local ret = {} for k,v in pairs(t) do local g if type(f) == 'function' then g = f(v) elseif type(g) == 'string' and v[f] ~= nil then g = v[f] else g = v end ret[g] = v end return ret end function sort(t,f) local res = {} for k,v in spairs(t,f) do table.insert(res,v) end return res end function groupBy(t,f) local res = {} for k,v in pairs(t) do local g if type(f) == 'function' then g = f(v) elseif type(f) == 'string' and v[f] ~= nil then g = v[f] else error('Invalid group parameter ['..f..']') end if res[g] == nil then res[g] = {} end table.insert(res[g],v) end return res end -- Curry and flaten from http://lua-users.org/wiki/CurriedLua function curry(func, num_args) num_args = num_args or debug.getinfo(func, "u").nparams if num_args < 2 then return func end local function helper(argtrace, n) if n < 1 then local foo = flatten(argtrace) return func(table.unpack(flatten(argtrace))) else return function (...) return helper({argtrace, ...}, n - select("#", ...)) end end end return helper({}, num_args) end function flatten(t) local ret = {} for _, v in ipairs(t) do if type(v) == 'table' then for _, fv in ipairs(flatten(v)) do ret[#ret + 1] = fv end else ret[#ret + 1] = v end end return ret end
local K, C, L = unpack(select(2, ...)) if C.Misc.MoveBlizzard ~= true then return end -- Lua API local _G = _G local type = type -- Lua Wow local IsAddOnLoaded = _G.IsAddOnLoaded -- Global variables that we don"t cache, list them here for the mikk"s Find Globals script -- GLOBALS: TradeSkillFrame, AchievementFrameHeader local MovableFrame = CreateFrame("Frame") -- Move some Blizzard frames K.Frames = { "AddonList", "AudioOptionsFrame", "BankFrame", "BonusRollFrame", "BonusRollLootWonFrame", "BonusRollMoneyWonFrame", "CharacterFrame", "DressUpFrame", "FriendsFrame", "GameMenuFrame", "GhostFrame", "GossipFrame", "GuildInviteFrame", "GuildRegistrarFrame", "HelpFrame", "InterfaceOptionsFrame", "ItemTextFrame", "LFDRoleCheckPopup", "LFGDungeonReadyDialog", "LFGDungeonReadyStatus", "LootFrame", "LossOfControlFrame", "MailFrame", "MerchantFrame", "OpenMailFrame", "PetitionFrame", "PetStableFrame", "PVEFrame", "PVPReadyDialog", "QuestFrame", "QuestLogPopupDetailFrame", "RaidBrowserFrame", "RaidParentFrame", "ReadyCheckFrame", "ReportCheatingDialog", "ReportPlayerNameDialog", "RolePollPopup", "ScrollOfResurrectionSelectionFrame", "SpellBookFrame", "StackSplitFrame", "StaticPopup1", "StaticPopup2", "StaticPopup3", "StaticPopup4", "TabardFrame", "TaxiFrame", "TimeManagerFrame", "TradeFrame", "TutorialFrame", "VideoOptionsFrame", "WorldStateScoreFrame", } K.AddonsList = { ["Blizzard_AchievementUI"] = {"AchievementFrame"}, ["Blizzard_ArchaeologyUI"] = {"ArchaeologyFrame"}, ["Blizzard_AuctionUI"] = {"AuctionFrame"}, ["Blizzard_BarberShopUI"] = {"BarberShopFrame"}, ["Blizzard_BindingUI"] = {"KeyBindingFrame"}, ["Blizzard_BlackMarketUI"] = {"BlackMarketFrame"}, ["Blizzard_Calendar"] = {"CalendarCreateEventFrame", "CalendarFrame", "CalendarViewEventFrame", "CalendarViewHolidayFrame"}, ["Blizzard_Collections"] = {"CollectionsJournal"}, ["Blizzard_EncounterJournal"] = {"EncounterJournal"}, ["Blizzard_GarrisonUI"] = {"GarrisonMissionFrame", "GarrisonCapacitiveDisplayFrame", "GarrisonLandingPage"}, ["Blizzard_GMChatUI"] = {"GMChatStatusFrame"}, ["Blizzard_GMSurveyUI"] = {"GMSurveyFrame"}, ["Blizzard_GuildBankUI"] = {"GuildBankFrame"}, ["Blizzard_GuildControlUI"] = {"GuildControlUI"}, ["Blizzard_GuildUI"] = {"GuildFrame", "GuildLogFrame"}, ["Blizzard_InspectUI"] = {"InspectFrame"}, ["Blizzard_ItemAlterationUI"] = {"TransmogrifyFrame"}, ["Blizzard_ItemSocketingUI"] = {"ItemSocketingFrame"}, ["Blizzard_ItemUpgradeUI"] = {"ItemUpgradeFrame"}, ["Blizzard_LookingForGuildUI"] = {"LookingForGuildFrame"}, ["Blizzard_MacroUI"] = {"MacroFrame"}, ["Blizzard_QuestChoice"] = {"QuestChoiceFrame"}, ["Blizzard_TalentUI"] = {"PlayerTalentFrame"}, ["Blizzard_TradeSkillUI"] = {"TradeSkillFrame"}, ["Blizzard_TrainerUI"] = {"ClassTrainerFrame"}, ["Blizzard_VoidStorageUI"] = {"VoidStorageFrame"}, } function MovableFrame:MakeMovable(frame) local name = frame:GetName() -- if K.CheckAddOn("KkthnxUI") and name == "LossOfControlFrame" then -- return -- end if name == "AchievementFrame" then AchievementFrameHeader:EnableMouse(false) end frame:EnableMouse(true) frame:SetMovable(true) frame:SetClampedToScreen(true) frame:RegisterForDrag("LeftButton") frame:SetScript("OnDragStart", function(self) self:StartMoving() end) frame:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end) end MovableFrame:RegisterEvent("PLAYER_LOGIN") MovableFrame:SetScript("OnEvent", function(self, event, addon) if event == "PLAYER_LOGIN" then self:RegisterEvent("ADDON_LOADED") for _, Frame in pairs(K.Frames) do if _G[Frame] then self:MakeMovable(_G[Frame]) end end -- Check Forced Loaded AddOns for AddOn, Table in pairs(K.AddonsList) do if IsAddOnLoaded(AddOn) then for _, Frame in pairs(Table) do self:MakeMovable(_G[Frame]) end end end end if event == "ADDON_LOADED" then if K.AddonsList[addon] then for _, Frame in pairs(K.AddonsList[addon]) do self:MakeMovable(_G[Frame]) end end end end)
------------------------------------- --- PANELS ------------------------------------- local Panels = MR.CL.Panels -- Networkings net.Receive("CL.Panels:RefreshProperties", function() Panels:RefreshProperties(MR.CL.ExposedPanels:Get("properties", "self")) end) local function validateEntry(panel) local input = panel:GetText() MR.Materials:SetNew(LocalPlayer(), panel:GetText()) --MR.Materials:SetOld(LocalPlayer(), "") -- I was restarting the fields if a wrong information was entered, but it's better to -- leave them until the player fixes the material name on his own. So if the menu is -- closed and the material is still invalid, it changes to our missing material. if input == "" or not MR.Materials:Validate(input) then MR.Materials:SetNew(LocalPlayer(), MR.Materials:GetMissing()) --MR.Materials:SetOld(LocalPlayer(), "") --panel:SetText(MR.Materials:GetMissing()) end timer.Simple(0.05, function() MR.CL.Materials:SetPreview() end) end function Panels:SetPropertiesPath(parent, frameType, info) local frame = MR.CL.Panels:StartContainer("Path", parent, frameType, info) local width = frame:GetWide() local panel = vgui.Create("DPanel") panel:SetSize(width, 0) panel:SetBackgroundColor(Color(255, 255, 255, 0)) local materialInfo = { width = width - MR.CL.Panels:GetGeneralBorders() * 2, height = MR.CL.Panels:GetTextHeight(), x = MR.CL.Panels:GetGeneralBorders(), y = MR.CL.Panels:GetGeneralBorders() } local materialInfo2 = { width = materialInfo.width, height = materialInfo.height, x = materialInfo.x, y = materialInfo.y + materialInfo.height + MR.CL.Panels:GetGeneralBorders() } -------------------------- -- Old material -------------------------- local materialText2 = vgui.Create("DTextEntry", panel) MR.CL.Panels:SetMRFocus(materialText2) materialText2:SetSize(materialInfo2.width, materialInfo2.height) materialText2:SetPos(materialInfo2.x, materialInfo2.y) materialText2:SetConVar("internal_mr_old_material") materialText2:SetTooltip("Base material") local backupMat2Paint = materialText2.Paint function materialText2:Paint(w, h) backupMat2Paint(self, w, h) if not materialText2:IsEditing() then draw.RoundedBox(2, 1, 1, w - 2, h - 2, Color(190, 190, 190, 255)) end end -------------------------- -- New material -------------------------- local materialText = vgui.Create("DTextEntry", panel) MR.CL.Panels:SetMRFocus(materialText) MR.CL.Panels:SetMRDefocusCallback(materialText, validateEntry, materialText) materialText:SetSize(materialInfo.width, materialInfo.height) materialText:SetPos(materialInfo.x, materialInfo.y) materialText:SetConVar("internal_mr_new_material") materialText:SetTooltip("New material") return MR.CL.Panels:FinishContainer(frame, panel, frameType) end -- Section: change properties function Panels:SetProperties(parent, frameType, info) local frame = MR.CL.Panels:StartContainer("Properties", parent, frameType, info) local width = frame:GetWide() local panel = vgui.Create("DPanel") panel:SetSize(width, 0) panel:SetBackgroundColor(Color(255, 255, 255, 0)) local alphaBarInfo = { width = MR.CL.Panels:GetTextHeight(), height = MR.CL.Panels:Preview_GetBoxSize(), x = MR.CL.Panels:GetGeneralBorders(), y = 0 } local propertiesPanelInfo = { width = width - alphaBarInfo.width - MR.CL.Panels:GetGeneralBorders() * 3, height = alphaBarInfo.height, x = alphaBarInfo.x + alphaBarInfo.width + MR.CL.Panels:GetGeneralBorders(), y = alphaBarInfo.y } local resetButtonInfo = { width = 16, height = 16, x = propertiesPanelInfo.x + propertiesPanelInfo.width - 16 - 4, y = alphaBarInfo.y + 4 } local totalHeight = alphaBarInfo.y + alphaBarInfo.height + MR.CL.Panels:GetGeneralBorders() -------------------------- -- Alpha bar -------------------------- local alphaBar = vgui.Create("DAlphaBar", panel) MR.CL.Panels:SetMRFocus(alphaBar) alphaBar:SetPos(alphaBarInfo.x, alphaBarInfo.y) alphaBar:SetSize(alphaBarInfo.width, alphaBarInfo.height) alphaBar:SetValue(1) alphaBar.OnChange = function(self, data) RunConsoleCommand("internal_mr_alpha", data) MR.CL.Materials:SetPreview() end -------------------------- -- Properties panel -------------------------- local function SetProperties(panel, propertiesPanelInfo) local propertiesPanel = vgui.Create("DProperties", panel) propertiesPanel:SetPos(propertiesPanelInfo.x, propertiesPanelInfo.y) propertiesPanel:SetSize(propertiesPanelInfo.width, propertiesPanelInfo.height) local function setValue(command, value) RunConsoleCommand(command, value) if not timer.Exists("MRWaitProperty") then timer.Create("MRWaitProperty", 0.03, 1, function() MR.CL.Materials:SetPreview() end) end end local function setValueFromText(command, value) setValue(command, value) timer.Simple(0.03, function() setValue(command, value) end) end local witdhMagnification = propertiesPanel:CreateRow("Magnification", "Width") witdhMagnification:Setup("Float", { min = 0.01, max = 6 }) witdhMagnification:SetValue(GetConVar("internal_mr_scalex"):GetFloat()) witdhMagnification.DataChanged = function(self, data) setValue("internal_mr_scalex", data) end MR.CL.Panels:SetMRFocus(witdhMagnification.Inner:GetChildren()[1].TextArea) witdhMagnification.Inner:GetChildren()[1].TextArea.OnEnter = function(self) setValueFromText("internal_mr_scalex", self:GetValue()) end local heightMagnification = propertiesPanel:CreateRow("Magnification", "Height") heightMagnification:Setup("Float", { min = 0.01, max = 6 }) heightMagnification:SetValue(GetConVar("internal_mr_scaley"):GetFloat()) heightMagnification.DataChanged = function(self, data) setValue("internal_mr_scaley", data) end MR.CL.Panels:SetMRFocus(heightMagnification.Inner:GetChildren()[1].TextArea) heightMagnification.Inner:GetChildren()[1].TextArea.OnEnter = function(self) setValueFromText("internal_mr_scaley", self:GetValue()) end local horizontalTranslation = propertiesPanel:CreateRow("Translation", "Horizontal") horizontalTranslation:Setup("Float", { min = -1, max = 1 }) horizontalTranslation:SetValue(GetConVar("internal_mr_offsetx"):GetFloat()) horizontalTranslation.DataChanged = function(self, data) setValue("internal_mr_offsetx", data) end MR.CL.Panels:SetMRFocus(horizontalTranslation.Inner:GetChildren()[1].TextArea) horizontalTranslation.Inner:GetChildren()[1].TextArea.OnEnter = function(self) setValueFromText("internal_mr_offsetx", self:GetValue()) end local verticalTranslation = propertiesPanel:CreateRow("Translation", "Vertical") verticalTranslation:Setup("Float", { min = -1, max = 1 }) verticalTranslation:SetValue(GetConVar("internal_mr_offsety"):GetFloat()) verticalTranslation.DataChanged = function(self, data) setValue("internal_mr_offsety", data) end MR.CL.Panels:SetMRFocus(verticalTranslation.Inner:GetChildren()[1].TextArea) verticalTranslation.Inner:GetChildren()[1].TextArea.OnEnter = function(self) setValueFromText("internal_mr_offsety", self:GetValue()) end local rotation = propertiesPanel:CreateRow("Others", "Rotation") rotation:Setup("Float", { min = -180, max = 180 }) rotation:SetValue(GetConVar("internal_mr_rotation"):GetFloat()) rotation.DataChanged = function(self, data) setValue("internal_mr_rotation", data) end MR.CL.Panels:SetMRFocus(rotation.Inner:GetChildren()[1].TextArea) rotation.Inner:GetChildren()[1].TextArea.OnEnter = function(self) setValueFromText("internal_mr_rotation", self:GetValue()) end local details = propertiesPanel:CreateRow("Others", "Detail") details:Setup("Combo", { text = GetConVar("internal_mr_detail"):GetString() }) for k,v in SortedPairs(MR.Materials:GetDetailList()) do details:AddChoice(k, { k, v }) end MR.CL.Panels:SetMRFocus(details.Inner:GetChildren()[1].Panel) details.DataChanged = function(self, data) setValue("internal_mr_detail", data[1]) end return propertiesPanel end local propertiesPanel = SetProperties(panel, propertiesPanelInfo) MR.CL.ExposedPanels:Set(propertiesPanel, "properties", "self") -------------------------- -- Reset button -------------------------- local resetButton = vgui.Create("DImageButton", panel) resetButton:SetSize(resetButtonInfo.width, resetButtonInfo.height) resetButton:SetPos(resetButtonInfo.x, resetButtonInfo.y) resetButton:SetImage("icon16/arrow_rotate_anticlockwise.png") resetButton.DoClick = function(self, isRightClick) propertiesPanel:Remove() if not isRightClick then MR.CL.CVars:SetPropertiesToDefaults(LocalPlayer()) end timer.Simple(0.01, function() local propertiesPanel = SetProperties(panel, propertiesPanelInfo) propertiesPanel.DoReset = resetButton.DoClick MR.CL.ExposedPanels:Set(propertiesPanel, "properties", "self") alphaBar:SetValue(1) timer.Simple(0.01, function() MR.CL.Materials:SetPreview() resetButton:MoveToFront() end) end) end -- Reset callback propertiesPanel.DoReset = resetButton.DoClick return MR.CL.Panels:FinishContainer(frame, panel, frameType, nil, totalHeight) end -- Reset the properties values function Panels:RefreshProperties(panel) if panel and panel ~= "" and panel.DoReset then panel.DoReset(nil, true) end end
-- The init file of PLoop.System.Net.MQTT require "PLoop.System.Net" -- Core require "PLoop.System.Net.OPC.Core" require "PLoop.System.Net.OPC.DataTypes" require "PLoop.System.Net.OPC.Reference" require "PLoop.System.Net.OPC.NodeClasses" require "PLoop.System.Net.OPC.EventTypes" require "PLoop.System.Net.OPC.VariableTypes" require "PLoop.System.Net.OPC.ObjectTypes" require "PLoop.System.Net.OPC.Services" -- require "PLoop.System.Net.OPC.Client"
--load all the module from the dll package.loadlib("LuaSmartCardLibrary.dll", "luaopen_card")() package.loadlib("LuaSmartCardLibrary.dll", "luaopen_sam")() package.loadlib("LuaSmartCardLibrary.dll", "luaopen_log")() package.loadlib("LuaSmartCardLibrary.dll", "luaopen_bytes")() package.loadlib("LuaSmartCardLibrary.dll", "luaopen_asn1")() package.loadlib("LuaSmartCardLibrary.dll", "luaopen_crypto")() package.loadlib("LuaSmartCardLibrary.dll", "luaopen_luasql_odbc")() --the place to save or log local msg = log.open_logfile("log\\log_dump.txt", 5) print("msg = " .. msg) card = pcsc_card sam = pcsc_sam ----------------------------------------------- -- FUNCTIONS ----------------------------------------------- function verify_sw(recv_sw, ref_sw) if (recv_sw ~= ref_sw) then card.disconnect_reader() error("Received " .. string.format("sw = %x", recv_sw) .. " Expect " .. string.format("sw = %x", ref_sw)) return false --not verified end return true end ----------------------------------------------- -- START MAIN ----------------------------------------------- local readers = card.list_readers() log.print(log.DEBUG, "Available readers = " .. readers) local isInitialized = card.init_reader() if (isInitialized) then log.print(log.DEBUG, "Reader Initialized") else log.print(log.ERROR, "Reader Not Initialized") error("Fail to initialize the reader/encoding station") return end --connect to card local reader_name = "ACS ACR122 0" local isconnected = card.connect_reader(reader_name) if (isconnected == false) then error("Cannot connect to reader") return end local atr = card.get_atr() log.print(log.INFO,"Card ATR = " .. atr) --connect to sam reader_name = "O2Micro CCID SC Reader 0" isconnected = sam.connect_reader(reader_name) if (isconnected == false) then error("Cannot connect to reader") return end atr = card.get_atr() log.print(log.INFO,"Card ATR = " .. atr) --select applet log.print(log.DEBUG,"Select DF ") sw, response = card.send_auto("00A404000BF7534D4152442E4D61696E") verify_sw(sw, 0x9000) --select sam log.print(log.DEBUG,"Select DF VSDC") sw, response = sam.send_auto("00A4040007A0000000031010") verify_sw(sw, 0x9000) --close log file log.close_logfile()
require("curses"); function read_cmd() curses.attron(curses.A_BOLD); curses.addstr("Command: "); curses.attron(underline); local s = ""; while (true) do local c = string.char(curses.getch()); if (c == '\n') then break; end s = s .. c; end curses.attroff(underline); curses.attroff(curses.A_BOLD); curses.addch("\n"); return s; end curses.filter(); curses.initscr(); curses.cbreak(); curses.keypad(curses.stdscr(), TRUE); if (curses.has_colors()) then curses.start_color(); curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK); underline = curses.COLOR_PAIR(1); else underline = curses.A_UNDERLINE; end while (true) do local s = read_cmd(); if (s == "exit") then break; end curses.reset_shell_mode(); io.write("\n"); io.flush(io.stdout); os.execute(s); curses.reset_prog_mode(); curses.touchwin(curses.stdscr()); curses.erase(); curses.refresh(); end curses.endwin();
local TAG = "城市争夺战 商店======snake" local activityConfig = require "config.activityConfig" local ShopModule = require "module.ShopModule" local buildScienceConfig = require "config.buildScienceConfig" local Time = require "module.Time" local BuildShopModule = require "module.BuildShopModule" local MapConfig = require "config.MapConfig" local begin_time = 1531229400; local function getTimeHMS(time) local H = math.floor(time /3600); time = math.fmod(time ,3600) local M = math.floor(time/60); time = math.fmod(time ,60) local S = time return H,M,S end local function get_timezone() local now = os.time() return os.difftime(now, os.time(os.date("!*t", now)))/3600 end local function date(now) local now = now or Time.now(); return os.date ("!*t", now + 8 * 3600); end local function getTimeByDate(year,month,day,hour,min,sec) local east8 = os.time({year = year, month = month, day = day, hour = hour, min = min, sec = sec})+ (get_timezone()-8) * 3600 return east8 end local View = {}; function View:OnDestroy() DispatchEvent("CurrencyRef"); end function View:Start(data) local _shopCfg=module.ShopModule.Load(21) for i=1,4 do DispatchEvent("CurrencyRef",{i,_shopCfg["top_resource_id"..i]}) end -- ERROR_LOG(module.playerModule.Get().id) self.root = CS.SGK.UIReference.Setup(self.gameObject) self.view = self.root.bg; self.top = self.view.topinfo; self.dropdown = self.view.bottom.bg.filter.Dropdown[UI.Dropdown]; self.dropdownController = self.view.bottom.bg.filter.Dropdown[SGK.DropdownController]; self.view.Center.mask[CS.UGUIClickEventListener].onClick = function ( ... ) if self.currentTips then --todo self.currentTips:SetActive(false); self.currentTips = nil; end self.view.Center.mask:SetActive(false); end self.mapid = data; self.scroll = self.view.Center.ScrollView[CS.UIMultiScroller]; self.scroll.enabled = false; self.scroll.RefreshIconCallback = function (obj, idx) obj.gameObject:SetActive(true); local item = SGK.UIReference.Setup(obj); local item_data = self.scrolldata[idx+1]; self:FreshItem(item_data,item,idx); end self:FreshUI(self.mapid); -- self.next_fresh_time = Time.now(); local time_t = date(Time.now()) -- print("时间================",sprinttb(date(Time.now()))) self.next_fresh_time = getTimeByDate(time_t.year,time_t.month,time_t.day+1,0,0,0); -- print("结束时间",Time.now(),end_time) -- self.next_fresh_time = Time.now() + ; end function View:Update( ... ) if self.next_fresh_time then --todo local time = self.next_fresh_time - Time.now(); if time >=0 then self.view.bottom.bg.time.timer[UI.Text].text = string.format("%02d:%02d:%02d",getTimeHMS(time )); else self.next_fresh_time = nil; local time_t = date(Time.now()) -- print("时间================",sprinttb(date(Time.now()))) self.next_fresh_time = getTimeByDate(time_t.year,time_t.month,time_t.day+1,0,0,0) BuildShopModule.QueryMapShopInfo(self.mapid,true); end end if self.next_query_time then local time = self.next_query_time - Time.now(); -- print(time); if time < 0 then -- print("重新查询数据"); -- self.next_query_time = nil; BuildShopModule.QueryMapDepot(self.mapid,true); self.next_query_time = Time.now() + 60; end end end -- 1, 2, 3, 4, nil _type function View:PerkItemID( _type ) local info = BuildShopModule.QueryMapShopInfo(self.mapid); if not info then return true ; end -- print("self.resource",sprinttb(self.resource)) local itemid = _type and self.resource[_type].item_id or nil; self.scrolldata = {}; -- -- print(sprinttb(info)) -- print(sprinttb(itemid)); for k,v in pairs(info) do if itemid and itemid == v.consume[2] then table.insert(self.scrolldata,v); end if not itemid then --特产 table.insert(self.scrolldata,v); end end -- module.ItemModule.GetItemCount(v.limt_consume[2]); -- print("===========",specialty_max,noSpecialty_max); -- print("=================",sprinttb(self.scrolldata)) self:FreshSpecialty(); table.sort(self.scrolldata,function (a, b) return a.gid < b.gid; end); self.scroll.DataCount = #self.scrolldata; -- self.scroll:ItemRef(); self.type = _type; end local product = { { flag = 1,id = 3005,limit = 20 }, { flag = 0,id = 3006,limit = 20 }, } function View:FreshSpecialty() local _count_t = module.ItemModule.GetItemCount(product[1].id); self.top.bg.exchangeContent_t.Text[UI.Text].text = (_count_t ==0 and "<color=#ff0000>" or "<color=#1a7d0f>").._count_t .."/"..product[1].limit.."</color>"; local _count = module.ItemModule.GetItemCount(product[2].id); self.top.bg.exchangeContent_t.desc[UI.Text].text = "今日兑换特产商品" self.top.bg.exchangeContent.desc[UI.Text].text = "今日兑换普通商品" self.top.bg.exchangeContent.Text[UI.Text].text = (_count ==0 and "<color=#ff0000>" or "<color=#1a7d0f>").._count .."/"..product[2].limit.."</color>"; end function View:FreshUI(mapid) local cfg = activityConfig.GetCityConfig(self.mapid); if not cfg then return; end self.depot = BuildShopModule.GetMapDepot(self.mapid); if not self.depot then BuildShopModule.QueryMapDepot(self.mapid,true); end self.resource = buildScienceConfig.GetResourceConfig(); -- ERROR_LOG(sprinttb(self.depot or {})) -- local info = BuildShopModule.QueryMapShopInfo(self.mapid); local info = BuildShopModule.QueryMapShopInfo(self.mapid); if not info then return; end -- print("===========",sprinttb(info)) local ret = self:PerkItemID(self.type); if ret then return; end self.scroll.enabled = true; self:FreshEvent(); end function View:FreshItem(data,item,idx) -- print(sprinttb(data)); local consume = data.consume; utils.IconFrameHelper.Create(item.bg.consoume,{count = consume[3],id = consume[2],type = consume[1],showDetail = true}); print("=========>>>",sprinttb(data)) local reward = data.reward utils.IconFrameHelper.Create(item.bg.reward,{count = reward[3],id = reward[2],type = reward[1],showDetail = true}); item.bg.flag:SetActive(data.specialty == 1); item.bg.flag[UI.Image]:SetNativeSize(); item.bg[CS.UGUISpriteSelector].index = data.specialty == 1 and 0 or 1; if not self.depot then return end print(sprinttb(self.depot),reward[2]) local lave = self.depot[reward[2]].value; -- print("剩余",reward[2],sprinttb(self.depot)) if self.depot then item.bg.bg.Text[UI.Text].text = "剩余:"..lave; if lave <=0 then item.bg.convert[CS.UGUIClickEventListener].interactable = false; else item.bg.convert[CS.UGUIClickEventListener].interactable = true; end end -- print("道具数量",lave); local _count_t = module.ItemModule.GetItemCount(product[data.specialty == 1 and 1 or 2].id); local cfg = module.ItemModule.GetConfig(consume[2]); item.bg.convert[CS.UGUIClickEventListener].onClick = function ( ... ) local self_consume_count = module.ItemModule.GetItemCount(consume[2]); if self_consume_count < consume[3] then showDlgError(nil,"兑换所需"..cfg.name.."不足!"); return; end if lave <=0 then showDlgError(nil,"该物品已经卖光了"); return; end if _count_t <=0 then showDlgError(nil,"今日限购次数已用尽"); return; end BuildShopModule.BuyMapProduct(data.gid,nil,self.mapid,function ( err ) if err == 0 then showDlgError(nil,"购买成功"); end end); end item.bg.parity[CS.UGUIClickEventListener].onClick = function ( ... ) item.bg.parity.tips:SetActive(not item.bg.parity.tips.gameObject.activeInHierarchy); print(not item.bg.parity.tips.gameObject.activeInHierarchy) if item.bg.parity.tips.gameObject.activeInHierarchy then self:FreshTips(data,item.bg.parity.tips,idx); self.view.Center.mask:SetActive(true); self.currentTips = item.bg.parity.tips.gameObject; else self.view.Center.mask:SetActive(false); end end end function View:FreshTips(data,view,_idx) self.isfrush = self.isfrush or {}; if self.isfrush[_idx] then return; end local item = view.bg; local consume = module.ItemModule.GetConfig(data.consume[2]); local reward = module.ItemModule.GetConfig(data.reward[2]); item.title[UI.Text].text = consume.name.." 兑换 "..reward.name local allmap = activityConfig.GetCityConfig().map_id; local temp_data = {} local index = 0; -- print("道具信息",sprinttb(data)) local min_all = {}; local min = nil; for k,v in pairs(allmap) do index = index + 1; local content = item["content"..index]; -- content.flag:SetActive(Shop_Product[data.gid] == i); local product = BuildShopModule.QueryMapProducInfo(v.map_id) -- print(data.reward[2]) -- print(sprinttb(product),sprinttb(product[data.consume[2]],sprinttb(product[data.consume[2]]))) if product and product[data.consume[2]] and product[data.consume[2]][data.reward[2]] then content:SetActive(true); -- content.flag:SetActive(true); min = {idx = index,value = product[data.consume[2]][data.reward[2]].value}; table.insert( min_all, min ) -- print("==============",sprinttb(data)) if v.map_id == self.mapid then -- print("地图ID相同") content.Text[UI.Text].color = UnityEngine.Color.yellow; else content.Text[UI.Text].color = UnityEngine.Color.white; end content.flag:SetActive(false); local info = MapConfig.GetMapConf(v.map_id); content.Text[UI.Text].text = " "..info.map_name.."\t"..product[data.consume[2]][data.reward[2]].value.."兑1"; else content:SetActive(false); content.flag:SetActive(false); end end table.sort( min_all, function ( a,b ) return a.value < b.value; end ) for k,v in pairs(min_all) do local content = item["content"..v.idx]; if min_all[1].value == v.value then content.flag:SetActive(true); end end for k,v in pairs(min_all) do end self.isfrush[_idx] = true; end function View:FreshEvent() if not self.resource then return; end self.dropdown:ClearOptions(); for i,v in ipairs(self.resource) do self.dropdownController:AddOpotion(v.name); end self.dropdownController:AddOpotion("全部"); self.dropdown.value = self.num and self.num - 1 or #self.resource; self.dropdown:RefreshShownValue(); self.dropdown.onValueChanged:AddListener(function ( num ) self:FreshFilter(num+1,#self.resource); end); self.top.bg.helpBtn[CS.UGUIClickEventListener].onClick = function () utils.SGKTools.ShowDlgHelp(SGK.Localize:getInstance():getValue("guanqiazhengduoshuoming01")) end local info = module.unionModule.Manage:GetSelfUnion(); if not info then -- ERROR_LOG("你没有公会"); return; end local scienceinfo = module.BuildScienceModule.GetScience(self.mapid); if not scienceinfo then return; end -- print(scienceinfo) -- print("++++++++++++p",scienceinfo.title,info.unionId) if info.unionId ~= scienceinfo.title then --自己公会不是所占领的公会 print("-自己公会不是所占领的公会") self.top.bg.changePrice[UI.Button].interactable = false; self.top.bg.changePrice[CS.UGUIClickEventListener].onClick = function () showDlgError(nil,SGK.Localize:getInstance():getValue("guanqiazhengduo38")) end return; else --自己不是工会长 if info.leaderId ~= module.playerModule.Get().id then print("自己不是工会长") self.top.bg.changePrice[UI.Button].interactable = false; self.top.bg.changePrice[CS.UGUIClickEventListener].onClick = function () showDlgError(nil,SGK.Localize:getInstance():getValue("guanqiazhengduo38")) end return; end end self.top.bg.changePrice[UI.Button].interactable = false; self.top.bg.changePrice[CS.UGUIClickEventListener].onClick = function () DialogStack.PushPrefStact("buildcity/buildShopPrice",self.mapid); end end --筛选 function View:FreshFilter( num,max ) if num == max+1 then self:PerkItemID(); else self:PerkItemID(num); self.num = num end self.isfrush = nil; end -- GetCityLvAndExp function View:onEvent( event ,data ) -- print("+++++++++++",event) if event == "MAP_SET_SHOPINFO_SUCCESS" then -- self.isfrush = nil; self:FreshUI(self.mapid); elseif event == "QUERY_MAP_SHOPINFO_SUCCESS" then if data == self.mapid then self.isfrush = nil; self:FreshUI(self.mapid); end elseif event == "LOCAL_SLESET_MAPID_CHANGE" then if data ~=self.mapid then self.mapid = data module.BuildScienceModule.QueryScience(self.mapid); else return; end self.isfrush = nil; self.type = nil self.num = nil; if self.currentTips then --todo self.currentTips:SetActive(false); self.currentTips = nil; end self.view.Center.mask:SetActive(false); self:FreshUI(data); elseif event == "MAP_SHOP_COUNT_INFOCHANGE" then if data == self.mapid then self.isfrush = nil; self:FreshUI(data); end elseif event == "MAP_SHOP_PRICE_INFOCHANGE" then if data == self.mapid then self.isfrush = nil; self:FreshUI(data); end elseif event =="QUERY_MAP_DEPOT" then if data == self.mapid then self.next_query_time = Time.now()+60; self:FreshUI(data); end end end function View:listEvent() return{ -- "SHOP_INFO_CHANGE", -- "SHOP_BUY_SUCCEED", -- "BUILD_SHOP_PRICE", "MAP_SET_SHOPINFO_SUCCESS", "QUERY_MAP_SHOPINFO_SUCCESS", "LOCAL_SLESET_MAPID_CHANGE", "QUERY_MAP_DEPOT", --数量变更通知 "MAP_SHOP_COUNT_INFOCHANGE", "MAP_SHOP_PRICE_INFOCHANGE", } end return View;
-- Note: This file contains comments taken from this document: -- http://java.sun.com/javase/6/docs/platform/serialization/spec/protocol.html -- -- The document is (C) 2005 Sun Microsystems, all rights reserved. -- I am only using it for reference. -- Removal of the comments should not affect functionality. -- -- This code is a hackjob. It will not load every class you throw at it. -- I can almost guarantee that, actually - as far as Java compatibility goes, -- this sucks! -- -GM function to32(s,o) return (string.byte(s,1+o) *256*256*256)+(string.byte(s,2+o) *256*256)+(string.byte(s,3+o) * 256)+string.byte(s,4+o) end function get64(fp) local s = fp:read(8) return (to32(s,4)*256*256*256*256)+to32(s,0) end function get32(fp) local s = fp:read(4) return (string.byte(s,1) *256*256*256)+(string.byte(s,2) *256*256)+(string.byte(s,3) * 256)+string.byte(s,4) end function get16(fp) local s = fp:read(2) return (string.byte(s,1) * 256)+string.byte(s,2) end function get8(fp) local s = fp:read(1) return string.byte(s,1) end function getasciiz(fp) local s = "" while true do local c = fp:read(1) if c == "\000" then break end s = s..c end return s end function getpascal(fp) return fp:read(get8(fp)) end function getpascal2(fp) return fp:read(get16(fp)) end function getpascal4(fp) return fp:read(get32(fp)) end jserhandles = { start = 0x7E0000, pos = 0x7E0000 } function java_serial_magic(fp) if get16(fp) ~= 0xACED then error("magic number failed") end end function java_serial_version(fp) local ver = get16(fp) print("Serial version: "..ver) end function java_serial_newhandle() local hdl = { id = jserhandles.pos } jserhandles[jserhandles.pos] = hdl jserhandles.pos = jserhandles.pos + 1 print(string.format("Handle %06X created", hdl.id)) return hdl end function java_serial_classdescflags(fp) -- classDescFlags: -- (byte) // Defined in Terminal Symbols and -- // Constants return get8(fp) end function java_serial_fields(fp) -- fields: -- (short)<count> fieldDesc[count] local fcount = get16(fp) local farray = { length = fcount, obj = {} } print("Field count: "..fcount) for i=1,fcount do local ftype = fp:read(1) local fname = getpascal2(fp) print("Field "..i.."/"..fcount.." "..ftype..": "..fname) -- fieldDesc: -- primitiveDesc -- objectDesc -- primitiveDesc: -- prim_typecode fieldName -- objectDesc: -- obj_typecode fieldName className1 -- prim_typecode: -- `B' // byte -- `C' // char -- `D' // double -- `F' // float -- `I' // integer -- `J' // long -- `S' // short -- `Z' // boolean -- obj_typecode: -- `[` // array -- `L' // object -- className1: -- (String)object // String containing the field's type, -- // in field descriptor format local fstype = nil if ftype == "[" or ftype == "L" then -- Oh boy. fstype = get8(fp) fstype = java_serial_content(fp,fstype).sval print("object string: "..fstype) end farray[i] = { ftype = ftype, fstype = fstype, fname = fname } farray.obj[fname] = farray[i] end return farray end function java_serial_newstring(fp) -- newString: -- TC_STRING newHandle (utf) local hdl = java_serial_newhandle() hdl.sval = getpascal2(fp) return hdl end function java_serial_newlongstring(fp) -- newString: -- TC_LONGSTRING newHandle (long-utf) local hdl = java_serial_newhandle() hdl.sval = getpascal4(fp) return hdl end function java_serial_prevobject(fp) -- prevObject -- TC_REFERENCE (int)handle return jserhandles[get32(fp)] end function java_serial_classannotation(fp) -- classAnnotation: -- endBlockData -- contents endBlockData // contents written by annotateClass return java_serial_contents(fp) end function java_serial_superclassdesc(fp) -- superClassDesc: -- classDesc return java_serial_classdesc(fp) end function java_serial_classdescinfo(fp) -- classDescInfo: -- classDescFlags fields classAnnotation superClassDesc local cdflags = java_serial_classdescflags(fp) local cfields = java_serial_fields(fp) local cannot = java_serial_classannotation(fp) local csuper = java_serial_superclassdesc(fp) print(string.format("### FLAGS: %02X",cdflags)) return { cdflags = cdflags, cfields = cfields, cannot = cannot, csuper = csuper } end function java_serial_newclassdesc(fp) -- TC_CLASSDESC className serialVersionUID newHandle classDescInfo -- className: -- (utf) -- serialVersionUID: -- (long) local chdl = java_serial_newhandle() chdl.htype = 0x72 chdl.cname = getpascal2(fp) chdl.cuid = get64(fp) chdl.cdinfo = java_serial_classdescinfo(fp) print("classdesc name: "..chdl.cname) return chdl end function java_serial_classdesc(fp) -- classDesc: -- newClassDesc -- nullReference -- (ClassDesc)prevObject // an object required to be of type -- // ClassDesc local id = get8(fp) local desc = nil if id == 0x70 then desc = {} elseif id == 0x72 then desc = java_serial_newclassdesc(fp) else error(string.format("block type not supported: %02X",id)) end return desc end function java_serial_newobject(fp) -- newObject: -- TC_OBJECT classDesc newHandle classdata[] // data for each class -- classdata: -- nowrclass // SC_SERIALIZABLE & classDescFlag && -- // !(SC_WRITE_METHOD & classDescFlags) -- wrclass objectAnnotation // SC_SERIALIZABLE & classDescFlag && -- // SC_WRITE_METHOD & classDescFlags -- externalContents // SC_EXTERNALIZABLE & classDescFlag && -- // !(SC_BLOCKDATA & classDescFlags -- objectAnnotation // SC_EXTERNALIZABLE & classDescFlag&& -- // SC_BLOCKDATA & classDescFlags -- nowrclass: -- values // fields in order of class descriptor -- wrclass: -- nowrclass -- objectAnnotation: -- endBlockData -- contents endBlockData // contents written by writeObject -- // or writeExternal PROTOCOL_VERSION_2. -- externalContent: // Only parseable by readExternal -- ( bytes) // primitive data -- object -- externalContents: // externalContent written by -- externalContent // writeExternal in PROTOCOL_VERSION_1. -- externalContents externalContent local cdesc = java_serial_classdesc(fp) local chdl = java_serial_newhandle() local fields = cdesc.cdinfo.cfields for i=1,fields.length do local fobj = fields[i] print("Field "..i.."/"..fields.length..": "..fobj.ftype) if fobj.ftype == "B" then fobj.ival = get8(fp) if fobj.ival >= 0x80 then fobj.ival = fobj.ival - 0x100 end print("Integer: "..fobj.ival) elseif fobj.ftype == "S" then fobj.ival = get16(fp) if fobj.ival >= 0x8000 then fobj.ival = fobj.ival - 0x10000 end print("Integer: "..fobj.ival) elseif fobj.ftype == "I" then fobj.ival = get32(fp) if fobj.ival >= 0x80000000 then fobj.ival = fobj.ival - 0x100000000 end print("Integer: "..fobj.ival) elseif fobj.ftype == "J" then fobj.ival = get64(fp) -- I'm not even going to attempt to signify this... print("Integer: "..fobj.ival) elseif fobj.ftype == "Z" then fobj.bval = get8(fp) ~= 0 if fobj.bval then print("Boolean: true") else print("Boolean: false") end elseif fobj.ftype == "F" then -- Blatantly ignoring this. fobj.fval = get32(fp) print("Float: "..fobj.fval) elseif fobj.ftype == "D" then -- Blatantly ignoring this, too! fobj.fval = get64(fp) print("Float: "..fobj.fval) elseif fobj.ftype == "[" or fobj.ftype == "L" then fobj.oval = java_serial_content(fp, get8(fp)) print(fobj.fstype) if fobj.fstype == "Ljava/lang/String;" then print("hai guise i has a string") fobj.sval = fobj.oval.sval if fobj.oval.bdata == nil then print("String: "..fobj.sval) else print("Rather not-nice string") end else print("Object containing data") end else error("unsupported block type: "..fobj.ftype) end end chdl.cdesc = cdesc chdl.fields = fields if ((cdesc.cdinfo.cdflags % 2) - (cdesc.cdinfo.cdflags % 1)) ~= 0 then chdl.weirdblock = java_serial_content(fp,get8(fp)) end return chdl --error("notdone") end function java_serial_newarray(fp) -- newArray: -- TC_ARRAY classDesc newHandle (int)<size> values[size] local cdesc = java_serial_classdesc(fp) local ahdl = java_serial_newhandle() local asize = get32(fp) print("array size: "..asize) print("array type: "..cdesc.cname) local adata = nil if cdesc.cname == "[B" then -- LUA WILL HATE MY GUTS print("Loading! This'll take far too long!") adata = fp:read(asize) print("Done! You can wake up now!") -- actually, it didn't when i tested an 8MB map. -- it took less than a second on this lappy. -- -GM else error("array type not supported: "..cdesc.cname) end ahdl.cdesc = cdesc ahdl.asize = asize ahdl.adata = adata return ahdl end function java_serial_blockdatashort(fp) -- blockdatashort: -- TC_BLOCKDATA (unsigned byte)<size> (byte)[size] local bsize = get8(fp) local rval = { bsize = bsize, bdata = fp:read(bsize) } rval.sval = rval.bdata local btest = get8(fp) if btest ~= 0x78 then error("expected block end") end return rval end function java_serial_content(fp,id) -- content: -- object -- blockdata -- object: -- newObject -- newClass -- newArray -- newString -- newEnum -- newClassDesc -- prevObject -- nullReference -- exception -- TC_RESET -- blockdata: -- blockdatashort -- blockdatalong local rdata = nil if id == 0x70 then rdata = {} elseif id == 0x71 then rdata = java_serial_prevobject(fp) elseif id == 0x73 then rdata = java_serial_newobject(fp) elseif id == 0x74 then rdata = java_serial_newstring(fp) elseif id == 0x75 then rdata = java_serial_newarray(fp) elseif id == 0x77 then rdata = java_serial_blockdatashort(fp) else error(string.format("block type not supported: %02X",id)) end return rdata end function java_serial_contents(fp, jdata) local id = fp:read(1) if id == nil or id == "x" then return jdata end local jdbase = java_serial_content(fp,string.byte(id)) jdata[jdata.length] = jdbase jdata.length = jdata.length + 1 return java_serial_contents(fp, jdata) end function java_loadserial(fn) fp = io.open(fn,"rb") -- We ditch the first 5 bytes. fp:read(5) -- stream: -- magic version contents java_serial_magic(fp) java_serial_version(fp) local jdata = java_serial_contents(fp,{length = 0}) return jdata end function java_loadserial_safe(fn) -- TODO change this to a pcall java_loadserial(fn) end print("javaformats.lua initialised")
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file window.lua -- -- load modules local log = require("ui/log") local rect = require("ui/rect") local view = require("ui/view") local label = require("ui/label") local panel = require("ui/panel") local event = require("ui/event") local border = require("ui/border") local curses = require("ui/curses") local action = require("ui/action") -- define module local window = window or panel() -- init window function window:init(name, bounds, title, shadow) -- init panel panel.init(self, name, bounds) -- check bounds assert(self:width() > 4 and self:height() > 3, string.format("%s: too small!", tostring(self))) -- insert shadow if shadow then self:insert(self:shadow()) self:frame():bounds():movee(-2, -1) self:frame():invalidate(true) end -- insert border self:frame():insert(self:border()) -- insert title if title then self._TITLE = label:new("window.title", rect{0, 0, #title, 1}, title) self:title():textattr_set("blue bold") self:title():action_set(action.ac_on_text_changed, function (v) if v:text() then local bounds = v:bounds() v:bounds():resize(#v:text(), v:height()) bounds:move2(math.max(0, math.floor((self:frame():width() - v:width()) / 2)), bounds.sy) v:invalidate(true) end end) self:frame():insert(self:title(), {centerx = true}) end -- insert panel self:frame():insert(self:panel()) -- insert frame self:insert(self:frame()) end -- get frame function window:frame() if not self._FRAME then self._FRAME = panel:new("window.frame", rect{0, 0, self:width(), self:height()}):background_set("white") end return self._FRAME end -- get panel function window:panel() if not self._PANEL then self._PANEL = panel:new("window.panel", self:frame():bounds()) self._PANEL:bounds():grow(-1, -1) self._PANEL:invalidate(true) end return self._PANEL end -- get title function window:title() return self._TITLE end -- get shadow function window:shadow() if not self._SHADOW then self._SHADOW = view:new("window.shadow", rect{2, 1, self:width(), self:height()}):background_set("black") end return self._SHADOW end -- get border function window:border() if not self._BORDER then self._BORDER = border:new("window.border", self:frame():bounds()) end return self._BORDER end -- on event function window:event_on(e) -- select panel? if e.type == event.ev_keyboard then if e.key_name == "Tab" then return self:panel():select_next() end end end -- return module return window
-- Mizar32 A board configuration return { cpu = 'at32uc3a0512', components = { sercon = { uart = "cdc", speed = 115200 }, mmcfs = { spi = 4, cs_port = 0, cs_pin = "SD_MMC_SPI_NPCS_PIN" }, adc = { buf_size = 2 }, term = { lines = 25, cols = 80 }, tcpip = { ip = "193.168.1.10", netmask = "255.255.255.0", gw = "192.168.1.1", dns = "192.168.1.1" }, dhcp = true, dns = true, cints = true, luaints = true, shell = true, xmodem = true, avr32_lcd = true, avr32_rtc = true, }, config = { vtmr = { num = 4, freq = 10 }, ram = { ext_start = { "SDRAM + ELUA_FIRMWARE_SIZE" }, ext_size = { "SDRAM_SIZE - ELUA_FIRMWARE_SIZE" }, } }, modules = { generic = { 'all', "-rpc", "-can" }, platform = { 'all' }, platform_name = 'mizar32' }, macros = { { "BOARD_SPI0_SCK_PIN", "AVR32_PIN_PA13" }, { "BOARD_SPI0_SCK_PIN_FUNCTION", 0 }, { "BOARD_SPI0_MISO_PIN", "AVR32_PIN_PA11" }, { "BOARD_SPI0_MISO_PIN_FUNCTION", 0 }, { "BOARD_SPI0_MOSI_PIN", "AVR32_PIN_PA12" }, { "BOARD_SPI0_MOSI_PIN_FUNCTION", 0 }, { "BOARD_SPI0_CS_PIN", "AVR32_PIN_PA10" }, { "BOARD_SPI0_CS_PIN_FUNCTION", 0 }, { "BOARD_SPI1_SCK_PIN", "AVR32_PIN_PA15" }, { "BOARD_SPI1_SCK_PIN_FUNCTION", 1 }, { "BOARD_SPI1_MISO_PIN", "AVR32_PIN_PA17" }, { "BOARD_SPI1_MISO_PIN_FUNCTION", 1 }, { "BOARD_SPI1_MOSI_PIN", "AVR32_PIN_PA16" }, { "BOARD_SPI1_MOSI_PIN_FUNCTION", 1 }, { "BOARD_SPI1_CS_PIN", "AVR32_PIN_PA14" }, { "BOARD_SPI1_CS_PIN_FUNCTION", 1 }, }, }
----------------------------------------------------------------------------------------------------------------------- -- RedFlat monitor widget -- ----------------------------------------------------------------------------------------------------------------------- -- Widget with circle indicator ----------------------------------------------------------------------------------------------------------------------- -- Grab environment ----------------------------------------------------------------------------------------------------------------------- local setmetatable = setmetatable local math = math local wibox = require("wibox") local beautiful = require("beautiful") local color = require("gears.color") local redutil = require("redflat.util") -- Initialize tables for module ----------------------------------------------------------------------------------------------------------------------- local cirmon = { mt = {} } local TPI = math.pi * 2 -- Generate default theme vars ----------------------------------------------------------------------------------------------------------------------- local function default_style() local style = { width = nil, line_width = 4, radius = 14, iradius = 6, step = 0.02, color = { main = "#b1222b", gray = "#575757", icon = "#a0a0a0" } } return redutil.table.merge(style, redutil.table.check(beautiful, "gauge.monitor.circle") or {}) end -- Create a new monitor widget -- @param style Table containing colors and geometry parameters for all elemets ----------------------------------------------------------------------------------------------------------------------- function cirmon.new(style) -- Initialize vars -------------------------------------------------------------------------------- style = redutil.table.merge(default_style(), style or {}) local cs = -TPI / 4 -- Create custom widget -------------------------------------------------------------------------------- local widg = wibox.widget.base.make_widget() widg._data = { color = style.color.icon, level = 0, alert = false } if style.width then widg:set_forced_width(style.width) end -- User functions ------------------------------------------------------------ function widg:set_value(x) local value = x < 1 and x or 1 local level = math.floor(value / style.step) * style.step if level ~= self._data.level then self._data.level = level self:emit_signal("widget::redraw_needed") end end function widg:set_alert(alert) if alert ~= self._data.alert then self._data.alert = alert self._data.color = alert and style.color.main or style.color.icon self:emit_signal("widget::redraw_needed") end end -- Fit ------------------------------------------------------------ function widg:fit(_, width, height) local size = math.min(width, height) return size, size end -- Draw ------------------------------------------------------------ function widg:draw(_, cr, width, height) -- center circle cr:set_source(color(self._data.color)) cr:arc(width / 2, height / 2, style.iradius, 0, TPI) cr:fill() -- progress circle cr:set_line_width(style.line_width) local cd = { TPI, TPI * self._data.level } for i = 1, 2 do cr:set_source(color(i > 1 and style.color.main or style.color.gray)) cr:arc(width / 2, height / 2, style.radius, cs, cs + cd[i]) cr:stroke() end end -------------------------------------------------------------------------------- return widg end -- Config metatable to call monitor module as function ----------------------------------------------------------------------------------------------------------------------- function cirmon.mt:__call(...) return cirmon.new(...) end return setmetatable(cirmon, cirmon.mt)
__STD_REQUIRE = require; local function checkstring(s) local t = type(s) if t == "string" then return s elseif t == "number" then return tostring(s) else error("bad argument #1 to 'require' (string expected, got "..t..")", 3) end end local function split_prefix_module_name(module_name) local prefix_index = module_name:find("://"); if prefix_index ~= nil then local prefix = module_name:sub(0, prefix_index - 1); local module_name_no_prefix = module_name:sub(prefix_index + 3); return prefix, module_name_no_prefix; end return nil, module_name; end local function make_prefix_searcher(prefix) return function(module_name) local module_prefix, _ = split_prefix_module_name(module_name); module_name = module_name:gsub("%.", "/"); if module_prefix == nil then -- Silenting no prefix for Lua modules module_name = prefix .. "://" .. module_name; end module_name = module_name .. '.lua'; local find_result = obe.System.Path(module_name):find(); if find_result:success() then local loadfile_env = setmetatable({require=make_base_require(module_prefix or prefix)}, {__index=_G}); return loadfile(find_result:path(), "bt", loadfile_env); else return "\n no file " .. module_name .. " (default prefix: " .. prefix .. ")"; end end end -- Drop in replacement for `require` function -- Allows to use upvalue system instead of globally replace `require` (unsafe) function make_base_require(prefix) local env_searchers = setmetatable( {[#package.searchers] = make_prefix_searcher(prefix)}, {__index=package.searchers} ); local env_package = setmetatable({searchers = env_searchers}, {__index=package}); local _ENV = setmetatable({package = env_package}, {__index=_G}); return function(name) name = checkstring(name) local module = package.loaded[name] if module then return module end local msg = {} local loader, param for _, searcher in ipairs(package.searchers) do loader, param = searcher(name) if type(loader) == "function" then break end if type(loader) == "string" then -- `loader` is actually an error message msg[#msg + 1] = loader end loader = nil end if loader == nil then error("module '" .. name .. "' not found:\n".. table.concat(msg), 2) end local res = loader(name, param) if res ~= nil then module = res elseif not package.loaded[name] then module = true else module = package.loaded[name] end package.loaded[name] = module return module end end require = make_base_require("cwd");
name = "xSoulStealerx" me = game.Players[name] me.Chatted:connect(function(msg) if string.sub(msg, 1, 6) == "music/" then local test = string.sub(msg,7) local msg = Instance.new("Hint") msg.Parent = workspace msg.Text = "" local son = Instance.new("Sound") son.Parent = workspace son.Volume = 0.5 son.SoundId = "rbxasset://sounds/uuhhh.wav" local shown = 40 local nuhhba = 1 for i=1, string.len(test) + shown do wait(0.13) if i >= shown then nuhhba = nuhhba + 1 end msg.Text = msg.Text..string.sub(test,i,i) msg.Text = string.sub(test, nuhhba, i) if string.lower(string.sub(test,i,i)) == "a" then son.Pitch = 0.35 elseif string.lower(string.sub(test,i,i)) == "b" then son.Pitch = 0.4 elseif string.lower(string.sub(test,i,i)) == "c" then son.Pitch = 0.45 elseif string.lower(string.sub(test,i,i)) == "d" then son.Pitch = 0.5 elseif string.lower(string.sub(test,i,i)) == "e" then son.Pitch = 0.55 elseif string.lower(string.sub(test,i,i)) == "f" then son.Pitch = 0.6 elseif string.lower(string.sub(test,i,i)) == "g" then son.Pitch = 0.65 elseif string.lower(string.sub(test,i,i)) == "h" then son.Pitch = 0.7 elseif string.lower(string.sub(test,i,i)) == "i" then son.Pitch = 0.75 elseif string.lower(string.sub(test,i,i)) == "j" then son.Pitch = 0.8 elseif string.lower(string.sub(test,i,i)) == "k" then son.Pitch = 0.85 elseif string.lower(string.sub(test,i,i)) == "l" then son.Pitch = 0.9 elseif string.lower(string.sub(test,i,i)) == "m" then son.Pitch = 0.95 elseif string.lower(string.sub(test,i,i)) == "n" then son.Pitch = 1 elseif string.lower(string.sub(test,i,i)) == "o" then son.Pitch = 1.05 elseif string.lower(string.sub(test,i,i)) == "p" then son.Pitch = 1.1 elseif string.lower(string.sub(test,i,i)) == "q" then son.Pitch = 1.15 elseif string.lower(string.sub(test,i,i)) == "r" then son.Pitch = 1.2 elseif string.lower(string.sub(test,i,i)) == "s" then son.Pitch = 1.25 elseif string.lower(string.sub(test,i,i)) == "t" then son.Pitch = 1.3 elseif string.lower(string.sub(test,i,i)) == "u" then son.Pitch = 1.35 elseif string.lower(string.sub(test,i,i)) == "v" then son.Pitch = 1.4 elseif string.lower(string.sub(test,i,i)) == "w" then son.Pitch = 1.45 elseif string.lower(string.sub(test,i,i)) == "x" then son.Pitch = 1.5 elseif string.lower(string.sub(test,i,i)) == "y" then son.Pitch = 1.55 elseif string.lower(string.sub(test,i,i)) == "z" then son.Pitch = 1.6 end son:play() end wait(1) msg:remove() end end)
-- Register a network event RegisterNetEvent( 'wk:deleteVehicle' ) -- The distance to check in front of the player for a vehicle -- Distance is in GTA units, which are quite big local distanceToCheck = 5.0 -- Add an event handler for the deleteVehicle event. -- Gets called when a user types in /dv in chat (see server.lua) AddEventHandler( 'wk:deleteVehicle', function() local ped = GetPlayerPed( -1 ) if ( DoesEntityExist( ped ) and not IsEntityDead( ped ) ) then local pos = GetEntityCoords( ped ) if ( IsPedSittingInAnyVehicle( ped ) ) then local vehicle = GetVehiclePedIsIn( ped, false ) if ( GetPedInVehicleSeat( vehicle, -1 ) == ped ) then SetEntityAsMissionEntity( vehicle, true, true ) deleteCar( vehicle ) if ( DoesEntityExist( vehicle ) ) then ShowNotification( "~r~Unable to delete vehicle, try again." ) else ShowNotification( "Vehicle deleted." ) end else ShowNotification( "You must be in the driver's seat!" ) end else local playerPos = GetEntityCoords( ped, 1 ) local inFrontOfPlayer = GetOffsetFromEntityInWorldCoords( ped, 0.0, distanceToCheck, 0.0 ) local vehicle = GetVehicleInDirection( playerPos, inFrontOfPlayer ) if ( DoesEntityExist( vehicle ) ) then SetEntityAsMissionEntity( vehicle, true, true ) deleteCar( vehicle ) if ( DoesEntityExist( vehicle ) ) then ShowNotification( "~r~Unable to delete vehicle, try again." ) else ShowNotification( "Vehicle deleted." ) end else ShowNotification( "You must be in or near a vehicle to delete it." ) end end end end ) -- Delete car function borrowed frtom Mr.Scammer's model blacklist, thanks to him! function deleteCar( entity ) Citizen.InvokeNative( 0xEA386986E786A54F, Citizen.PointerValueIntInitialized( entity ) ) end -- Gets a vehicle in a certain direction -- Credit to Konijima function GetVehicleInDirection( coordFrom, coordTo ) local rayHandle = CastRayPointToPoint( coordFrom.x, coordFrom.y, coordFrom.z, coordTo.x, coordTo.y, coordTo.z, 10, GetPlayerPed( -1 ), 0 ) local _, _, _, _, vehicle = GetRaycastResult( rayHandle ) return vehicle end -- Shows a notification on the player's screen function ShowNotification( text ) SetNotificationTextEntry( "STRING" ) AddTextComponentString( text ) DrawNotification( false, false ) end
#! /usr/bin/env wsapi.cgi local orbit = require("orbit") local cjson = require("cjson") module("example", package.seeall, orbit.new) function log(web) local env_info = {} for k, v in pairs(web.vars) do if type(v) == "string" then env_info[k] = v end end print(web.path_info .. " " .. web.method .. " " .. cjson.encode(web.input) .. " " .. cjson.encode(env_info)) end function json_get_ok_1(web) log(web) web:content_type('application/json') return cjson.encode({ code = 1 }) end function json_post_ok(web) log(web) web:content_type('application/json') return cjson.encode({ code = 1 }) end function json_put_ok(web) log(web) web:content_type('application/json') return cjson.encode({ code = 1 }) end function json_get_ko(web) log(web) web:status("500") web:content_type('application/json') return cjson.encode({ code = 1 }) end function json_post_ko(web) log(web) web:status("500") web:content_type('application/json') return cjson.encode({ code = 1 }) end function json_put_ko(web) log(web) web:status("500") web:content_type('application/json') return cjson.encode({ code = 1 }) end function post_ok(web) log(web) web:content_type('text/plain') return "Hello" end -- Builds the application's dispatch table, you can -- pass multiple patterns, and any captures get passed to -- the controller example:dispatch_get(json_get_ok_1, "/json/ok/1") example:dispatch_post(json_post_ok, "/json/ok") example:dispatch_put(json_put_ok, "/json/ok") example:dispatch_get(json_get_ko, "/json/ko") example:dispatch_post(json_post_ko, "/json/ko") example:dispatch_put(json_put_ko, "/json/ko") example:dispatch_post(post_ok, "/post/ok") return _M
-- Enhanced from a script written by Wim Langers require'cdlua' require'iuplua' require'iupluacd' require'cdluapdf' function DrawInCanvas(canvas) -- If you want that your coordinates means the same thing independent from the driver -- then set the Window to be the your "world" coordinate system canvas:wWindow(0, 50, 0, 50) -- The you just have to choose how this "world" will be showed in the canvas by setting the Viewport -- Since you set a square world, set a square Viewport to keep the aspect ratio local width, height = canvas:GetSize() local square_size = width if (width > height) then square_size = height end canvas:wViewport(0, square_size, 0, square_size) -- The file drivers will have the same size all the time, but the dialog you can change its size -- since this is dinamically changed, the drawing will scale on screen when the dialog is resized -- if you do not want that, you can set wWindow and wViewport in another place in the code canvas:Foreground(cd.BLACK) canvas:TextAlignment(cd.CENTER) canvas:TextOrientation(0) -- size in mm actually do not depend on the transformation canvas:wFont('Courier', cd.BOLD, 3) -- size in mm canvas:wLineWidth(0.25) -- size in mm canvas:wRect(10,10 + 8,10 + 1,10 + 7) canvas:wText(10 + 2,10 + 2,'S') canvas:wText(10 + 2,10 + 5,'R') canvas:wText(10 + 6,10 + 5,'Q') canvas:wArc(10 + 9,10 + 2,2,2,0,360) canvas:wSector(20,20,2,2,0,360) end -- PS canvas = cd.CreateCanvas(cd.PS,'test.ps -l0 -r0 -b0 -t0 -o') -- no margins, landscape as a rotation, default size A4, 300 DPI DrawInCanvas(canvas) cd.KillCanvas(canvas) -- PDF canvas = cd.CreateCanvas(cd.PDF,'test.pdf -o') -- landscape as just a swith between w and h, default size A4, 300 DPI DrawInCanvas(canvas) cd.KillCanvas(canvas) -- SVG canvas = cd.CreateCanvas(cd.SVG,'test.svg 50x50') -- size in mm, 96 DPI DrawInCanvas(canvas) cd.KillCanvas(canvas) -- Screen iupCanvas = iup.canvas{scrollbar = 'yes'} dlg = iup.dialog{iupCanvas, title="Canvas Test", size="100x100"} function iupCanvas:map_cb() canvas = cd.CreateCanvas(cd.IUP,self) -- store the CD canvas in a IUP attribute end function iupCanvas:action() canvas:Activate() canvas:Clear() DrawInCanvas(canvas) end dlg:show() iup.MainLoop()
pfUI:RegisterSkin("Character", function () local border = tonumber(pfUI_config.appearance.border.default) local bpad = border > 1 and border - 1 or 1 local magicResTextureCords = { {0.21875, 0.78125, 0.25, 0.3203125}, {0.21875, 0.78125, 0.0234375, 0.09375}, {0.21875, 0.78125, 0.13671875, 0.20703125}, {0.21875, 0.78125, 0.36328125, 0.43359375}, {0.21875, 0.78125, 0.4765625, 0.546875} } do -- character frame local CharacterFrame = _G["PaperDollFrame"] StripTextures(CharacterFrame) CreateBackdrop(CharacterFrame, nil, nil, .75) CharacterFrame.backdrop:SetPoint("TOPLEFT", 10, -12) CharacterFrame.backdrop:SetPoint("BOTTOMRIGHT", -32, 76) SkinCloseButton(CharacterFrameCloseButton, CharacterFrame, -37, -17) CharacterFramePortrait:Hide() CharacterNameFrame:SetPoint("TOP", -10, -20) StripTextures(CharacterAttributesFrame) StripTextures(CharacterResistanceFrame) CharacterModelFrameRotateLeftButton:Hide() CharacterModelFrameRotateRightButton:Hide() EnableClickRotate(CharacterModelFrame) for i,c in pairs(magicResTextureCords) do local magicResFrame = _G["MagicResFrame"..i] magicResFrame:SetWidth(26) magicResFrame:SetHeight(26) CreateBackdrop(magicResFrame) SetAllPointsOffset(magicResFrame.backdrop, magicResFrame, 2) for k,f in pairs({magicResFrame:GetRegions()}) do if f:GetObjectType() == "Texture" then f:SetTexCoord(c[1], c[2], c[3], c[4]) SetAllPointsOffset(f, magicResFrame, 3) end end end local slots = { "HeadSlot", "NeckSlot", "ShoulderSlot", "BackSlot", "ChestSlot", "ShirtSlot", "TabardSlot", "WristSlot", "HandsSlot", "WaistSlot", "LegsSlot", "FeetSlot", "Finger0Slot", "Finger1Slot", "Trinket0Slot", "Trinket1Slot", "MainHandSlot", "SecondaryHandSlot", "RangedSlot", "AmmoSlot" } for i, slot in pairs(slots) do local slotId, _, _ = GetInventorySlotInfo(slot) local quality = GetInventoryItemQuality("player", slotId) local frame = _G["Character"..slot] local texture = _G["Character"..slot.."IconTexture"] texture:SetTexCoord(.08, .92, .08, .92) texture:ClearAllPoints() texture:SetPoint("TOPLEFT", frame, "TOPLEFT", 4, -4) texture:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -4, 4) StripTextures(frame) CreateBackdrop(frame) frame.backdrop:SetPoint("TOPLEFT", frame, "TOPLEFT", 2, -2) frame.backdrop:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -2, 2) if not frame.scoreText then frame.scoreText = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal") frame.scoreText:SetFont(pfUI.font_default, 12, "OUTLINE") frame.scoreText:SetPoint("BOTTOMRIGHT", 0, 0) end if true == false and i ~= 1 and i ~= 9 and i ~= 17 then local isBottomSlots = i > 17 local lastSlot = slots[i-1] lastSlot = _G["Character"..lastSlot] slot:ClearAllPoints() if isBottomSlots then slot:SetPoint("LEFT", lastSlot, "RIGHT", 8, 0) else slot:SetPoint("TOP", lastSlot, "BOTTOM", 0, -7) end end end hooksecurefunc("PaperDollItemSlotButton_Update", function() for i, slot in pairs(slots) do local slotId, _, _ = GetInventorySlotInfo(slot) local quality = GetInventoryItemQuality("player", slotId) slot = _G["Character"..slot] if slot and slot.backdrop then if quality and quality > 0 then slot.backdrop:SetBackdropBorderColor(GetItemQualityColor(quality)) else slot.backdrop:SetBackdropBorderColor(pfUI.cache.er, pfUI.cache.eg, pfUI.cache.eb, pfUI.cache.ea) end if ShaguScore and GetInventoryItemLink("player", slotId) and slot.scoreText then local _, _, itemID = string.find(GetInventoryItemLink("player", slotId), "item:(%d+):%d+:%d+:%d+") local itemLevel = ShaguScore.Database[tonumber(itemID)] or 0 local _, _, itemRarity, _, _, _, _, itemSlot, _ = GetItemInfo(itemID) local r,g,b = GetItemQualityColor((itemRarity or 1)) local score = ShaguScore:Calculate(itemSlot, itemRarity, itemLevel) if score and score > 0 then if quality and quality > 0 then slot.scoreText:SetText(score) slot.scoreText:SetTextColor(r, g, b, 1) else slot.scoreText:SetText("") end else if slot.scoreText then slot.scoreText:SetText("") end end else if slot.scoreText then slot.scoreText:SetText("") end end end end end) end do -- pet frame CreateBackdrop(PetPaperDollFrame, nil, nil, .75) PetPaperDollFrame.backdrop:SetPoint("TOPLEFT", 10, -12) PetPaperDollFrame.backdrop:SetPoint("BOTTOMRIGHT", -32, 76) StripTextures(PetPaperDollFrame) StripTextures(PetAttributesFrame) StripTextures(PetPaperDollFrameExpBar) CreateBackdrop(PetPaperDollFrameExpBar) PetPaperDollFrameExpBar:SetStatusBarTexture("Interface\\AddOns\\pfUI\\img\\bar") PetPaperDollFrameExpBar:ClearAllPoints() PetPaperDollFrameExpBar:SetPoint("BOTTOM", PetModelFrame, "BOTTOM", 0, -120) PetPaperDollCloseButton:Hide() PetModelFrameRotateLeftButton:Hide() PetModelFrameRotateRightButton:Hide() EnableClickRotate(PetModelFrame) PetTrainingPointText:ClearAllPoints() PetTrainingPointText:SetJustifyH("RIGHT") PetTrainingPointText:SetPoint("TOPRIGHT", PetArmorFrame, "BOTTOMRIGHT", 0, -16) PetTrainingPointLabel:ClearAllPoints() PetTrainingPointLabel:SetJustifyH("LEFT") PetTrainingPointLabel:SetPoint("TOPLEFT", PetArmorFrame, "BOTTOMLEFT", 0, -16) PetPaperDollPetInfo:ClearAllPoints() PetPaperDollPetInfo:SetPoint("TOPLEFT", PetModelFrame, "TOPLEFT") PetPaperDollPetInfo:SetFrameLevel(255) PetResistanceFrame:ClearAllPoints() PetResistanceFrame:SetPoint("TOPRIGHT", PetModelFrame, "TOPRIGHT") for i,c in pairs(magicResTextureCords) do local magicResFrame = _G["PetMagicResFrame"..i] magicResFrame:SetWidth(26) magicResFrame:SetHeight(26) CreateBackdrop(magicResFrame) SetAllPointsOffset(magicResFrame.backdrop, magicResFrame, 2) for k,f in pairs({magicResFrame:GetRegions()}) do if f:GetObjectType() == "Texture" then f:SetTexCoord(c[1], c[2], c[3], c[4]) SetAllPointsOffset(f, magicResFrame, 3) end end end end do -- reputation frame CreateBackdrop(ReputationFrame, nil, nil, .75) ReputationFrame.backdrop:SetPoint("TOPLEFT", 10, -12) ReputationFrame.backdrop:SetPoint("BOTTOMRIGHT", -32, 76) StripTextures(ReputationFrame) for i = 1, NUM_FACTIONS_DISPLAYED do local frame = _G["ReputationBar" .. i] local header = _G["ReputationHeader"..i] local name = _G["ReputationBar"..i.."FactionName"] local war = _G["ReputationBar"..i.."AtWarCheck"] StripTextures(frame) CreateBackdrop(frame) frame:SetStatusBarTexture("Interface\\AddOns\\pfUI\\img\\bar") StripTextures(war) war:SetPoint("LEFT", frame, "RIGHT", 0, 0) war.icon = war:CreateTexture(nil, "OVERLAY") war.icon:SetPoint("LEFT", 6, -8) war.icon:SetWidth(32) war.icon:SetHeight(32) war.icon:SetTexture("Interface\\Buttons\\UI-CheckBox-SwordCheck") StripTextures(header) header:SetNormalTexture(nil) header.SetNormalTexture = function() return end header:SetPoint("TOPLEFT", frame, "TOPLEFT", -125, 0) header.text = header:CreateFontString(nil, "OVERLAY") header.text:SetFontObject(GameFontWhite) header.text:SetJustifyH("CENTER") header.text:SetJustifyV("CENTER") header.text:SetPoint("LEFT", 0, 0) header.text:SetWidth(12) header.text:SetHeight(12) header.SetNormalTexture = function(self, tex) self.text:SetText(strfind(tex, "MinusButton") and "-" or "+") end header.backdrop = CreateFrame("Frame", nil, header) header.backdrop:SetAllPoints(header.text) CreateBackdrop(header.backdrop) end StripTextures(ReputationListScrollFrame) SkinScrollbar(ReputationListScrollFrameScrollBar) ReputationDetailFrame:ClearAllPoints() ReputationDetailFrame:SetPoint("TOPLEFT", ReputationFrame, "TOPRIGHT", -26, -28) CreateBackdrop(ReputationDetailFrame) StripTextures(ReputationDetailFrame) SkinCloseButton(ReputationDetailCloseButton, ReputationDetailFrame, -3, -3) SkinCheckbox(ReputationDetailAtWarCheckBox) local texWar = ReputationDetailAtWarCheckBox:GetCheckedTexture() texWar:SetWidth(20) texWar:SetHeight(20) SkinCheckbox(ReputationDetailInactiveCheckBox) SkinCheckbox(ReputationDetailMainScreenCheckBox) end do -- skills frame StripTextures(SkillFrame) CreateBackdrop(SkillFrame, nil, nil, .75) SkillFrame.backdrop:SetPoint("TOPLEFT", 10, -12) SkillFrame.backdrop:SetPoint("BOTTOMRIGHT", -32, 76) SkillFrameCancelButton:Hide() SkillFrameExpandButtonFrame:DisableDrawLayer("BACKGROUND") StripTextures(SkillFrameCollapseAllButton) SkillFrameCollapseAllButton:SetNormalTexture(nil) SkillFrameCollapseAllButton.SetNormalTexture = function(self, tex) self.text:SetText(strfind(tex, "MinusButton") and "-" or "+") end SkillFrameCollapseAllButton:SetPoint("LEFT", SkillFrameExpandButtonFrame, "LEFT", -50, 5) SkillFrameCollapseAllButton.text = SkillFrameCollapseAllButton:CreateFontString(nil, "OVERLAY") SkillFrameCollapseAllButton.text:SetFontObject(GameFontWhite) SkillFrameCollapseAllButton.text:SetJustifyH("CENTER") SkillFrameCollapseAllButton.text:SetJustifyV("CENTER") SkillFrameCollapseAllButton.text:SetPoint("LEFT", 0, 0) SkillFrameCollapseAllButton.text:SetWidth(14) SkillFrameCollapseAllButton.text:SetHeight(14) SkillFrameCollapseAllButton.backdrop = CreateFrame("Frame", nil, SkillFrameCollapseAllButton) SkillFrameCollapseAllButton.backdrop:SetAllPoints(SkillFrameCollapseAllButton.text) CreateBackdrop(SkillFrameCollapseAllButton.backdrop) for i = 1, SKILLS_TO_DISPLAY do local lastframe = _G["SkillRankFrame" .. i-1] local frame = _G["SkillRankFrame" .. i] local border = _G["SkillRankFrame"..i.."Border"] local header = _G["SkillTypeLabel"..i] StripTextures(border) StripTextures(header) StripTextures(frame) frame:SetHeight(12) if lastframe then frame:SetPoint("TOPLEFT", lastframe, "BOTTOMLEFT", 0, -6) end CreateBackdrop(frame) frame:SetStatusBarTexture("Interface\\AddOns\\pfUI\\img\\bar") StripTextures(border) StripTextures(header) header:SetNormalTexture(nil) header:SetPoint("TOPLEFT", frame, "TOPLEFT", -18, 0) header.text = header:CreateFontString(nil, "OVERLAY") header.text:SetFontObject(GameFontWhite) header.text:SetJustifyH("CENTER") header.text:SetJustifyV("CENTER") header.text:SetPoint("LEFT", 0, 0) header.text:SetWidth(10) header.text:SetHeight(10) header.SetNormalTexture = function(self, tex) self.text:SetText(strfind(tex, "MinusButton") and "-" or "+") end header.backdrop = CreateFrame("Frame", nil, header) header.backdrop:SetAllPoints(header.text) CreateBackdrop(header.backdrop) StripTextures(SkillListScrollFrame) SkinScrollbar(SkillListScrollFrameScrollBar) StripTextures(SkillDetailScrollFrame) SkinScrollbar(SkillDetailScrollFrameScrollBar) CreateBackdrop(SkillDetailScrollFrame) SkillDetailScrollFrame:SetPoint("TOPLEFT", SkillListScrollFrame, "BOTTOMLEFT", 0, -10) SkillDetailScrollFrame:SetPoint("BOTTOMRIGHT", SkillFrame, "BOTTOMRIGHT", -45, 90) SkillDetailScrollFrameScrollBar:SetPoint("TOPRIGHT", SkillDetailScrollFrame, "TOPRIGHT", -22, 0) SkillDetailScrollFrameScrollBar:SetPoint("BOTTOMRIGHT", SkillDetailScrollFrame, "BOTTOMRIGHT", -22, 0) StripTextures(SkillDetailStatusBar) CreateBackdrop(SkillDetailStatusBar) SkillDetailStatusBar:SetStatusBarTexture("Interface\\AddOns\\pfUI\\img\\bar") SkillDetailStatusBar:SetParent(SkillDetailScrollFrame) SkillDetailStatusBar:SetFrameLevel(128) SkillDetailStatusBar:ClearAllPoints() SkillDetailStatusBar:SetPoint("TOPLEFT", SkillDetailScrollFrame, "TOPLEFT", 10, -10) SkillDetailStatusBar:SetPoint("TOPRIGHT", SkillDetailScrollFrame, "TOPRIGHT", -30, -40) StripTextures(SkillDetailStatusBarUnlearnButton) SkillDetailStatusBarUnlearnButton:SetPoint("LEFT", SkillDetailStatusBar, "RIGHT", -2, -5) SkillDetailStatusBarUnlearnButton:SetWidth(32) SkillDetailStatusBarUnlearnButton:SetHeight(32) SkillDetailStatusBarUnlearnButton.icon = SkillDetailStatusBarUnlearnButton:CreateTexture(nil, "ARTWORK") SkillDetailStatusBarUnlearnButton.icon:SetPoint("LEFT", 7, 5) SkillDetailStatusBarUnlearnButton.icon:SetWidth(16) SkillDetailStatusBarUnlearnButton.icon:SetHeight(16) SkillDetailStatusBarUnlearnButton.icon:SetTexture("Interface\\Buttons\\UI-GroupLoot-Pass-Up") end end do -- honor tab CreateBackdrop(HonorFrame, nil, nil, .75) HonorFrame.backdrop:SetPoint("TOPLEFT", 10, -12) HonorFrame.backdrop:SetPoint("BOTTOMRIGHT", -32, 76) StripTextures(HonorFrame) HonorFrameProgressBar:SetStatusBarTexture("Interface\\AddOns\\pfUI\\img\\bar") CreateBackdrop(HonorFrameProgressBar) HonorFrameProgressBar:SetHeight(24) end do -- tabs local CharacterFrame = _G["PaperDollFrame"] hooksecurefunc("PetTab_Update", function() CharacterFrameTab1:SetPoint("TOPLEFT", CharacterFrame.backdrop, "BOTTOMLEFT", bpad, -(border + (border == 1 and 1 or 2))) for i=1, 5 do local tab = _G["CharacterFrameTab"..i] SkinTab(tab) tab.backdrop:SetFrameLevel(1) if i ~= 1 then local lastTab = _G["CharacterFrameTab"..(i-1)] if i == 3 and not HasPetUI() then lastTab = _G["CharacterFrameTab"..(i-2)] end tab:ClearAllPoints() tab:SetPoint("LEFT", lastTab, "RIGHT", border*2 + 1, 0) end end end, true) end end)
local S = farming.intllib --= A nice addition from Ademant's grain mod :) -- Rye farming.register_plant("hades_extrafarming:rye", { description = S("Rye seed"), paramtype2 = "meshoptions", inventory_image = "farming_rye_seed.png", steps = 8, place_param2 = 3 }) minetest.override_item("hades_extrafarming:rye", { description = S("Rye"), groups = {food_rye = 1, flammable = 4} }) minetest.override_item("hades_extrafarming:rye_1", {drop = {}}) minetest.override_item("hades_extrafarming:rye_2", {drop = {}}) minetest.override_item("hades_extrafarming:rye_3", {drop = {}}) minetest.register_craft({ output = "hades_extrafarming:flour", recipe = { {"hades_extrafarming:rye", "hades_extrafarming:rye", "hades_extrafarming:rye"}, {"hades_extrafarming:rye", "hades_extrafarming:mortar_pestle", ""} }, replacements = {{"group:food_mortar_pestle", "hades_extrafarming:mortar_pestle"}} }) -- Oats farming.register_plant("hades_extrafarming:oat", { description = S("Oat seed"), paramtype2 = "meshoptions", inventory_image = "farming_oat_seed.png", steps = 8, place_param2 = 3 }) minetest.override_item("hades_extrafarming:oat", { description = S("Oats"), groups = {food_oats = 1, flammable = 4} }) minetest.override_item("hades_extrafarming:oat_1", {drop = {}}) minetest.override_item("hades_extrafarming:oat_2", {drop = {}}) minetest.override_item("hades_extrafarming:oat_3", {drop = {}}) minetest.register_craft({ output = "hades_extrafarming:flour", recipe = { {"hades_extrafarming:oat", "hades_extrafarming:oat", "hades_extrafarming:oat"}, {"hades_extrafarming:oat", "hades_extrafarming:mortar_pestle", ""} }, replacements = {{"group:food_mortar_pestle", "hades_extrafarming:mortar_pestle"}} }) -- Rice farming.register_plant("hades_extrafarming:rice", { description = S("Rice grains"), paramtype2 = "meshoptions", inventory_image = "farming_rice_seed.png", steps = 8, place_param2 = 3 }) minetest.override_item("hades_extrafarming:rice", { description = S("Rice"), groups = {food_rice = 1, flammable = 4} }) minetest.override_item("hades_extrafarming:rice_1", {drop = {}}) minetest.override_item("hades_extrafarming:rice_2", {drop = {}}) minetest.override_item("hades_extrafarming:rice_3", {drop = {}}) minetest.register_craftitem("hades_extrafarming:rice_bread", { description = S("Rice Bread"), inventory_image = "farming_rice_bread.png", on_use = minetest.item_eat(5), groups = {food_rice_bread = 1, flammable = 2, food = 2, eatable = 5} }) minetest.register_craftitem("hades_extrafarming:rice_flour", { description = S("Rice Flour"), inventory_image = "farming_rice_flour.png", groups = {food_rice_flour = 1, flammable = 1} }) minetest.register_craft({ output = "hades_extrafarming:rice_flour", recipe = { {"hades_extrafarming:rice", "hades_extrafarming:rice", "hades_extrafarming:rice"}, {"hades_extrafarming:rice", "hades_extrafarming:mortar_pestle", ""} }, replacements = {{"group:food_mortar_pestle", "hades_extrafarming:mortar_pestle"}} }) minetest.register_craft({ type = "cooking", cooktime = 15, output = "hades_extrafarming:rice_bread", recipe = "hades_extrafarming:rice_flour" }) -- Multigrain flour minetest.register_craftitem("hades_extrafarming:flour_multigrain", { description = S("Multigrain Flour"), inventory_image = "farming_flour_multigrain.png", groups = {food_flour = 1, flammable = 1}, }) minetest.register_craft({ type = "shapeless", output = "hades_extrafarming:flour_multigrain", recipe = { "hades_farming:wheat", "hades_extrafarming:barley", "hades_extrafarming:oat", "hades_extrafarming:rye", "hades_extrafarming:mortar_pestle" }, replacements = {{"group:food_mortar_pestle", "hades_extrafarming:mortar_pestle"}} }) -- Multigrain bread minetest.register_craftitem("hades_extrafarming:bread_multigrain", { description = S("Multigrain Bread"), inventory_image = "farming_bread_multigrain.png", on_use = minetest.item_eat(7), groups = {food_bread = 1, flammable = 2, food = 2, eatable = 7} }) minetest.register_craft({ type = "cooking", cooktime = 15, output = "hades_extrafarming:bread_multigrain", recipe = "hades_extrafarming:flour_multigrain" }) -- Fuels minetest.register_craft({ type = "fuel", recipe = "hades_extrafarming:rice_bread", burntime = 1 }) minetest.register_craft({ type = "fuel", recipe = "hades_extrafarming:bread_multigrain", burntime = 1 }) minetest.register_craft({ type = "fuel", recipe = "hades_extrafarming:rye", burntime = 1 }) minetest.register_craft({ type = "fuel", recipe = "hades_extrafarming:oat", burntime = 1 }) minetest.register_craft({ type = "fuel", recipe = "hades_extrafarming:rice", burntime = 1 })
-- Hello World server -- -- Expects "Hello" from client, replies with "World" -- local zmq = require 'luazmq' local mp = require 'MessagePack' local dumpstring = require 'dump'.dumpstring zmq.init() local address = 'tcp://127.0.0.1:12315' local s = zmq.socket(zmq.ROUTER) s:bind(address) print('server start at ' .. address) while true do local id = s:recv() local data = s:recv() print(id, data) s:send(id, zmq.SNDMORE) s:send(data) --local request = mp.unpack(data) --print(dumpstring(request)) end zmq.shutdown() zmq.terminate()
#!/usr/bin/env lua --[[------------------------------------------------------------------- LuaSrcDiet Compresses Lua source code by removing unnecessary characters. Copyright (c) 2005 Kein-Hong Man <khman@users.sf.net> The COPYRIGHT file describes the conditions under which this software may be distributed (basically a Lua 5-style license.) http://luaforge.net/projects/luasrcdiet/ (TODO) http://www.geocities.com/keinhong/luasrcdiet.html See the ChangeLog for more information. ----------------------------------------------------------------------- -- * See the README file and script comments for notes and caveats. ----------------------------------------------------------------------- --]] --[[------------------------------------------------------------------- -- description and help texts --]]------------------------------------------------------------------- title = [[ LuaSrcDiet: Puts your Lua 5 source code on a diet Version 0.9.1 (20050816) Copyright (c) 2005 Kein-Hong Man The COPYRIGHT file describes the conditions under which this software may be distributed (basically a Lua 5-style license.) ]] USAGE = [[ usage: %s [options] [filenames] options: -h, --help prints usage information -o <file> specify file name to write output --quiet do not display statistics --read-only read file and print token stats --keep-lines preserve line numbering --maximum maximize reduction of source --dump dump raw tokens from lexer -- stop handling arguments example: >%s myscript.lua -o myscript_.lua ]] -- for embedding, we won't set arg[0] local usage, exec if arg[0] then exec = "lua LuaSrcDiet.lua" else exec = "LuaSrcDiet" end usage = string.format(USAGE, exec, exec) -- user options config = {} config.SUFFIX = "_" --[[------------------------------------------------------------------- -- llex is a port of the Lua 5.0.2 lexer (llex.*) to Lua, with the -- token output modified and the code simplified for LuaSrcDiet. ----------------------------------------------------------------------- -- Instead of returning a number, llex:lex() returns strings, like -- "TK_EOS". The other values returned are the original snippet of -- source and the "value" of the lexed token, if applicable. ----------------------------------------------------------------------- -- * Prep lexer with llex:setinput(), llex will close the file handle. -- * For LuaSrcDiet, llex has been changed: -- TK_* returns classes of tokens, made less specific -- "TK_OP" -> operators and punctuations, "TK_KEYWORD" -> keywords -- "TK_EOL" -> end-of-lines, "TK_SPACE" -> whitespace -- "TK_COMMENT" -> comments, "TK_LCOMMENT" -> block comments ----------------------------------------------------------------------- --]] llex = {} ----------------------------------------------------------------------- -- llex initialization stuff ----------------------------------------------------------------------- llex.EOZ = -1 -- end of stream marker llex.keywords = -- Lua 5 keywords "and break do else elseif end false for function if in local \ nil not or repeat return then true until while " llex.str2tok = {} -- for matching keywords for v in string.gfind(llex.keywords, "[^%s]+") do llex.str2tok[v] = true end --[[------------------------------------------------------------------- -- Support functions for Lua lexer (mainly error handling) -- * REMOVED functions luaX_errorline, luaX_errorline, luaX_token2str, -- luaX_syntaxerror, either unused or simplified. ----------------------------------------------------------------------- --]] function llex:checklimit(val, limit, msg) if val > limit then msg = string.format("too many %s (limit=%d)", msg, limit) -- luaX_syntaxerror merged here; removed token reference error(string.format("%s:%d: %s", self.source, self.line, msg)) end end function llex:error(s, token) -- luaX_errorline merged here error(string.format("%s:%d: %s near '%s'", self.source, self.line, s, token)) end function llex:lexerror(s, token) if token then self:error(s, token) else self:error(s, self.buff) end end --[[------------------------------------------------------------------- -- Principal input, output stream functions: nextc, save -- * self.c and self.ch are identical, self.ch is the string version -- * lexer has a token buffer, buff, intended for the lexed value, and -- another buffer, obuff, for the original characters -- it's not a -- very efficient method, but we want both, just in case ----------------------------------------------------------------------- --]] ----------------------------------------------------------------------- -- returns the next character as a number ----------------------------------------------------------------------- function llex:nextc() if self.ipos > self.ilen then if self.z then -- read from specified stream self.ibuf = self.z:read("*l") if self.ibuf == nil then -- close stream self.z:close() self.c = self.EOZ; self.ch = "" self.z = nil return else -- preprocess source line self.ibuf = self.ibuf.."\n" self.ipos = 1 self.ilen = string.len(self.ibuf) -- then grabs the first char (below) end else -- end of string chunk self.c = self.EOZ; self.ch = "" return end end self.c = string.byte(self.ibuf, self.ipos) -- return a character self.ch = string.char(self.c) self.ipos = self.ipos + 1 end ----------------------------------------------------------------------- -- ADDED initialize token buffers ----------------------------------------------------------------------- function llex:initbuff() self.buff = "" self.obuff = "" end ----------------------------------------------------------------------- -- saves given character into buffer, c must be a string ----------------------------------------------------------------------- function llex:save(c) self.buff = self.buff..c end ----------------------------------------------------------------------- -- ADDED saves original character into buffer ----------------------------------------------------------------------- function llex:osave(c) self.obuff = self.obuff..c end ----------------------------------------------------------------------- -- save current character and grabs next character ----------------------------------------------------------------------- function llex:save_and_next() self:save(self.ch) self:osave(self.ch) self:nextc() end ----------------------------------------------------------------------- -- move on to next line, updating line number count ----------------------------------------------------------------------- function llex:inclinenumber() self:nextc() -- skip EOL self.line = self.line + 1 -- number of lines is limited to MAXINT self:checklimit(self.line, 2147483645, "lines in a chunk") end --[[------------------------------------------------------------------- -- Initialize lexer to a particular stream (handle) or string ----------------------------------------------------------------------- --]] ----------------------------------------------------------------------- -- input stream initialization (file handle) ----------------------------------------------------------------------- function llex:setinput(z, source) if z then self.ilen = 0 -- length self.z = z -- input stream end self.ipos = 1 -- position self.line = 1 self.lastline = 1 self.source = source if not self.source then -- default source name self.source = "main" end self:nextc() -- read first char -- shbang handling moved to llex() end ----------------------------------------------------------------------- -- input stream initialization (string) ----------------------------------------------------------------------- function llex:setstring(chunk, source) self.ibuf = chunk self.ilen = string.len(self.ibuf) -- length self:setinput(nil, source) end --[[------------------------------------------------------------------- -- Main Lua lexer functions ----------------------------------------------------------------------- --]] ----------------------------------------------------------------------- -- grab a class of characters ----------------------------------------------------------------------- function llex:readloop(pat) while string.find(self.ch, pat) do self:save_and_next() end end ----------------------------------------------------------------------- -- grab characters until end-of-line ----------------------------------------------------------------------- function llex:readtoeol() while self.ch ~= '\n' and self.c ~= self.EOZ do self:save_and_next() end end ----------------------------------------------------------------------- -- read a number ----------------------------------------------------------------------- function llex:read_numeral(comma) self:initbuff() if comma then self.buff = '.'; self.obuff = '.' end self:readloop("%d") if self.ch == '.' then self:save_and_next() if self.ch == '.' then self:save_and_next() self:lexerror("ambiguous syntax (decimal point x string concatenation)") end end self:readloop("%d") if self.ch == 'e' or self.ch == 'E' then self:save_and_next() -- read 'E' if self.ch == '+' or self.ch == '-' then self:save_and_next() -- optional exponent sign end self:readloop("%d") end local value = tonumber(self.buff) if not value then self:lexerror("malformed number") end return self.obuff, value end ----------------------------------------------------------------------- -- read a long string or long comment ----------------------------------------------------------------------- function llex:read_long_string(comment) local cont = 0 -- nesting local eols = 0 if comment then self.buff = "--[" else self.buff = "[" -- save first '[' end self.obuff = self.buff self:save_and_next() -- pass the second '[' if self.ch == '\n' then -- string starts with a newline? eols = eols + 1 self:osave('\n') self:inclinenumber() -- skip it end while true do -- case ----------------------------------------------------------- if self.c == self.EOZ then -- EOZ if comment then self:lexerror("unfinished long comment", "<eof>") else self:lexerror("unfinished long string", "<eof>") end -- case ----------------------------------------------------------- elseif self.ch == '[' then self:save_and_next() if self.ch == '[' then cont = cont + 1 self:save_and_next() end -- case ----------------------------------------------------------- elseif self.ch == ']' then self:save_and_next() if self.ch == ']' then if cont == 0 then break end cont = cont - 1 self:save_and_next() end -- case ----------------------------------------------------------- elseif self.ch == '\n' then self:save('\n') eols = eols + 1 self:osave('\n') self:inclinenumber() -- case ----------------------------------------------------------- else self:save_and_next() -- endcase -------------------------------------------------------- end end--while self:save_and_next() -- skip the second ']' if comment then return self.obuff, eols end return self.obuff, string.sub(self.buff, 3, -3) end ----------------------------------------------------------------------- -- read a string ----------------------------------------------------------------------- function llex:read_string(del) self:initbuff() self:save_and_next() while self.ch ~= del do -- case ----------------------------------------------------------- if self.c == self.EOZ then self:lexerror("unfinished string", "<eof>") -- case ----------------------------------------------------------- elseif self.ch == '\n' then self:lexerror("unfinished string") -- case ----------------------------------------------------------- elseif self.ch == '\\' then self:osave('\\') self:nextc() -- do not save the '\' if self.c ~= self.EOZ then -- will raise an error next loop local i = string.find("\nabfnrtv", self.ch, 1, 1) if i then -- standard escapes self:save(string.sub("\n\a\b\f\n\r\t\v", i, i)) self:osave(self.ch) if i == 1 then self:inclinenumber() else self:nextc() end elseif string.find(self.ch, "%d") == nil then -- escaped punctuation self:save_and_next() -- handles \\, \", \', and \? else -- \xxx sequence local c = 0 i = 0 repeat c = 10 * c + self.ch -- (coerced) self:osave(self.ch) self:nextc() i = i + 1 until (i >= 3 or not string.find(self.ch, "%d")) if c > 255 then -- UCHAR_MAX self:lexerror("escape sequence too large") end self:save(string.char(c)) end end -- case ----------------------------------------------------------- else self:save_and_next() -- endcase -------------------------------------------------------- end end -- endwhile self:save_and_next() -- skip delimiter return self.obuff, string.sub(self.buff, 2, -2) end --[[------------------------------------------------------------------- -- Lexer feeder function for parser -- * As we are not actually parsing the token stream, we return a token -- class, the original snippet, and the token's value (for strings and -- numbers.) Most token just passes through LuaSrcDiet processing... ----------------------------------------------------------------------- --]] ----------------------------------------------------------------------- -- lex function enhanced to return the snippets required for processing -- * basically adds: TK_COMMENT, TK_LCOMMENT, TK_EOL, TK_SPACE ----------------------------------------------------------------------- function llex:lex() local strfind = string.find while true do local c = self.c -- case ----------------------------------------------------------- if self.line == 1 and self.ipos == 2 -- shbang handling and self.ch == '#' then -- skip first line self:initbuff() self:readtoeol() return "TK_COMMENT", self.obuff end -- case ----------------------------------------------------------- if self.ch == '\n' then -- end of line self:inclinenumber() return "TK_EOL", '\n' -- case ----------------------------------------------------------- elseif self.ch == '-' then -- comment self:nextc() if self.ch ~= '-' then -- '-' operator return "TK_OP", '-' end -- else is a comment '--' or '--[[' self:nextc() if self.ch == '[' then self:nextc() if self.ch == '[' then -- block comment return "TK_LCOMMENT", self:read_long_string(1) -- long comment else -- short comment self.buff = "" self.obuff = "--[" self:readtoeol() return "TK_COMMENT", self.obuff end else -- short comment self.buff = "" self.obuff = "--" self:readtoeol() return "TK_COMMENT", self.obuff end -- case ----------------------------------------------------------- elseif self.ch == '[' then -- literal string self:nextc() if self.ch ~= '[' then return "TK_OP", '[' else return "TK_STRING", self:read_long_string() end -- case ----------------------------------------------------------- elseif self.ch == "\"" or self.ch == "\'" then -- strings return "TK_STRING", self:read_string(self.ch) -- case ----------------------------------------------------------- elseif self.ch == '.' then -- dot, concat, self:nextc() -- or number if self.ch == '.' then self:nextc() if self.ch == '.' then self:nextc() return "TK_OP", '...' else return "TK_OP", '..' end elseif strfind(self.ch, "%d") == nil then return "TK_OP", '.' else return "TK_NUMBER", self:read_numeral(1) end -- case ----------------------------------------------------------- elseif self.c == self.EOZ then -- end of input return "TK_EOS", '' -- case ----------------------------------------------------------- else local op = strfind("=><~", self.ch, 1, 1) -- relational ops local c = self.ch if op then self:nextc() if self.ch ~= '=' then -- single-char ops return "TK_OP", c else -- double-char ops self:nextc() return "TK_OP", c..'=' end else if strfind(self.ch, "%s") then -- whitespace self:initbuff() self:readloop("%s") return "TK_SPACE", self.obuff elseif strfind(self.ch, "%d") then -- number return "TK_NUMBER", self:read_numeral() elseif strfind(self.ch, "[%a_]") then -- identifier -- identifier or reserved word self:initbuff() self:readloop("[%w_]") if self.str2tok[self.buff] then -- reserved word return "TK_KEYWORD", self.buff end return "TK_NAME", self.buff else -- control/symbol if strfind(self.ch, "%c") then self:error("invalid control char", string.format("char(%d)", self.c)) end self:nextc() return "TK_OP", c -- single-chars end end -- endcase -------------------------------------------------------- end--if self.ch end--while end ----------------------------------------------------------------------- -- 'original' lex function, behaves *exactly* like original llex.c -- * currently unused by LuaSrcDiet ----------------------------------------------------------------------- function llex:olex() local _ltok, _lorig, _lval while true do _ltok, _lorig, _lval = self:lex() if _ltok ~= "TK_COMMENT" and _ltok ~= "TK_LCOMMENT" and _ltok ~= "TK_EOL" and _ltok ~= "TK_SPACE" then return _ltok, _lorig, _lval end end end --[[------------------------------------------------------------------- -- Major functions -- * We aren't using lval[] for now, except for TK_LCOMMENT processing, -- perhaps for heavy-duty optimization, like constant optimization... ----------------------------------------------------------------------- --]] stats_c = nil -- number of tokens of a given type stats_l = nil -- bytes occupied by tokens of a given type ltok = nil -- source list of tokens lorig = nil -- source list of original snippets lval = nil -- source list of actual token values ntokens = 0 -- number of tokens processed from file ----------------------------------------------------------------------- -- "classes" of tokens; the last 4 aren't standard in llex.c -- * arrangement/count significant!!! hardcoded for stats display ----------------------------------------------------------------------- ttypes = { "TK_KEYWORD", "TK_NAME", "TK_NUMBER", "TK_STRING", "TK_OP", "TK_EOS", "TK_COMMENT", "TK_LCOMMENT", "TK_EOL", "TK_SPACE", } ----------------------------------------------------------------------- -- reads source file and create token array + fill in statistics ----------------------------------------------------------------------- function LoadFile(filename) if not filename and type(filename) ~= "string" then error("invalid filename specified") end stats_c = {} stats_l = {} ltok = {} lorig = {} lval = {} ntokens = 0 for _, i in ipairs(ttypes) do -- init counters stats_c[i] = 0; stats_l[i] = 0 end --------------------------------------------------------------------- local INF = io.open(filename, "rb") if not INF then error("cannot open \""..filename.."\" for reading") end llex:setinput(INF, filename) local _ltok, _lorig, _lval local i = 0 while _ltok ~= "TK_EOS" do _ltok, _lorig, _lval = llex:lex() i = i + 1 ltok[i] = _ltok lorig[i] = _lorig lval[i] = _lval stats_c[_ltok] = stats_c[_ltok] + 1 stats_l[_ltok] = stats_l[_ltok] + string.len(_lorig) end ntokens = i -- INF closed by llex end ----------------------------------------------------------------------- -- returns token tables containing valid tokens only (for verification) ----------------------------------------------------------------------- function GetRealTokens(stok, sorig, stokens) local rtok, rorig, rtokens = {}, {}, 0 for i = 1, stokens do local _stok = stok[i] local _sorig = sorig[i] if _stok ~= "TK_COMMENT" and _stok ~= "TK_LCOMMENT" and _stok ~= "TK_EOL" and _stok ~= "TK_SPACE" then rtokens = rtokens + 1 rtok[rtokens] = _stok rorig[rtokens] = _sorig end end return rtok, rorig, rtokens end ----------------------------------------------------------------------- -- display only source token statistics (for --read-only option) ----------------------------------------------------------------------- function DispSrcStats(filename) local underline = "--------------------------------\n" LoadFile(filename) print(title) io.stdout:write("Statistics for: "..filename.."\n\n" ..string.format("%-14s%8s%10s\n", "Elements", "Count", "Bytes") ..underline) local total_c, total_l, tok_c, tok_l = 0, 0, 0, 0 for j = 1, 10 do local i = ttypes[j] local c, l = stats_c[i], stats_l[i] total_c = total_c + c total_l = total_l + l if j <= 6 then tok_c = tok_c + c tok_l = tok_l + l end io.stdout:write(string.format("%-14s%8d%10d\n", i, c, l)) if i == "TK_EOS" then io.stdout:write(underline) end end io.stdout:write(underline ..string.format("%-14s%8d%10d\n", "Total Elements", total_c, total_l) ..underline ..string.format("%-14s%8d%10d\n", "Total Tokens", tok_c, tok_l) ..underline.."\n") end ----------------------------------------------------------------------- -- display source and destination stats (enabled by default) ----------------------------------------------------------------------- function DispAllStats(srcfile, src_c, src_l, destfile, dest_c, dest_l) local underline = "--------------------------------------------------\n" print(title) local stot_c, stot_l, stok_c, stok_l = 0, 0, 0, 0 local dtot_c, dtot_l, dtok_c, dtok_l = 0, 0, 0, 0 io.stdout:write("Statistics for: "..srcfile.." -> "..destfile.."\n\n" ..string.format("%-14s%8s%10s%8s%10s\n", "Lexical", "Input", "Input", "Output", "Output") ..string.format("%-14s%8s%10s%8s%10s\n", "Elements", "Count", "Bytes", "Count", "Bytes") ..underline) for j = 1, 10 do local i = ttypes[j] local s_c, s_l = src_c[i], src_l[i] local d_c, d_l = dest_c[i], dest_l[i] stot_c = stot_c + s_c stot_l = stot_l + s_l dtot_c = dtot_c + d_c dtot_l = dtot_l + d_l if j <= 6 then stok_c = stok_c + s_c stok_l = stok_l + s_l dtok_c = dtok_c + d_c dtok_l = dtok_l + d_l end io.stdout:write(string.format("%-14s%8d%10d%8d%10d\n", i, s_c, s_l, d_c, d_l)) if i == "TK_EOS" then io.stdout:write(underline) end end io.stdout:write(underline ..string.format("%-14s%8d%10d%8d%10d\n", "Total Elements", stot_c, stot_l, dtot_c, dtot_l) ..underline ..string.format("%-14s%8d%10d%8d%10d\n", "Total Tokens", stok_c, stok_l, dtok_c, dtok_l) ..underline.."\n") end ----------------------------------------------------------------------- -- token processing function ----------------------------------------------------------------------- function ProcessToken(srcfile, destfile) LoadFile(srcfile) if ntokens < 1 then error("no tokens to process") end local dtok = {} -- processed list of tokens local dorig = {} -- processed list of original snippets local dtokens = 0 -- number of tokens generated local stok, sorig, stokens = -- src tokens for verification GetRealTokens(ltok, lorig, ntokens) --------------------------------------------------------------------- -- saves specified token to the destination token list --------------------------------------------------------------------- local function savetok(src) dtokens = dtokens + 1 dtok[dtokens] = ltok[src] dorig[dtokens] = lorig[src] end --------------------------------------------------------------------- -- check if token at location is whitespace-equivalent --------------------------------------------------------------------- local function iswhitespace(i) local tok = ltok[i] if tok == "TK_SPACE" or tok == "TK_EOL" or tok == "TK_COMMENT" or tok == "TK_LCOMMENT" then return true end end --------------------------------------------------------------------- -- compare two tokens and returns whitespace if needed in between -- * note that some comparisons won't occur in Lua code; we assume -- no knowledge of Lua syntax, only knowledge of lexical analysis --------------------------------------------------------------------- local function whitesp(previ, nexti) local p = ltok[previ] local n = ltok[nexti] -- if next token is a whitespace, remove current whitespace token if iswhitespace(n) then return "" end -- otherwise we are comparing non-whitespace tokens, so we use -- the following optimization rules... ------------------------------------------------------------------- if p == "TK_OP" then if n == "TK_NUMBER" then -- eg . .123 if string.sub(lorig[nexti], 1, 1) == "." then return " " end end return "" ------------------------------------------------------------------- elseif p == "TK_KEYWORD" or p == "TK_NAME" then if n == "TK_KEYWORD" or n == "TK_NAME" then return " " elseif n == "TK_NUMBER" then -- eg foo.123 if string.sub(lorig[nexti], 1, 1) == "." then return "" end return " " end return "" ------------------------------------------------------------------- elseif p == "TK_STRING" then return "" ------------------------------------------------------------------- elseif p == "TK_NUMBER" then if n == "TK_NUMBER" then return " " elseif n == "TK_KEYWORD" or n == "TK_NAME" then -- eg 123 e4 local c = string.sub(lorig[nexti], 1, 1) if string.lower(c) == "e" then return " " end end return "" ------------------------------------------------------------------- else -- should never arrive here error("token comparison failed") end end --------------------------------------------------------------------- -- main processing loop (pass 1) --------------------------------------------------------------------- local i = 1 -- token position local linestart = true -- true at the start of a line local tok = "" -- current token local prev = 0 -- index of previous non-whitespace tok while true do tok = ltok[i] ------------------------------------------------------------------- if tok == "TK_SPACE" then if linestart then -- delete leading whitespace lorig[i] = "" else -- remove in-between whitespace if possible lorig[i] = whitesp(prev, i + 1) end savetok(i) ------------------------------------------------------------------- elseif tok == "TK_NAME" or tok == "TK_KEYWORD" or tok == "TK_OP" or tok == "TK_STRING" or tok == "TK_NUMBER" then -- these are all unchanged prev = i savetok(i) linestart = false ------------------------------------------------------------------- elseif tok == "TK_EOL" then if linestart then if config.KEEP_LINES then savetok(i) linestart = true end -- otherwise it's an empty line, drop it else savetok(i) linestart = true end ------------------------------------------------------------------- elseif tok == "TK_COMMENT" then -- must keep shbang for correctness, force a TK_EOL too if i == 1 and string.sub(lorig[i], 1, 1) == "#" then savetok(i) linestart = false end -- don't change linestart; the now empty line can be consumed ------------------------------------------------------------------- elseif tok == "TK_LCOMMENT" then local eols = nil if config.KEEP_LINES then -- preserve newlines inside long comments if lval[i] > 0 then eols = string.rep("\n", lval[i]) end end if iswhitespace(i + 1) then lorig[i] = eols or "" else lorig[i] = eols or " " end savetok(i) ------------------------------------------------------------------- elseif tok == "TK_EOS" then savetok(i) break ------------------------------------------------------------------- else error("unidentified token encountered") end--if tok i = i + 1 end--while --------------------------------------------------------------------- -- aggressive end-of-line removal pass (pass 2) --------------------------------------------------------------------- if config.ZAP_EOLS then ltok, lorig = {}, {} ntokens = 0 -- redo source table by removing deleted bits for i = 1, dtokens do local tok = dtok[i] local orig = dorig[i] if orig ~= "" or tok == "TK_EOS" then ntokens = ntokens + 1 ltok[ntokens] = tok lorig[ntokens] = orig end end -- try to remove end-of-lines by comparing token pairs dtok, dorig = {}, {} dtokens = 0 i = 1 tok, prev = "", "" while tok ~= "TK_EOS" do tok = ltok[i] if tok == "TK_EOL" and prev ~= "TK_COMMENT" then -- TK_COMMENT to trap shbang case if whitesp(i - 1, i + 1) == " " then -- can't delete savetok(i) end else prev = tok savetok(i) end i = i + 1 end--while end --------------------------------------------------------------------- -- write output file --------------------------------------------------------------------- local dest = table.concat(dorig) -- join up source local OUTF = io.open(destfile, "wb") if not OUTF then error("cannot open \""..destfile.."\" for writing") end OUTF:write(dest) io.close(OUTF) --------------------------------------------------------------------- -- post processing: verification and reporting --------------------------------------------------------------------- src_stats_c = stats_c src_stats_l = stats_l LoadFile(destfile) -- reload to verify output okay dtok, dorig, dtokens = -- dest tokens for verification GetRealTokens(ltok, lorig, ntokens) -- WARNING the following WON'T WORK when an optimization method -- changes the real token stream in any way if stokens ~= dtokens then error("token count incorrect") end for i = 1, stokens do if stok[i] ~= dtok[i] or sorig[i] ~= dorig[i] then error("token verification by comparison failed") end end if not config.QUIET then DispAllStats(srcfile, src_stats_c, src_stats_l, destfile, stats_c, stats_l) end end ----------------------------------------------------------------------- -- dump token (diagnostic feature) ----------------------------------------------------------------------- function DumpTokens(srcfile) local function Esc(v) return string.format("%q", v) end LoadFile(srcfile) for i = 1, ntokens do local ltok, lorig, lval = ltok[i], lorig[i], lval[i] -- display only necessary information if ltok == "TK_KEYWORD" or ltok == "TK_NAME" or ltok == "TK_NUMBER" or ltok == "TK_STRING" or ltok == "TK_OP" then print(ltok, lorig) elseif ltok == "TK_COMMENT" or ltok == "TK_LCOMMENT" or ltok == "TK_SPACE" then print(ltok, Esc(lorig)) elseif ltok == "TK_EOS" or ltok == "TK_EOL" then print(ltok) else error("unknown token type encountered") end end end ----------------------------------------------------------------------- -- perform per-file handling ----------------------------------------------------------------------- function DoFiles(files) for i, srcfile in ipairs(files) do local destfile ------------------------------------------------------------------- -- find and replace extension for filenames ------------------------------------------------------------------- local extb, exte = string.find(srcfile, "%.[^%.%\\%/]*$") local basename, extension = srcfile, "" if extb and extb > 1 then basename = string.sub(srcfile, 1, extb - 1) extension = string.sub(srcfile, extb, exte) end destfile = config.OUTPUT_FILE or basename..config.SUFFIX..extension if srcfile == destfile then error("output filename identical to input filename") end ------------------------------------------------------------------- -- perform requested operations ------------------------------------------------------------------- if config.DUMP then DumpTokens(srcfile) elseif config.READ_ONLY then DispSrcStats(srcfile) else ProcessToken(srcfile, destfile) end end--for end --[[------------------------------------------------------------------- -- Command-line interface ----------------------------------------------------------------------- --]] function main() --------------------------------------------------------------- -- handle arguments --------------------------------------------------------------- if table.getn(arg) == 0 then print(title..usage) return end local files, i = {}, 1 while i <= table.getn(arg) do local a, b = arg[i], arg[i + 1] if string.sub(a, 1, 1) == "-" then -- handle options here if a == "-h" or a == "--help" then print(title) print(usage) return elseif a == "--quiet" then config.QUIET = true elseif a == "--read-only" then config.READ_ONLY = true elseif a == "--keep-lines" then config.KEEP_LINES = true elseif a == "--maximum" then config.MAX = true elseif a == "--dump" then config.DUMP = true elseif a == "-o" then if not b then error("-o option needs a file name") end config.OUTPUT_FILE = b i = i + 1 elseif a == "--" then break -- ignore rest of args else error("unrecognized option "..a) end else table.insert(files, a) -- potential filename end i = i + 1 end--while --------------------------------------------------------------- if config.MAX then -- set flags for maximum reduction config.KEEP_LINES = false config.ZAP_EOLS = true end if table.getn(files) > 0 then if table.getn(files) > 1 then if config.OUTPUT_FILE then error("with -o, only one source file can be specified") end end DoFiles(files) else print("LuaSrcDiet: nothing to do!") end end ----------------------------------------------------------------------- -- program entry point ----------------------------------------------------------------------- if not TEST then local OK, msg = pcall(main) if not OK then print("* Run with option -h or --help for usage information") print(msg) end end -- end of script
c_vertexes={} c_colors={} c_segments={} local mn2=50 local mn1=50 local fk=2*math.pi local r1=4000 local r2=4000 local r3=4000 local index1 = 0 local c1=0x00903050 local segm1 =fk/mn1 local segm2 =fk/mn2/2 for k=0,mn2 do local z=r3*math.cos(k*segm2) for i=1,mn1 do local x=math.sin(i*segm1)*r1*math.sin(k*segm2) local y=math.cos(i*segm1)*r2*math.sin(k*segm2) table.insert(c_vertexes,{x,y,z}) table.insert(c_colors,c1) if i~=mn1 then table.insert(c_segments,{index1,index1+1}) else table.insert(c_segments,{index1,index1+1-mn1}) end index1=index1+1 end end index1= 0 for k=0,mn2-1 do for i=1,mn1 do table.insert(c_segments,{index1,index1+mn1}) index1=index1+1 end end meshes = { { vertexes = c_vertexes, segments = c_segments, colors = c_colors } }
-- VARIABLES =================================================================== -- [components] local owner_pathFinding = nil local owner_transform = nil local owner_rigidBody = nil local isConstruct = false --Enemy INFO ParticleSpeed = 20 myMoveIndex = 2 local telePoints = nil local finalPos = Vector3() local currIndex = 1 isReverse = false local direction = Vector3() local sizeTele = 0 local Spawner = nil local spawnerScript = nil moveIndex = 1 local moveDelayTimer = 20.0 --Amount of time it delays for start and then end DelayAmount = 3.0 --To Delay when it reaches each checkpoint DelayYet = false local moveVecNow = Vector3(0.0,1.0,0.0) -- FUNCTIONS =================================================================== function Constructor() end function MyConstructor() -- Find components write("MyConstructor is called") owner_transform = owner:GetComponent("Transform") owner_rigidBody = owner:GetComponent("RigidBody") Spawner = CurrentLayer():GetObject("Slime_Spawner") if(Spawner ~= nil) then spawnerScript = Spawner:GetLuaScript("Enemy_Spawner.lua") end levelName = PlayerPref_GetString ("CurrentLevel") --Take note in case of future levels? if(levelName == "Level_Changi")then telePathName = PlayerPref_GetStringArray("NamesWaypoints", levelName) nextPos = telePathName[ToInt(moveIndex)] telePoints = PlayerPref_GetVector3Array(nextPos, levelName) else telePoints = PlayerPref_GetVector3Array("TeleportTrail", levelName) end owner_startpos = owner_transform:GetWorldPosition() sizeTele = #telePoints --Uses waypoints if(isReverse)then currIndex = sizeTele - 1 finalPos = telePoints[1] else currIndex = 2 finalPos = telePoints[sizeTele] end direction = telePoints[currIndex] - owner_startpos direction = direction:Normalized() isConstruct = true particle = owner:GetComponent("ParticleEmitter_Circle") particle:AddAttractor(owner:GetID()) --particle:SetEmitRate(2.5) owner:GetComponent("Attractor"):SetForce(1) --script = owner:GetLuaScript("ParticleEmission.lua") --if (script ~= nil) then -- script:SetVariable("interval", 0.2) -- script:SetVariable("emitRate", 2500) -- script:SetVariable("speed", 10) --else -- write("ParticleEmission.lua is missing") --end end function OnUpdate(dt) if(isConstruct)then if (moveDelayTimer < DelayAmount) then moveDelayTimer = moveDelayTimer + dt MoveIdle(dt) else --:GetComponent("Attractor"):SetForce(0.15) MoveToEnd() end end end function MoveIdle(dt) currVel = owner_rigidBody:GetVelocity() owner_rigidBody:AddForce( moveVecNow* 20.0) if(currVel:y() <= -7.0)then moveVecNow = Vector3(0.0,1.0,0.0) elseif(currVel:y() >= 7.0)then moveVecNow = Vector3(0.0,-1.0,0.0) end end -- FUNCTIONS RELATED TO MOVEMENT =============================================== function MoveToEnd() -- Distance check to end pt if(DistanceCheck() == true)then if(not DelayYet)then moveDelayTimer = 0.0 moveVecNow = Vector3(0.0,1.0,0.0) owner_rigidBody:AddForce( moveVecNow* 20.0) DelayAmount = 15.0 DelayYet = true return end if(spawnerScript ~=nil)then spawnerScript:CallFunction("IdleEnd") end owner:Destroy() return end ChangeWayPoint() owner_rigidBody:SetVelocity(direction * ParticleSpeed) end function DistanceCheck() currePos = owner_transform:GetWorldPosition() distance = finalPos - currePos distanceLength = distance:Length() if (distanceLength < 2.0) then myVel = owner_rigidBody:GetVelocity() myVel.x = 0 myVel.z = 0 owner_rigidBody:SetVelocity(myVel) return true end return false end function ChangeWayPoint() currePos = owner_transform:GetWorldPosition() distance = telePoints[currIndex] - currePos distanceLength = distance:Length() direction = telePoints[currIndex] - currePos direction = direction:Normalized() --!NOTE! this distance cant be more than the distancecheck --distancelength if (distanceLength < 1.0) then if(isReverse)then currIndex = currIndex - 1 else currIndex = currIndex + 1 end owner_rigidBody:SetVelocity(Vector3()) direction = telePoints[currIndex] - currePos direction = direction:Normalized() end end
local activityConfig = require "config.activityConfig" local equipConfig = require "config.equipmentConfig" local HeroScroll = require "hero.HeroScroll" local CemeteryConf = require "config.cemeteryConfig" local SmallTeamDungeonConf = require "config.SmallTeamDungeonConf" local openLevel = require "config.openLevel" local newSelectTeam = {} function newSelectTeam:Start(data) --self:init(data) end function newSelectTeam:init(data) if not data then return end self:initData(data) self:initUi() self:initGuide() end function newSelectTeam:initGuide() module.guideModule.PlayByType(102,0.2) end function newSelectTeam:initData(data) if data then self.chapterId = data.chapterId end self.cfg = activityConfig.GetAllActivityTitle(4, self.chapterId) or {} table.sort(self.cfg, function(a, b) if a.lv_limit == b.lv_limit then return a.id > b.id end return a.lv_limit < b.lv_limit end) end function newSelectTeam:initUi() self.view = CS.SGK.UIReference.Setup(self.gameObject) self:initTop() self:initScrollView() end function newSelectTeam:initTop() local _itemList = { [1] = {id = 90023}, [2] = {id = 90024}, } for i = 1, 2 do local _view = self.view.root["item"..i] _view.number[UI.Text].text = tostring(module.ItemModule.GetItemCount(_itemList[i].id)) CS.UGUIClickEventListener.Get(_view.gameObject).onClick = function() DialogStack.PushPrefStact("ItemDetailFrame", {id = _itemList[i].id, type = utils.ItemHelper.TYPE.ITEM, InItemBag = 2},UnityEngine.GameObject.FindWithTag("UITopRoot").gameObject) end end if openLevel.GetStatus(1331) then self.view.root.luckBtn:SetActive(true) else self.view.root.luckBtn:SetActive(false) end CS.UGUIClickEventListener.Get(self.view.root.luckBtn.gameObject).onClick = function() DialogStack.PushPref("fightResult/luckyCoin") end end function newSelectTeam:initScrollView() self.scrollView = self.view.root.ScrollView[CS.UIMultiScroller] self.scrollView.RefreshIconCallback = function (obj, idx) local _view = CS.SGK.UIReference.Setup(obj.gameObject) local _cfg = self.cfg[idx + 1] local pic_cfg = CemeteryConf.Getteam_battle_conf(_cfg.id) --print(sprinttb(pic_cfg)) --_view.root.icon[UI.Image]:LoadSprite("guanqia/".._cfg.use_picture) _view.root.IconMask.icon[UI.Image]:LoadSpriteWithExt("guanqia/"..pic_cfg.bg_xditu..".jpg") if pic_cfg.bg_xditu_2 and pic_cfg.bg_xditu_2 ~= "" and pic_cfg.bg_xditu_2 ~= "0" then _view.root.IconMask.icon2:SetActive(true) _view.root.IconMask.icon2[UI.Image]:LoadSpriteWithExt("guanqia/"..pic_cfg.bg_xditu_2..".png") else _view.root.IconMask.icon2:SetActive(false) end _view.root.name[UI.Text].text = _cfg.name _view.root.time[UI.Text].text = _cfg.activity_time local _reward = activityConfig.GetReward(_cfg.id) or {} --_view.root.ScrollView[CS.UIMultiScroller].RefreshIconCallback = function (rObj, rIdx) for rIdx=0,#_reward-1 do local rObj = _view.root.item local _rView = CS.SGK.UIReference.Setup(rObj.gameObject) local _rCfg = _reward[rIdx + 1] local _equip = equipConfig.GetConfig(_rCfg.id) _rView.IconFrame:SetActive(false) _rView.suit:SetActive(false) --if _equip then local _icon = utils.IconFrameHelper.Create(_rView,{id = _rCfg.id,type = _rCfg.type,showDetail = true}) _icon[UnityEngine.RectTransform].anchoredPosition = CS.UnityEngine.Vector2(0,0) -- local suitTab = HeroScroll.GetSuitConfig(_equip.suit_id) -- if suitTab and next(suitTab) ~= nil then -- local suitCfg = suitTab[2][_equip.quality] -- if suitCfg then -- _rView.suit:SetActive(true) -- _rView.suit.Frame[CS.UGUISpriteSelector].index = _equip.quality -1 -- _rView.suit.Icon[UI.Image]:LoadSprite("icon/"..suitCfg.icon) -- -- utils.IconFrameHelper.Create(_rView.IconFrame, {customCfg = { -- -- icon = suitCfg.icon, -- -- role_stage = -1, -- -- star = 0, -- -- level = 0, -- -- }, type = 42}) -- CS.UGUIClickEventListener.Get(_rView.suit.gameObject).onClick = function() -- DialogStack.PushPrefStact("dataBox/suitsManualFrame", {suitId = _equip.suit_id,hideSuits = true,quality = _equip.quality}) -- end -- end -- end --else --ERROR_LOG(_cfg.id, _rCfg.id, "error") --end rObj:SetActive(true) end --_view.root.ScrollView[CS.UIMultiScroller].DataCount = #_reward _view.root.bg:SetActive(not (_cfg.lv_limit > module.HeroModule.GetManager():Get(11000).level)) _view.root.difficulty:SetActive(_cfg.id > 1000 and (_cfg.lv_limit <= module.HeroModule.GetManager():Get(11000).level)) --_view.root.difficulty:SetActive(_cfg.id > 1000) _view.root.name:SetActive(not (_cfg.lv_limit > module.HeroModule.GetManager():Get(11000).level)) _view.root.lock:SetActive(_cfg.lv_limit > module.HeroModule.GetManager():Get(11000).level) local _battleCfg = SmallTeamDungeonConf.GetTeam_pve_fight(_cfg.isunique) local _count = module.CemeteryModule.GetTEAMRecord(_battleCfg.idx[1][1].gid) or 0 --print("kkkkk",_battleCfg.idx[1][1].drop1,module.ItemModule.GetItemCount(_battleCfg.idx[1][1].drop1)) _view.root.tip:SetActive((not _view.root.lock.activeSelf) and _count == 0) _view.root.ExtraReward:SetActive(module.ItemModule.GetItemCount(_battleCfg.idx[1][1].drop1) ~= 0 and (not (_cfg.lv_limit > module.HeroModule.GetManager():Get(11000).level))) if _view.root.lock.activeSelf then _view.root.IconMask.icon[UI.Image].color = {r = 94 / 255, g = 94 / 255, b = 94 / 255, a = 1} _view.root.IconMask.icon2[UI.Image].color = {r = 94 / 255, g = 94 / 255, b = 94 / 255, a = 1} else _view.root.IconMask.icon[UI.Image].color = {r = 1, g = 1, b = 1, a = 1} _view.root.IconMask.icon2[UI.Image].color = {r = 1, g = 1, b = 1, a = 1} end --_view.root.ScrollView:SetActive(not _view.root.lock.activeSelf) if _view.root.lock.activeSelf then _view.root.lock.info[UI.Text].text = SGK.Localize:getInstance():getValue("tips_lv_02", _cfg.lv_limit) end local _one, _ten = module.CemeteryModule.Query_Pve_Schedule(_cfg.id) -- _view.root.double:SetActive(_ten and _ten > 0 and not _view.root.lock.activeSelf) -- if _ten and _ten > 0 then -- _view.root.double.number[UI.Text].text = tostring(_ten) -- end _view.root.double:SetActive(false) CS.UGUIClickEventListener.Get(_view.root.IconMask.icon.gameObject).onClick = function() if not _view.root.lock.activeSelf then module.guideModule.SelectChapterGuide[self.chapterId] = idx + 1 --DialogStack.Push("TeamPveEntrance", {gid = _cfg.isunique}) DialogStack.Push("newSelectMap/activityInfo", {gid = _cfg.isunique}) else showDlgError(nil, "等级不足") end end obj:SetActive(true) end local TotalHeight = self.view.root.ScrollView[UnityEngine.RectTransform].rect.height--sizeDelta.y local Item_Height = CS.SGK.UIReference.Setup(self.scrollView.itemPrefab)[UnityEngine.RectTransform].sizeDelta.y self.scrollView.DataCount = #self.cfg if module.guideModule.SelectChapterGuide[self.chapterId] then local _idx = module.guideModule.SelectChapterGuide[self.chapterId] if _idx - 1 > math.abs(math.floor(TotalHeight/Item_Height)) then self.scrollView:ScrollMove(_idx - 1 - math.abs(math.floor(TotalHeight/Item_Height))) end --self.scrollView:ScrollMove(module.guideModule.SelectChapterGuide[self.chapterId] - 1 - 1) else local _idx = 1 for i,v in ipairs(self.cfg) do if v.lv_limit > module.HeroModule.GetManager():Get(11000).level then _idx = i break end end if _idx-1 > math.abs(math.floor(TotalHeight/Item_Height)) then self.scrollView:ScrollMove(_idx - 1 - math.abs(math.floor(TotalHeight/Item_Height))) --self.scrollView:ScrollMove(_idx - 1 - 1) end end end function newSelectTeam:listEvent() return { "LOCAL_GUIDE_CHANE", } end function newSelectTeam:onEvent(event, data) if event == "LOCAL_GUIDE_CHANE" then self:initGuide() end end return newSelectTeam
--[[ Copyright (c) 2016-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. ]]-- local tnt = require 'torchnet.env' local argcheck = require 'argcheck' local utils = require 'torchnet.utils' local doc = require 'argcheck.doc' doc[[ ### tnt.transform *Torchnet* provides a set of general data transformations. These transformations are either directly on the data (e.g., normalization) or on their structure. This is particularly handy when manipulating [tnt.Dataset](#tnt.Dataset). Most of the transformations are simple but can be [composed](#transform.compose) or [merged](#transform.merge). ]] local transform = {} tnt.transform = transform local unpack = unpack or table.unpack doc[[ <a name="transform.identity"> #### transform.identity(...) The identity transform takes any input and return it as it is. For example, this function is useful when composing transformations on data from multiple sources, and some of the sources must not be transformed. ]] transform.identity = function(...) local args = {...} return function() return unpack(args) end end transform.compose = argcheck{ doc = [[ <a name = "transform.compose"> #### transform.compose(@ARGP) @ARGT This function takes a `table` of functions and composes them to return one transformation. This function assumes that the table of transformations is indexed by contiguous ordered keys starting at 1. The transformations are composed in the ascending order. For example, the following code: ```lua > f = transform.compose{ [1] = function(x) return 2*x end, [2] = function(x) return x + 10 end, foo = function(x) return x / 2 end, [4] = function(x) return x - x end } > f(3) 16 ``` is equivalent to compose the transformations stored in [1] and [2], i.e., defining the following transformation: ```lua > f = function(x) return 2*x + 10 end ``` Note that transformations stored with keys `foo` and `4` are ignored. ]], {name='transforms', type='table'}, call = function(transforms) for k,v in ipairs(transforms) do assert(type(v) == 'function', 'table of functions expected') end transforms = utils.table.copy(transforms) return function(z) for _, trans in ipairs(transforms) do z = trans(z) end return z end end } transform.merge = argcheck{ doc = [[ <a name = "transform.merge"> #### transform.merge(@ARGP) @ARGT This function takes a `table` of transformations and merge them into one transformation. Once apply to an input, this transformation will produce a `table` of output, containing the transformed input. For example, the following code: ```lua > f = transform.merge{ [1] = function(x) return 2*x end, [2] = function(x) return x + 10 end, foo = function(x) return x / 2 end, [4] = function(x) return x - x end } ``` produces a function which applies a set of transformations to the same input: ```lua > f(3) { 1 : 6 2 : 13 foo : 1.5 4 : 0 } ``` ]], {name='transforms', type='table'}, call = function(transforms) for k,v in pairs(transforms) do assert(type(v) == 'function', 'table of functions expected') end transforms = utils.table.copy(transforms) return function(z) local newz = {} for k, trans in pairs(transforms) do newz[k] = trans(z) end return utils.table.mergetensor(newz) end end } transform.tablenew = argcheck{ doc = [[ <a name = "transform.tablenew"> #### transform.tablenew() This function creates a new table of functions from an existing table of functions. ]], call = function() return function(func) local tbl = {} for k,v in pairs(func) do tbl[k] = v end return tbl end end } transform.tableapply = argcheck{ doc = [[ <a name = "transform.tableapply"> #### transform.tableapply(@ARGP) @ARGT This function applies a transformation to a table of input. It return a table of output of the same size as the input. For example, the following code: ```lua > f = transform.tableapply(function(x) return 2*x end) ``` produces a function which multiplies any input by 2: ```lua > f({[1] = 1, [2] = 2, foo = 3, [4] = 4}) { 1 : 2 2 : 4 foo : 6 4 : 8 } ``` ]], {name='transform', type='function'}, call = function(transform) return function(tbl) return utils.table.foreach(tbl, transform) end end } transform.tablemergekeys = argcheck{ doc = [[ <a name = "transform.tablemergekeys"> #### transform.tablemergekeys() This function merges tables by key. More precisely, the input must be a `table` of `table` and this function will reverse the table orderto make the keys from the nested table accessible first. For example, if the input is: ```lua > x = { sample1 = {input = 1, target = "a"} , sample2 = {input = 2, target = "b", flag = "hard"} ``` Then apply this function will produce: ```lua > transform.tablemergekeys(x) { input : { sample1 : 1 sample2 : 2 } target : { sample1 : "a" sample2 : "b" } flag : { sample2: "hard" } } ``` ]], call = function() return function(tbl) local mergedtbl = {} for idx, elem in pairs(tbl) do for key, value in pairs(elem) do if not mergedtbl[key] then mergedtbl[key] = {} end mergedtbl[key][idx] = value end end return mergedtbl end end } transform.makebatch = argcheck{ doc = [[ <a name = "transform.makebatch"> #### transform.makebatch(@ARGP) @ARGT This function is used in many `tnt.Dataset` to format samples in the format used by the `tnt.Engine`. This function first [merges keys](#transform.tablemergekeys) to produces a table of output. Then, transform this table into a tensor by either using a `merge` transformation provided by the user or by simply concatenating the table into a tensor directly. This function uses the [compose](#transform.compose) transform to apply successive transformations. ]], {name='merge', type='function', opt=true}, call = function(merge) local makebatch if merge then makebatch = transform.compose{ transform.tablemergekeys(), merge } else makebatch = transform.compose{ transform.tablemergekeys(), transform.tableapply( function(field) if utils.table.canmergetensor(field) then return utils.table.mergetensor(field) else return field end end ) } end return function(samples) assert(type(samples) == 'table', 'makebatch: table of samples expected') return makebatch(samples) end end } transform.randperm = argcheck{ doc = [[ <a name = "transform.randperm"> #### transform.randperm(@ARGP) @ARGT This function create a vector containing a permutation of the indices from 1 to `size`. This vector is a `LongTensor` and `size` must be a number. Once the vector created, this function can be used to call a specific indices in it. For example: ```lua > p = transform.randperm(3) ``` creates a function `p` which contains a permutation of indices: ```lua > p(1) 2 > p(2) 1 > p(3) 3 ``` ]], {name="size", type="number"}, call = function(size) local perm = torch.randperm(size, 'torch.LongTensor') return function(idx) return perm[idx] end end } transform.normalize = argcheck{ doc = [[ <a name = "transform.normalize"> #### transform.normalize(@ARGP) @ARGT This function normalizes data, i.e., it removes its mean and divide it by its standard deviation. The input must be a `Tensor`. Once create, a `threshold` can be given (must be a number). Then, the data will be divided by their standard deviation, only if this deviation is greater than the `threshold`. This is handy, if the deviation is small and deviding by it could lead to unstability. ]], {name='threshold', type='number', default=0}, call = function(threshold) return function(z) local std = z:std() z:add(-z:mean()) if std > threshold then z:div(std) end return z end end } return transform
local Rain = require('rain') local numberOfDrops = 1 local width, height = love.graphics.getDimensions() local rain = Rain(width, height, numberOfDrops) function love.load(arg) love.graphics.setBackgroundColor(230, 230, 250) -- Purple end function love.keypressed(k) if k == 'escape' or k == 'q' then love.event.quit() end if k == 'f' then if (love.window.getFullscreen()) then love.window.setFullscreen(false, 'desktop') else love.window.setFullscreen(true, 'desktop') end width, height = love.graphics.getDimensions() end end function love.draw() love.graphics.setColor(255, 255, 255) love.graphics.print("Current FPS: " .. tostring(love.timer.getFPS()), 10, 10) -- Draw rain for index, drop in ipairs(rain:getDrops()) do -- Get Drop data local x1, y1, x2, y2, thick, droplets = drop:get(20) -- Draw drop love.graphics.setColor(138, 43, 226) love.graphics.setLineWidth(thick) love.graphics.line(x1, y1, x2, y2) if (droplets) then for _, droplet in ipairs(droplets) do local x, y, radius = droplet:get() love.graphics.circle('fill', x, y, radius) end end -- After capturing the current state, update the drop position rain:update(drop, index) end end
local chat = require("lukkit/chat") -- Text components are used to create plain messages. local component = chat.text("your text") -- Translatables are used for client side translations. It can be used to send translation keys for the client translate -- client side, this means you are limited to the text provided by Minecraft (see below) unless a resource pack is used -- to add more. Some translations support arguments with can also be TranslatableComponents (or just TextComponents). -- Default translations: https://github.com/SpigotMC/BungeeCord/blob/master/chat/src/main/resources/mojang-translations/en_US.properties local component = chat.translatable("commands.give.success") -- -- Formatting -- -- Set the color of the text component:color(chat.color.GOLD) -- Bold the text and it's children component:bold() -- italicize the text and it's children component:italic() -- Underline the text and it's children component:underlined() -- Strikethrough the text and it's children component:strikethrough() -- Obfuscate the text and it's children -- Obfuscation makes the text randomly change to other charaters of the same width component:obfuscated() -- To remove a specific formatting component:bold(false) component:italic(false) component:underlined(false) component:strikethrough(false) component:obfuscated(false) -- -- Click events -- These events are ran when the user clicks the text component or it's children -- -- Open a url at the given path component:click(chat.clickEvents.OPEN_URL, "https://lukkit.net") -- Open a file at the given path component:click(chat.clickEvents.OPEN_FILE, "logs/latest.log") -- Run the given command component:click(chat.clickEvents.RUN_COMMAND, "/lukkit dev reload all") -- Inserts the given string into the players' text box component:click(chat.clickEvents.SUGGEST_COMMAND, "/lukkit help") -- Change to the given page number in a book -- NOTE: Not sure if we should do string or int component:click(chat.clickEvents.CHANGE_PAGE, "15") -- -- Hover Events -- -- TODO
local function ApplyLeading(tooltip_mc, element, amount) local val = 0 if element then if amount == 0 or amount == nil then amount = tooltip_mc.m_Leading * 0.5 end local heightPadding = 0 if element.heightOverride then heightPadding = element.heightOverride / amount else heightPadding = element.height / amount end heightPadding = Ext.Round(heightPadding) if heightPadding <= 0 then heightPadding = 1 end element.heightOverride = heightPadding * amount end end local function RepositionElements(tooltip_mc) --tooltip_mc.list.sortOnce("orderId",16,false) local leading = tooltip_mc.m_Leading * 0.5; local index = 0 local element = nil local lastElement = nil while index < tooltip_mc.list.length do element = tooltip_mc.list.content_array[index] if element.list then element.list.positionElements() end if element == tooltip_mc.equipHeader then element.updateHeight() else if element.needsSubSection then if element.heightOverride == 0 or element.heightOverride == nil then element.heightOverride = element.height end --element.heightOverride = element.heightOverride + leading; element.heightOverride = element.heightOverride + leading if lastElement and not lastElement.needsSubSection then if lastElement.heightOverride == 0 or lastElement.heightOverride == nil then lastElement.heightOverride = lastElement.height end --lastElement.heightOverride = lastElement.heightOverride + leading; lastElement.heightOverride = lastElement.heightOverride + leading end end --tooltip_mc.applyLeading(element) ApplyLeading(tooltip_mc, element) end lastElement = element index = index + 1 end --tooltip_mc.repositionElements() tooltip_mc.list.positionElements() tooltip_mc.resetBackground() end local replaceText = {} ---@param tag string ---@param data TagTooltipData ---@return string local function GetTagTooltipText(tag, data, tooltipType) local finalText = "" local tagName = "" local tagDesc = "" if data.Title == nil then tagName = Ext.GetTranslatedStringFromKey(tag) else local t = type(data.Title) if t == "string" then tagName = data.Title elseif t == "table" and data.Type == "TranslatedString" then tagName = data.Title.Value elseif t == "function" then local b,result = xpcall(data.Title, debug.traceback, tag, tooltipType) if b then tagName = result else Ext.PrintError(result) end end end if data.Description == nil then tagDesc = Ext.GetTranslatedStringFromKey(tag.."_Description") else local t = type(data.Description) if t == "string" then tagDesc = data.Description elseif t == "table" and data.Type == "TranslatedString" then tagDesc = data.Description.Value elseif t == "function" then local b,result = xpcall(data.Description, debug.traceback, tag, tooltipType) if b then tagDesc = result else Ext.PrintError(result) end end end if tagName ~= "" then finalText = tagName end if tagDesc ~= "" then if finalText ~= "" then finalText = finalText .. "<br>" end finalText = finalText .. tagDesc end return GameHelpers.Tooltip.ReplacePlaceholders(finalText) end local function FormatTagText(content_array, group, isControllerMode) local updatedText = false for i=0,#content_array,1 do local element = content_array[i] if element ~= nil then local b,result = xpcall(function() if element.label_txt ~= nil then local searchText = StringHelpers.Trim(element.label_txt.htmlText):gsub("[\r\n]", "") local tag = replaceText[searchText] local data = TooltipHandler.TagTooltips[tag] if data ~= nil then local finalText = GetTagTooltipText(tag, data, "Item") if not StringHelpers.IsNullOrWhitespace(finalText) then element.label_txt.htmlText = finalText updatedText = true end end -- if Vars.DebugMode then -- PrintDebug(string.format("(%s) label_txt.htmlText(%s) color(%s)", group.groupID, element.label_txt.htmlText, element.label_txt.textColor)) -- end end return true end, debug.traceback) if not b then Ext.PrintError("[LeaderLib:FormatTagText] Error:") Ext.PrintError(result) end end end if updatedText and group ~= nil then group.iconId = 16 group.setupHeader() end end UI.FormatArrayTagText = FormatTagText local function FormatTagTooltip(ui, tooltip_mc, ...) local length = #tooltip_mc.list.content_array if length > 0 then for i=0,length,1 do local group = tooltip_mc.list.content_array[i] if group ~= nil then --print(string.format("[%i] groupID(%i) orderId(%s) icon(%s) list(%s)", i, group.groupID or -1, group.orderId or -1, group.iconId, group.list)) if group.list ~= nil then FormatTagText(group.list.content_array, group, false) end end end end end --Fires after TooltipHooks.NextRequest is processed and made nil. function TooltipHandler.OnTooltipPositioned(ui, ...) if Game.Tooltip.LastRequestTypeEquals("Item") and TooltipHandler.HasTagTooltipData or #Listeners.OnTooltipPositioned > 0 then local root = ui:GetRoot() if root ~= nil then local tooltips = {} if root.formatTooltip ~= nil then tooltips[#tooltips+1] = root.formatTooltip.tooltip_mc end if root.compareTooltip ~= nil then tooltips[#tooltips+1] = root.compareTooltip.tooltip_mc end if root.offhandTooltip ~= nil then tooltips[#tooltips+1] = root.offhandTooltip.tooltip_mc end if #tooltips > 0 then for i,tooltip_mc in pairs(tooltips) do if Features.FormatTagElementTooltips then FormatTagTooltip(ui, tooltip_mc) end InvokeListenerCallbacks(Listeners.OnTooltipPositioned, ui, tooltip_mc, false, TooltipHandler.LastItem, ...) end end end end end function TooltipHandler.AddTooltipTags(item, tooltip) for tag,data in pairs(TooltipHandler.TagTooltips) do if GameHelpers.ItemHasTag(item, tag) then local finalText = GetTagTooltipText(tag, data, "Item") if not StringHelpers.IsNullOrWhitespace(finalText) then tooltip:AppendElement({ Type="StatsTalentsBoost", Label=finalText }) local searchText = finalText:gsub("<font.->", ""):gsub("</font>", ""):gsub("<br>", "") replaceText[searchText] = tag end end end end Ext.RegisterUINameInvokeListener("showFormattedTooltipAfterPos", TooltipHandler.OnTooltipPositioned)
local CorePackages = game:GetService("CorePackages") local InGameMenuDependencies = require(CorePackages.InGameMenuDependencies) local Roact = InGameMenuDependencies.Roact local Cryo = InGameMenuDependencies.Cryo local UIBlox = InGameMenuDependencies.UIBlox local t = InGameMenuDependencies.t local withStyle = UIBlox.Core.Style.withStyle local InGameMenu = script.Parent.Parent local GlobalConfig = require(InGameMenu.GlobalConfig) local validateProps = t.strictInterface({ themeKey = t.optional(t.string), fontKey = t.optional(t.string), AnchorPoint = t.optional(t.Vector2), LayoutOrder = t.optional(t.integer), Position = t.optional(t.UDim2), Size = t.optional(t.UDim2), Text = t.string, TextColor3 = t.optional(t.Color3), TextTransparency = t.optional(t.numberConstrained(0, 1)), TextWrapped = t.optional(t.boolean), TextXAlignment = t.optional(t.enum(Enum.TextXAlignment)), TextYAlignment = t.optional(t.enum(Enum.TextYAlignment)), TextTruncate = t.optional(t.enum(Enum.TextTruncate)), Visible = t.optional(t.boolean), ZIndex = t.optional(t.integer), [Roact.Children] = t.optional(t.table), }) local function ThemedTextLabel(props) if GlobalConfig.propValidation then assert(validateProps(props)) end return withStyle(function(style) local textTheme = style.Theme[props.themeKey or "TextDefault"] local textFont = style.Font[props.fontKey or "Body"] -- We want to allow you to override TextColor3 or TextTransparency if -- desired, so those two props come first. local primitiveProps = Cryo.Dictionary.join({ TextColor3 = textTheme.Color, TextTransparency = textTheme.Transparency, }, props, { fontKey = Cryo.None, themeKey = Cryo.None, BackgroundTransparency = 1, Font = textFont.Font, TextSize = textFont.RelativeSize * style.Font.BaseSize, }) return Roact.createElement("TextLabel", primitiveProps) end) end return ThemedTextLabel
local bmf = require 'bitmapFontLoader' local printf = function(self, string) local origin = self.node:getOrigin() self.text = string local node, rect = bmf.newString(self.bmflabel, self.text, self.material, self.geometry, self.shaderProgram) node:setOrigin(origin) node:setRenderCategory(self.node) node:getStateMachine():pushState(self.nodeStates.display) njli.World.getInstance():getScene():getRootNode():addChildNode(node) njli.Node.destroy(self.node, true) self.node = node self.rect = rect end local actionUpdate = function(action, timeStep) end local actionComplete = function(action) end local hide = function(self, camera) self.node:hide(camera) end local enter = function(self) local nodeName = self.node:getName() print("enter (" .. nodeName .. ") - START") print("enter (" .. nodeName .. ") - END") end local update = function(self, timeStep) end local exit = function(self) local nodeName = self.node:getName() print("exit (" .. nodeName .. ") - START") print("exit (" .. nodeName .. ") - END") end local onMessage = function(self, message) end local collide = function(self, otherNode, collisionPoint) end local near = function(self, otherNode) end local touchDown = function(self, rayContact) end local touchUp = function(self, rayContact) end local touchMove = function(self, rayContact) end local touchCancelled = function(self, rayContact) end local delete = function(self) local nodeName = self.node:getName() print("delete (" .. nodeName .. ") - START") self.node:getStateMachine():pushState(nil) njli.Node.destroy(self.node, true) self.node = nil for k,v in pairs(self.nodeStates) do njli.NodeState.destroy(self.nodeStates[k]) self.nodeStates[k] = nil end self.nodeStates = nil print("delete (" .. nodeName .. ") - END") end local methods = { printf = printf, actionUpdate = actionUpdate, actionComplete = actionComplete, hide = hide, enter = enter, update = update, exit = exit, onMessage = onMessage, collide = collide, near = near, touchDown = touchDown, touchUp = touchUp, touchMove = touchMove, touchCancelled = touchCancelled, __gc = delete } local new = function(name, bmflabel, material, geometry, shaderProgram) print("new (" .. name .. ") - START") local node, rect = bmf.newString(bmflabel, name, material, geometry, shaderProgram) local names = { display = name, } local nodeStates = {} for k,v in pairs(names) do nodeStates[k] = njli.NodeState.create() nodeStates[k]:setName(names[k]) end node:setOrigin(bullet.btVector3(0,0,0)) node:getStateMachine():pushState(nodeStates.display) njli.World.getInstance():getScene():getRootNode():addChildNode(node) local properties = { node = node, rect = rect, nodeStates = nodeStates, nodeStateNames = names, text = name, bmflabel = bmflabel, material = material, geometry = geometry, shaderProgram = shaderProgram, instanceName = name, } print("new (" .. name .. ") - END") return setmetatable(properties, {__index = methods}) end return { new = new, }
local qt = require "qtest" local S = require "serialize" ---- orderedPairs local orderedPairs = S.orderedPairs local function top(t, o) local s = "" for k,v in orderedPairs(t) do s = s .. tostring(k) .. "=" .. tostring(v) .. ";" end return qt.eq(o, s) end top( {y="A", x="a", [5]="b", [false] = true, [true] = false, 9}, "1=9;false=true;true=false;5=b;x=a;y=A;" ) ---- serialize to function/string local serialize = S.serialize local function serTest(x) local tt = {} local function tw(x) table.insert(tt, x) end serialize(x, tw) local str = table.concat(tt) local x2 = assert(load("return " .. str))() qt._eq(x, x2, 2) -- no writer => return string local str2 = serialize(x) qt._eq(str, str2, 2) -- writer == table local t3 = {} local r = serialize(x, t3) qt._eq(str, table.concat(t3), 2) end serTest(1) serTest("a") serTest{"a",7,x="2",[9]={},["a-b"]=false} -- inf, -inf, nan serTest(1/0) serTest(-1/0) serTest(0/0) ---- serialize ordered qt.eq( '{9,[false]=true,[true]=false,[5]="b",x="a",y="A"}', serialize({y="A", x="a", [5]="b", [false] = true, [true] = false, 9}, nil, "s") )
local Array = require('arken.Array') local FormHelper = require('arken.Helper.FormHelper') local test = {} test.should_return_html_not_checked = function() local list = Array.new{ { id = 1, name = 'description' } } local data = { id = '1' } local controller = {controller_name = 'form', action_name = 'save'} local form = FormHelper.new{ name = 'form', controller = controller, data = data } local result = form:selectList('id', list, 'id', 'name' ) local html = [[<select id="form_id" name="form[id]" style="width:250px;"><option value="1" >description</option></select>]] assert( result == html, result ) end test.should_return_html_checked = function() local list = Array.new{ { id = 1, name = 'description' } } local data = { id = 1 } local controller = {controller_name = 'form', action_name = 'save'} local form = FormHelper.new{ name = 'form', controller = controller, data = data } local result = form:selectList('id', list, 'id', 'name' ) local html = [[<select id="form_id" name="form[id]" style="width:250px;"><option value="1" selected >description</option></select>]] assert( result == html, result ) end test.should_return_html_multiple_list_and_checked = function() local list = Array.new{ { id = 1, name = 'John' }, { id = 2, name = 'Suse' }, { id = 3, name = 'Rute' } } local data = { id = 1 } local controller = {controller_name = 'form', action_name = 'save'} local form = FormHelper.new{ name = 'form', controller = controller, data = data } local result = form:selectList('id', list, 'id', 'name' ) local html = [[<select id="form_id" name="form[id]" style="width:250px;"><option value="1" selected >John</option><option value="2" >Suse</option><option value="3" >Rute</option></select>]] assert( result == html, result ) end test.should_return_html_multiple_true = function() local list = Array.new{ { id = 1, name = 'description' } } local data = { id = 1 } local controller = {controller_name = 'form', action_name = 'save'} local form = FormHelper.new{ name = 'form', controller = controller, data = data } local result = form:selectList('id', list, 'id', 'name', { multiple = true } ) local html = [[<select multiple="multiple" size="5" id="form_id" name="form[id]" style="width:250px;"><option value="1" selected >description</option></select>]] assert( result == html, result ) end test.should_return_html_multiple = function() local list = Array.new{ { id = 1, name = 'description' } } local data = { id = 1 } local controller = {controller_name = 'form', action_name = 'save'} local form = FormHelper.new{ name = 'form', controller = controller, data = data } local result = form:selectList('id', list, 'id', 'name', { multiple = 7 } ) local html = [[<select multiple="multiple" size="7" id="form_id" name="form[id]" style="width:250px;"><option value="1" selected >description</option></select>]] assert( result == html, result ) end test.should_return_html_blank_true = function() local list = Array.new{ { id = 1, name = 'description' } } local data = { id = 1 } local controller = {controller_name = 'form', action_name = 'save'} local form = FormHelper.new{ name = 'form', controller = controller, data = data } local result = form:selectList('id', list, 'id', 'name', { blank = true } ) local html = [[<select id="form_id" name="form[id]" style="width:250px;"><option value="" ></option><option value="1" selected >description</option></select>]] assert( result == html, result ) end test.should_return_html_blank_value = function() local list = Array.new{ { id = 1, name = 'description' } } local data = { id = 1 } local controller = {controller_name = 'form', action_name = 'save'} local form = FormHelper.new{ name = 'form', controller = controller, data = data } local result = form:selectList('id', list, 'id', 'name', { blank = 'SELECT OPTION' } ) local html = [[<select id="form_id" name="form[id]" style="width:250px;"><option value="" >SELECT OPTION</option><option value="1" selected >description</option></select>]] assert( result == html, result ) end return test
return {'wodka','wodkafles','wodanseik','wodan','wodkas','wodans'}
package.path = package.path .. ";../src/?.lua" require 'busted.runner'() local match = require("luassert.match") --Mocking the kong/restify dependencies local BasePlugin = { extend = function() return { super = { new = function() end, access = function() end } } end } local responses = { send_HTTP_FORBIDDEN = function() return "FORBIDDEN" end } package.loaded['kong.plugins.base_plugin'] = BasePlugin package.loaded['kong.tools.responses'] = responses local iputils = { parse_cidrs = function(cidrs) return cidrs end, parse_cidr = function(cidr) return cidr end, ip_in_cidrs = function(header, cidrs) return cidrs[1] == header end } package.loaded['resty.iputils'] = iputils --Globals _G.ngx = { req = { get_headers = function() return {} end } } function setHeader(header, value) _G.ngx.req.get_headers = function() local tbl = {} tbl[header] = value return tbl end end --Test local Handler = require "handler" describe("handler", function() describe("new", function() it("calls super", function() local s = spy.on(Handler.super, 'new') Handler.new() assert.spy(s).was_called_with(_, "header-access-control") end) end) describe("access", function() it("calls super", function() local s = spy.on(Handler.super, 'access') Handler.access(_, {}) assert.spy(s).was_called_with(_) end) it("succeeds if valid header using ip type", function() setHeader("header_whitelist", "header_whitelist_val") local response = Handler.access(_, {header = "header_whitelist", type='ip', whitelist = {"header_whitelist_val"}}) assert.are.same(response, Nil) end) it("succeeds if valid header using regular type", function() setHeader("header_whitelist", "header_whitelist_val") local response = Handler.access(_, {header = "header_whitelist", type='regular', whitelist = {"header_whitelist_val"}}) assert.are.same(response, Nil) end) it("returns forbidden if header not found using", function() setHeader("other", "other") local response = Handler.access(_, {header = "header_whitelist", type='ip', blacklist = {"header_whitelist_val"}}) assert.are.same(response, "FORBIDDEN") end) it("returns forbidden if header value black listed using ip type", function() setHeader("header_blacklist", "header-blacklist_val") local response = Handler.access(_, {header = "header_blacklist", type='ip', blacklist = {"header-blacklist_val"}}) assert.are.same(response, "FORBIDDEN") end) it("returns forbidden if header value black listed using regular type", function() setHeader("header_blacklist", "header-blacklist_val") local response = Handler.access(_, {header = "header_blacklist", type='regular', blacklist = {"header-blacklist_val"}}) assert.are.same(response, "FORBIDDEN") end) it("returns forbidden if header value is not white listed using ip type", function() setHeader("header_not_whitelisted", "some_val") local response = Handler.access(_, {header = "header_whitelist", type='ip', whitelist = {"header_whitelist_val"}}) assert.are.same(response, "FORBIDDEN") end) it("returns forbidden if header value is not white listed using regular type", function() setHeader("header_not_whitelisted", "some_val") local response = Handler.access(_, {header = "header_whitelist", type='regular', whitelist = {"header_whitelist_val"}}) assert.are.same(response, "FORBIDDEN") end) end) end)
ModMagicNumbersFileAdd( "mods/mod_dev_settings/files/magic_numbers.xml" )
-- local mg = metagui settings = { } local modules = { } local moduleProto = { } local moduleMt = extend(moduleProto) local pageProto = { } local pageMt = extend(pageProto) local loadedPages = { } local ap = mg.cfg.assetPath local function setAssetPath(p) mg.cfg.assetPath = p or ap end local scriptId, scriptPath function settings.module(p) p = p or { } local m = setmetatable({ }, moduleMt) m.id = p.id or scriptId m.weight = p.weight m.assetPath = scriptPath m.pages = { } modules[m.id] = m return m end function moduleProto:page(p) local pg = setmetatable({ }, pageMt) pg.module = self pg.title = p.title pg.icon = p.icon pg.contents = p.contents table.insert(self.pages, pg) return pg end function pageProto:init() end function pageProto:onSwitch() end function pageProto:save() end function tabField:onTabChanged(tab) local page = tab.page if not page.loaded then page.loaded = true setAssetPath(page.module.scriptPath) mg.widgetContext = page mg.createImplicitLayout(page.contents, tab.contents, { mode = "vertical", expandMode = {2, 2} }) page:init() setAssetPath() table.insert(loadedPages, page) end page:onSwitch() end function apply:onClick() for _, p in pairs(loadedPages) do p:save() end player.setProperty("metagui:settings", metagui.settings) player.setProperty("metaGUISettings", nil) -- clear out old property end function cancel:onClick() pane.dismiss() end -- begin init local registry = mg.registry _ENV.registry = registry -- leave this here for modules -- load in module scripts for k, v in pairs(registry.settings) do scriptId = k scriptPath = util.pathDirectory(v) require(v) end local modSort = { } for k, v in pairs(modules) do table.insert(modSort, v) end table.sort(modSort, function(a, b) return a.weight < b.weight or (a.weight == b.weight and a.id < b.id) end) for _, m in ipairs(modSort) do setAssetPath(m.scriptPath) for i, pg in ipairs(m.pages) do local tab = tabField:newTab{ title = pg.title, icon = pg.icon, } tab.page = pg pg.tab = tab end end setAssetPath() local firstTab = tabField.tabScroll.children[1].children[1] if firstTab then firstTab:select() end
class "sScriptConfig" function sScriptConfig:__init(name, theme) UpdateWindow() self.name = name self.theme = theme self.state = nil self.states = {} self.substates = {} self.par = {} self.resize = false self.move = false self.pos = {x = 0, z = 50} self.touch = {x = 0, z = 0} self.Scale = {x = 0.65*1920/WINDOW_W, z = 0.65*1080/WINDOW_H} self.keyChange = nil self.lastMove = 0 self.LastIncrRequest = 0 self.slide = {false, false, false, false} self.loaded = false AddUnloadCallback(function() self:Unload_Sprites() end) AddDrawCallback(function() self:Draw() end) AddMsgCallback(function(Msg, Key) self:Msg(Msg, Key) end) AddTickCallback(function() self:Tick() end) return self end local function remove(name) if not GetSave("sScriptConfig")[name] then GetSave("sScriptConfig")[name] = {} end table.clear(GetSave("sScriptConfig")[name]) end local function load(name) if not GetSave("sScriptConfig")[name] then GetSave("sScriptConfig")[name] = {} end return GetSave("sScriptConfig")[name] end local function save(name, content) if not GetSave("sScriptConfig")[name] then GetSave("sScriptConfig")[name] = {} end table.clear(GetSave("sScriptConfig")[name]) table.merge(GetSave("sScriptConfig")[name], content, true) end function sScriptConfig:load() local function sensitiveMerge(base, t) for i, v in pairs(t) do if type(base[i]) == type(v) then if type(v) == "table" then sensitiveMerge(base[i], v) else base[i] = v end end end end local config = load(self.name) for var, value in pairs(config) do for _,par in pairs(self.par) do if par.name == value.name and par.state == value.state then if value.code == SCRIPT_PARAM_ONKEYDOWN or value.code == SCRIPT_PARAM_ONKEYTOGGLE then par.key = value.key end if value.code == SCRIPT_PARAM_ONOFF or value.code == SCRIPT_PARAM_LIST then par.value = value.value end if value.code == SCRIPT_PARAM_SLICE then par.slider = value.slider end end end end end function sScriptConfig:save() local content = {} content = {} for var, param in pairs(self.par) do table.insert(content, param) end save(self.name, content) end function sScriptConfig:addParam(par) table.insert(self.par, par) end function sScriptConfig:getParam(state, param1, param2) for _,par in pairs(self.par) do if par.name == param1 and par.state == state then if par.code == SCRIPT_PARAM_SLICE and param2 then for k=1,#par.slider do if par.text[k] == param2 then return par.slider[k] end end elseif par.code == SCRIPT_PARAM_ONKEYDOWN then return IsKeyDown(par.key) else return par.value end end end end function sScriptConfig:setParam(state, value, param1, param2) for _,par in pairs(self.par) do if par.name == param1 and par.state == state then if par.code == SCRIPT_PARAM_SLICE and param2 then for k=1,#par.slider do if par.text[k] == param2 then par.slider[k] = value end end elseif par.code == SCRIPT_PARAM_LIST then if par.value == #par.list then par.value = 1 else par.value = value end else par.value = value end end end end function sScriptConfig:incParamBy1(state, param1, param2) if not self:ValidIncrRequest() then return end for _,par in pairs(self.par) do if par.name == param1 and par.state == state then if par.code == SCRIPT_PARAM_SLICE and param2 then for k=1,#par.slider do if par.text[k] == param2 then par.slider[k] = par.slider[k] + 1 end end elseif par.code == SCRIPT_PARAM_LIST then if par.value == #par.list then par.value = 1 else par.value = par.value + 1 end else par.value = par.value + 1 end end end end function sScriptConfig:ValidIncrRequest() if GetInGameTimer() - self.LastIncrRequest < 0.5 then return false else self.LastIncrRequest = GetInGameTimer() return true end end function sScriptConfig:addState(state) table.insert(self.states, state) if self.state == nil then self.state = state end end function sScriptConfig:addSubStates(state, sub) self.substates[state] = sub if self.state == nil or self.state == state then self.state = sub[1] end end function sScriptConfig:Unload_Sprites() for _,k in pairs(self.Sprites) do k:Release() end end function sScriptConfig:Load_Sprites() self.hadToDownload = false self.Sprites = {} self.SpriteTable = { "top", "mid", "drag", "drag_selected", "code1", "code1_selected", "code2", "code4", "SLIDER_1", "SLIDER_2", "SLIDER_3", "SLIDER_4", "code3", "code7", "state", "state_selected", "state_bottom", "state_bottom_selected", "bot", "Words\\Button\\Change", "Scripts\\"..self.name } self.dontDownload = {"chibi\\"..GetUser():lower(), "Scripts\\"..self.name.." Logo", "Scripts\\"..self.theme.." Logo"} self.buttonTable = { "1","2","3","4","5","6","7","8","9","0","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","Space","Ctrl" } self.buttonTable2 = { 20,33,34,35,36,45,46,104,105,106,107,108,109 } self.numTable = { "1","2","3","4","5","6","7","8","9","0","%" } for _, sprite in pairs(self.SpriteTable) do location = "sScriptConfig\\"..self.theme.."\\" .. sprite .. ".png" if FileExist(SPRITE_PATH .. location) then self.Sprites[sprite] = createSprite(location) elseif self.theme == "Scriptology" then DownloadFile("https://raw.github.com/nebelwolfi/BoL/master/Sprites/"..location.."?rand="..math.random(1,10000), SPRITE_PATH..location, function () print("Downloading a sprite please wait... ") end) self.hadToDownload = true end end for _, sprite in pairs(self.dontDownload) do location = "sScriptConfig\\"..self.theme.."\\" .. sprite .. ".png" if FileExist(SPRITE_PATH .. location) then self.Sprites[sprite] = createSprite(location) end end for _, sprite in pairs(self.numTable) do location = "sScriptConfig\\"..self.theme.."\\Num\\" .. sprite .. ".png" if FileExist(SPRITE_PATH .. location) then self.Sprites[sprite] = createSprite(location) elseif self.theme == "Scriptology" then DownloadFile("https://raw.github.com/nebelwolfi/BoL/master/Sprites/"..location.."?rand="..math.random(1,10000), SPRITE_PATH..location, function () print("Downloading a sprite please wait... ") end) self.hadToDownload = true end end for _, sprite in pairs(self.buttonTable) do location = "sScriptConfig\\"..self.theme.."\\Words\\Button\\" .. sprite .. ".png" if sprite == "Space" then sprite = 32 elseif sprite == "Alt" then sprite = 18 elseif sprite == "Ctrl" then sprite = 17 else sprite = string.byte(sprite) end if FileExist(SPRITE_PATH .. location) then self.Sprites[sprite] = createSprite(location) elseif self.theme == "Scriptology" then DownloadFile("https://raw.github.com/nebelwolfi/BoL/master/Sprites/"..location.."?rand="..math.random(1,10000), SPRITE_PATH..location, function () print("Downloading a sprite please wait... ") end) self.hadToDownload = true end end for _, sprite in pairs(self.buttonTable2) do location = "sScriptConfig\\"..self.theme.."\\Words\\Button\\" .. sprite .. ".png" if FileExist(SPRITE_PATH .. location) then self.Sprites[sprite] = createSprite(location) elseif self.theme == "Scriptology" then DownloadFile("https://raw.github.com/nebelwolfi/BoL/master/Sprites/"..location.."?rand="..math.random(1,10000), SPRITE_PATH..location, function () print("Downloading a sprite please wait... ") end) self.hadToDownload = true end end for _, sprite in pairs(self.states) do if not self.substates[sprite] then location = "sScriptConfig\\"..self.theme.."\\Words\\" .. sprite .. ".png" if FileExist(SPRITE_PATH .. location) then self.Sprites[sprite] = createSprite(location) elseif self.theme == "Scriptology" then DownloadFile("https://raw.github.com/nebelwolfi/BoL/master/Sprites/"..location.."?rand="..math.random(1,10000), SPRITE_PATH..location, function () print("Downloading a sprite please wait... ") end) self.hadToDownload = true end location = "sScriptConfig\\"..self.theme.."\\Words\\" .. sprite .. "_selected.png" if FileExist(SPRITE_PATH .. location) then self.Sprites[sprite.."_selected"] = createSprite(location) elseif self.theme == "Scriptology" then DownloadFile("https://raw.github.com/nebelwolfi/BoL/master/Sprites/"..location.."?rand="..math.random(1,10000), SPRITE_PATH..location, function () print("Downloading a sprite please wait... ") end) self.hadToDownload = true end elseif self.substates[sprite] then for v,k in pairs(self.substates[sprite]) do location = "sScriptConfig\\"..self.theme.."\\Words\\" .. k .. ".png" if FileExist(SPRITE_PATH .. location) then self.Sprites[k] = createSprite(location) elseif self.theme == "Scriptology" then DownloadFile("https://raw.github.com/nebelwolfi/BoL/master/Sprites/"..location.."?rand="..math.random(1,10000), SPRITE_PATH..location, function () print("Downloading a sprite please wait... ") end) self.hadToDownload = true end location = "sScriptConfig\\"..self.theme.."\\Words\\" .. k .. "_selected.png" if FileExist(SPRITE_PATH .. location) then self.Sprites[k.."_selected"] = createSprite(location) elseif self.theme == "Scriptology" then DownloadFile("https://raw.github.com/nebelwolfi/BoL/master/Sprites/"..location.."?rand="..math.random(1,10000), SPRITE_PATH..location, function () print("Downloading a sprite please wait... ") end) self.hadToDownload = true end end end end for _, par in pairs(self.par) do sprite=par.name location = "sScriptConfig\\"..self.theme.."\\Words\\" .. sprite .. ".png" if FileExist(SPRITE_PATH .. location) then self.Sprites[sprite] = createSprite(location) elseif self.theme == "Scriptology" then DownloadFile("https://raw.github.com/nebelwolfi/BoL/master/Sprites/"..location.."?rand="..math.random(1,10000), SPRITE_PATH..location, function () print("Downloading a sprite please wait... ") end) self.hadToDownload = true end location = "sScriptConfig\\"..self.theme.."\\Words\\" .. sprite .. "_selected.png" if FileExist(SPRITE_PATH .. location) then self.Sprites[sprite.."_selected"] = createSprite(location) elseif self.theme == "Scriptology" then DownloadFile("https://raw.github.com/nebelwolfi/BoL/master/Sprites/"..location.."?rand="..math.random(1,10000), SPRITE_PATH..location, function () print("Downloading a sprite please wait... ") end) self.hadToDownload = true end if par.code == SCRIPT_PARAM_LIST then for _,k in pairs(par.list) do location = "sScriptConfig\\"..self.theme.."\\Words\\" .. k .. ".png" if FileExist(SPRITE_PATH .. location) then self.Sprites[k] = createSprite(location) elseif self.theme == "Scriptology" then DownloadFile("https://raw.github.com/nebelwolfi/BoL/master/Sprites/"..location.."?rand="..math.random(1,10000), SPRITE_PATH..location, function () print("Downloading a sprite please wait... ") end) self.hadToDownload = true end end end end if not self.hadToDownload then while #self.states < 6 do self:addState("blank") end self.offsets = {top = self.Sprites["top"].height, button = self.Sprites["state"].height, bot = self.Sprites["drag"].height*2, width = self.Sprites["top"].width, buttonwidth = self.Sprites["state"].width} else self:Unload_Sprites() DelayAction(function() print("Reloading menu... Please wait!") DelayAction(function() print("Reloaded. Have fun!") end, 1.5) self.loaded = false end, 1.5) end end function sScriptConfig:Draw() if (self.keyChange or IsKeyDown(16)) and self.loaded then self.Sprites["top"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["top"]:Draw(self.pos.x, self.pos.z+WINDOW_H/4, 255) if self.Sprites["Scripts\\"..self.name.." Logo"] then self.Sprites["Scripts\\"..self.name.." Logo"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["Scripts\\"..self.name.." Logo"]:Draw(self.pos.x+self.Scale.z*(self.offsets.buttonwidth/2-self.Sprites["Scripts\\"..self.name.." Logo"].width/2), self.pos.z+WINDOW_H/4+self.Scale.z*(self.Sprites["top"].height/2-self.Sprites["Scripts\\"..self.name.." Logo"].height/2), 255) elseif self.Sprites["Scripts\\"..self.theme.." Logo"] then self.Sprites["Scripts\\"..self.theme.." Logo"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["Scripts\\"..self.theme.." Logo"]:Draw(self.pos.x+self.Scale.z*(self.offsets.buttonwidth/2-self.Sprites["Scripts\\"..self.theme.." Logo"].width/2), self.pos.z+WINDOW_H/4+self.Scale.z*(self.Sprites["top"].height/2-self.Sprites["Scripts\\"..self.theme.." Logo"].height/2), 255) end self.Sprites["Scripts\\"..self.name]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["Scripts\\"..self.name]:Draw(self.pos.x+self.Scale.z*((self.offsets.buttonwidth+self.Sprites["top"].width)/2-self.Sprites["Scripts\\"..self.name].width/2), self.pos.z+WINDOW_H/4+self.Scale.z*(self.Sprites["top"].height/2-self.Sprites["Scripts\\"..self.name].height/2), 255) for _,par in pairs(self.states) do if not self.substates[par] then if self.state ~= par and self.Sprites[par] or self.state == par and self.Sprites[par.."_selected"] then if self.state == par then self.Sprites["state_selected"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["state_selected"]:Draw(self.pos.x, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*(_-1)), 255) self.Sprites[par.."_selected"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites[par.."_selected"]:Draw(self.pos.x+self.Scale.x*20, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*(_-0.5))-self.Scale.z*self.Sprites[par.."_selected"].height/2, 255) else self.Sprites["state"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["state"]:Draw(self.pos.x, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*(_-1)), 255) self.Sprites[par]:SetScale(self.Scale.x,self.Scale.z) self.Sprites[par]:Draw(self.pos.x+self.Scale.x*20, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*(_-0.5)-self.Sprites[par].height/2), 255) end else self.Sprites["state"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["state"]:Draw(self.pos.x, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*(_-1)), 255) end else for v,k in pairs(self.substates[par]) do if self.state ~= k and self.Sprites[k] or self.state == k and self.Sprites[k.."_selected"] then if self.state == k then self.Sprites["state_selected"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["state_selected"]:Draw(self.pos.x, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*(_-1)+self.offsets.button/2*(v-1)), 255) self.Sprites[k.."_selected"]:SetScale(self.Scale.x*3/4,self.Scale.z*3/4) self.Sprites[k.."_selected"]:Draw(self.pos.x+self.Scale.x*20, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*(_-0.5)-self.offsets.button/2+self.offsets.button/2*(v-1)+self.Sprites[k.."_selected"].height/2-self.Sprites[k].height/4), 255) else self.Sprites["state"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["state"]:Draw(self.pos.x, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*(_-1)+self.offsets.button/2*(v-1)), 255) self.Sprites[k]:SetScale(self.Scale.x*3/4,self.Scale.z*3/4) self.Sprites[k]:Draw(self.pos.x+self.Scale.x*20, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*(_-0.5)-self.offsets.button/2+self.offsets.button/2*(v-1)+self.Sprites[k].height/2-self.Sprites[k].height/4), 255) end else self.Sprites["state"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["state"]:Draw(self.pos.x, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*(_-1)+self.offsets.button/2*(v-1)), 255) end end end end self.Sprites["mid"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["mid"]:Draw(self.pos.x+self.Scale.x*self.offsets.buttonwidth, self.pos.z+WINDOW_H/4+self.Scale.z*self.offsets.top, 255) if self.Sprites["chibi\\"..GetUser():lower()] then self.Sprites["chibi\\"..GetUser():lower()]:SetScale(self.Scale.x*0.75,self.Scale.z*0.75) self.Sprites["chibi\\"..GetUser():lower()]:Draw(self.pos.x+self.Scale.x*self.offsets.width-self.Scale.x*(self.Sprites["chibi\\"..GetUser():lower()].width-75), self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*#self.states)-self.Scale.z*(self.Sprites["chibi\\"..GetUser():lower()].height-120), 175) end local a = 0 local c = 0 local y = 0 for _,par in pairs(self.par) do if par.state == self.state and self.Sprites["code"..par.code] and ((par.code == SCRIPT_PARAM_ONKEYDOWN or par.code == SCRIPT_PARAM_ONKEYTOGGLE) and self.Sprites[string.char(par.key)] or (par.code == SCRIPT_PARAM_SLICE and self.Sprites["code"..par.code] or self.Sprites[par.name])) then if c == 4 then c = 0 y = y + 1 end bxPos = self.pos.x+self.Scale.x*(self.Sprites["code"..par.code].width*(c)+40+c*45+self.offsets.buttonwidth) byPos = self.pos.z+WINDOW_H/4+self.Scale.z*((40+self.Sprites["code"..par.code].height)*(y)+20+self.offsets.top) if par.code == SCRIPT_PARAM_ONOFF then if par.value then self.Sprites["code"..par.code.."_selected"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["code"..par.code.."_selected"]:Draw(bxPos,byPos, 255) self.Sprites[par.name.."_selected"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites[par.name.."_selected"]:Draw(bxPos+self.Scale.x*(self.Sprites["code"..par.code].width/2-self.Sprites[par.name].width/2),byPos+self.Scale.z*(self.Sprites["code"..par.code].height/2-self.Sprites[par.name].height/2), 255) else self.Sprites["code"..par.code]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["code"..par.code]:Draw(bxPos,byPos, 255) self.Sprites[par.name]:SetScale(self.Scale.x,self.Scale.z) self.Sprites[par.name]:Draw(bxPos+self.Scale.x*(self.Sprites["code"..par.code].width/2-self.Sprites[par.name].width/2),byPos+self.Scale.z*(self.Sprites["code"..par.code].height/2-self.Sprites[par.name].height/2), 255) end elseif par.code == SCRIPT_PARAM_ONKEYDOWN or par.code == SCRIPT_PARAM_ONKEYTOGGLE then a = a + 1 local b = 0 local ppos = par.name local kpos = par.key for _,k in pairs(self.par) do if par.state == k.state and (k.code == SCRIPT_PARAM_ONKEYDOWN or k.code == SCRIPT_PARAM_ONKEYTOGGLE) then ppos = k.name kpos = k.key b = b + 1 end end xOffset = b > 1 and self.Scale.x*(0-a*self.Sprites["mid"].width/(2*b)+(b+0.75)*self.Sprites["mid"].width/(4*b)) or 0 self.Sprites[par.name]:SetScale(self.Scale.x*0.75,self.Scale.z*0.75) self.Sprites[par.name]:Draw(self.pos.x+xOffset+self.Scale.x*(self.offsets.buttonwidth+self.Sprites["mid"].width/2-self.Sprites[ppos].width/2+15),self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*#self.states)-self.Scale.z*self.Sprites[kpos].height/2, 255) if self.keyChange then self.Sprites["Words\\Button\\Change"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["Words\\Button\\Change"]:Draw(self.pos.x+xOffset+self.Scale.x*(self.offsets.buttonwidth+self.Sprites["mid"].width/2-self.Sprites["Words\\Button\\Change"].width/2-1),self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*#self.states-self.Sprites["Words\\Button\\Change"].height/2-self.Sprites[ppos].height*2-20), 255) else self.Sprites[par.key]:SetScale(self.Scale.x,self.Scale.z) self.Sprites[par.key]:Draw(self.pos.x+xOffset+self.Scale.x*(self.offsets.buttonwidth+self.Sprites["mid"].width/2-self.Sprites[kpos].width/2-1),self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*#self.states-self.Sprites[kpos].height/2-self.Sprites[ppos].height*2-20), 255) end elseif par.code == SCRIPT_PARAM_SLICE then --{0,30,100,5} if c > 0 then y = y + 1 c = 0 end if y == 0 then y = 0.2+0.05*#par.slider end if y == 2 then y = 1.5 end self.Sprites[par.name]:SetScale(self.Scale.x*1.25,self.Scale.z*1.25) self.Sprites[par.name]:Draw(self.pos.x+self.Scale.x*(self.offsets.buttonwidth+self.Sprites["mid"].width/2-self.Sprites["code"..par.code].width/2-self.Sprites["code"..par.code].width/2),self.pos.z+WINDOW_H/4+self.Scale.z*(35+self.offsets.top+self.offsets.button*(#self.states-3)*y-10), 255) self.Sprites["code"..par.code]:SetScale(self.Scale.x*1.25,self.Scale.z*1.25) self.Sprites["code"..par.code]:Draw(self.pos.x+self.Scale.x*(self.offsets.buttonwidth+self.Sprites["mid"].width/2-self.Sprites["code"..par.code].width/2-1),self.pos.z+WINDOW_H/4+self.Scale.z*(35+self.offsets.top+self.offsets.button*(#self.states-3)*y), 255) for k=#par.slider,1,-1 do self.Sprites["SLIDER_"..k]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["SLIDER_"..k]:Draw(self.pos.x+self.Scale.x*((self.Sprites["code"..par.code].width+70)*par.slider[k]/100+k*2+self.offsets.buttonwidth-self.Sprites["SLIDER_"..k].width/2+self.Sprites["mid"].width/2-self.Sprites["code"..par.code].width/2),self.pos.z+WINDOW_H/4+self.Scale.z*(30+self.offsets.top-self.Sprites["SLIDER_"..k].height+self.offsets.button*(#self.states-3)*y), 255) self.Sprites[par.text[k]]:SetScale(self.Scale.x*0.37,self.Scale.z*0.37) self.Sprites[par.text[k]]:Draw(self.pos.x+self.Scale.x*((self.Sprites["code"..par.code].width+70)*par.slider[k]/100+k*2+self.offsets.buttonwidth-self.Sprites[par.text[k]].width/2*0.37+self.Sprites["mid"].width/2-self.Sprites["code"..par.code].width/2),self.pos.z+WINDOW_H/4+self.Scale.z*(35+self.offsets.top-self.Sprites["SLIDER_"..k].height+self.offsets.button*(#self.states-3)*y), 255) if self.slide[k] then nxPos = self.pos.x+self.Scale.x*(self.offsets.buttonwidth+self.Sprites["mid"].width/2+self.Sprites["code"..par.code].width/2+self.Sprites["code"..par.code].width/4+15) nzPos = self.pos.z+WINDOW_H/4+self.Scale.z*(35+self.offsets.top+self.offsets.button*(#self.states-3)*y-10) if par.slider[k] > 99 then self.Sprites["1"]:SetScale(self.Scale.x*0.37,self.Scale.z*0.37) self.Sprites["1"]:Draw(nxPos,nzPos, 255) self.Sprites["0"]:SetScale(self.Scale.x*0.37,self.Scale.z*0.37) self.Sprites["0"]:Draw(nxPos+self.Scale.x*self.Sprites["0"].width/2,nzPos, 255) self.Sprites["0"]:SetScale(self.Scale.x*0.37,self.Scale.z*0.37) self.Sprites["0"]:Draw(nxPos+self.Scale.x*self.Sprites["0"].width/2+self.Scale.x*self.Sprites["0"].width/2,nzPos, 255) self.Sprites["%"]:SetScale(self.Scale.x*0.37,self.Scale.z*0.37) self.Sprites["%"]:Draw(nxPos+self.Scale.x*self.Sprites["0"].width/2+self.Scale.x*self.Sprites["0"].width/2+self.Scale.x*self.Sprites["%"].width/4+self.Scale.x*4,nzPos, 255) elseif par.slider[k] > 9 then self.Sprites[""..math.floor(par.slider[k]/10)]:SetScale(self.Scale.x*0.37,self.Scale.z*0.37) self.Sprites[""..math.floor(par.slider[k]/10)]:Draw(nxPos,nzPos, 255) self.Sprites[""..math.floor(par.slider[k]-math.floor(par.slider[k]/10)*10)]:SetScale(self.Scale.x*0.37,self.Scale.z*0.37) self.Sprites[""..math.floor(par.slider[k]-math.floor(par.slider[k]/10)*10)]:Draw(nxPos+self.Scale.x*self.Sprites["0"].width/2,nzPos, 255) self.Sprites["%"]:SetScale(self.Scale.x*0.37,self.Scale.z*0.37) self.Sprites["%"]:Draw(nxPos+self.Scale.x*self.Sprites["0"].width/2+self.Scale.x*self.Sprites["%"].width/4+self.Scale.x*4,nzPos, 255) else self.Sprites[""..math.floor(par.slider[k])]:SetScale(self.Scale.x*0.37,self.Scale.z*0.37) self.Sprites[""..math.floor(par.slider[k])]:Draw(nxPos+self.Scale.x*self.Sprites["0"].width/2,nzPos, 255) self.Sprites["%"]:SetScale(self.Scale.x*0.37,self.Scale.z*0.37) self.Sprites["%"]:Draw(nxPos+self.Scale.x*self.Sprites["0"].width/2+self.Scale.x*self.Sprites["%"].width/4+self.Scale.x*4,nzPos, 255) end end end elseif par.code == SCRIPT_PARAM_LIST then if not self.Sprites[par.list[par.value]] then par.value = 1 end if c > 0 then bxPos = self.pos.x+self.Scale.x*(40+self.offsets.buttonwidth) y = y + 1 byPos = self.pos.z+WINDOW_H/4+self.Scale.z*((80+45+self.Sprites[par.name].height)*(y+0.5)+self.offsets.top) else byPos = self.pos.z+WINDOW_H/4+self.Scale.z*((80+45+self.Sprites[par.name].height)*(y+0.5)+self.offsets.top) end self.Sprites[par.name]:SetScale(self.Scale.x,self.Scale.z) self.Sprites[par.name]:Draw(bxPos,byPos,255) bxPos = self.pos.x+self.Scale.x*(self.Sprites["mid"].width/2+self.Sprites[par.name].width/2-self.Sprites[par.list[par.value]].width/2+40+self.offsets.buttonwidth) byPos = self.pos.z+WINDOW_H/4+self.Scale.z*((80+45+self.Sprites[par.name].height)*(y+0.5)+self.offsets.top) self.Sprites[par.list[par.value]]:SetScale(self.Scale.x*0.5,self.Scale.z*0.5) self.Sprites[par.list[par.value]]:Draw(bxPos,byPos, 255) elseif par.code == SCRIPT_PARAM_INFO then end c = c+1 end end if self.resize then self.Sprites["drag_selected"]:SetScale(self.Scale.x,self.Scale.z) --self.Sprites[par.."_selected"].height self.Sprites["drag_selected"]:Draw(self.pos.x+self.Scale.x*self.offsets.width-self.Scale.x*self.offsets.bot/2, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*#self.states)-self.Scale.z*self.offsets.bot/2, 255) else self.Sprites["drag"]:SetScale(self.Scale.x,self.Scale.z) self.Sprites["drag"]:Draw(self.pos.x+self.Scale.x*self.offsets.width-self.Scale.x*self.offsets.bot/2-1, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*#self.states)-self.Scale.z*self.offsets.bot/2-1, 255) end end end function sScriptConfig:Tick() if not self.loaded then self.loaded = true self:load() self:Load_Sprites() end local cursor = GetCursorPos() if self.resize then if self.Scale.x > 0.2 and cursor.x+15 < self.pos.x+self.Scale.x*self.offsets.width-self.Scale.x*self.offsets.bot/2 and cursor.y < self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*#self.states+self.offsets.bot)-self.Scale.z*self.offsets.bot/2 then self.Scale = {x = self.Scale.x-0.05, z = self.Scale.z-0.05} elseif self.Scale.x < 1 and cursor.x-15 > self.pos.x+self.Scale.x*self.offsets.width and cursor.y > self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*#self.states+self.offsets.bot) then self.Scale = {x = self.Scale.x+0.05, z = self.Scale.z+0.05} end end if self.move then self.pos = {x = cursor.x-self.touch.x, z = cursor.y-self.touch.z} self.pos = {x = self.pos.x < 0 and 0 or (self.pos.x+self.Scale.x*self.offsets.width > WINDOW_W and WINDOW_W-self.Scale.x*self.offsets.width or self.pos.x), z = self.pos.z < -WINDOW_H/4 and -WINDOW_H/4 or self.pos.z} end for _,par in pairs(self.par) do if par.state == self.state and par.code == SCRIPT_PARAM_SLICE then for k=1,#par.slider do if self.slide[k] then local val = self.touch.z+(cursor.x-self.touch.x)/self.Scale.x/self.Sprites["code"..SCRIPT_PARAM_SLICE].width*100--((cursor.x-self.touch.x)*par.slider[k]/100-self.Sprites["SLICE"].width/100) val = val < 0 and 0 or (val > 100 and 100 or val) par.slider[k] = val end end end end end function sScriptConfig:Msg(Msg, Key) if not self.loaded or self.hadToDownload then return end local cursor = GetCursorPos() if Msg == KEY_DOWN and Key > 16 and self.keyChange then for _,par in pairs(self.par) do if par.state == self.state and self.keyChange == par and (par.code == SCRIPT_PARAM_ONKEYDOWN or par.code == SCRIPT_PARAM_ONKEYTOGGLE) then if self.Sprites[Key] then par.key = Key self.keyChange = nil self:save() end end end end if Msg == KEY_DOWN and Key > 16 then for _,par in pairs(self.par) do if par.code == SCRIPT_PARAM_ONKEYTOGGLE and par.key == Key then par.value = not par.value if par.value then PrintAlertRed(par.state.." "..par.name.." is now on!") else PrintAlertRed(par.state.." "..par.name.." is now off!") end end end end if Msg == KEY_UP and Key == 16 then self:save() end if Msg == WM_LBUTTONDOWN and (self.keyChange or IsKeyDown(16)) then if CursorIsUnder(self.pos.x+self.Scale.x*self.offsets.width-self.Scale.x*self.offsets.bot/2, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*#self.states)-self.Scale.z*self.offsets.bot/2, self.Scale.x*self.offsets.width-self.Scale.x*self.offsets.bot/2, self.Scale.z*self.offsets.bot/2) then self.resize = true end if CursorIsUnder(self.pos.x, self.pos.z+WINDOW_H/4, self.Scale.x*self.offsets.width, self.Scale.z*self.offsets.top) then self.touch = {x = cursor.x-self.pos.x, z = cursor.y-self.pos.z} self.move = true end local a = 0 local c = 0 local y = 0 for _,par in pairs(self.par) do if par.state == self.state and self.Sprites["code"..par.code] then if c == 4 then c = 0 y = y + 1 end bxPos = self.pos.x+self.Scale.x*(self.Sprites["code"..par.code].width*(c)+40+c*45+self.offsets.buttonwidth) byPos = self.pos.z+WINDOW_H/4+self.Scale.z*(20+(40+self.Sprites["code"..par.code].height)*(y)+self.offsets.top) if par.code == SCRIPT_PARAM_ONOFF then if CursorIsUnder(bxPos, byPos, self.Scale.x*self.Sprites["code"..par.code].width, self.Scale.z*self.Sprites["code"..par.code].height) then par.value = not par.value self:save() end elseif par.code == SCRIPT_PARAM_ONKEYDOWN or par.code == SCRIPT_PARAM_ONKEYTOGGLE then a = a + 1 local b = 0 local ppos = par.name local kpos = par.key for _,k in pairs(self.par) do if par.state == k.state and (k.code == SCRIPT_PARAM_ONKEYDOWN or k.code == SCRIPT_PARAM_ONKEYTOGGLE) then ppos = k.name kpos = k.key b = b + 1 end end xOffset = b > 1 and self.Scale.x*(0-a*self.Sprites["mid"].width/(2*b)+(b+0.75)*self.Sprites["mid"].width/(4*b)) or 0 sprite = par.key > 32 and "Button\\"..string.char(par.key) or "Button\\".."Space" if CursorIsUnder(self.pos.x+xOffset+self.Scale.x*(self.offsets.buttonwidth+self.Sprites["mid"].width/2-self.Sprites[par.key].width/2-1),self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*#self.states-self.Sprites[par.key].height/2-self.Sprites[par.name].height*2-20), self.Scale.x*self.Sprites[par.key].width, self.Scale.z*self.Sprites[par.key].height) then self.keyChange = par end elseif par.code == SCRIPT_PARAM_SLICE then if c > 0 then y = y + 1 c = 0 end if y == 0 then y = 0.2+0.05*#par.slider end if y == 2 then y = 1.5 end for k=1,#par.slider do sxPos = self.pos.x+self.Scale.x*((self.Sprites["code"..par.code].width+70)*par.slider[k]/100+k*2+self.offsets.buttonwidth-self.Sprites["SLIDER_"..k].width/2+self.Sprites["mid"].width/2-self.Sprites["code"..par.code].width/2) syPos = self.pos.z+WINDOW_H/4+self.Scale.z*(30+self.offsets.top-self.Sprites["SLIDER_"..k].height+self.offsets.button*(#self.states-3)*y) if CursorIsUnder(sxPos,syPos,self.Sprites["SLIDER_"..k].width,self.Sprites["SLIDER_"..k].height) then self.touch = {x = cursor.x, z = par.slider[k]} self.slide[k] = true break end end elseif par.code == SCRIPT_PARAM_LIST then if c > 0 then y = y +1 end bxPos = self.pos.x+self.Scale.x*(self.Sprites["mid"].width/2+self.Sprites[par.name].width/2-self.Sprites[par.list[par.value]].width/2+40+self.offsets.buttonwidth) byPos = self.pos.z+WINDOW_H/4+self.Scale.z*((80+45+self.Sprites[par.name].height)*(y+0.5)+self.offsets.top) if CursorIsUnder(bxPos, byPos, self.Scale.x*self.Sprites[par.list[par.value]].width, self.Scale.z*self.Sprites[par.list[par.value]].height) then par.value = par.value + 1 if par.value > #par.list then par.value = 1 end end end c = c+1 end end for _,k in pairs(self.states) do if not self.substates[k] then if CursorIsUnder(self.pos.x, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*(_-1)), self.Scale.x*self.offsets.buttonwidth, self.Scale.z*self.offsets.button) then self.state = k end else for v,l in pairs(self.substates[k]) do if CursorIsUnder(self.pos.x, self.pos.z+WINDOW_H/4+self.Scale.z*(self.offsets.top+self.offsets.button*(_-1)+self.offsets.button/2*(v-1)), self.Scale.x*self.offsets.buttonwidth, self.Scale.z*self.offsets.button/2) then self.state = l end end end end elseif Msg == WM_LBUTTONUP then self.resize = false self.move = false for _,par in pairs(self.par) do if par.state == self.state and par.code == SCRIPT_PARAM_SLICE then for k=1,#par.slider do if self.slide[k] then self.slide[k] = false end end end end end end -- -- Alerter Class -- written by Weee -- adjusted so it doesn't create a scriptConfig instance --[[ PrintAlert(text, duration, r, g, b, sprite) - Pushes an alert message (notification) to the middle of the screen. Together with first message it also adds a configuration menu to the scriptConfig. text: Alert text - <string> ]] local __mAlerter, __Alerter_OnTick, __Alerter_OnDraw = nil, nil, nil function PrintAlertRed(text, duration) if not __mAlerter then __mAlerter = __Alerter() end return __mAlerter:Push(text, duration, 255, 0, 0) end class("__Alerter") function __Alerter:__init() if not __Alerter_OnTick then function __Alerter_OnTick() if __mAlerter then __mAlerter:OnTick() end end AddTickCallback(__Alerter_OnTick) end if not __Alerter_OnDraw then function __Alerter_OnDraw() if __mAlerter then __mAlerter:OnDraw() end end AddDrawCallback(__Alerter_OnDraw) end self.yO = -WINDOW_H * 0.25 self.x = WINDOW_W/2 self.y = WINDOW_H/2 + self.yO self._alerts = {} self.activeCount = 0 return self end function __Alerter:OnTick() self.yO = -WINDOW_H * 0.25 self.x = WINDOW_W/2 self.y = WINDOW_H/2 + self.yO --if #self._alerts == 0 then self:__finalize() end end function __Alerter:OnDraw() local gameTime = GetInGameTimer() for i, alert in ipairs(self._alerts) do self.activeCount = 0 for j = 1, i do local cAlert = self._alerts[j] if not cAlert.outro then self.activeCount = self.activeCount + 1 end end if self.activeCount <= 3 and (not alert.playT or alert.playT + 0.5*2 + alert.duration > gameTime) then alert.playT = not alert.playT and self._alerts[i-1] and (self._alerts[i-1].playT + 0.5 >= gameTime and self._alerts[i-1].playT + 0.5 or gameTime) or alert.playT or gameTime local intro = alert.playT + 0.5 > gameTime alert.outro = alert.playT + 0.5 + alert.duration <= gameTime alert.step = alert.outro and math.min(1, (gameTime - alert.playT - 0.5 - alert.duration) / 0.5) or gameTime >= alert.playT and math.min(1, (gameTime - alert.playT) / 0.5) or 0 local xO = alert.outro and self:Easing(alert.step, 0, 50) or self:Easing(alert.step, -50, 50) local alpha = alert.outro and self:Easing(alert.step, 255, -255) or self:Easing(alert.step, 0, 255) local yOffsetTar = GetTextArea(alert.text, 20).y * 1.2 * (self.activeCount-1) alert.yOffset = intro and alert.step == 0 and yOffsetTar or #self._alerts > 1 and not alert.outro and (alert.yOffset < yOffsetTar and math.min(yOffsetTar, alert.yOffset + 0.5) or alert.yOffset > yOffsetTar and math.max(yOffsetTar, alert.yOffset - 0.5)) or alert.yOffset local x = self.x + xO local y = self.y - alert.yOffset -- outline: local o = 1--TODO if o > 0 then for j = -o, o do for k = -o, o do DrawTextA(alert.text, 20, math.floor(x+j), math.floor(y+k), ARGB(alpha, 0, 0, 0), "center", "center") end end end -- sprite: if alert.sprite then alert.sprite:SetScale(alert.spriteScale, alert.spriteScale) alert.sprite:Draw(math.floor(x - GetTextArea(alert.text, 20).x/2 - alert.sprite.width * alert.spriteScale * 1.5), math.floor(y - alert.sprite.width * alert.spriteScale / 2), alpha) end -- text: DrawTextA(alert.text, 20, math.floor(x), math.floor(y), ARGB(alpha, alert.r, alert.g, alert.b), "center", "center") elseif alert.playT and alert.playT + 0.5*2 + alert.duration <= gameTime then table.remove(self._alerts, i) end end end function __Alerter:Push(text, duration, r, g, b, sprite) local alert = {} alert.text = text alert.sprite = sprite alert.spriteScale = sprite and 20 / sprite.height alert.duration = duration or 1 alert.r = r alert.g = g alert.b = b alert.parent = self alert.yOffset = 0 alert.reset = function(duration) alert.playT = GetInGameTimer() - 0.5 alert.duration = duration or 0 alert.yOffset = GetTextArea(alert.text, 20).y * (self.activeCount-1) end self._alerts[#self._alerts+1] = alert return alert end function __Alerter:Easing(step, sPos, tPos) step = step - 1 return tPos * (step ^ 3 + 1) + sPos end function __Alerter:__finalize() __Alerter_OnTick = nil __Alerter_OnDraw = nil __mAlerter = nil end
return function() local Option = require(script.Parent.Parent.Parent.Option) local assign = require(script.Parent.Parent.Parent.TableUtils.assign) it("should accept zero additional tables", function() local input = {} local result = assign(input) expect(input).to.equal(result) end) it("should merge multiple tables onto the given target table", function() local target = { a = 5, b = 6, } local source1 = { b = 7, c = 8, } local source2 = { b = 8, } assign(target, source1, source2) expect(target.a).to.equal(5) expect(target.b).to.equal(source2.b) expect(target.c).to.equal(source1.c) end) it("should remove keys if specified as None", function() local target = { foo = 2, bar = 3, } local source = { foo = Option.None, } assign(target, source) expect(target.foo).to.equal(nil) expect(target.bar).to.equal(3) end) it("should re-add keys if specified after None", function() local target = { foo = 2, } local source1 = { foo = Option.None, } local source2 = { foo = 3, } assign(target, source1, source2) expect(target.foo).to.equal(source2.foo) end) end
local wezterm = require 'wezterm' actions = { wezterm.on('trigger-vim-with-scrollback', function(window, pane) local scrollback = pane:get_lines_as_text() local name = os.tmpname() local f = io.open(name, 'w+') f:write(scrollback) f:flush() f:close() window:perform_action( wezterm.action { SpawnCommandInNewWindow = { args = { 'nvim', name }, } }, pane ) wezterm.sleep_ms(1000) os.remove(name) end), wezterm.on("toggle-ligatures", function(win, pane) local overrides = win:get_config_overrides() or {} if not overrides.harfbuzz_features then overrides.harfbuzz_features = {"calt=0", "clig=0", "liga=0"} else overrides.harfbuzz_features = nil end win:set_config_overrides(overrides) end), wezterm.on("toggle-opacity", function(win, pane) local overrides = win:get_config_overrides() or {} if not overrides.window_background_opacity then overrides.window_background_opacity = 0.5; else overrides.window_background_opacity = nil end win:set_config_overrides(overrides) end), wezterm.on('open-file-manager', function(win, pane) local f = io.popen ("/bin/hostname") local hostname = f:read("*a") or "" f:close() local hostname = hostname:gsub("%s+", "") local curentDir = pane:get_current_working_dir() local dirPath = curentDir:gsub("file://" .. hostname, "") local success, stdout, stderr = wezterm.run_child_process({"xdg-open", dirPath }) end), getColorscheme = function(dark, light, hour) if not light then return dark end local hour = hour and hour or 18 local currentHour = tonumber(os.date('%H')) if currentHour > 5 and currentHour < hour then return light else return dark end end, } return actions
-- classical-physics data:extend({ { type = "technology", name = "classical-physics", icon = "__fundamental_physics__/graphics/technology/classical-physics.png", icon_size = 128, effects = {}, unit = { count_formula = "5", ingredients = { {"science-pack-1", 1}, }, time = 30 }, upgrade = false, order = "e-l-g" }, }) if data.raw.technology["basic-automation"] then mylib.add_prerequisite("basic-automation", "classical-physics") else mylib.add_prerequisite("automation", "classical-physics") end if data.raw.technology["basic-logistics"] then mylib.add_prerequisite("basic-logistics", "classical-physics") else mylib.add_prerequisite("logistics", "classical-physics") end if data.raw.recipe["facility-science-pack-1"] then mylib.add_prerequisite("facility-1", "classical-physics") end mylib.add_prerequisite("optics", "classical-physics") for i=1,3 do table.insert(data.raw.technology["classical-physics"].effects,{ type = "unlock-recipe", recipe = "research-report-integration-"..i }) table.insert(data.raw.technology["classical-physics"].effects,{ type = "unlock-recipe", recipe = "research-report-secondary-analysis-"..i }) end -- spectral-analysis data:extend({ { type = "technology", name = "spectral-analysis-1", icon = "__fundamental_physics__/graphics/technology/spectral-analysis.png", icon_size = 256, effects = { { type = "unlock-recipe", recipe = "fundamental-physics-research-center-mk1" }, { type = "unlock-recipe", recipe = "particle-physics-analysis-center-mk1" }, { type = "unlock-recipe", recipe = "research-report-integration-4" },{ type = "unlock-recipe", recipe = "research-report-secondary-analysis-4" } }, unit = { count_formula = "500", ingredients = { {"science-pack-1", 1}, {"science-pack-2", 1}, }, time = 45 }, prerequisites = {"optics"}, upgrade = true, max_level = "1", order = "e-l-g" }, { type = "technology", name = "spectral-analysis-2", icon = "__fundamental_physics__/graphics/technology/spectral-analysis.png", icon_size = 256, effects = { { type = "laboratory-productivity", modifier = 0.02 } }, unit = { count_formula = "1000*L^(1.2)", ingredients = { {"research-report-1", 3}, {"research-report-2", 2}, {"research-report-3", 2}, {"research-report-4", 1}, {"research-report-5", 1}, }, time = 45 }, prerequisites = {"spectral-analysis-1"}, upgrade = true, max_level = "infinite", order = "e-l-g" }, }) if data.raw.technology["facility-1"] then mylib.add_prerequisite("spectral-analysis-1", "facility-1") else table.insert(data.raw.technology["spectral-analysis-1"].effects,{ type = "unlock-recipe", recipe = "facility-mk1" }) end for k,v in pairs(data.raw.recipe) do if string.sub(v.name, 1,17)=="spectral-analysis" then table.insert(data.raw.technology["spectral-analysis-1"].effects,{ type = "unlock-recipe", recipe = v.name }) end end -- standard-model data:extend({ { type = "technology", name = "standard-model-1", icon = "__fundamental_physics__/graphics/technology/standard-model.png", icon_size = 256, effects = { { type = "laboratory-productivity", modifier = 0.02 }, { type = "unlock-recipe", recipe = "fundamental-physics-research-center-mk2" }, { type = "unlock-recipe", recipe = "particle-physics-analysis-center-mk2" }, { type = "unlock-recipe", recipe = "particle-collision-10mev" }, { type = "unlock-recipe", recipe = "particle-collision-100mev" }, { type = "unlock-recipe", recipe = "research-report-integration-5" },{ type = "unlock-recipe", recipe = "research-report-secondary-analysis-5" } }, unit = { count_formula = "1000", ingredients = { {"science-pack-1", 1}, {"science-pack-2", 1}, {"science-pack-3", 1}, {"military-science-pack", 1}, {"production-science-pack", 1}, {"high-tech-science-pack", 1} }, time = 60 }, prerequisites = {"spectral-analysis-1"}, upgrade = true, max_level = "1", order = "e-l-g" }, { type = "technology", name = "standard-model-2", icon = "__fundamental_physics__/graphics/technology/standard-model.png", icon_size = 256, effects = { { type = "laboratory-productivity", modifier = 0.02 }, { type = "unlock-recipe", recipe = "particle-collision-1gev" }, { type = "unlock-recipe", recipe = "particle-collision-10gev" }, { type = "unlock-recipe", recipe = "particle-collision-100gev" }, { type = "unlock-recipe", recipe = "particle-collision-250gev" }, { type = "unlock-recipe", recipe = "particle-accelerator-mk3" }, }, unit = { count_formula = "2000*L^(1.2)", ingredients = { {"research-report-1", 3}, {"research-report-2", 3}, {"research-report-3", 2}, {"research-report-4", 2}, {"research-report-5", 1}, {"research-report-6", 1}, }, time = 60 }, prerequisites = {"standard-model-1"}, upgrade = true, max_level = "2", order = "e-l-g" }, { type = "technology", name = "standard-model-3", icon = "__fundamental_physics__/graphics/technology/standard-model.png", icon_size = 256, effects = { { type = "laboratory-productivity", modifier = 0.02 } }, unit = { count_formula = "2000*L^(1.2)", ingredients = { {"research-report-1", 3}, {"research-report-2", 3}, {"research-report-3", 2}, {"research-report-4", 2}, {"research-report-5", 1}, {"research-report-6", 1}, }, time = 60 }, prerequisites = {"standard-model-2"}, upgrade = true, max_level = "infinite", order = "e-l-g" }, }) if data.raw.technology["facility-1"] then mylib.add_prerequisite("standard-model-1", "facility-2") mylib.add_prerequisite("standard-model-1", "particle-accelerator-2") else table.insert(data.raw.technology["standard-model-1"].effects,{ type = "unlock-recipe", recipe = "facility-mk2" }) table.insert(data.raw.technology["standard-model-2"].effects,{ type = "unlock-recipe", recipe = "facility-mk3" }) table.insert(data.raw.technology["standard-model-1"].effects,{ type = "unlock-recipe", recipe = "particle-accelerator-mk1" }) table.insert(data.raw.technology["standard-model-1"].effects,{ type = "unlock-recipe", recipe = "particle-accelerator-mk2" }) end -- deep-space-accelerator data:extend({ { type = "technology", name = "deep-space-accelerator", icon = "__fundamental_physics__/graphics/technology/deep-space-accelerator.png", icon_size = 256, effects = { { type = "unlock-recipe", recipe = "deep-space-accelerator" }, { type = "unlock-recipe", recipe = "fundamental-physics-research-center-mk3" }, { type = "unlock-recipe", recipe = "particle-physics-analysis-center-mk3" }, { type = "unlock-recipe", recipe = "particle-accelerator-mk4" },{ type = "unlock-recipe", recipe = "research-report-integration-6" },{ type = "unlock-recipe", recipe = "research-report-secondary-analysis-6" } }, unit = { count_formula = "5000", ingredients = { {"science-pack-1", 1}, {"science-pack-2", 1}, {"science-pack-3", 1}, {"production-science-pack", 1}, {"high-tech-science-pack", 1}, {"space-science-pack", 1} }, time = 60 }, prerequisites = {"standard-model-2", "rocketry"}, upgrade = false, order = "e-l-g" }, }) -- superstring-theory data:extend({ { type = "technology", name = "superstring-theory-1", icon = "__fundamental_physics__/graphics/technology/superstring-theory.png", icon_size = 128, effects = { { type = "laboratory-productivity", modifier = 0.02 }, }, unit = { count_formula = "3000*L^(1.2)", ingredients = { {"research-report-1", 4}, {"research-report-2", 4}, {"research-report-3", 3}, {"research-report-4", 3}, {"research-report-5", 2}, {"research-report-6", 2}, {"research-report-7", 1}, }, time = 60 }, prerequisites = {"deep-space-accelerator"}, upgrade = true, max_level = "infinite", order = "e-l-g" }, }) mylib.add_prerequisite("superstring-theory", "facility-3")
-- manage a pool of worker threads running arbitrary lua tasks -- copyright 2017 Samuel Baird MIT Licence local class = require('core.class') local array = require('core.array') local rascal = require('rascal.core') local proxy_client = require('rascal.proxy.client') local proxy_server = require('rascal.proxy.server') local random_key = require('rascal.util.random_key') return class(function (task_server) local worker_api_description = { worker_is_idle = 'worker_id:string', worker_did_yield_result = 'worker_id:string, result:*', worker_request_work = 'worker_id:string -> task:*', worker_did_close = 'worker_id:string', -- allow a proxy inside tasks to queue more tasks worker_queue_lua = 'lua_source:string, parameters:*', worker_queue_lua_file = 'lua_filename:string, parameters:*', } local publish_signal_api_description = { worker_signal_waiting = '', worker_signal_close = '', } function task_server:init(no_workers, use_external_process) self.id = 'task_server:' .. random_key.printable(16) if use_external_process then self.channel_prefix = 'ipc://' .. self.id else self.channel_prefix = 'inproc://' .. self.id end -- push and pop work queue as a stack, pop newest task, not oldest task, to limit overfilling queues from several layers of producers self.workers = {} self.work_queue = array() proxy_server(self, worker_api_description, self.channel_prefix .. '.api', zmq.REP) self.publish = proxy_server(self, publish_signal_api_description, self.channel_prefix .. '.pub', zmq.PUB) for i = 1, no_workers do self:add_worker(i, use_external_process) end end function task_server:add_worker(worker_id, use_external_process) local worker = { id = worker_id, idle = true, on_result = nil } self.workers[worker_id] = worker -- implement external process version of detach if use_external_process then detach_process("require('rascal.util.task_server').run_as_worker(worker_id, channel_prefix)", { worker_id = worker_id, channel_prefix = self.channel_prefix }) else detach("require('rascal.util.task_server').run_as_worker(worker_id, channel_prefix)", { worker_id = worker_id, channel_prefix = self.channel_prefix }) end end -- usage API -- function task_server:queue_lua(lua_source, parameters, on_result, task_or_filename) self.work_queue:push({ lua_source = lua_source, parameters = parameters, on_result = on_result, name = task_or_filename or '<anonymous_task>', }) self.publish:worker_signal_waiting() end function task_server:queue_lua_file(lua_filename, parameters, on_result) local input = assert(io.open(lua_filename, 'r'), 'could not read lua task file ' .. lua_filename) local source = input:read('*a') input:close() return self:queue_lua(source, parameters, on_result, lua_filename) end function task_server:is_complete() if not self.work_queue:is_empty() then return false end for _, worker in pairs(self.workers) do if not worker.idle then return false end end return true end function task_server:close() while true do self.publish:worker_signal_close() loop:sleep_ex(100) local all_closed = true for _, worker in pairs(self.workers) do if not worker.closed then all_closed = false end end if all_closed then break end end end function task_server:complete(close) -- keep polling the main event loop until the task server is marked as complete while not self:is_complete() do loop:sleep_ex(100) end if close then self:close() end -- clean up events loop:sleep_ex(100) end -- worker API -- function task_server:worker_is_idle(worker_id) local worker = self.workers[worker_id] if worker then worker.on_result = nil worker.idle = true end end function task_server:worker_did_yield_result(worker_id, result) local worker = self.workers[worker_id] if worker and worker.on_result then worker.on_result(result) end end function task_server:worker_request_work(worker_id) local worker = self.workers[worker_id] local task = self.work_queue:pop() if worker and task then worker.idle = false worker.on_result = task.on_result return { name = task.name, lua_source = task.lua_source, parameters = task.parameters, } end end function task_server:worker_did_close(worker_id) local worker = self.workers[worker_id] if worker then worker.closed = true end end function task_server:worker_queue_lua(...) return self:queue_lua(...) end function task_server:worker_queue_lua_file(...) return self:queue_lua_file(...) end function task_server.run_as_worker(worker_id, channel_prefix) local working = false local api = proxy_client(channel_prefix .. '.api', zmq.REQ, worker_api_description) local function handle_work(name, lua_source, parameters) local thread_code = array() -- create the environment of local vars for this function local environment = {} environment.worker_id = worker_id environment.api = api if parameters then for k, v in pairs(parameters) do environment[k] = v end end -- preamble thread_code:push([[local environment = ...]]) for name, _ in pairs(environment) do thread_code:push('local ' .. name .. ' = environment.' .. name) end -- insert some direct proxy functions thread_code:push('yield = function (value) api:worker_did_yield_result(worker_id, value) end') thread_code:push('queue_lua = function (source, parameters, on_result) assert(on_result == nil, "no callback possible on worker queued task") api:worker_queue_lua(source, parameters) end') thread_code:push('queue_lua_file = function (filename, parameters, on_result) assert(on_result == nil, "no callback possible on worker queued task") api:worker_queue_lua_file(lua_filename, parameters) end') -- assemble the code thread_code:push(lua_source) local code_string = table.concat(thread_code, ' ') -- print(code_string) -- compile task code local fn, message = loadstring(code_string, name) if not fn then error(message .. '\n' .. code_string) end -- finally run the task fn(environment) end local function request_work_if_idle() if working then return end working = true local task = api:worker_request_work(worker_id) if not task then working = false return end local success, result = pcall_trace(handle_work, task.name, task.lua_source, task.parameters) if success then if type(result) ~= 'nil' then api:worker_did_yield_result(worker_id, result) end else log('error in task: [' .. task.name ..'] ' .. result) end working = false api:worker_is_idle(worker_id) -- check again for work after full callstack unwind loop:add_time(1, request_work_if_idle) end -- connect signals from the co-ordinator push API local signals = { worker_signal_waiting = request_work_if_idle, worker_signal_close = function () api:worker_did_close(worker_id) loop:sleep_ex(1000) loop:stop() end } proxy_server(signals, publish_signal_api_description, channel_prefix .. '.pub', zmq.SUB) -- connect timer event as a fall back from published signals loop:add_interval(500, request_work_if_idle) -- once the loop starts request the first work loop:add_time(0, request_work_if_idle) -- event loop driven from now on rascal.run_loop() end end)