content
stringlengths
5
1.05M
-- Tests for caesar_cipher.lua local caesar = require 'caesar_cipher' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end run('Ciphering test', function() assert(caesar.cipher('abcd',1) == 'bcde') assert(caesar.cipher('WXYZ',2) == 'YZAB') assert(caesar.cipher('abcdefghijklmnopqrstuvwxyz',3) == 'defghijklmnopqrstuvwxyzabc') assert(caesar.cipher('ABCDEFGHIJKLMNOPQRSTUVWXYZ',4) == 'EFGHIJKLMNOPQRSTUVWXYZABCD') end) run('Deciphering test', function() assert(caesar.decipher('bcde',1) == 'abcd') assert(caesar.decipher('YZAB',2) == 'WXYZ') assert(caesar.decipher('defghijklmnopqrstuvwxyzabc',3) == 'abcdefghijklmnopqrstuvwxyz') assert(caesar.decipher('EFGHIJKLMNOPQRSTUVWXYZABCD',4) == 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
--DEBUG = true local class if DEBUG == false then class = require("lib.external.30log") require("lib.orm.model") else class = require("30log") require("table_util") require("model") end local Casa = Model:extend("Casa", { columns = { nome = {}, idade = { notNull=true } }, belongsTo={ pessoa='Pessoa' } }) function Casa:init(columns) Casa.super:init(columns, self) end return Casa
-- vim.cmd [[ packadd nvim-lsp-installer ]] local lsp_installer = require("nvim-lsp-installer") local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()) local installed_servers = require'nvim-lsp-installer.servers' -- Provide settings first! lsp_installer.settings { ui = { icons = { server_installed = "✓", server_pending = "➜", server_uninstalled = "✗" }, borders = false, keymaps = { -- Keymap to expand a server in the UI toggle_server_expand = "<CR>", -- Keymap to install a server install_server = "i", -- Keymap to reinstall/update a server update_server = "u", -- Keymap to uninstall a server uninstall_server = "X", }, }, -- The directory in which to install all servers. install_root_dir = vim.fn.stdpath("data") .. "lsp_servers", pip = { -- These args will be added to `pip install` calls. Note that setting extra args might impact intended behavior -- and is not recommended. -- -- Example: { "--proxy", "https://proxyserver" } install_args = {}, }, -- Controls to which degree logs are written to the log file. It's useful to set this to vim.log.levels.DEBUG when -- debugging issues with server installations. log_level = vim.log.levels.INFO, -- Limit for the maximum amount of servers to be installed at the same time. Once this limit is reached, any further -- servers that are requested to be installed will be put in a queue. max_concurrent_installers = 4, } lsp_installer.on_server_ready(function (server) server:setup { on_attach = require('lsp').on_attach, capabilities = capabilities } vim.cmd [[ do User LspAttachBuffers ]] end)
-- 比较两数大小 function max(num1, num2) if (num1 > num2) then result = num1; else result = num2; end return result; end -- 调用函数 print("两值比较最大值为 ",max(10,4)) print("两值比较最大值为 ",max(5,6)) -- 将函数作为参数传递给另一个函数 myprint = function(param) -- 定义格式化打印函数 print("这是打印函数 - ##",param,"##") end function add(num1,num2,functionPrint) result = num1 + num2 -- 定义加法运算 -- 调用传递的函数参数 functionPrint(result) end myprint(10) -- 直接调用打印函数 -- myprint 函数作为参数传递 add(2,5,myprint) -- 将打印函数作为加法函数的一个参数
local path = require('plenary.path') local Job = require('plenary.job') local utils = require('noteflow.utils') local note = require('noteflow.notes') local config = require('noteflow.config') local log = utils.log local text_iterator = utils.text_iterator local from_paths = utils.from_paths local luv = vim.loop local get_mt_time = function(fn) local stat = luv.fs_lstat(fn) return stat.mtime.sec end local mt = {} mt.__index = mt local cache = { notes = {} } local already_run = false function mt:initialized() return already_run end function mt:by_title(title) for _,meta in pairs(self.notes) do if meta.title == title then return meta end end end mt.refresh = utils.async(function(_, opts) opts = opts or {} local tmpl_dir = config.templates_dir if not already_run and not opts.silent then vim.cmd('echo "Refreshing note cache for the first time..."') end local processing = 0 local processed = 0 local args = config.find_command() local vault_dir = config.vault_dir local new_notes = {} local notes = cache.notes local cor = coroutine.running() local job = Job:new{ command = args[1], args = vim.list_slice(args, 2), cwd = vault_dir, on_stdout = function(_,fn,_) fn = from_paths(vault_dir, fn):absolute() if not fn or fn == "" then return end if tmpl_dir and fn:sub(1,#tmpl_dir) == tmpl_dir then return end local mt_time = nil if notes[fn] then mt_time = get_mt_time(fn) local meta = notes[fn] new_notes[fn] = meta if meta.mt_time == mt_time then if opts.on_insert then opts.on_insert(meta) end return end end processing = processing + 1 path:new(fn):read(function(text) local meta = note.parse_note(text_iterator(text), fn) meta.mt_time = mt_time or get_mt_time(fn) new_notes[fn] = meta if opts.on_insert then pcall(opts.on_insert,meta) end processed = processed + 1 if processed >= processing then cache.notes = new_notes utils.resume(cor) end end) end, on_stderr = function(error) print('Error while indexing notes: ' .. error) end, on_exit = function() if processing == 0 then cache.notes = new_notes utils.resume(cor) end end } job:start() already_run = true coroutine.yield() end) return setmetatable(cache, mt)
----------------------------------- -- Area: Alzadaal Undersea Ruins -- ZNM: Cheese Hoarder Gigiroon -- TODO: Running around mechanic and dropping bombs ----------------------------------- mixins = {require("scripts/mixins/rage")} require("scripts/globals/status") ----------------------------------- function onMobInitialize(mob) mob:setMobMod(tpz.mobMod.IDLE_DESPAWN, 300) end function onMobSpawn(mob) mob:setLocalVar("[rage]timer", 3600) -- 60 minutes end function onMobFight(mob, target) end function onMobDeath(mob) end
--[[ desc: Input, a component with key map. author: Musoucrow since: 2018-3-29 alter: 2018-5-5 ]]-- ---@class Actor.Component.Input local _Input = require("core.class")() function _Input:Ctor() self.map = {} end return _Input
if game:GetService("RunService"):IsEdit() then local Sunshine = require(script.Parent.Sunshine) local PluginNetworkClient = require(script.Parent.PluginNetworkClient) for _, child in pairs(workspace:GetChildren()) do if child:IsA("Message") and child.Name == "SunshineSuiteWorkspace" then child:Destroy() end end Sunshine.workspace = Instance.new("Message") Sunshine.workspace.Name = "SunshineSuiteWorkspace" Sunshine.workspace.Parent = workspace Sunshine.gui = Instance.new("ScreenGui") Sunshine.gui.Name = "SunshineSuiteScreenGui" Sunshine.gui.IgnoreGuiInset = true -- why does this property need to exist it should always be true Sunshine.gui.ResetOnSpawn = false -- this should always be false, again why does it exist Sunshine.gui.Parent = game:GetService("CoreGui") -- TANGERINE Sunshine.plugin = plugin Sunshine.PluginNetworkClient = PluginNetworkClient PluginNetworkClient:init(plugin) Sunshine:manage() Sunshine:addSystemFolder(script:WaitForChild("systems")) Sunshine:loadScene(require(script:WaitForChild("scene"))) else wait(2) for _, child in pairs(workspace:GetChildren()) do if child:IsA("Message") and child.Name == "SunshineSuiteWorkspace" then child:Destroy() end end end
fn = vim.fn api = vim.api cmd = vim.cmd opt = vim.opt g = vim.g _G.theme = "paradise-dark" local modules = { 'options', 'mappings', 'statusline', 'colors', 'plugins', } for i, a in ipairs(modules) do local ok, err = pcall(require, a) if not ok then error("Error calling " .. a .. err) end end -- Auto commands cmd [[ au TermOpen term://* setlocal nonumber norelativenumber signcolumn=no | setfiletype terminal ]]
--[[ File Name : Friends.lua Created By : tubiakou Creation Date : [2019-01-07 01:28] Last Modified : [2019-02-11 22:07] Description : Friends class for the WoW addon AllFriends --]] --[[ This module of AllFriends implements a Friends class, responsible for all functionality related to the Friends List. This includes taking / restoring snapshots, providing information, etc. --]] --local addonName, AF = ... local addonName, AF_G = ... -- Some local overloads to optimize performance (i.e. stop looking up these -- standard functions every single time they are called, and instead refer to -- them by local variables. local string = string local strgsub = string.gsub local strlower = string.lower -- Class table AF.Friends = { -- Class data prototypes (i.e. "default" values for new objects) ---------------------------------------------------------------------------- class = "friends", -- Class identifier } AF.Friends_mt = { __index = AF.Friends } -- Class metatable --- Class constructor "new" -- Creates a new Friends object and sets initial state. -- @return The newly constructed and initialized Friends object function AF.Friends:new( ) local friendsObj = {} -- New object setmetatable( friendsObj, AF.Friends_mt ) -- Set up the object's metatable -- Per-object data initialization ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- return friendsObj end --- Class public method "getFriends" -- Returns a table representing all the friends currently in the friend list. -- The table is numerically indexed and takes the form: -- tFriendList = { -- playerObj1, -- [1] -- playerObj2, -- [2] -- ... -- playerObjx -- [x] -- } -- return tFriendList Table representing all friends currently in the friend list function AF.Friends:getFriends( ) local tFriendList = {} local numServerFriends = C_FriendList.GetNumFriends( ) debug:debug( "Friend list contains %d friends", numServerFriends ) local _, friendInfo, playerName, playerRealm for i = 1, numServerFriends do friendInfo = C_FriendList.GetFriendInfoByIndex( i ) playerName = strlower( strgsub( friendInfo.name, "-.+$", "" ) ) _, playerRealm = AF:getLocalizedRealm( friendInfo.name ) debug:debug( "Retrieved %s-%s (%d of %d) from friend-list", playerName, playerRealm, i, numServerFriends ) tFriendList[i] = AF.Player:new( playerName .. "-" .. playerRealm ) end debug:debug( "Done retrieving friends - returning [%s]", AF._tostring( tFriendList ) ) return tFriendList end --- Class public method "getFriendsAsNames" -- Returns a table representing all the friends currently in the friend list. -- The table takes the form: -- tFriendList = { -- [ "playername-playerrealm"] = 1, -- [ "anotherplayer-anotherrealm"] = 2, -- } -- return tFriendList Table representing all friends currently in the friend list function AF.Friends:getFriendsAsNames( ) local tFriendList = {} local numServerFriends = C_FriendList.GetNumFriends( ) debug:debug( "Friend list contains %d friends", numServerFriends ) local _, friendInfo, playerName, playerRealm for i = 1, numServerFriends do friendInfo = C_FriendList.GetFriendInfoByIndex( i ) playerName = strlower( strgsub( friendInfo.name, "-.+$", "" ) ) _, playerRealm = AF:getLocalizedRealm( friendInfo.name ) debug:debug( "Retrieved %s-%s (%d of %d) from friend-list", playerName, playerRealm, i, numServerFriends ) tFriendList[ playerName .. "-" .. playerRealm ] = i end debug:debug( "Done retrieving friends - returning [%s]", AF._tostring( tFriendList ) ) return tFriendList end --- Class public method "countFriendList" -- Returns the number of players in the current friend-list -- @return Number of players in the current friend-list function AF.Friends:countFriendList( ) local numFriends = C_FriendList.GetNumFriends( ) debug:debug( "C_FriendsList.GetNumFriends() returned %d", numFriends ) return numFriends end --- Class public method "isFriendListAvailable" -- It appears that when starting the game, the Friend List may not yet be -- available by the time events such as PLAYER_LOGIN and PLAYER_ENTERING_WORLD -- fire. This tests whether a friend-list is currently available. -- -- NOTE: this method assumes that the friend-list contains at-least one player. -- -- @return: true Friend-list is available. -- @return: false Friend-list is unavailable. function AF.Friends:isFriendListAvailable( ) local friendInfo = C_FriendList.GetFriendInfoByIndex( 1 ) if( friendInfo == nil ) then debug:debug( "GetFriendInfoByIndex() returned nil - server friend list unavailable." ) return false elseif( friendInfo.name == nil ) then debug:debug( "friendInfo.name is nil - server friend list unavailable." ) return false elseif( friendInfo.name == "" ) then debug:debug( "friendInfo.name is empty - server friend list unavailable." ) return false else debug:debug( "Server friend-list available." ) return true end end --- Class public method "findFriend" -- Takes the specified player object and indicates whether or not they are -- present in the current friend list. -- @param playerObj Player object to be checked within friend list -- @return true Specified player is in friend list -- @return false Specified player not in friend list, or invalid object function AF.Friends:findFriend( playerObj ) -- Parameter validation if( not playerObj ) then debug:warn( "Invalid player object - can't search within friends." ) return false end -- Identify player by name if on the local realm, or name-realm if on a -- connected realm, since this is what the WoW API current expects. local playerKey if( playerObj:isLocal( ) ) then playerKey = playerObj:getName( ) else playerKey = playerObj:getKey( ) end local friendReturn = C_FriendList.GetFriendInfo( playerKey ) if( friendReturn ~= nil ) then debug:debug( "Player %s is in friend list.", playerKey ) return true else debug:debug( "Player %s not in friend list.", playerKey ) return false end end --- Class public method "addFriend" -- Takes the specified player object and adds the player to the current friend -- list. The operation is idempotent - adding a friend that is already present -- will return success. -- @param playerObj Player object to be added to the friend list -- @return true Added successfully (or was already present) -- @return false Failure while adding friend function AF.Friends:addFriend( playerObj ) -- Parameter validation if( not playerObj ) then debug:warn( "Invalid player object - can't add to friend list." ) return false end -- Qualify the player name with the player's realm if the realm is not -- local. Otherwise use just the player's name. local playerKey if( playerObj:isLocal( ) ) then playerKey = playerObj:getName( ) else playerKey = playerObj:getKey( ) end if( not self:findFriend( playerObj ) ) then C_FriendList.AddFriend( playerKey ) debug:info( "Added %s to friend list.", playerKey ) end return true end --- Class public method "removeFriend" -- Takes the specified player object and ensures the player is no longer in the -- current friend list. The operation is idempotent; Removing a non-existent -- friend will return success. -- @param playerObj Player object to be removed from the friend list -- @return true Removed successfully (or was already not present) -- @return false Failure while removing friend function AF.Friends:removeFriend( playerObj ) -- Parameter validation if( not pcall( function( ) return playerObj:chkType( AF.Player.class ) end ) ) then debug:warn( "Invalid player object - can't remove from friend list." ) return false end -- Qualify the player name with the player's realm if the realm is not -- local. Otherwise use just the player's name. local playerKey if( playerObj:isLocal( ) ) then playerKey = playerObj:getName( ) else playerKey = playerObj:getKey( ) end if( not self:findFriend( playerObj ) ) then debug:debug( "Player %s already absent from friend list.", playerKey ) else C_FriendList.RemoveFriend( playerKey ) debug:info( "Removed %s from friend list.", playerKey ) end return true end --- Class public method "chkType" -- Asserts whether the specified class ID matches the ID of this class -- @param wantedType Class ID to assert against this class's ID -- @return true Returned of the specified class ID matches this class's ID -- @return <error raised by the assert() if the IDs don't match> function AF.Friends:chkType( wantedType ) return assert( self.class == wantedType ) end -- vim: autoindent tabstop=4 shiftwidth=4 softtabstop=4 expandtab
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild -- -- This file is compatible with Lua 5.3 local class = require("class") require("kaitaistruct") ExprIfIntOps = class.class(KaitaiStruct) function ExprIfIntOps:_init(io, parent, root) KaitaiStruct._init(self, io) self._parent = parent self._root = root or self self:_read() end function ExprIfIntOps:_read() self.skip = self._io:read_bytes(2) if true then self.it = self._io:read_s2le() end if true then self.boxed = self._io:read_s2le() end end ExprIfIntOps.property.is_eq_prim = {} function ExprIfIntOps.property.is_eq_prim:get() if self._m_is_eq_prim ~= nil then return self._m_is_eq_prim end self._m_is_eq_prim = self.it == 16705 return self._m_is_eq_prim end ExprIfIntOps.property.is_eq_boxed = {} function ExprIfIntOps.property.is_eq_boxed:get() if self._m_is_eq_boxed ~= nil then return self._m_is_eq_boxed end self._m_is_eq_boxed = self.it == self.boxed return self._m_is_eq_boxed end
local map_string = [[ ################################# #...............................# #..##...........................# #..##...............#...........# #...................##..........# #.....####...........#..........# #.....#..#...........##.........# #..#..#..#............###.......# #.....####...........#####......# #...............................# #................###......##....# #................###.....##.....# #................###....###.....# #...##...................#......# #...####....#...................# #....##....###........###.......# #...........#..........##.......# #....................####.......# #...............................# #...............................# #...............................# ################################# ]] local map = {size = {0, 0}, cels = {}} do -- Generate map from ascii local width = #map_string:match("[^\n]+") local x = 0 local y = 0 for row in map_string:gmatch("[^\n]+") do map.cels[y] = {} for char in row:gmatch(".") do map.cels[y][x] = {} if char == '#' then map.cels[y][x].type = 'wall' elseif char == 'A' then map.cels[y][x].type = 'arch' elseif char == 'T' then map.cels[y][x].type = 'trap' else map.cels[y][x].type = 'floor' end x = x + 1 end print(row) x = 0 y = y + 1 end print(width, y) map.size = {width - 1, y - 1} end return map
Objects = { createObject ( 6959, 997.5, 1323.7998, -10.1, 90, 0, 90 ), createObject ( 6959, 997.5, 1365.0996, -10.1, 90, 0, 90 ), createObject ( 6959, 997.5, 1406.4, -10.1, 90, 0, 90 ), createObject ( 6959, 997.5, 1447.7, -10.1, 90, 0, 90 ), createObject ( 6959, 997.5, 1489, -10.1, 90, 0, 90 ), createObject ( 6959, 997.5, 1530.2998, -10.1, 90, 0, 90 ), createObject ( 8171, 977.5, 1414.2002, -0.8 ), createObject ( 3115, 988.09998, 1533.1, 7.8, 0, 10, 270 ), createObject ( 3115, 988.09961, 1512.7002, 4.2, 0, 9.998, 270 ), createObject ( 3115, 988.09998, 1492.3, 0.6, 0, 9.998, 270 ), createObject ( 3115, 969.29999, 1492.3, 0.6, 0, 9.998, 270 ), createObject ( 3115, 969.29999, 1512.7, 4.2, 0, 9.998, 270 ), createObject ( 3115, 969.29999, 1533.1, 7.8, 0, 9.998, 270 ), createObject ( 6959, 959.90039, 1530.2002, -10.1, 90, 0, 90 ), createObject ( 6959, 959.90002, 1488.9, -10.1, 90, 0, 90 ), createObject ( 6959, 959.90002, 1447.6, -10.1, 90, 0, 90 ), createObject ( 6959, 959.90039, 1406.2998, -10.1, 90, 0, 90 ), createObject ( 6959, 959.5, 1349.4004, -10.1, 90, 0, 90 ), createObject ( 6959, 959.5, 1308.1, -10.1, 90, 0, 90 ), createObject ( 3997, 989, 1450.2002, -15.4, 0, 0, 90 ), createObject ( 8947, 990.09998, 1336.8, -5.6, 339.999, 0, 0 ), createObject ( 8947, 990.09998, 1359.6, -13.9, 339.999, 0, 0 ), createObject ( 8947, 990.09998, 1382.4, -22.2, 339.999, 0, 0 ), createObject ( 6959, 982.79999, 1349.5, -20.8, 90, 0, 90 ), createObject ( 6959, 982.7998, 1324.4004, -10.1, 90, 0.198, 90 ), createObject ( 6959, 977.5, 1340.2002, 9.9, 0, 0, 90 ), createObject ( 8947, 990.09961, 1313.7002, 2.8, 339.994, 0, 0 ), createObject ( 6959, 977.5, 1381.5, 9.9, 0, 0, 90 ), createObject ( 6959, 977.5, 1422.7998, 9.9, 0, 0, 90 ), createObject ( 6959, 977.5, 1464.0996, 9.9, 0, 0, 90 ), createObject ( 6959, 977.40039, 1486.0996, 9.9, 0.099, 0, 90 ), createObject ( 6959, 962.90039, 1298.9004, 9.9, 0, 0, 90 ), createObject ( 6959, 976.90002, 1530.3, -12.4, 90, 0, 0 ), createObject ( 6959, 935.59998, 1530.3, -12.4, 90, 0, 0 ), createObject ( 6959, 976.79999, 1365, -0.8 ), createObject ( 6959, 976.79999, 1404.9, -0.8 ), createObject ( 6959, 976.79999, 1444.9, -0.8 ), createObject ( 6959, 976.79999, 1484.9, -0.8 ), createObject ( 6959, 976.79999, 1524.9, -0.8 ), createObject ( 6959, 935.5, 1524.9, -0.8 ), createObject ( 6959, 962.09998, 1370.2, -20.8, 90, 0, 359.75 ), createObject ( 6959, 920.90002, 1370.4, -20.8, 90, 0, 359.747 ), createObject ( 6959, 935.5, 1484.9, -0.8 ), createObject ( 6959, 935.5, 1444.9, -0.8 ), createObject ( 6959, 935.5, 1404.9, -0.8 ), createObject ( 6959, 935.5, 1364.9004, -0.8 ), createObject ( 6959, 929.09998, 1530.3, -10.7, 90, 0, 90 ), createObject ( 6959, 929.09961, 1489, -10.1, 90, 0, 90 ), createObject ( 6959, 929.09961, 1447.7002, -10.1, 90, 0, 90 ), createObject ( 6959, 929.09998, 1406.4, -10.1, 90, 0, 90 ), createObject ( 6959, 929.09961, 1365.0996, -10.1, 90, 0, 90 ), createObject ( 3095, 993.09961, 1345.5996, 3.7, 90, 0, 0 ), createObject ( 3095, 984.09961, 1345.5996, 3.7, 90, 0, 0 ), createObject ( 3095, 975.09961, 1345.5996, 3.7, 90, 0, 0 ), createObject ( 3095, 966.09961, 1345.5996, 3.7, 90, 0, 0 ), createObject ( 3095, 957.09961, 1345.5996, 3.7, 90, 0, 0 ), createObject ( 6959, 939.90002, 1522.8, 9.9, 0.022, 0, 90 ), createObject ( 6959, 939.90002, 1481.5, 9.9, 0.022, 0, 90 ), createObject ( 6959, 939.90002, 1440.2, 9.9, 0.022, 0, 90 ), createObject ( 6959, 939.90002, 1398.9, 9.9, 0.022, 0, 90 ), createObject ( 6959, 939.90039, 1357.5996, 9.9, 0.022, 0, 90 ), createObject ( 6959, 939.90002, 1316.3, 9.9, 0.022, 0, 90 ), createObject ( 6959, 939.90002, 1298.9, 9.9, 0.022, 359.985, 90 ), createObject ( 6959, 920, 1522.8, -10.1, 90, 0, 90 ), createObject ( 6959, 920, 1481.5, -10.1, 90, 0, 90 ), createObject ( 6959, 920, 1440.2, -10.1, 90, 0, 90 ), createObject ( 6959, 920, 1298.9004, -10.1, 90, 0, 90 ), createObject ( 6959, 920, 1340.2, -10.1, 90, 0, 90 ), createObject ( 6959, 920, 1381.5, -10.1, 90, 0, 92 ), createObject ( 6959, 940.59961, 1278.2998, -10.1, 90, 0, 0 ), createObject ( 3095, 993.09998, 1345.7, 5.3, 90, 0, 0 ), createObject ( 3095, 984.09998, 1345.7, 5.3, 90, 0, 0 ), createObject ( 3095, 975.09998, 1345.7, 5.3, 90, 0, 0 ), createObject ( 3095, 966.09961, 1345.7002, 5.3, 90, 0, 0 ), createObject ( 3095, 957.09998, 1345.7, 5.3, 90, 0, 0 ), createObject ( 11353, 953.5, 1278.7, 14.2, 0, 0, 90 ), createObject ( 11353, 920.79999, 1305.4, 14.2 ), createObject ( 11353, 920.79999, 1359.7, 14.2 ), createObject ( 11353, 920.79999, 1414, 14.2 ), createObject ( 11353, 920.79999, 1468.3, 14.2 ), createObject ( 11353, 920.90002, 1511.5, 14.3 ), createObject ( 6959, 940.79999, 1543.4, -10.1, 90, 0, 0 ), createObject ( 11353, 996.90039, 1306.4004, 14.3 ), createObject ( 11353, 996.90002, 1360.7, 14.3 ), createObject ( 11353, 996.7998, 1428.5, 14.2 ), createObject ( 11353, 996.90002, 1479.6, 14.3 ), createObject ( 987, 932.20001, 1543.2, 9.8, 0, 0, 180 ), createObject ( 987, 944.20001, 1543.2, 9.8, 0, 0, 179.995 ), createObject ( 987, 956.20001, 1543.2, 9.8, 0, 0, 179.995 ), createObject ( 987, 959.20001, 1543.2, 9.8, 0, 0, 179.995 ), createObject ( 987, 959.09998, 1531.4, 9.8, 0, 0, 90 ), createObject ( 987, 959.09998, 1519.4, 9.8, 0, 0, 90 ), createObject ( 987, 959.09998, 1507.4, 9.8, 0, 0, 90 ), createObject ( 987, 971.40002, 1506.4, 9.8, 0, 0, 179.995 ), createObject ( 987, 983.40002, 1506.4, 9.8, 0, 0, 179.995 ), createObject ( 987, 995.40002, 1506.4, 9.8, 0, 0, 179.995 ), createObject ( 8620, 996.7002, 1395.7998, 32.9, 0, 0, 90 ), createObject ( 2774, 920.79999, 1539.4, 5.7 ), createObject ( 2774, 920.7998, 1541, 5.7 ), createObject ( 2774, 920.79999, 1542.6, 5.7 ), createObject ( 2774, 959, 1506.7998, 5.7 ), createObject ( 2774, 959, 1506.8, -17.9 ), createObject ( 987, 952.20001, 1374.9, 9.7, 0, 0, 90.25 ), createObject ( 987, 952.20001, 1386.8, 9.7, 0, 0, 90.247 ), createObject ( 987, 952.20001, 1398.8, 9.7, 0, 0, 90.247 ), createObject ( 987, 952.20001, 1410.7, 9.7, 0, 0, 90.247 ), createObject ( 987, 940.5, 1374.9004, 9.7 ), createObject ( 987, 928.5, 1374.9, 9.7 ), createObject ( 987, 922.5, 1374.9, 9.7 ), createObject ( 2774, 922.09961, 1374.7998, 5.7 ), createObject ( 987, 952.29999, 1422.6, 9.7, 0, 0, 180 ), createObject ( 987, 933.20001, 1422.5, 9.7, 0, 0, 179.995 ), createObject ( 2774, 996.7998, 1308.7002, 9.2, 0, 90, 90 ), createObject ( 4874, 942.79999, 1325.3, 13.6, 0, 0, 90 ), createObject ( 987, 952.29999, 1422.7, 9.7 ), createObject ( 987, 964.29999, 1422.7, 9.7 ), createObject ( 987, 984.40002, 1422.8, 9.7 ), createObject ( 3268, 940, 1517.7002, 9.8, 0, 0, 90 ), createObject ( 8947, 989, 1243.4, 8.8 ), createObject ( 8947, 989, 1220.5996, 4.8, 339.983, 0, 179.995 ), createObject ( 8947, 989, 1290.7, 4.8, 339.994, 0, 0 ), createObject ( 11353, 996.90002, 1252.2, 14.3 ), createObject ( 11353, 981.20001, 1252.5, 14.3 ), createObject ( 3749, 989, 1223.3, 15.6 ), createObject ( 8947, 989, 1267.9, 8.8 ), createObject ( 1634, 936.70001, 1369.4, 11, 0, 0, 91.995 ), createObject ( 11458, 936.90002, 1441.1, 10, 0, 0, 30 ), createObject ( 11458, 930.20001, 1486.4, 10, 0, 0, 319.998 ), createObject ( 11458, 956.90002, 1473.5, 10, 0, 0, 319.993 ), createObject ( 11458, 987.59998, 1493.3, 10, 0, 0, 319.993 ), createObject ( 11459, 960.20001, 1491.2, 9.9, 0, 0, 30 ), createObject ( 11459, 973.09998, 1465.3, 9.9, 0, 0, 329.998 ), createObject ( 11459, 985.59998, 1449.8, 9.9, 0, 0, 329.996 ), createObject ( 11459, 941.79999, 1474.2, 9.9, 0, 0, 89.996 ), createObject ( 11459, 978.70001, 1502, 9.9, 0, 0, 89.995 ), createObject ( 11442, 951.79999, 1436.3, 9.9, 0, 0, 12 ), createObject ( 11442, 970.09998, 1436.5, 9.9, 0, 0, 331.997 ), createObject ( 11442, 945.59998, 1489.7, 9.9, 0, 0, 41.996 ), createObject ( 11442, 935.29999, 1457.6, 9.9, 0, 0, 91.995 ), createObject ( 11457, 957.59998, 1460.4, 9.4, 0, 0, 30 ), createObject ( 11457, 979.29999, 1479.1, 9.4, 0, 0, 79.998 ), createObject ( 3279, 992.09998, 1501.9, 9.9, 0, 0, 180 ), createObject ( 3279, 927.20001, 1499, 9.9, 0, 0, 179.995 ), createObject ( 3279, 991.59998, 1375.8, 9.9, 0, 0, 179.995 ), createObject ( 3279, 990.59998, 1328.1, 9.9, 0, 0, 179.995 ), createObject ( 3279, 968.2002, 1284.5, 9.9, 0, 0, 89.995 ), createObject ( 18257, 942.90002, 1520.6, 9.9 ), createObject ( 2934, 948.90002, 1513.6, 11.2 ), createObject ( 1685, 929.40002, 1510.2, 10.5 ), createObject ( 1685, 929.40002, 1512.3, 10.5 ), createObject ( 1685, 929.40002, 1514.6, 10.5 ), createObject ( 1685, 929.40002, 1516.8, 10.5 ), createObject ( 3279, 990.7002, 1430.5, 9.9, 0, 0, 179.995 ), createObject ( 970, 993.29999, 1319.8, 10.4 ), createObject ( 970, 989.09998, 1319.8, 10.4 ), createObject ( 970, 984.90002, 1319.8, 10.4 ), createObject ( 970, 982.79999, 1317.7, 10.4, 0, 0, 90 ), createObject ( 970, 982.79999, 1313.5, 10.4, 0, 0, 90 ), createObject ( 970, 982.79999, 1309.3, 10.4, 0, 0, 90 ), createObject ( 970, 982.79999, 1305.1, 10.4, 0, 0, 90 ), createObject ( 3095, 955, 1370.2, 3.7, 90, 0, 0 ), createObject ( 3095, 950.59998, 1374.5, 3.7, 90, 0, 270 ), createObject ( 3095, 950.59998, 1383.5, 3.7, 90, 0, 270 ), createObject ( 3095, 955.40002, 1385.6, 3.7, 270, 0, 0 ), createObject ( 6959, 939.40002, 1369.8, 8.1, 0.022, 0, 90 ), createObject ( 2774, 958.70001, 1378.5, 9, 0, 90, 89.75 ), createObject ( 10832, 954.40002, 1377.7, 1, 0, 0, 180 ), createObject ( 6959, 977.40002, 1486.1, 9.8, 0.099, 0, 90 ), createObject ( 6959, 977.5, 1464.1, 9.8, 0, 0, 90 ), createObject ( 6959, 977.5, 1422.8, 9.8, 0, 0, 90 ), createObject ( 6959, 977.5, 1422.8, 9.7, 0, 0, 90 ), createObject ( 6959, 977.5, 1381.5, 9.8, 0, 0, 90 ), createObject ( 2774, 920.70001, 1360.8, -3.2 ), createObject ( 1597, 963.70001, 1324.9, 12.4 ), createObject ( 1597, 963.70001, 1312.3, 12.4 ), createObject ( 1597, 963.70001, 1299.5, 12.4 ), createObject ( 1597, 995, 1339.4, 12.4 ), createObject ( 1597, 995, 1360.9004, 12.4 ), createObject ( 3606, 982.70001, 1518.8, -12, 0, 0, 0.994 ), createObject ( 12978, 966.40002, 1519.5, -15.3 ), createObject ( 8650, 993.40002, 1421.8, -14.3, 0, 0, 90 ), createObject ( 8650, 993.40002, 1449.2, -14.3, 0, 0, 89.75 ), createObject ( 9345, 987.5, 1411, -15.3, 0, 0, 159.999 ), createObject ( 11490, 987.70001, 1470.3, -15.5, 0, 0, 270 ), createObject ( 11491, 976.70001, 1470.3, -14, 0, 0, 270 ), createObject ( 9345, 976, 1458.3, -15.3, 0, 0, 270.749 ), createObject ( 716, 986, 1409.7002, -19 ), createObject ( 716, 975.79999, 1459.9, -19 ), createObject ( 11547, 991.59998, 1435.7, -12.5 ), createObject ( 3660, 988, 1423.5, -12.8 ), createObject ( 3660, 988, 1448.1, -12.8 ), createObject ( 3362, 990.20001, 1500.6, -15.5, 0, 0, 189.748 ), createObject ( 3660, 960.7002, 1396.2002, -12.8, 0, 0, 90 ), createObject ( 3660, 960.7998, 1443.2002, -12.8, 0, 0, 90 ), createObject ( 3660, 960.70001, 1491.8, -12.8, 0, 0, 90 ), createObject ( 1597, 995.09998, 1396.5, -12.7 ), createObject ( 1597, 935.40002, 1414.7, -12.5 ), createObject ( 1597, 935.40002, 1396.7, -12.5 ), createObject ( 1597, 935.29999, 1379.5, -12.5 ), createObject ( 1597, 947.09998, 1376.2, -12.5, 0, 0, 90 ), createObject ( 1597, 935.09998, 1491.9, -12.5 ), createObject ( 1597, 935.20001, 1506.9, -12.5 ), createObject ( 1597, 935.29999, 1520.7, -12.5 ), createObject ( 1597, 948, 1524.4, -12.5, 0, 0, 90 ), createObject ( 14789, 930.5, 1470.7998, -11.1 ), createObject ( 14787, 943, 1466.8, -15.2 ), createObject ( 14788, 930.5, 1470.8, -13.3 ), createObject ( 14788, 930.5, 1456.90002, -13.3 ), createObject ( 6965, 949.40002, 1499.1, -11.7, 0, 0, 12.75 ), createObject ( 6964, 949.40002, 1499.1, -16, 0, 0, 12.75 ), createObject ( 11489, 935, 1436.3, -15.5, 0, 0, 67.496 ), createObject ( 3660, 958.5, 1396.3, -12.8, 0, 0, 90 ), createObject ( 3660, 958.5, 1443.2, -12.8, 0, 0, 90 ), createObject ( 2639, 947.70001, 1469.6, -14.8 ), createObject ( 2639, 942.09998, 1469.6, -14.8 ), createObject ( 2639, 942.09998, 1471.7, -14.8 ), createObject ( 2639, 942.09998, 1473.9, -14.8 ), createObject ( 2639, 947.70001, 1471.7, -14.8 ), createObject ( 2639, 947.70001, 1473.8, -14.8 ), createObject ( 3997, 989, 1450.2002, -15.4, 0, 0, 90 ), createObject ( 2207, 943.90002, 1476.9, -15.4 ), createObject ( 1671, 944.79999, 1478.7, -14.9 ), createObject ( 16782, 944.5, 1480.8, -11.2, 0, 0, 270 ), createObject ( 14791, 944.09998, 1460.8, -13.3 ), createObject ( 9131, 995.90002, 1506.3, 10.8 ), createObject ( 9131, 995.90002, 1506.3, 13 ), createObject ( 9131, 995.90002, 1506.3, 15.2 ), createObject ( 11353, 942.70001, 1278.6, 14.1, 0, 0, 90 ), createObject ( 2774, 919.5, 1278.6, 5.7 ), createObject ( 2774, 917.90002, 1278.6, 5.7 ), createObject ( 2774, 916.29999, 1278.6, 5.7 ), } for index, object in ipairs ( Objects ) do setElementDoubleSided ( object, true ) setObjectBreakable(object, false) end
-- load module luafsm = require('luafsm') -- define the state machine hello_world_states = { entry = "print_hello", substates = { print_hello = function() io.write("hello") return true, "print_space" end, print_space = function() io.write(" ") return true, "print_world" end, print_world = function() io.write("world") return true, "print_newline" end, print_newline = function() io.write("\n") return true, nil end, } } -- instantiate it hello_world_fsm = luafsm.create(hello_world_states) -- run it until it has finished while hello_world_fsm() == false do end
import "metabase_common.lua" writer "writer_gnumakegcccompatible.lua" local cppFlagsCommon = "-Wall" option("cc", "gcc") option("cxx", "g++") option("ar", "ar") option("ld", "g++") option("cxxflags", "-Wall") option("arflags", "crsT") option("ldflags", "") config "Debug" option("cppflags", cppFlagsCommon .. " -g -O0") config_end() config "Release" option("cppflags", cppFlagsCommon .. " -g -O2") config_end() config "Master" option("cppflags", cppFlagsCommon .. " -O2") config_end() config "Debug" config_end() config "Release" config_end() config "Master" config_end()
local Rand = require("api.Rand") local function pick(choices, chance) return function() if Rand.one_in(chance) then return Rand.choice(choices) end return choices[1] end end data:add_multi( "elona_sys.map_tileset", { { _id = "default", door = { open_tile = "elona.feat_door_wooden_open", closed_tile = "elona.feat_door_wooden_closed", }, tiles = { ["elona.mapgen_default"] = "elona.wall_oriental_top", ["elona.mapgen_wall"] = "elona.wall_stone_1_top", ["elona.mapgen_room"] = "elona.cracked_dirt_2", ["elona.mapgen_tunnel"] = "elona.dark_dirt_1", }, fog = "elona.wall_stone_4_fog" }, { _id = "jail", elona_id = 12, door = { open_tile = "elona.feat_door_jail_open", closed_tile = "elona.feat_door_jail_closed", } }, { _id = "sf", elona_id = 8, door = { open_tile = "elona.feat_door_sf_open", closed_tile = "elona.feat_door_sf_closed", } }, { _id = "eastern", elona_id = 9, door = { open_tile = "elona.feat_door_eastern_open", closed_tile = "elona.feat_door_eastern_closed", } }, { _id = "home", elona_id = 3, tiles = { ["elona.mapgen_room"] = "elona.dirt", ["elona.mapgen_tunnel"] = "elona.dirt", ["elona.mapgen_wall"] = "elona.wall_dirt_dark_top", }, fog = "elona.wall_dirt_dark_fog" }, { _id = "wilderness", elona_id = 4, tiles = { ["elona.mapgen_default"] = "elona.grass", }, fog = "elona.wall_stone_1_fog" }, { _id = "town", elona_id = 2, tiles = { ["elona.mapgen_wall"] = "elona.wall_stone_1_top" }, fog = "elona.wall_stone_2_fog" }, { _id = "water", elona_id = 10, tiles = { ["elona.mapgen_room"] = "elona.anime_water_shallow", ["elona.mapgen_tunnel"] = pick({"elona.dark_dirt_1","elona.dark_dirt_2","elona.dark_dirt_3","elona.dark_dirt_4"}, 2), ["elona.mapgen_wall"] = "elona.wall_dirt_dark_top", ["elona.mapgen_default"] = "elona.wall_dirt_dark_top", } }, { _id = "castle", elona_id = 11, tiles = { ["elona.mapgen_default"] = "elona.wall_stone_4_top", ["elona.mapgen_tunnel"] = "elona.tiled_2", ["elona.mapgen_wall"] = "elona.wall_wooden_top", ["elona.mapgen_room"] = "elona.carpet_green", }, fog = "elona.wall_stone_3_fog" }, { _id = "dungeon", elona_id = 0, tiles = { ["elona.mapgen_default"] = "elona.wall_dirt_dark_top", ["elona.mapgen_tunnel"] = pick({"elona.dark_dirt_1","elona.dark_dirt_2","elona.dark_dirt_3","elona.dark_dirt_4"}, 2), ["elona.mapgen_wall"] = "elona.wall_dirt_dark_top", ["elona.mapgen_room"] = pick({"elona.dark_dirt_1","elona.dark_dirt_2","elona.dark_dirt_3","elona.dark_dirt_4"}, 2), }, fog = "elona.wall_stone_2_fog" }, { _id = "snow", elona_id = 6, tiles = { ["elona.mapgen_default"] = "elona.wall_dirt_dark_top", ["elona.mapgen_tunnel"] = pick({"elona.snow", "elona.snow_mound", "elona.snow_plants"}, 2), ["elona.mapgen_wall"] = "elona.wall_dirt_dark_top", ["elona.mapgen_room"] = pick({"elona.dark_dirt_1", "elona.dark_dirt_2", "elona.dark_dirt_3", "elona.dark_dirt_4", "elona.destroyed", "elona.dirt_patch"}, 3), }, fog = "elona.wall_stone_2_fog" }, { _id = "tower_of_fire", elona_id = 7, tiles = { ["elona.mapgen_default"] = "elona.wall_tower_of_fire_top", ["elona.mapgen_tunnel"] = "elona.tower_of_fire_tile_2", ["elona.mapgen_wall"] = "elona.wall_tower_of_fire_top", ["elona.mapgen_room"] = pick({"elona.tower_of_fire_tile_1", "elona.tower_of_fire_tile_2"}, 2) }, fog = "elona.wall_stone_3_fog" }, { _id = "dungeon_forest", elona_id = 300, tiles = { ["elona.mapgen_default"] = "elona.wall_forest_top", ["elona.mapgen_tunnel"] = "elona.grass", ["elona.mapgen_wall"] = "elona.wall_forest_top", ["elona.mapgen_room"] = pick({"elona.grass", "elona.grass_violets", "elona.grass_rocks", "elona.grass_tall_1", "elona.grass_tall_2", "elona.grass_patch_1"}, 6) }, fog = "elona.wall_stone_1_fog" }, { _id = "noyel_fields", tiles = { ["elona.mapgen_default"] = "elona.wall_forest_top", ["elona.mapgen_tunnel"] = "elona.grass", ["elona.mapgen_wall"] = "elona.wall_forest_top", ["elona.mapgen_room"] = pick({"elona.snow", "elona.snow_mound", "elona.snow_plants", "elona.snow_rock", "elona.snow_stump", "elona.snow_flowers_1"}, 6) }, fog = "elona.wall_stone_1_fog" }, { _id = "tower_1", elona_id = 100, tiles = { ["elona.mapgen_default"] = "elona.wall_concrete_top", ["elona.mapgen_tunnel"] = "elona.cobble_4", ["elona.mapgen_wall"] = "elona.wall_concrete_light_top", ["elona.mapgen_room"] = pick({"elona.tile_1", "elona.tile_2", "elona.tile_3"}, 2) }, fog = "elona.wall_stone_3_fog" }, { _id = "tower_2", elona_id = 101, tiles = { ["elona.mapgen_default"] = "elona.wall_stone_7_top", ["elona.mapgen_tunnel"] = "elona.concrete_2", ["elona.mapgen_wall"] = "elona.wall_stone_7_top", ["elona.mapgen_room"] = "elona.cobble_3" }, fog = "elona.wall_stone_3_fog" }, { _id = "dungeon_castle", elona_id = 200, tiles = { ["elona.mapgen_default"] = "elona.wall_dirt_top", ["elona.mapgen_tunnel"] = pick({ "elona.dark_dirt_1", "elona.dark_dirt_2", "elona.dark_dirt_3", "elona.dark_dirt_4", "elona.destroyed", "elona.dirt_patch" }, 2), ["elona.mapgen_wall"] = "elona.wall_stone_1_top", ["elona.mapgen_room"] = pick({"elona.cobble_dark_1", "elona.cobble_dark_2", "elona.cobble_dark_3", "elona.cobble_dark_4"}, 2) }, fog = "elona.wall_stone_4_fog" }, { _id = "world_map", elona_id = 1, tiles = { -- ["elona.mapgen_wall"] = "elona.wall_stone_1_top", -- was -1 }, fog = pick("elona.wall_oriental_top", 4, "elona.wall_brick_top") }, } )
-- Copyright 2017-2019, Firaxis Games include("TeamSupport"); include("DiplomacyRibbonSupport"); print("LeaderIcon for BSM") -- =========================================================================== -- Class Table -- =========================================================================== LeaderIcon = { playerID = -1, TEAM_RIBBON_PREFIX = "ICON_TEAM_RIBBON_" } local m_bspec = false -- =========================================================================== function LeaderIcon:GetInstance(instanceManager:table, uiNewParent:table) local instance:table = instanceManager:GetInstance(uiNewParent); return LeaderIcon:AttachInstance(instance); end -- =========================================================================== -- Essentially the "new" -- =========================================================================== function LeaderIcon:AttachInstance( instance:table ) if instance == nil then UI.DataError("NIL instance passed into LeaderIcon:AttachInstance. Setting the value to the ContextPtr's 'Controls'."); instance = Controls; end setmetatable(instance, {__index = self }); self.Controls = instance; self:Reset(); return instance; end -- =========================================================================== function LeaderIcon:UpdateIcon(iconName: string, playerID: number, isUniqueLeader: boolean, ttDetails: string) LeaderIcon.playerID = playerID; local pPlayer:table = Players[playerID]; local pPlayerConfig:table = PlayerConfigurations[playerID]; local localPlayerID:number = Game.GetLocalPlayer(); -- Display the civ colors/icon for duplicate civs if isUniqueLeader == false and (playerID == localPlayerID or Players[localPlayerID]:GetDiplomacy():HasMet(playerID)) then local backColor, frontColor = UI.GetPlayerColors( playerID ); self.Controls.CivIndicator:SetHide(false); self.Controls.CivIndicator:SetColor(backColor); self.Controls.CivIcon:SetHide(false); self.Controls.CivIcon:SetColor(frontColor); self.Controls.CivIcon:SetIcon("ICON_"..pPlayerConfig:GetCivilizationTypeName()); else self.Controls.CivIcon:SetHide(true); self.Controls.CivIndicator:SetHide(true); end -- Set leader portrait and hide overlay if not local player self.Controls.Portrait:SetIcon(iconName); self.Controls.YouIndicator:SetHide(playerID ~= localPlayerID); -- Set the tooltip local tooltip:string = self:GetToolTipString(playerID); if (ttDetails ~= nil and ttDetails ~= "") then tooltip = tooltip .. "[NEWLINE]" .. ttDetails; end self.Controls.Portrait:SetToolTipString(tooltip); self:UpdateTeamAndRelationship(playerID); end -- =========================================================================== function LeaderIcon:UpdateIconSimple(iconName: string, playerID: number, isUniqueLeader: boolean, ttDetails: string) LeaderIcon.playerID = playerID; local localPlayerID:number = Game.GetLocalPlayer(); self.Controls.Portrait:SetIcon(iconName); self.Controls.YouIndicator:SetHide(playerID ~= localPlayerID); -- Display the civ colors/icon for duplicate civs if isUniqueLeader == false and (playerID ~= -1 and Players[localPlayerID]:GetDiplomacy():HasMet(playerID)) then local backColor, frontColor = UI.GetPlayerColors( playerID ); self.Controls.CivIndicator:SetHide(false); self.Controls.CivIndicator:SetColor(backColor); self.Controls.CivIcon:SetHide(false); self.Controls.CivIcon:SetColor(frontColor); self.Controls.CivIcon:SetIcon("ICON_"..PlayerConfigurations[playerID]:GetCivilizationTypeName()); else self.Controls.CivIcon:SetHide(true); self.Controls.CivIndicator:SetHide(true); end if playerID < 0 then self.Controls.TeamRibbon:SetHide(true); self.Controls.Relationship:SetHide(true); self.Controls.Portrait:SetToolTipString(""); return; end -- Set the tooltip local tooltip:string = self:GetToolTipString(playerID); if (ttDetails ~= nil and ttDetails ~= "") then tooltip = tooltip .. "[NEWLINE]" .. ttDetails; end self.Controls.Portrait:SetToolTipString(tooltip); self:UpdateTeamAndRelationship(playerID); end -- =========================================================================== -- playerID, Index of the player to compare a relationship. (May be self.) -- =========================================================================== function LeaderIcon:UpdateTeamAndRelationship( playerID: number) local localPlayerID :number = Game.GetLocalPlayer(); if localPlayerID == PlayerTypes.NONE or playerID == PlayerTypes.OBSERVER then return; end -- Local player is auto-play. -- Don't even attempt it, just hide the icon if this game mode doesn't have the capabilitiy. if GameCapabilities.HasCapability("CAPABILITY_DISPLAY_HUD_RIBBON_RELATIONSHIPS") == false then self.Controls.Relationship:SetHide( true ); return; end -- Nope, autoplay or observer if playerID < 0 then UI.DataError("Invalid playerID="..tostring(playerID).." to check against for UpdateTeamAndRelationship()."); return; end if PlayerConfigurations[Game.GetLocalPlayer()] ~= nil then if PlayerConfigurations[Game.GetLocalPlayer()]:GetLeaderTypeName() == "LEADER_SPECTATOR" then m_bspec = true end end if (m_bspec == true) and Game.GetLocalPlayer() ~= nil then if (GameConfiguration.GetValue("OBSERVER_ID_"..Game.GetLocalPlayer()) ~= nil) and (GameConfiguration.GetValue("OBSERVER_ID_"..Game.GetLocalPlayer()) ~= 1000) and (GameConfiguration.GetValue("OBSERVER_ID_"..Game.GetLocalPlayer()) ~= -1) then localPlayerID = GameConfiguration.GetValue("OBSERVER_ID_"..Game.GetLocalPlayer()) end end local pPlayer :table = Players[playerID]; local pPlayerConfig :table = PlayerConfigurations[playerID]; local isHuman :boolean = pPlayerConfig:IsHuman(); local isSelf :boolean = (playerID == localPlayerID); local isMet :boolean = Players[localPlayerID]:GetDiplomacy():HasMet(playerID); -- Team Ribbon local isTeamRibbonHidden:boolean = true; if(isSelf or isMet) then -- Show team ribbon for ourselves and civs we've met local teamID:number = pPlayerConfig:GetTeam(); if Teams[teamID] ~= nil then if #Teams[teamID] > 1 then local teamRibbonName:string = self.TEAM_RIBBON_PREFIX .. tostring(teamID); self.Controls.TeamRibbon:SetIcon(teamRibbonName); self.Controls.TeamRibbon:SetColor(GetTeamColor(teamID)); isTeamRibbonHidden = false; end end end self.Controls.TeamRibbon:SetHide(isTeamRibbonHidden); -- Relationship status (Humans don't show anything, unless we are at war) local eRelationship :number = pPlayer:GetDiplomaticAI():GetDiplomaticStateIndex(localPlayerID); local relationType :string = GameInfo.DiplomaticStates[eRelationship].StateType; local isValid :boolean= (isHuman and Relationship.IsValidWithHuman( relationType )) or (not isHuman and Relationship.IsValidWithAI( relationType )); if isValid then self.Controls.Relationship:SetVisState(eRelationship); if (GameInfo.DiplomaticStates[eRelationship].Hash ~= DiplomaticStates.NEUTRAL) then self.Controls.Relationship:SetToolTipString(Locale.Lookup(GameInfo.DiplomaticStates[eRelationship].Name)); end end self.Controls.Relationship:SetHide( not isValid ); end -- =========================================================================== -- Resets the view of attached controls -- =========================================================================== function LeaderIcon:Reset() if self.Controls == nil then UI.DataError("Attempting to call Reset() on a nil LeaderIcon."); return; end self.Controls.TeamRibbon:SetHide(true); self.Controls.Relationship:SetHide(true); self.Controls.YouIndicator:SetHide(true); end ------------------------------------------------------------------ function LeaderIcon:RegisterCallback(event: number, func: ifunction) self.Controls.SelectButton:RegisterCallback(event, func); end ------------------------------------------------------------------ function LeaderIcon:GetToolTipString(playerID:number) local result:string = ""; local pPlayerConfig:table = PlayerConfigurations[playerID]; if pPlayerConfig and pPlayerConfig:GetLeaderTypeName() then local isHuman :boolean = pPlayerConfig:IsHuman(); local leaderDesc :string = pPlayerConfig:GetLeaderName(); local civDesc :string = pPlayerConfig:GetCivilizationDescription(); local localPlayerID :number = Game.GetLocalPlayer(); if localPlayerID==PlayerTypes.NONE or localPlayerID==PlayerTypes.OBSERVER then return ""; end if GameConfiguration.IsAnyMultiplayer() and isHuman then if(playerID ~= localPlayerID and not Players[localPlayerID]:GetDiplomacy():HasMet(playerID)) then result = Locale.Lookup("LOC_DIPLOPANEL_UNMET_PLAYER") .. " (" .. pPlayerConfig:GetPlayerName() .. ")"; else result = Locale.Lookup("LOC_DIPLOMACY_DEAL_PLAYER_PANEL_TITLE", leaderDesc, civDesc) .. " (" .. pPlayerConfig:GetPlayerName() .. ")"; end else if(playerID ~= localPlayerID and not Players[localPlayerID]:GetDiplomacy():HasMet(playerID)) then result = Locale.Lookup("LOC_DIPLOPANEL_UNMET_PLAYER"); else result = Locale.Lookup("LOC_DIPLOMACY_DEAL_PLAYER_PANEL_TITLE", leaderDesc, civDesc); end end end local bspec = false local spec_ID = 0 if (Game:GetProperty("SPEC_NUM") ~= nil) then for k = 1, Game:GetProperty("SPEC_NUM") do if ( Game:GetProperty("SPEC_ID_"..k)~= nil) then if Game.GetLocalPlayer() == Game:GetProperty("SPEC_ID_"..k) then bspec = true spec_ID = k end end end end if bspec == true then local govType:string = ""; local eSelectePlayerGovernment :number = Players[playerID]:GetCulture():GetCurrentGovernment(); if eSelectePlayerGovernment ~= -1 then govType = Locale.Lookup(GameInfo.Governments[eSelectePlayerGovernment].Name); else govType = Locale.Lookup("LOC_GOVERNMENT_ANARCHY_NAME" ); end local cities = Players[playerID]:GetCities(); local numCities = 0; local ERD_Total_Population = 0; for i,city in cities:Members() do ERD_Total_Population = ERD_Total_Population + city:GetPopulation(); numCities = numCities + 1; end local pPlayerCulture:table = Players[playerID]:GetCulture(); local culture_num = 0 for k = 0, 58 do if (pPlayerCulture:HasCivic(k) == true) then culture_num = culture_num + 1 end end local pPlayerTechs:table = Players[playerID]:GetTechs(); local tech_num = 0 for k = 0, 73 do if (pPlayerTechs:HasTech(k) == true) then tech_num = tech_num + 1 end end local unit_num = 0 local unit_str = 0 if Players[playerID]:GetUnits() ~= nil then if Players[playerID]:GetUnits():GetCount() ~= nil then unit_num = Players[playerID]:GetUnits():GetCount() end end local playerTreasury:table = Players[playerID]:GetTreasury(); local goldBalance :number = math.floor(playerTreasury:GetGoldBalance()); local goldYield :number = math.floor((playerTreasury:GetGoldYield() - playerTreasury:GetTotalMaintenance())); local pGameEras:table = Game.GetEras(); local score = pGameEras:GetPlayerCurrentScore(playerID); local detailsString = "Current Era Score: ".. score; local isFinalEra:boolean = pGameEras:GetCurrentEra() == pGameEras:GetFinalEra(); if not isFinalEra then detailsString = detailsString .. Locale.Lookup("LOC_DARK_AGE_THRESHOLD_TEXT", pGameEras:GetPlayerDarkAgeThreshold(playerID)); detailsString = detailsString .. Locale.Lookup("LOC_GOLDEN_AGE_THRESHOLD_TEXT", pGameEras:GetPlayerGoldenAgeThreshold(playerID)); end if pGameEras:HasHeroicGoldenAge(playerID) then sEras = " ("..Locale.Lookup("LOC_ERA_PROGRESS_HEROIC_AGE").." [ICON_GLORY_SUPER_GOLDEN_AGE])"; elseif pGameEras:HasGoldenAge(playerID) then sEras = " ("..Locale.Lookup("LOC_ERA_PROGRESS_GOLDEN_AGE").." [ICON_GLORY_GOLDEN_AGE])"; elseif pGameEras:HasDarkAge(playerID) then sEras = " ("..Locale.Lookup("LOC_ERA_PROGRESS_DARK_AGE").." [ICON_GLORY_DARK_AGE])"; else sEras = " ("..Locale.Lookup("LOC_ERA_PROGRESS_NORMAL_AGE").." [ICON_GLORY_NORMAL_AGE])"; end local sEras_2 = "" local activeCommemorations = pGameEras:GetPlayerActiveCommemorations(playerID); for i,activeCommemoration in ipairs(activeCommemorations) do local commemorationInfo = GameInfo.CommemorationTypes[activeCommemoration]; if (commemorationInfo ~= nil) then if pGameEras:HasHeroicGoldenAge(playerID) then sEras_2 = sEras_2.."[NEWLINE]"..Locale.Lookup(commemorationInfo.GoldenAgeBonusDescription) elseif pGameEras:HasGoldenAge(playerID) then sEras_2 = sEras_2.."[NEWLINE]"..Locale.Lookup(commemorationInfo.GoldenAgeBonusDescription) elseif pGameEras:HasDarkAge(playerID) then sEras_2 = sEras_2.."[NEWLINE]"..Locale.Lookup(commemorationInfo.DarkAgeBonusDescription) else sEras_2 = sEras_2.."[NEWLINE]"..Locale.Lookup(commemorationInfo.NormalAgeBonusDescription) end end end result = result .."[NEWLINE]"..sEras ..sEras_2 .."[NEWLINE]"..detailsString .."[NEWLINE] " .."[NEWLINE]"..Locale.Lookup("LOC_DIPLOMACY_INTEL_GOVERNMENT").." "..Locale.ToUpper(govType) .."[NEWLINE]"..Locale.Lookup("LOC_PEDIA_CONCEPTS_PAGEGROUP_CITIES_NAME").. ": " .. "[COLOR_FLOAT_PRODUCTION]" .. numCities .. "[ENDCOLOR] [ICON_Housing] ".. Locale.Lookup("LOC_DEAL_CITY_POPULATION_TOOLTIP", ERD_Total_Population) .. " [ICON_Citizen]" .."[NEWLINE] " .."[NEWLINE][ICON_Capital] "..Locale.Lookup("LOC_WORLD_RANKINGS_OVERVIEW_DOMINATION_SCORE", Players[playerID]:GetScore()) .."[NEWLINE][ICON_Favor] "..Locale.Lookup("LOC_DIPLOMATIC_FAVOR_NAME") .. ": [COLOR_Red]" .. Players[playerID]:GetFavor().."[ENDCOLOR]" .."[NEWLINE][ICON_Gold] "..Locale.Lookup("LOC_YIELD_GOLD_NAME")..": "..goldBalance.." ( " .. "[COLOR_GoldMetalDark]" .. (goldYield>0 and "+" or "") .. (goldYield>0 and goldYield or "-?") .. "[ENDCOLOR] )" .."[NEWLINE]"..Locale.Lookup("LOC_WORLD_RANKINGS_OVERVIEW_SCIENCE_SCIENCE_RATE", "[COLOR_FLOAT_SCIENCE]" .. Round(Players[playerID]:GetTechs():GetScienceYield(),1) .. "[ENDCOLOR]").." Technologies know: "..tech_num .."[NEWLINE]"..Locale.Lookup("LOC_WORLD_RANKINGS_OVERVIEW_CULTURE_CULTURE_RATE", "[COLOR_FLOAT_CULTURE]" .. Round(Players[playerID]:GetCulture():GetCultureYield(),1) .. "[ENDCOLOR]").." Civics known: "..culture_num .."[NEWLINE]"..Locale.Lookup("LOC_WORLD_RANKINGS_OVERVIEW_CULTURE_TOURISM_RATE", "[COLOR_Tourism]" .. Round(Players[playerID]:GetStats():GetTourism(),1) .. "[ENDCOLOR]") .."[NEWLINE]"..Locale.Lookup("LOC_WORLD_RANKINGS_OVERVIEW_RELIGION_FAITH_RATE", Round(Players[playerID]:GetReligion():GetFaithYield(),1)) .."[NEWLINE][ICON_Strength] "..Locale.Lookup("LOC_WORLD_RANKINGS_OVERVIEW_DOMINATION_MILITARY_STRENGTH", "[COLOR_FLOAT_MILITARY]" .. Players[playerID]:GetStats():GetMilitaryStrengthWithoutTreasury() .. "[ENDCOLOR]").." # Units: "..unit_num ; local tooltip = ""; local canTrade = false; local MAX_WIDTH = 4; local pLuxuries = ""; local pStrategics = ""; local pLuxNum = 0; local pStratNum = 0; local minAmount = 0; local pForDeal = DealManager.GetWorkingDeal(DealDirection.OUTGOING, Game.GetLocalPlayer(), playerID); local pPlayerResources = DealManager.GetPossibleDealItems(playerID, Game.GetLocalPlayer(), DealItemTypes.RESOURCES, pForDeal); local pLocalPlayerResources = Players[Game.GetLocalPlayer()]:GetResources(); if (pPlayerResources ~= nil) then for i,entry in ipairs(pPlayerResources) do local resource = GameInfo.Resources[entry.ForType]; local amount = entry.MaxAmount; local amountString = (playerID ~= Game.GetLocalPlayer()) and (pLocalPlayerResources:HasResource(entry.ForType) and "[COLOR_ModStatusGreenCS]" .. amount .. "[ENDCOLOR]" or "[COLOR_ModStatusRedCS]" .. amount .. "[ENDCOLOR]") or amount; local showResource = true or not pLocalPlayerResources:HasResource(entry.ForType); if (resource.ResourceClassType == "RESOURCECLASS_STRATEGIC") then if (amount > minAmount and showResource) then pStrategics = ((pStratNum - MAX_WIDTH)%(MAX_WIDTH) == 0) and (pStrategics .. "[NEWLINE]" .. "[ICON_"..resource.ResourceType.."]".. amountString .. " ") or (pStrategics .. "[ICON_"..resource.ResourceType.."]".. amountString .. " "); pStratNum = pStratNum + 1; end elseif (resource.ResourceClassType == "RESOURCECLASS_LUXURY") then if (amount > minAmount and showResource) then pLuxuries = ((pLuxNum - MAX_WIDTH)%(MAX_WIDTH) == 0) and (pLuxuries .. "[NEWLINE]" .. "[ICON_"..resource.ResourceType.."]" .. amountString .. " ") or (pLuxuries .. "[ICON_"..resource.ResourceType.."]" .. amountString .. " "); pLuxNum = pLuxNum + 1; end end end end if (minAmount > 0) then tooltip = Locale.Lookup("LOC_HUD_REPORTS_TAB_RESOURCES") .. " (> " .. minAmount .. ") :"; end tooltip = pStratNum > 0 and (tooltip .. "[NEWLINE]Tradeable Strategics:" .. pStrategics) or (tooltip .. ""); tooltip = pLuxNum > 0 and (tooltip .. "[NEWLINE]Tradeable Luxuries:" .. pLuxuries) or (tooltip .. ""); if (pStratNum > 0 or pLuxNum > 0) then result = result .."[NEWLINE]"..tooltip else result = result end end return result; end -- =========================================================================== function LeaderIcon:AppendTooltip( extraText:string ) if extraText == nil or extraText == "" then return; end --Ignore blank local tooltip:string = self:GetToolTipString(self.playerID) .. "[NEWLINE]" .. extraText; self.Controls.Portrait:SetToolTipString(tooltip); end
require "some" x = 0; y = 0; function love.load() fruits = {"apple", "banana"} table.insert(fruits, "pear") for i=1,#fruits do print(fruits[i]) end listOfRectangles = {} end -- function love.draw() -- love.graphics.print(x, 300, 300) -- love.graphics.print(y, 300, 400) -- -- love.graphics.ellipse("fill", 10, 10, 50, 30); -- -- love.graphics.circle("fill", 10, 10, 100, 25); -- love.graphics.rectangle("line", x, y, 10, 10); -- end -- -- 100 frames / sec -- function love.update(dt) -- if love.keyboard.isDown("up") then -- y = y - 100 * dt -- end -- if love.keyboard.isDown("down") then -- y = y + 100 * dt -- end -- if love.keyboard.isDown("left") then -- x = x - 100 * dt -- end -- if love.keyboard.isDown("right") then -- x = x + 100 * dt -- end -- end function love.keypressed(key) -- Remember, 2 equal signs (==) for comparing! if key == "space" then createRect() end end function love.update(dt) for i,v in ipairs(listOfRectangles) do v.x = v.x + v.speed * dt end end function love.draw(dt) for i,v in ipairs(listOfRectangles) do love.graphics.rectangle("line", v.x, v.y, v.width, v.height) end end
object_static_item_item_hoth_standing_light = object_static_item_shared_item_hoth_standing_light:new { } ObjectTemplates:addTemplate(object_static_item_item_hoth_standing_light, "object/static/item/item_hoth_standing_light.iff")
local npairs = require('nvim-autopairs') npairs.setup({ -- defaults -- local disable_filetype = { "TelescopePrompt" } -- local ignored_next_char = string.gsub([[ [%w%%%'%[%"%.] ]],"%s+", "") -- local enable_moveright = true -- local check_ts = false, disable_filetype = { "TelescopePrompt" }, }) _G.calls= {} vim.g.completion_confirm_key = "" calls.completion_confirm = function() if vim.fn.pumvisible() ~= 0 then if vim.fn.complete_info()["selected"] ~= -1 then require'completion'.confirmCompletion() return npairs.esc("<c-y>") else vim.api.nvim_select_popupmenu_item(0, false, false, {}) require'completion'.confirmCompletion() return npairs.esc("<c-n><c-y>") end else return npairs.autopairs_cr() end end -- local utils = require('settings/utils') vim.api.nvim_set_keymap('i', '<CR>', 'v:lua.calls.completion_confirm()', {expr = true , noremap = true})
----------------------------------- -- Area: Chamber of Oracles -- NPC: Pedestal of Water -- Involved in Zilart Mission 7 -- !pos 199 -2 36 168 ------------------------------------- require("scripts/globals/titles") require("scripts/globals/keyitems") require("scripts/globals/missions") local ID = require("scripts/zones/Chamber_of_Oracles/IDs") ------------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) local ZilartStatus = player:getCharVar("ZilartStatus") if (player:getCurrentMission(ZILART) == tpz.mission.id.zilart.THE_CHAMBER_OF_ORACLES) then if (player:hasKeyItem(tpz.ki.WATER_FRAGMENT)) then player:delKeyItem(tpz.ki.WATER_FRAGMENT) player:setCharVar("ZilartStatus", ZilartStatus + 64) player:messageSpecial(ID.text.YOU_PLACE_THE, tpz.ki.WATER_FRAGMENT) if (ZilartStatus == 255) then player:startEvent(1) end elseif (ZilartStatus == 255) then -- Execute cutscene if the player is interrupted. player:startEvent(1) else player:messageSpecial(ID.text.IS_SET_IN_THE_PEDESTAL, tpz.ki.WATER_FRAGMENT) end elseif (player:hasCompletedMission(ZILART, tpz.mission.id.zilart.THE_CHAMBER_OF_ORACLES)) then player:messageSpecial(ID.text.HAS_LOST_ITS_POWER, tpz.ki.WATER_FRAGMENT) else player:messageSpecial(ID.text.PLACED_INTO_THE_PEDESTAL) end end function onEventUpdate(player, csid, option) -- printf("onUpdate CSID: %u", csid) -- printf("onUpdate RESULT: %u", option) end function onEventFinish(player, csid, option) -- printf("onFinish CSID: %u", csid) -- printf("onFinish RESULT: %u", option) if (csid == 1) then player:addTitle(tpz.title.LIGHTWEAVER) player:setCharVar("ZilartStatus", 0) player:addKeyItem(tpz.ki.PRISMATIC_FRAGMENT) player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.PRISMATIC_FRAGMENT) player:completeMission(ZILART, tpz.mission.id.zilart.THE_CHAMBER_OF_ORACLES) player:addMission(ZILART, tpz.mission.id.zilart.RETURN_TO_DELKFUTTS_TOWER) end end
require 'busted.runner'() local lfs = require 'lfs' local SRV_CONFIG_FOLDER = './tests/data/srv-configs' local SMARTSTACK_CONFIG = './tests/data/services.yaml' local SRV1_CONFIG_PATH = './tests/data/srv-configs/service1.main.yaml' local ENVOY_CONFIGS_PATH = './tests/data/srv-configs' describe("config_loader", function() local config_loader setup(function() _G.os.getenv = function(e) if e == 'SRV_CONFIGS_PATH' then return SRV_CONFIG_FOLDER elseif e == 'SERVICES_YAML_PATH' then return SMARTSTACK_CONFIG elseif e == 'ENVOY_CONFIGS_PATH' then return ENVOY_CONFIGS_PATH end return e end config_loader = require 'config_loader' stub(ngx, 'log') end) after_each(function() config_loader.clear_mod_time_table() end) it("loads a valid config file", function() local config = config_loader.parse_configs(SRV1_CONFIG_PATH) assert.are.equal(123, config['cached_endpoints']['test_cache']['ttl']) assert.are.equal('^abc$', config['cached_endpoints']['test_cache']['pattern']) assert.are.equal('XY1', config['uncacheable_headers'][1]) end) it("returns nil if file_path is nil", function() stub(ngx, 'log') local config = config_loader.parse_configs(nil) assert.is_nil(config) assert.stub(ngx.log).was.called.with(ngx.ERR, 'No file provided. Cannot parse configs.') end) it("returns nil and log if config file is missing", function() stub(ngx, 'log') local config = config_loader.parse_configs('tests/data/srv-configs/missing_config.yaml') assert.is_nil(config) assert.stub(ngx.log).was.called.with(ngx.ERR, 'File missing, cannot parse: tests/data/srv-configs/missing_config.yaml') end) it("file has not changed, returns nil", function() local old_att = lfs.attributes lfs.attributes = function(a, b) return 12346 end config_loader.set_mod_time(SRV1_CONFIG_PATH, 12346) local config = config_loader.parse_configs(SRV1_CONFIG_PATH) lfs.attributes = old_att assert.is_nil(config) end) it("file has changed, reload it", function() local old_att = lfs.attributes lfs.attributes = function(a, b) return 12347 end config_loader.set_mod_time(SRV1_CONFIG_PATH, 12346) local config = config_loader.parse_configs(SRV1_CONFIG_PATH) lfs.attributes = old_att assert.are.equal(123, config['cached_endpoints']['test_cache']['ttl']) assert.are.equal('^abc$', config['cached_endpoints']['test_cache']['pattern']) assert.are.equal('XY1', config['uncacheable_headers'][1]) end) it("can load multiple config files", function() config_loader.load_services_configs(SRV_CONFIG_FOLDER) assert.are.equal('XY1', config_loader.get_spectre_config_for_namespace('service1.main')['uncacheable_headers'][1]) assert.are.equal('XY2', config_loader.get_spectre_config_for_namespace('service2.main')['uncacheable_headers'][1]) assert.are.equal('XY2', config_loader.get_spectre_config_for_namespace('service2.canary')['uncacheable_headers'][1]) assert.are.equal('XY3', config_loader.get_spectre_config_for_namespace('service3.main')['uncacheable_headers'][1]) --assert.is_true(ngx.shared.services_configs['service2.main']['cached_endpoints']) assert._is_true(config_loader.get_spectre_config_for_namespace('service2.main')['cached_endpoints']['test_cache']['dont_cache_missing_ids']) end) it("can load services.yaml", function() config_loader.load_smartstack_info(SMARTSTACK_CONFIG) assert.are.equal('169.254.255.254', config_loader.get_smartstack_info_for_namespace('service1.main')['host']) assert.are.equal(20001, config_loader.get_smartstack_info_for_namespace('service1.main')['port']) assert.are.equal(20003, config_loader.get_smartstack_info_for_namespace('service2.canary')['port']) end) it("setup reload timer", function() local mock_timer = function(a, b) return true, '' end ngx.timer.at = mock_timer local spy_timer = spy.on(ngx.timer, 'at') config_loader.reload_configs(false) assert.is_not_nil(config_loader.get_spectre_config_for_namespace('service1.main')) assert.is_not_nil(config_loader.get_smartstack_info_for_namespace('service1.main')) assert.spy(spy_timer).was.called() end) it("don't setup reload timer if premature = true", function() local mock_timer = function(a, b) return true, '' end ngx.timer.at = mock_timer local spy_timer = spy.on(ngx.timer, 'at') config_loader.reload_configs(true) assert.is_not_nil(config_loader.get_spectre_config_for_namespace('service1.main')) assert.is_not_nil(config_loader.get_smartstack_info_for_namespace('service1.main')) assert.spy(spy_timer).was_not_called() end) end)
add_rules("mode.debug", "mode.release") set_languages("c++17") target("sodium") set_kind("static") add_files("3rd/libsodium/src/libsodium/crypto_aead/aes256gcm/aesni/aead_aes256gcm_aesni.c", "3rd/libsodium/src/libsodium/crypto_aead/chacha20poly1305/sodium/aead_chacha20poly1305.c", "3rd/libsodium/src/libsodium/crypto_aead/xchacha20poly1305/sodium/aead_xchacha20poly1305.c", "3rd/libsodium/src/libsodium/crypto_core/ed25519/ref10/ed25519_ref10.c", "3rd/libsodium/src/libsodium/crypto_core/hchacha20/core_hchacha20.c", "3rd/libsodium/src/libsodium/crypto_core/salsa/ref/core_salsa_ref.c", "3rd/libsodium/src/libsodium/crypto_generichash/blake2b/ref/blake2b-compress-ref.c", "3rd/libsodium/src/libsodium/crypto_generichash/blake2b/ref/blake2b-ref.c", "3rd/libsodium/src/libsodium/crypto_generichash/blake2b/ref/generichash_blake2b.c", "3rd/libsodium/src/libsodium/crypto_onetimeauth/poly1305/onetimeauth_poly1305.c", "3rd/libsodium/src/libsodium/crypto_onetimeauth/poly1305/donna/poly1305_donna.c", "3rd/libsodium/src/libsodium/crypto_pwhash/crypto_pwhash.c", "3rd/libsodium/src/libsodium/crypto_pwhash/argon2/argon2-core.c", "3rd/libsodium/src/libsodium/crypto_pwhash/argon2/argon2.c", "3rd/libsodium/src/libsodium/crypto_pwhash/argon2/argon2-encoding.c", "3rd/libsodium/src/libsodium/crypto_pwhash/argon2/argon2-fill-block-ref.c", "3rd/libsodium/src/libsodium/crypto_pwhash/argon2/blake2b-long.c", "3rd/libsodium/src/libsodium/crypto_pwhash/argon2/pwhash_argon2i.c", "3rd/libsodium/src/libsodium/crypto_scalarmult/curve25519/scalarmult_curve25519.c", "3rd/libsodium/src/libsodium/crypto_scalarmult/curve25519/ref10/x25519_ref10.c", "3rd/libsodium/src/libsodium/crypto_stream/chacha20/stream_chacha20.c", "3rd/libsodium/src/libsodium/crypto_stream/chacha20/ref/chacha20_ref.c", "3rd/libsodium/src/libsodium/crypto_stream/salsa20/stream_salsa20.c", "3rd/libsodium/src/libsodium/crypto_stream/salsa20/ref/salsa20_ref.c", "3rd/libsodium/src/libsodium/crypto_verify/sodium/verify.c", "3rd/libsodium/src/libsodium/randombytes/randombytes.c", "3rd/libsodium/src/libsodium/randombytes/sysrandom/randombytes_sysrandom.c", "3rd/libsodium/src/libsodium/sodium/core.c", "3rd/libsodium/src/libsodium/sodium/runtime.c", "3rd/libsodium/src/libsodium/sodium/utils.c", "3rd/libsodium/src/libsodium/sodium/version.c", "3rd/libsodium/src/libsodium/crypto_pwhash/argon2/pwhash_argon2id.c", "3rd/libsodium/src/libsodium/sodium/codecs.c", "3rd/libsodium/src/libsodium/crypto_generichash/crypto_generichash.c", "3rd/libsodium/src/libsodium/crypto_stream/crypto_stream.c", "3rd/libsodium/src/libsodium/crypto_stream/xsalsa20/stream_xsalsa20.c", "3rd/libsodium/src/libsodium/crypto_core/hsalsa20/ref2/core_hsalsa20_ref2.c", "3rd/libsodium/src/libsodium/crypto_stream/xchacha20/stream_xchacha20.c", "3rd/libsodium/src/libsodium/crypto_auth/hmacsha256/auth_hmacsha256.c", "3rd/libsodium/src/libsodium/crypto_hash/sha256/cp/hash_sha256_cp.c" ) add_defines( "PACKAGE_VERSION=\"1.0.18\"", "PACKAGE_STRING=\"libsodium-1.0.18\"", "PACKAGE_BUGREPORT=\"https://github.com/jedisct1/libsodium/issues\"", "PACKAGE_URL=\"https://github.com/jedisct1/libsodium\"", "PACKAGE=\"libsodium\"", "VERSION=\"1.0.18\"", "HAVE_PTHREAD=1", "STDC_HEADERS=1", "HAVE_SYS_TYPES_H=1", "HAVE_SYS_STAT_H=1", "HAVE_STDLIB_H=1", "HAVE_STRING_H=1", "HAVE_MEMORY_H=1", "HAVE_STRINGS_H=1", "HAVE_INTTYPES_H=1", "HAVE_STDINT_H=1", "HAVE_UNISTD_H=1", "__EXTENSIONS__=1", "_ALL_SOURCE=1", "_GNU_SOURCE=1", "_POSIX_PTHREAD_SEMANTICS=1", "_TANDEM_SOURCE=1", "HAVE_DLFCN_H=1", "LT_OBJDIR=\".libs/\"", "HAVE_SYS_MMAN_H=1", "NATIVE_LITTLE_ENDIAN=1", "ASM_HIDE_SYMBOL=.hidden", "HAVE_WEAK_SYMBOLS=1", "HAVE_ATOMIC_OPS=1", "HAVE_ARC4RANDOM=1", "HAVE_ARC4RANDOM_BUF=1", "HAVE_MMAP=1", "HAVE_MLOCK=1", "HAVE_MADVISE=1", "HAVE_MPROTECT=1", "HAVE_NANOSLEEP=1", "HAVE_POSIX_MEMALIGN=1", "HAVE_GETPID=1", "CONFIGURED=1", "DEV_MODE=1", "HAVE_TMMINTRIN_H=1", "HAVE_WMMINTRIN_H=1", --[[#PC on here]] "HAVE_AMD64_ASM_V=1", "HAVE_AVX_ASM_V=1", "AVE_CPUID_V=1", "HAVE_TI_MODE_V=1", "HAVE_CPUID=1", "__x86_64__=1") add_includedirs( "3rd/libsodium/src/libsodium/include", "3rd/libsodium/src/libsodium/include/sodium") target("easyloggingpp") set_kind("static") add_files("3rd/easyloggingpp/src/**.cc") add_includedirs("3rd/easyloggingpp/src") add_defines("ELPP_THREAD_SAFE", "ELPP_FRESH_LOG_FILE", "ELPP_FEATURE_ALL", "ELPP_LOGGING_FLAGS_FROM_ARG", "ELPP_NO_DEFAULT_LOG_FILE") target("chimney-c") set_kind("binary") add_files("src/**.cpp") add_deps("easyloggingpp","sodium") add_includedirs("src/include", "3rd/rapidjson/include", "3rd/easyloggingpp/src") add_links("pthread") add_defines("ELPP_THREAD_SAFE", "ELPP_FRESH_LOG_FILE", "ELPP_FEATURE_ALL", "ELPP_LOGGING_FLAGS_FROM_ARG", "ELPP_NO_DEFAULT_LOG_FILE")
local M = {} M.config = function() local cmp = require'cmp' local fk = vim.fn.feedkeys local map = cmp.mapping local pv = vim.fn.pumvisible local rep = vim.api.nvim_replace_termcodes local snip = require'luasnip' cmp.setup{ formatting = { format = function (entry, vimitem) vimitem.kind = string.format( '%s %s', require'soup.kind'[vimitem.kind], vimitem.kind ) vimitem.menu = ({ buffer = '[BUF]', nvim_lsp = '[LSP]', nvim_lua = '[Lua]', })[entry.source.name] return vimitem end }, mapping = { ['<C-Space>'] = map.complete(), ['<C-d>'] = map.scroll_docs(-4), ['<C-e>'] = map.close(), ['<C-f>'] = map.scroll_docs(4), ['<C-n>'] = map.select_next_item(), ['<C-p>'] = map.select_prev_item(), ['<CR>'] = map.confirm{ behavior = cmp.ConfirmBehavior.Insert, select = true, }, ['<S-Tab>'] = function(fb) if pv() == 1 then fk(rep('<C-p>', true, true, true), 'n') elseif snip.jumpable(-1) then fk(rep('<Plug>luasnip-jump-prev', true, true, true), '') else fb() end end, ['<Tab>'] = function(fb) if pv() == 1 then fk(rep('<C-n>', true, true, true), 'n') elseif snip.expand_or_jumpable() then fk(rep('<Plug>luasnip-expand-or-jump', true, true, true), '') else fb() end end, }, snippet = { expand = function(args) require'luasnip'.lsp_expand(args.body) end, }, sources = { {name = 'nvim_lua'}, {name = 'nvim_lsp'}, {name = 'luasnip'}, {name = 'path'}, {name = 'buffer'}, }, } end return M
-------------------------------------------------------------------------------- local composer = require "composer" local widget = require "widget" local store = require "store" local _ = require "lib.underscore" local Message = require "app.views.message" local NavBar = require "app.views.navBar" local ListItem = require "app.views.listItem" local Button = require "app.views.button" local Head = require "app.views.head" local ProductPurchase = require "app.views.product_purchase" -------------------------------------------------------------------------------- local scene = composer.newScene() local navigationBar local activateBtn local list local buttonGroup local purchase_window local products = {} local sceneGroup local form_definitions -------------------------------------------------------------------------------- local function activatedAll() local all = Purchase:count({ product = appconfig.inapp_code_all }) > 0 local each = true for i = 1, #form_definitions.sections do if each then local definition = form_definitions.sections[i] if definition.inapp_code then each = Purchase:count({ product = definition.inapp_code }) > 0 end end end return all or each end local function doPurchase(product_id) ads.hide() purchase_window:hide() local purchase = Purchase:find({product = product_id}) if not purchase then Purchase:insert({ product = product_id }) end premium = true banner_height = 0 list.height = _AH - navigationBar.height navigationBar:toFront() if activatedAll() then buttonGroup.isVisible = false else list.height = list.height - 60 buttonGroup:toFront() buttonGroup.y = 0 end list.top = navigationBar.bottom list:reloadData() list:scrollToY({ y = 0 }) return true end local function productCallback( event ) if event and event.products then for i = 1,#event.products do local product = event.products[i] products[product.productIdentifier] = product if product.productIdentifier == appconfig.inapp_code_all and product.localizedPrice then activateBtn:setText(T:t("select_section.activate_all") .. " (" .. product.localizedPrice .. ")") end end list:reloadData() else print("NO PRODUCT IN EVENT") print("EVENT: " .. inspect(event)) end end local function loadProducts() if (store.canLoadProducts) then local result = store.loadProducts( _.keys(products), productCallback) else Message.toast("store.calLoadProducts vraci false, neni podpora nacitani produktu?") end end local function storeTransaction( event ) local transaction = event.transaction if transaction.state == "purchased" then doPurchase(transaction.productIdentifier) Message.toast(T:t("product_purchase.purchased_msg"), { color = "#448800" }) elseif transaction.state == "restored" then Message.toast(T:t("product_purchase.restored_msg"), { color = "#448800" }) doPurchase(transaction.productIdentifier) elseif transaction.state == "cancelled" then purchase_window:hide() Message.toast(T:t("product_purchase.cancelled_msg"), { color = "#881100" }) elseif transaction.state == "failed" then purchase_window:hide() Message.toast(T:t("product_purchase.failed_msg") .. " (" .. transaction.errorString .. ")", { color = "#881100" }) else purchase_window:hide() print("unknown event") end store.finishTransaction( transaction ) end local function tryPurchase(code) code = code or appconfig.inapp_code_all if system.getInfo("platformName") == "Android" then store.purchase( code ) else store.purchase({code}) end end local function tryRestorePurchase() store.restore() end -------------------------------------------------------------------------------- local function isProductActive(product) return product.free or (product.inapp_code and Purchase:count({ product = product.inapp_code }) > 0) or (Purchase:count({ product = appconfig.inapp_code_all }) > 0) end local function onRowRender(event) local row = event.row local color = "#000000" local lock = nil if not isProductActive(row.params) then -- if not row.params.free and -- (not row.params.inapp_code or Purchase:count({ product = row.params.inapp_code }) == 0) and -- (Purchase:count({ product = appconfig.inapp_code_all })) then color = "#777777" lock = T:t("select_section.activate") if products[row.params.inapp_code] and products[row.params.inapp_code].localizedPrice then lock = T:t("select_section.activate_for") .. " " .. products[row.params.inapp_code].localizedPrice end end local item = ListItem:new({ width = _AW, height = 60, title = T:t("title." .. row.params.code), titleColor = color, rightTextSize = 13, rightText = lock }) row:insert(item.group) end local function onRowTouch(event) local row = event.row if event.phase == 'tap' or event.phase == 'release' then -- if row.params.free or -- (row.params.inapp_code and Purchase:count({ product = row.params.inapp_code }) > 0) then if isProductActive(row.params) then row.params.clearForm = true composer.gotoScene("app.new_rating_step_1", { effect = "slideLeft", params = row.params }) else local product = {} if products[row.params.inapp_code] and products[row.params.inapp_code].localizedPrice then product = products[row.params.inapp_code] end purchase_window:show({ title = product.title or T:t("title." .. row.params.code), price = product.localizedPrice or row.params.inapp_price, description = product.description or row.params.inapp_description }) purchase_window.onPurchase = function() tryPurchase(row.params.inapp_code) end end end end function scene:redrawScene() local group = self.view if sceneGroup then sceneGroup:removeSelf() end sceneGroup = display.newGroup() group:insert(sceneGroup) navigationBar = NavBar.create({ title = T:t("select_section.title"), backBtn = { title = T:t("nav.back"), scene = "app.dashboard" }, }) sceneGroup:insert(navigationBar) if not activatedAll() then if not store or not store.isActive then local store_provider = "apple" if system.getInfo("platformName") == "Android" then print("ANDROID V3 IAP") store = require( "plugin.google.iap.v3" ) store_provider = "google" end print("------------------------------ STORE INIT: " .. store_provider .. " -----------------") store.init(store_provider, storeTransaction) print("------------------------------ STORE INIT DONE -------------------------------------") end buttonGroup = display.newGroup() sceneGroup:insert(buttonGroup) activateBtn = Button:new( buttonGroup, _B - 40, T:t("select_section.activate_all"), "main", function() if products[appconfig.inapp_code_all] then purchase_window:show({ title = products[appconfig.inapp_code_all].title or "", price = products[appconfig.inapp_code_all].localizedPrice or "", description = products[appconfig.inapp_code_all].description or "" }) purchase_window.onPurchase = function() tryPurchase(appconfig.inapp_code_all) end else Message.toast("Product is not available", { color = "#881100" }) end end, (_AW - 60) / 2, _L + _AW / 2 - (_AW - 60) / 4 - 10 ) restoreBtn = Button:new(buttonGroup, _B - 40, T:t("select_section.restore_purchases"), "gray", tryRestorePurchase, (_AW - 60) / 2, _L + _AW / 2 + (_AW - 60) / 4 + 10) buttonGroup.y = - banner_height end local head_height = Head.conditional_draw(sceneGroup, T:t("select_section.head_text"), _T + 65) list = widget.newTableView({ x = _W / 2, top = navigationBar.bottom + 5 + head_height, width = _AW, height = _AH - navigationBar.height - 60 - banner_height - head_height, left = _L, onRowTouch = onRowTouch, onRowRender = onRowRender }) sceneGroup:insert(list) products = {} products[appconfig.inapp_code_all] = {} for i = 1, #form_definitions.sections do local definition = form_definitions.sections[i] if definition.inapp_code then products[definition.inapp_code] = { } end list:insertRow({ rowHeight = 60, isCategory = false, rowColor = { 1, 1, 1 }, lineColor = { 0.90, 0.90, 0.90 }, params = definition }) end local foot_text = T:t('select_section.foot_text') if foot_text and string.len(foot_text) > 0 then list:insertRow({ rowHeight = 60, isCategory = true, rowColor = { 0.9, 0.9, 0.9 }, lineColor = { 0.90, 0.90, 0.90 }, params = foot_text }) end if store.isActive then timer.performWithDelay(50, loadProducts) end list:scrollToY({ y = 0, time = 0 }) purchase_window = ProductPurchase:new(sceneGroup, { height = 120 }) end function scene:create(event) form_definitions = loadTable("config/form_definitions.json", system.ResourceDirectory) or {sections = {}} end function scene:show(event) if event.phase == 'will' then self:redrawScene(event) end end scene:addEventListener( "create", scene) scene:addEventListener( "show", scene) return scene
require("assert_equal_expected") insulate("", function() test("Expected to be equal", function() local expected = 1 local actual = 1 assert.is_eq_expected(expected, actual) end) test("Expected to NOT be equal", function() local expected = 1 local actual = 2 assert.is_not_eq_expected(expected, actual) end) end)
string.startswith = function (s, p) return string.sub(s, 1, string.len(p)) == p end string.endswith = function (s, p) return string.sub(s, string.len(s) - string.len(p) + 1) == p end string.split = function (str, delimiter) if str == nil or str == '' or delimiter == nil then return nil end local result = {} for match in (str .. delimiter):gmatch("(.-)" .. delimiter) do table.insert(result, match) end return result end
local tasty = require 'tasty' local test = tasty.test_case local group = tasty.test_group local assert = tasty.assert return { group 'ListAttributes' { test('has field `start`', function () local la = ListAttributes(7, DefaultStyle, Period) assert.are_equal(la.start, 7) end), test('has field `style`', function () local la = ListAttributes(1, Example, Period) assert.are_equal(la.style, 'Example') end), test('has field `delimiter`', function () local la = ListAttributes(1, Example, Period) assert.are_equal(la.delimiter, 'Period') end), test('can be compared on equality', function () assert.are_equal( ListAttributes(2, DefaultStyle, Period), ListAttributes(2, DefaultStyle, Period) ) assert.is_falsy( ListAttributes(2, DefaultStyle, Period) == ListAttributes(4, DefaultStyle, Period) ) end), test('can be modified through `start`', function () local la = ListAttributes(3, Decimal, OneParen) la.start = 20 assert.are_equal(la, ListAttributes(20, Decimal, OneParen)) end), test('can be modified through `style`', function () local la = ListAttributes(3, Decimal, OneParen) la.style = LowerRoman assert.are_equal(la, ListAttributes(3, LowerRoman, OneParen)) end), test('can be modified through `delimiter`', function () local la = ListAttributes(5, UpperAlpha, DefaultDelim) la.delimiter = TwoParens assert.are_equal(la, ListAttributes(5, UpperAlpha, TwoParens)) end), test('can be cloned', function () local la = ListAttributes(2, DefaultStyle, Period) local cloned = la:clone() assert.are_equal(la, cloned) la.start = 9 assert.are_same(cloned.start, 2) end), group 'Constructor' { test('omitting a start numer sets it to 1', function () assert.are_equal(ListAttributes().start, 1) end), test('omitting a style sets it to DefaultStyle', function () assert.are_equal(ListAttributes(0).style, DefaultStyle) end), test('omitting a delimiter sets it to DefaultDelim', function () assert.are_equal(ListAttributes(0, UpperRoman).delimiter, DefaultDelim) end) } }, }
local function create() local inst = {} inst.items = {} function inst:GetItem(slot) return self.items[slot] end function inst:RemoveItem(slot) self.items[slot] = nil end function inst:SetItem(slot, name) self.items[slot] = CreateItem(self, slot, name) end function inst:IsEmpty(slot) return not self.items[slot] end function inst:ChangeWithCursor(slot) MOUSE_SLOT.items[1], self.items[slot] = self.items[slot], MOUSE_SLOT.items[1] --[[if MOUSE_SLOT.item == self.items[slot].id then self.items[slot].amount = self.items[slot].amount + MOUSE_SLOT.amount MOUSE_SLOT.item = 0 MOUSE_SLOT.amount = 0 return end MOUSE_SLOT.item, self.items[slot].id = self.items[slot].id, MOUSE_SLOT.item MOUSE_SLOT.amount, self.items[slot].amount = self.items[slot].amount, MOUSE_SLOT.amount]] end --[[local inst = {} inst.items = {} function inst:AddSlot(slot) local i = {} i.id = 0 i.amount = 0 function i:Reduce(amount) self.amount = self.amount - amount if self.amount <= 0 then self.id = 0 self.amount = 0 end print(self.amount) end function i:GetItem() return ITEMS[self.id] end function i:IsEmpty() return self.id == 0 end self.items[slot] = i end function inst:SetItem(slot, item) self.items[slot].id = item end function inst:ChangeWithCursor(slot) if MOUSE_SLOT.item == self.items[slot].id then self.items[slot].amount = self.items[slot].amount + MOUSE_SLOT.amount MOUSE_SLOT.item = 0 MOUSE_SLOT.amount = 0 return end MOUSE_SLOT.item, self.items[slot].id = self.items[slot].id, MOUSE_SLOT.item MOUSE_SLOT.amount, self.items[slot].amount = self.items[slot].amount, MOUSE_SLOT.amount end function inst:PutIn(inventory) -- Coming soon end function inst:GetItem(slot) return ITEMS[self.items[slot].id] end function inst:GetItemStack(slot) return self.items[slot] end function inst:IsEmpty(slot) if self.items[slot].amount <= 0 then self.items[slot].id = 0 self.items[slot].amount = 0 return true end return self.items[slot].id == 0 end function inst:GetAmount(slot) return self.items[slot].amount end function inst:SetAmount(slot, a) self.items[slot].amount = a end]] --inst:SetItem("arm", "food_bowl") return inst end return create
local ok, saga = pcall(require, "lspsaga") if (not ok) then return end local map = require('helpers.map').map saga.init_lsp_saga({ code_action_icon = " ", definition_preview_icon = " ", dianostic_header_icon = "  ", error_sign = " ", finder_definition_icon = " ", finder_reference_icon = " ", hint_sign = "⚡", infor_sign = "", warn_sign = "", }) local opts = { noremap=true, silent=true } map("n", "<Leader>cf", ":Lspsaga lsp_finder<CR>", opts) map("n", "<Leader>ca", ":Lspsaga code_action<CR>", opts) map("v", "<Leader>ca", ":<C-U>Lspsaga range_code_action<CR>", opts) map("n", "<Leader>ch", ":Lspsaga hover_doc<CR>", opts) map("n", "<Leader>ck", '<cmd>lua require("lspsaga.action").smart_scroll_with_saga(-1)<CR>', opts) map("n", "<Leader>cj", '<cmd>lua require("lspsaga.action").smart_scroll_with_saga(1)<CR>', opts) map("n", "<Leader>cs", ":Lspsaga signature_help<CR>", opts) map("n", "<Leader>ci", ":Lspsaga show_line_diagnostics<CR>", opts) map("n", "<Leader>cc", ":Lspsaga show_cursor_diagnostics<CR>", opts) map("n", "<Leader>cn", ":Lspsaga diagnostic_jump_next<CR>", opts) map("n", "<Leader>cp", ":Lspsaga diagnostic_jump_prev<CR>", opts) map("n", "<Leader>cr", ":Lspsaga rename<CR>", opts) map("n", "<Leader>cd", ":Lspsaga preview_definition<CR>", opts)
local base58 = require('basex').base58bitcoin local cipher = require('app.cipher') local mediatypes = require('app.mediatypes') local utils = require('app.utils') local cipher_encrypt = cipher.encrypt local cipher_decrypt = cipher.decrypt local DEFAULT_TYPE_ID = mediatypes.DEFAULT_TYPE_ID local ID_TYPE_MAP = mediatypes.ID_TYPE_MAP local decode_urlsafe_base64 = utils.decode_urlsafe_base64 local encode_urlsafe_base64 = utils.encode_urlsafe_base64 local get_substring = utils.get_substring local _M = {} _M.encode = function(params) local file_id_bytes, err = decode_urlsafe_base64(params.file_id) if not file_id_bytes then return nil, err end local file_id_size_byte = string.char(#file_id_bytes) local media_type_byte = string.char(params.media_type_id or DEFAULT_TYPE_ID) local tiny_id_raw_bytes = table.concat{ file_id_size_byte, file_id_bytes, media_type_byte, } local tiny_id_encr_bytes = cipher_encrypt(tiny_id_raw_bytes) return base58:encode(tiny_id_encr_bytes) end _M.decode = function(tiny_id) -- decrypt tiny_id local tiny_id_encr_bytes, err = base58:decode(tiny_id) if not tiny_id_encr_bytes then return nil, err end local tiny_id_raw_bytes, err = cipher_decrypt(tiny_id_encr_bytes) -- luacheck: ignore 411 if not tiny_id_raw_bytes then return nil, err end -- get file_id size local file_id_size = string.byte(tiny_id_raw_bytes:sub(1, 1)) if not file_id_size or file_id_size < 1 then return nil, 'Wrong file_id size' end -- get file_id local file_id_bytes, pos file_id_bytes, pos = get_substring(tiny_id_raw_bytes, 2, file_id_size) if #file_id_bytes < file_id_size then return nil, 'file_id size less than declared' end local file_id = encode_urlsafe_base64(file_id_bytes) -- get media_type local media_type = nil local media_type_id = nil if pos then local media_type_byte = get_substring(tiny_id_raw_bytes, pos, 1) media_type_id = string.byte(media_type_byte) if media_type_id ~= DEFAULT_TYPE_ID then media_type = ID_TYPE_MAP[media_type_id] end end return { file_id = file_id, media_type_id = media_type_id, media_type = media_type, } end return _M
if not pcall(require, "lualine") then return end local should_reload = true local reloader = function() if should_reload then RELOAD "lualine" RELOAD "bufferline" RELOAD "kalimali.lualine.utils" RELOAD "kalimali.lualine.bufferline" end end reloader() local lualine = require 'lualine' local utils = require 'kalimali.lualine.utils' -- LUALINE CONFIGS -- Default Configs local lualine_config = utils.default_config -- LEFT SECTION -- utils.ins_left (config, utils.ins_delim) utils.ins_left (lualine_config, utils.show_mode) utils.ins_left (lualine_config, utils.show_git_branch) utils.ins_left (lualine_config, utils.ins_section) utils.ins_left (lualine_config, utils.show_filename) utils.ins_left (lualine_config, utils.show_filesize) -- utils.ins_left (config, utils.ins_section) -- RIGHT SECTION utils.ins_right (lualine_config, utils.show_lspserver) utils.ins_right (lualine_config, utils.show_lspdiagnostics) utils.ins_right (lualine_config, utils.show_encoding) -- utils.ins_right (config, utils.show_fileformat) utils.ins_right (lualine_config, utils.show_git_diff) utils.ins_right (lualine_config, utils.show_progress) utils.ins_right (lualine_config, utils.show_location) lualine.setup(lualine_config)
---@class CS.FairyGUI.GPath ---@field public length number ---@field public segmentCount number ---@type CS.FairyGUI.GPath CS.FairyGUI.GPath = { } ---@return CS.FairyGUI.GPath function CS.FairyGUI.GPath.New() end ---@overload fun(points:CS.System.Collections.Generic.IEnumerable_CS.FairyGUI.GPathPoint): void ---@overload fun(pt1:CS.FairyGUI.GPathPoint, pt2:CS.FairyGUI.GPathPoint): void ---@overload fun(pt1:CS.FairyGUI.GPathPoint, pt2:CS.FairyGUI.GPathPoint, pt3:CS.FairyGUI.GPathPoint): void ---@param pt1 CS.FairyGUI.GPathPoint ---@param optional pt2 CS.FairyGUI.GPathPoint ---@param optional pt3 CS.FairyGUI.GPathPoint ---@param optional pt4 CS.FairyGUI.GPathPoint function CS.FairyGUI.GPath:Create(pt1, pt2, pt3, pt4) end function CS.FairyGUI.GPath:Clear() end ---@return CS.UnityEngine.Vector3 ---@param t number function CS.FairyGUI.GPath:GetPointAt(t) end ---@return number ---@param segmentIndex number function CS.FairyGUI.GPath:GetSegmentLength(segmentIndex) end ---@param segmentIndex number ---@param t0 number ---@param t1 number ---@param points CS.System.Collections.Generic.List_CS.UnityEngine.Vector3 ---@param ts CS.System.Collections.Generic.List_CS.System.Single ---@param pointDensity number function CS.FairyGUI.GPath:GetPointsInSegment(segmentIndex, t0, t1, points, ts, pointDensity) end ---@param points CS.System.Collections.Generic.List_CS.UnityEngine.Vector3 ---@param pointDensity number function CS.FairyGUI.GPath:GetAllPoints(points, pointDensity) end return CS.FairyGUI.GPath
----------------------------------- -- Area: Windurst Waters -- NPC: Machitata -- Involved in Quest: Hat in Hand -- !pos 163 0 -22 238 ----------------------------------- local ID = require("scripts/zones/Windurst_Waters/IDs") require("scripts/globals/settings") require("scripts/globals/keyitems") require("scripts/globals/quests") require("scripts/globals/titles") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) function testflag(set, flag) return (set % (2*flag) >= flag) end hatstatus = player:getQuestStatus(WINDURST, tpz.quest.id.windurst.HAT_IN_HAND) if ((hatstatus == 1 or player:getCharVar("QuestHatInHand_var2") == 1) and testflag(tonumber(player:getCharVar("QuestHatInHand_var")), 1) == false) then player:messageSpecial(ID.text.YOU_SHOW_OFF_THE, tpz.ki.NEW_MODEL_HAT) player:addCharVar("QuestHatInHand_var", 1) player:addCharVar("QuestHatInHand_count", 1) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
local Typer = require(script.Parent.Parent.Parent.Typer) local function toList(set) local new = {} local index = 1 for key in next, set do new[index] = key index = index + 1 end return new end return Typer.AssignSignature(Typer.Table, toList)
local on_tick = {} local event = require("__flib__.event") local translation = require("__flib__.translation") local function handler(e) if translation.translating_players_count() > 0 then translation.iterate_batch(e) else event.on_tick(nil) end end function on_tick.update() if global.__flib and translation.translating_players_count() > 0 then event.on_tick(handler) end end return on_tick
function saving(p,typ,money) local username = getElementData(p,"username") if typ == 1 then setElementData(p,"susa:d_licence",1) local f = dbQuery(db, "UPDATE accounts SET d_licence=?, money=? WHERE username=?",1 ) dbFree(f) elseif typ == 2 then setElementData(p,"susa:b_licence",1) local f = dbQuery(db, "UPDATE accounts SET b_licence=?,money=? WHERE username=?",1) dbFree(f) elseif typ == 3 then setElementData(p,"susa:taxi",1) local f = dbQuery(db, "UPDATE accounts SET taxi_licence=?,money=? WHERE username=?",1) dbFree(f) elseif typ == 4 then setElementData(p,"susa:trash",1) local f = dbQuery(db, "UPDATE accounts SET bus_licence=?,money=? WHERE username=?",1) dbFree(f) elseif typ == 5 then setElementData(p,"susa:bus",1) local f = dbQuery(db, "UPDATE accounts SET trashman_licence=?,money=? WHERE username=?",1) dbFree(f) elseif typ == 6 then setElementData(p,"susa:tuning",1) local f = dbQuery(db, "UPDATE accounts SET tuning_licence=?,money=? WHERE username=?",1) dbFree(f) end setPlayerMoney(p,money) end addEvent("licence",true) addEventHandler("licence",root,saving) addCommandHandler("leave", function(plr) setElementData(plr,"susa:taxi",0) setElementData(plr,"susa:bus",0) setElementData(plr,"susa:trash",0) outputChatBox("You successfully quit your job. Now you can accept other jobs.",plr,0,180,0,false) end )
if not modules then modules = { } end modules ['typo-fkr'] = { version = 1.001, comment = "companion to typo-fkr.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } local nuts = nodes.nuts local tonut = nuts.tonut local getid = nuts.getid local getnext = nuts.getnext local getchar = nuts.getchar local getfont = nuts.getfont local getattr = nuts.getattr local nodecodes = nodes.nodecodes local glyph_code = nodecodes.glyph local fontdata = fonts.hashes.identifiers local getkernpair = fonts.handlers.otf.getkern local insert_before = nuts.insert_before local new_kern = nuts.pool.fontkern local enableaction = nodes.tasks.enableaction local a_extrakern = attributes.private("extrafontkern") -- 0=none 1=min 2=max 3=mixed typesetters.fontkerns = { } function typesetters.fontkerns.handler(head) local kepthead = head local head = tonut(head) local current = head local lastfont = nil local lastchar = nil local lastdata = nil local done = false while current do local id = getid(current) if id == glyph_code then local a = getattr(current,a_extrakern) if a then local char = getchar(current) local font = getfont(current) if font ~= lastfont then if a > 0 and lastchar then if not lastdata then lastdata = fontdata[lastfont] end local kern = nil local data = fontdata[font] local kern1 = getkernpair(lastdata,lastchar,char) local kern2 = getkernpair(data,lastchar,char) if a == 1 then kern = kern1 > kern2 and kern2 or kern1 -- min elseif a == 2 then kern = kern1 > kern2 and kern1 or kern2 -- max else -- 3 kern = (kern1 + kern2)/2 -- mixed end if kern ~= 0 then head, current = insert_before(head,current,new_kern(kern)) done = true end lastdata = data else lastdata = nil end elseif lastchar then if not lastdata then lastdata = fontdata[lastfont] end local kern = getkernpair(lastdata,lastchar,char) if kern ~= 0 then head, current = insert_before(head,current,new_kern(kern)) done = true end end lastchar = char lastfont = font elseif lastfont then lastfont = nil lastchar = nil lastdata = nil end elseif lastfont then lastfont = nil lastchar = nil lastdata = nil end current = getnext(current) end return kepthead, done end if context then local variables = interfaces.variables local unsetvalue = attributes.unsetvalue local enabled = false local setattribute = tex.setattribute local values = { [variables.none ] = 0, [variables.min ] = 1, [variables.max ] = 2, [variables.mixed] = 3, [variables.reset] = unsetvalue, } local function setextrafontkerns(str) if not enabled then enableaction("processors","typesetters.fontkerns.handler") enabled = true end setattribute(a_extrakern,values[str] or unsetvalue) end interfaces.implement { name = "setextrafontkerns", arguments = "string", actions = setextrafontkerns, } end
local bp = require("bp") test_ai = {} function test_ai:test_call_func( ) local testValue = 1 local action = bp.call_func {function(graph) testValue = graph:get_data().value end} local graph = bp.graph {} graph:set_data({value=1234}) action:start(graph) action:update() lu.assertTrue(action:is_done()) lu.assertEquals(testValue, 1234) end function test_ai:test_wait( ) local action = bp.wait{5000} action:start() lu.assertFalse(action:is_done()) action:update(1000) lu.assertFalse(action:is_done()) action:update(4000) lu.assertTrue(action:is_done()) local action = bp.wait{5000} action:start() lu.assertFalse(action:is_done()) action:update(6000) lu.assertTrue(action:is_done()) end function test_ai:test_if_else( ) --测试:if_else进入true local check_ret_true = function() return true end local trueAction = bp.call_func {function(graph) graph:get_data().value = 2 end} local action = bp.if_else {check_ret_true, trueAction} local testTbl = { value = 1 } local graph = bp.graph {} graph:set_data(testTbl) action:start(graph) action:update() lu.assertTrue(action:is_done()) lu.assertEquals(testTbl.value, 2) --测试:if_else进入false local check_ret_false = function() return false end local FalseAction = bp.oo.class { __index = { start = function(self, graph) self.graph = graph end, is_done = function(self) return true end, update = function(self) self.graph:get_data().value = 333333 end } } local action = bp.if_else {check_ret_false, trueAction, FalseAction{}} local testTbl = { value = 1 } local graph = bp.graph {} graph:set_data(testTbl) action:start(graph) action:update() lu.assertTrue(action:is_done()) lu.assertEquals(testTbl.value, 333333) end local CheckerCallable = bp.oo.class { type = "checker", __index = { start = function(self, graph) self.graph = graph end, }, __call = function(self) return self[1] end } local Checker = bp.oo.class { type = "checker", __index = { start = function(self, graph) self.graph = graph end, update = function(self) return self[1] end, }, } function test_ai:test_if_else_with_checker() --测试:if_else的是否会调用条件节点的start函数 local actionA = bp.call_func {function(graph) graph:get_data().value = "a" end} local action = bp.if_else {CheckerCallable{true}, actionA} local testTbl = { } local graph = bp.graph {} graph:set_data(testTbl) action:start(graph) action:update() lu.assertTrue(action:is_done()) lu.assertEquals(testTbl.value, "a") local action = bp.if_else {Checker{true}, actionA} local testTbl = { } local graph = bp.graph {} graph:set_data(testTbl) action:start(graph) action:update() lu.assertTrue(action:is_done()) lu.assertEquals(testTbl.value, "a") end function test_ai:test_sequence( ) local actionA = bp.call_func {function(graph) graph:get_data().value = "a" end} local actionB = bp.call_func {function(graph) graph:get_data().value = "b" end} local actionC = bp.call_func {function(graph) graph:get_data().value = "c" end} local action = bp.sequence{ actionA, bp.wait{1000}, actionB, actionC } local testTbl = {value = "0"} local graph = bp.graph {} graph:set_data(testTbl) action:start(graph) lu.assertFalse(action:is_done()) action:update(500) lu.assertFalse(action:is_done()) lu.assertEquals(testTbl.value, "a") --在sequence里的delay,就算是时间到了,也要下次Update才会运行delay后面的Action action:update(500) lu.assertTrue(action:is_done()) lu.assertEquals(testTbl.value, "c") local action = bp.sequence{ actionA, bp.wait{1000}, actionB, bp.wait{1000}, actionC } local testTbl = {value = "0"} local graph = bp.graph {} graph:set_data(testTbl) action:start(graph) action:update(1000) lu.assertEquals(testTbl.value, "b") lu.assertFalse(action:is_done()) action:update(1000) lu.assertEquals(testTbl.value, "c") lu.assertTrue(action:is_done()) --最后一个是delay local action = bp.sequence{ actionA, bp.wait{1000} } local testTbl = {value = "0"} local graph = bp.graph {} graph:set_data(testTbl) action:start(graph) action:update(500) lu.assertEquals(testTbl.value, "a") lu.assertFalse(action:is_done()) action:update(500) lu.assertTrue(action:is_done()) --测试delay被If包裹后会不会被漏掉 local action = bp.sequence{ actionA, bp.if_else{ bp.random{10000}, bp.wait{1000}, bp.wait{1000}}, actionB, bp.wait{1000}, actionC } local testTbl = {value = "0"} local graph = bp.graph {} graph:set_data(testTbl) action:start(graph) action:update(1000) lu.assertEquals(testTbl.value, "b") action:update(1000) lu.assertEquals(testTbl.value, "c") end function test_ai:test_random( ) local trueAction = bp.call_func {function(graph) graph:get_data().value = "true" end} local falseAction = bp.call_func {function(graph) graph:get_data().value = "false" end} local testTbl = {value = 1} local ifAction = bp.if_else {bp.random{10000}, trueAction, falseAction} local graph = bp.graph {} graph:set_data(testTbl) ifAction:start(graph) ifAction:update() lu.assertTrue(ifAction:is_done()) lu.assertEquals(testTbl.value, "true") testTbl.value = 1 local ifAction = bp.if_else {bp.random{0}, trueAction, falseAction} local graph = bp.graph {} graph:set_data(testTbl) ifAction:start(graph) ifAction:update() lu.assertTrue(ifAction:is_done()) lu.assertEquals(testTbl.value, "false") end function test_ai:test_all_true( ) local is_value_1_and_set_2 = function(graph) local data = graph:get_data() local isTrue = data.value == 1 data.value = 2 return isTrue end local is_value_2_and_set_3 = function(graph) local data = graph:get_data() local isTrue = data.value == 2 data.value = 3 return isTrue end local set_result_true = bp.call_func {function(graph) local data = graph:get_data() data.result = "true" end} local set_result_false = bp.call_func {function(graph) local data = graph:get_data() data.result = "false" end} local action = bp.if_else {bp.all_true{is_value_1_and_set_2, is_value_2_and_set_3}, set_result_true, set_result_false} local testTbl = { value = 1 } local graph = bp.graph {} graph:set_data(testTbl) action:start(graph) action:update() lu.assertTrue(action:is_done()) lu.assertEquals(testTbl.value, 3) lu.assertEquals(testTbl.result, "true") local action = bp.if_else {bp.all_true{is_value_1_and_set_2, is_value_2_and_set_3}, set_result_true, set_result_false} local testTbl = { value = 1111 } local graph = bp.graph {} graph:set_data(testTbl) action:start(graph) action:update() lu.assertTrue(action:is_done()) lu.assertEquals(testTbl.value, 2) lu.assertEquals(testTbl.result, "false") local action = bp.if_else {bp.all_true{Checker{true}, bp.get_bb{"bb_value"}}, set_result_true, set_result_false} local testTbl = { value = 1 } local graph = bp.graph {} graph:set_bb("bb_value", true) graph:set_data(testTbl) action:start(graph) action:update() lu.assertTrue(action:is_done()) lu.assertEquals(testTbl.value, 1) lu.assertEquals(testTbl.result, "true") end function test_ai:test_any_true( ) local conditionTrue = function(graph) return true end local conditionFalse = function(graph) return false end local conditionNil = function(graph) return nil end local trueAction = bp.call_func {function(graph) graph:get_data().result = "true" end} local falseAction = bp.call_func {function(graph) graph:get_data().result = "false" end} local action = bp.if_else {bp.any_true{conditionTrue, conditionFalse}, trueAction, falseAction} local testTbl = {} local graph = bp.graph {} graph:set_data(testTbl) action:start(graph) action:update() lu.assertTrue(action:is_done()) lu.assertEquals(testTbl.result, "true") action = bp.if_else {bp.any_true{conditionFalse, conditionTrue}, trueAction, falseAction} testTbl = {} graph = bp.graph {} graph:set_data(testTbl) action:start(graph) action:update() lu.assertTrue(action:is_done()) lu.assertEquals(testTbl.result, "true") action = bp.if_else {bp.any_true{conditionFalse, conditionNil, conditionFalse}, trueAction, falseAction} testTbl = {} graph = bp.graph {} graph:set_data(testTbl) action:start(graph) action:update() lu.assertTrue(action:is_done()) lu.assertEquals(testTbl.result, "false") end function test_ai:test_loop( ) local funcAction = bp.call_func {function(graph) local data = graph:get_data() data.loop = data.loop + 1 end} local action = bp.loop {5, funcAction} local testTbl = {loop=0} local graph = bp.graph {} graph:set_data(testTbl) action:start(graph) lu.assertFalse(action:is_done()) for i=1,5 do lu.assertFalse(action:is_done()) action:update() lu.assertEquals(testTbl.loop, i) if i ~= 5 then lu.assertFalse(action:is_done()) else lu.assertTrue(action:is_done()) end end local action = bp.loop {4, bp.sequence { funcAction, bp.wait{100}} } local testTbl = {loop=0} local graph = bp.graph {} graph:set_data(testTbl) action:start(graph) action:update(99) lu.assertEquals(testTbl.loop, 1) lu.assertFalse(action:is_done()) action:update(1) lu.assertEquals(testTbl.loop, 1) lu.assertFalse(action:is_done()) action:update(55) lu.assertEquals(testTbl.loop, 2) lu.assertFalse(action:is_done()) action:update(2) lu.assertEquals(testTbl.loop, 2) lu.assertFalse(action:is_done()) action:update(155) lu.assertEquals(testTbl.loop, 2) lu.assertFalse(action:is_done()) action:update(555) lu.assertEquals(testTbl.loop, 3) lu.assertFalse(action:is_done()) action:update(100) lu.assertEquals(testTbl.loop, 4) lu.assertTrue(action:is_done()) end function test_ai:test_loop_infinite( ) local funcAction = bp.call_func {function(graph) local data = graph:get_data() data.loop = data.loop + 1 end} local act = bp.loop {-1, bp.sequence { funcAction, bp.wait{2}}} local data = {loop=0} local graph = bp.graph {} graph:set_data(data) act:start(graph) for i=1,10 do act:update(1) lu.assertEquals(data.loop, i) act:update(1) end end function test_ai:test_parallel() --测试:同时跑几个 action local run_num = 4 local acts = {} for i=1,run_num do local funcAction = bp.call_func {function(graph) local data = graph:get_data() data.test_num = data.test_num + 1 end} acts[#acts + 1] = funcAction end local act = bp.parallel(acts) local data = {test_num=0} local graph = bp.graph {} graph:set_data(data) act:start(graph) act:update(1) lu.assertEquals(data.test_num, run_num) lu.assertTrue(act:is_done()) end function test_ai:test_parallel_with_wait() --测试:同时跑几个 action,其中有一个等待节点,需要等该节点完成才算真正完成 local run_num = 4 local acts = {} for i=1,run_num do local funcAction = bp.call_func {function(graph) local data = graph:get_data() data.test_num = data.test_num + 1 end} acts[#acts + 1] = funcAction end table.insert(acts, 2, bp.wait {100}) local act = bp.parallel(acts) local data = {test_num=0} local graph = bp.graph {} graph:set_data(data) act:start(graph) act:update(10) lu.assertEquals(data.test_num, run_num) lu.assertFalse(act:is_done()) act:update(50) lu.assertEquals(data.test_num, run_num) lu.assertFalse(act:is_done()) act:update(40) lu.assertEquals(data.test_num, run_num) lu.assertTrue(act:is_done()) end function test_ai:test_bd() local act = bp.sequence { bp.set_bb {"test_bd_1", 1}, bp.set_bb {"test_bd_2", true}, bp.set_bb {"test_bd_3", "test_bd_3"}, } local graph = bp.graph {} graph:set_data(data) act:start(graph) act:update(10) lu.assertEquals(graph:get_bb("test_bd_1"), 1) lu.assertEquals(graph:get_bb("test_bd_2"), true) lu.assertEquals(graph:get_bb("test_bd_3"), "test_bd_3") end local ReturnNum = bp.oo.class { type = "ReturnNum", __index = { start = function(self, graph) self.graph = graph end, update = function(self, dt) return self.return_num end, }, } local ReturnNum = bp.oo.class { type = "ReturnNum", __index = { start = function(self, graph) self.graph = graph end, update = function(self, dt) return self.return_num end, }, } function test_ai:test_operator() local trueAction = bp.call_func {function(graph) graph:get_data().value = 1 end} local falseAction = bp.call_func {function(graph) graph:get_data().value = 2 end} --测试:not local act = bp.if_else { bp.operator {"not", false}, trueAction, falseAction } local graph = bp.graph {} local data = {value=0} graph:set_data(data) act:start(graph) act:update() lu.assertEquals(data.value, 1) --测试:大于 local act = bp.if_else { bp.operator {">", 22, 11}, trueAction, falseAction } local graph = bp.graph {} local data = {value=0} graph:set_data(data) act:start(graph) act:update() lu.assertEquals(data.value, 1) --测试:小于 local act = bp.if_else { bp.operator {"<", 11, 22}, trueAction, falseAction } local graph = bp.graph {} local data = {value=0} graph:set_data(data) act:start(graph) act:update() lu.assertEquals(data.value, 1) --测试:等于 local act = bp.if_else { bp.operator {"==", ReturnNum{return_num=11}, 11}, trueAction, falseAction } local graph = bp.graph {} local data = {value=0} graph:set_data(data) act:start(graph) act:update() lu.assertEquals(data.value, 1) --测试:小于等于 local act = bp.if_else { bp.operator {"<=", 11, ReturnNum{return_num=22}}, trueAction, falseAction } local graph = bp.graph {} local data = {value=0} graph:set_data(data) act:start(graph) act:update() lu.assertEquals(data.value, 1) --测试:大于等于 local act = bp.if_else { bp.operator {">=", ReturnNum{return_num=22}, ReturnNum{return_num=11}}, trueAction, falseAction } local graph = bp.graph {} local data = {value=0} graph:set_data(data) act:start(graph) act:update() lu.assertEquals(data.value, 1) --测试:not nil local act = bp.if_else { bp.operator {"not", ReturnNum{return_num=nil}}, trueAction, falseAction } local graph = bp.graph {} local data = {value=0} graph:set_data(data) act:start(graph) act:update() lu.assertEquals(data.value, 1) --测试:传入updater local act = bp.if_else { bp.operator {"not", Checker{false}}, trueAction, falseAction } local graph = bp.graph {} local data = {value=0} graph:set_data(data) act:start(graph) act:update() lu.assertEquals(data.value, 1) --测试:传入callable local act = bp.if_else { bp.operator {"not", CheckerCallable{false}}, trueAction, falseAction } local graph = bp.graph {} local data = {value=0} graph:set_data(data) act:start(graph) act:update() lu.assertEquals(data.value, 1) end function test_ai:test_slot_action() local SlotName = "SlotName1" local graph = bp.graph {} local fake_act_out = {} local fake_act_in = {} graph:register_slot(fake_act_out, "out", 1, SlotName) graph:register_slot(fake_act_in, "in", 1, SlotName) graph:set_slot_value(fake_act_out, 1, "haha") local slot_value = graph:get_slot_value(fake_act_in, 1) lu.assertEquals(slot_value, "haha") local SlotName = "SlotName2" local graph = bp.graph {} local get_bb_value = bp.get_bb {"test_bd_key"} --注册孔是为了在 get_bb 内部的孔是按顺序的数字作 key,只需要调用 self.graph:set_slot_value(1, get到的某值) graph:register_slot(get_bb_value, "out", 1, SlotName) local op_not_act = bp.operator {"not"} graph:register_slot(op_not_act, "in", 1, SlotName) local act = bp.sequence { bp.set_bb {"test_bd_key", true}, get_bb_value, bp.if_else { op_not_act, nil, bp.call_func {function(graph) graph:get_data().value = 1 end} }, } local data = {value=0} graph:set_data(data) act:start(graph) act:update(1) lu.assertEquals(data.value, 1) end
SLASH_PTR1 = "/ptr"; SlashCmdList["PTR"] = function (message) local parsed = EOT_ParseCommand(message) if parsed[1] == nil then EOT_Log("/ptr") EOT_Log(" buff - Buff the current target. Hold ctrl for offspec") EOT_Log(" wipe - Wipe your group quickly") EOT_Log(" res - Revive/reset health/mana of your group") EOT_Log(" gather - Ports your entire group to you") EOT_Log(" raidbuff - Buffs the entire group") EOT_Log(" phase - Unlearns skills from later phases") EOT_Log(" aura - place an aura on the entire group") EOT_Log(" roster - creates a copyable list of the current raid members") elseif parsed[1] == "god" then if parsed[2] == "on" or parsed[2] == "off" then EOT_GodGroup(parsed[2]) else EOT_Log("/ptr god") EOT_Log(" on - turns godmode on for the group") EOT_Log(" off - turns godmode off for the group") end elseif parsed[1] == "aura" then EOT_AuraGroup(tonumber(parsed[2])) elseif parsed[1] == "buff" then if parsed[2] == nil then EOT_Log("/ptr buff") EOT_Log(" 0 - Castable buffs only") EOT_Log(" 1 - Trash consumes") EOT_Log(" 2 - Boss consumes") EOT_Log(" 3 - Boss consumes + flasks") else EOT_BuffTarget(tonumber(parsed[2])) end elseif parsed[1] == "raidbuff" then if parsed[2] == nil then EOT_Log("/ptr raidbuff") EOT_Log(" 0 - Castable buffs only") EOT_Log(" 1 - Trash consumes") EOT_Log(" 2 - Boss consumes") EOT_Log(" 3 - Boss consumes + flasks") else EOT_BuffGroup(tonumber(parsed[2])) end elseif parsed[1] == "wipe" then EOT_WipeGroup() elseif parsed[1] == "res" then EOT_ResGroup() elseif parsed[1] == "gather" then EOT_GatherGroup() elseif parsed[1] == "repair" then EOT_RepairGroup() elseif parsed[1] == "phase" then EOT_SetPhaseTarget(tonumber(parsed[2])) elseif parsed[1] == "cooldown" then EOT_CooldownGroup(0) elseif parsed[1] == "roster" then EOT_PrintGroup() else EOT_Error("No such command:", parsed[1]) end end EoTPTR = CreateFrame("Frame", nil, UIParent) EOT_Log("AddOn loaded. Type /ptr for help.") -- initialize default variables EoTPTR.frames = {}
local class = require 'middleclass' return class('Game', require 'Application')
local export = {} local m_data = require('grc-utilities/data') local tokenize = require('grc-utilities').tokenize local ufind = mw.ustring.find local ugsub = mw.ustring.gsub local U = mw.ustring.char local ulower = mw.ustring.lower local uupper = mw.ustring.upper local UTF8char = '[%z\1-\127\194-\244][\128-\191]*' -- Diacritics local diacritics = m_data.named -- Greek local acute = diacritics.acute local grave = diacritics.grave local circumflex = diacritics.circum local diaeresis = diacritics.diaeresis local smooth = diacritics.smooth local rough = diacritics.rough local macron = diacritics.macron local breve = diacritics.breve local subscript = diacritics.subscript -- Latin local hat = diacritics.Latin_circum local macron_diaeresis = macron .. diaeresis .. "?" .. hat local a_subscript = '^[αΑ].*' .. subscript .. '$' local velar = 'κγχξ' local tt = { -- Vowels ["α"] = "a", ["ε"] = "e", ["η"] = "e" .. macron, ["ι"] = "i", ["ο"] = "o", ["υ"] = "u", ["ω"] = "o" .. macron, -- Consonants ["β"] = "b", ["γ"] = "g", ["δ"] = "d", ["ζ"] = "z", ["θ"] = "th", ["κ"] = "k", ["λ"] = "l", ["μ"] = "m", ["ν"] = "n", ["ξ"] = "x", ["π"] = "p", ["ρ"] = "r", ["σ"] = "s", ["ς"] = "s", ["τ"] = "t", ["φ"] = "ph", ["χ"] = "kh", ["ψ"] = "ps", -- Archaic letters ["ϝ"] = "w", ["ϻ"] = "ś", ["ϙ"] = "q", ["ϡ"] = "š", ["ͷ"] = "v", -- Incorrect characters: see [[Wiktionary:About Ancient Greek#Miscellaneous]]. -- These are tracked by [[Module:script utilities]]. ["ϐ"] = "b", ["ϑ"] = "th", ["ϰ"] = "k", ["ϱ"] = "r", ["ϲ"] = "s", ["ϕ"] = "ph", -- Diacritics -- unchanged: macron, diaeresis, grave, acute [breve] = '', [smooth] = '', [rough] = '', [circumflex] = hat, [subscript] = 'i', } function export.tr(text, lang, sc) if text == '῾' then return 'h' end --[[ Replace semicolon or Greek question mark with regular question mark, except after an ASCII alphanumeric character (to avoid converting semicolons in HTML entities). ]] text = ugsub(text, "([^A-Za-z0-9])[;" .. U(0x37E) .. "]", "%1?") -- Handle the middle dot. It is equivalent to semicolon or colon, but semicolon is probably more common. text = text:gsub("·", ";") local tokens = tokenize(text) --now read the tokens local output = {} for i, token in pairs(tokens) do -- Convert token to lowercase and substitute each character -- for its transliteration local translit = ulower(token):gsub(UTF8char, tt) local next_token = tokens[i + 1] if token == 'γ' and next_token and velar:find(next_token, 1, true) then -- γ before a velar should be <n> translit = 'n' elseif token == 'ρ' and tokens[i - 1] == 'ρ' then -- ρ after ρ should be <rh> translit = 'rh' elseif ufind(token, a_subscript) then -- add macron to ᾳ translit = ugsub(translit, '([aA])', '%1' .. macron) end if token:find(rough) then if ufind(token, '^[Ρρ]') then translit = translit .. 'h' else -- vowel translit = 'h' .. translit end end -- Remove macron from a vowel that has a circumflex. if ufind(translit, macron_diaeresis) then translit = translit:gsub(macron, '') end -- Capitalize first character of transliteration. if token ~= ulower(token) then translit = translit:gsub("^" .. UTF8char, uupper) end table.insert(output, translit) end output = table.concat(output) return output end return export
local ok, gfold = pcall(require, "gfold") if not ok then return end gfold.setup({ picker = { on_select = function(repo) if not repo then return end vim.cmd("cd " .. repo.path) vim.cmd("%bw!") vim.lsp.stop_client(vim.lsp.get_active_clients()) vim.cmd("e .") end }, status = { enable = false, }, cwd = vim.fn.getenv("HOME") .. "/projects", }) local wk = require "which-key" wk.register({ r = { "<cmd>lua require 'gfold'.pick_repo()<CR>", "Switch Repo" }, }, { prefix = "<leader>" })
-- https://www.codewars.com/kata/5772382d509c65de7e000982/solutions/lua
--[[-- Interactable entities that can be held in inventories. Items are objects that are contained inside of an `Inventory`, or as standalone entities if they are dropped in the world. They usually have functionality that provides more gameplay aspects to the schema. For example, the zipties in the HL2 RP schema allow a player to tie up and search a player. For an item to have an actual presence, they need to be instanced (usually with `ix.item.Instance`). Items describe the properties, while instances are a clone of these properties that can have their own unique data (e.g an ID card will have the same name but different numerical IDs). You can think of items as the class, while instances are objects of the `Item` class. ]] -- @classmod Item local ITEM = ix.meta.item or {} ITEM.__index = ITEM ITEM.name = "Undefined" ITEM.description = ITEM.description or "An item that is undefined." ITEM.id = ITEM.id or 0 ITEM.uniqueID = "undefined" --- Returns a string representation of this item. -- @realm shared -- @treturn string String representation -- @usage print(ix.item.instances[1]) -- > "item[1]" function ITEM:__tostring() return "item["..self.uniqueID.."]["..self.id.."]" end --- Returns true if this item is equal to another item. Internally, this checks item IDs. -- @realm shared -- @item other Item to compare to -- @treturn bool Whether or not this item is equal to the given item -- @usage print(ix.item.instances[1] == ix.item.instances[2]) -- > false function ITEM:__eq(other) return self:GetID() == other:GetID() end --- Returns this item's database ID. This is guaranteed to be unique. -- @realm shared -- @treturn number Unique ID of item function ITEM:GetID() return self.id end function ITEM:GetName() return (CLIENT and L(self.name) or self.name) end function ITEM:GetDescription() if (!self.description) then return "ERROR" end return L(self.description or "noDesc") end function ITEM:GetModel() return self.model end function ITEM:GetSkin() return self.skin or 0 end function ITEM:GetMaterial() return nil end -- returns the ID of the owning character if there is one function ITEM:GetCharacterID() return self.characterID end -- returns the steamid64 of the owning player if there is one function ITEM:GetPlayerID() return self.playerID end -- Dev Buddy. You don't have to print the item data with PrintData(); function ITEM:Print(detail) if (detail == true) then print(Format("%s[%s]: >> [%s](%s,%s)", self.uniqueID, self.id, self.owner, self.gridX, self.gridY)) else print(Format("%s[%s]", self.uniqueID, self.id)) end end -- Dev Buddy, You don't have to make another function to print the item Data. function ITEM:PrintData() self:Print(true) print("ITEM DATA:") for k, v in pairs(self.data) do print(Format("[%s] = %s", k, v)) end end function ITEM:Call(method, client, entity, ...) local oldPlayer, oldEntity = self.player, self.entity self.player = client or self.player self.entity = entity or self.entity if (type(self[method]) == "function") then local results = {self[method](self, ...)} self.player = nil self.entity = nil return unpack(results) end self.player = oldPlayer self.entity = oldEntity end function ITEM:GetOwner() local inventory = ix.item.inventories[self.invID] if (inventory) then return inventory.GetOwner and inventory:GetOwner() end local id = self:GetID() for _, v in ipairs(player.GetAll()) do local character = v:GetCharacter() if (character and character:GetInventory():GetItemByID(id)) then return v end end end function ITEM:SetData(key, value, receivers, noSave, noCheckEntity) self.data = self.data or {} self.data[key] = value if (SERVER) then if (!noCheckEntity) then local ent = self:GetEntity() if (IsValid(ent)) then local data = ent:GetNetVar("data", {}) data[key] = value ent:SetNetVar("data", data) end end end if (receivers != false and (receivers or self:GetOwner())) then net.Start("ixInventoryData") net.WriteUInt(self:GetID(), 32) net.WriteString(key) net.WriteType(value) net.Send(receivers or self:GetOwner()) end if (!noSave and ix.db) then local query = mysql:Update("ix_items") query:Update("data", util.TableToJSON(self.data)) query:Where("item_id", self:GetID()) query:Execute() end end function ITEM:GetData(key, default) self.data = self.data or {} if (self.data) then if (key == true) then return self.data end local value = self.data[key] if (value != nil) then return value elseif (IsValid(self.entity)) then local data = self.entity:GetNetVar("data", {}) value = data[key] if (value != nil) then return value end end else self.data = {} end if (default != nil) then return default end return end function ITEM:Hook(name, func) if (name) then self.hooks[name] = func end end function ITEM:PostHook(name, func) if (name) then self.postHooks[name] = func end end function ITEM:Remove(bNoReplication, bNoDelete) local inv = ix.item.inventories[self.invID] if (self.invID > 0 and inv) then local failed = false for x = self.gridX, self.gridX + (self.width - 1) do if (inv.slots[x]) then for y = self.gridY, self.gridY + (self.height - 1) do local item = inv.slots[x][y] if (item and item.id == self.id) then inv.slots[x][y] = nil else failed = true end end end end if (failed) then local items = inv:GetItems() inv.slots = {} for _, v in pairs(items) do if (v.invID == inv:GetID()) then for x = self.gridX, self.gridX + (self.width - 1) do for y = self.gridY, self.gridY + (self.height - 1) do inv.slots[x][y] = v.id end end end end if (IsValid(inv.owner) and inv.owner:IsPlayer()) then inv:Sync(inv.owner, true) end return false end else -- @todo definition probably isn't needed inv = ix.item.inventories[self.invID] if (inv) then ix.item.inventories[self.invID][self.id] = nil end end if (SERVER and !bNoReplication) then local entity = self:GetEntity() if (IsValid(entity)) then entity:Remove() end local receivers = inv.GetReceivers and inv:GetReceivers() if (self.invID != 0 and istable(receivers)) then net.Start("ixInventoryRemove") net.WriteUInt(self.id, 32) net.WriteUInt(self.invID, 32) net.Send(receivers) end if (!bNoDelete) then local item = ix.item.instances[self.id] if (item and item.OnRemoved) then item:OnRemoved() end local query = mysql:Delete("ix_items") query:Where("item_id", self.id) query:Execute() ix.item.instances[self.id] = nil end end return true end if (SERVER) then function ITEM:GetEntity() local id = self:GetID() for _, v in ipairs(ents.FindByClass("ix_item")) do if (v.ixItemID == id) then return v end end end -- Spawn an item entity based off the item table. function ITEM:Spawn(position, angles) -- Check if the item has been created before. if (ix.item.instances[self.id]) then local client -- Spawn the actual item entity. local entity = ents.Create("ix_item") entity:Spawn() entity:SetAngles(angles or Angle(0, 0, 0)) -- Make the item represent this item. entity:SetItem(self.id) -- If the first argument is a player, then we will find a position to drop -- the item based off their aim. if (type(position) == "Player") then client = position position = position:GetItemDropPos(entity) end entity:SetPos(position) if (IsValid(client)) then entity.ixSteamID = client:SteamID() entity.ixCharID = client:GetCharacter():GetID() end -- Return the newly created entity. return entity end end -- Transfers an item to a specific inventory. function ITEM:Transfer(invID, x, y, client, noReplication, isLogical) invID = invID or 0 if (self.invID == invID) then return false, "same inv" end local inventory = ix.item.inventories[invID] local curInv = ix.item.inventories[self.invID or 0] if (curInv and !IsValid(client)) then client = curInv.GetOwner and curInv:GetOwner() or nil end -- check if this item doesn't belong to another one of this player's characters local itemPlayerID = self:GetPlayerID() local itemCharacterID = self:GetCharacterID() if (!self.bAllowMultiCharacterInteraction and IsValid(client) and client:GetCharacter()) then local playerID = client:SteamID64() local characterID = client:GetCharacter():GetID() if (itemPlayerID and itemCharacterID) then if (itemPlayerID == playerID and itemCharacterID != characterID) then return false, "itemOwned" end else self.characterID = characterID self.playerID = playerID local query = mysql:Update("ix_items") query:Update("character_id", characterID) query:Update("player_id", playerID) query:Where("item_id", self:GetID()) query:Execute() end end if (hook.Run("CanTransferItem", self, curInv, inventory) == false) then return false, "notAllowed" end local authorized = false if (inventory and inventory.OnAuthorizeTransfer and inventory:OnAuthorizeTransfer(client, curInv, self)) then authorized = true end if (!authorized and self.CanTransfer and self:CanTransfer(curInv, inventory) == false) then return false, "notAllowed" end if (curInv) then if (invID and invID > 0 and inventory) then local targetInv = inventory local bagInv if (!x and !y) then x, y, bagInv = inventory:FindEmptySlot(self.width, self.height) end if (bagInv) then targetInv = bagInv end if (!x or !y) then return false, "noFit" end local prevID = self.invID local status, result = targetInv:Add(self.id, nil, nil, x, y, noReplication) if (status) then if (self.invID > 0 and prevID != 0) then -- we are transferring this item from one inventory to another curInv:Remove(self.id, false, true, true) self.invID = invID if (self.OnTransferred) then self:OnTransferred(curInv, inventory) end hook.Run("OnItemTransferred", self, curInv, inventory) return true elseif (self.invID > 0 and prevID == 0) then -- we are transferring this item from the world to an inventory ix.item.inventories[0][self.id] = nil if (self.OnTransferred) then self:OnTransferred(curInv, inventory) end hook.Run("OnItemTransferred", self, curInv, inventory) return true end else return false, result end elseif (IsValid(client)) then -- we are transferring this item from an inventory to the world self.invID = 0 curInv:Remove(self.id, false, true) local query = mysql:Update("ix_items") query:Update("inventory_id", 0) query:Where("item_id", self.id) query:Execute() inventory = ix.item.inventories[0] inventory[self:GetID()] = self if (self.OnTransferred) then self:OnTransferred(curInv, inventory) end hook.Run("OnItemTransferred", self, curInv, inventory) if (!isLogical) then return self:Spawn(client) end return true else return false, "noOwner" end else return false, "invalidInventory" end end end ix.meta.item = ITEM
---@meta --=== file === ---@class file file = {} ---@class fd local fd = {} ---Change current directory (and drive). This will be used\ ---when no drive/directory is prepended to filenames. ---@param dir string|'"/FLASH"'|'"/SD0"'|'"/SD1"' @directory name ---@return boolean function file.chdir(dir) end ---Determines whether the specified file exists. ---@param filename string @file to check ---@return boolean @"`true` of the file exists (even if 0 bytes in size), \n and `false` if it does not exist" function file.exists(filename) end ---Format the file system. Completely erases any\ ---existing file system and writes a new one. ---@return nil function file.format() end ---Returns the flash address and physical\ ---size of the file system area, in bytes. ---@return number flash_address ---@return number size function file.fscfg() end ---Return size information for the file system.\ ---The unit is Byte for SPIFFS and kByte for FatFS. ---@return number remaining ---@return number used ---@return number total function file.fsinfo() end ---Lists all files in the file system. ---@return table @"a lua table which contains \n the `{file name: file size}` pairs" function file.list() end ---Registers callback functions. ---@param event string|'"rtc"' @"Trigger events are: **rtc** deliver current date & time to the file system. \n Function is expected to return a table containing the fields **year, mon, day, hour, min, sec** \n of current date and time. Not supported for internal flash." ---@param callback fun() @function. Unregisters the callback if function() is omitted. ---@return nil function file.on(event, callback) end ---Opens a file for access, potentially creating it (for write modes).\ ---When done with the file, it must be closed using `file.close()`. ---@param filename string @file to be opened, directories are not supported ---@param mode string @mode ---|>' "r"' #read mode ---| ' "w"' #write mode ---| ' "a"' #append mode ---| ' "r+"' #update mode, all previous data is preserved ---| ' "w+"' #update mode, all previous data is erased ---| ' "a+"' #append update mode, previous data is preserved, writing is only allowed at the end of file ---@return fd fileObj @file object if file opened ok. `nil` if file not opened, or not exists (read modes). function file.open(filename, mode) end ---Remove a file from the file system.\ ---The file must not be currently open. ---@param filename string @file to remove ---@return nil function file.remove(filename) end ---Renames a file. If a file is currently open, it will be closed first. ---@param oldname string @old file name ---@param newname string @new file name ---@return boolean function file.rename(oldname, newname) end ---Closes the open file, if any. ---@return nil function file.close() end ---Closes the open file, if any. ---@return nil function fd:close() end ---Flushes any pending writes to the file system,\ ---ensuring no data is lost on a restart. Closing\ ---the open file using `file.close() / fd:close()`\ ---performs an implicit flush as well. ---@return nil function file.flush() end ---Flushes any pending writes to the file system,\ ---ensuring no data is lost on a restart. Closing\ ---the open file using `file.close() / fd:close()`\ ---performs an implicit flush as well. ---@return nil function fd:flush() end ---Read content from the open file. ---@param n_or_char? integer @(optional): --- - if nothing passed in, then read up to FILE_READ_CHUNK bytes\ ---or the entire file (whichever is smaller). --- - if passed a number n, then read up to n bytes or the entire file\ ---(whichever is smaller). --- - if passed a string containing the single character `char`,\ ---then read until char appears next in the file,\ ---FILE_READ_CHUNK bytes have been read, or EOF is reached. ---@return string|nil @File content as a string, or `nil` when EOF function file.read(n_or_char) end ---Read content from the open file. ---@param n_or_char? integer @(optional): --- - if nothing passed in, then read up to FILE_READ_CHUNK bytes\ ---or the entire file (whichever is smaller). --- - if passed a number `n`, then read up to *n* bytes or the entire file\ ---(whichever is smaller). --- - if passed a string containing the single character `char`,\ ---then read until char appears next in the file,\ ---FILE_READ_CHUNK bytes have been read, or EOF is reached. ---@return string|nil @File content as a string, or `nil` when EOF function fd:read(n_or_char) end ---Read the next line from the open file. Lines are defined as zero\ ---or more bytes ending with a EOL ('\n') byte. ---@return string|nil @File content in string, line by line, including EOL('\n'). ---Return `nil` when EOF. function file.readline() end ---Read the next line from the open file. Lines are defined as zero\ ---or more bytes ending with a EOL ('\n') byte. ---@return string|nil @File content in string, line by line, including EOL('\n'). ---Return `nil` when EOF. function fd:readline() end ---@alias seekwhence32_f string ---| '"set"' #Base is position 0 (beginning of the file) ---|>'"cur"' #Base is current position ---| '"end"' #Base is end of file ---Sets and gets the file position, measured from the beginning of the file,\ ---to the position given by offset plus a base specified by the string whence.\ ---If no parameters are given, the function simply returns the current file offset. ---@param whence? seekwhence32_f @(optional) 'set' | 'cur' | 'end' ---@param offset? integer @(optional) default 0 ---@return integer @the resulting file position, or `nil` on error function file.seek(whence, offset) end ---Sets and gets the file position, measured from the beginning of the file,\ ---to the position given by offset plus a base specified by the string whence.\ ---If no parameters are given, the function simply returns the current file offset. ---@param whence? seekwhence32_f @(optional) 'set' | 'cur' | 'end' ---@param offset? integer @(optional) default 0 ---@return integer @the resulting file position, or `nil` on error function fd:seek(whence, offset) end ---Write a string to the open file. ---@param str string @content to be write to file ---@return boolean|nil @`true` if write ok, `nil` on error function file.write(str) end ---Write a string to the open file. ---@param str string @content to be write to file ---@return boolean|nil @`true` if write ok, `nil` on error function fd:write(str) end ---Write a string to the open file and append '\n' at the end. ---@param str string @content to be write to file ---@return boolean|nil @`true` if write ok, `nil` on error function file.writeline(str) end ---Write a string to the open file and append '\n' at the end. ---@param str string @content to be write to file ---@return boolean|nil @`true` if write ok, `nil` on error function fd:writeline(str) end
function love.timer.getTime() return os.time() end function love.timer.getDelta() return dt end
--[[ APP_easing Display the various easing/interpolation functions ]] local vkeys = require("vkeys") local GraphicGroup = require("GraphicGroup") local functor = require("functor") local easing = require("easing") local radians = math.rad local maths = require("maths") local map = maths.map local EasingGraph = require("GEasingGraph") local BPanel = require("BPage") local BView = require("BView") local sliding = require("sliding") local easings = { {row = 1, column = 1, title = "easeLinear", interpolator = easing.easeLinear}; {row = 2, column = 1, title = "easeInQuad", interpolator = easing.easeInQuad}; {row = 2, column = 2, title = "easeOutQuad", interpolator = easing.easeOutQuad}; {row = 2, column = 3, title = "easeInOutQuad", interpolator = easing.easeInOutQuad}; {row = 3, column = 1, title = "easeInCubic", interpolator = easing.easeInCubic}; {row = 3, column = 2, title = "easeOutCubic", interpolator = easing.easeOutCubic}; {row = 3, column = 3, title = "easeInOutCubic", interpolator = easing.easeInOutCubic}; {row = 4, column = 1, title = "easeInQuart", interpolator = easing.easeInQuart}; {row = 4, column = 2, title = "easeOutQuart", interpolator = easing.easeOutQuart}; {row = 4, column = 3, title = "easeInOutQuart", interpolator = easing.easeInOutQuart}; {row = 5, column = 1, title = "easeInQuint", interpolator = easing.easeInQuint}; {row = 5, column = 2, title = "easeOutQuint", interpolator = easing.easeOutQuint}; {row = 5, column = 3, title = "easeInOutQuint", interpolator = easing.easeInOutQuint}; {row = 6, column = 1, title = "easeInSine", interpolator = easing.easeInSine}; {row = 6, column = 2, title = "easeOutSine", interpolator = easing.easeOutSine}; {row = 6, column = 3, title = "easeInOutSine", interpolator = easing.easeInOutSine}; {row = 7, column = 1, title = "easeInExpo", interpolator = easing.easeInExpo}; {row = 7, column = 2, title = "easeOutExpo", interpolator = easing.easeOutExpo}; {row = 7, column = 3, title = "easeInOutExpo", interpolator = easing.easeInOutExpo}; {row = 8, column = 1, title = "easeInCirc", interpolator = easing.easeInCirc}; {row = 8, column = 2, title = "easeOutCirc", interpolator = easing.easeOutCirc}; {row = 8, column = 3, title = "easeInOutCirc", interpolator = easing.easeInOutCirc}; } function app(params) local winparams = {frame = {x=0,y=0, width = 800, height = 1024}} local win1 = WMCreateWindow(winparams) function win1.drawBackground(self, ctx) ctx:fill(255); ctx:fillAll() end local panel = BPanel:new({frame={x=0, y=0,width=0,height=0}}) -- create the easing graphics local xmargin = 10; local ymargin = 10; local cellWidth = 200; local cellHeight = 240; local widthGap = 40; local heightGap = 40; for _, entry in ipairs(easings) do local x = xmargin + (entry.column-1) * (cellWidth + widthGap) local y = ymargin + (entry.row-1) * (cellHeight + heightGap) entry.frame = {x=x, y=y, width = cellWidth, height=cellHeight} --print(x,y,entry.frame.width, entry.frame.height) local easing = EasingGraph:new(entry) panel:addChild(easing) end local psize = panel:getPreferredSize() --print("Panel Size: ", psize.width, psize.height) local view = BView:new({ frame={x=8,y=8, width = 700, height = 800}, page = panel }) local boxSlider = sliding.createSlider({ startPoint = {x=view.frame.x+view.frame.width+10,y=view.frame.y}; endPoint = {x=view.frame.x+view.frame.width+10, y=view.frame.y+view.frame.height}; thickness = 24; thumb = { length = 60; thumbColor = 0x70; } }) -- connect slider to viewbox on(boxSlider, functor(view.handleVerticalPositionChange, view)) win1:add(view) win1:add(boxSlider) win1:show() ---[[ while true do win1:draw() yield(); end --]] local function drawproc() win1:draw() end --periodic(1000/20, drawproc) end require("windowapp") return app
-- not a test, but a helper local function local function is_truthy(condition) if condition then return true end return false end function test_true_is_truthy() assert_equal(true, is_truthy(true)) end function test_false_is_not_truthy() assert_equal(false, is_truthy(false)) end function test_nil_is_also_not_truthy() assert_equal(false, is_truthy(nil)) end function test_everything_else_is_truthy() assert_equal(true, is_truthy(1)) assert_equal(true, is_truthy(0)) assert_equal(true, is_truthy({'tables'})) assert_equal(true, is_truthy({})) assert_equal(true, is_truthy("Strings")) assert_equal(true, is_truthy("")) assert_equal(true, is_truthy(function() return 'functions too' end)) end -- Bonus note: -- Is it better to use -- if obj == nil then -- or -- if obj then -- Why?
fightcondition = createConditionObject(CONDITION_INFIGHT) setConditionParam(fightcondition, CONDITION_PARAM_TICKS, 5000) ordercondition = createConditionObject(CONDITION_EXHAUST) setConditionParam(ordercondition, CONDITION_PARAM_TICKS, 500) movecondition = createConditionObject(CONDITION_EXHAUST) setConditionParam(movecondition, CONDITION_PARAM_TICKS, 250) confusioncondition = createConditionObject(CONDITION_DRUNK) setConditionParam(confusioncondition, CONDITION_PARAM_TICKS, 1000) invisiblecondition = createConditionObject(CONDITION_INVISIBLE) setConditionParam(invisiblecondition, CONDITION_PARAM_TICKS, -1) bebo = createConditionObject(CONDITION_DRUNK) setConditionParam(bebo, CONDITION_PARAM_TICKS, -1)
module ('mapgenerator', package.seeall) do require 'map.tileset' require 'map.tiletype' require 'map.map' require 'map.generator.grid' require 'map.generator.procedural.cave' local tilesets = {} function get_tileset() if not tilesets.default then tilesets.default = tileset:new { types = { ["I"] = tiletype:new { imgpath = 'data/tile/ice.png', floor = true } } } end return tilesets.default end local function generate_map_with_grid(grid) return map:new { tileset = grid.tileset, width = grid.width, height = grid.height, tiles = grid } end local function find_grounded_open_spots(map) local spots = {} for j=1,map.height-2 do for i=1,map.width-1 do if not map:get_tile_floor(j ,i) and not map:get_tile_floor(j ,i+1) and not map:get_tile_floor(j+1,i) and not map:get_tile_floor(j+1,i+1) and map:get_tile_floor(j+2,i) and map:get_tile_floor(j+2,i+1) then table.insert(spots, {j=j,i=i}) end end end return spots end local function get_random_position(spots, debug) local i = (debug and 1) or love.math.random(#spots) local result = spots[i] table.remove(spots, i) return {result.i+1, result.j+1} end function random_map(debug) local blocks = { width = 4, height = 4, tileset = get_tileset(), total_rarity = 0, { ' ', ' I ', ' ', ' ', rarity = 1 }, { ' ', ' I ', ' ', ' ', rarity = 1 }, { ' ', ' ', 'IIII', 'IIII', rarity = 2 }, { ' ', ' III', ' III', ' ', rarity = 2 }, } for _, block in ipairs(blocks) do blocks.total_rarity = blocks.total_rarity + block.rarity end local blocks_grid = random_grid_from_blocks(26, 18, blocks) local cavegrid = mapgenerator.generate_cave_from_grid(blocks_grid) local m = generate_map_with_grid(cavegrid) local valid_spots = find_grounded_open_spots(m) m.locations.playerstart = get_random_position(valid_spots, debug) table.insert(m.things, { type = "door", position = get_random_position(valid_spots, debug) }) table.insert(m.things, { type = "npc_cain", position = get_random_position(valid_spots, debug) }) table.insert(m.things, { type = "vendor", position = get_random_position(valid_spots, debug) }) for i=1,(debug and 1 or 10) do table.insert(m.things, { type = "drillbeast", position = get_random_position(valid_spots, debug) }) end for i=1,5 do table.insert(m.things, { type = "ironaxe", position = get_random_position(valid_spots, debug) }) table.insert(m.things, { type = "leatherarmor", position = get_random_position(valid_spots, debug) }) end return m end -- A map file is a lua script that should return a table that will be used to construct a map object. -- This lua script is allowed to construct tilesets and tiletypes, and nothing more. function from_file(path) local ok, chunk = pcall(love.filesystem.load, path) if not ok then print(chunk) return nil, chunk end setfenv(chunk, { tileset = tileset, tiletype = tiletype }) local ok, result = pcall(chunk) if not ok then print(result) return nil, result end return map:new(result) end end
if game.SinglePlayer() then if SERVER then util.AddNetworkString('pac_footstep') hook.Add("PlayerFootstep", "footstep_fix", function(ply, pos, _, snd, vol) net.Start("pac_footstep") net.WriteEntity(ply) net.WriteVector(pos) net.WriteString(snd) net.WriteFloat(vol) net.Broadcast() end) end if CLIENT then net.Receive("pac_footstep", function(len) local ply = net.ReadEntity() local pos = net.ReadVector() local snd = net.ReadString() local vol = net.ReadFloat() if ply:IsValid() then hook.Run("pac_PlayerFootstep", ply, pos, snd, vol) end end) end else hook.Add("PlayerFootstep", "footstep_fix", function(ply, pos, _, snd, vol) return hook.Run("pac_PlayerFootstep", ply, pos, snd, vol) end) end
if not turtle then error( "Cannot load turtle API on computer", 2 ) end native = turtle.native or turtle local function addCraftMethod( object ) if peripheral.getType( "left" ) == "workbench" then object.craft = function( ... ) return peripheral.call( "left", "craft", ... ) end elseif peripheral.getType( "right" ) == "workbench" then object.craft = function( ... ) return peripheral.call( "right", "craft", ... ) end else object.craft = nil end end -- Put commands into environment table local env = _ENV for k,v in pairs( native ) do if k == "equipLeft" or k == "equipRight" then env[k] = function( ... ) local result, err = v( ... ) addCraftMethod( turtle ) return result, err end else env[k] = v end end addCraftMethod( env )
local Factory = require("support.factory") local Ability = require("invokation.dota2.Ability") Factory.define("ability", function(attributes) return Ability(Factory.create("dota_ability", attributes)) end)
--- Free functions used to create and prepare some font objects. -- -- 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. -- -- [ MIT license: http://www.opensource.org/licenses/mit-license.php ] -- --- Each .ttf / .ttc file may have more than one font. Each font has a sequential -- index number starting from 1. Call this function to get the font offset for -- a given index. A regular .ttf file will only define one font that will always be -- at offset 0, so it will return 0 for index 1, and -1 for all other indices. -- You can just skip this step if you know it's that kind of font. -- @function GetFontOffsetForIndex -- @tparam Bytes|string bytes Font data, e.g. as read from a file. Data is assumed to be valid. -- @uint[opt=1] index Font index, &ge; 1. -- @treturn int Offset into _bytes_, or -1 if _index_ is out of range. -- @see NewFont --- Given an offset into the file that defines a font, this function builds -- the necessary cached info for the rest of the system. You don't need to -- do anything special to free it, because the contents are pure value data -- with no additional data structures. -- @function NewFont -- @tparam Bytes|string bytes Font data, typically the contents of a file. -- @int[opt=0] offset Offset into _bytes_, cf. @{GetFontOffsetForIndex}. -- @treturn ?|FontInfo|nil On success, a new @{FontInfo} instance. Otherwise, **nil**. --- Initializes a packing context. Future calls using this context will pack -- characters into its 1-channel, _width_ x _height_ @{Packing:GetBitmap|bitmap}. -- -- TODO: options for bitmap... -- @function NewPacking -- @uint width Packing width... -- @uint height ...and height. -- @uint[opt=0] stride_in_bytes Distance from one row to the next (or 0 to mean they -- are packed tightly together). -- @uint[opt=1] packing Amount of padding to leave between each character (normally -- you want 1 for bitmaps you'll use as textures with bilinear filtering). -- @treturn ?|Packing|nil On success, a new @{Packing} instance. Otherwise, **nil**. --- Encode a size so that certain methods associate it with @{FontInfo:ScaleForMappingEmToPixels}. -- @function PointSize -- @number size Font size, &gt; 0. -- @treturn string Encoded size.
local entity_list = require("entity-list") function has_value(tab, val) for index, value in ipairs(tab) do if value == val then return true end end return false end function place_off_grid(dataType) for i, e in pairs(data.raw[dataType]) do if not e.flags then e.flags = {} end local flags = e.flags if not has_value(flags, "placeable-off-grid") then table.insert(flags, "placeable-off-grid") e.flags = flags end end end for i, e in pairs(entity_list) do if not settings.startup["pof-disable-"..e].value then place_off_grid(e) end end
-- Generated By protoc-gen-lua Do not Edit local protobuf = require( "depends/protobuf/protobuf" ) local __COMMON_ENUMS_PB = require( "pb/__common_enums_pb" ) local COMMON_BASE_PB = require( "pb/common_base_pb" ) --module('login_pb') local login_pb = {} local LOGINREQUEST = protobuf.Descriptor(); local LOGINREQUEST_USER_ID_FIELD = protobuf.FieldDescriptor(); local LOGINREQUEST_CHANNEL_UID_FIELD = protobuf.FieldDescriptor(); local LOGINRESPONSE = protobuf.Descriptor(); local LOGINRESPONSE_USER_ID_FIELD = protobuf.FieldDescriptor(); local LOGINRESPONSE_PLAYER_FIELD = protobuf.FieldDescriptor(); local CREATECHARACTERREQUEST = protobuf.Descriptor(); local CREATECHARACTERREQUEST_USER_ID_FIELD = protobuf.FieldDescriptor(); local CREATECHARACTERREQUEST_PLAYER_NAME_FIELD = protobuf.FieldDescriptor(); local CREATECHARACTERRESPONSE = protobuf.Descriptor(); local CREATECHARACTERRESPONSE_USER_ID_FIELD = protobuf.FieldDescriptor(); local LOGOUTRESPONSE = protobuf.Descriptor(); local LOGOUTRESPONSE_USER_ID_FIELD = protobuf.FieldDescriptor(); local HEARTBEAT = protobuf.Descriptor(); local HEARTBEAT_PLAYER_ID_FIELD = protobuf.FieldDescriptor(); LOGINREQUEST_USER_ID_FIELD.name = "user_id" LOGINREQUEST_USER_ID_FIELD.full_name = ".my_project.LoginRequest.user_id" LOGINREQUEST_USER_ID_FIELD.number = 1 LOGINREQUEST_USER_ID_FIELD.index = 0 LOGINREQUEST_USER_ID_FIELD.label = 2 LOGINREQUEST_USER_ID_FIELD.has_default_value = false LOGINREQUEST_USER_ID_FIELD.default_value = 0 LOGINREQUEST_USER_ID_FIELD.type = 5 LOGINREQUEST_USER_ID_FIELD.cpp_type = 1 LOGINREQUEST_CHANNEL_UID_FIELD.name = "channel_uid" LOGINREQUEST_CHANNEL_UID_FIELD.full_name = ".my_project.LoginRequest.channel_uid" LOGINREQUEST_CHANNEL_UID_FIELD.number = 2 LOGINREQUEST_CHANNEL_UID_FIELD.index = 1 LOGINREQUEST_CHANNEL_UID_FIELD.label = 2 LOGINREQUEST_CHANNEL_UID_FIELD.has_default_value = false LOGINREQUEST_CHANNEL_UID_FIELD.default_value = "" LOGINREQUEST_CHANNEL_UID_FIELD.type = 9 LOGINREQUEST_CHANNEL_UID_FIELD.cpp_type = 9 LOGINREQUEST.name = "LoginRequest" LOGINREQUEST.full_name = ".my_project.LoginRequest" LOGINREQUEST.nested_types = {} LOGINREQUEST.enum_types = {} LOGINREQUEST.fields = {LOGINREQUEST_USER_ID_FIELD, LOGINREQUEST_CHANNEL_UID_FIELD} LOGINREQUEST.is_extendable = false LOGINREQUEST.extensions = {} LOGINRESPONSE_USER_ID_FIELD.name = "user_id" LOGINRESPONSE_USER_ID_FIELD.full_name = ".my_project.LoginResponse.user_id" LOGINRESPONSE_USER_ID_FIELD.number = 1 LOGINRESPONSE_USER_ID_FIELD.index = 0 LOGINRESPONSE_USER_ID_FIELD.label = 2 LOGINRESPONSE_USER_ID_FIELD.has_default_value = false LOGINRESPONSE_USER_ID_FIELD.default_value = 0 LOGINRESPONSE_USER_ID_FIELD.type = 5 LOGINRESPONSE_USER_ID_FIELD.cpp_type = 1 LOGINRESPONSE_PLAYER_FIELD.name = "player" LOGINRESPONSE_PLAYER_FIELD.full_name = ".my_project.LoginResponse.player" LOGINRESPONSE_PLAYER_FIELD.number = 11 LOGINRESPONSE_PLAYER_FIELD.index = 1 LOGINRESPONSE_PLAYER_FIELD.label = 1 LOGINRESPONSE_PLAYER_FIELD.has_default_value = false LOGINRESPONSE_PLAYER_FIELD.default_value = nil LOGINRESPONSE_PLAYER_FIELD.message_type = COMMON_BASE_PB._PLAYER LOGINRESPONSE_PLAYER_FIELD.type = 11 LOGINRESPONSE_PLAYER_FIELD.cpp_type = 10 LOGINRESPONSE.name = "LoginResponse" LOGINRESPONSE.full_name = ".my_project.LoginResponse" LOGINRESPONSE.nested_types = {} LOGINRESPONSE.enum_types = {} LOGINRESPONSE.fields = {LOGINRESPONSE_USER_ID_FIELD, LOGINRESPONSE_PLAYER_FIELD} LOGINRESPONSE.is_extendable = false LOGINRESPONSE.extensions = {} CREATECHARACTERREQUEST_USER_ID_FIELD.name = "user_id" CREATECHARACTERREQUEST_USER_ID_FIELD.full_name = ".my_project.CreateCharacterRequest.user_id" CREATECHARACTERREQUEST_USER_ID_FIELD.number = 1 CREATECHARACTERREQUEST_USER_ID_FIELD.index = 0 CREATECHARACTERREQUEST_USER_ID_FIELD.label = 2 CREATECHARACTERREQUEST_USER_ID_FIELD.has_default_value = false CREATECHARACTERREQUEST_USER_ID_FIELD.default_value = 0 CREATECHARACTERREQUEST_USER_ID_FIELD.type = 5 CREATECHARACTERREQUEST_USER_ID_FIELD.cpp_type = 1 CREATECHARACTERREQUEST_PLAYER_NAME_FIELD.name = "player_name" CREATECHARACTERREQUEST_PLAYER_NAME_FIELD.full_name = ".my_project.CreateCharacterRequest.player_name" CREATECHARACTERREQUEST_PLAYER_NAME_FIELD.number = 2 CREATECHARACTERREQUEST_PLAYER_NAME_FIELD.index = 1 CREATECHARACTERREQUEST_PLAYER_NAME_FIELD.label = 2 CREATECHARACTERREQUEST_PLAYER_NAME_FIELD.has_default_value = false CREATECHARACTERREQUEST_PLAYER_NAME_FIELD.default_value = "" CREATECHARACTERREQUEST_PLAYER_NAME_FIELD.type = 9 CREATECHARACTERREQUEST_PLAYER_NAME_FIELD.cpp_type = 9 CREATECHARACTERREQUEST.name = "CreateCharacterRequest" CREATECHARACTERREQUEST.full_name = ".my_project.CreateCharacterRequest" CREATECHARACTERREQUEST.nested_types = {} CREATECHARACTERREQUEST.enum_types = {} CREATECHARACTERREQUEST.fields = {CREATECHARACTERREQUEST_USER_ID_FIELD, CREATECHARACTERREQUEST_PLAYER_NAME_FIELD} CREATECHARACTERREQUEST.is_extendable = false CREATECHARACTERREQUEST.extensions = {} CREATECHARACTERRESPONSE_USER_ID_FIELD.name = "user_id" CREATECHARACTERRESPONSE_USER_ID_FIELD.full_name = ".my_project.CreateCharacterResponse.user_id" CREATECHARACTERRESPONSE_USER_ID_FIELD.number = 1 CREATECHARACTERRESPONSE_USER_ID_FIELD.index = 0 CREATECHARACTERRESPONSE_USER_ID_FIELD.label = 2 CREATECHARACTERRESPONSE_USER_ID_FIELD.has_default_value = false CREATECHARACTERRESPONSE_USER_ID_FIELD.default_value = 0 CREATECHARACTERRESPONSE_USER_ID_FIELD.type = 5 CREATECHARACTERRESPONSE_USER_ID_FIELD.cpp_type = 1 CREATECHARACTERRESPONSE.name = "CreateCharacterResponse" CREATECHARACTERRESPONSE.full_name = ".my_project.CreateCharacterResponse" CREATECHARACTERRESPONSE.nested_types = {} CREATECHARACTERRESPONSE.enum_types = {} CREATECHARACTERRESPONSE.fields = {CREATECHARACTERRESPONSE_USER_ID_FIELD} CREATECHARACTERRESPONSE.is_extendable = false CREATECHARACTERRESPONSE.extensions = {} LOGOUTRESPONSE_USER_ID_FIELD.name = "user_id" LOGOUTRESPONSE_USER_ID_FIELD.full_name = ".my_project.LogoutResponse.user_id" LOGOUTRESPONSE_USER_ID_FIELD.number = 1 LOGOUTRESPONSE_USER_ID_FIELD.index = 0 LOGOUTRESPONSE_USER_ID_FIELD.label = 2 LOGOUTRESPONSE_USER_ID_FIELD.has_default_value = false LOGOUTRESPONSE_USER_ID_FIELD.default_value = 0 LOGOUTRESPONSE_USER_ID_FIELD.type = 5 LOGOUTRESPONSE_USER_ID_FIELD.cpp_type = 1 LOGOUTRESPONSE.name = "LogoutResponse" LOGOUTRESPONSE.full_name = ".my_project.LogoutResponse" LOGOUTRESPONSE.nested_types = {} LOGOUTRESPONSE.enum_types = {} LOGOUTRESPONSE.fields = {LOGOUTRESPONSE_USER_ID_FIELD} LOGOUTRESPONSE.is_extendable = false LOGOUTRESPONSE.extensions = {} HEARTBEAT_PLAYER_ID_FIELD.name = "player_id" HEARTBEAT_PLAYER_ID_FIELD.full_name = ".my_project.HeartBeat.player_id" HEARTBEAT_PLAYER_ID_FIELD.number = 1 HEARTBEAT_PLAYER_ID_FIELD.index = 0 HEARTBEAT_PLAYER_ID_FIELD.label = 2 HEARTBEAT_PLAYER_ID_FIELD.has_default_value = false HEARTBEAT_PLAYER_ID_FIELD.default_value = "" HEARTBEAT_PLAYER_ID_FIELD.type = 9 HEARTBEAT_PLAYER_ID_FIELD.cpp_type = 9 HEARTBEAT.name = "HeartBeat" HEARTBEAT.full_name = ".my_project.HeartBeat" HEARTBEAT.nested_types = {} HEARTBEAT.enum_types = {} HEARTBEAT.fields = {HEARTBEAT_PLAYER_ID_FIELD} HEARTBEAT.is_extendable = false HEARTBEAT.extensions = {} CreateCharacterRequest = protobuf.Message(CREATECHARACTERREQUEST) CreateCharacterResponse = protobuf.Message(CREATECHARACTERRESPONSE) HeartBeat = protobuf.Message(HEARTBEAT) LoginRequest = protobuf.Message(LOGINREQUEST) LoginResponse = protobuf.Message(LOGINRESPONSE) LogoutResponse = protobuf.Message(LOGOUTRESPONSE) login_pb.CREATECHARACTERREQUEST = CREATECHARACTERREQUEST login_pb.CREATECHARACTERRESPONSE = CREATECHARACTERRESPONSE login_pb.CreateCharacterRequest = CreateCharacterRequest login_pb.CreateCharacterResponse = CreateCharacterResponse login_pb.HEARTBEAT = HEARTBEAT login_pb.HeartBeat = HeartBeat login_pb.LOGINREQUEST = LOGINREQUEST login_pb.LOGINRESPONSE = LOGINRESPONSE login_pb.LOGOUTRESPONSE = LOGOUTRESPONSE login_pb.LoginRequest = LoginRequest login_pb.LoginResponse = LoginResponse login_pb.LogoutResponse = LogoutResponse return login_pb
-- // Dependencies local Aiming = loadstring(game:HttpGet("https://raw.githubusercontent.com/Stefanuk12/ROBLOX/master/Universal/Aiming/GamePatches/RushPoint.lua"))() -- // Services local Workspace = game:GetService("Workspace") -- // Vars local CurrentCamera = Workspace.CurrentCamera local CFramelookAt = CFrame.lookAt -- // Hook local __index __index = hookmetamethod(game, "__index", function(t, k) -- // Make sure it is the shoot function trying to get the camera's cframe if (not checkcaller() and t == CurrentCamera and k == "CFrame" and Aiming.Check() and debug.validlevel(3) and #debug.getupvalues(3) == 11) then local Origin = __index(t, k).Position local Destination = Aiming.SelectedPart.Position local Modified = CFramelookAt(Origin, Destination) return Modified end -- // Return old return __index(t, k) end)
---@class i18n local i18n = ECSLoader:CreateModule("i18n") local _UseLanguage function i18n:LoadLanguageData() local locale = ExtendedCharacterStats.general.langugage if (not locale) or (locale == "auto") then locale = GetLocale() end _UseLanguage(locale) end ---@param lang string _UseLanguage = function(lang) if lang == "deDE" then i18n:UseGerman() elseif lang == "frFR" then i18n:UseFrench() else i18n:UseEnglish() end end ---@param lang string function i18n:SetLanguage(lang) _UseLanguage(lang) end ---@param key string @The specified key for the target text ---@return string @The formated text function i18n:translate(key, ...) local args = {...} for i, v in ipairs(args) do args[i] = tostring(v); end if (not i18n.texts[key]) then print("|cffff0000[ERROR]|r Missing translation for <" .. key .. "> key") return "" end return string.format(i18n.texts[key], unpack(args)) end setmetatable(i18n, {__call = function(_, ...) return i18n:translate(...) end})
local ACTIONS_PATH = ACTIONS_PATH or ({...})[1]:gsub("[%.\\/]init$", "") .. '.' return { Dispatcher = require(ACTIONS_PATH .. "dispatcher"), Task = require(ACTIONS_PATH .. "tasks") }
local function input(event) -- for update button if event.type ~= "InputEventType_Release" then if event.DeviceInput.button == "DeviceButton_left mouse button" then MESSAGEMAN:Broadcast("MouseLeftClick") elseif event.DeviceInput.button == "DeviceButton_right mouse button" then MESSAGEMAN:Broadcast("MouseRightClick") end end return false end local t = Def.ActorFrame{ OnCommand=function(self) SCREENMAN:GetTopScreen():AddInputCallback(input) end, } local frameX = THEME:GetMetric("ScreenTitleMenu","ScrollerX")-10 local frameY = THEME:GetMetric("ScreenTitleMenu","ScrollerY") t[#t+1] = LoadActor("bn.png") .. { InitCommand=function(self) self:xy(0,-23):halign(0):valign(0):diffusealpha(1):zoomto(SCREEN_WIDTH, SCREEN_HEIGHT) end } t[#t+1] = LoadActor("bgscroll1.png") .. { InitCommand=function(self) self:xy(20,0):halign(0):valign(0):texcoordvelocity(0.002,-0.01):scaletocover(0,0,capWideScale(640,1080),capWideScale(480, 1080)) end } t[#t+1] = LoadActor("bgscroll2.png") .. { InitCommand=function(self) self:xy(0,30):halign(0):valign(0):texcoordvelocity(-0.002,-0.01):scaletocover(0,0,capWideScale(640,1080),capWideScale(480, 1080)) end } t[#t+1] = LoadActor("bgscroll3.png") .. { InitCommand=function(self) self:xy(100,0):halign(0):valign(0):texcoordvelocity(0.002,-0.01):scaletocover(0,0,capWideScale(640,1080),capWideScale(480, 1080)) end } t[#t+1] = LoadActor("bgscroll.png") .. { InitCommand=function(self) self:xy(30,0):halign(0):valign(0):texcoordvelocity(0.002,-0.01):scaletocover(0,0,capWideScale(640,1080),capWideScale(480, 1080)) end } t[#t+1] = LoadFont("Common Formal") .. { InitCommand=function(self) self:xy(2,478):zoom(0.55):valign(1):halign(0) end, OnCommand=function(self) self:settext("PRESS START") end, } t[#t+1] = LoadFont("Common Formal") .. { InitCommand=function(self) self:xy(630,25):zoom(0.5):valign(1):halign(1):shadowlength(2) end, OnCommand=function(self) self:settext("Etterna "..GAMESTATE:GetEtternaVersion()):diffuse(color("#999999")) end, } t[#t+1] = LoadFont("Common Formal") .. { InitCommand=function(self) self:xy(4,25):zoom(0.5):valign(1):halign(0):shadowlength(2) end, OnCommand=function(self) self:settextf("%i songs in %i groups", SONGMAN:GetNumSongs(), SONGMAN:GetNumSongGroups()):diffuse(color("#999999")) end, } -- lazy game update button -mina local gameneedsupdating = false local buttons = {x=22,y=40,width=140,height=36,fontScale=0.3,color=getMainColor('frames')} t[#t+1] = Def.Quad{ InitCommand=function(self) self:xy(buttons.x,buttons.y):zoomto(buttons.width,buttons.height):halign(1):valign(0):diffuse(buttons.color):diffusealpha(0) local latest = tonumber((DLMAN:GetLastVersion():gsub("[.]","",1))) local current = tonumber((GAMESTATE:GetEtternaVersion():gsub("[.]","",1))) if latest and latest > current then gameneedsupdating = true end end, OnCommand=function(self) if gameneedsupdating then self:diffusealpha(1) end end, MouseLeftClickMessageCommand=function(self) if isOver(self) and gameneedsupdating then GAMESTATE:ApplyGameCommand("urlnoexit,https://github.com/etternagame/etterna/releases;text,GitHub") end end } t[#t+1] = LoadFont("Common Large") .. { OnCommand=function(self) self:xy(buttons.x+3,buttons.y+14):halign(1):zoom(buttons.fontScale):diffuse(getMainColor('positive')) if gameneedsupdating then self:settext("Update Available\nClick to Update") else self:settext("") end end } function mysplit(inputstr, sep) if sep == nil then sep = "%s" end local t={} ; i=1 for str in string.gmatch(inputstr, "([^"..sep.."]+)") do t[i] = str i = i + 1 end return t end local transformF = THEME:GetMetric("ScreenTitleMenu", "ScrollerTransform") local scrollerX = THEME:GetMetric("ScreenTitleMenu", "ScrollerX") local scrollerY = THEME:GetMetric("ScreenTitleMenu", "ScrollerY") local scrollerChoices = THEME:GetMetric("ScreenTitleMenu", "ChoiceNames") local _, count = string.gsub(scrollerChoices, "%,", "") local choices = mysplit(scrollerChoices, ",") local choiceCount = count+1 local i for i=1,choiceCount do t[#t+1] = Def.Quad { OnCommand=function(self) self:xy(scrollerX,scrollerY):zoomto(260,16) transformF(self, 0, i, choiceCount) self:addx(SCREEN_CENTER_X-20) self:addy(SCREEN_CENTER_Y-20) self:diffusealpha(0) end, MouseLeftClickMessageCommand = function(self) if(isOver(self)) then SCREENMAN:GetTopScreen():playcommand("MadeChoicePlayer_1") SCREENMAN:GetTopScreen():playcommand("Choose") if choices[i] ~= "Multi" and choices[i] ~= "GameStart" then -- for some reason multi gets stuck :/ GAMESTATE:ApplyGameCommand(THEME:GetMetric("ScreenTitleMenu", "Choice"..choices[i])) end end end, } end return t
object_mobile_peawp_bodyguard_trainer = object_mobile_shared_peawp_bodyguard_trainer:new { } ObjectTemplates:addTemplate(object_mobile_peawp_bodyguard_trainer, "object/mobile/peawp_bodyguard_trainer.iff")
local M = torch.zeros(total_num_words(), word_vecs_size):float() --Reading Contents for line in io.lines(w2v_txtfilename) do local parts = split(line, ' ') local w = parts[1] local w_id = get_id_from_word(w) if w_id ~= unk_w_id then for i=2, #parts do M[w_id][i-1] = tonumber(parts[i]) end end end return M
if not modules then modules = { } end modules ['data-use'] = { version = 1.001, comment = "companion to luat-lib.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } local format, lower, gsub, find = string.format, string.lower, string.gsub, string.find local trace_locating = false trackers.register("resolvers.locating", function(v) trace_locating = v end) local report_mounts = logs.reporter("resolvers","mounts") local resolvers = resolvers -- we will make a better format, maybe something xml or just text or lua resolvers.automounted = resolvers.automounted or { } function resolvers.automount(usecache) local mountpaths = resolvers.cleanpathlist(resolvers.expansion('TEXMFMOUNT')) if (not mountpaths or #mountpaths == 0) and usecache then mountpaths = caches.getreadablepaths("mount") end if mountpaths and #mountpaths > 0 then resolvers.starttiming() for k=1,#mountpaths do local root = mountpaths[k] local f = io.open(root.."/url.tmi") if f then for line in f:lines() do if line then if find(line,"^[%%#%-]") then -- or %W -- skip elseif find(line,"^zip://") then if trace_locating then report_mounts("mounting %a",line) end table.insert(resolvers.automounted,line) resolvers.usezipfile(line) end end end f:close() end end resolvers.stoptiming() end end -- status info statistics.register("used config file", function() return caches.configfiles() end) statistics.register("used cache path", function() return caches.usedpaths() end) -- experiment (code will move) function statistics.savefmtstatus(texname,formatbanner,sourcefile,kind,banner) -- texname == formatname local enginebanner = status.banner if formatbanner and enginebanner and sourcefile then local luvname = file.replacesuffix(texname,"luv") -- utilities.lua.suffixes.luv local luvdata = { enginebanner = enginebanner, formatbanner = formatbanner, sourcehash = md5.hex(io.loaddata(resolvers.findfile(sourcefile)) or "unknown"), sourcefile = sourcefile, luaversion = LUAVERSION, } io.savedata(luvname,table.serialize(luvdata,true)) lua.registerfinalizer(function() logs.report("format banner","%s",banner) logs.newline() end) end end -- todo: check this at startup and return (say) 999 as signal that the run -- was aborted due to a wrong format in which case mtx-context can trigger -- a remake function statistics.checkfmtstatus(texname) local enginebanner = status.banner if enginebanner and texname then local luvname = file.replacesuffix(texname,"luv") -- utilities.lua.suffixes.luv if lfs.isfile(luvname) then local luv = dofile(luvname) if luv and luv.sourcefile then local sourcehash = md5.hex(io.loaddata(resolvers.findfile(luv.sourcefile)) or "unknown") local luvbanner = luv.enginebanner or "?" if luvbanner ~= enginebanner then return format("engine mismatch (luv: %s <> bin: %s)",luvbanner,enginebanner) end local luvhash = luv.sourcehash or "?" if luvhash ~= sourcehash then return format("source mismatch (luv: %s <> bin: %s)",luvhash,sourcehash) end local luvluaversion = luv.luaversion or 0 if luvluaversion ~= LUAVERSION then return format("lua mismatch (luv: %s <> bin: %s)",luvluaversion,LUAVERSION) end else return "invalid status file" end else return "missing status file" end end return true end
menu = {} username = "" roomname = "" function menu.update(dt, data, msg) return menu end function menu.draw() if mode == 1 then love.graphics.setColor(0,0,0) love.graphics.setFont(largefont) love.graphics.printf("Please enter a username!",100,100,love.graphics.getWidth()-200,"center") love.graphics.printf(username,100,300,love.graphics.getWidth()-200,"center") love.graphics.setFont(midfont) love.graphics.printf(errormsg,100,500,love.graphics.getWidth()-200,"center") elseif mode == 2 then love.graphics.setColor(0,0,0) love.graphics.setFont(largefont) love.graphics.printf("Please enter a room name!",100,100,love.graphics.getWidth()-200,"center") love.graphics.printf(roomname,100,300,love.graphics.getWidth()-200,"center") love.graphics.setFont(midfont) love.graphics.printf(errormsg,100,500,love.graphics.getWidth()-200,"center") end return menu end function menu.textinput(t) if mode == 1 then username = username .. t elseif mode == 2 then roomname = roomname .. t end return menu end function menu.keypressed(key) if key == "backspace" then if mode == 1 then local byteoffset = utf8.offset(username, -1) if byteoffset then username = string.sub(username, 1, byteoffset - 1) end elseif mode == 2 then local byteoffset = utf8.offset(roomname, -1) if byteoffset then roomname = string.sub(roomname, 1, byteoffset - 1) end end elseif key == "return" then -- We want a room! if mode == 1 then mode = 2 elseif mode == 2 then udp:send("#"..roomname.."@"..username) end end return menu end function menu.acceptMessage(data, msg) if data:sub(1,1) == "!" then setUpGame(data, false) return gameHandWait elseif data:sub(1,1) == "&" then return waiting elseif string.sub(data,1,1) == "@" then mode = 1 errormsg = "Username already used or no valid username entered" elseif string.sub(data,1,1) == "#" then mode = 2 errormsg = "Room in use or no valid room entered." end return menu end
local Q = require 'Q' local qc = require 'Q/UTILS/lua/q_core' local Vector = require 'libvec' local test = {} test.t1 = function () local sum_prod = require 'Q/ML/LOGREG/lua/sum_prod_eval' local N = 256 * 65536 local M = 16 local X = {} for i = 1, M do X[i] = Q.rand({lb = 0, ub = 10, qtype = "F4", len = N}):eval() end local w = Q.rand({lb = 0, ub = 1, qtype = "F4", len = N}):eval() local start_time = qc.RDTSC() Vector.reset_timers() local A = sum_prod(X, w) Vector.print_timers() local stop_time = qc.RDTSC() print("sum_prod eval = ", stop_time-start_time) --[[ for i = 1, 3 do for j = 1, 3 do print(A[i][j]) end print("================") end ]] print("==============================================") if _G['g_time'] then for k, v in pairs(_G['g_time']) do local niters = _G['g_ctr'][k] or "unknown" local ncycles = tonumber(v) print("0," .. k .. "," .. niters .. "," .. ncycles) end end print("SUCCESS") os.exit() end test.t2 = function () local sum_prod = require 'Q/ML/LOGREG/lua/sum_prod_chunk' local N = 256 * 65536 local M = 16 local X = {} for i = 1, M do X[i] = Q.rand({lb = 0, ub = 10, qtype = "F4", len = N}):eval() end local w = Q.rand({lb = 0, ub = 1, qtype = "F4", len = N}):eval() local start_time = qc.RDTSC() Vector.reset_timers() local A = sum_prod(X, w) Vector.print_timers() local stop_time = qc.RDTSC() print("sum_prod chunk = ", stop_time-start_time) --[[ for i = 1, 3 do for j = 1, 3 do print(A[i][j]) end print("================") end ]] print("==============================================") if _G['g_time'] then for k, v in pairs(_G['g_time']) do local niters = _G['g_ctr'][k] or "unknown" local ncycles = tonumber(v) print("0," .. k .. "," .. niters .. "," .. ncycles) end end print("SUCCESS") os.exit() end return test
--[[ @author Sebastian "CrosRoad95" Jura <sebajura1234@gmail.com> @copyright 2011-2021 Sebastian Jura <sebajura1234@gmail.com> @license MIT ]]-- function findPlayer(plr,cel) local target=nil if (tonumber(cel) ~= nil) then target=getElementByID("p"..cel) else -- podano fragment nicku for _,thePlayer in ipairs(getElementsByType("player")) do if string.find(string.gsub(getPlayerName(thePlayer):lower(),"#%x%x%x%x%x%x", ""), cel:lower(), 0, true) then if (target) then outputChatBox("* Znaleziono więcej niż jednego gracza o pasującym nicku, podaj więcej liter.", plr) return nil end target=thePlayer end end end if target and getElementData(target,"p:inv") then return nil end return target end local function findFreeValue(tablica_id) table.sort(tablica_id) local wolne_id=1 for i,v in ipairs(tablica_id) do if (v==wolne_id) then wolne_id=wolne_id+1 end if (v>wolne_id) then return wolne_id end end return wolne_id end function assignPlayerID(plr) local gracze=getElementsByType("player") local tablica_id = {} for i,v in ipairs(gracze) do local lid=getElementData(v, "id") if (lid) then table.insert(tablica_id, tonumber(lid)) end end local free_id=findFreeValue(tablica_id) if isElement(plr) then setElementData(plr,"id", free_id) setElementID(plr, "p" .. free_id) end return free_id end function getPlayerID(plr) if not plr then return "" end local id=getElementData(plr,"id") if (id) then return id else return assignPlayerID(plr) end end addEventHandler ("onPlayerJoin", getRootElement(), function() assignPlayerID(source) end)
local lspconfig = require('lspconfig') local lsp_status = require('lsp-status') local cmp_nvim_lsp = require('cmp_nvim_lsp') lsp_status.register_progress() local on_attach = function(client, bufnr) if client.resolved_capabilities.hover then vim.api.nvim_exec([[ augroup lsp_hover autocmd! autocmd CursorHold <buffer> lua vim.lsp.buf.hover() augroup END ]], false) end if client.resolved_capabilities.document_formatting then vim.api.nvim_exec([[ augroup lsp_document_formatting autocmd! autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting() augroup END ]], false) end if client.resolved_capabilities.definition then vim.api.nvim_set_keymap('n', '<C-]>', '<Cmd>lua vim.lsp.buf.definition()<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<C-t>', '<C-o>', { noremap = true, silent = true }) end lsp_status.on_attach(client) end local capabilities = lsp_status.capabilities capabilities = cmp_nvim_lsp.update_capabilities(capabilities) lspconfig.gopls.setup { on_attach = on_attach, capabilities = capabilities, } lspconfig.terraformls.setup { on_attach = on_attach, capabilities = capabilities, } lspconfig.rust_analyzer.setup { on_attach = on_attach, capabilities = capabilities, settings = { ["rust-analyzer"] = { cargo = { loadOutDirsFromCheck = true }, procMacro = { enable = true } } } } lspconfig.yamlls.setup { on_attach = on_attach, capabilities = capabilities, settings = { yaml = { schemas = { kubernetes = 'kubernetes/*', } } } } lspconfig.sumneko_lua.setup { on_attach = on_attach, capabilities = capabilities, cmd = { 'lua-langserver' }, settings = { Lua = { diagnostics = { -- Suppress "Undefined global `vim`" error for neovim lua globals = { 'vim' } } } } } lspconfig.tsserver.setup { on_attach = on_attach, capabilities = capabilities, }
------------------------------------------------------------------------------------------- -- -- raylib [core] example - Basic window -- -- This example has been created using raylib 1.6 (www.raylib.com) -- raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) -- -- Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) -- ------------------------------------------------------------------------------------------- -- Initialization ------------------------------------------------------------------------------------------- local screenWidth = 800 local screenHeight = 450 InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window") SetTargetFPS(60) -- Set target frames-per-second ------------------------------------------------------------------------------------------- -- Main game loop while not WindowShouldClose() do -- Detect window close button or ESC key -- Update --------------------------------------------------------------------------------------- -- TODO: Update your variables here --------------------------------------------------------------------------------------- -- Draw --------------------------------------------------------------------------------------- BeginDrawing() ClearBackground(RAYWHITE) DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY) EndDrawing() --------------------------------------------------------------------------------------- end -- De-Initialization ------------------------------------------------------------------------------------------- CloseWindow() -- Close window and OpenGL context -------------------------------------------------------------------------------------------
local LogFile={}; function LogFile.create(_filename) LogFile.filename=_filename; LogFile.handle=io.open(LogFile.filename, "w"); end function LogFile.println(line) LogFile.handle:write(line .. "\n"); end function LogFile.print(line) LogFile.handle:write(line); end function LogFile.close() LogFile.handle:close(); end return LogFile;
local M = {} local tinsert, ipairs, setmetatable = table.insert, ipairs, setmetatable function M.new(key) local meta = { __index = function(_, k) return M[k] end } return setmetatable({ deps = {}, collect = {}, key = key }, meta) end function M:record(path) if not self.deps[path] then self.deps[path] = true tinsert(self.collect, path) end end function M:fetch(binding) if #self.collect == 0 then return end for _, key in ipairs(self.collect) do binding:watch(key, function() binding:computed_trigger(self.key) end) end self.collect = {} end return M
-- Corona Cannon -- A complete remake of Ghosts vs. Monsters sample game for Corona SDK. -- Most of the graphics made by kenney.nl -- Please use Corona daily build 2016.2818 or later. -- Created by Sergey Lerg for Corona Labs. -- License - MIT. display.setStatusBar(display.HiddenStatusBar) system.activate('multitouch') if system.getInfo('build') >= '2017.2741' then -- Allow the game to be opened using an old Corona version display.setDefault('isAnchorClamped', true) -- Needed for scenes/reload_game.lua animation end local platform = system.getInfo('platformName') if platform == 'tvOS' then system.setIdleTimer(true) end -- Hide navigation bar on Android if platform == 'Android' then native.setProperty('androidSystemUiVisibility', 'immersiveSticky') end -- Exit and enter fullscreen mode -- CMD+CTRL+F on OS X -- F11 or ALT+ENTER on Windows if platform == 'Mac OS X' or platform == 'Win' then Runtime:addEventListener('key', function(event) if event.phase == 'down' and ( (platform == 'Mac OS X' and event.keyName == 'f' and event.isCommandDown and event.isCtrlDown) or (platform == 'Win' and (event.keyName == 'f11' or (event.keyName == 'enter' and event.isAltDown))) ) then if native.getProperty('windowMode') == 'fullscreen' then native.setProperty('windowMode', 'normal') else native.setProperty('windowMode', 'fullscreen') end end end) end local composer = require('composer') composer.recycleOnSceneChange = true -- Automatically remove scenes from memory composer.setVariable('levelCount', 15) -- Set how many levels there are under levels/ directory -- Add support for back button on Android and Window Phone -- When it's pressed, check if current scene has a special field gotoPreviousScene -- If it's a function - call it, if it's a string - go back to the specified scene if platform == 'Android' or platform == 'WinPhone' then Runtime:addEventListener('key', function(event) if event.phase == 'down' and event.keyName == 'back' then local scene = composer.getScene(composer.getSceneName('current')) if scene then if type(scene.gotoPreviousScene) == 'function' then scene:gotoPreviousScene() return true elseif type(scene.gotoPreviousScene) == 'string' then composer.gotoScene(scene.gotoPreviousScene, {time = 500, effect = 'slideRight'}) return true end end end end) end -- Please note that above Runtime events use anonymous listeners. While it's fine for these cases, -- it is not possible to remove the event listener if needed. For instanse, an accelerometer event listener must be removed at some point -- to reduce battery consumption. -- The above cases are fine to use anonymous listeners because we don't need to remove them ever. -- Add support for controllers so the game is playable on Android TV, Apple TV and with a MFi controller require('libs.controller') -- Activate by requiring -- This library automatically loads and saves it's storage into databox.json inside Documents directory -- And it uses iCloud KVS storage on iOS and tvOS local databox = require('libs.databox') databox({ isSoundOn = true, isMusicOn = true, isHelpShown = true, overscanValue = 0 }) -- This library manages sound files and music files playback -- Inside it there is a list of all used audio files local sounds = require('libs.sounds') sounds.isSoundOn = databox.isSoundOn sounds.isMusicOn = databox.isMusicOn -- This library helps position elements on the screen during the resize event require('libs.relayout') -- This library deals with the overscan issue that is present on many TVs local overscan = require('libs.overscan') overscan.compensate(databox.overscanValue) -- Show menu scene composer.gotoScene('scenes.menu')
local skynet = require "skynet" local sharetable = require "skynet.sharetable" skynet.start(function() -- You can also use sharetable.loadfile / sharetable.loadstring sharetable.loadtable ("test", { x=1,y={ 'hello world' },['hello world'] = true }) local t = sharetable.query("test") for k,v in pairs(t) do print(k,v) end sharetable.loadstring ("test", "return { ... }", 1,2,3) skynet.sleep(1) for k,v in pairs(t) do print(k,v) end end)
--[[ Carbon for Lua #class Math.Vector #inherits OOP.Object #description { **Abstract Template `Vector<N>`** Provides a metaprogramming-driven method of generating N-length vectors. Presently has a hard maximum component count of 26, can be expanded upon request. } ]] local Carbon = (...) local OOP = Carbon.OOP local Dictionary = Carbon.Collections.Dictionary local List = Carbon.Collections.List local CodeGenerationException = Carbon.Exceptions.CodeGenerationException local TemplateEngine = Carbon.TemplateEngine local loadstring = loadstring or load local SIMPLE_LOOSE_BINARY_OPERATOR = function(symbol, default) default = default or 0 return (([[ return function(self, {%= ARGS_STRING %}, out) return self.class:PlacementNew(out, {% for i = 1, LENGTH do _(("self[%d] {symbol} (%s or {default})"):format( i, ARGS[i] )) if (i < LENGTH) then _(", ") end end %} ) end ]]) :gsub("{symbol}", symbol) :gsub("{default}", default) ) end local SIMPLE_BINARY_OPERATOR = function(symbol, default) default = default or 0 return (([[ return function(self, other, out) return self.class:PlacementNew(out, {% for i = 1, LENGTH do _(("self[%d] {symbol} (other[%d] or {default})"):format(i, i)) if (i < LENGTH) then _(", ") end end %} ) end ]]) :gsub("{symbol}", symbol) :gsub("{default}", default) ) end local Vector = { Engine = TemplateEngine:New(), __cache = {}, __methods = { --[[#method 1 { class public @Vector<N> Vector<N>:New(...) -alias: object public @void Vector<N>:Init(...) optional ...: The arguments to the intialization. Should be `N` arguments long. Creates a new @Vector with `N` components. }]] Init = [[ return function(self, {%= ARGS_STRING %}) {% for i, arg in ipairs(ARGS) do _(("self[%d] = %s or %s;"):format( i, arg, PARAMETERS.DefaultValues[i] )) end %} end ]], --[[#method { object public @unumber Vector<N>:Length() Returns the length of the vector. }]] Length = [[ return function(self) return math.sqrt( {% for i = 1, LENGTH do _(("self[%d]^2%s"):format( i, i < LENGTH and "+" or "" )) end %}) end ]], --[[#method { object public @unumber Vector<N>:LengthSquared() Returns the length of the vector squared. }]] LengthSquared = [[ return function(self) return {% for i = 1, LENGTH do _(("self[%d]^2%s"):format( i, i < LENGTH and "+" or "" )) end %} end ]], --[[#method { object public self Vector<N>:Normalize!() -alias: object public self Vector<N>:NormalizeInPlace() Normalizes the vector in-place. Called in Carbide as `Vector:Normalize!()` }]] NormalizeInPlace = function(self) return self:Normalize(self) end, --[[#method { object public out Vector<N>:Normalize([@Vector<N> out]) optional out: Where to place the data of the normalized vector. A new `Vector<N>` if not given. Normalizes the @Vector<N> object, optionally outputting the data to an existing @Vector<N>. }]] Normalize = [[ local abs = math.abs return function(self, out) out = out or self.class:New() local square_length = self:LengthSquared() if (square_length == 0) then square_length = 1 / {%= PARAMETERS.NormalizedLength^2 %} else {% if (PARAMETERS.NormalizedLength ~= 1) then %} square_length = square_length / {%= PARAMETERS.NormalizedLength^2 %} {% end %} end -- First-order Padé approximation for unit-ish vectors if (abs(1 - square_length) < 2.107342e-8) then {% for i = 1, LENGTH do _(("out[%d] = self[%d] * 2 / (1 + square_length)"):format(i, i)) end %} else local length = math.sqrt(square_length) {% for i = 1, LENGTH do _(("out[%d] = %g * self[%d] / length;"):format( i, PARAMETERS.NormalizedLength, i )) end %} end return out end ]], --[[#method { object public @loose<Vector> Vector:LooseScale(@number scalar) required scalar: The value to scale by. Scales the @Vector and returns it in @loose form. }]] LooseScale = [[ return function(self, scalar) return {% for i = 1, LENGTH do _(("self[%d] * scalar"):format(i)) if (i < LENGTH) then _(",") end end %} end ]], --[[#method { object public @Vector Vector:Scale(@number scalar, [@Vector out]) required scalar: The value to scale by. optional out: Where to put the resulting data. Scales the @Vector, optionally outputting into an existing @Vector. }]] Scale = function(self, scalar, out) return self.class:PlacementNew(out, self:LooseScale(scalar)) end, --[[#method { object public @Vector Vector:Scale!(@number scalar) -alias: object public @Vector Vector:ScaleInPlace(@number scalar) required scalar: The value to scale by. Scales the @Vector in place. }]] ScaleInPlace = function(self, scalar) return self:Scale(scalar, self) end, --[[#method { object public @tuple<N, unumber> Vector<N>:GetComponents() Returns the individual components of the @Vector<N> in order. Much faster than `unpack`. }]] GetComponents = [[ return function(self) return {% for i = 1, LENGTH do _(("self[%d]"):format(i)) if (i < LENGTH) then _(",") end end %} end ]], --[[#method { object public @number Vector<N>:DotMultiply(@Vector<N> other) required other: The @Vector to multiply with. Performs a dot product between two vectors. }]] DotMultiply = [[ return function(self, other) return {% for i = 1, LENGTH do _(("self[%d] * (other[%d] or 0)"):format(i, i)) if (i < LENGTH) then _(" + ") end end %} end ]], --[[#method { object public (@number, @Vector<N>) Vector<N>:Multiply((@number, @Vector<N>) other, [@Vector<N> out]) required other: The object to multiply with; a vector, matrix, or number. optional out: Where to put the resulting data, if specified. }]] Multiply = function(self, other, out) if (type(other) == "number") then return self:Scale(other, out) elseif (type(other) == "table") then if (other.Is[Carbon.Math.Matrix]) then return self:MultiplyMatrix(other, out) elseif (other.Is[self.class]) then return self:DotMultiply(other) end end return nil end, MultiplyMatrixInPlace = function(self, other) return self:MultiplyMatrix(other, self) end, MultiplyMatrix = function(self, other, out) return other:PreMultiplyVector(self, out) end, PostMultiplyMatrixInPlace = function(self, other) return self:PostMultiplyMatrix(other, self) end, PostMultiplyMatrix = function(self, other, out) return other:MultiplyVector(self, out) end, Add = function(self, other, out) return self:AddVector(other, out) end, AddLooseVector = SIMPLE_LOOSE_BINARY_OPERATOR("+"), AddLooseVectorInPlace = [[ return function(self, {%=ARGS_STRING %}) return self:AddLooseVector({%=ARGS_STRING %}, self) end ]], AddVector = SIMPLE_BINARY_OPERATOR("+"), AddVectorInPlace = function(self, other) return self:AddVector(other, self) end, Subtract = function(self, other, out) return self:SubtractVector(other, out) end, SubtractLooseVector = SIMPLE_LOOSE_BINARY_OPERATOR("-"), SubtractLooseVectorInPlace = [[ return function(self, {%=ARGS_STRING %}) return self:SubtractLooseVector({%=ARGS_STRING %}, self) end ]], SubtractVector = SIMPLE_BINARY_OPERATOR("-"), SubtractVectorInPlace = function(self, other) return self:SubtractVector(other, self) end, }, __metatable = { -- String conversion: -- tostring(Vector) __tostring = [[ return function(self) return ("({%= ("%g, "):rep(LENGTH):sub(1,-3) %})"):format( {% for i = 1, LENGTH do _(("self[%d]%s"):format( i, i < LENGTH and "," or "" )) end %}) end ]], __add = function(self, ...) return self:Add(...) end, __sub = function(self, ...) return self:Subtract(...) end, __mul = function(self, ...) return self:Multiply(...) end } } local arg_list = {"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"} --[[#method { private function Vector:__generate_method(@string body, @dictionary arguments, [@dictionary env]) required body: Template-enabled code to return a function. required arguments: Arguments to the template optional env: The environment to generate the method under. Generates a method using Carbon's TemplateEngine and handles errors. }]] function Vector:__generate_method(body, arguments, env) env = env or {} local generated, exception = self.Engine:Render(body, arguments) if (not generated) then return false, exception end Dictionary.ShallowMerge(_G, env) local generator, err = Carbon.LoadString(generated, body:sub(1, 50), env) if (not generator) then return false, CodeGenerationException:New(err, generated), generated end return generated, generator() end --[[#method { public @Vector<length> Vector:Generate(@uint length, [@dictionary parameters]) required length: The length of the vector. optional parameters: Options for generating the class: Generates a new Vector class with the given keys and parameters. Results are cached, but this method may still be slow. It performs runtime code generation and template parsing on each generated class. The following parameters are valid: - @number NormalizedLength (1): The length the vector reaches when normalized. - @number DefaultValue (0): The value to initialize all members to if not given. - @list<@number> DefaultValues: A list of values to initialize specific keys to. If any are given, all keys must be specified. }]] function Vector:Generate(length, parameters) if (self.__cache[length]) then return self.__cache[length] end parameters = parameters or {} local args = {} for i = 1, length do table.insert(args, arg_list[i]) end local args_string = table.concat(args, ",") if (parameters.DefaultValue) then parameters.DefaultValues = {} for i = 1, length do table.insert(paramters.DefaultValues, parameters.DefaultValue) end elseif (not parameters.DefaultValues) then parameters.DefaultValues = {} for i = 1, length do table.insert(parameters.DefaultValues, 0) end end parameters.NormalizedLength = parameters.NormalizedLength or 1 local class = OOP:Class() class.__generated = {} class.Is[Vector] = true local body = { ComponentCount = length } class:Members(body) -- These are all LOUD to show that they're template arguments. local gen_args = { LENGTH = length, ARGS = args, ARGS_STRING = args_string, PARAMETERS = parameters, CLASS = class } -- Process methods for the generated class for name, body in pairs(self.__methods) do if (type(body) == "string") then local generated generated, class[name] = self:__generate_method(body, gen_args) class.__generated[name] = generated if (not class[name]) then return false, err, body end else class[name] = body end end local metatable = {} for name, body in pairs(self.__metatable) do if (type(body) == "string") then local generated generated, metatable[name] = self:__generate_method(body, gen_args) class.__generated[name] = generated if (not metatable[name]) then return false, err, body end else metatable[name] = body end end class:Metatable(metatable) :Attributes { PooledInstantiation = true, PoolSize = 64, SparseInstances = true, ExplicitInitialization = true } self.__cache[length] = class return class end return Vector
local kong = kong local _M = {} local function show_kong_headers(show) kong.configuration.enabled_headers['X-Kong-Upstream-Latency'] = show kong.configuration.enabled_headers['X-Kong-Proxy-Latency'] = show kong.configuration.enabled_headers['Via'] = show end function _M.execute(config) show_kong_headers(config.show_kong_headers) if config.add_magalu_header then kong.response.set_header('x-magalu', 'Hello TDC Connections') end end return _M
local Layout = {mediaPath = {}} local SML, mediaRequired, anchoringQueued local mediaPath = Layout.mediaPath local backdropTbl = {insets = {}} local _G = getfenv(0) ShadowUF.Layout = Layout -- Someone is using another mod that is forcing a media type for all mods using SML function Layout:MediaForced(mediaType) local oldPath = mediaPath[mediaType] self:CheckMedia() if( mediaPath[mediaType] ~= oldPath ) then self:Reload() end end local function loadMedia(type, name, default) if( name == "" ) then return "" end local media = SML:Fetch(type, name, true) if( not media ) then mediaRequired = mediaRequired or {} mediaRequired[type] = name return default end return media end -- Updates the background table local function updateBackdrop() -- Update the backdrop table local backdrop = ShadowUF.db.profile.backdrop backdropTbl.bgFile = mediaPath.background backdropTbl.edgeFile = mediaPath.border backdropTbl.tile = backdrop.tileSize > 0 and true or false backdropTbl.edgeSize = backdrop.edgeSize backdropTbl.tileSize = backdrop.tileSize backdropTbl.insets.left = backdrop.inset backdropTbl.insets.right = backdrop.inset backdropTbl.insets.top = backdrop.inset backdropTbl.insets.bottom = backdrop.inset end -- Tries to load media, if it fails it will default to whatever I set function Layout:CheckMedia() mediaPath[SML.MediaType.STATUSBAR] = loadMedia(SML.MediaType.STATUSBAR, ShadowUF.db.profile.bars.texture, "Interface\\AddOns\\ShadowedUnitFrames\\media\\textures\\Aluminium") mediaPath[SML.MediaType.FONT] = loadMedia(SML.MediaType.FONT, ShadowUF.db.profile.font.name, "Interface\\AddOns\\ShadowedUnitFrames\\media\\fonts\\Myriad Condensed Web.ttf") mediaPath[SML.MediaType.BACKGROUND] = loadMedia(SML.MediaType.BACKGROUND, ShadowUF.db.profile.backdrop.backgroundTexture, "Interface\\ChatFrame\\ChatFrameBackground") mediaPath[SML.MediaType.BORDER] = loadMedia(SML.MediaType.BORDER, ShadowUF.db.profile.backdrop.borderTexture, "") updateBackdrop() end -- We might not have had a media we required at initial load, wait for it to load and then update everything when it does function Layout:MediaRegistered(event, mediaType, key) if( mediaRequired and mediaRequired[mediaType] and mediaRequired[mediaType] == key ) then mediaPath[mediaType] = SML:Fetch(mediaType, key) mediaRequired[mediaType] = nil self:Reload() end end -- Helper functions function Layout:ToggleVisibility(frame, visible) if( frame and visible ) then frame:Show() elseif( frame ) then frame:Hide() end end function Layout:SetBarVisibility(frame, key, status) if( status and not frame[key]:IsVisible() ) then frame[key]:Show() ShadowUF.Layout:PositionWidgets(frame, ShadowUF.db.profile.units[frame.unitType]) elseif( not status and frame[key]:IsVisible() ) then frame[key]:Hide() ShadowUF.Layout:PositionWidgets(frame, ShadowUF.db.profile.units[frame.unitType]) end end -- Frame changed somehow between when we first set it all up and now function Layout:Reload(unit) updateBackdrop() -- Now update them for frame in pairs(ShadowUF.Units.frameList) do if( frame.unit and ( not unit or frame.unitType == unit ) and not frame.isHeaderFrame ) then frame:SetVisibility() self:Load(frame) frame:FullUpdate() end end ShadowUF:FireModuleEvent("OnLayoutReload", unit) end -- Do a full update function Layout:Load(frame) local unitConfig = ShadowUF.db.profile.units[frame.unitType] -- About to set layout ShadowUF:FireModuleEvent("OnPreLayoutApply", frame, unitConfig) -- Load all of the layout things self:SetupFrame(frame, unitConfig) self:SetupBars(frame, unitConfig) self:PositionWidgets(frame, unitConfig) self:SetupText(frame, unitConfig) -- Layouts been fully set ShadowUF:FireModuleEvent("OnLayoutApplied", frame, unitConfig) end -- Register it on file load because authors seem to do a bad job at registering the callbacks SML = LibStub:GetLibrary("LibSharedMedia-3.0") SML:Register(SML.MediaType.FONT, "Myriad Condensed Web", "Interface\\AddOns\\ShadowedUnitFrames\\media\\fonts\\Myriad Condensed Web.ttf") SML:Register(SML.MediaType.BORDER, "Square Clean", "Interface\\AddOns\\ShadowedUnitFrames\\media\\textures\\ABFBorder") SML:Register(SML.MediaType.BACKGROUND, "Chat Frame", "Interface\\ChatFrame\\ChatFrameBackground") SML:Register(SML.MediaType.STATUSBAR, "BantoBar", "Interface\\AddOns\\ShadowedUnitFrames\\media\\textures\\banto") SML:Register(SML.MediaType.STATUSBAR, "Smooth", "Interface\\AddOns\\ShadowedUnitFrames\\media\\textures\\smooth") SML:Register(SML.MediaType.STATUSBAR, "Perl", "Interface\\AddOns\\ShadowedUnitFrames\\media\\textures\\perl") SML:Register(SML.MediaType.STATUSBAR, "Glaze", "Interface\\AddOns\\ShadowedUnitFrames\\media\\textures\\glaze") SML:Register(SML.MediaType.STATUSBAR, "Charcoal", "Interface\\AddOns\\ShadowedUnitFrames\\media\\textures\\Charcoal") SML:Register(SML.MediaType.STATUSBAR, "Otravi", "Interface\\AddOns\\ShadowedUnitFrames\\media\\textures\\otravi") SML:Register(SML.MediaType.STATUSBAR, "Striped", "Interface\\AddOns\\ShadowedUnitFrames\\media\\textures\\striped") SML:Register(SML.MediaType.STATUSBAR, "LiteStep", "Interface\\AddOns\\ShadowedUnitFrames\\media\\textures\\LiteStep") SML:Register(SML.MediaType.STATUSBAR, "Aluminium", "Interface\\AddOns\\ShadowedUnitFrames\\media\\textures\\Aluminium") SML:Register(SML.MediaType.STATUSBAR, "Minimalist", "Interface\\AddOns\\ShadowedUnitFrames\\media\\textures\\Minimalist") function Layout:LoadSML() SML.RegisterCallback(self, "LibSharedMedia_Registered", "MediaRegistered") SML.RegisterCallback(self, "LibSharedMedia_SetGlobal", "MediaForced") self:CheckMedia() end --[[ Keep in mind this is relative to where you're parenting it, RT will put the object outside of the frame, on the right side, at the top of it while ITR will put it inside the frame, at the top to the right * Positions OUTSIDE the frame RT = Right Top, RC = Right Center, RB = Right Bottom LT = Left Top, LC = Left Center, LB = Left Bottom, BL = Bottom Left, BC = Bottom Center, BR = Bottom Right TR = Top Right, TC = Top Center, TL = Top Left * Positions INSIDE the frame CLI = Inside Center Left, CRI = Inside Center Right TRI = Inside Top Right, TLI = Inside Top Left BRI = Inside Bottom Right, BRI = Inside Bottom left ]] local preDefPoint = {C = "CENTER", CLI = "LEFT", RT = "TOPLEFT", BC = "TOP", CRI = "RIGHT", LT = "TOPRIGHT", TR = "BOTTOMRIGHT", BL = "TOPLEFT", LB = "BOTTOMRIGHT", LC = "RIGHT", RB = "BOTTOMLEFT", RC = "LEFT", TC = "BOTTOM", BR = "TOPRIGHT", TL = "BOTTOMLEFT", BRI = "BOTTOMRIGHT", BLI = "BOTTOMLEFT", TRI = "TOPRIGHT", TLI = "TOPLEFT"} local preDefRelative = {C = "CENTER", CLI = "LEFT", RT = "TOPRIGHT", BC = "BOTTOM", CRI = "RIGHT", LT = "TOPLEFT", TR = "TOPRIGHT", BL = "BOTTOMLEFT", LB = "BOTTOMLEFT", LC = "LEFT", RB = "BOTTOMRIGHT", RC = "RIGHT", TC = "TOP", BR = "BOTTOMRIGHT", TL = "TOPLEFT", BRI = "BOTTOMRIGHT", BLI = "BOTTOMLEFT", TRI = "TOPRIGHT", TLI = "TOPLEFT"} local columnDirection = {RT = "RIGHT", C = "RIGHT", BC = "BOTTOM", LT = "LEFT", TR = "TOP", BL = "BOTTOM", LB = "LEFT", LC = "LEFT", TRI = "TOP", RB = "RIGHT", RC = "RIGHT", TC = "TOP", CLI = "RIGHT", TL = "TOP", BR = "BOTTOM", IBL = "RIGHT", IBR = "RIGHT", CRI = "RIGHT", TLI = "TOP"} local auraDirection = {RT = "BOTTOM", C = "LEFT", BC = "LEFT", LT = "BOTTOM", TR = "LEFT", BL = "RIGHT", LB = "TOP", LC = "LEFT", TRI = "LEFT", RB = "TOP", RC = "LEFT", TC = "LEFT", CLI = "RIGHT", TL = "RIGHT", BR = "LEFT", IBL = "TOP", IBR = "TOP", CRI = "LEFT", TLI = "RIGHT"} -- Figures out how text should be justified based on where it's anchoring function Layout:GetJustify(config) local point = config.anchorPoint and config.anchorPoint ~= "" and preDefPoint[config.anchorPoint] or config.point if( point and point ~= "" ) then if( string.match(point, "LEFT$") ) then return "LEFT" elseif( string.match(point, "RIGHT$") ) then return "RIGHT" end end return "CENTER" end function Layout:GetPoint(key) return preDefPoint[key] or "CENTER" end function Layout:GetRelative(key) return preDefRelative[key] or "CENTER" end function Layout:GetColumnGrowth(key) return columnDirection[key] or "DOWN" end function Layout:GetAuraGrowth(key) return auraDirection[key] or "LEFT" end function Layout:ReverseDirection(key) return key == "LEFT" and "RIGHT" or key == "RIGHT" and "LEFT" or key == "TOP" and "BOTTOM" or key == "BOTTOM" and "TOP" end -- Gets the relative anchoring for Blizzards default raid frames, these differ from the split ones function Layout:GetRelativeAnchor(point) if( point == "TOP" ) then return "BOTTOM", 0, -1 elseif( point == "BOTTOM" ) then return "TOP", 0, 1 elseif( point == "LEFT" ) then return "RIGHT", 1, 0 elseif( point == "RIGHT" ) then return "LEFT", -1, 0 elseif( point == "TOPLEFT" ) then return "BOTTOMRIGHT", 1, -1 elseif( point == "TOPRIGHT" ) then return "BOTTOMLEFT", -1, -1 elseif( point == "BOTTOMLEFT" ) then return "TOPRIGHT", 1, 1 elseif( point == "BOTTOMRIGHT" ) then return "TOPLEFT", -1, 1 else return "CENTER", 0, 0 end end function Layout:GetSplitRelativeAnchor(point, columnPoint) -- Column is growing to the RIGHT if( columnPoint == "LEFT" ) then return "TOPLEFT", "TOPRIGHT", 1, 0 -- Column is growing to the LEFT elseif( columnPoint == "RIGHT" ) then return "TOPRIGHT", "TOPLEFT", -1, 0 -- Column is growing DOWN elseif( columnPoint == "TOP" ) then return "TOP" .. point, "BOTTOM" .. point, 0, -1 -- Column is growing UP elseif( columnPoint == "BOTTOM" ) then return "BOTTOM" .. point, "TOP" .. point, 0, 1 end end function Layout:AnchorFrame(parent, frame, config) if( not config or not config.anchorTo or not config.x or not config.y ) then return end local anchorTo = config.anchorTo local prefix = string.sub(config.anchorTo, 0, 1) if( config.anchorTo == "$parent" ) then anchorTo = parent -- $ is used as an indicator of a sub-frame inside a parent, $healthBar -> parent.healthBar and so on elseif( prefix == "$" ) then anchorTo = parent[string.sub(config.anchorTo, 2)] -- # is used as an indicator of an actual frame created by SUF, it lets us know that the frame might not be created yet -- and if so, to watch for it to be created and fix the anchoring elseif( prefix == "#" ) then anchorTo = string.sub(config.anchorTo, 2) -- The frame we wanted to anchor to doesn't exist yet, so will queue and wait for it to exist if( not _G[anchorTo] ) then frame.queuedParent = parent frame.queuedConfig = config frame.queuedName = anchorTo anchoringQueued = anchoringQueued or {} anchoringQueued[frame] = true -- For the time being, will take over the frame we wanted to anchor to's position. local unit = string.match(anchorTo, "SUFUnit(%w+)") or string.match(anchorTo, "SUFHeader(%w+)") if( unit and ShadowUF.db.profile.positions[unit] ) then self:AnchorFrame(parent, frame, ShadowUF.db.profile.positions[unit]) end return end end -- Figure out where it's anchored local point = config.point and config.point ~= "" and config.point or preDefPoint[config.anchorPoint] or "CENTER" local relativePoint = config.relativePoint and config.relativePoint ~= "" and config.relativePoint or preDefRelative[config.anchorPoint] or "CENTER" -- Effective scaling is only used for unit based frames and if they are anchored to UIParent local scale = 1 if( config.anchorTo == "UIParent" and frame.unitType ) then scale = frame:GetScale() * UIParent:GetScale() end frame:ClearAllPoints() frame:SetPoint(point, anchorTo, relativePoint, config.x / scale, config.y / scale) end -- Setup the main frame function Layout:SetupFrame(frame, config) local backdrop = ShadowUF.db.profile.backdrop frame:SetBackdrop(backdropTbl) frame:SetBackdropColor(backdrop.backgroundColor.r, backdrop.backgroundColor.g, backdrop.backgroundColor.b, backdrop.backgroundColor.a) frame:SetBackdropBorderColor(backdrop.borderColor.r, backdrop.borderColor.g, backdrop.borderColor.b, backdrop.borderColor.a) -- Prevent these from updating while in combat to prevent tainting if( not InCombatLockdown() ) then frame:SetHeight(config.height) frame:SetWidth(config.width) frame:SetScale(config.scale) -- Let the frame clip closer to the edge, not using inset + clip as that lets you move it too far in local clamp = backdrop.inset + 0.20 frame:SetClampRectInsets(clamp, -clamp, -clamp, clamp) frame:SetClampedToScreen(true) -- This is wrong technically, I need to redo the backdrop stuff so it will accept insets and that will fit hitbox issues -- for the time being, this is a temporary fix to it local hit = backdrop.borderTexture == "None" and backdrop.inset or 0 frame:SetHitRectInsets(hit, hit, hit, hit) if( not frame.ignoreAnchor ) then self:AnchorFrame(frame.parent or UIParent, frame, ShadowUF.db.profile.positions[frame.unitType]) end end -- Check if we had anything parented to us if( anchoringQueued ) then for queued in pairs(anchoringQueued) do if( queued.queuedName == frame:GetName() ) then self:AnchorFrame(queued.queuedParent, queued, queued.queuedConfig) queued.queuedParent = nil queued.queuedConfig = nil queued.queuedName = nil anchoringQueued[queued] = nil end end end end -- Setup bars function Layout:SetupBars(frame, config) for _, module in pairs(ShadowUF.modules) do local key = module.moduleKey local widget = frame[key] if( widget and ( module.moduleHasBar or config[key] and config[key].isBar ) ) then self:ToggleVisibility(widget, frame.visibility[key]) if( widget:IsShown() and widget.SetStatusBarTexture ) then widget:SetStatusBarTexture(mediaPath.statusbar) widget:GetStatusBarTexture():SetHorizTile(false) end if( widget.background ) then if( config[key].background ) then widget.background:SetTexture(mediaPath.statusbar) widget.background:SetHorizTile(false) widget.background:Show() widget.background.overrideColor = ShadowUF.db.profile.bars.backgroundColor or config[key].backgroundColor if( widget.background.overrideColor ) then widget.background:SetVertexColor(widget.background.overrideColor.r, widget.background.overrideColor.g, widget.background.overrideColor.b, ShadowUF.db.profile.bars.backgroundAlpha) end else widget.background:Hide() end end end end end -- Setup text function Layout:SetupFontString(fontString, extraSize) local size = ShadowUF.db.profile.font.size + (extraSize or 0) if( size <= 0 ) then size = 1 end fontString:SetFont(mediaPath.font, size, ShadowUF.db.profile.font.extra) if( ShadowUF.db.profile.font.shadowColor and ShadowUF.db.profile.font.shadowX and ShadowUF.db.profile.font.shadowY ) then fontString:SetShadowColor(ShadowUF.db.profile.font.shadowColor.r, ShadowUF.db.profile.font.shadowColor.g, ShadowUF.db.profile.font.shadowColor.b, ShadowUF.db.profile.font.shadowColor.a) fontString:SetShadowOffset(ShadowUF.db.profile.font.shadowX, ShadowUF.db.profile.font.shadowY) else fontString:SetShadowColor(0, 0, 0, 0) fontString:SetShadowOffset(0, 0) end end local totalWeight = {} function Layout:SetupText(frame, config) -- Update tag text frame.fontStrings = frame.fontStrings or {} for _, fontString in pairs(frame.fontStrings) do ShadowUF.Tags:Unregister(fontString) fontString:Hide() end for k in pairs(totalWeight) do totalWeight[k] = nil end -- Update the actual text, and figure out the weighting information now for id, row in pairs(config.text) do local parent = row.anchorTo == "$parent" and frame or frame[string.sub(row.anchorTo, 2)] if( parent and parent:IsShown() and row.enabled and row.text ~= "" ) then local fontString = frame.fontStrings[id] or frame.highFrame:CreateFontString(nil, "ARTWORK") self:SetupFontString(fontString, row.size) fontString:SetTextColor(ShadowUF.db.profile.font.color.r, ShadowUF.db.profile.font.color.g, ShadowUF.db.profile.font.color.b, ShadowUF.db.profile.font.color.a) fontString:SetText(row.text) fontString:SetJustifyH(self:GetJustify(row)) self:AnchorFrame(frame, fontString, row) -- We figure out the anchor point so we can put text in the same area with the same width requirements local anchorPoint = columnDirection[row.anchorPoint] if( string.len(row.anchorPoint) == 3 ) then anchorPoint = anchorPoint .. "I" end fontString.availableWidth = parent:GetWidth() - row.x fontString.widthID = row.anchorTo .. anchorPoint .. row.y totalWeight[fontString.widthID] = (totalWeight[fontString.widthID] or 0) + row.width ShadowUF.Tags:Register(frame, fontString, row.text) fontString:UpdateTags() fontString:Show() frame.fontStrings[id] = fontString end end -- Now set all of the width using our weightings for id, fontString in pairs(frame.fontStrings) do if( fontString:IsShown() ) then fontString:SetWidth(fontString.availableWidth * (config.text[id].width / totalWeight[fontString.widthID])) fontString:SetHeight(ShadowUF.db.profile.font.size + 1) frame:RegisterUpdateFunc(fontString, "UpdateTags") else frame:UnregisterAll(fontString) end end end -- Setup the bar barOrder/info local currentConfig local function sortOrder(a, b) return currentConfig[a].order < currentConfig[b].order end local barOrder = {} function Layout:PositionWidgets(frame, config) -- Deal with setting all of the bar heights local totalWeight, totalBars, hasFullSize = 0, -1 -- Figure out total weighting as well as what bars are full sized for i=#(barOrder), 1, -1 do table.remove(barOrder, i) end for key, module in pairs(ShadowUF.modules) do if( ( module.moduleHasBar or config[key] and config[key].isBar ) and frame[key] and frame[key]:IsShown() and config[key].height > 0 ) then totalWeight = totalWeight + config[key].height totalBars = totalBars + 1 table.insert(barOrder, key) -- Decide whats full sized if( not frame.visibility.portrait or config.portrait.isBar or config[key].order < config.portrait.fullBefore or config[key].order > config.portrait.fullAfter ) then hasFullSize = true frame[key].fullSize = true else frame[key].fullSize = nil end end end -- Sort the barOrder so it's all nice and orderly (:>) currentConfig = config table.sort(barOrder, sortOrder) -- Now deal with setting the heights and figure out how large the portrait should be. local clip = ShadowUF.db.profile.backdrop.inset + ShadowUF.db.profile.backdrop.clip local clipDoubled = clip * 2 local portraitOffset, portraitAlignment, portraitAnchor, portraitWidth if( not config.portrait.isBar ) then self:ToggleVisibility(frame.portrait, frame.visibility.portrait) if( frame.visibility.portrait ) then -- Figure out portrait alignment portraitAlignment = config.portrait.alignment -- Set the portrait width so we can figure out the offset to use on bars, will do height and position later portraitWidth = math.floor(frame:GetWidth() * config.portrait.width) - ShadowUF.db.profile.backdrop.inset frame.portrait:SetWidth(portraitWidth - (portraitAlignment == "RIGHT" and 1 or 0.5)) -- Disable portrait if there isn't enough room if( portraitWidth <= 0 ) then frame.portrait:Hide() end -- As well as how much to offset bars by (if it's using a left alignment) to keep them all fancy looking portraitOffset = clip if( portraitAlignment == "LEFT" ) then portraitOffset = portraitOffset + portraitWidth end end end -- Position and size everything local portraitHeight, xOffset = 0, -clip local availableHeight = frame:GetHeight() - clipDoubled - (math.abs(ShadowUF.db.profile.bars.spacing) * totalBars) for id, key in pairs(barOrder) do local bar = frame[key] -- Position the actual bar based on it's type if( bar.fullSize ) then bar:SetWidth(frame:GetWidth() - clipDoubled) bar:SetHeight(availableHeight * (config[key].height / totalWeight)) bar:ClearAllPoints() bar:SetPoint("TOPLEFT", frame, "TOPLEFT", clip, xOffset) else bar:SetWidth(frame:GetWidth() - portraitWidth - clipDoubled) bar:SetHeight(availableHeight * (config[key].height / totalWeight)) bar:ClearAllPoints() bar:SetPoint("TOPLEFT", frame, "TOPLEFT", portraitOffset, xOffset) portraitHeight = portraitHeight + bar:GetHeight() end -- Figure out where the portrait is going to be anchored to if( not portraitAnchor and config[key].order >= config.portrait.fullBefore ) then portraitAnchor = bar end xOffset = xOffset - bar:GetHeight() + ShadowUF.db.profile.bars.spacing end -- Now position the portrait and set the height if( frame.portrait and frame.portrait:IsShown() and portraitAnchor and portraitHeight > 0 ) then if( portraitAlignment == "LEFT" ) then frame.portrait:ClearAllPoints() frame.portrait:SetPoint("TOPLEFT", portraitAnchor, "TOPLEFT", -frame.portrait:GetWidth() - 0.5, 0) elseif( portraitAlignment == "RIGHT" ) then frame.portrait:ClearAllPoints() frame.portrait:SetPoint("TOPRIGHT", portraitAnchor, "TOPRIGHT", frame.portrait:GetWidth() + 1, 0) end if( hasFullSize ) then frame.portrait:SetHeight(portraitHeight) else frame.portrait:SetHeight(frame:GetHeight() - clipDoubled) end end ShadowUF:FireModuleEvent("OnLayoutWidgets", frame, config) end
-------------------------------------------------------------------------------- -- account.lua -------------------------------------------------------------------------------- local store = require("lib.store") return store.model("Account", { attributes = { "account", -- 账号 'password', -- 登录密码 "name", -- 昵称 'gender', -- 性别 'face', -- 头像 'game', -- 游戏标志 'group', -- 社团 'groupname', -- 社团名字 'custom', -- 自定义 'lock', -- 锁定机器 'sign', -- 签名 'viplevel', -- 会员等级 'expire', -- 会员到期时间 'exp', -- 经验 "score", -- 分数 }, indices = { "account" }, uniques = { "account" }, tracked = { } })
local M = { __prefix = 'pokemon', } M.name = function(self) return self:fetch('pokemon.names') end M.location = function(self) return self:fetch('pokemon.locations') end local Base = require "faker.base" return Base(M)
-- handle new payments events ONLY SERVER-SIDE AddEventHandler('tebex:newPayment', function(packageName, packageData) print( ("[PAYMENTS]: New payment for %s"):format(packageName) ) end) -- execute any framework function ONLY SERVER-SIDE ESX = nil TriggerEvent('esx:getSharedObject', function(o) ESX = o end) AddEventHandler('tebex:newPayment', function(packageName, packageData) if packageName == "Money" then local playerId = packageData.variables["server_id"] -- you should have setup a variable on your package first! local xPlayer = ESX.GetPlayerFromId(playerId) if xPlayer then xPlayer.addMoney(100) -- notify player? TriggerClientEvent('chat:addMessage', playerId, { args={"TEBEX", "You bought "..packageName} }) end end end)
project "lua_grdmap" language "C++" files { "code/**.cpp" , "code/**.c" , "code/**.h" , "all.h" } links { "lib_lua" , "lib_grd" } includedirs { "." , "../lua_grd" } KIND{kind="lua",dir="wetgenes/grdmap",name="core",luaname="wetgenes.grdmap.core",luaopen="wetgenes_grdmap_core"}
msg = "Date duži ne mogu biti stranice trougla."
package.cpath = package.cpath..";../?.so" package.path = package.cpath..";../?.lua" local ljson_decoder = require 'json_decoder' local decoder = ljson_decoder.new() local function cmp_lua_var(obj1, obj2) if type(obj1) ~= type(obj2) then return end if type(obj1) == "string" or type(obj1) == "number" or type(obj1) == "nil" or type(obj1) == "boolean" then return obj1 == obj2 and true or nil end if (type(obj1) ~= "table") then print("unknown type", type(obj1)); return end -- compare table for k, v in pairs(obj1) do if not cmp_lua_var(v, obj2[k]) then -- print(v," vs ", obj2[k]) return end end for k, v in pairs(obj2) do if not cmp_lua_var(v, obj1[k]) then -- print(v," vs ", obj1[k]) return end end return true end local test_fail_num = 0; local test_total = 0; local function ljson_test(test_id, parser, input, expect) test_total = test_total + 1 io.write(string.format("Testing %s ...", test_id)) local result = decoder:decode(input) if cmp_lua_var(result, expect) then print("succ!") else test_fail_num = test_fail_num + 1 print("failed!") --ljson_decoder.debug(result) end end local json_parser = ljson_decoder.create() -- Test 1 local input = [=[[1, 2, 3, {"key1":"value1", "key2":"value2"}, "lol"]]=] local output = {1, 2, 3, {["key1"] = "value1", ["key2"] = "value2" }, "lol"} ljson_test("test1", json_parser, input, output); -- Test 2 input = [=[[]]=] output = {} ljson_test("test2", json_parser, input, output); -- Test 3 input = [=[[{}]]=] output = {{}} ljson_test("test3", json_parser, input, output); input = [=[[null]]=] output = {nil} ljson_test("test4", json_parser, input, output); input = [=[[true, false]]=] output = {true, false} ljson_test("test5", json_parser, input, output); input = "-" -- invalid input output = nil ljson_test("test6", json_parser, input, output); -- The input string is "[\0265]", where char \0265 is illegal. The json decoder -- once crash on this case. input = string.format("[%c]", 181) output = nil ljson_test("test7", json_parser, input, output); input = string.format("[ %c]", 181) output = nil ljson_test("test8", json_parser, input, output); io.write(string.format( "\n============================\nTotal test count %d, fail %d\n", test_total, test_fail_num)) if test_fail_num == 0 then os.exit(0) else os.exit(1) end
--- Bresenham Based Ray-Casting FOV calculator. -- See http://en.wikipedia.org/wiki/Bresenham's_line_algorithm. -- Included for sake of having options. Provides three functions for computing FOV -- @module ROT.FOV.Bresenham local ROT = require((...):gsub(('.[^./\\]*'):rep(2) .. '$', '')) local Bresenham=ROT.FOV:extend("Bresenham") -- internal Point class local Point = ROT.Class:extend("Point") function Point:init(x, y) self.isPoint = true self.x=x self.y=y end function Point:hashCode() local prime =31 local result=1 result=prime*result+self.x result=prime*result+self.y return result end function Point:equals(other) if self==other then return true end if other==nil or not other.isPoint or (other.x and other.x ~= self.x) or (other.y and other.y ~= self.y) then return false end return true end function Point:adjacentPoints() local points={} local i =1 for ox=-1,1 do for oy=-1,1 do points[i]=Point(self.x+ox,self.y+oy) i=i+1 end end return points end -- internal Line class local Line = ROT.Class:extend("Line") function Line:init(x1, y1, x2, y2) self.x1=x1 self.y1=y1 self.x2=x2 self.y2=y2 self.points={} end function Line:getPoints() local dx =math.abs(self.x2-self.x1) local dy =math.abs(self.y2-self.y1) local sx =self.x1<self.x2 and 1 or -1 local sy =self.y1<self.y2 and 1 or -1 local err=dx-dy while true do table.insert(self.points, Point(self.x1, self.y1)) if self.x1==self.x2 and self.y1==self.y2 then break end local e2=err*2 if e2>-dx then err=err-dy self.x1 =self.x1+sx end if e2<dx then err=err+dx self.y1 =self.y1+sy end end return self end --- Constructor. -- Called with ROT.FOV.Bresenham:new() -- @tparam function lightPassesCallback A function with two parameters (x, y) that returns true if a map cell will allow light to pass through -- @tparam table options Options -- @tparam int options.topology Direction for light movement Accepted values: (4 or 8) -- @tparam boolean options.useDiamond If true, the FOV will be a diamond shape as opposed to a circle shape. function Bresenham:init(lightPassesCallback, options) Bresenham.super.init(self, lightPassesCallback, options) end --- Compute. -- Get visibility from a given point. -- This method cast's rays from center to points on a circle with a radius 3-units longer than the provided radius. -- A list of cell's within the radius is kept. This list is checked at the end to verify that each cell has been passed to the callback. -- @tparam int cx x-position of center of FOV -- @tparam int cy y-position of center of FOV -- @tparam int r radius of FOV (i.e.: At most, I can see for R cells) -- @tparam function callback A function that is called for every cell in view. Must accept four parameters. -- @tparam int callback.x x-position of cell that is in view -- @tparam int callback.y y-position of cell that is in view -- @tparam int callback.r The cell's distance from center of FOV -- @tparam number callback.visibility The cell's visibility rating (from 0-1). How well can you see this cell? function Bresenham:compute(cx, cy, r, callback) local notvisited={} for x=-r,r do for y=-r,r do notvisited[Point(cx+x, cy+y):hashCode()]={cx+x, cy+y} end end callback(cx,cy,1,1) notvisited[Point(cx, cy):hashCode()]=nil local thePoints=self:_getCircle(cx, cy, r+3) for _,p in pairs(thePoints) do local x,y=p[1],p[2] local line=Line(cx,cy,x, y):getPoints() for i=2,#line.points do local point=line.points[i] if self:_oob(cx-point.x, cy-point.y, r) then break end if notvisited[point:hashCode()] then callback(point.x, point.y, i, 1-(i/r)) notvisited[point:hashCode()]=nil end if not self:_lightPasses(point.x, point.y) then break end end end for _,v in pairs(notvisited) do local x,y=v[1],v[2] local line=Line(cx,cy,x, y):getPoints() for i=2,#line.points do local point=line.points[i] if self:_oob(cx-point.x, cy-point.y, r) then break end if notvisited[point:hashCode()] then callback(point.x, point.y, i, 1-(i/r)) notvisited[point:hashCode()]=nil end if not self:_lightPasses(point.x, point.y) then break end end end end --- Compute Thorough. -- Get visibility from a given point. -- This method cast's rays from center to every cell within the given radius. -- This method is much slower, but is more likely to not generate any anomalies within the field. -- @tparam int cx x-position of center of FOV -- @tparam int cy y-position of center of FOV -- @tparam int r radius of FOV (i.e.: At most, I can see for R cells) -- @tparam function callback A function that is called for every cell in view. Must accept four parameters. -- @tparam int callback.x x-position of cell that is in view -- @tparam int callback.y y-position of cell that is in view -- @tparam int callback.r The cell's distance from center of FOV -- @tparam number callback.visibility The cell's visibility rating (from 0-1). How well can you see this cell? function Bresenham:computeThorough(cx, cy, r, callback) local visited={} callback(cx,cy,r) visited[Point(cx, cy):hashCode()]=0 for x=-r,r do for y=-r,r do local line=Line(cx,cy,x+cx, y+cy):getPoints() for i=2,#line.points do local point=line.points[i] if self:_oob(cx-point.x, cy-point.y, r) then break end if not visited[point:hashCode()] then callback(point.x, point.y, r) visited[point:hashCode()]=0 end if not self:_lightPasses(point.x, point.y) then break end end end end end --- Compute Thorough. -- Get visibility from a given point. The quickest method provided. -- This method cast's rays from center to points on a circle with a radius 3-units longer than the provided radius. -- Unlike compute() this method stops at that point. It will likely miss cell's for fields with a large radius. -- @tparam int cx x-position of center of FOV -- @tparam int cy y-position of center of FOV -- @tparam int r radius of FOV (i.e.: At most, I can see for R cells) -- @tparam function callback A function that is called for every cell in view. Must accept four parameters. -- @tparam int callback.x x-position of cell that is in view -- @tparam int callback.y y-position of cell that is in view -- @tparam int callback.r The cell's distance from center of FOV -- @tparam number callback.visibility The cell's visibility rating (from 0-1). How well can you see this cell? function Bresenham:computeQuick(cx, cy, r, callback) local visited={} callback(cx,cy,1, 1) visited[Point(cx, cy):hashCode()]=0 local thePoints=self:_getCircle(cx, cy, r+3) for _,p in pairs(thePoints) do local x,y=p[1],p[2] local line=Line(cx,cy,x, y):getPoints() for i=2,#line.points do local point=line.points[i] if self:_oob(cx-point.x, cy-point.y, r) then break end if not visited[point:hashCode()] then callback(point.x, point.y, i, 1-(i*i)/(r*r)) visited[point:hashCode()]=0 end if not self:_lightPasses(point.x, point.y) then break end end end end function Bresenham:_oob(x, y, r) if not self._options.useDiamond then local ab=((x*x)+(y*y)) local c =(r*r) return ab > c else return math.abs(x)+math.abs(y)>r end end return Bresenham
--Need to redefine this old-way because sometimes cannot be copied right parameter ---------------- --DEFINE ITEMS-- ---------------- data:extend({ { type = "item", name = "armored-platform-minigun-mk1", icon = "__Armored-train__/graphics/icons/armored-paltform-minigun-mk1-icon.png", icon_size = 32, flags = {}, subgroup = "transport", order = "a[train-system]-l[armored_platform_turret1]", place_result = "armored-platform-minigun-mk1", stack_size = 5 }, ------------------ --DEFINE RECIPES-- ------------------ { type = "recipe", name = "armored-platform-minigun-mk1", enabled = false, ingredients = { {"armored-platform-mk1", 1}, {"repair-pack", 1}, {"platform-minigun-turret-mk1", 1}, }, result = "armored-platform-minigun-mk1" } }) ------------------ --DEFINE ENTITIES-- ------------------ --Deep copy base data and create new one with custom parametres local armored_platform_minigun_mk1 = util.table.deepcopy(data.raw["cargo-wagon"]["cargo-wagon"]) armored_platform_minigun_mk1.name = "armored-platform-minigun-mk1" armored_platform_minigun_mk1.icon = "__Armored-train__/graphics/icons/armored-paltform-mk1-icon.png" armored_platform_minigun_mk1.minable = { mining_time = 1, result = "armored-platform-mk1" --wagon or platform dismantled and turret is placed to inventory (using buffer) } --COPY FROM BASE HP data from tank \/ ------------------------------------- local base_tank = data.raw.car["tank"]; --use flags (not flamable) armored_platform_minigun_mk1.flags = base_tank.flags; --copy tank resistancec (maybe add acid resistane) armored_platform_minigun_mk1.resistances = base_tank.resistances; ------------------------------------- --COPY FROM BASE HP data from tank /\ --ACTUAL PARAMETRES \/ armored_platform_minigun_mk1.max_health = 1000 armored_platform_minigun_mk1.weight = 2000 armored_platform_minigun_mk1.energy_per_hit_point = 5 armored_platform_minigun_mk1.inventory_size = 10 --ACTUAL PARAMETRES /\ --no doors armored_platform_minigun_mk1.horizontal_doors = nil armored_platform_minigun_mk1.vertical_doors = nil --pictures armored_platform_minigun_mk1.pictures = { layers = { { priority = "very-low", width = 256, height = 256, back_equals_front = false, --means to not rotate mirroring direction_count = 128, --means to add aditional frames allow_low_quality_rotation = true, line_length = 32, lines_per_file = 1, shift = {0.4, -1.25}, filenames = { "__Armored-train__/graphics/entity/armored-platform-mk2/armored-platform-mk2-01.png", "__Armored-train__/graphics/entity/armored-platform-mk2/armored-platform-mk2-02.png", "__Armored-train__/graphics/entity/armored-platform-mk2/armored-platform-mk2-03.png", "__Armored-train__/graphics/entity/armored-platform-mk2/armored-platform-mk2-04.png" }, }, --DECORATIVES --SHADOW { priority = "very-low", --draw_as_shadow = true, --draw as shadow on groud level as in riginal game (use original shadow zip) width = 126, height = 62, back_equals_front = false, --means to not rotate mirroring direction_count = 128, --means to add aditional frames allow_low_quality_rotation = true, line_length = 32, lines_per_file = 1, shift = {-0.65, -1.4}, scale = 1, filenames = { "__Armored-train__/graphics/entity/minigun-turret-128/minigun-turret-128-01-shadow.png", "__Armored-train__/graphics/entity/minigun-turret-128/minigun-turret-128-02-shadow.png", "__Armored-train__/graphics/entity/minigun-turret-128/minigun-turret-128-03-shadow.png", "__Armored-train__/graphics/entity/minigun-turret-128/minigun-turret-128-04-shadow.png", }, }, --MAIN SPRITE { priority = "very-low", width = 66, height = 64, back_equals_front = false, --means to not rotate mirroring direction_count = 128, --means to add aditional frames allow_low_quality_rotation = true, line_length = 32, lines_per_file = 1, shift = {0.0, -1.25}, filenames = { "__Armored-train__/graphics/entity/minigun-turret-128/minigun-turret-128-01.png", "__Armored-train__/graphics/entity/minigun-turret-128/minigun-turret-128-02.png", "__Armored-train__/graphics/entity/minigun-turret-128/minigun-turret-128-03.png", "__Armored-train__/graphics/entity/minigun-turret-128/minigun-turret-128-04.png", }, }, --MASK { priority = "very-low", width = 30, height = 28, back_equals_front = false, --means to not rotate mirroring direction_count = 128, --means to add aditional frames allow_low_quality_rotation = true, line_length = 32, lines_per_file = 1, shift = {0.0, -1.4}, scale = 1, filenames = { "__Armored-train__/graphics/entity/minigun-turret-128/minigun-turret-128-01-mask.png", "__Armored-train__/graphics/entity/minigun-turret-128/minigun-turret-128-02-mask.png", "__Armored-train__/graphics/entity/minigun-turret-128/minigun-turret-128-03-mask.png", "__Armored-train__/graphics/entity/minigun-turret-128/minigun-turret-128-04-mask.png", }, } }, } --FINAL RESULTS and write data:extend({armored_platform_minigun_mk1})
require "lmk" require "lmkutil" local startTime = os.time () local function print_usage () print ("") print ("LMK options:") print (" -u <path/lmk file>") print (" -b <path/lmk file>") print (" -m <debug, opt, bc>") print (" -f <function name>") print (" -r <on/off>") print (" -v <on/off>") print (" -c <on/off>") end local argList = lmkutil.process_args (arg) local result, msg = true, nil if argList then local doBuild = true for ix = 1, #argList do local opt = argList[ix].opt local values = argList[ix].values if opt == "-u" then doBuild = false if not values then result, msg = lmk.update () else for jy = 1, #values do result, msg = lmk.update (values[jy]) if not result then break end end end elseif opt == "-s" then if values then lmk.set_system (values[1]) else end elseif opt == "-b" then doBuild = false if not values then result, msg = lmk.build () else for jy = 1, #values do result, msg = lmk.build (values[jy]) if not result then break end end end elseif opt == "-m" then if not values then lmk.set_build_mode ("debug") else if #values > 1 then print ("Warning: -m only take one parameter. " .. "Ignoring other parameters: ") for jy = 2, #values do print (" " .. values[jy]) end end lmk.set_build_mode (values[1]) end elseif opt == "-p" then doBuild = false if not values then result, msg = lmk.init () else for jy = 1, #values do result, msg = lmk.init (values[jy]) if not result then break end end end elseif opt == "-f" then if not values then lmk.set_process_func_name ("main") else if #values > 1 then print ("Warning: -f only take one parameter. " .. "Ignoring other parameters: ") for jy = 2, #values do print (" " .. values[jy]) end end lmk.set_process_func_name (values[1]) end elseif opt == "-r" then if not values then lmk.set_recurse (true) else local value = values[1]:lower () if (value == "true") or (value == "on") or (value == "1") then lmk.set_recurse (true) else lmk.set_recurse (false) end end elseif opt == "-v" then if not values then lmk.set_verbose (true) else local value = values[1]:lower () if (value == "true") or (value == "on") or (value == "1") then lmk.set_verbose (true) else lmk.set_verbose (false) end end elseif opt == "-c" then if not values then lmk.set_color_mode (true) else local value = values[1]:lower () if (value == "true") or (value == "on") or (value == "1") then lmk.set_color_mode (true) else lmk.set_color_mode (false) end end elseif opt == "-h" then print_usage (); os.exit () else result = false msg = "Unknown opt: " .. opt print_usage () end if not result then break end end if result and doBuild then lmk.build () end else result, msg = lmk.build () end if not result then print ("Error: " .. (msg and msg or "Unknown Error")) end local deltaTime = os.time () - startTime local hours = math.floor (deltaTime / 3600) local min = math.floor ((deltaTime - (hours * 3600)) / 60) local sec = math.floor (deltaTime - ((min * 60) + (hours * 3600))) print ("Execution time: " .. ((hours < 10) and "0" or "") .. tostring (hours) .. ":" .. ((min < 10) and "0" or "") .. tostring (min) .. ":" .. ((sec < 10) and "0" or "") .. tostring (sec))
DEBUGMODE = false MTAVER = 1.4 HVER = "2.1.2"
local _M = {} local k8s_suffix = os.getenv("fqdn_suffix") if (k8s_suffix == nil) then k8s_suffix = "" end local function _StrIsEmpty(s) return s == nil or s == '' end local function _LoadTimeline(data) local timeline = {} for _, timeline_post in ipairs(data) do local new_post = {} new_post["post_id"] = tostring(timeline_post.post_id) new_post["creator"] = {} new_post["creator"]["user_id"] = tostring(timeline_post.creator.user_id) new_post["creator"]["username"] = timeline_post.creator.username new_post["req_id"] = tostring(timeline_post.req_id) new_post["text"] = timeline_post.text new_post["user_mentions"] = {} for _, user_mention in ipairs(timeline_post.user_mentions) do local new_user_mention = {} new_user_mention["user_id"] = tostring(user_mention.user_id) new_user_mention["username"] = user_mention.username table.insert(new_post["user_mentions"], new_user_mention) end new_post["media"] = {} for _, media in ipairs(timeline_post.media) do local new_media = {} new_media["media_id"] = tostring(media.media_id) new_media["media_type"] = media.media_type table.insert(new_post["media"], new_media) end new_post["urls"] = {} for _, url in ipairs(timeline_post.urls) do local new_url = {} new_url["shortened_url"] = url.shortened_url new_url["expanded_url"] = url.expanded_url table.insert(new_post["urls"], new_url) end new_post["timestamp"] = tostring(timeline_post.timestamp) new_post["post_type"] = timeline_post.post_type table.insert(timeline, new_post) end return timeline end function _M.ReadHomeTimeline() local bridge_tracer = require "opentracing_bridge_tracer" local ngx = ngx local GenericObjectPool = require "GenericObjectPool" local social_network_HomeTimelineService = require "social_network_HomeTimelineService" local HomeTimelineServiceClient = social_network_HomeTimelineService.HomeTimelineServiceClient local cjson = require "cjson" local liblualongnumber = require "liblualongnumber" local req_id = tonumber(string.sub(ngx.var.request_id, 0, 15), 16) local tracer = bridge_tracer.new_from_global() local parent_span_context = tracer:binary_extract( ngx.var.opentracing_binary_context) local span = tracer:start_span("read_home_timeline_client", { ["references"] = { { "child_of", parent_span_context } } }) local carrier = {} tracer:text_map_inject(span:context(), carrier) ngx.req.read_body() local args = ngx.req.get_uri_args() if (_StrIsEmpty(args.user_id) or _StrIsEmpty(args.start) or _StrIsEmpty(args.stop)) then ngx.status = ngx.HTTP_BAD_REQUEST ngx.say("Incomplete arguments") ngx.log(ngx.ERR, "Incomplete arguments") ngx.exit(ngx.HTTP_BAD_REQUEST) end local client = GenericObjectPool:connection( HomeTimelineServiceClient, "home-timeline-service" .. k8s_suffix, 9090) local status, ret = pcall(client.ReadHomeTimeline, client, req_id, tonumber(args.user_id), tonumber(args.start), tonumber(args.stop), carrier) if not status then ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR if (ret.message) then ngx.say("Get home-timeline failure: " .. ret.message) ngx.log(ngx.ERR, "Get home-timeline failure: " .. ret.message) else ngx.say("Get home-timeline failure: " .. ret) ngx.log(ngx.ERR, "Get home-timeline failure: " .. ret) end client.iprot.trans:close() span:finish() ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) else GenericObjectPool:returnConnection(client) local home_timeline = _LoadTimeline(ret) ngx.header.content_type = "application/json; charset=utf-8" ngx.say(cjson.encode(home_timeline) ) end span:finish() ngx.exit(ngx.HTTP_OK) end return _M
-- imports local WIM = WIM; local _G = _G; local CreateFrame = CreateFrame; local select = select; local type = type; local table = table; local pairs = pairs; local string = string; local next = next; local Ambiguate = Ambiguate; -- set name space setfenv(1, WIM); -- Core information addonTocName = "WIM"; version = "@project-version@"; beta = false; -- flags current version as beta. debug = false; -- turn debugging on and off. useProtocol2 = true; -- test switch for new W2W Protocol. (Dev use only) -- is Private Server? --[[isPrivateServer = not (string.match(_G.GetCVar("realmList"), "worldofwarcraft.com$") or string.match(_G.GetCVar("realmList"), "battle.net$") or string.match(_G.GetCVar("realmListbn"), "battle.net$")) and true or false;--]] constants = {}; -- constants such as class colors will be stored here. (includes female class names). modules = {}; -- module table. consists of all registerd WIM modules/plugins/skins. (treated the same). windows = {active = {whisper = {}, chat = {}, w2w = {}}}; -- table of WIM windows. libs = {}; -- table of loaded library references. stats = {}; -- default options. live data is found in WIM.db -- modules may insert fields into this table to -- respect their option contributions. db_defaults = { enabled = true, showToolTips = true, modules = {}, alertedPrivateServer = false, }; -- WIM.env is an evironmental reference for the current instance of WIM. -- Information is stored here such as .realm and .character. -- View table dump for more available information. env = {}; -- default lists - This will store lists such as friends, guildies, raid members etc. lists = {}; -- list of all the events registered from attached modules. local Events = {}; -- create a frame to moderate events and frame updates. local workerFrame = CreateFrame("Frame", "WIM_workerFrame"); workerFrame:SetScript("OnEvent", function(self, event, ...) WIM:CoreEventHandler(event, ...); end); -- some events we always want to listen to so data is ready upon WIM being enabled. workerFrame:RegisterEvent("VARIABLES_LOADED"); workerFrame:RegisterEvent("ADDON_LOADED"); -- called when WIM is first loaded into memory but after variables are loaded. local function initialize() --load cached information from the WIM_Cache saved variable. env.cache[env.realm] = env.cache[env.realm] or {}; env.cache[env.realm][env.character] = env.cache[env.realm][env.character] or {}; lists.friends = env.cache[env.realm][env.character].friendList; lists.guild = env.cache[env.realm][env.character].guildList; if(type(lists.friends) ~= "table") then lists.friends = {}; end if(type(lists.guild) ~= "table") then lists.guild = {}; end workerFrame:RegisterEvent("GUILD_ROSTER_UPDATE"); workerFrame:RegisterEvent("FRIENDLIST_UPDATE"); workerFrame:RegisterEvent("BN_FRIEND_LIST_SIZE_CHANGED"); workerFrame:RegisterEvent("BN_FRIEND_INFO_CHANGED"); --querie guild roster if( _G.IsInGuild() ) then _G.GuildRoster(); end -- import libraries. libs.SML = _G.LibStub:GetLibrary("LibSharedMedia-3.0"); libs.ChatHandler = _G.LibStub:GetLibrary("LibChatHandler-1.0"); isInitialized = true; RegisterPrematureSkins(); --enableModules local moduleName, tData; for moduleName, tData in pairs(modules) do modules[moduleName].db = db; if(modules[moduleName].canDisable ~= false) then local modDB = db.modules[moduleName]; if(modDB) then if(modDB.enabled == nil) then modDB.enabled = modules[moduleName].enableByDefault; end EnableModule(moduleName, modDB.enabled); else if(modules[moduleName].enableByDefault) then EnableModule(moduleName, true); end end else EnableModule(moduleName, true); end end for mName, module in pairs(modules) do if(db.enabled) then if(type(module.OnEnableWIM) == "function") then module:OnEnableWIM(); end else if(type(module.OnDisableWIM) == "function") then module:OnDisableWIM(); end end end -- notify all modules of current state. CallModuleFunction("OnStateChange", WIM.curState); RegisterSlashCommand("enable", function() SetEnabled(not db.enabled) end, L["Toggle WIM 'On' and 'Off'."]); RegisterSlashCommand("debug", function() debug = not debug; end, L["Toggle Debugging Mode 'On' and 'Off'."]); FRIENDLIST_UPDATE(); -- pretend event has been fired in order to get cache loaded. CallModuleFunction("OnInitialized"); WindowParent:Show(); dPrint("WIM initialized..."); end --Begin Compat wrappers for retail and classic to access same functions and expect same returns --These should work in all files that use them since they are written to WIMs global namespace --Retail kind of has these for now, but won't forever, and classic is not expected to make same API restructuring, so this ugly mess is probably required forever function GetBNGetFriendInfo(friendIndex) local accountInfo = _G.C_BattleNet and _G.C_BattleNet.GetFriendAccountInfo(friendIndex); if accountInfo then local wowProjectID = accountInfo.gameAccountInfo.wowProjectID or 0; local clientProgram = accountInfo.gameAccountInfo.clientProgram ~= "" and accountInfo.gameAccountInfo.clientProgram or nil; return accountInfo.bnetAccountID, accountInfo.accountName, accountInfo.battleTag, accountInfo.isBattleTagFriend, accountInfo.gameAccountInfo.characterName, accountInfo.gameAccountInfo.gameAccountID, clientProgram, accountInfo.gameAccountInfo.isOnline, accountInfo.lastOnlineTime, accountInfo.isAFK, accountInfo.isDND, accountInfo.customMessage, accountInfo.note, accountInfo.isFriend, accountInfo.customMessageTime, wowProjectID, accountInfo.rafLinkType == _G.Enum.RafLinkType.Recruit, accountInfo.gameAccountInfo.canSummon, accountInfo.isFavorite, accountInfo.gameAccountInfo.isWowMobile; else return _G.BNGetFriendInfo(friendIndex) end end function GetBNGetFriendInfoByID(id) local accountInfo = _G.C_BattleNet and _G.C_BattleNet.GetAccountInfoByID(id); if accountInfo then local wowProjectID = accountInfo.gameAccountInfo.wowProjectID or 0; local clientProgram = accountInfo.gameAccountInfo.clientProgram ~= "" and accountInfo.gameAccountInfo.clientProgram or nil; return accountInfo.bnetAccountID, accountInfo.accountName, accountInfo.battleTag, accountInfo.isBattleTagFriend, accountInfo.gameAccountInfo.characterName, accountInfo.gameAccountInfo.gameAccountID, clientProgram, accountInfo.gameAccountInfo.isOnline, accountInfo.lastOnlineTime, accountInfo.isAFK, accountInfo.isDND, accountInfo.customMessage, accountInfo.note, accountInfo.isFriend, accountInfo.customMessageTime, wowProjectID, accountInfo.rafLinkType == _G.Enum.RafLinkType.Recruit, accountInfo.gameAccountInfo.canSummon, accountInfo.isFavorite, accountInfo.gameAccountInfo.isWowMobile; else return _G.BNGetFriendInfoByID(id) end end function GetBNGetGameAccountInfo(toonId) local gameAccountInfo = _G.C_BattleNet and _G.C_BattleNet.GetGameAccountInfoByID(toonId) if gameAccountInfo then local wowProjectID = gameAccountInfo.wowProjectID or 0; local characterName = gameAccountInfo.characterName or ""; local realmName = gameAccountInfo.realmName or ""; local realmID = gameAccountInfo.realmID or 0; local factionName = gameAccountInfo.factionName or ""; local raceName = gameAccountInfo.raceName or ""; local className = gameAccountInfo.className or ""; local areaName = gameAccountInfo.areaName or ""; local characterLevel = gameAccountInfo.characterLevel or ""; local richPresence = gameAccountInfo.richPresence or ""; local gameAccountID = gameAccountInfo.gameAccountID or 0; local playerGuid = gameAccountInfo.playerGuid or 0; return gameAccountInfo.hasFocus, characterName, gameAccountInfo.clientProgram, realmName, realmID, factionName, raceName, className, "", areaName, characterLevel, richPresence, nil, nil, gameAccountInfo.isOnline, gameAccountID, nil, gameAccountInfo.isGameAFK, gameAccountInfo.isGameBusy, playerGuid, wowProjectID, gameAccountInfo.isWowMobile else return _G.BNGetGameAccountInfo(toonId) end end --End Compat wrappers for retail and classic to access same functions and expect same returns -- called when WIM is enabled. -- WIM will not be enabled until WIM is initialized event is fired. local function onEnable() db.enabled = true; local tEvent; for tEvent, _ in pairs(Events) do workerFrame:RegisterEvent(tEvent); end if(isInitialized) then for mName, module in pairs(modules) do if(type(module.OnEnableWIM) == "function") then module:OnEnableWIM(); end if(db.modules[mName] and db.modules[mName].enabled and type(module.OnEnable) == "function") then module:OnEnable(); end end end -- DisplayTutorial(L["WIM (WoW Instant Messenger)"], L["WIM is currently running. To access WIM's wide array of options type:"].." |cff69ccf0/wim|r"); dPrint("WIM is now enabled."); --[[ --Private Server Check if(isPrivateServer and not db.alertedPrivateServer) then _G.StaticPopupDialogs["WIM_PRIVATE_SERVER"] = { preferredIndex = STATICPOPUP_NUMDIALOGS, text = L["WIM has detected that you are playing on a private server. Some servers can not process ChatAddonMessages. Would you like to enable them anyway?"], button1 = _G.TEXT(_G.YES), button2 = _G.TEXT(_G.NO), OnShow = function(self) end, OnHide = function() end, OnAccept = function() db.disableAddonMessages = false; db.alertedPrivateServer = true; end, OnCancel = function() db.disableAddonMessages = true; db.alertedPrivateServer = true; end, timeout = 0, whileDead = 1, hideOnEscape = 1 }; _G.StaticPopup_Show ("WIM_PRIVATE_SERVER", theLink); end--]] end -- called when WIM is disabled. local function onDisable() db.enabled = false; local tEvent; for tEvent, _ in pairs(Events) do workerFrame:UnregisterEvent(tEvent); end if(isInitialized) then for _, module in pairs(modules) do if(type(module.OnDisableWIM) == "function") then module:OnDisableWIM(); end if(type(module.OnDisable) == "function") then module:OnDisable(); end end end dPrint("WIM is now disabled."); end function SetEnabled(enabled) if( enabled ) then onEnable(); else onDisable(); end end -- events are passed to modules. Events do not need to be -- unregistered. A disabled module will not receive events. local function RegisterEvent(event) Events[event] = true; if( db and db.enabled ) then workerFrame:RegisterEvent(event); end end -- create a new WIM module. Will return module object. function CreateModule(moduleName, enableByDefault) if(type(moduleName) == "string") then modules[moduleName] = { title = moduleName, enabled = false, enableByDefault = enableByDefault or false, canDisable = true, resources = { lists = lists, windows = windows, env = env, constants = constants, libs = libs, }, db = db, db_defaults = db_defaults, RegisterEvent = function(self, event) RegisterEvent(event); end, Enable = function() EnableModule(moduleName, true) end, Disable = function() EnableModule(moduleName, false) end, dPrint = function(self, t) dPrint(t); end, hasWidget = false, RegisterWidget = function(widgetName, createFunction) RegisterWidget(widgetName, createFunction, moduleName); end } return modules[moduleName]; else return nil; end end function EnableModule(moduleName, enabled) if(enabled == nil) then enabled = false; end local module = modules[moduleName]; if(module) then if(module.canDisable == false and enabled == false) then dPrint("Module '"..moduleName.."' can not be disabled!"); return; end if(db) then db.modules[moduleName] = WIM.db.modules[moduleName] or {}; db.modules[moduleName].enabled = enabled; end if(enabled) then module.enabled = enabled; if(enabled and type(module.OnEnable) == "function") then module:OnEnable(); elseif(not enabled and type(module.OnDisable) == "function") then module:OnDisable(); end dPrint("Module '"..moduleName.."' Enabled"); else if(module.hasWidget) then dPrint("Module '"..moduleName.."' will be disabled after restart."); else module.enabled = enabled; if(enabled and type(module.OnEnable) == "function") then module:OnEnable(); elseif(not enabled and type(module.OnDisable) == "function") then module:OnDisable(); end dPrint("Module '"..moduleName.."' Disabled"); end end end end function CallModuleFunction(funName, ...) -- notify all enabled modules. dPrint("Calling Module Function: "..funName); local module, tData, fun; for module, tData in pairs(WIM.modules) do fun = tData[funName]; if(type(fun) == "function" and tData.enabled) then dPrint(" +--"..module); fun(tData, ...); end end end -------------------------------------- -- Event Handlers -- -------------------------------------- function WIM.honorChatFrameEventFilter(event, ...) local arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15 = ...; local chatFilters = _G.ChatFrame_GetMessageEventFilters(event); local filter = false; if chatFilters then local narg1, narg2, narg3, narg4, narg5, narg6, narg7, narg8, narg9, narg10, narg11, narg12, narg13, narg14, narg15; for _, filterFunc in next, chatFilters do filter, narg1, narg2, narg3, narg4, narg5, narg6, narg7, narg8, narg9, narg10, narg11, narg12, narg13, narg14, narg15 = filterFunc(workerFrame, event, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15); if filter then return true, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15; elseif(narg1) then arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15 = narg1, narg2, narg3, narg4, narg5, narg6, narg7, narg8, narg9, narg10, narg11, narg12, narg13, narg14, narg15; end end end return filter, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15; end function WIM:EventHandler(event,...) -- depricated - here for compatibility only end -- This is WIM's core event controler. function WIM:CoreEventHandler(event, ...) -- Core WIM Event Handlers. dPrint("Event '"..event.."' received."); local fun = WIM[event]; if(type(fun) == "function") then dPrint(" +-- WIM:"..event); fun(WIM, ...); end -- Module Event Handlers if(db and db.enabled) then local module, tData; for module, tData in pairs(modules) do fun = tData[event]; if(type(fun) == "function" and tData.enabled) then dPrint(" +-- "..module..":"..event); fun(modules[module], ...); end end end end function WIM:VARIABLES_LOADED() _G.WIM3_Data = _G.WIM3_Data or {}; db = _G.WIM3_Data; _G.WIM3_Cache = _G.WIM3_Cache or {}; env.cache = _G.WIM3_Cache; _G.WIM3_Filters = _G.WIM3_Filters or GetDefaultFilters(); _G.WIM3_ChatFilters = _G.WIM3_ChatFilters or {}; if(#_G.WIM3_Filters == 0) then _G.WIM3_Filters = GetDefaultFilters(); end filters = _G.WIM3_Filters; chatFilters = _G.WIM3_ChatFilters; _G.WIM3_History = _G.WIM3_History or {}; history = _G.WIM3_History; -- load some environment data. env.realm = _G.GetRealmName(); env.character = _G.UnitName("player"); -- inherrit any new default options which wheren't shown in previous releases. inherritTable(db_defaults, db); lists.gm = {}; -- load previous state into memory curState = db.lastState; SetEnabled(db.enabled); initialize(); --_G.print("WIM Notice: Since 7.0 there is a new bug where first whisper is not visible until you get a 2nd whisper, or you scroll up and then back down. That's work around. Scroll up, then scroll down.") end function WIM:FRIENDLIST_UPDATE() env.cache[env.realm][env.character].friendList = env.cache[env.realm][env.character].friendList or {}; for key, d in pairs(env.cache[env.realm][env.character].friendList) do if(d == 1) then env.cache[env.realm][env.character].friendList[key] = nil; end end if _G.C_FriendList then for i=1, _G.C_FriendList.GetNumFriends() do local name = _G.C_FriendList.GetFriendInfoByIndex(i).name; if(name) then env.cache[env.realm][env.character].friendList[name] = 1; --[set place holder for quick lookup end end else for i=1, _G.GetNumFriends() do local name = _G.GetFriendInfo(i); if(name) then env.cache[env.realm][env.character].friendList[name] = 1; --[set place holder for quick lookup end end end lists.friends = env.cache[env.realm][env.character].friendList; dPrint("Friends list updated..."); end function WIM:BN_FRIEND_LIST_SIZE_CHANGED() env.cache[env.realm][env.character].friendList = env.cache[env.realm][env.character].friendList or {}; for key, d in pairs(env.cache[env.realm][env.character].friendList) do if(d == 2) then env.cache[env.realm][env.character].friendList[key] = nil; end end for i=1, _G.BNGetNumFriends() do local id, name = GetBNGetFriendInfo(i); if(name) then env.cache[env.realm][env.character].friendList[name] = 2; --[set place holder for quick lookup if(windows.active.whisper[name]) then windows.active.whisper[name]:SendWho(); end end end lists.friends = env.cache[env.realm][env.character].friendList; dPrint("RealID list updated..."); end WIM.BN_FRIEND_INFO_CHANGED = WIM.BN_FRIEND_LIST_SIZE_CHANGED; function WIM:GUILD_ROSTER_UPDATE() env.cache[env.realm][env.character].guildList = env.cache[env.realm][env.character].guildList or {}; for key, _ in pairs(env.cache[env.realm][env.character].guildList) do env.cache[env.realm][env.character].guildList[key] = nil; end if(_G.IsInGuild()) then for i=1, _G.GetNumGuildMembers(true) do local name = _G.GetGuildRosterInfo(i); if(name) then name = Ambiguate(name, "none") env.cache[env.realm][env.character].guildList[name] = i; --[set place holder for quick lookup end end end lists.guild = env.cache[env.realm][env.character].guildList; dPrint("Guild list updated..."); end function IsGM(name) if(name == nil or name == "") then return false; end -- Blizz gave us a new tool. Lets use it. if(_G.GMChatFrame_IsGM and _G.GMChatFrame_IsGM(name)) then lists.gm[name] = 1; return true; end if(lists.gm[name]) then return true; else return false; end end function IsInParty(user) for i=1, 4 do if(_G.GetUnitName("party"..i, true) == user) then return true; end end return false; end function IsInRaid(user) for i=1, _G.GetNumGroupMembers() do if(_G.GetUnitName("raid"..i, true) == user) then return true; end end return false; end function CompareVersion(v, withV) withV = withV or version; local M, m, r = string.match(v, "(%d+).(%d+).(%d+)"); local cM, cm, cr = string.match(withV, "(%d+).(%d+).(%d+)"); M, m = M*100000, m*1000; cM, cm = cM*100000, cm*1000; local this, that = cM+cm+cr, M+m+r; return that - this; end local talentOrder = {}; function TalentsToString(talents, class) --passed talents in format of "#/#/#"; -- first check that all required information is passed. local t1, t2, t3 = string.match(talents or "", "(%d+)/(%d+)/(%d+)"); if(not t1 or not t2 or not t3 or not class) then return talents; end -- next check if we even have information to show. if(talents == "0/0/0") then return L["None"]; end local classTbl = constants.classes[class]; if(not classTbl) then return talents; end -- clear talentOrder for k, _ in pairs(talentOrder) do talentOrder[k] = nil; end --calculate which order the tabs should be in; in relation to spec. table.insert(talentOrder, t1.."1"); table.insert(talentOrder, t2.."2"); table.insert(talentOrder, t3.."3"); table.sort(talentOrder); local fVal, f = string.match(_G.tostring(talentOrder[3]), "^(%d+)(%d)$"); local sVal, s = string.match(_G.tostring(talentOrder[2]), "^(%d+)(%d)$"); local tVal, t = string.match(_G.tostring(talentOrder[1]), "^(%d+)(%d)$"); if(_G.tonumber(fVal)*.75 <= _G.tonumber(sVal)) then if(_G.tonumber(fVal)*.75 <= _G.tonumber(tVal)) then return L["Hybrid"]..": "..talents; else return classTbl.talent[_G.tonumber(f)].."/"..classTbl.talent[_G.tonumber(s)]..": "..talents; end else return classTbl.talent[_G.tonumber(f)]..": "..talents; end end function GetTalentSpec() local talents, tabs = "", _G.GetNumTalentTabs(); for i=1, tabs do local name, _, _, _, pointsSpent = _G.GetTalentTabInfo(i); talents = i==tabs and talents..pointsSpent or talents..pointsSpent.."/"; end return talents ~= "" and talents or "0/0/0"; end -- list of PreSendFilterText(text) local preSendFilterTextFunctions = {}; function PreSendFilterText(text) for i=1, #preSendFilterTextFunctions do text = preSendFilterTextFunctions[i](text); end return text; end function RegisterPreSendFilterText(func) if(type(func) == "function") then table.insert(preSendFilterTextFunctions, func); end end --[[ Example usage RegisterPreSendFilterText( function(text) return "john"; end ); ]]
--[[/* * (C) 2012-2013 Marmalade. * * 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. */--]] -------------------------------------------------------------------------------- -- Director singleton -------------------------------------------------------------------------------- director = quick.QDirector:new() getmetatable(director).__serialize = function(o) local obj = serializeTLMT(getmetatable(o), o) return obj end -------------------------------------------------------------------------------- -- Private API -------------------------------------------------------------------------------- -- Update display info function directorUpdateDisplayInfo(dw, dh) dbg.assertFuncVarTypes({"number", "number"}, dw, dh) director:_updateDisplayInfo(dw, dh) end -- Purge everything function director:_purge() -- Replacing the global scene will force the old one to be GC'd director.globalScene = director:createScene({name="globalScene"}) collectgarbage("collect") collectgarbage("collect") end -- Overall update --Recursions for director:update() below function director:_updateNodeAndChildren(n, dt, alphaMul, strokeAlphaMul) dbg.assertFuncVarType("userdata", n) dbg.assertFuncVarType("number", dt) -- Update node tweens if n._tweensPaused == false then n:updateTweens(dt * n._tweensTimeScale) end -- Update node timers if n._timersPaused == false then QTimer:updateTimers(n.timers, dt * n._timersTimeScale) end n._alphaInternal = n.alpha * alphaMul if director.isAlphaInherited == true then alphaMul = alphaMul * n.alpha end if n._strokeAlphaInternal then n._strokeAlphaInternal = n.strokeAlpha * strokeAlphaMul if director.isAlphaInherited == true then strokeAlphaMul = strokeAlphaMul * n.strokeAlpha end end -- Update children for i,v in ipairs(n.children) do self:_updateNodeAndChildren(v, dt, alphaMul, strokeAlphaMul) end end function director:_syncNodeAndChildren(n, dt) dbg.assertFuncVarType("userdata", n) dbg.assertFuncVarType("number", dt) -- Sync n:sync() -- Sync children for i,v in ipairs(n.children) do self:_syncNodeAndChildren(v, dt) end end -- Called from QSystemObject::Update() function director:update() -- Update global timers if system._timersPaused == false then QTimer:updateTimers(system.timers, system.deltaTime * system._timersTimeScale) end local o = director:getOverlayScene() -- Update overlay scene graph if o ~= nil then local keepQueue = true if director:isOverlayModal() == true then keepQueue = false end handleEventQueue(o, keepQueue) director:_updateNodeAndChildren(o, system.deltaTime, 1, 1) -- Sync scene graph director:_syncNodeAndChildren(o, system.deltaTime) end local s = director:getCurrentScene() handleEventQueue(s, false) -- Update scene graph (but don't sync) director:_updateNodeAndChildren(s, system.deltaTime, 1, 1) -- Sync scene graph director:_syncNodeAndChildren(s, system.deltaTime) -- Sync web views if nui then nui:_syncWebViews() end -- Process instant scene changes without event locks getting in the way of -- the tearDown process director:_processInstantSceneChange() end --[[ /* Create a tween object. We use a factory method to create these, so we can ensure that QTween:initTween is called, which sets up the Lua peer table for the C++ userdata object. @return A tween object. */ --]] function director:createTween() local t = quick.QTween() QTween:initTween(t) return t end --[[ /** -- Called to complete an overlay scene Throws the following events: <overlay> - exitPostTransition <overlay> - tearDown <current scene> - overlayEnd */ --]] function director:_overlayComplete() if self._overlayTransitionType ~= "" then local exitPostTransitionEvent = QEvent:create("exitPostTransition") self._overlayScene:handleEvent(exitPostTransitionEvent) end self:_updateNodeAndChildren(self._overlayScene, 0, 1, 1) self:_syncNodeAndChildren(self._overlayScene, 0) if self._overlayScene.isSetUp == true then local tearDownEvent = QEvent:create("tearDown", { nopropagation = true }) self._overlayScene:handleEvent(tearDownEvent) self._overlayScene.isSetUp = false end -- Perform a bit of GC collectgarbage("collect") self:cleanupTextures() -- Send an event to current scene local overlayEndEvent = QEvent:create("overlayEnd", { nopropagation = true }) self.currentScene:handleEvent(overlayEndEvent) end -- Called to complete a scene transition function director:_transitionComplete() -- dbg.print("director:_transitionComplete") if self._outgoingScene ~= nil then -- Send events to current scene -- dbg.print("exitPostTransition") local exitPostTransitionEvent = QEvent:create("exitPostTransition") self._outgoingScene:handleEvent(exitPostTransitionEvent) if self._outgoingScene.isSetUp == true then -- dbg.print("tearDown") local tearDownEvent = QEvent:create("tearDown", { nopropagation = true }) self._outgoingScene:handleEvent(tearDownEvent) self._outgoingScene.isSetUp = false end self._outgoingScene = nil end self:setCurrentScene( self._incomingScene) -- Perform a bit of GC so we can load the new scene collectgarbage("collect") self:cleanupTextures() if self._incomingScene ~= nil then -- Send events to new scene local enterPostTransitionEvent = QEvent:create("enterPostTransition", { nopropagation = true }) self._incomingScene:handleEvent(enterPostTransitionEvent) self._incomingScene = nil end end function director:setCurrentScene(scene) -- dbg.print("director:setCurrentScene") -- nil will set the global scene if scene == nil then scene = director.globalScene -- dbg.print("director.globalScene is " .. scene or "nil") end dbg.assertFuncUserDataType("quick::QScene", scene) -- Store the LUA reference to the current scene self.currentScene = scene -- Pass it down to the CPP code as well (as this dosn't count as a LUA reference) self._currentScene = scene end -- Processing of instant scene changes function director:_processInstantSceneChange() if self._newScene ~= nil then -- Tear down the old scene if self.currentScene.isSetUp == true then local tearDownEvent = QEvent:create("tearDown", { nopropagation = true }) self.currentScene:handleEvent(tearDownEvent) self.currentScene.isSetUp = false end -- Flip to the new scene self:setCurrentScene( self._newScene) -- Perform a bit of GC so we can load the new scene collectgarbage("collect") self:cleanupTextures() if self._newScene.isSetUp == false then -- dbg.print("Performing new scene setup on scene: " .. self._newScene.name) local setUpEvent = QEvent:create("setUp", { nopropagation = true }) self._newScene:handleEvent(setUpEvent) self._newScene.isSetUp = true end -- Clear the new scene pointer self._newScene = nil end end -------------------------------------------------------------------------------- -- Public API -------------------------------------------------------------------------------- --[[ /** Gets the currently active scene */ --]] function director:getCurrentScene() -- Get the current scene from LUA side return self.currentScene end --[[ /** Gets the current overlay scene */ --]] function director:getOverlayScene() -- Get the current scene from LUA side return self._overlayScene end --[[ /** Check if the overlay modal */ --]] function director:isOverlayModal() return self._modalOverlay end --[[ /** Remove a node from its scene. @param n The node to remove. */ --]] function director:removeNode(n) dbg.assertFuncVarType("userdata", n) n:setParent(nil) end function director:addNodeToLists(n) dbg.assertFuncVarType("userdata", n) if self.addNodesToScene == true then local sc = self:getCurrentScene() dbg.assert(sc, "No current scene") sc:addChild(n) end end --[[ /** Set the default color for newly created nodes. @param r The red component of the color. @param g The green component of the color. @param b The blue component of the color. */ --]] function director:setNodesColor(r, g, b, a) dbg.assertFuncVarTypes({"number", "number", "number", "number"}, r, g, b, a) self.nodesColor.r = r or 255 self.nodesColor.g = g or 255 self.nodesColor.b = b or 255 self.nodesColor.a = a or 255 end -------------------------------------------------------------------------------- -- Public API - factory functions -------------------------------------------------------------------------------- -- THESE HAVE NOW BEEN MOVED TO THE RESPECTIVE OBJECT FILES -- E.G. director:createNode() is defined in QNode.lua --[[ /** Create a bounding box object, from x and y bounds. @param xMin Local minimum x value. @param xMax Local maximum x value. @param yMin Local minimum y value. @param yMax Local maximum y value. @return The created bounding box object. */ --]] function director:createBBox(_xMin, _xMax, _yMin, _yMax) dbg.assertFuncVarTypes({"number", "number", "number", "number"}, _xMin, _xMax, _yMin, _yMax) local bb = {xMin=_xMin, xMax=_xMax, yMin=_yMin, yMax=_yMax} return bb end ---------------------------------- -- Scenes ---------------------------------- --[[ /** Move to a new scene. Throws the following events: <new scene> - setUp (only if the new scene is not already set up) <new scene> - enterPreTransition <current scene> - exitPreTransition @param newScene The new Scene object to move to @param options A table of options, e.g. "transition", "time" */ --]] function director:moveToScene(newScene, options) -- Check if we are moving to the default scene if newScene == nil then -- dbg.print("moveToScene(nil)") newScene = self.globalScene end dbg.assertFuncUserDataType("quick::QScene", newScene) dbg.assertFuncVarTypes({"table", "nil"}, options) -- If this is the same as the current scene, then bail at this point local oldScene = self.currentScene if newScene == oldScene then dbg.print("Already in target scene") return end -- Set details of transition self._transitionScene = newScene self._transitionTime = 0 self._transitionType = "" if options ~= nil then -- get transition information self._transitionTime = options.transitionTime or 0 self._transitionType = options.transitionType or "" end if self._transitionType ~= "" then -- this is a timed transition -- dbg.print("Timed transition to " .. newScene.name) -- Send events to new scene -- NOTE: We temporarily set director.currentScene to this scene, so that the setUp function -- can assume newly created objects will get added to this scene self.currentScene = newScene if newScene.isSetUp == false then local setUpEvent = QEvent:create("setUp", { nopropagation = true }) newScene:handleEvent(setUpEvent) newScene.isSetUp = true end local enterPreTransitionEvent = QEvent:create("enterPreTransition", { nopropagation = true }) newScene:handleEvent(enterPreTransitionEvent) self.currentScene = oldScene -- Once we've called enterPreTransition on the new scene, we should sync() that scene graph once -- so that stuff is in the right place as it's getting transitioned in. We pass a deltaTime of 0 self:_updateNodeAndChildren(newScene, 0, 1, 1) self:_syncNodeAndChildren(newScene, 0) -- Send events to current scene local exitPreTransitionEvent = QEvent:create("exitPreTransition", { nopropagation = true }) oldScene:handleEvent(exitPreTransitionEvent) -- LUA side storage for usage in _transitionComplete self._outgoingScene = oldScene self._incomingScene = newScene else -- this is actually an instant transition -- dbg.print("Instant transition to " .. newScene.name) -- no need to actually do a transition self._transitionScene = nil -- Queue up a scene change for next update self._newScene = newScene end end --[[ /** Show a scene on the top of current one. Throws the following events: <overlay scene> - setUp (only if the overlay scene is not already set up) <overlay scene> - enterPreTransition <current scene> - overlayBegin @param newScene The new Scene object to show @param options A table of options, e.g. "transition", "time" */ --]] function director:showOverlay(overlayScene, options) dbg.assertFuncUserDataType("quick::QScene", overlayScene) dbg.assertFuncVarTypes({"table", "nil"}, options) -- Do not show another overlay until current hidden if self._overlayScene ~= nil or self._overlayTransitionScene ~= nil then dbg.print("An overlay already shown") return end -- Cannot show the current scene if overlayScene == self._currentScene then dbg.print("The overlay is current scene") return end -- Set details of transition self._overlayTransitionScene = overlayScene self._overlayTransitionTime = 0 self._overlayTransitionType = "" self._modalOverlay = false local oldScene = self.currentScene if options ~= nil then -- Get transition information self._overlayTransitionTime = options.transitionTime or 0 self._overlayTransitionType = options.transitionType or "" self._modalOverlay = options.isModal or false end self.currentScene = overlayScene if overlayScene.isSetUp == false then local setUpEvent = QEvent:create("setUp", { nopropagation = true }) overlayScene:handleEvent(setUpEvent) overlayScene.isSetUp = true end self.currentScene = oldScene if self._overlayTransitionType ~= "" then local enterPreTransitionEvent = QEvent:create("enterPreTransition", { nopropagation = true }) overlayScene:handleEvent(enterPreTransitionEvent) -- Once we've called enterPreTransition on the new scene, we should sync() that scene graph once -- so that stuff is in the right place as it's getting transitioned in. We pass a deltaTime of 0 self:_updateNodeAndChildren(overlayScene, 0, 1, 1) self:_syncNodeAndChildren(overlayScene, 0) else -- no need to actually do a transition self._overlayTransitionScene = overlayScene end -- Send events to current scene local overlayBeginEvent = QEvent:create("overlayBegin", { nopropagation = true }) self.currentScene:handleEvent(overlayBeginEvent) end --[[ /** Hide the overlay Throws the following events: <overlay> - exitPreTransition @param options A table of options, e.g. "transition", "time" */ --]] function director:hideOverlay(options) -- Hide if the overlay if self._overlayScene == nil then dbg.print("The overlay is not shown") return end -- Set details of transition self._overlayTransitionTime = 0 self._overlayTransitionType = "" if options ~= nil then -- Get transition information self._overlayTransitionTime = options.transitionTime or 0 self._overlayTransitionType = options.transitionType or "" end if self._overlayTransitionType ~= "" then local enterPreTransitionEvent = QEvent:create("exitPreTransition", { nopropagation = true }) self._overlayScene:handleEvent(enterPreTransitionEvent) end self._overlayTransitionScene = self._overlayScene end
local enemy = {} enemy.__index = enemy local maxSpeed = 350 local accSpeed = 500 local function new(x, y) x = x or 0 y = y or 0 return setmetatable({ x = x, y = y, r = 10, dx = 0, dy = 0, timer = 0, keys = {}, hp = 100, hpRegen = 1, minDmg = -5, maxDmg = -10, invTimer = 0}, enemy) end function enemy:draw() love.graphics.setColor(0.7, 0.1, 0.1) love.graphics.circle( 'fill', self.x, self.y, self.r) love.graphics.print(math.floor(self.hp), self.x, self.y) end function enemy:update(dt, field) self.timer = self.timer - dt self.invTimer = self.invTimer - dt self.hp = math.min(self.hp + self.hpRegen * dt, 100) if self.timer < 0 then self.timer = 0.2 self.keys = { ["w"] = love.math.random(0, 1) == 1, ["s"] = love.math.random(0, 1) == 1, ["d"] = love.math.random(0, 1) == 1, ["a"] = love.math.random(0, 1) == 1, } end if self.keys['w'] then self.dy = self.dy - accSpeed * dt end if self.keys['s'] then self.dy = self.dy + accSpeed * dt end if self.keys['a'] then self.dx = self.dx - accSpeed * dt end if self.keys['d'] then self.dx = self.dx + accSpeed * dt end if self.dx > maxSpeed then self.dx = maxSpeed elseif self.dx < -maxSpeed then self.dx = -maxSpeed end if self.dy > maxSpeed then self.dy = maxSpeed elseif self.dy < -maxSpeed then self.dy = -maxSpeed end local newX = self.x + self.dx * dt local newY = self.y + self.dy * dt if field:isWalkable(newX, newY) >= 0 then self.x = newX self.y = newY elseif field:isWalkable(self.x, newY) >= 0 then self.y = newY self.dx = 0 elseif field:isWalkable(newX, self.y) >= 0 then self.x = newX self.dy = 0 end end function enemy:getDmg() return love.math.random(self.minDmg, self.maxDmg) end function enemy:hit(dmg) if self.invTimer <= 0 then self.hp = self.hp - dmg self.invTimer = 0.1 return dmg end return 0 end function enemy:alive() return self.hp > 0 end return setmetatable({new = new}, {__call = function(_, ...) return new(...) end})
--[=========================================================================[ ZSS v1.0.1 See http://github.com/Phrogz/ZSS for usage documentation. Licensed under MIT License. See https://opensource.org/licenses/MIT for details. --]=========================================================================] local ZSS = { VERSION="1.0.1", debug=print, info=print, warn=print, error=print, ANY_VALUE={}, NIL_VALUE={} } local updaterules, updateconstantschain, dirtyblocks -- ZSS:new{ -- constants = { none=false, transparent=processColor(0,0,0,0), color=processColor }, -- directives = { ['font-face']=processFontFaceRule }, -- basecss = [[...css code...]], -- files = { 'a.css', 'b.css' }, -- } function ZSS:new(opts) local style = { _directives = {}, -- map from name of at rule (without @) to function to invoke _constants = {}, -- value literal strings mapped to equivalent values (e.g. "none"=false) _sheets = {}, -- array of sheetids, also mapping sheetid to its active state _sheetconst = {}, -- map of sheetid to table of constants for that sheet _sheetblocks = {}, -- map of sheetid to table of blocks underlying the constants _envs = {}, -- map of sheetid to table that mutates to evaluate functions _rules = {}, -- map of sheetids to array of rule tables, each sorted by document order _lookup = {}, -- rules for active sheets indexed by type, then by id (with 'false' indicating no type or id) _kids = setmetatable({},{__mode='k'}), -- set of child tables mapped to true _parent = nil, -- reference to the style instance that spawned this one } style._envs[1] = setmetatable({},{__index=style._constants}) setmetatable(style,{__index=self}) style:directives{ -- Process @vars { foo:42 } with sheet ordering and chaining vars = function(self, values, sheetid, blocks) local consts = self._sheetconst[sheetid] local blocksforthissheet = self._sheetblocks[sheetid] if not blocksforthissheet then blocksforthissheet = {} self._sheetblocks[sheetid] = blocksforthissheet end -- iterate over blocks instead of values, in case a value is nil for k,v in pairs(blocks) do consts[k] = values[k] blocksforthissheet[k] = blocks[k] end end } if opts then if opts.constants then style:constants(opts.constants,true) end if opts.directives then style:directives(opts.directives) end if opts.basecss then style:add(opts.basecss, 'basecss') end if opts.files then style:load(table.unpack(opts.files)) end end updaterules(style) return style end -- Usage: myZSS:load( 'file1.css', 'file2.css', ... ) function ZSS:load(...) self._deferupdate = true for _,filename in ipairs{...} do local file = io.open(filename) if file then self:add(file:read('*all'), filename) file:close() else error("Could not load CSS file '"..filename.."'.") end end updaterules(self) self._deferupdate = false return self end -- Usage: myZSS:constants{ none=false, transparent=color(0,0,0,0), rgba=color.makeRGBA } function ZSS:constants(valuemap, preserveCaches) for k,v in pairs(valuemap) do self._constants[k]=v end if not preserveCaches then dirtyblocks(self) end return self end function ZSS:directives(handlermap) for k,v in pairs(handlermap) do self._directives[k]=v end return self end -- Turn Lua code into function blocks that return the value function ZSS:compile(str, sheetid, property) local dynamic = str:find('@[%a_][%w_]*') or str:find('^!') local env = self._envs[sheetid] or self._envs[1] local func,err = load('return '..str:gsub('@([%a_][%w_]*)','_data_.%1'):gsub('^!',''), str, 't', env) if not func then self.error(("Error compiling CSS expression for '%s' in '%s': %s"):format(property, sheetid, err)) else -- [1] will hold the actual cached value (deferred until the first request) -- [2] is whether or not a cached value exists in [1] (needed in case the computed value is nil) -- [3] is the environment of the function (cached for convenient lookup) -- [4] is the function that produces the value -- [5] indicates if the block must be computed each time, or may be cached -- [6] is the sheetid (used for evaluation error messages) -- [7] is the name of the property being evaluated (used for evaluation error messages) return {nil,false,env,func,dynamic,sheetid,property,zssblock=true} end end -- Compute the value for a block function ZSS:eval(block, data, ignorecache) if block[2] and not ignorecache then return block[1] end block[3]._data_ = data -- may be nil; important to clear out from previous eval local ok,valOrError = pcall(block[4]) if ok then if not block[5] then block[2]=true block[1]=valOrError end return valOrError else self.error(("Error evaluating CSS value for '%s' in '%s': %s"):format(block[7], block[6], valOrError)) end end -- Convert a selector string into its component pieces; function ZSS:parse_selector(selector_str, sheetid) local selector = { type = selector_str:match('^@?[%a_][%w_-]*') or false, id = selector_str:match('#([%a_][%w_-]*)') or false, tags={}, data={} } local tagrank = 0 -- Find all the tags for name in selector_str:gmatch('%.([%a_][%w_-]*)') do selector.tags[name] = true tagrank = tagrank + 1 end -- Find all attribute sections, e.g. [@attr], [@attr<17], [attr=12], … for attr in selector_str:gmatch('%[%s*(.-)%s*%]') do local attr_name_only = attr:match('^@?([%a_][%w_-]*)$') if attr_name_only then selector.data[attr_name_only] = ZSS.ANY_VALUE tagrank = tagrank + 1 else local name, op, val = attr:match('^@([%a_][%w_-]*)%s*(==)%s*(.-)$') if name then local value = self:eval(self:compile(val, sheetid, selector_str)) selector.data[name] = value==nil and ZSS.NIL_VALUE or value else selector.data[attr] = self:compile(attr, sheetid, selector_str) end -- attribute selectors with comparisons count slightly more than bare attributes or tags tagrank = tagrank + 1.001 end end selector.rank = { selector.id and 1 or 0, tagrank, selector.type and 1 or 0, 0 -- the document order will be determined during updaterules() } return selector end -- Add a block of raw CSS rules (as a single string) to the style sheet -- Returns the sheet itself (for chaining) and id associated with the css (for later enable/disable) function ZSS:add(css, sheetid) sheetid = sheetid or 'css#'..(#self:sheetids()+1) local newsheet = not self._rules[sheetid] if newsheet then table.insert(self._sheets, sheetid) self._sheets[sheetid] = true self._sheetconst[sheetid] = setmetatable({},{__index=self._constants}) self._envs[sheetid] = setmetatable({},{__index=self._sheetconst[sheetid]}) -- inherit from the last active sheet in the chain for i=#self._sheets-1,1,-1 do if self._sheets[self._sheets[i]] then getmetatable(self._sheetconst[sheetid]).__index = self._sheetconst[self._sheets[i]] break end end end self._rules[sheetid] = {} for rule_str in css:gsub('/%*.-%*/',''):gmatch('[^%s][^{]+%b{}') do -- Convert declarations into a table mapping property to block local decl_str = rule_str:match('[^{]*(%b{})'):sub(2,-2) local blocks = {} for key,val in decl_str:gmatch('([^%s:;]+)%s*:%s*([^;]+)') do blocks[key] = self:compile(val, sheetid, key) end -- Create a unique rule for each selector in the rule local selectors_str = rule_str:match('(.-)%s*{') for selector_str in selectors_str:gmatch('%s*([^,]+)') do -- Check if this is a directive (at-rule) that needs processing local name = selector_str:match('^%s*@([%a_][%w_-]*)%s*$') if name and self._directives[name] then -- bake value blocks into values before handing off local values = {} for k,block in pairs(blocks) do values[k] = self:eval(block) end self._directives[name](self, values, sheetid, blocks) end local selector = self:parse_selector(selector_str:match "^%s*(.-)%s*$", sheetid) if selector then local rule = {selector=selector, declarations=blocks, doc=sheetid, selectorstr=selector_str} table.insert(self._rules[sheetid], rule) end end end -- sort rules and determine active based on rank if not self._deferupdate then updaterules(self) end return self, sheetid end -- Given an element table, compute the declaration(s) that apply. For example: -- local values = myZSS:match{tags={ped=1}} -- local values = myZSS:match{type='text', id='accel', tags={label=1}} -- local values = myZSS:match{type='text', id='accel', tags={value=1, negative=1}, value=-0.3} function ZSS:match(el) local placeholders, data local result, sortedrules, ct = {}, {}, 0 local function checkrules(rules) for _,rule in ipairs(rules) do local sel = rule.selector for tag,_ in pairs(sel.tags) do -- TODO: handle anti-tags in the selector, where _==false if not (el.tags and el.tags[tag]) then goto skiprule end end for name,desired in pairs(sel.data) do if type(desired)=='table' and desired.zssblock then if not self:eval(desired, el, true) then goto skiprule end else local actual = el[name] if desired==ZSS.NIL_VALUE then if actual~=nil then goto skiprule end elseif desired==ZSS.ANY_VALUE then if actual==nil then goto skiprule end else if actual~=desired then goto skiprule end end end end ct = ct + 1 sortedrules[ct] = rule ::skiprule:: end end local function addfortype(byid) if el.id and byid[el.id] then addforid(byid[el.id]) end if byid[false] then addforid(byid[false]) end end -- check rules that specify this element's type local byid = el.type and self._lookup[el.type] if byid then -- check rules that specify this element's id if el.id and byid[el.id] then checkrules(byid[el.id]) end -- check rules that don't care about the element id if byid[false] then checkrules(byid[false]) end end -- check rules that don't care about the element type local byid = self._lookup[false] if byid then -- check rules that specify this element's id if el.id and byid[el.id] then checkrules(byid[el.id]) end -- check rules that don't care about the element id if byid[false] then checkrules(byid[false]) end end if ct>1 then table.sort(sortedrules, function(r1, r2) r1,r2 = r1.selector.rank,r2.selector.rank if r1[1]<r2[1] then return true elseif r1[1]>r2[1] then return false elseif r1[2]<r2[2] then return true elseif r1[2]>r2[2] then return false elseif r1[3]<r2[3] then return true elseif r1[3]>r2[3] then return false elseif r1[4]<r2[4] then return true else return false end end) end -- merge the declarations from the rules in order for _,rule in ipairs(sortedrules) do for k,block in pairs(rule.declarations) do result[k] = block end end -- Convert blocks to values (honoring cached values) for k,block in pairs(result) do result[k] = self:eval(block, el) end return result end function ZSS:extend(...) local kid = self:new() kid._parent = self -- getmetatable(kid).__index = self setmetatable(kid._constants, {__index=self._constants}) setmetatable(kid._directives,{__index=self._directives}) setmetatable(kid._envs,{__index=self._envs}) self._kids[kid] = true kid:load(...) return kid end function ZSS:sheetids() local ids = self._parent and self._parent:sheetids() or {} table.move(self._sheets, 1, #self._sheets, #ids+1, ids) for _,id in ipairs(self._sheets) do ids[id] = true end return ids end function ZSS:disable(sheetid) local ids = self:sheetids() if ids[sheetid] then self._sheets[sheetid] = false updaterules(self) updateconstantschain(self) dirtyblocks(self,sheetid) else local quote='%q' for i,id in ipairs(ids) do ids[i] = quote:format(id) end self.warn(("Cannot disable() CSS with id '%s' (no such sheet loaded).\nAvailable sheet ids: %s"):format(sheetid, table.concat(ids, ", "))) end end function ZSS:enable(sheetid) if self._rules[sheetid] then self._sheets[sheetid] = true updaterules(self) updateconstantschain(self) dirtyblocks(self,sheetid) elseif self._sheets[sheetid]~=nil then -- wipe out a local override that may have been disabling an ancestor self._sheets[sheetid] = nil updaterules(self) updateconstantschain(self) dirtyblocks(self,sheetid) else local disabled = {} local quote='%q' for id,state in pairs(self._sheets) do if state==false then table.insert(disabled, quote:format(id)) end end if #disabled==0 then self.warn(("Cannot enable() CSS with id '%s' (no sheets are disabled)."):format(sheetid)) else self.warn(("Cannot enable() CSS with id '%s' (no such sheet disabled).\nDisabled ids: %s"):format(sheetid, table.concat(disabled, ", "))) end end end updaterules = function(self) -- reset the lookup cache self._lookup = {} local rulesadded = 0 -- add all rules from the parent style if self._parent then for type,rulesfortype in pairs(self._parent._lookup) do local byid = self._lookup[type] if not byid then byid = {} self._lookup[type] = byid end for id,rulesforid in pairs(rulesfortype) do local rules = byid[id] if not rules then rules = {} byid[id] = rules end for i=1,#rulesforid do local rule = rulesforid[i] -- do not use rule if we set its document inactive if self._sheets[rule.doc]~=false then rules[#rules+1] = rule rulesadded = rulesadded + 1 end end end end end -- add all the rules from this style's active sheets for _,sheetid in ipairs(self._sheets) do if self._sheets[sheetid] then for _,rule in ipairs(self._rules[sheetid]) do local byid = self._lookup[rule.selector.type] if not byid then byid = {} self._lookup[rule.selector.type] = byid end local rulesforid = byid[rule.selector.id] if not rulesforid then rulesforid = {} byid[rule.selector.id] = rulesforid end rulesforid[#rulesforid+1] = rule rulesadded = rulesadded + 1 rule.selector.rank[4] = rulesadded end end end -- ensure that any extended children are updated for kid,_ in pairs(self._kids) do updaterules(kid) end end updateconstantschain = function(self) local lastactive = self._constants for _,sheetid in ipairs(self._sheets) do -- If the sheet is active, put it into the chain if self._sheets[sheetid] then local sheetconst = self._sheetconst[sheetid] getmetatable(sheetconst).__index = lastactive lastactive = sheetconst end end end dirtyblocks = function(self, sheetid) local dirtythissheet = not sheetid for _,id in ipairs(self._sheets) do if id==sheetid then dirtythissheet=true end if dirtythissheet then for _,rule in ipairs(self._rules[id]) do for k,block in pairs(rule.declarations) do block[2]=false end end if self._sheetblocks[id] then for k,block in pairs(self._sheetblocks[id]) do self._sheetconst[id][k] = self:eval(block,nil,true) end end end end for kid,_ in pairs(self._kids) do dirtyblocks(kid) end end return ZSS
local Parser = {} Parser.kind = {} local kindSeed = 0 local kind2Txt = {} local function regKind( name ) local kind = kindSeed kindSeed = kindSeed + 1 kind2Txt[ kind ] = name Parser.kind[ name ] = kind return kind end local kindCmnt = regKind( "Cmnt" ) local kindStr = regKind( "Str" ) local kindInt = regKind( "Int" ) local kindReal = regKind( "Real" ) local kindChar = regKind( "Char" ) local kindSymb = regKind( "Symb" ) local kindDlmt = regKind( "Dlmt" ) local kindKywd = regKind( "Kywd" ) local kindOpe = regKind( "Ope" ) local kindType = regKind( "Type" ) local kindEof = regKind( "EOF" ) local quotedCharSet = {} quotedCharSet[ 'a' ] = true quotedCharSet[ 'b' ] = true quotedCharSet[ 'f' ] = true quotedCharSet[ 'n' ] = true quotedCharSet[ 'r' ] = true quotedCharSet[ 't' ] = true quotedCharSet[ 'v' ] = true quotedCharSet[ '\\' ] = true quotedCharSet[ '"' ] = true quotedCharSet[ "'" ] = true local op2Set = {} op2Set[ '+' ] = true op2Set[ '-' ] = true op2Set[ '*' ] = true op2Set[ '/' ] = true op2Set[ '//' ] = true op2Set[ '^' ] = true op2Set[ '%' ] = true op2Set[ '&' ] = true op2Set[ '~' ] = true op2Set[ '|' ] = true op2Set[ '>>' ] = true op2Set[ '<<' ] = true op2Set[ '..' ] = true op2Set[ '<' ] = true op2Set[ '<=' ] = true op2Set[ '>' ] = true op2Set[ '>=' ] = true op2Set[ '==' ] = true op2Set[ '~=' ] = true op2Set[ 'and' ] = true op2Set[ 'or' ] = true op2Set[ '@' ] = true op2Set[ '=' ] = true local op1Set = {} op1Set[ '-' ] = true op1Set[ 'not' ] = true op1Set[ '#' ] = true op1Set[ '~' ] = true op1Set[ '*' ] = true local function createReserveInfo( luaMode ) local keywordSet = {} local typeSet = {} local builtInSet = {}; keywordSet[ "local" ] = true keywordSet[ "function" ] = true keywordSet[ "if" ] = true keywordSet[ "else" ] = true keywordSet[ "elseif" ] = true keywordSet[ "while" ] = true keywordSet[ "for" ] = true keywordSet[ "in" ] = true keywordSet[ "return" ] = true keywordSet[ "break" ] = true keywordSet[ "nil" ] = true keywordSet[ "true" ] = true keywordSet[ "false" ] = true builtInSet[ "require" ] = true if luaMode then keywordSet[ "end" ] = true keywordSet[ "then" ] = true keywordSet[ "do" ] = true keywordSet[ "until" ] = true else keywordSet[ "let" ] = true keywordSet[ "mut" ] = true keywordSet[ "pub" ] = true keywordSet[ "pro" ] = true keywordSet[ "pri" ] = true keywordSet[ "fn" ] = true keywordSet[ "each" ] = true keywordSet[ "form" ] = true keywordSet[ "class" ] = true keywordSet[ "static" ] = true keywordSet[ "advertise" ] = true keywordSet[ "as" ] = true keywordSet[ "import" ] = true keywordSet[ "new" ] = true builtInSet[ "super" ] = true typeSet[ "int" ] = true typeSet[ "real" ] = true typeSet[ "stem" ] = true typeSet[ "str" ] = true typeSet[ "Map" ] = true typeSet[ "bool" ] = true end -- 2文字以上の演算子 local multiCharDelimitMap = {} multiCharDelimitMap[ "=" ] = { "==" } multiCharDelimitMap[ "~" ] = { "~=" } multiCharDelimitMap[ "<" ] = { "<=" } multiCharDelimitMap[ ">" ] = { ">=" } multiCharDelimitMap[ "." ] = { ".." } multiCharDelimitMap[ "@" ] = { "@@" } multiCharDelimitMap[ "@@" ] = { "@@?" } multiCharDelimitMap[ ".." ] = { "..." } return keywordSet, typeSet, multiCharDelimitMap end function Parser.getKindTxt( kind ) return kind2Txt[ kind ] end function Parser.isOp2( ope ) return op2Set[ ope ] end function Parser.isOp1( ope ) return op1Set[ ope ] end local ParserMtd = { } function Parser:create( path, luaMode ) local stream = io.open( path, "r" ) if not stream then return nil end local obj = { stream = stream, lineNo = 0, pos = 1, lineTokenList = {}, } setmetatable( obj, { __index = ParserMtd } ) local keywordSet, typeSet, multiCharDelimitMap = createReserveInfo( luaMode or string.find( path, "%.lua$" ) ) obj.keywordSet = keywordSet obj.typeSet = typeSet obj.multiCharDelimitMap = multiCharDelimitMap return obj end function ParserMtd:parse() local function readLine() self.lineNo = self.lineNo + 1 return self.stream:read( '*l' ) end local rawLine = readLine() if not rawLine then return nil end local list = {} local startIndex = 1 --[[ 複数行コメントの処理。 @param comIndex 現在の解析行内の複数行コメント開始位置 @param termStr 複数行コメントの終端文字列 ]] local multiComment = function( comIndex, termStr ) local searchIndex = comIndex local comment = "" while true do local termIndex, termEndIndex = string.find( rawLine, termStr, searchIndex, true ) if termIndex then comment = comment .. rawLine:sub( searchIndex, termEndIndex ) return comment, termEndIndex + 1 end comment = comment .. rawLine:sub( searchIndex ) .. "\n" searchIndex = 1 rawLine = readLine() if not rawLine then error( "illegal comment" ) end end end --[[ ソースをコメント、文字列、その他(ステートメント候補)に カテゴライズした結果を登録する。 この関数内でステートメント候補の文字列をトークン毎に分割して登録する。 @param kind カテゴライズの種類 @param val カテゴライズした文字列 @param column 現在の解析行内の位置 ]] local addVal = function( kind, val, column ) local function createInfo( tokenKind, token, tokenColumn ) if tokenKind == kindSymb then if self.keywordSet[ token ] then tokenKind = kindKywd elseif self.typeSet[ token ] then tokenKind = kindType elseif op2Set[ token ] or op1Set[ token ] then tokenKind = kindOpe end end return { kind = tokenKind, txt = token, pos = { lineNo = self.lineNo, column = tokenColumn } } end --[[ token の startIndex から始まる数値表現領域を特定する @param token 文字列 @param startIndex token 内の検索開始位置。 この位置から数値表現が始まる。 @return 数値表現の終了位置, 整数かどうか ]] local function analyzeNumber( token, startIndex ) local nonNumIndex = token:find( '[^%d]', startIndex ) if not nonNumIndex then return #token, true end local intFlag = true local nonNumChar = token:byte( nonNumIndex ) if nonNumChar == 46 then -- . intFlag = false nonNumIndex = token:find( '[^%d]', nonNumIndex + 1 ) nonNumChar = token:byte( nonNumIndex ) end if nonNumChar == 120 or nonNumChar == 88 then -- X or x nonNumIndex = token:find( '[^%d]', nonNumIndex + 1 ) nonNumChar = token:byte( nonNumIndex ) end if nonNumChar == 101 or nonNumChar == 69 then -- E or e intFlag = false local nextChar = token:byte( nonNumIndex + 1 ) if nextChar == 45 or nextChar == 43 then -- '-' or '+' nonNumIndex = token:find( '[^%d]', nonNumIndex + 2 ) else nonNumIndex = token:find( '[^%d]', nonNumIndex + 1 ) end end if not nonNumIndex then return #token, intFlag end return nonNumIndex - 1, intFlag end if kind == kindSymb then local searchIndex = 1 while true do -- 空白系以外の何らかの文字領域を探す local tokenIndex, tokenEndIndex = string.find( val, "[%g]+", searchIndex ) if not tokenIndex then break end local columnIndex = column + tokenIndex - 2 searchIndex = tokenEndIndex + 1 local token = val:sub( tokenIndex, tokenEndIndex ) local startIndex = 1 while true do if token:find( '^[%d]', startIndex ) then -- 数値の場合 local endIndex, intFlag = analyzeNumber( token, startIndex ) local info = createInfo( intFlag and kindInt or kindReal, token:sub( startIndex, endIndex ), columnIndex + startIndex ) table.insert( list, info ) startIndex = endIndex + 1 else -- 区切り文字を探す local index = string.find( token, '[^%w_]', startIndex ) if index then if index > startIndex then local info = createInfo( kindSymb, token:sub( startIndex, index - 1 ), columnIndex + startIndex ) table.insert( list, info ) end local delimit = token:sub( index, index ) local candidateList = self.multiCharDelimitMap[ delimit ] while candidateList do local findFlag = false for candIndex, candidate in ipairs( candidateList ) do if candidate == token:sub( index, index + #candidate - 1 ) then delimit = candidate candidateList = self.multiCharDelimitMap[ delimit ] findFlag = true break end end if not findFlag then break end end startIndex = index + #delimit local workKind = kindDlmt if op2Set[ delimit ] or op1Set[ delimit ] then workKind = kindOpe end if delimit == "?" then local nextChar = token:sub( index, startIndex ) table.insert( list, createInfo( kindChar, nextChar, columnIndex + startIndex ) ) startIndex = startIndex + 1 else table.insert( list, createInfo( workKind, delimit, columnIndex + index ) ) end else if startIndex <= #token then table.insert( list, createInfo( kindSymb, token:sub( startIndex ), columnIndex + startIndex ) ) end break end end end end else table.insert( list, createInfo( kind, val, column ) ) end end -- 検索開始位置。 -- 領域開始位置と検索開始位置が異なる場合がある。 -- たとえば、 0.12e-2 のときに - の部分が検索開始位置、 0 の部分が領域開始位置になる local searchIndex = startIndex -- 領域をカテゴライズする while true do local syncIndexFlag = true local index = string.find( rawLine, [[[%-%?"%'%`%[].]], searchIndex ) if not index then addVal( kindSymb, rawLine:sub( startIndex ), startIndex ) return list end local findChar = string.byte( rawLine, index ) local nextChar = string.byte( rawLine, index + 1 ) if findChar == 45 and nextChar ~= 45 then -- -- searchIndex = index + 1 syncIndexFlag = false else if startIndex < index then addVal( kindSymb, rawLine:sub( startIndex, index - 1 ), startIndex ) end if findChar == 39 and nextChar == 39 then -- "''" if string.byte( rawLine, index + 2 ) == 39 then -- 複数行コメントの場合 local comment, nextIndex = multiComment( index + 3, "'''" ) addVal( kindCmnt, "'''" .. comment, index ) searchIndex = nextIndex else addVal( kindCmnt, rawLine:sub( index ), index ) searchIndex = #rawLine + 1 end elseif findChar == 91 then -- '[' if nextChar == 64 then -- '@' addVal( kindDlmt, "[@", index ) searchIndex = index + 2 else addVal( kindDlmt, "[", index ) searchIndex = index + 1 end elseif findChar == 34 or findChar == 39 then -- '"' or "'" -- 文字列の場合 local workIndex = index + 1 local pattern = '["\'\\]' while true do local endIndex = string.find( rawLine, pattern, workIndex ) if not endIndex then error( string.format( "illegal string: %d: %s", index, rawLine ) ) end local workChar = string.byte( rawLine, endIndex ) if workChar == findChar then -- '"' addVal( kindStr, rawLine:sub( index, endIndex ), index ) searchIndex = endIndex + 1 break elseif workChar == 92 then -- \\ workIndex = workIndex + 2 else workIndex = workIndex + 1 end end elseif findChar == 96 then -- '`' if nextChar == findChar and string.byte( rawLine, index + 2 ) == 96 then -- '```' -- 複数行文字列の場合 local str, nextIndex = multiComment( index + 3, '```' ) addVal( kindStr, '```' .. str, index ) searchIndex = nextIndex else addVal( kindDlmt, '`', index ) end elseif findChar == 63 then -- ? local codeChar = rawLine:sub( index + 1, index + 1 ) if nextChar == 92 then -- \\ local quoted = rawLine:sub( index + 2, index + 2 ) if quotedCharSet[ quoted ] then codeChar = rawLine:sub( index + 1, index + 2 ) else codeChar = quoted end searchIndex = index + 3 else searchIndex = index + 2 end addVal( kindChar, codeChar, index ) else error( string.format( "illegal syntax:%s:%s", self.lineNo, rawLine:sub( index ) ) ) end end if syncIndexFlag then startIndex = searchIndex end end end function ParserMtd:getToken() if not self.lineTokenList then return end if #self.lineTokenList < self.pos then self.pos = 1 self.lineTokenList = {} while #self.lineTokenList == 0 do self.lineTokenList = self:parse() if not self.lineTokenList then return nil end end end local token = self.lineTokenList[ self.pos ] self.pos = self.pos + 1 return token end local eofToken = { kind = kindEof, txt = "", pos = { lineNo = 0, column = 0 } } function Parser:getEofToken() return eofToken end return Parser
UTIL = UTIL or require "util" Enums = Enums or require "enums" local Elements = Enums.Elements Modules = Modules or require "modules" local Vec = Modules.Vec local Collider = Modules.Collider local Dim = Modules.Dim Contents = Contents or {} Contents.Game = Contents.Game or {} Contents.Game.Bullet = Contents.Game.Bullet or require "game.bullet" local Bullet = Contents.Game.Bullet --* Player Class local Player = { sprite = { [Elements.FIRE] = love.graphics.newImage("images/playerf.png"), [Elements.WATER] = love.graphics.newImage("images/playerw.png"), [Elements.PLANT] = love.graphics.newImage("images/playerp.png") }, WALK = 200, JUMP = 530 } for _, i in ipairs(Player.sprite) do i:setFilter("nearest", "nearest") end local player_sprite = love.graphics.newImage("images/player.png") Player.tam = Dim:extract(player_sprite) player_sprite = nil Player.__index = Player function Player:new(pos, vel, acc) local player = { weapon = Elements.FIRE, pos = pos or Vec:new(), vel = vel or Vec:new(), acc = acc or Vec:new(), shoot_vel = 450, dir = 1, onJump = false, life = 30 } setmetatable(player, self) function player:draw(pos) local real_pos if self.dir == 1 then real_pos = pos * UTIL.game.scale love.graphics.draw(self.sprite[self.weapon], real_pos.x, real_pos.y, 0, UTIL.game.scale, UTIL.game.scale) else pos = pos:copy() pos.x = pos.x + self.tam.width real_pos = (pos) * UTIL.game.scale love.graphics.draw(self.sprite[self.weapon], real_pos.x, real_pos.y, 0, -UTIL.game.scale, UTIL.game.scale) end end function player:drawLife() local pos = Vec:new(UTIL.window.width / 2, UTIL.window.height - 50) local bar = Dim:new(self.life * 10, 20) pos = pos - bar:toVec() / 2 local border = 1 love.graphics.setColor(255, 255, 255) love.graphics.rectangle("fill", pos.x - border, pos.y - border, bar.width + 2 * border, bar.height + 2 * border) love.graphics.setColor(255, 0, 0) love.graphics.rectangle("fill", pos.x, pos.y, bar.width, bar.height) love.graphics.setColor(255, 255, 255) end function player:drawDev(pos, color) local col = self:getCollider() local aux = col.p2 - col.p1 Collider:new(pos, pos + aux):draw(color) pos.y = pos.y - 5 pos = pos * UTIL.game.scale local text = tostring(math.floor(self.life * 1000) / 1000) UTIL.printw(text, Fonts.PressStart2P, pos.x - 20, pos.y, self.tam.width * UTIL.game.scale + 40, "center", 1) end function player:update(dt) self.vel = self.vel + self.acc * dt self.pos = self.pos + self.vel * dt end function player:shoot() local pos = self.pos:copy() if self.dir == -1 then pos.x = pos.x + self.tam.width end pos.y = pos.y + 8 pos.x = pos.x + 28 * self.dir return Bullet:new(self.weapon, pos, Vec:new(self.dir * self.shoot_vel, 0)) end function player:walk(dir) self.vel.x = dir * self.WALK -- self.dir = dir ~= 0 ? dir : self.dir self.dir = dir ~= 0 and dir or self.dir end function player:jump() self.vel.y = -self.JUMP self.onJump = true end function player:stopJump() if self.onJump then self.vel.y = self.vel.y / 2 self.onJump = false end end function player:getCollider() local p2 = self.tam:toVec() p2 = self.pos + p2 return Collider:new(self.pos, p2) end return player end return Player
-- FUNCTIONAL require 'Q/UTILS/lua/strict' local Q = require 'Q' local C_to_txt = require "Q/UTILS/lua/C_to_txt" local lVector = require 'Q/RUNTIME/VCTR/lua/lVector' local qconsts = require 'Q/UTILS/lua/q_consts' local ffi = require 'ffi' local Scalar = require 'libsclr' ; local cmem = require 'libcmem'; local get_ptr = require 'Q/UTILS/lua/get_ptr' local tests = {} tests.t1 = function() local x_length = 10 local x_qtype = "I4" local M = { qtype = x_qtype, gen = true, has_nulls = true, is_memo = true, num_elements = x_length } -- creating a vector local x = lVector(M) -- providing value for vector local x_width = qconsts.qtypes[x_qtype].width local base_data = cmem.new(x_length * x_width) local iptr = ffi.cast(qconsts.qtypes[x_qtype].ctype .. " *", get_ptr(base_data)) for itr = 1, x_length do iptr[itr - 1] = itr * 10 end -- creating vector with nulls to serve as an input for drop_nulls -- treating nn vector as I1 local field_size = 8 local qtype = "I1" local num_elements = math.ceil(x_length / 8) local nn_data = cmem.new(num_elements * field_size) local nn_iptr = ffi.cast(qconsts.qtypes[qtype].ctype .. " *", get_ptr(nn_data)) for itr = 1, num_elements do nn_iptr[itr - 1] = 85 end -- writing values to vector x:put_chunk(base_data, nn_data, x_length) -- Q.print_csv(x) local sval = Scalar.new("1000", "I4") local z = Q.drop_nulls(x, sval) Q.print_csv(z) assert(Q.sum(z):eval():to_num() == 5250) print("Test t1 succeeded") end return tests
-- License: CC0 -- A simple Pandoc Lua filter to extract the links in a file. function Link(elem) if elem.target:find("^https?://") then io.stdout:write(elem.target .. "\n") elseif elem.target:find("^mailto:") then -- Do nothing else -- Internal link io.stdout:write("https://issarice.com/" .. elem.target .. "\n") end end
collectibles = { {"do_antimagic", 1}, {"do_antigravity", 1}, } markers = { { map = "res/map/highland/highland.tmx", position = {1900, 600}, step = 0 }, { map = "res/map/gandria/gandria.tmx", position = {2275, 375}, npc = "npc_jonathan", step = -1 } }
local MyStation = function(templateName, x, y) -- needs to be a CpuShip to have beams local station = CpuShip(): setTemplate(templateName): setFaction("Academy"): setPosition(x, y): setRotation(math.random(0,359)): setShieldsMax(): setImpulseMaxSpeed(0): setRotationMaxSpeed(0): setBeamWeapon(0, 360, 0, 2500, 6, 6): setScanState("full") station:orderStandGround() Station:withComms(station, { hailText = function() local text = station:getCallSign() .. "\n\n" text = text .. string.format("Hull: %.0f/%.0f\n\n", station:getHull(), station:getHullMax()) text = text .. "We offer repairs, restocks and recharges when no enemies are on our scanners." return text end }) Cron.regular(function(self) -- station could be moved, because it is a "Ship" if not station:isValid() then Cron.abort(self) else station:setPosition(x, y) end end, 0.1) return station end My.EventHandler:register("onWorldCreation", function() local x, y = 0, 0 local station = MyStation("Large Station", x, y) station:setCallSign("Academy") My.EventHandler:fire("onStationSpawn", station) Cron.regular(function() if not station:isValid() then victory("Unknown") end end, 1) local angles = {0} if _G.GameConfig.numberLanes == 2 then angles = {-40, 40} elseif _G.GameConfig.numberLanes == 3 then angles = {-60, 0, 60} elseif _G.GameConfig.numberLanes == 4 then angles = {-80, -40, 0, 40, 80} end for i, avgAngle in ipairs(angles) do local avgDistance = 12000 local x1, y1 = Util.addVector(x, y, (math.random() * 20) - 10 + avgAngle, avgDistance) local station3 = MyStation("Medium Station", x1, y1) if GameConfig.laneNames[i] and GameConfig.stationNames[1] then station3:setCallSign(GameConfig.laneNames[i] .. " " .. GameConfig.stationNames[1]) end local x2, y2 = Util.addVector(x1, y1, (math.random() * 0.4 + 0.5) * avgAngle + math.random(-10, 10), avgDistance * (math.random() * 0.4 + 0.8)) local station2 = MyStation("Medium Station", x2, y2) if GameConfig.laneNames[i] and GameConfig.stationNames[2] then station2:setCallSign(GameConfig.laneNames[i] .. " " .. GameConfig.stationNames[2]) end local x3, y3 = Util.addVector(x2, y2, (math.random() * 0.4 + 0.2) * avgAngle + math.random(-10, 10), avgDistance * (math.random() * 0.4 + 0.8)) local station1 = MyStation("Medium Station", x3, y3) if GameConfig.laneNames[i] and GameConfig.stationNames[3] then station1:setCallSign(GameConfig.laneNames[i] .. " " .. GameConfig.stationNames[3]) end local x4, y4 = Util.addVector(x3, y3, (math.random() * 0.4 + 0.2) * avgAngle + math.random(-10, 10), avgDistance * (math.random() * 0.4 + 1.3)) My.EventHandler:fire("onStationSpawn", station3) My.EventHandler:fire("onStationSpawn", station2) My.EventHandler:fire("onStationSpawn", station1) local jumpAngle = Util.angleFromVector(x3 - x4, y3 - y4) -- just in case someone gets sucked local jumpX, jumpY = Util.addVector(x4, y4, jumpAngle, 5000) WormHole():setPosition(x4, y4):setTargetPosition(jumpX, jumpY) local zone = (function() local angle1 = Util.angleFromVector(x1 - x, y1 - y) local firstX, firstY = Util.addVector(x1, y1, angle1 - 180, 2000) local angle2 = Util.angleFromVector(x2 - x, y2 - y) local angle3 = Util.angleFromVector(x3 - x1, y3 - y1) local angle4 = Util.angleFromVector(x4 - x2, y4 - y2) local angle5 = Util.angleFromVector(x4 - x3, y4 - y3) local lastX, lastY = Util.addVector(x3, y3, angle5, 5000) local points = {} local pointX, pointY = Util.addVector(firstX, firstY, angle2 - 180, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(firstX, firstY, angle2 - 135, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(firstX, firstY, angle2 - 90, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(x1, y1, angle2 - 90, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(x2, y2, angle3 - 90, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(x3, y3, angle4 - 90, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(lastX, lastY, angle4 - 90, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(lastX, lastY, angle4 - 45, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(lastX, lastY, angle4, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(lastX, lastY, angle4 + 45, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(lastX, lastY, angle4 + 90, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(x3, y3, angle4 + 90, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(x2, y2, angle3 + 90, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(x1, y1, angle2 + 90, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(firstX, firstY, angle2 + 90, 5000) table.insert(points, pointX) table.insert(points, pointY) pointX, pointY = Util.addVector(firstX, firstY, angle2 + 135, 5000) table.insert(points, pointX) table.insert(points, pointY) return Zone():setPoints(table.unpack(points)) end)() zone:setFaction("Academy") zone:setColor(31,63,31) zone:setLabel(GameConfig.laneNames[i] or ("Campus" .. i)) local spawnAngle = Util.angleFromVector(x3 - x4, y4 - y4) table.insert(My.World.lanes, { spawn = function(self, spaceObject) if Fleet:isFleet(spaceObject) then for _, ship in pairs(spaceObject:getShips()) do self:spawn(ship) end else spaceObject:setPosition(Util.addVector(x4, y4, spawnAngle + math.random(-45, 45), 3000)) spaceObject:setRotation(spawnAngle) end end, isStation1Valid = function() return station1:isValid() end, getStation1 = function() return station1 end, isStation2Valid = function() return station2:isValid() end, getStation2 = function() return station2 end, isStation3Valid = function() return station3:isValid() end, getStation3 = function() return station3 end, getWormHolePosition = function() return x4, y4 end, }) end My.World.hqStation = station end, -100)
object_mobile_loveday_ewok_cupid_familiar = object_mobile_shared_loveday_ewok_cupid_familiar:new { } ObjectTemplates:addTemplate(object_mobile_loveday_ewok_cupid_familiar, "object/mobile/loveday_ewok_cupid_familiar.iff")
local pairwise_utils = require 'pairwise_transform_utils' local data_augmentation = require 'data_augmentation' local iproc = require 'iproc' local gm = {} gm.Image = require 'graphicsmagick.Image' local pairwise_transform = {} function pairwise_transform.user(x, y, size, offset, n, options) assert(x:size(1) == y:size(1)) local scale_y = y:size(2) / x:size(2) assert(x:size(3) == y:size(3) / scale_y) x, y = pairwise_utils.preprocess_user(x, y, scale_y, size, options) assert(x:size(3) == y:size(3) / scale_y and x:size(2) == y:size(2) / scale_y) local batch = {} local lowres_y = nil local xs ={x} local ys = {y} local ls = {} if options.active_cropping_rate > 0 then lowres_y = pairwise_utils.low_resolution(y) end if options.pairwise_flip and n == 1 then xs[1], ys[1] = data_augmentation.pairwise_flip(xs[1], ys[1]) elseif options.pairwise_flip then xs, ys, ls = pairwise_utils.flip_augmentation(x, y, lowres_y) end assert(#xs == #ys) local perm = torch.randperm(#xs) for i = 1, n do local t = perm[(i % #xs) + 1] local xc, yc = pairwise_utils.active_cropping(xs[t], ys[t], ls[t], size, scale_y, options.active_cropping_rate, options.active_cropping_tries) xc = iproc.byte2float(xc) yc = iproc.byte2float(yc) if options.rgb then else if xc:size(1) > 1 then yc = iproc.rgb2y(yc) xc = iproc.rgb2y(xc) end end if options.gcn then local mean = xc:mean() local stdv = xc:std() if stdv > 0 then xc:add(-mean):div(stdv) else xc:add(-mean) end end yc = iproc.crop(yc, offset, offset, size - offset, size - offset) if options.pairwise_y_binary then yc[torch.lt(yc, 0.5)] = 0 yc[torch.gt(yc, 0)] = 1 end table.insert(batch, {xc, yc}) end return batch end return pairwise_transform
ESX = nil TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) ESX.RegisterServerCallback('denyCloseFrame:isPlayerWhitelist', function(src, cb) local xPlayer = ESX.GetPlayerFromId(src) local xlincense = xPlayer.getIdentifier() for k, v in ipairs(Config.WhitelistLicence) do if v == xlincense then cb(true) end end cb(false) end)