content
stringlengths
5
1.05M
-- default spacebar config c = {} c.paths = {} -- Paths c.paths.yabai = '/opt/homebrew/bin/yabai' return c
function table.find (tbl, index, value) for i, v in pairs (tbl) do if v[index] == value then return i; end end return false; end local mods = {}; local mods_ordered = {}; addEventHandler ("onResourceStart", resourceRoot, function () local meta = xmlLoadFile ("meta.xml"); for i, v in ipairs (xmlNodeGetChildren (meta)) do if xmlNodeGetName(v) == "file" then local name = xmlNodeGetAttribute (v, "name"); if name then local dir = xmlNodeGetAttribute (v, "src"); local model = xmlNodeGetAttribute (v, "model"); local type = xmlNodeGetAttribute (v, "mod_type"); local background = xmlNodeGetAttribute (v, "background") == "true"; local file = fileOpen (dir); local size = fileGetSize (file)/1000000; fileClose(file); if not table.find (mods, "name", name) then local txd, dff; if dir:find (".txd") then txd = dir; else dff = dir; end local info = {name = name, size = size, model = model, type = type, background = background}; if not mods_ordered[type] then mods_ordered[type] = {}; end if txd then info.txd = txd; table.insert (mods, info); table.insert (mods_ordered[type], info); else info.dff = dff; table.insert (mods, info); table.insert (mods_ordered[type], info); end else local index = table.find (mods, "name", name); local tbl = mods[index]; local txd, dff; if tbl then if dir:find (".txd") then txd = dir; else dff = dir; end if txd then tbl.txd = txd; else tbl.dff = dff; end tbl.size = tbl.size + size; end end end end end end ); addEvent ("onClientRequestList", true); addEventHandler ("onClientRequestList", root, function () triggerLatentClientEvent (client, "onClientDownloadList", client, mods, mods_ordered); end );
-- Settings -- -- Load filetype plugin and indent files vim.cmd 'filetype plugin indent on' -- Enable syntax highlighting vim.cmd 'syntax on' -- Enable 24-bit RGB color in the TUI vim.opt.termguicolors = true -- Enable the colorscheme vim.cmd 'colorscheme onedark' -- Access system clipboard in VIM vim.opt.clipboard = 'unnamed' -- Turn off search highlighting vim.opt.hlsearch = false -- Ignore case in search patterns (case insensitive search) vim.opt.ignorecase = true -- Show tab line even if only one file is open vim.opt.showtabline = 2 -- Show cursor line vim.wo.cursorline = true -- Set relative number on focus and norelative number when lost focus vim.cmd [[ let g:buffers = ["NvimTree", "toggleterm", "Trouble", "dapui_watches", "dapui_stacks", "dapui_scopes", "dapui_breakpoints"] augroup numbertoggle autocmd! autocmd BufEnter,FocusGained,InsertLeave * if index(g:buffers, &ft) < 0 | set number relativenumber | endif autocmd BufLeave,FocusLost,InsertEnter * set norelativenumber augroup END ]] -- Enable to leave a buffer with unsaved changes vim.opt.hidden = true -- Always show sign columns vim.opt.signcolumn = 'yes' -- If this many milliseconds nothing is typed the swap file will be written to -- disk. Also used for the CursorHold autocommand event - used for -- nvim-lightbuld. vim.opt.updatetime = 300 -- Autoopen of quickfix list (etc. after vimgrep) vim.cmd [[ augroup autoquickfix autocmd! autocmd QuickFixCmdPost [^l]* cwindow autocmd QuickFixCmdPost l* lwindow augroup END ]] -- General file configuration vim.opt.tabstop = 4 vim.opt.softtabstop = 4 vim.opt.shiftwidth = 4 vim.opt.autoindent = true vim.opt.encoding = 'utf-8' -- Keybindings -- -- Navigation in split windows vim.api.nvim_set_keymap('n', '<C-j>', '<C-w><C-j>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<C-k>', '<C-w><C-k>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<C-l>', '<C-w><C-l>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<C-h>', '<C-w><C-h>', { noremap = true, silent = true }) -- Tab navigation vim.api.nvim_set_keymap('n', '<M-l>', 'gt', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<M-h>', 'gT', { noremap = true, silent = true }) -- Quickfix list navigation vim.api.nvim_set_keymap('n', ']q', ':cnext<CR>', { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '[q', ':cprevious<CR>', { noremap = true, silent = true }) -- Map yanking to PRIMARY and CLIPBOARD registers PRIMARY (*) mnemonic: Star is -- Select (for copy-on-select) CLIPBOARD (+) mnemonic: CTRL PLUS C (for the -- common keybind) vim.api.nvim_set_keymap('', '<Leader>y', '"*y', { noremap = true, silent = false }) vim.api.nvim_set_keymap('', '<Leader>p', '"*p', { noremap = true, silent = false }) vim.api.nvim_set_keymap('', '<Leader>Y', '"+y', { noremap = true, silent = false }) vim.api.nvim_set_keymap('', '<Leader>P', '"+p', { noremap = true, silent = false }) -- Terminal vim.api.nvim_set_keymap('t', '<Esc>', '<C-\\><C-n>', { noremap = true, silent = false }) vim.api.nvim_set_keymap('t', '<C-[>', '<C-\\><C-n>', { noremap = true, silent = false }) -- Search for visually selected text using // vim.api.nvim_set_keymap('v', '//', 'y/\\V<C-R>=escape(@","/\")<CR><CR>', { noremap = true, silent = false })
-- Manage Prompt Sections -- Sections Consist of a table with properties local sections = {} local function merge(t1, t2) for k, v in pairs(t2) do if (type(v) == "table") and (type(t1[k] or false) == "table") then merge(t1[k], t2[k]) else t1[k] = v end end return t1 end local function sectionContent(section, options, context) local text = section.content(options, context) if text then if type(text) == "table" then return text end if text ~= "" then if not options then options = {} end -- include core options fore each section return { title = nil, path = nil, text = text, foreground = options.foreground, background = options.background, bold = options.bold, leader = options.leader } end end return nil end local function empty() return nil end local function getOptions(section, options) local combined = (section and section.options) or {} -- apply any passed in options to the sections options if options then combined = merge(merge({}, combined), options) end return combined end -- Register a section function SECTION_register(section) sections[section.name] = section end -- Compile a builder against a set of options function SECTION_compile(name, options) local section = sections[name] local compiled = {prepare = empty, content = empty} -- no section found return empty builder if not section then return compiled end local opts = getOptions(section, options) -- add section functions if section.prepare then function compiled.prepare(context) return section.prepare(opts, context) end end if section.content then function compiled.content(context) return sectionContent(section, opts, context) end end return compiled end function SECTION_content(name, options, context) local section = sections[name] if section then local opts = getOptions(section, options) return sectionContent(section, opts, context) end return nil end
local crab = {} crab.skin = {crab1, crab2, crab3, crab4, crab5, crab6, crab7, crab8, crab9, crab10} for i = 1, 10 do if not pcall(function () crab.skin[i] = love.graphics.newImage("assets/crab/crabm" .. i .. ".png") end) then print("Could not load crab asset.") return 2 end end crab.scalex = 0.5 crab.scaley = 0.5 crab.r = math.rad(0) crab.sizex = crab.skin[1]:getWidth() crab.sizey = crab.skin[1]:getHeight() crab.x = love.graphics.getWidth() / 2 crab.y = love.graphics.getHeight() - (crab.sizey / 2) + 50 crab.skincrabpos = 1 crab.speed = 150 crab.crabtimer = 0 return crab
--[[ -- slt2 - Simple Lua Template 2 -- -- Project page: https://github.com/henix/slt2 -- -- @License -- MIT License --]] local slt2 = {} -- a tree fold on inclusion tree -- @param init_func: must return a new value when called local function include_fold(template, start_tag, end_tag, fold_func, init_func) local result = init_func() start_tag = start_tag or '#{' end_tag = end_tag or '}#' local start_tag_inc = start_tag..'include:' local start1, end1 = string.find(template, start_tag_inc, 1, true) local start2 = nil local end2 = 0 while start1 ~= nil do if start1 > end2 + 1 then -- for beginning part of file result = fold_func(result, string.sub(template, end2 + 1, start1 - 1)) end start2, end2 = string.find(template, end_tag, end1 + 1, true) assert(start2, 'end tag "'..end_tag..'" missing') do -- recursively include the file local filename = assert(loadstring('return '..string.sub(template, end1 + 1, start2 - 1)))() assert(filename) local fin = assert(io.open(filename)) -- TODO: detect cyclic inclusion? result = fold_func(result, include_fold(fin:read('*a'), start_tag, end_tag, fold_func, init_func), filename) fin:close() end start1, end1 = string.find(template, start_tag_inc, end2 + 1, true) end result = fold_func(result, string.sub(template, end2 + 1)) return result end -- preprocess included files -- @return string function slt2.precompile(template, start_tag, end_tag) return table.concat(include_fold(template, start_tag, end_tag, function(acc, v) if type(v) == 'string' then table.insert(acc, v) elseif type(v) == 'table' then table.insert(acc, table.concat(v)) else error('Unknown type: '..type(v)) end return acc end, function() return {} end)) end -- unique a list, preserve order local function stable_uniq(t) local existed = {} local res = {} for _, v in ipairs(t) do if not existed[v] then table.insert(res, v) existed[v] = true end end return res end -- @return { string } function slt2.get_dependency(template, start_tag, end_tag) return stable_uniq(include_fold(template, start_tag, end_tag, function(acc, v, name) if type(v) == 'string' then elseif type(v) == 'table' then if name ~= nil then table.insert(acc, name) end for _, subname in ipairs(v) do table.insert(acc, subname) end else error('Unknown type: '..type(v)) end return acc end, function() return {} end)) end -- @return { name = string, code = string / function} function slt2.loadstring(template, start_tag, end_tag, tmpl_name) -- compile it to lua code local lua_code = {} start_tag = start_tag or '#{' end_tag = end_tag or '}#' local output_func = "coroutine.yield" template = slt2.precompile(template, start_tag, end_tag) local start1, end1 = string.find(template, start_tag, 1, true) local start2 = nil local end2 = 0 local cEqual = string.byte('=', 1) while start1 ~= nil do if start1 > end2 + 1 then table.insert(lua_code, output_func..'('..string.format("%q", string.sub(template, end2 + 1, start1 - 1))..')') end start2, end2 = string.find(template, end_tag, end1 + 1, true) assert(start2, 'end_tag "'..end_tag..'" missing') if string.byte(template, end1 + 1) == cEqual then table.insert(lua_code, output_func..'('..string.sub(template, end1 + 2, start2 - 1)..')') else table.insert(lua_code, string.sub(template, end1 + 1, start2 - 1)) end start1, end1 = string.find(template, start_tag, end2 + 1, true) end table.insert(lua_code, output_func..'('..string.format("%q", string.sub(template, end2 + 1))..')') local ret = { name = tmpl_name or '=(slt2.loadstring)' } if setfenv == nil then -- lua 5.2 ret.code = table.concat(lua_code, '\n') else -- lua 5.1 ret.code = assert(loadstring(table.concat(lua_code, '\n'), ret.name)) end return ret end -- @return { name = string, code = string / function } function slt2.loadfile(filename, start_tag, end_tag) local fin = assert(io.open(filename)) local all = fin:read('*a') fin:close() return slt2.loadstring(all, start_tag, end_tag, filename) end local mt52 = { __index = _ENV } local mt51 = { __index = _G } -- @return a coroutine function function slt2.render_co(t, env) local f if setfenv == nil then -- lua 5.2 if env ~= nil then setmetatable(env, mt52) end f = assert(load(t.code, t.name, 't', env or _ENV)) else -- lua 5.1 if env ~= nil then setmetatable(env, mt51) end f = setfenv(t.code, env or _G) end return f end -- @return string function slt2.render(t, env) local result = {} local co = coroutine.create(slt2.render_co(t, env)) while coroutine.status(co) ~= 'dead' do local ok, chunk = coroutine.resume(co) if not ok then error(chunk) end table.insert(result, chunk) end return table.concat(result) end return slt2
describe('stringstrong.septableconcat() #concat #sep #table', function() local strongstring lazy_setup(function() strongstring = require('src/strongstring') end) it('concat table with sep', function() local t = {'abc', 'def'} local sep = '.' assert.are.equals('abc.def', strongstring.septableconcat(t, sep)) end) it('sep is empty', function() local t = {'abc', 'def'} local sep = '' assert.are.equals('abcdef', strongstring.septableconcat(t, sep)) end) it('sep is wrong data type', function() local t = {'abc', 'def'} local sep = false assert.are.equals(nil, strongstring.septableconcat(t, sep)) end) it('no sep', function() local t = {'abc', 'def'} assert.are.equals('abcdef', strongstring.septableconcat(t)) end) it('table has only one element', function() local t = {'abc'} local sep = '/' assert.are.equals('abc', strongstring.septableconcat(t, sep)) end) it('empty table', function() local t = {} local sep = '/' assert.are.equals(nil, strongstring.septableconcat(t, sep)) end) it('table with numbers', function() local t = {1, 2, 3} local sep = '/' assert.are.equals(nil, strongstring.septableconcat(t, sep)) end) end)
-- Override minimap update function function map.update_hud_flags(player) if not player or player.is_fake_player then return -- Can't be used by a fake player end local creative_enabled = minetest.is_creative_enabled(player:get_player_name()) local inv = player:get_inventory() local has_map = inv:contains_item("main", "map:mapping_kit") local has_radar = inv:contains_item("main", "minimap_radar:radar") player:hud_set_flags({ minimap = creative_enabled or has_map or has_radar, -- Radar needs to enable the minimap too minimap_radar = creative_enabled or has_radar }) end -- Radar item minetest.register_craftitem("minimap_radar:radar", { description = "Radar\nUse with 'Minimap' key", inventory_image = "minimap_radar_radar.png", stack_max = 1, on_use = function(itemstack, user, pointed_thing) map.update_hud_flags(user) end }) -- Crafting if minetest.get_modpath("technic") then minetest.register_craft({ output = "minimap_radar:radar", recipe = { {"technic:stainless_steel_ingot", "default:diamond", "technic:stainless_steel_ingot"}, {"dye:green", "technic:prospector", "dye:black"}, {"technic:stainless_steel_ingot", "default:diamond", "technic:stainless_steel_ingot"}, } }) elseif minetest.get_modpath("moreores") then minetest.register_craft({ output = "minimap_radar:radar", recipe = { {"moreores:silver_ingot", "default:diamond", "moreores:silver_ingot"}, {"dye:green", "moreores:mithril_block", "dye:black"}, {"moreores:silver_ingot", "default:diamond", "moreores:silver_ingot"}, } }) else minetest.register_craft({ output = "minimap_radar:radar", recipe = { {"default:steel_ingot", "default:diamond", "default:steel_ingot"}, {"dye:green", "default:mese", "dye:black"}, {"default:steel_ingot", "default:diamond", "default:steel_ingot"}, } }) end
local _2afile_2a = "fnl/conjure/log.fnl" local _2amodule_name_2a = "conjure.log" local _2amodule_2a do package.loaded[_2amodule_name_2a] = {} _2amodule_2a = package.loaded[_2amodule_name_2a] end local _2amodule_locals_2a do _2amodule_2a["aniseed/locals"] = {} _2amodule_locals_2a = (_2amodule_2a)["aniseed/locals"] end local autoload = (require("conjure.aniseed.autoload")).autoload local a, buffer, client, config, editor, nvim, str, text, timer, view, sponsors = autoload("conjure.aniseed.core"), autoload("conjure.buffer"), autoload("conjure.client"), autoload("conjure.config"), autoload("conjure.editor"), autoload("conjure.aniseed.nvim"), autoload("conjure.aniseed.string"), autoload("conjure.text"), autoload("conjure.timer"), autoload("conjure.aniseed.view"), require("conjure.sponsors") do end (_2amodule_locals_2a)["a"] = a _2amodule_locals_2a["buffer"] = buffer _2amodule_locals_2a["client"] = client _2amodule_locals_2a["config"] = config _2amodule_locals_2a["editor"] = editor _2amodule_locals_2a["nvim"] = nvim _2amodule_locals_2a["str"] = str _2amodule_locals_2a["text"] = text _2amodule_locals_2a["timer"] = timer _2amodule_locals_2a["view"] = view _2amodule_locals_2a["sponsors"] = sponsors local state = (state or {["last-open-cmd"] = nil, hud = {id = nil, timer = nil, ["created-at-ms"] = 0}, ["jump-to-latest"] = {mark = nil, ns = nvim.create_namespace("conjure_log_jump_to_latest")}}) do end (_2amodule_locals_2a)["state"] = state local function _break() return (client.get("comment-prefix") .. string.rep("-", config["get-in"]({"log", "break_length"}))) end _2amodule_locals_2a["break"] = _break local function state_key_header() return (client.get("comment-prefix") .. "State: " .. client["state-key"]()) end _2amodule_locals_2a["state-key-header"] = state_key_header local function log_buf_name() return ("conjure-log-" .. nvim.fn.getpid() .. client.get("buf-suffix")) end _2amodule_locals_2a["log-buf-name"] = log_buf_name local function log_buf_3f(name) return text["ends-with"](name, log_buf_name()) end _2amodule_2a["log-buf?"] = log_buf_3f local function on_new_log_buf(buf) state["jump-to-latest"].mark = nvim.buf_set_extmark(buf, state["jump-to-latest"].ns, 0, 0, {}) return nvim.buf_set_lines(buf, 0, -1, false, {(client.get("comment-prefix") .. "Sponsored by @" .. a.get(sponsors, a.inc(math.floor(a.rand(a.dec(a.count(sponsors)))))) .. " \226\157\164")}) end _2amodule_locals_2a["on-new-log-buf"] = on_new_log_buf local function upsert_buf() return buffer["upsert-hidden"](log_buf_name(), on_new_log_buf) end _2amodule_locals_2a["upsert-buf"] = upsert_buf local function clear_close_hud_passive_timer() return a["update-in"](state, {"hud", "timer"}, timer.destroy) end _2amodule_2a["clear-close-hud-passive-timer"] = clear_close_hud_passive_timer local function close_hud() clear_close_hud_passive_timer() if state.hud.id then pcall(nvim.win_close, state.hud.id, true) state.hud.id = nil return nil else return nil end end _2amodule_2a["close-hud"] = close_hud local function hud_lifetime_ms() return (vim.loop.now() - state.hud["created-at-ms"]) end _2amodule_2a["hud-lifetime-ms"] = hud_lifetime_ms local function close_hud_passive() if (state.hud.id and (hud_lifetime_ms() > config["get-in"]({"log", "hud", "minimum_lifetime_ms"}))) then local original_timer_id = state.hud["timer-id"] local delay = config["get-in"]({"log", "hud", "passive_close_delay"}) if (0 == delay) then return close_hud() else if not a["get-in"](state, {"hud", "timer"}) then return a["assoc-in"](state, {"hud", "timer"}, timer.defer(close_hud, delay)) else return nil end end else return nil end end _2amodule_2a["close-hud-passive"] = close_hud_passive local function break_lines(buf) local break_str = _break() local function _7_(_5_) local _arg_6_ = _5_ local n = _arg_6_[1] local s = _arg_6_[2] return (s == break_str) end return a.map(a.first, a.filter(_7_, a["kv-pairs"](nvim.buf_get_lines(buf, 0, -1, false)))) end _2amodule_locals_2a["break-lines"] = break_lines local function set_win_opts_21(win) local function _8_() if config["get-in"]({"log", "wrap"}) then return true else return false end end nvim.win_set_option(win, "wrap", _8_()) nvim.win_set_option(win, "foldmethod", "marker") nvim.win_set_option(win, "foldmarker", (config["get-in"]({"log", "fold", "marker", "start"}) .. "," .. config["get-in"]({"log", "fold", "marker", "end"}))) return nvim.win_set_option(win, "foldlevel", 0) end _2amodule_locals_2a["set-win-opts!"] = set_win_opts_21 local function in_box_3f(box, pos) return ((pos.x >= box.x1) and (pos.x <= box.x2) and (pos.y >= box.y1) and (pos.y <= box.y2)) end _2amodule_locals_2a["in-box?"] = in_box_3f local function flip_anchor(anchor, n) local chars = {anchor:sub(1, 1), anchor:sub(2)} local flip = {N = "S", S = "N", E = "W", W = "E"} local function _9_(_241) return a.get(flip, _241) end return str.join(a.update(chars, n, _9_)) end _2amodule_locals_2a["flip-anchor"] = flip_anchor local function pad_box(box, padding) local function _10_(_241) return (_241 - padding.x) end local function _11_(_241) return (_241 - padding.y) end local function _12_(_241) return (_241 + padding.x) end local function _13_(_241) return (_241 + padding.y) end return a.update(a.update(a.update(a.update(box, "x1", _10_), "y1", _11_), "x2", _12_), "y2", _13_) end _2amodule_locals_2a["pad-box"] = pad_box local function hud_window_pos(anchor, size, rec_3f) local north = 0 local west = 0 local south = (editor.height() - 2) local east = editor.width() local padding_percent = config["get-in"]({"log", "hud", "overlap_padding"}) local pos local _14_ if ("NE" == anchor) then _14_ = {row = north, col = east, box = {y1 = north, x1 = (east - size.width), y2 = (north + size.height), x2 = east}} elseif ("SE" == anchor) then _14_ = {row = south, col = east, box = {y1 = (south - size.height), x1 = (east - size.width), y2 = south, x2 = east}} elseif ("SW" == anchor) then _14_ = {row = south, col = west, box = {y1 = (south - size.height), x1 = west, y2 = south, x2 = (west + size.width)}} elseif ("NW" == anchor) then _14_ = {row = north, col = west, box = {y1 = north, x1 = west, y2 = (north + size.height), x2 = (west + size.width)}} else nvim.err_writeln("g:conjure#log#hud#anchor must be one of: NE, SE, SW, NW") _14_ = hud_window_pos("NE", size) end pos = a.assoc(_14_, "anchor", anchor) if (not rec_3f and in_box_3f(pad_box(pos.box, {x = editor["percent-width"](padding_percent), y = editor["percent-height"](padding_percent)}), {x = editor["cursor-left"](), y = editor["cursor-top"]()})) then local function _16_() if (size.width > size.height) then return 1 else return 2 end end return hud_window_pos(flip_anchor(anchor, _16_()), size, true) else return pos end end _2amodule_locals_2a["hud-window-pos"] = hud_window_pos local function display_hud() if config["get-in"]({"log", "hud", "enabled"}) then clear_close_hud_passive_timer() local buf = upsert_buf() local last_break = a.last(break_lines(buf)) local line_count = nvim.buf_line_count(buf) local size = {width = editor["percent-width"](config["get-in"]({"log", "hud", "width"})), height = editor["percent-height"](config["get-in"]({"log", "hud", "height"}))} local pos = hud_window_pos(config["get-in"]({"log", "hud", "anchor"}), size) local border = config["get-in"]({"log", "hud", "border"}) local win_opts local function _18_() if (1 == nvim.fn.has("nvim-0.5")) then return {border = border} else return nil end end win_opts = a.merge({relative = "editor", row = pos.row, col = pos.col, anchor = pos.anchor, width = size.width, height = size.height, focusable = false, style = "minimal"}, _18_()) if (state.hud.id and not nvim.win_is_valid(state.hud.id)) then close_hud() else end if state.hud.id then nvim.win_set_buf(state.hud.id, buf) else state.hud.id = nvim.open_win(buf, false, win_opts) set_win_opts_21(state.hud.id) end state.hud["created-at-ms"] = vim.loop.now() if last_break then nvim.win_set_cursor(state.hud.id, {1, 0}) return nvim.win_set_cursor(state.hud.id, {math.min((last_break + a.inc(math.floor((win_opts.height / 2)))), line_count), 0}) else return nvim.win_set_cursor(state.hud.id, {line_count, 0}) end else return nil end end _2amodule_locals_2a["display-hud"] = display_hud local function win_visible_3f(win) return (nvim.fn.tabpagenr() == a.first(nvim.fn.win_id2tabwin(win))) end _2amodule_locals_2a["win-visible?"] = win_visible_3f local function with_buf_wins(buf, f) local function _23_(win) if (buf == nvim.win_get_buf(win)) then return f(win) else return nil end end return a["run!"](_23_, nvim.list_wins()) end _2amodule_locals_2a["with-buf-wins"] = with_buf_wins local function win_botline(win) return a.get(a.first(nvim.fn.getwininfo(win)), "botline") end _2amodule_locals_2a["win-botline"] = win_botline local function trim(buf) local line_count = nvim.buf_line_count(buf) if (line_count > config["get-in"]({"log", "trim", "at"})) then local target_line_count = (line_count - config["get-in"]({"log", "trim", "to"})) local break_line local function _25_(line) if (line >= target_line_count) then return line else return nil end end break_line = a.some(_25_, break_lines(buf)) if break_line then nvim.buf_set_lines(buf, 0, break_line, false, {}) local line_count0 = nvim.buf_line_count(buf) local function _27_(win) local _let_28_ = nvim.win_get_cursor(win) local row = _let_28_[1] local col = _let_28_[2] nvim.win_set_cursor(win, {1, 0}) return nvim.win_set_cursor(win, {row, col}) end return with_buf_wins(buf, _27_) else return nil end else return nil end end _2amodule_locals_2a["trim"] = trim local function last_line(buf, extra_offset) return a.first(nvim.buf_get_lines((buf or upsert_buf()), (-2 + (extra_offset or 0)), -1, false)) end _2amodule_2a["last-line"] = last_line local cursor_scroll_position__3ecommand = {top = "normal zt", center = "normal zz", bottom = "normal zb", none = nil} _2amodule_2a["cursor-scroll-position->command"] = cursor_scroll_position__3ecommand local function jump_to_latest() local buf = upsert_buf() local last_eval_start = nvim.buf_get_extmark_by_id(buf, state["jump-to-latest"].ns, state["jump-to-latest"].mark, {}) local function _31_(win) local function _32_() return nvim.win_set_cursor(win, last_eval_start) end pcall(_32_) local cmd = a.get(cursor_scroll_position__3ecommand, config["get-in"]({"log", "jump_to_latest", "cursor_scroll_position"})) if cmd then local function _33_() return nvim.command(cmd) end return nvim.win_call(win, _33_) else return nil end end return with_buf_wins(buf, _31_) end _2amodule_2a["jump-to-latest"] = jump_to_latest local function append(lines, opts) local line_count = a.count(lines) if (line_count > 0) then local visible_scrolling_log_3f = false local buf = upsert_buf() local join_first_3f = a.get(opts, "join-first?") local lines0 local function _35_(s) return s:gsub("\n", "\226\134\181") end lines0 = a.map(_35_, lines) local lines1 if (line_count <= config["get-in"]({"log", "strip_ansi_escape_sequences_line_limit"})) then lines1 = a.map(text["strip-ansi-escape-sequences"], lines0) else lines1 = lines0 end local comment_prefix = client.get("comment-prefix") local fold_marker_end = str.join({comment_prefix, config["get-in"]({"log", "fold", "marker", "end"})}) local lines2 if (not a.get(opts, "break?") and not join_first_3f and config["get-in"]({"log", "fold", "enabled"}) and (a.count(lines1) >= config["get-in"]({"log", "fold", "lines"}))) then lines2 = a.concat({str.join({comment_prefix, config["get-in"]({"log", "fold", "marker", "start"}), " ", text["left-sample"](str.join("\n", lines1), editor["percent-width"](config["get-in"]({"preview", "sample_limit"})))})}, lines1, {fold_marker_end}) else lines2 = lines1 end local last_fold_3f = (fold_marker_end == last_line(buf)) local lines3 if a.get(opts, "break?") then local _38_ if client["multiple-states?"]() then _38_ = {state_key_header()} else _38_ = nil end lines3 = a.concat({_break()}, _38_, lines2) elseif join_first_3f then local _40_ if last_fold_3f then _40_ = {(last_line(buf, -1) .. a.first(lines2)), fold_marker_end} else _40_ = {(last_line(buf) .. a.first(lines2))} end lines3 = a.concat(_40_, a.rest(lines2)) else lines3 = lines2 end local old_lines = nvim.buf_line_count(buf) do local ok_3f, err = nil, nil local function _43_() local _44_ if buffer["empty?"](buf) then _44_ = 0 elseif join_first_3f then if last_fold_3f then _44_ = -3 else _44_ = -2 end else _44_ = -1 end return nvim.buf_set_lines(buf, _44_, -1, false, lines3) end ok_3f, err = pcall(_43_) if not ok_3f then error(("Conjure failed to append to log: " .. err .. "\n" .. "Offending lines: " .. a["pr-str"](lines3))) else end end do local new_lines = nvim.buf_line_count(buf) local jump_to_latest_3f = config["get-in"]({"log", "jump_to_latest", "enabled"}) local _48_ if join_first_3f then _48_ = old_lines else _48_ = a.inc(old_lines) end nvim.buf_set_extmark(buf, state["jump-to-latest"].ns, _48_, 0, {id = state["jump-to-latest"].mark}) local function _50_(win) visible_scrolling_log_3f = ((win ~= state.hud.id) and win_visible_3f(win) and (jump_to_latest_3f or (win_botline(win) >= old_lines))) local _let_51_ = nvim.win_get_cursor(win) local row = _let_51_[1] local _ = _let_51_[2] if jump_to_latest_3f then return jump_to_latest() elseif (row == old_lines) then return nvim.win_set_cursor(win, {new_lines, 0}) else return nil end end with_buf_wins(buf, _50_) end if (not a.get(opts, "suppress-hud?") and not visible_scrolling_log_3f) then display_hud() else close_hud() end return trim(buf) else return nil end end _2amodule_2a["append"] = append local function create_win(cmd) state["last-open-cmd"] = cmd local buf = upsert_buf() local function _55_() if config["get-in"]({"log", "botright"}) then return "botright " else return "" end end nvim.command(("keepalt " .. _55_() .. cmd .. " " .. buffer.resolve(log_buf_name()))) nvim.win_set_cursor(0, {nvim.buf_line_count(buf), 0}) set_win_opts_21(0) return buffer.unlist(buf) end _2amodule_locals_2a["create-win"] = create_win local function split() return create_win("split") end _2amodule_2a["split"] = split local function vsplit() return create_win("vsplit") end _2amodule_2a["vsplit"] = vsplit local function tab() return create_win("tabnew") end _2amodule_2a["tab"] = tab local function buf() return create_win("buf") end _2amodule_2a["buf"] = buf local function find_windows() local buf0 = upsert_buf() local function _56_(win) return ((state.hud.id ~= win) and (buf0 == nvim.win_get_buf(win))) end return a.filter(_56_, nvim.tabpage_list_wins(0)) end _2amodule_locals_2a["find-windows"] = find_windows local function close(windows) local function _57_(_241) return nvim.win_close(_241, true) end return a["run!"](_57_, windows) end _2amodule_locals_2a["close"] = close local function close_visible() close_hud() return close(find_windows()) end _2amodule_2a["close-visible"] = close_visible local function toggle() local windows = find_windows() if a["empty?"](windows) then if ((state["last-open-cmd"] == "split") or (state["last-open-cmd"] == "vsplit")) then return create_win(state["last-open-cmd"]) else return nil end else return close_visible(windows) end end _2amodule_2a["toggle"] = toggle local function dbg(desc, ...) if config["get-in"]({"debug"}) then append(a.concat({(client.get("comment-prefix") .. "debug: " .. desc)}, text["split-lines"](a["pr-str"](...)))) else end return ... end _2amodule_2a["dbg"] = dbg local function reset_soft() return on_new_log_buf(upsert_buf()) end _2amodule_2a["reset-soft"] = reset_soft local function reset_hard() return nvim.ex.bwipeout_(upsert_buf()) end _2amodule_2a["reset-hard"] = reset_hard
local _ = function(k, ...) return ImportPackage("i18n").t(GetPackageName(), k, ...) end local deliveryNpc = { { location = {-16925, -29058, 2200, -90}, spawn = {-17450, -28600, 2060, -90} }, { location = {-168301, -41499, 1192, 90}, spawn = {-168233, -40914, 1146, 90} }, { location = {146585, 211065, 1307, -90}, spawn = {145692, 210574, 1307, 0} } } local deliveryPoint = { {116691, 164243, 3028}, {38964, 204516, 550}, {182789, 186140, 1203}, {211526, 176056, 1209}, {42323, 137508, 1569}, {122776, 207169, 1282}, {209829, 92977, 1312}, {176840, 10049, 10370}, {198130, -49703, 1109}, {130042, 78285, 1566}, {203711, 190025, 1312}, {170311, -161302, 1242}, {152267, -143379, 1242}, {-181677, -31627, 1148}, {-179804, -66772, 1147}, {182881, 148416, 5933} } local LOCATION_PRICE = 2000 local LOCATION_REFUND_PERCENTAGE = 0.8 local PRICE_DIVIDER = 250 local PRICE_PER_DIVIDE = 15 local deliveryNpcCached = {} local playerDelivery = {} local trucksOnLocation = {} AddEvent("OnPackageStart", function() for k, v in pairs(deliveryNpc) do deliveryNpc[k].npc = CreateNPC(deliveryNpc[k].location[1], deliveryNpc[k].location[2], deliveryNpc[k].location[3], deliveryNpc[k].location[4]) CreateText3D(_("delivery_job") .. "\n" .. _("press_e"), 18, deliveryNpc[k].location[1], deliveryNpc[k].location[2], deliveryNpc[k].location[3] + 120, 0, 0, 0) table.insert(deliveryNpcCached, deliveryNpc[k].npc) end end) AddEvent("OnPlayerQuit", function(player) if playerDelivery[player] ~= nil then playerDelivery[player] = nil end end) AddEvent("OnPlayerJoin", function(player) CallRemoteEvent(player, "SetupDelivery", deliveryNpcCached, LOCATION_PRICE) end) AddRemoteEvent("StartStopDelivery", function(player) local nearestDelivery = GetNearestDelivery(player) local useBank = PlayerData[player].bank_balance >= LOCATION_PRICE local useCash = PlayerData[player].inventory['cash'] ~= nil and PlayerData[player].inventory['cash'] >= LOCATION_PRICE if PlayerData[player].job == "" then if PlayerData[player].job_vehicle ~= nil then DestroyVehicle(PlayerData[player].job_vehicle) DestroyVehicleData(PlayerData[player].job_vehicle) PlayerData[player].job_vehicle = nil CallRemoteEvent(player, "ClientDestroyCurrentWaypoint") else local isSpawnable = true local jobCount = 0 for k, v in pairs(PlayerData) do if v.job == "delivery" then jobCount = jobCount + 1 end end if jobCount == 15 then return CallRemoteEvent(player, "MakeNotification", _("job_full"), "linear-gradient(to right, #ff5f6d, #ffc371)") end for k, v in pairs(GetAllVehicles()) do local x, y, z = GetVehicleLocation(v) local dist2 = GetDistance3D(deliveryNpc[nearestDelivery].spawn[1], deliveryNpc[nearestDelivery].spawn[2], deliveryNpc[nearestDelivery].spawn[3], x, y, z) if dist2 < 500.0 then isSpawnable = false break end end if isSpawnable then if useCash then RemovePlayerCash(player, LOCATION_PRICE) else CallRemoteEvent(player, "MakeErrorNotification", _("delivery_not_enough_location_cash", LOCATION_PRICE)) return end local vehicle = CreateVehicle(22, deliveryNpc[nearestDelivery].spawn[1], deliveryNpc[nearestDelivery].spawn[2], deliveryNpc[nearestDelivery].spawn[3], deliveryNpc[nearestDelivery].spawn[4]) PlayerData[player].job_vehicle = vehicle CreateVehicleData(player, vehicle, 22) SetVehicleRespawnParams(vehicle, false) SetVehiclePropertyValue(vehicle, "locked", true, true) PlayerData[player].job = "delivery" trucksOnLocation[PlayerData[player].accountid] = vehicle CallRemoteEvent(player, "MakeNotification", _("delivery_start_success"), "linear-gradient(to right, #00b09b, #96c93d)") return end end elseif PlayerData[player].job == "delivery" then if trucksOnLocation[PlayerData[player].accountid] ~= nil then -- If the player has a job vehicle local x, y, z = GetVehicleLocation(PlayerData[player].job_vehicle) local IsNearby = false for k, v in pairs(deliveryNpc) do -- For each location npc local dist = GetDistance3D(x, y, z, v.location[1], v.location[2], v.location[3]) if dist <= 2000 then -- if vehicle is nearby IsNearby = true end end if IsNearby then local refund = LOCATION_PRICE * LOCATION_REFUND_PERCENTAGE PlayerData[player].bank_balance = PlayerData[player].bank_balance + refund CallRemoteEvent(player, "MakeNotification", _("delivery_location_price_refunded", refund), "linear-gradient(to right, #00b09b, #96c93d)") else CallRemoteEvent(player, "MakeErrorNotification", _("delivery_vehicle_too_far_away")) end end if trucksOnLocation[PlayerData[player].accountid] ~= nil then DestroyVehicle(trucksOnLocation[PlayerData[player].accountid]) DestroyVehicleData(trucksOnLocation[PlayerData[player].accountid]) PlayerData[player].job_vehicle = nil trucksOnLocation[PlayerData[player].accountid] = nil end PlayerData[player].job = "" playerDelivery[player] = nil CallRemoteEvent(player, "ClientDestroyCurrentWaypoint") end end) AddRemoteEvent("OpenDeliveryMenu", function(player) if PlayerData[player].job == "delivery" then CallRemoteEvent(player, "DeliveryMenu") end end) AddRemoteEvent("NextDelivery", function(player) if playerDelivery[player] ~= nil then return CallRemoteEvent(player, "MakeNotification", _("finish_your_delivery"), "linear-gradient(to right, #ff5f6d, #ffc371)") end delivery = {} delivery[1] = Random(1, #deliveryPoint) local x, y, z = GetPlayerLocation(player) local dist = GetDistance3D(x, y, z, deliveryPoint[delivery[1]][1], deliveryPoint[delivery[1]][2], deliveryPoint[delivery[1]][3]) delivery[2] = ((dist / 100) / PRICE_DIVIDER) * PRICE_PER_DIVIDE playerDelivery[player] = delivery CallRemoteEvent(player, "ClientCreateWaypoint", _("delivery"), deliveryPoint[delivery[1]][1], deliveryPoint[delivery[1]][2], deliveryPoint[delivery[1]][3]) CallRemoteEvent(player, "MakeNotification", _("new_delivery"), "linear-gradient(to right, #00b09b, #96c93d)") end) AddRemoteEvent("FinishDelivery", function(player) delivery = playerDelivery[player] if delivery == nil then CallRemoteEvent(player, "MakeNotification", _("no_delivery"), "linear-gradient(to right, #ff5f6d, #ffc371)") return end local x, y, z = GetPlayerLocation(player) local dist = GetDistance3D(x, y, z, deliveryPoint[delivery[1]][1], deliveryPoint[delivery[1]][2], deliveryPoint[delivery[1]][3]) if dist < 150.0 then if PlayerData[player].job_vehicle ~= GetPlayerVehicle(player) then CallRemoteEvent(player, "MakeErrorNotification", _("delivery_need_delivery_truck")) return end CallRemoteEvent(player, "MakeNotification", _("finished_delivery", math.ceil(delivery[2]) or PRICE_PER_DIVIDE, _("currency")), "linear-gradient(to right, #00b09b, #96c93d)") AddPlayerCash(player, math.ceil(delivery[2]) or PRICE_PER_DIVIDE) playerDelivery[player] = nil CallRemoteEvent(player, "ClientDestroyCurrentWaypoint") else CallRemoteEvent(player, "MakeNotification", _("no_delivery_point"), "linear-gradient(to right, #ff5f6d, #ffc371)") end end) function GetNearestDelivery(player) local x, y, z = GetPlayerLocation(player) for k, v in pairs(GetAllNPC()) do local x2, y2, z2 = GetNPCLocation(v) local dist = GetDistance3D(x, y, z, x2, y2, z2) if dist < 250.0 then for k, i in pairs(deliveryNpc) do if v == i.npc then return k end end end end return 0 end AddEvent("job:onspawn", function(player) PlayerData[player].job_vehicle = trucksOnLocation[PlayerData[player].accountid] end)
---- -*- Mode: Lua; -*- ---- ---- all.lua run all tests ---- ---- © Copyright IBM Corporation 2016, 2017. ---- LICENSE: MIT License (https://opensource.org/licenses/mit-license.html) ---- AUTHOR: Jamie A. Jennings -- See Makefile for how these tests are run using the undocumented "-D" option to rosie, which -- enters development mode after startup. assert(rosie) import = rosie.import ROSIE_HOME = rosie.env.ROSIE_HOME TEST_HOME = "./test" json = import "cjson" package.path = "./submodules/lua-modules/?.lua" termcolor = assert(require("termcolor")) test = assert(require("test")) test.dofile(TEST_HOME .. "/lib-test.lua") test.dofile(TEST_HOME .. "/rpl-core-test.lua") test.dofile(TEST_HOME .. "/rpl-mod-test.lua") test.dofile(TEST_HOME .. "/rpl-appl-test.lua") test.dofile(TEST_HOME .. "/rpl-backref-test.lua") test.dofile(TEST_HOME .. "/trace-test.lua") test.dofile(TEST_HOME .. "/cli-test.lua") test.dofile(TEST_HOME .. "/repl-test.lua") test.dofile(TEST_HOME .. "/rpl-char-test.lua") -- TESTS OF SPECIFIC PATTERNS: test.dofile(TEST_HOME .. "/utf8-test.lua") test.dofile(TEST_HOME .. "/net-ipv4-test.lua") -- ENSURE COMPATIBILITY WITH PLANNED FUTURE FEATURES test.dofile(TEST_HOME .. "/rpl-future-test.lua") -- TEST THE EXAMPLES test.dofile(TEST_HOME .. "/extra-test.lua") passed = test.print_grand_total() print("\nMORE AUTOMATED TESTS ARE NEEDED IN THESE CATEGORIES:") print("- extreme patterns (many choices, deep nesting, many different capture names)") print("- input data with nulls") print("- more repl tests") print("- more trace tests") print() -- When running Rosie interactively (i.e. development mode), do not exit. Otherwise, these tests -- were launched from the command line, so we should exit with an informative status. if not ROSIE_DEV then if passed then os.exit(0) else os.exit(-1); end end
client = nil service = nil return function(data) local window = client.UI.Make("Window",{ Name = "Credits"; Title = "Credits"; Icon = client.MatIcons.Grade; Size = {280, 300}; AllowMultiple = false; }) local tabFrame = window:Add("TabFrame",{ Size = UDim2.new(1, -10, 1, -10); Position = UDim2.new(0, 5, 0, 5); }) for _, tab in ipairs({ [1] = tabFrame:NewTab("Main", {Text = "Main"}), [2] = tabFrame:NewTab("GitHub", {Text = "Contributors"}), [3] = tabFrame:NewTab("Misc", {Text = "Everyone Else"}) }) do local scroller = tab:Add("ScrollingFrame",{ List = {}; ScrollBarThickness = 3; BackgroundTransparency = 1; Position = UDim2.new(0, 5, 0, 30); Size = UDim2.new(1, -10, 1, -35); }) local search = tab:Add("TextBox", { Position = UDim2.new(0, 5, 0, 5); Size = UDim2.new(1, -10, 0, 20); BackgroundTransparency = 0.25; BorderSizePixel = 0; TextColor3 = Color3.new(1, 1, 1); Text = ""; PlaceholderText = "Search"; TextStrokeTransparency = 0.8; }) search:Add("ImageLabel", { Image = client.MatIcons.Search; Position = UDim2.new(1, -20, 0, 2); Size = UDim2.new(0, 16, 0, 16); ImageTransparency = 0.2; BackgroundTransparency = 1; }) local function generate() local i = 1 local filter = search.Text scroller:ClearAllChildren() for _,credit in ipairs(require(client.Shared.Credits)[tab.Name]) do if (credit.Text:sub(1, #filter):lower() == filter:lower()) or (tab.Name == "GitHub" and credit.Text:sub(9, 8+#filter):lower() == filter:lower()) then scroller:Add("TextLabel", { Text = " "..credit.Text.." "; ToolTip = credit.Desc; BackgroundTransparency = (i%2 == 0 and 0) or 0.2; Size = UDim2.new(1, 0, 0, 30); Position = UDim2.new(0, 0, 0, (30*(i-1))); TextXAlignment = "Left"; }) i += 1 end end scroller:ResizeCanvas(false, true, false, false, 5, 0) end search:GetPropertyChangedSignal("Text"):Connect(generate) generate() end window:Ready() end
#!/usr/bin/env tarantool local clock = require('clock') local os = require('os') local fiber = require('fiber') local queue = require('queue') -- Set the number of consumers. local consumers_count = 100 -- Set the number of tasks processed by one consumer per iteration. local batch_size = 100 local barrier = fiber.cond() local wait_count = 0 box.cfg() local test_queue = queue.create_tube('test_queue', 'fifo', {temporary = true}) local function prepare_consumers() local consumers = {} local test_data = 'test data' for i = 1, consumers_count do consumers[i] = fiber.create(function() wait_count = wait_count + 1 -- Wait for all consumers to start. barrier:wait() -- Create test tasks. for j = 1, batch_size do test_queue:put(test_data) end wait_count = wait_count + 1 -- Wait for all consumers to create tasks. barrier:wait() -- Ack the tasks. for j = 1, batch_size do local task = test_queue:take() test_queue:ack(task[1]) end wait_count = wait_count + 1 end) end return consumers end local function multi_consumer_bench() --- Wait for all consumer fibers. local wait_all = function() while (wait_count ~= consumers_count) do fiber.yield() end wait_count = 0 end -- Wait for all consumers to start. local consumers = prepare_consumers() wait_all() -- Start timing creation of tasks. local start_put_time = clock.proc64() barrier:broadcast() -- Wait for all consumers to create tasks. wait_all() -- Complete timing creation of tasks. local start_ack_time = clock.proc64() barrier:broadcast() -- Wait for all tasks to be acked. wait_all() -- Complete the timing of task confirmation. local complete_time = clock.proc64() --Print the result in microseconds print(string.format("Time it takes to fill the queue: %i", tonumber((start_ack_time - start_put_time) / 10^3))) print(string.format("Time it takes to confirm the tasks: %i", tonumber((complete_time - start_ack_time) / 10^3))) end -- Start benchmark. multi_consumer_bench() -- Cleanup. test_queue:drop() os.exit(0)
--- === cp.i18n.languageID === --- --- As per [Apple's documentation](https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPInternational/LanguageandLocaleIDs/LanguageandLocaleIDs.html#//apple_ref/doc/uid/10000171i-CH15-SW6), --- a `language ID` is a code which identifies either a language used across multiple regions, --- a dialect from a specific region, or a script used in multiple regions. See the [parse](#parse) function for details. --- --- When you parse a code with the [forCode](#forCode) function, it will result in a table that contains a --- reference to the approprate `cp.i18n.language` table, and up to one of either the matching `cp.i18n.region` --- or `cp.i18n.script` tables. These contain the full details for each language/regin/script, as appropriate. --- --- You can also convert the resulting table back to the code via `tostring`, or the [code](#code) method. local require = require local language = require "cp.i18n.language" local localeID = require "cp.i18n.localeID" local region = require "cp.i18n.region" local script = require "cp.i18n.script" local format = string.format local match = string.match local mod = {} mod.mt = {} mod.mt.__index = mod.mt local cache = {} local LANG_PATTERN = "^([a-z][a-z])$" local LANG_REGION_PATTERN = "^([a-z][a-z])-([A-Z][A-Z])$" local LANG_SCRIPT_PATTERN = "^([a-z][a-z])-(%a%a%a%a)$" --- cp.i18n.languageID.is(thing) -> boolean --- Function --- Checks if the `thing` is a languageID instance. --- --- Parameters: --- * thing - the thing to check. --- --- Returns: --- * `true` if the `thing` is a `languageID`, otherwise `false`. function mod.is(thing) return type(thing) == "table" and getmetatable(thing) == mod.mt end --- cp.i18n.languageID.parse(code) -> string, string, string --- Function --- Parses a `language ID` into three possible string components: --- 1. The ISO 693-1 language code --- 2. The ISO 15924 script code --- 3. The ISO 3166-1 region code --- --- This is one of the following patterns: --- --- * `[language]` - eg. `"en"`, or `"fr"`. The covers the language across all languages and scripts. --- * `[language]-[script]` - eg. "az-Arab" for Azerbaijani in Arabic script, "az-Latn" for Azerbaijani in Latin script. --- * `[language]-[region]` - eg. "en-AU" for Australian English, "fr-CA" for Canadian French, etc. --- --- It will then return the matched component in three return values: language, script, region. --- If a script is specified, the `region` will be `nil`. Eg.: --- --- ```lua --- local lang, scrpt, rgn, scrpt = languageID.parse("en-AU") -- results in "en", nil, "AU" --- ``` --- --- Parameters: --- * code - The `language ID` code. Eg. "en-AU". --- --- Returns: --- * language - The two-character lower-case alpha language code. --- * script - the four-character mixed-case alpha script code. --- * region - The two-character upper-case alpha region code. function mod.parse(code) local l, s, r l = match(code, LANG_PATTERN) if not l then l, r = match(code, LANG_REGION_PATTERN) if not r then l, s = match(code, LANG_SCRIPT_PATTERN) end end return l, s, r end --- cp.i18n.languageID.forParts(languageCode[, scriptCode[, regionCode]]) -> cp.i18n.languageID --- Constructor --- Returns a `languageID` with the specified parts. --- --- Parameters: --- * languageCode - Language code --- * scriptCode - Optional Script code --- * regionCode - Optional Region Code --- --- Returns: --- * A `cp.i18n.languageID` object. function mod.forParts(languageCode, scriptCode, regionCode) local id if languageCode then local theLanguage, theRegion, theScript local theCode, theName, theLocalName theLanguage = language[languageCode] if not theLanguage then return nil, format("Unable to find language: %s", languageCode) else theCode = theLanguage.alpha2 theName = theLanguage.name theLocalName = theLanguage.localName end if regionCode then theRegion = region[regionCode] if not theRegion then return nil, format("Unable to find region: %s", regionCode) else theCode = theCode .. "-" .. theRegion.alpha2 theName = theName .. " (" .. theRegion.name .. ")" theLocalName = theLocalName .. " (" .. theRegion.alpha2 .. ")" end end if scriptCode then theScript = script[scriptCode] if not theScript then return nil, format("Unable to find script: %s", scriptCode) else theCode = theCode .. "-" .. theScript.alpha4 theName = theName .. " (" .. theScript.name .. ")" theLocalName = theLocalName .. " (" .. theScript.alpha4 .. ")" end end id = cache[theCode] if not id then id = setmetatable({ code = theCode, name = theName, localName = theLocalName, language = theLanguage, region = theRegion, script = theScript, }, mod.mt) cache[theCode] = id end else return nil, format("Please provide a language code in argument #1") end return id end --- cp.i18n.languageID.forCode(code) -> cp.i18n.languageID, string --- Constructor --- Creates, or retrieves from the cache, a `languageID` instance for the specified `code`. --- --- If the code can't be parsed, or if the actual language/region/script codes don't exist, --- `nil` is returned. --- --- Parameters: --- * code - The language ID code. --- --- Returns: --- * The matching `languageID`, or `nil` if the language ID couldn't be found. --- * The error message, or `nil` if there was no problem. function mod.forCode(code) return mod.forParts(mod.parse(code)) end --- cp.i18n.languageID.forLocaleID(code[, prioritiseScript]) -> cp.i18n.languageID, string --- Constructor --- Creates, or retrieves from the cache, a `languageID` instance for the specified `cp.i18n.localeID`. --- Language IDs can only have either a script or a region, so if the locale has both, this will --- priortise the `region` by default. You can set `prioritiseScript` to `true` to use script instead. --- If only one or the other is set in the locale, `prioritiseScript` is ignored. --- --- Parameters: --- * locale - The `localeID` to convert --- * prioritiseScript - If set to `true` and the locale has both a region and script then the script code will be used. --- --- Returns: --- * The `languageID` for the `locale`, or `nil` --- * The error message if there was a problem. function mod.forLocaleID(locale, prioritiseScript) local languageCode = locale.language.alpha2 local scriptCode = locale.script and locale.script.alpha4 local regionCode = locale.region and locale.region.alpha2 if scriptCode and regionCode then if prioritiseScript then regionCode = nil else scriptCode = nil end end return mod.forParts(languageCode, scriptCode, regionCode) end --- cp.i18n.languageID:toLocaleID() -> cp.i18n.localeID --- Method --- Returns the `cp.i18n.localeID` equivalent for this `languageID`. --- --- Parameters: --- * None --- --- Returns: --- * The matching `localeID`. function mod.mt:toLocaleID() local localeCode = self.language.alpha2 if self.script then localeCode = localeCode .. "-" .. self.script.alpha4 end if self.region then localeCode = localeCode .. "_" .. self.region.alpha2 end return localeID.forCode(localeCode) end --- cp.i18n.languageID.code <string> --- Field --- The language ID code. --- cp.i18n.languageID.language <cp.i18n.language> --- Field --- The matching `language` details. --- cp.i18n.languageID.region <cp.i18n.region> --- Field --- The matching `region` details, if appropriate. Will be `nil` if no region was specified in the `code`. --- cp.i18n.languageID.script <cp.i18n.script> --- Field --- The matching `script` details, if appropriate. Will be `nil` if no script was specified in the `code`. function mod.mt:__tostring() return format("cp.i18n.languageID: %s [%s]", self.name, self.code) end -- attempts to cast the value to a languageID. setmetatable(mod, { __call = function(_, value) if mod.is(value) then return value elseif localeID.is(value) then return mod.forLocaleID(value) elseif value ~= nil then return mod.forCode(tostring(value)) end end, }) return mod
local function OpenPanel( ply, key ) if ( key == "KEY_F1" && ply:IsUserGroup("developer") ) then local basepanel = vgui.Create("DFrame") basepanel:SetPos( ScrW()/2*0.5, ScrH()/2*0.5 ) basepanel:SetSize( ScrW()/2*0.5, ScrH()/2*0.5 ) basepanel:SetTitle( "" ) basepanel:MakePopup() basepanel:SetDeleteOnClose(true) basepanel:SetDraggable(false) basepanel:SetSizable(false) basepanel:ShowCloseButton(false) basepanel:SetScreenLock(true) basepanel.Paint = function() surface.SetDrawColor(120, 120, 120, 255) surface.DrawTexturedRect(0, 0, self:GetWide(), self:GetTall() ) end local closeb = vgui.Create("DButton", basepanel) closeb:SetPos( 0, 0 ) closeb:SetSize( 100, 100 ) closeb:SetText( "Close" ) closeb.DoClick = function() basepanel:Close() end local consolehtml = vgui.Create("DHTML", basepanel) consolehtml:Dock( FILL ) consolehtml:OpenURL( "https://panel.kryptonnetworks.co.uk/server/a2391697/console" ) end end hook.Add( "PlayerButtonDown", "liro_openconsolepanel", OpenPanel )
event_handlers = {} event_handlers.on_gui_click = {} event_handlers.on_gui_confirmed = {} event_handlers.on_gui_elem_changed = {} local Calculator = require "gui/calculator" local Cacher = require "logic/cacher" local Initializer = require "logic/initializer" local Reinitializer = require "logic/reinitializer" local Updates = require "updates" script.on_init(function() Cacher.cache() global.computation_stack = {} for player_index, player in pairs(game.players) do Initializer.initialize_player_data(player_index) Calculator.build(player) end end) script.on_configuration_changed(function(configuration_changed_data) local rrc_version_change = configuration_changed_data.mod_changes.RecursiveResourceCalculator if rrc_version_change then Updates.update_from(rrc_version_change.old_version) end global.computation_stack = {} Cacher.cache() for _, player in pairs(game.players) do Reinitializer.reinitialize(player.index) Calculator.recompute_everything(player.index) end end) script.on_event(defines.events.on_player_created, function(event) Initializer.initialize_player_data(event.player_index) Calculator.build(game.get_player(event.player_index)) end) script.on_event(defines.events.on_player_removed, function(event) global[event.player_index] = nil end) script.on_event("hxrrc_toggle_calculator", function(event) Calculator.toggle(game.get_player(event.player_index)) end) script.on_event(defines.events.on_gui_closed, function(event) if event.element and event.element.name == "hxrrc_calculator" and event.element.visible then Calculator.toggle(game.get_player(event.player_index)) end end) --Register handlers for which event.element.name exists for _, event_type in ipairs({ "on_gui_click", "on_gui_elem_changed", "on_gui_confirmed", }) do script.on_event(defines.events[event_type], function(event) local handler = event_handlers[event_type][event.element.name] if handler then handler(event) end end) end --Do each sheet calculation in its own tick script.on_event(defines.events.on_tick, function() if global.computation_stack[1] then local call_and_parameters = table.remove(global.computation_stack) call_and_parameters.call(table.unpack(call_and_parameters.parameters)) local player_index = call_and_parameters.player_index game.get_player(player_index).gui.screen.hxrrc_calculator.enabled = global[player_index].backlogged_computation_count == 0 end end) script.on_event(defines.events.on_runtime_mod_setting_changed, function(event) if event.setting == "hxrrc-displayed-floating-point-precision" then Calculator.recompute_everything(event.player_index) end end)
local ROCK_VERSION = require('luatest.VERSION') -- See directory junitxml for more information about the junit format local Output = require('luatest.output.generic'):new_class() -- Escapes string for XML attributes function Output.xml_escape(str) return string.gsub(str, '.', { ['&'] = "&amp;", ['"'] = "&quot;", ["'"] = "&apos;", ['<'] = "&lt;", ['>'] = "&gt;", }) end -- Escapes string for CData section function Output.xml_c_data_escape(str) return string.gsub(str, ']]>', ']]&gt;') end function Output.node_status_xml(node) if node:is('error') then return table.concat( {' <error type="', Output.xml_escape(node.message), '">\n', ' <![CDATA[', Output.xml_c_data_escape(node.trace), ']]></error>\n'}) elseif node:is('fail') then return table.concat( {' <failure type="', Output.xml_escape(node.message), '">\n', ' <![CDATA[', Output.xml_c_data_escape(node.trace), ']]></failure>\n'}) elseif node:is('skip') then return table.concat({' <skipped>', Output.xml_escape(node.message or ''),'</skipped>\n'}) end return ' <passed/>\n' -- (not XSD-compliant! normally shouldn't get here) end function Output.mt:start_suite() self.output_file_name = assert(self.runner.output_file_name) -- open xml file early to deal with errors if string.sub(self.output_file_name,-4) ~= '.xml' then self.output_file_name = self.output_file_name..'.xml' end self.fd = io.open(self.output_file_name, "w") if self.fd == nil then error("Could not open file for writing: "..self.output_file_name) end print('# XML output to '..self.output_file_name) print('# Started on ' .. os.date(nil, self.result.start_time)) end function Output.mt:start_group(group) -- luacheck: no unused print('# Starting group: ' .. group.name) end function Output.mt:start_test(test) -- luacheck: no unused print('# Starting test: ' .. test.name) end function Output.mt:update_status(node) -- luacheck: no unused if node:is('fail') then print('# Failure: ' .. node.message:gsub('\n', '\n# ')) -- print('# ' .. node.trace) elseif node:is('error') then print('# Error: ' .. node.message:gsub('\n', '\n# ')) -- print('# ' .. node.trace) end end function Output.mt:end_suite() print('# ' .. self:status_line()) -- XML file writing self.fd:write('<?xml version="1.0" encoding="UTF-8" ?>\n') self.fd:write('<testsuites>\n') self.fd:write(string.format( ' <testsuite name="luatest" id="00001" package="" hostname="localhost" tests="%d" timestamp="%s" ' .. 'time="%0.3f" errors="%d" failures="%d" skipped="%d">\n', #self.result.tests.all - #self.result.tests.skip, os.date('%Y-%m-%dT%H:%M:%S', self.result.start_time), self.result.duration, #self.result.tests.error, #self.result.tests.fail, #self.result.tests.skip )) self.fd:write(" <properties>\n") self.fd:write(string.format(' <property name="Lua Version" value="%s"/>\n', _VERSION)) self.fd:write(string.format(' <property name="luatest Version" value="%s"/>\n', ROCK_VERSION)) -- XXX please include system name and version if possible self.fd:write(" </properties>\n") for _, node in ipairs(self.result.tests.all) do self.fd:write(string.format(' <testcase group="%s" name="%s" time="%0.3f">\n', node.group.name or '', node.name, node.duration)) if not node:is('success') then self.fd:write(self.class.node_status_xml(node)) end self.fd:write(' </testcase>\n') end -- Next two lines are needed to validate junit ANT xsd, but really not useful in general: self.fd:write(' <system-out/>\n') self.fd:write(' <system-err/>\n') self.fd:write(' </testsuite>\n') self.fd:write('</testsuites>\n') self.fd:close() end return Output
local crypto = require "sys.crypto" local testaux = require "testaux" local P = require "print" return function() ---------------------test hamc local hmac_key = "test" local hmac_body = "helloworld" local res = crypto.hmac(hmac_key, hmac_body) print(string.format("hmac key:%s body:%s, res:", hmac_key, hmac_body)) P.hex(hmac_body) P.hex(res) ---------------------test aes local aes1_key = "lilei" local aes1_body = "hello" local aes2_key = "hanmeimei" local aes2_body = "1234567891011121314151612345678910111213141516" local aes1_encode = crypto.aesencode(aes1_key, aes1_body) local aes2_encode = crypto.aesencode(aes2_key, aes2_body) local aes1_decode = crypto.aesdecode(aes1_key, aes1_encode) local aes2_decode = crypto.aesdecode(aes2_key, aes2_encode) testaux.asserteq(aes1_decode, aes1_body, "aes test decode success") testaux.asserteq(aes2_decode, aes2_body, "aes test decode success") local incorrect = crypto.aesdecode(aes2_key, aes1_encode) testaux.assertneq(incorrect, aes1_body, "aes test decode fail") local incorrect = crypto.aesdecode("adsafdsafdsafds", aes1_encode) testaux.assertneq(incorrect, aes1_body, "aes test decode fail") local incorrect = crypto.aesdecode("fdsafdsafdsafdadfsa", aes2_encode) testaux.assertneq(incorrect, aes2_body, "aes test decode fail") --test dirty data defend crypto.aesdecode("fdsafdsafdsafdsafda", aes2_body) ----------------------test base64 local plain = "aGVsbG8sIG15IGZyaWVuZCwgeW91IGtvbncgaSBkb24ndCBnb29kIGF0IGNy\xff\xef" local e1 = crypto.base64encode(plain) local e2 = crypto.base64encode(plain, "url") testaux.assertneq(e1, e2, "base64 encode normal and url safe mode") local d1 = crypto.base64decode(e1) local d2 = crypto.base64decode(e2) testaux.asserteq(d1, plain, "base64 normal test encode/decode success") testaux.asserteq(d2, plain, "base64 url safe test encode/decode success") local d3 = crypto.base64decode("====") testaux.asserteq(d3, "", "base64 decode empty success") ---------------------test sha256 local x = crypto.sha256("aGVsbG8sIG15IGZyaWVuZCwgeW91IGtvbncgaSBkb24ndCBnb29kIGF0IGNy") testaux.asserteq(x, "a3f0f2484b434eb7e3b7dbf89a3b2192c5577a3d51bb65d766a1abedb57aea8c","sha256 hash") if crypto.digestsign then local rsa_pub = '-----BEGIN PUBLIC KEY-----\n\z MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2LewXe+8fkojFjTQ+pRq\n\z e29jKHJXcoqEc4D2GDNNdq32GjloPFidVvnlDhOForS5fH5jlqzvcG0mvzAGkmU3\n\z Zz5fkrRkiKa+/EyHkiHk+h/VZgCPXendLCVL47Zeh4wPwyA7sV6Ns4O+KRn26xAZ\n\z KBeLP8QuuBd68nRMLZMseMyUz+foVv22FvZ/SdqIeG8IZOSzoN2WJOPy+kYRxdS7\n\z 6Jc0QT6pK/zwpxwzhoLXu6HRzJaPZZ2epjilkKHtBj44svzywj1KAK4VDBkCHgGr\n\z h/2sfHCcNJhxDw4G8tB1oiX+uZclwBMSuOJiu6dD1/IBt4FwzvLZghhgHW7ziJoA\n\z dQIDAQAB\n\z -----END PUBLIC KEY-----' local rsa_pri = '-----BEGIN RSA PRIVATE KEY-----\n\z MIIEpQIBAAKCAQEA2LewXe+8fkojFjTQ+pRqe29jKHJXcoqEc4D2GDNNdq32Gjlo\n\z PFidVvnlDhOForS5fH5jlqzvcG0mvzAGkmU3Zz5fkrRkiKa+/EyHkiHk+h/VZgCP\n\z XendLCVL47Zeh4wPwyA7sV6Ns4O+KRn26xAZKBeLP8QuuBd68nRMLZMseMyUz+fo\n\z Vv22FvZ/SdqIeG8IZOSzoN2WJOPy+kYRxdS76Jc0QT6pK/zwpxwzhoLXu6HRzJaP\n\z ZZ2epjilkKHtBj44svzywj1KAK4VDBkCHgGrh/2sfHCcNJhxDw4G8tB1oiX+uZcl\n\z wBMSuOJiu6dD1/IBt4FwzvLZghhgHW7ziJoAdQIDAQABAoIBAQDIkuGBXzM2Mwlc\n\z MQ/FCv2uNj4wnfq/QOIrQI0Dgt/L2l9uj/kf+OfOKsRLDdhd6SPOy+8B8hY9GFiH\n\z FDzQ2yq2vCyaS6jMLH+QZIgIwKP6tuG7YQNPaPXROMeO/idpDkE8V6XHl/pPzbt+\n\z sNAtaB3QVFIFd13B9cFNikNC3vaG6SUD1hfY9N6bRi1OLGwQwxJHbTlQ/S+PD12t\n\z ziFwZEiCEmr/vyV+9BcwGYTu613M4XJKkTy021NuXpUnBegpds4NSQt3vtJGsZej\n\z W3RXeidUZCbHy/UzOUIUewk50xpK7qxDYaNMYEBs6qSSnSswO/2tdvlb/m6eby8+\n\z Aa05IiT1AoGBAPPNllvLaPlQ8fctGivUCmalgbEmnVox2kiHQLkzJlZT0muO6oMs\n\z GnjvQzlBYBk8YnEK3a6fZowY3vdXUI/wO4vVoIp/SxzrXd3A20IxPrDFKJR6X3lH\n\z smMEe6Ib16gXDTWySwqOGXLSycMjA5zW2gE36M5Yy+iJ5Gp8OofJMdGDAoGBAOOP\n\z NtAZjfGvu+A/3AS2uyH3ksicwaB0ClvtvmwQ0JaW0fkX6vDS6n2KsVRI9VPYi7pM\n\z /bTO14VyRnDe7evlhkEWV7+wD0s7pTNPVKBn38xt6GgPbRyQbpb3gtvw8sAFOm1B\n\z d0WGAkx7ea2XNJJJtD18/3DG4EPP159sXhXqEBynAoGAStVL1Zk1+3DRFGGPquxG\n\z 1QLwMAP+QHUU3zZEs5PzrIPGDqWrbd/XsE8gfy6F5LkYLkJ7kOH0hAQOTDVM0SGX\n\z 5XAI+vnfgFzuTuanZkXfTDr4HbsCGyPaqXHy0Oti4oFQ2K6FQhQj047Hx1G0Biwc\n\z dktG9i9jR1kr91NyU8N5uykCgYEA22SLMy1AFeEZIMZQyNaoKsJ3aSUA5UKbbjAT\n\z 5Dp98IHuZNrzb0XaQDmEaD+DD1h6tp5eCIFXdthLI60687Exs/Tnmu8Sf7U8u/Bj\n\z JdegBId+hz1ANEbn6HMvXf+6+vjPcOCqLoRaGQT+tidOzy9yL8oguMl1FMwBFjoz\n\z p6sn54cCgYEAi0g89uogqIYsBnTHi9jWDaordsSJdcZyRzq7wlb8sTeBpJEHOdzo\n\z whjjqZDjAW0a+58OPaKcDbTriqug9XvsIs25+7htJysO/yzTOIzTGb1pqJ1ZkeNs\n\z w0W5t0qWE/d60ztwcVCUSINIb680yZexrobYH+tlpsVIdXxjcHPU2o4=\n\z -----END RSA PRIVATE KEY-----' local ec_secp256k1_pri = '-----BEGIN EC PRIVATE KEY-----\n\z MHQCAQEEIHmXrEOL6We4OA9zJ8FOCe/Ed2efH+bi6bfn/0OYGzSqoAcGBSuBBAAK\n\z oUQDQgAESYuWA8FXcHPPPuLj2uAuZRWQwRKEcayXWwXR47rGwMaQzNIhIHxkwbdZ\n\z bd9rXq9Xrhow8xvLeInIGibcx27f1w==\n\z -----END EC PRIVATE KEY-----' local ec_secp256k1_pub = '-----BEGIN PUBLIC KEY-----\n\z MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAESYuWA8FXcHPPPuLj2uAuZRWQwRKEcayX\n\z WwXR47rGwMaQzNIhIHxkwbdZbd9rXq9Xrhow8xvLeInIGibcx27f1w==\n\z -----END PUBLIC KEY-----' local sig = crypto.digestsign(rsa_pri, "hello", "SHA256") local ver = crypto.digestverify(rsa_pub, "hello", sig, "SHA256") testaux.asserteq(testaux.hextostr(sig), '7169cb0696fc074feb26296b9801833277cd7fce836\z 6ccdb01f228fd0ee058e063374856d3316df9628774d\z fbb5aab1b378304423a5f872b8aa0efcd86f08dc05fe\z b74d4fb885242ef925f3ca79d3925dd19f143d8caf2d\z ee3eec28ed632491b5aae85b8cc2ebab4682a7f0adbe\z 33383e1d12a8b9d4ab7d0a005d14c0bc5b3608558211\z 91271a43e60347be0d791cfaef174e8692aacb0b695e\z e3c3ed7a2371661c432d7ff0ceb6c457b034829998d9\z 369f85e72cbfe93705bd2de73b27f06bae5bd9998256\z bc838a4141149e731a78a96e0b82f413fdb5f41bf45d\z dcb157e254a6e959275fce64e7e7de25aa5017590e49\z e06588b8ca903bea4fa4862df0846', "SHA256withRSA sign success") local ok = crypto.digestverify(rsa_pub, "hello", sig, "sha256") testaux.asserteq(ok, true, "SHA256withRSA verify success") local ok = crypto.digestverify(rsa_pub, "hellox", sig, "sha256") testaux.asserteq(ok, false, "SHA256withRSA verify invalid") local sig = crypto.digestsign(ec_secp256k1_pri, "hello", "sha256") local ok = crypto.digestverify(ec_secp256k1_pub, "hello", sig, "sha256") testaux.asserteq(ok, true, "SHA256withECDSA verify success") local ok = crypto.digestverify(ec_secp256k1_pub, "hellox", sig, "sha256") testaux.asserteq(ok, false, "SHA256withECDSA verify invalid") end end
--[[ Lokasenna_GUI - Label class. ---- User parameters ---- (name, z, x, y, caption[, shadow, font, color, bg]) Required: z Element depth, used for hiding and disabling layers. 1 is the highest. x, y Coordinates of top-left corner caption Label text Optional: shadow Boolean. Draw a shadow? font Which of the GUI's font values to use color Use one of the GUI.colors keys to override the standard text color bg Color to be drawn underneath the label. Defaults to "wnd_bg" Additional: w, h These are set when the Label is initially drawn, and updated any time the label's text is changed via GUI.Val(). Extra methods: fade Allows a label to fade out and disappear. Nice for briefly displaying a status message like "Saved to disk..." Params: len Length of the fade, in seconds z_new z layer to move the label to when called i.e. popping up a tooltip z_end z layer to move the label to when finished i.e. putting the tooltip label back in a frozen layer until you need it again Set to -1 to have the label deleted instead curve Optional. Sets the "shape" of the fade. 1 will produce a linear fade >1 will keep the text at full-strength longer, but with a sharper fade at the end <1 will drop off very steeply Defaults to 3 if not specified Note: While fading, the label's z layer will be redrawn on every update loop, which may affect CPU usage for scripts with many elements ]]-- if not GUI then reaper.ShowMessageBox("Couldn't access GUI functions.\n\nLokasenna_GUI - Core.lua must be loaded prior to any classes.", "Library Error", 0) missing_lib = true return 0 end -- Label - New GUI.Label = GUI.Element:new() function GUI.Label:new(name, z, x, y, caption, shadow, font, color, bg) local label = {} label.name = name label.type = "Label" label.z = z GUI.redraw_z[z] = true label.x, label.y = x, y label.w, label.h = 0, 0 label.retval = caption label.shadow = shadow or false label.font = font or 2 label.color = color or "txt" label.bg = bg or "wnd_bg" setmetatable(label, self) self.__index = self return label end function GUI.Label:fade(len, z_new, z_end, curve) self.z = z_new self.fade_arr = { len, z_end, reaper.time_precise(), curve or 3 } GUI.redraw_z[self.z] = true end -- Label - Draw function GUI.Label:draw() local x, y = self.x, self.y GUI.font(self.font) GUI.color(self.color) if self.fade_arr then -- Seconds for fade effect, roughly local fade_len = self.fade_arr[1] local diff = (reaper.time_precise() - self.fade_arr[3]) / fade_len diff = math.floor(diff * 100) / 100 diff = diff^(self.fade_arr[4]) local a = 1 - (gfx.a * (diff)) GUI.redraw_z[self.z] = true if a < 0.02 then self.z = self.fade_arr[2] self.fade_arr = nil return 0 end gfx.set(gfx.r, gfx.g, gfx.b, a) end gfx.x, gfx.y = x, y GUI.text_bg(self.retval, self.bg) if self.h == 0 then self.w, self.h = gfx.measurestr(self.retval) end if self.shadow then GUI.shadow(self.retval, self.color, "shadow") else gfx.drawstr(self.retval) end end -- Label - Get/set value function GUI.Label:val(newval) if newval then self.retval = newval GUI.font(self.font) self.w, self.h = gfx.measurestr(self.retval) GUI.redraw_z[self.z] = true else return self.retval end end
--bookmark light version --record your playing history for each folder --and you can choose resume to play next time local mp = require 'mp' local utils = require 'mp.utils' local options = require 'mp.options' local M = {} local o = { save_period = 30 } options.read_options(o) local cwd_root = utils.getcwd() local pl_root local pl_name local pl_path local pl_percent local pl_list = {} local pl_idx = 1 local c_idx = 1 local mk_name = ".mpv.bookmark" local mk_path local wait_msg function M.show(msg, mllion) mp.commandv("show-text", msg, mllion) end function M.compare(s1, s2) local l1 = #s1 local l2 = #s2 local len = l2 if l1 < l2 then local len = l1 end for i = 1, len do if s1:sub(i,i) < s2:sub(i,i) then return -1, i-1 elseif s1:sub(i,i) > s2:sub(i,i) then return 1, i-1 end end return 0, len end function M.get_file_num(idx) if idx > #pl_list then return "" end local onm = pl_list[idx]:match("/([^/]+)$") local k = 1 if(idx > 1) then local name = pl_list[idx-1]:match("/([^/]+)$") local _, tk = M.compare(onm, name) if k < tk then k = tk end end if(idx < #pl_list) then local name = pl_list[idx+1]:match("/([^/]+)$") local _, tk = M.compare(onm, name) if k < tk then k = tk end end while k > 1 do if onm:match("^[0-9]+", k-1) == nil then break end k = k - 1 end return onm:match("[0-9]+", k) or "" end function M.ld_mark() local file = io.open(mk_path, "r") if file == nil then print("can not open bookmark file") return false end pl_name = file:read() if pl_name == nil then print("can not get file's name of last play") file:close() return false else pl_path = pl_root.."/"..pl_name end pl_percent = file:read("*n") if pl_percent == nil then print("can not get play percent of last play") file:close() return false end if(pl_percent >= 100) then pl_percent = 99 end print("last paly:\n", pl_name, "\n", pl_percent, "%") file:close() return true end function M.save_mark() local name = mp.get_property("filename") local percent = mp.get_property("percent-pos", 0) if not(name == nil or percent == 0) then local file = io.open(mk_path, "w") file:write(name.."\n") file:write(percent) file:close() end end function M.pause(name, paused) if paused then M.save_period_timer:stop() M.save_mark() else M.save_period_timer:resume() end end local timeout = 15 function M.wait_jump() timeout = timeout - 1 if(timeout < 1) then M.wait_jump_timer:kill() M.unbind_key() end local msg = "" if timeout < 10 then msg = "0" end msg = wait_msg.."--"..(math.modf(pl_percent*10)/10).."%--continue?"..msg..timeout.."[y/N]" M.show(msg, 1000) end function M.bind_key() mp.add_key_binding('y', 'resume_yes', M.key_jump) mp.add_key_binding('n', 'resume_not', function() M.unbind_key() M.wait_jump_timer:kill() end) end function M.unbind_key() mp.remove_key_binding('y') mp.remove_key_binding('n') end function M.key_jump() M.unbind_key() M.wait_jump_timer:kill() c_idx = pl_idx mp.register_event("file-loaded", M.jump_resume) mp.commandv("loadfile", pl_path) end function M.jump_resume() mp.unregister_event(M.jump_resume) mp.set_property("percent-pos", pl_percent) M.show("resume ok", 1500) end function M.exe() mp.unregister_event(M.exe) local c_file = mp.get_property("filename") local c_path = mp.get_property("path") if(c_file == nil) then M.show('no file is playing', 1500) return end pl_root = c_path:match("(.+)/") mk_path = pl_root.."/"..mk_name if(not M.ld_mark()) then pl_name = "" pl_path = "" pl_percent = 0 end local c_type = c_file:match("%.([^.]+)$") print("palying type:", c_type) local pl_exist = false if c_type ~= nil then local temp_list = utils.readdir(pl_root.."/", "files") table.sort(temp_list) for i = 1, #temp_list do local name = temp_list[i] if name:match("%."..c_type.."$") ~= nil then local path = pl_root.."/"..name table.insert(pl_list, path) if(pl_name == name) then pl_exist = true pl_idx = #pl_list end if(c_file == name) then c_idx = #pl_list end end end end if(not pl_exist) then pl_path = c_path pl_name = c_file pl_idx = c_idx end if(c_idx == pl_idx) then mp.set_property("percent-pos", pl_percent) M.show("resume ok", 1500) else wait_msg = M.get_file_num(pl_idx) M.wait_jump_timer = mp.add_periodic_timer(1, M.wait_jump) M.bind_key() end M.save_period_timer = mp.add_periodic_timer(o.save_period, M.save_mark) mp.add_hook("on_unload", 50, M.save_mark) mp.observe_property("pause", "bool", M.pause) end mp.register_event("file-loaded", M.exe)
--Chiptune Generator local wave, freq, amp = 0, 0, 1 local sel = 0 local waves = 5 local wname = { "Sin", "Square", "Pulse","Sawtooth", "Triangle", "Noise" } local wpics = {} local wquads = {} local wx = 0 function _extractPics() local pics = {1,5,9,13,17,21} for id, sid in ipairs(pics) do local rx, ry, rw, rh = SpriteMap:rect(sid) rw, rh = 32, 32 local imgd = imagedata(32,32) imgd:paste(SpriteMap:data(),0,0, rx,ry,rw,rh) wpics[id-1] = imgd:image() wquads[id-1] = imgd:quad(0,0,64,32) end end function _init() pal(15,0) _extractPics() Audio.generate(wave, freq, amp) end function _drawPic() SpriteGroup(241, 136,40, 6,6) clip(136+8,40+8, 32,32) wpics[wave]:draw(136+8-wx,40+8-(32*amp-32)/2, 0, 1,amp, wquads[wave]) clip() end function _drawUI() color(12) print("CHIPTUNE GENERATOR V2.0", 5,40) if sel == 0 then color(7) print("> Wave: "..wname[wave+1],10,55) else color(6) print("Wave: "..wname[wave+1],10,55) end if sel == 1 then color(7) print("> Frequency: "..freq.."Hz",10,65) else color(6) print("Frequency: "..freq.."Hz",10,65) end if sel == 2 then color(7) print("> AMP: "..amp,10,75) else color(6) print("AMP: "..amp,10,75) end end function _draw() clear(0) rect(0,32, 192, 128-64, false, 5) pushMatrix() _drawUI() _drawPic() popMatrix() end function _updatePic(dt) wx = (wx + (freq/10)*dt) % 32 end function _update(dt) _updatePic(dt) if btnp(3) then sel = sel-1 if sel == -1 then sel = 2 end elseif btnp(4) then sel = (sel+1)%3 end if btnp(5) then --Inc if sel == 0 then wave = math.min(wave+1,waves) elseif sel == 1 then freq = math.min(freq+100,20000) elseif sel == 2 then amp = amp+0.1 end Audio.generate(wave,freq,amp) elseif btnp(6) then --Dec if sel == 0 then wave = math.max(wave-1,0) elseif sel == 1 then freq = math.max(freq-100,0) elseif sel == 2 then amp = amp-0.1 end Audio.generate(wave,freq,amp) end if btnp(7) then Audio.generate() end end
local itemUtil = {} local sounds = require("__base__.prototypes.entity.sounds") local danyao_pic = "__xiuxian-graphics__/graphics/icons/danyao/dan-juqi.png" local dihuo_pic = "__xiuxian-graphics__/graphics/icons/地火.png" function itemUtil.createDanyao(item_name) data:extend( { { type = "tool", name = item_name, icon = danyao_pic, icon_size = 128, --icon_mipmaps = 3, subgroup = "服用的丹药", durability = 1, stack_size = 100 } }) end function itemUtil.createDanyaoFu(item_name) data:extend( { { type = "capsule", name = item_name, icon = danyao_pic, icon_size = 128, --icon_mipmaps = 3, subgroup = "服用的丹药", capsule_action = { type = "use-on-self", attack_parameters = { type = "projectile", activation_type = "consume", ammo_category = "capsule", cooldown = 30, range = 0, ammo_type = { category = "capsule", target_type = "position", -- "entity", "position" or "direction" action = { type = "direct", action_delivery = { type = "instant", target_effects = { { type = "damage", damage = { type = "physical", amount = -80 } }, { type = "play-sound", sound = sounds.eat_fish } } } } } } }, stack_size = 100 } }) end function itemUtil.createDanyaoRecipe(item_name) data:extend( { { type = "recipe", name = item_name, enabled = false, ingredients = { { "灵石", 50 } }, result = item_name } }) end function itemUtil.createModule(item_name, tier) --模块在其类别内的层。升级模块时使用:Ctrl +单击模块进入实体,如果它们具有相同的类别,它将用较高层模块替换较低层模块。 tier = tier or 1 data:extend( { { type = "module", name = item_name, icon = dihuo_pic, icon_size = 60, subgroup = "地火", category = "地火", tier = tier, effect = { speed = { bonus = 0.5 }, consumption = { bonus = 0.5 } }, ingredients = { { "灵石", 50 } }, stack_size = 100 } }) end function itemUtil.createModuleRecipe(item_name, tier) tier = tier or 1 data:extend( { { type = "recipe", name = item_name, enabled = false, subgroup = "地火", ingredients = { { "火灵石矿", 100 * tier } }, result = item_name } }) end return itemUtil
table.insert(emojichatHTML, [===[gs","url"],char:"🔗",fitzpatrick_scale:!1,category:"objects"},paperclip:{keywords:["documents","stationery"],char:"📎",fitzpatrick_scale:!1,category:"objects"},paperclips:{keywords:["documents","stationery"],char:"🖇",fitzpatrick_scale:!1,category:"objects"},scissors:{keywords:["stationery","cut"],char:"✂️",fitzpatrick_scale:!1,category:"objects"},triangular_ruler:{keywords:["stationery","math","architect","sketch"],char:"📐",fitzpatrick_scale:!1,category:"objects"},straight_ruler:{keywords:["stationery","calculate","length","math","school","drawing","architect","sketch"],char:"📏",fitzpatrick_scale:!1,category:"objects"},abacus:{keywords:["calculation"],char:"🧮",fitzpatrick_scale:!1,category:"objects"},pushpin:{keywords:["stationery","mark","here"],char:"📌",fitzpatrick_scale:!1,category:"objects"},round_pushpin:{keywords:["stationery","location","map","here"],char:"📍",fitzpatrick_scale:!1,category:"objects"},triangular_flag_on_post:{keywords:["mark","milestone","place"],char:"🚩",fitzpatrick_scale:!1,category:"objects"},white_flag:{keywords:["losing","loser","lost","surrender","give up","fail"],char:"🏳",fitzpatrick_scale:!1,category:"objects"},black_flag:{keywords:["pirate"],char:"🏴",fitzpatrick_scale:!1,category:"objects"},rainbow_flag:{keywords:["flag","rainbow","pride","gay","lgbt","glbt","queer","homosexual","lesbian","bisexual","transgender"],char:"🏳️‍🌈",fitzpatrick_scale:!1,category:"objects"},closed_lock_with_key:{keywords:["security","privacy"],char:"🔐",fitzpatrick_scale:!1,category:"objects"},lock:{keywords:["security","password","padlock"],char:"🔒",fitzpatrick_scale:!1,category:"objects"},unlock:{keywords:["privacy","security"],char:"🔓",fitzpatrick_scale:!1,category:"objects"},lock_with_ink_pen:{keywords:["security","secret"],char:"🔏",fitzpatrick_scale:!1,category:"objects"},pen:{keywords:["stationery","writing","write"],char:"🖊",fitzpatrick_scale:!1,category:"objects"},fountain_pen:{keywords:["stationery","writing","write"],char:"🖋",fitzpatrick_scale:!1,category:"objects"},black_nib:{keywords:["pen","stationery","writing","write"],char:"✒️",fitzpatrick_scale:!1,category:"objects"},memo:{keywords:["write","documents","stationery","pencil","paper","writing","legal","exam","quiz","test","study","compose"],char:"📝",fitzpatrick_scale:!1,category:"objects"},pencil2:{keywords:["stationery","write","paper","writing","school","study"],char:"✏️",fitzpatrick_scale:!1,category:"objects"},crayon:{keywords:["drawing","creativity"],char:"🖍",fitzpatrick_scale:!1,category:"objects"},paintbrush:{keywords:["drawing","creativity","art"],char:"🖌",fitzpatrick_scale:!1,category:"objects"},mag:{keywords:["search","zoom","find","detective"],char:"🔍",fitzpatrick_scale:!1,category:"objects"},mag_right:{keywords:["search","zoom","find","detective"],char:"🔎",fitzpatrick_scale:!1,category:"objects"},heart:{keywords:["love","like","valentines"],char:"❤️",fitzpatrick_scale:!1,category:"symbols"},orange_heart:{keywords:["love","like","affection","valentines"],char:"🧡",fitzpatrick_scale:!1,category:"symbols"},yellow_heart:{keywords:["love","like","affection","valentines"],char:"💛",fitzpatrick_scale:!1,category:"symbols"},green_heart:{keywords:["love","like","affection","valentines"],char:"💚",fitzpatrick_scale:!1,category:"symbols"},blue_heart:{keywords:["love","like","affection","valentines"],char:"💙",fitzpatrick_scale:!1,category:"symbols"},purple_heart:{keywords:["love","like","affection","valentines"],char:"💜",fitzpatrick_scale:!1,category:"symbols"},black_heart:{keywords:["evil"],char:"🖤",fitzpatrick_scale:!1,category:"symbols"},broken_heart:{keywords:["sad","sorry","break","heart","heartbreak"],char:"💔",fitzpatrick_scale:!1,category:"symbols"},heavy_heart_exclamation:{keywords:["decoration","love"],char:"❣",fitzpatrick_scale:!1,category:"symbols"},two_hearts:{keywords:["love","like","affection","valentines","heart"],char:"💕",fitzpatrick_scale:!1,category:"symbols"},revolving_hearts:{keywords:["love","like","affection","valentines"],char:"💞",fitzpatrick_scale:!1,category:"symbols"},heartbeat:{keywords:["love","like","affection","valentines","pink","heart"],char:"💓",fitzpatrick_scale:!1,category:"symbols"},heartpulse:{keywords:["like","love","affection","valentines","pink"],char:"💗",fitzpatrick_scale:!1,category:"symbols"},sparkling_heart:{keywords:["love","like","affection","valentines"],char:"💖",fitzpatrick_scale:!1,category:"symbols"},cupid:{keywords:["love","like","heart","affection","valentines"],char:"💘",fitzpatrick_scale:!1,category:"symbols"},gift_heart:{keywords:["love","valentines"],char:"💝",fitzpatrick_scale:!1,category:"symbols"},heart_decoration:{keywords:["purple-square","love","like"],char:"💟",fitzpatrick_scale:!1,category:"symbols"},peace_symbol:{keywords:["hippie"],char:"☮",fitzpatrick_scale:!1,category:"symbols"},latin_cross:{keywords:["christianity"],char:"✝",fitzpatrick_scale:!1,category:"symbols"},star_and_crescent:{keywords:["islam"],char:"☪",fitzpatrick_scale:!1,category:"symbols"},om:{keywords:["hinduism","buddhism","sikhism","jainism"],char:"🕉",fitzpatrick_scale:!1,category:"symbols"},wheel_of_dharma:{keywords:["hinduism","buddhism","sikhism","jainism"],char:"☸",fitzpatrick_scale:!1,category:"symbols"},star_of_david:{keywords:["judaism"],char:"✡",fitzpatrick_scale:!1,category:"symbols"},six_pointed_star:{keywords:["purple-square","religion","jewish","hexagram"],char:"🔯",fitzpatrick_scale:!1,category:"symbols"},menorah:{keywords:["hanukkah","candles","jewish"],char:"🕎",fitzpatrick_scale:!1,category:"symbols"},yin_yang:{keywords:["balance"],char:"☯",fitzpatrick_scale:!1,category:"symbols"},orthodox_cross:{keywords:["suppedaneum","religion"],char:"☦",fitzpatrick_scale:!1,category:"symbols"},place_of_worship:{keywords:["religion","church","temple","prayer"],char:"🛐",fitzpatrick_scale:!1,category:"symbols"},ophiuchus:{keywords:["sign","purple-square","constellation","astrology"],char:"⛎",fitzpatrick_scale:!1,category:"symbols"},aries:{keywords:["sign","purple-square","zodiac","astrology"],char:"♈",fitzpatrick_scale:!1,category:"symbols"},taurus:{keywords:["purple-square","sign","zodiac","astrology"],char:"♉",fitzpatrick_scale:!1,category:"symbols"},gemini:{keywords:["sign","zodiac","purple-square","astrology"],char:"♊",fitzpatrick_scale:!1,category:"symbols"},cancer:{keywords:["sign","zodiac","purple-square","astrology"],char:"♋",fitzpatrick_scale:!1,category:"symbols"},leo:{keywords:["sign","purple-square","zodiac","astrology"],char:"♌",fitzpatrick_scale:!1,category:"symbols"},virgo:{keywords:["sign","zodiac","purple-square","astrology"],char:"♍",fitzpatrick_scale:!1,category:"symbols"},libra:{keywords:["sign","purple-square","zodiac","astrology"],char:"♎",fitzpatrick_scale:!1,category:"symbols"},scorpius:{keywords:["sign","zodiac","purple-square","astrology","scorpio"],char:"♏",fitzpatrick_scale:!1,category:"symbols"},sagittarius:{keywords:["sign","zodiac","purple-square","astrology"],char:"♐",fitzpatrick_scale:!1,category:"symbols"},capricorn:{keywords:["sign","zodiac","purple-square","astrology"],char:"♑",fitzpatrick_scale:!1,category:"symbols"},aquarius:{keywords:["sign","purple-square","zodiac","astrology"],char:"♒",fitzpatrick_scale:!1,category:"symbols"},pisces:{keywords:["purple-square","sign","zodiac","astrology"],char:"♓",fitzpatrick_scale:!1,category:"symbols"},id:{keywords:["purple-square","words"],char:"🆔",fitzpatrick_scale:!1,category:"symbols"},atom_symbol:{keywords:["science","physics","chemistry"],char:"⚛",fitzpatrick_scale:!1,category:"symbols"},u7a7a:{keywords:["kanji","japanese","chinese","empty","sky","blue-square"],char:"🈳",fitzpatrick_scale:!1,category:"symbols"},u5272:{keywords:["cut","divide","chinese","kanji","pink-square"],char:"🈹",fitzpatrick_scale:!1,category:"symbols"},radioactive:{keywords:["nuclear","danger"],char:"☢",fitzpatrick_scale:!1,category:"symbols"},biohazard:{keywords:["danger"],char:"☣",fitzpatrick_scale:!1,category:"symbols"},mobile_phone_off:{keywords:["mute","orange-square","silence","quiet"],char:"📴",fitzpatrick_scale:!1,category:"symbols"},vibration_mode:{keywords:["orange-square","phone"],char:"📳",fitzpatrick_scale:!1,category:"symbols"},u6709:{keywords:["orange-square","chinese","have","kanji"],char:"🈶",fitzpatrick_scale:!1,category:"symbols"},u7121:{keywords:["nothing","chinese","kanji","japanese","orange-square"],char:"🈚",fitzpatrick_scale:!1,category:"symbols"},u7533:{keywords:["chinese","japanese","kanji","orange-square"],char:"🈸",fitzpatrick_scale:!1,category:"symbols"},u55b6:{keywords:["japanese","opening hours","orange-square"],char:"🈺",fitzpatrick_scale:!1,category:"symbols"},u6708:{keywords:["chinese","month","moon","japanese","orange-square","kanji"],char:"🈷️",fitzpatrick_scale:!1,category:"symbols"},eight_pointed_black_star:{keywords:["orange-square","shape","polygon"],char:"✴️",fitzpatrick_scale:!1,category:"symbols"},vs:{keywords:["words","orange-square"],char:"🆚",fitzpatrick_scale:!1,category:"symbols"},accept:{keywords:["ok","good","chinese","kanji","agree","yes","orange-circle"],char:"🉑",fitzpatrick_scale:!1,category:"symbols"},white_flower:{keywords:["japanese","spring"],char:"💮",fitzpatrick_scale:!1,category:"symbols"},ideograph_advantage:{keywords:["chinese","kanji","obtain","get","circle"],char:"🉐",fitzpatrick_scale:!1,category:"symbols"},secret:{keywords:["privacy","chinese","sshh","kanji","red-circle"],char:"㊙️",fitzpatrick_scale:!1,category:"symbols"},congratulations:{keywords:["chinese","kanji","japanese","red-circle"],char:"㊗️",fitzpatrick_scale:!1,category:"symbols"},u5408:{keywords:["japanese","chinese","join","kanji","red-square"],char:"🈴",fitzpatrick_scale:!1,category:"symbols"},u6e80:{keywords:["full","chinese","japanese","red-square","kanji"],char:"🈵",fitzpatrick_scale:!1,category:"symbols"},u7981:{keywords:["kanji","japanese","chinese","forbidden","limit","restricted","red-square"],char:"🈲",fitzpatrick_scale:!1,category:"symbols"},a:{keywords:["red-square","alphabet","letter"],char:"🅰️",fitzpatrick_scale:!1,category:"symbols"},b:{keywords:["red-square","alphabet","letter"],char:"🅱️",fitzpatrick_scale:!1,category:"symbols"},ab:{keywords:["red-square","alphabet"],char:"🆎",fitzpatrick_scale:!1,category:"symbols"},cl:{keywords:["alphabet","words","red-square"],char:"🆑",fitzpatrick_scale:!1,category:"symbols"},o2:{keywords:["alphabet","red-square","letter"],char:"🅾️",fitzpatrick_scale:!1,category:"symbols"},sos:{keywords:["help","red-square","words","emergency","911"],char:"🆘",fitzpatrick_scale:!1,category:"symbols"},no_entry:{keywords:["limit","security","privacy","bad","denied","stop","circle"],char:"⛔",fitzpatrick_scale:!1,category:"symbols"},name_badge:{keywords:["fire","forbid"],char:"📛",fitzpatrick_scale:!1,category:"symbols"},no_entry_sign:{keywords:["forbid","stop","limit","denied","disallow","circle"],char:"🚫",fitzpatrick_scale:!1,category:"symbols"},x:{keywords:["no","delete","remove","cancel","red"],char:"❌",fitzpatrick_scale:!1,category:"symbols"},o:{keywords:["circle","round"],char:"⭕",fitzpatrick_scale:!1,category:"symbols"},stop_sign:{keywords:["stop"],char:"🛑",fitzpatrick_scale:!1,category:"symbols"},anger:{keywords:["angry","mad"],char:"💢",fitzpatrick_scale:!1,category:"symbols"},hotsprings:{keywords:["bath","warm","relax"],char:"♨️",fitzpatrick_scale:!1,category:"symbols"},no_pedestrians:{keywords:["rules","crossing","walking","circle"],char:"🚷",fitzpatrick_scale:!1,category:"symbols"},do_not_litter:{keywords:["trash","bin","garbage","circle"],char:"🚯",fitzpatrick_scale:!1,category:"symbols"},no_bicycles:{keywords:["cyclist","prohibited","circle"],char:"🚳",fitzpatrick_scale:!1,category:"symbols"},"non-potable_water":{keywords:["drink","faucet","tap","circle"],char:"🚱",fitzpatrick_scale:!1,category:"symbols"},underage:{keywords:["18","drink","pub","night","minor","circle"],char:"🔞",fitzpatrick_scale:!1,category:"symbols"},no_mobile_phones:{keywords:["iphone","mute","circle"],char:"📵",fitzpatrick_scale:!1,category:"symbols"},exclamation:{keywords:["heavy_exclamation_mark","danger","surprise","punctuation","wow","warning"],char:"❗",fitzpatrick_scale:!1,category:"symbols"},grey_exclamation:{keywords:["surprise","punctuation","gray","wow","warning"],char:"❕",fitzpatrick_scale:!1,category:"symbols"},question:{keywords:["doubt","confused"],char:"❓",fitzpatrick_scale:!1,category:"symbols"},grey_question:{keywords:["doubts","gray","huh","confused"],char:"❔",fitzpatrick_scale:!1,category:"symbols"},bangbang:{keywords:["exclamation","surprise"],char:"‼️",fitzpatrick_scale:!1,category:"symbols"},interrobang:{keywords:["wat","punctuation","surprise"],char:"⁉️",fitzpatrick_scale:!1,category:"symbols"},low_brightness:{keywords:["sun","afternoon","warm","summer"],char:"🔅",fitzpatrick_scale:!1,category:"symbols"},high_brightness:{keywords:["sun","light"],char:"🔆",fitzpatrick_scale:!1,category:"symbols"},trident:{keywords:["weapon","spear"],char:"🔱",fitzpatrick_scale:!1,category:"symbols"},fleur_de_lis:{keywords:["decorative","scout"],char:"⚜",fitzpatrick_scale:!1,category:"symbols"},part_alternation_mark:{keywords:["graph","presentation","stats","business","economics","bad"],char:"〽️",fitzpatrick_scale:!1,category:"symbols"},warning:{keywords:["exclamation","wip","alert","error","problem","issue"],char:"⚠️",fitzpatrick_scale:!1,category:"symbols"},children_crossing:{keywords:["school","warning","danger","sign","driving","yellow-diamond"],char:"🚸",fitzpatrick_scale:!1,category:"symbols"},beginner:{keywords:["badge","shield"],char:"🔰",fitzpatrick_scale:!1,category:"symbols"},recycle:{keywords:["arrow","environment","garbage","trash"],char:"♻️",fitzpatrick_scale:!1,category:"symbols"},u6307:{keywords:["chinese","point","green-square","kanji"],char:"🈯",fitzpatrick_scale:!1,category:"symbols"},chart:{keywords:["green-square","graph","presentation","stats"],char:"💹",fitzpatrick_scale:!1,category:"symbols"},sparkle:{keywords:["stars","green-square","awesome","good","fireworks"],char:"❇️",fitzpatrick_scale:!1,category:"symbols"},eight_spoked_asterisk:{keywords:["star","sparkle","green-square"],char:"✳️",fitzpatrick_scale:!1,category:"symbols"},negative_squared_cross_mark:{keywords:["x","green-square","no","deny"],char:"❎",fitzpatrick_scale:!1,category:"symbols"},white_check_mark:{keywords:["green-square","ok","agree","vote","election","answer","tick"],char:"✅",fitzpatrick_scale:!1,category:"symbols"},diamond_shape_with_a_dot_inside:{keywords:["jewel","blue","gem","crystal","fancy"],char:"💠",fitzpatrick_scale:!1,category:"symbols"},cyclone:{keywords:["weather","swirl","blue","cloud","vortex","spiral","whirlpool","spin","tornado","hurricane","typhoon"],char:"🌀",fitzpatrick_scale:!1,category:"symbols"},loop:{keywords:["tape","cassette"],char:"➿",fitzpatrick_scale:!1,category:"symbols"},globe_with_meridians:{keywords:["earth","international","world","internet","interweb","i18n"],char:"🌐",fitzpatrick_scale:!1,category:"symbols"},m:{keywords:["alphabet","blue-circle","letter"],char:"Ⓜ️",fitzpatrick_scale:!1,category:"symbols"},atm:{keywords:["money","sales","cash","blue-square","payment","bank"],char:"🏧",fitzpatrick_scale:!1,category:"symbols"},sa:{keywords:["japanese","blue-square","katakana"],char:"🈂️",fitzpatrick_scale:!1,category:"symbols"},passport_control:{keywords:["custom","blue-square"],char:"🛂",fitzpatrick_scale:!1,category:"symbols"},customs:{keywords:["passport","border","blue-square"],char:"🛃",fitzpatrick_scale:!1,category:"symbols"},baggage_claim:{keywords:["blue-square","airport","transport"],char:"🛄",fitzpatrick_scale:!1,category:"symbols"},left_luggage:{keywords:["blue-square","travel"],char:"🛅",fitzpatrick_scale:!1,category:"symbols"},wheelchair:{keywords:["blue-square","disabled","a11y","accessibility"],char:"♿",fitzpatrick_scale:!1,category:"symbols"},no_smoking:{keywords:["cigarette","blue-square","smell","smoke"],char:"🚭",fitzpatrick_scale:!1,category:"symbols"},wc:{keywords:["toilet","restroom","blue-square"],char:"🚾",fitzpatrick_scale:!1,category:"symbols"},parking:{keywords:["cars","blue-square","alphabet","letter"],char:"🅿️",fitzpatrick_scale:!1,category:"symbols"},potable_water:{keywords:["blue-square","liquid","restroom","cleaning","faucet"],char:"🚰",fitzpatrick_scale:!1,category:"symbols"},mens:{keywords:["toilet","restroom","wc","blue-square","gender","male"],char:"🚹",fitzpatrick_scale:!1,category:"symbols"},womens:{keywords:["purple-square","woman","female","toilet","loo","restroom","gender"],char:"🚺",fitzpatrick_scale:!1,category:"symbols"},baby_symbol:{keywords:["orange-square","child"],char:"🚼",fitzpatrick_scale:!1,category:"symbols"},restroom:{keywords:["blue-square","toilet","refresh","wc","gender"],char:"🚻",fitzpatrick_scale:!1,category:"symbols"},put_litter_in_its_place:{keywords:["blue-square","sign","human","info"],char:"🚮",fitzpatrick_scale:!1,category:"symbols"},cinema:{keywords:["blue-square","record","film","movie","curtain","stage","theater"],char:"🎦",fitzpatrick_scale:!1,category:"symbols"},signal_strength:{keywords:["blue-square","reception","phone","internet","connection","wifi","bluetooth","bars"],char:"📶",fitzpatrick_scale:!1,category:"symbols"},koko:{keywords:["blue-square","here","katakana","japanese","destination"],char:"🈁",fitzpatrick_scale:!1,category:"symbols"},ng:{keywords:["blue-square","words","shape","icon"],char:"🆖",fitzpatrick_scale:!1,category:"symbols"},ok:{keywords:["good","agree","yes","blue-square"],char:"🆗",fitzpatrick_scale:!1,category:"symbols"},up:{keywords:["blue-square","above","high"],char:"🆙",fitzpatrick_scale:!1,category:"symbols"},cool:{keywords:["words","blue-square"],char:"🆒",fitzpatrick_scale:!1,category:"symbols"},new:{keywords:["blue-square","words","start"],char:"🆕",fitzpatrick_scale:!1,category:"symbols"},free:{keywords:["blue-square","words"],char:"🆓",fitzpatrick_scale:!1,category:"symbols"},zero:{keywords:["0","numbers","blue-square","null"],char:"0️⃣",fitzpatrick_scale:!1,category:"symbols"},one:{keywords:["blue-square","numbers","1"],char:"1️⃣",fitzpatrick_scale:!1,category:"symbols"},two:{keywords:["numbers","2","prime","blue-square"],char:"2️⃣",fitzpatrick_scale:!1,category:"symbols"},three:{keywords:["3","numbers","prime","blue-square"],char:"3️⃣",fitzpatrick_scale:!1,category:"symbols"},four:{keywords:["4","numbers","blue-square"],char:"4️⃣",fitzpatrick_scale:!1,category:"symbols"},five:{keywords:["5","numbers","blue-square","prime"],char:"5️⃣",fitzpatrick_scale:!1,category:"symbols"},six:{keywords:["6","numbers","blue-square"],char:"6️⃣",fitzpatrick_scale:!1,category:"symbols"},seven:{keywords:["7","numbers","blue-square","prime"],char:"7️⃣",fitzpatrick_scale:!1,category:"symbols"},eight:{keywords:["8","blue-square","numbers"],char:"8️⃣",fitzpatrick_scale:!1,category:"symbols"},nine:{keywords:["blue-square","numbers","9"],char:"9️⃣",fitzpatrick_scale:!1,category:"symbols"},keycap_ten:{keywords:["numbers","10","blue-square"],char:"🔟",fitzpatrick_scale:!1,category:"symbols"},asterisk:{keywords:["star","keycap"],char:"*⃣",fitzpatrick_scale:!1,category:"symbols"},eject_button:{keywords:["blue-square"],char:"⏏️",fitzpatrick_scale:!1,category:"symbols"},arrow_forward:{keywords:["blue-square","right","direction","play"],char:"▶️",fitzpatrick_scale:!1,category:"symbols"},pause_button:{keywords:["pause","blue-square"],char:"⏸",fitzpatrick_scale:!1,category:"symbols"},next_track_button:{keywords:["forward","next","blue-square"],char:"⏭",fitzpatrick_scale:!1,category:"symbols"},stop_button:{keywords:["blue-square"],char:"⏹",fitzpatrick_scale:!1,category:"symbols"},record_button:{keywords:["blue-square"],char:"⏺",fitzpatrick_scale:!1,category:"symbols"},play_or_pause_button:{keywords:["blue-square","play","pause"],char:"⏯",fitzpatrick_scale:!1,category:"symbols"},previous_track_button:{keywords:["backward"],char:"⏮",fitzpatrick_scale:!1,category:"symbols"},fast_forward:{keywords:["blue-square","play","speed","continue"],char:"⏩",fitzpatrick_scale:!1,category:"symbols"},rewind:{keywords:["play","blue-square"],char:"⏪",fitzpatrick_scale:!1,category:"symbols"},twisted_rightwards_arrows:{keywords:["blue-square","shuffle","music","random"],char:"🔀",fitzpatrick_scale:!1,category:"symbols"},repeat:{keywords:["loop","record"],char:"🔁",fitzpatrick_scale:!1,category:"symbols"},repeat_one:{keywords:["blue-square","loop"],char:"🔂",fitzpatrick_scale:!1,category:"symbols"},arrow_backward:{keywords:["blue-square","left","direction"],char:"◀️",fitzpatrick_scale:!1,category:"symbols"},arrow_up_small:{keywords:["blue-square","triangle","direction","point","forward","top"],char:"🔼",fitzpatrick_scale:!1,category:"symbols"},arrow_down_small:{keywords:["blue-square","direction","bottom"],char:"🔽",fitzpatrick_scale:!1,category:"symbols"},arrow_double_up:{keywords:["blue-square","direction","top"],char:"⏫",fitzpatrick_scale:!1,category:"symbols"},arrow_double_down:{keywords:["blue-square","direction","bottom"],char:"⏬",fitzpatrick_scale:!1,category:"symbols"},arrow_right:{keywords:["blue-square","next"],char:"➡️",fitzpatrick_scale:!1,category:"symbols"},arrow_left:{keywords:["blue-square","previous","back"],char:"⬅️",fitzpatrick_scale:!1,category:"symbols"},arrow_up:{keywords:["blue-square","continue","top","direction"],char:"⬆️",fitzpatrick_scale:!1,category:"symbols"},arrow_down:{keywords:["blue-square","direction","bottom"],char:"⬇️",fitzpatrick_scale:!1,category:"symbols"},arrow_upper_right:{keywords:["blue-square","point","direction","diagonal","northeast"],char:"↗️",fitzpatrick_scale:!1,category:"symbols"},arrow_lower_right:{keywords:["blue-square","direction","diagonal","southeast"],char:"↘️",fitzpatrick_scale:!1,category:"symbols"},arrow_lower_left:{keywords:["blue-square","direction","diagonal","southwest"],char:"↙️",fitzpatrick_scale:!1,category:"symbols"},arrow_upper_left:{keywords:["blue-square","point","direction","diagonal","northwest"],char:"↖️",fitzpatrick_scale:!1,category:"symbols"},arrow_up_down:{keywords:["blue-square","direction","way","vertical"],char:"↕️",fitzpatrick_scale:!1,category:"symbols"},left_right_arrow:{keywords:["shape","direction","horizontal","sideways"],char:"↔️",fitzpatrick_scale:!1,category:"symbols"},arrows_counterclockwise:{keywords:["blue-square","sync","cycle"],char:"🔄",fitzpatrick_scale:!1,category:"symbols"},arrow_right_hook:{keywords:["blue-square","return","rotate","direction"],char:"↪️",fitzpatrick_scale:!1,category:"symbols"},leftwards_arrow_with_hook:{keywords:["back","return","blue-square","undo","enter"],char:"↩️",fitzpatrick_scale:!1,category:"symbols"},arrow_heading_up:{keywords:["blue-square","direction","top"],char:"⤴️",fitzpatrick_scale:!1,category:"symbols"},arrow_heading_down:{keywords:["blue-square","direction","bottom"],char:"⤵️",fitzpatrick_scale:!1,category:"symbols"},hash:{keywords:["symbol","blue-square","twitter"],char:"#️⃣",fitzpatrick_scale:!1,category:"symbols"},information_source:{keywords:["blue-square","alphabet","letter"],char:"ℹ️",fitzpatrick_scale:!1,category:"symbols"},abc:{keywords:["blue-square","alphabet"],char:"🔤",fitzpatrick_scale:!1,category:"symbols"},abcd:{keywords:["blue-square","alphabet"],char:"🔡",fitzpatrick_scale:!1,category:"symbols"},capital_abcd:{keywords:["alphabet","words","blue-square"],char:"🔠",fitzpatrick_scale:!1,category:"symbols"},symbols:{keywords:["blue-square","music","note","ampersand","percent","glyphs","characters"],char:"🔣",fitzpatrick_scale:!1,category:"symbols"},musical_note:{keywords:["score","tone","sound"],char:"🎵",fitzpatrick_scale:!1,category:"symbols"},notes:{keywords:["music","score"],char:"🎶",fitzpatrick_scale:!1,category:"symbols"},wavy_dash:{keywords:["draw","line","moustache","mustache","squiggle","scribble"],char:"〰️",fitzpatrick_scale:!1,category:"symbols"},curly_loop:{keywords:["scribble","draw","shape","squiggle"],char:"➰",fitzpatrick_scale:!1,category:"symbols"},heavy_check_mark:{keywords:["ok","nike","answer","yes","tick"],char:"✔️",fitzpatrick_scale:!1,category:"symbols"},arrows_clockwise:{keywords:["sync","cycle","round","repeat"],char:"🔃",fitzpatrick_scale:!1,category:"symbols"},heavy_plus_sign:{keywords:["math","calculation","addition","more","increase"],char:"➕",fitzpatrick_scale:!1,category:"symbols"},heavy_minus_sign:{keywords:["math","calculation","subtract","less"],char:"➖",fitzpatrick_scale:!1,category:"symbols"},heavy_division_sign:{keywords:["divide","math","calculation"],char:"➗",fitzpatrick_scale:!1,category:"symbols"},heavy_multiplication_x:{keywords:["math","calculation"],char:"✖️",fitzpatrick_scale:!1,category:"symbols"},infinity:{keywords:["forever"],char:"♾",fitzpatrick_scale:!1,category:"symbols"},heavy_dollar_sign:{keywords:["money","sales","payment","currency","buck"],char:"💲",fitzpatrick_scale:!1,category:"symbols"},currency_exchange:{keywords:["money","sales","dollar","travel"],char:"💱",fitzpatrick_scale:!1,category:"symbols"},copyright:{keywords:["ip","license","circle","law","legal"],char:"©️",fitzpatrick_scale:!1,category:"symbols"},registered:{keywords:["alphabet","circle"],char:"®️",fitzpatrick_scale:!1,category:"symbols"},tm:{keywords:["trademark","brand","law","legal"],char:"™️",fitzpatrick_scale:!1,category:"symbols"},end:{keywords:["words","arrow"],char:"🔚",fitzpatrick_scale:!1,category:"symbols"},back:{keywords:["arrow","words","return"],char:"🔙",fitzpatrick_scale:!1,category:"symbols"},on:{keywords:["arrow","words"],char:"🔛",fitzpatrick_scale:!1,category:"symbols"},top:{keywords:["words","blue-square"],char:"🔝",fitzpatrick_scale:!1,category:"symbols"},soon:{keywords:["arrow","words"],char:"🔜",fitzpatrick_scale:!1,category:"symbols"},ballot_box_with_check:{keywords:["ok","agree","confirm","black-square","vote","election","yes","tick"],char:"☑️",fitzpatrick_scale:!1,category:"symbols"},radio_button:{keywords:["input","old","music","circle"],char:"🔘",fitzpatrick_scale:!1,category:"symbols"},white_circle:{keywords:["shape","round"],char:"⚪",fitzpatrick_scale:!1,category:"symbols"},black_circle:{keywords:["shape","button","round"],char:"⚫",fitzpatrick_scale:!1,category:"symbols"},red_circle:{keywords:["shape","error","danger"],char:"🔴",fitzpatrick_scale:!1,category:"symbols"},large_blue_circle:{keywords:["shape","icon","button"],char:"🔵",fitzpatrick_scale:!1,category:"symbols"},small_orange_diamond:{keywords:["shape","jewel","gem"],char:"🔸",fitzpatrick_scale:!1,category:"symbols"},small_blue_diamond:{keywords:["shape","jewel","gem"],char:"🔹",fitzpatrick_scale:!1,category:"symbols"},large_orange_diamond:{keywords:["shape","jewel","gem"],char:"🔶",fitzpatrick_scale:!1,category:"symbols"},large_blue_diamond:{keywords:["shape","jewel","gem"],char:"🔷",fitzpatrick_scale:!1,category:"symbols"},small_red_triangle:{keywords:["shape","direction","up","top"],char:"🔺",fitzpatrick_scale:!1,category:"symbols"},black_small_square:{keywords:["shape","icon"],char:"▪️",fitzpatrick_scale:!1,category:"symbols"},white_small_square:{keywords:["shape","icon"],char:"▫️",fitzpatrick_scale:!1,category:"symbols"},black_large_square:{keywords:["shape","icon","button"],char:"⬛",fitzpatrick_scale:!1,category:"symbols"},white_large_square:{keywords:["shape","icon","stone","button"],char:"⬜",fitzpatrick_scale:!1,category:"symbols"},small_red_triangle_down:{keywords:["shape","direction","bottom"],char:"🔻",fitzpatrick_scale:!1,category:"symbols"},black_medium_square:{keywords:["shape","button","icon"],char:"◼️",fitzpatrick_scale:!1,category:"symbols"},white_medium_square:{keywords:["shape","stone","icon"],char:"◻️",fitzpatrick_scale:!1,category:"symbols"},black_medium_small_square:{keywords:["icon","shape","button"],char:"◾",fitzpatrick_scale:!1,category:"symbols"},white_medium_small_square:{keywords:["shape","stone","icon","button"],char:"◽",fitzpatrick_scale:!1,category:"symbols"},black_square_button:{keywords:["shape","input","frame"],char:"🔲",fitzpatrick_scale:!1,category:"symbols"},white_square_button:{keywords:["shape","input"],char:"🔳",fitzpatrick_scale:!1,category:"symbols"},speaker:{keywords:["sound","volume","silence","broadcast"],char:"🔈",fitzpatrick_scale:!1,category:"symbols"},sound:{keywords:["volume","speaker","broadcast"],char:"🔉",fitzpatrick_scale:!1,category:"symbols"},loud_sound:{keywords:["volume","noise","noisy","speaker","broadcast"],char:"🔊",fitzpatrick_scale:!1,category:"symbols"},mute:{keywords:["sound","volume","silence","quiet"],char:"🔇",fitzpatrick_scale:!1,category:"symbols"},mega:{keywords:["sound","speaker","volume"],char:"📣",fitzpatrick_scale:!1,category:"symbols"},loudspeaker:{keywords:["volume","sound"],char:"📢",fitzpatrick_scale:!1,category:"symbols"},bell:{keywords:["sound","notification","christmas","xmas","chime"],char:"🔔",fitzpatrick_scale:!1,category:"symbols"},no_bell:{keywords:["sound","volume","mute","quiet","silent"],char:"🔕",fitzpatrick_scale:!1,category:"symbols"},black_joker:{keywords:["poker","cards","game","play","magic"],char:"🃏",fitzpatrick_scale:!1,category:"symbols"},mahjong:{keywords:["game","play","chinese","kanji"],char:"🀄",fitzpatrick_scale:!1,category:"symbols"},spades:{keywords:["poker","cards","suits","magic"],char:"♠️",fitzpatrick_scale:!1,category:"symbols"},clubs:{keywords:["poker","cards","magic","suits"],char:"♣️",fitzpatrick_scale:!1,category:"symbols"},hearts:{keywords:["poker","cards","magic","suits"],char:"♥️",fitzpatrick_scale:!1,category:"symbols"},diamonds:{keywords:["poker","cards","magic","suits"],char:"♦️",fitzpatrick_scale:!1,category:"symbols"},flower_playing_cards:{keywords:["game","sunset","red"],char:"🎴",fitzpatrick_scale:!1,category:"symbols"},thought_balloon:{keywords:["bubble","cloud","speech","thinking","dream"],char:"💭",fitzpatrick_scale:!1,category:"symbols"},right_anger_bubble:{keywords:["caption","speech","thinking","mad"],char:"🗯",fitzpatrick_scale:!1,category:"symbols"},speech_balloon:{keywords:["bubble","words","message","talk","chatting"],char:"💬",fitzpatrick_scale:!1,category:"symbols"},left_speech_bubble:{keywords:["words","message","talk","chatting"],char:"🗨",fitzpatrick_scale:!1,category:"symbols"},clock1:{keywords:["time","late","early","schedule"],char:"🕐",fitzpatrick_scale:!1,category:"symbols"},clock2:{keywords:["time","late","early","schedule"],char:"🕑",fitzpatrick_scale:!1,category:"symbols"},clock3:{keywords:["time","late","early","schedule"],char:"🕒",fitzpatrick_scale:!1,category:"symbols"},clock4:{keywords:["time","late","early","schedule"],char:"🕓",fitzpatrick_scale:!1,category:"symbols"},clock5:{keywords:["time","late","early","schedule"],char:"🕔",fitzpatrick_scale:!1,category:"symbols"},clock6:{keywords:["time","late","early","schedule","dawn","dusk"],char:"🕕",fitzpatrick_scale:!1,category:"symbols"},clock7:{keywords:["time","late","early","schedule"],char:"🕖",fitzpatrick_scale:!1,category:"symbols"},clock8:{keywords:["time","late","early","schedule"],char:"🕗",fitzpatrick_scale:!1,category:"symbols"},clock9:{keywords:["time","late","early","schedule"],char:"🕘",fitzpatrick_scale:!1,category:"symbols"},clock10:{keywords:["time","late","early","schedule"],char:"🕙",fitzpatrick_scale:!1,category:"symbols"},clock11:{keywords:["time","late","early","schedule"],char:"🕚",fitzpatrick_scale:!1,category:"symbols"},clock12:{keywords:["time","noon","midnight","midday","late","early","schedule"],char:"🕛",fitzpatrick_scale:!1,category:"symbols"},clock130:{keywords:["time","late","early","schedule"],char:"🕜",fitzpatrick_scale:!1,category:"symbols"},clock230:{keywords:["time","late","early","schedule"],char:"🕝",fitzpatrick_scale:!1,category:"symbols"},clock330:{keywords:["time","late","early","schedule"],char:"🕞",fitzpatrick_scale:!1,category:"symbols"},clock430:{keywords:["time","late","early","schedule"],char:"🕟",fitzpatrick_scale:!1,category:"symbols"},clock530:{keywords:["time","late","early","schedule"],char:"🕠",fitzpatrick_scale:!1,category:"symbols"},clock630:{keywords:["time","late","early","schedule"],char:"🕡",fitzpatrick_scale:!1,category:"symbols"},clock730:{keywords:["time","late","early","schedule"],char:"🕢",fitzpatrick_scale:!1,category:"symbols"},clock830:{keywords:["time","late","early","schedule"],char:"🕣",fitzpatrick_scale:!1,category:"symbols"},clock930:{keywords:["time","late","early","schedule"],char:"🕤",fitzpatrick_scale:!1,category:"symbols"},clock1030:{keywords:["time","late","early","schedule"],char:"🕥",fitzpatrick_scale:!1,category:"symbols"},clock1130:{keywords:["time","late","early","schedule"],char:"🕦",fitzpatrick_scale:!1,category:"symbols"},clock1230:{keywords:["time","late","early","schedule"],char:"🕧",fitzpatrick_scale:!1,category:"symbols"},afghanistan:{keywords:["af","flag","nation","country","banner"],char:"🇦🇫",fitzpatrick_scale:!1,category:"flags"},aland_islands:{keywords:["Åland","islands","flag","nation","country","banner"],char:"🇦🇽",fitzpatrick_scale:!1,category:"flags"},albania:{keywords:["al","flag","nation","country","banner"],char:"🇦🇱",fitzpatrick_scale:!1,category:"flags"},algeria:{keywords:["dz","flag","nation","country","banner"],char:"🇩🇿",fitzpatrick_scale:!1,category:"flags"},american_samoa:{keywords:["american","ws","flag","nation","country","banner"],char:"🇦🇸",fitzpatrick_scale:!1,category:"flags"},andorra:{keywords:["ad","flag","nation","country","banner"],char:"🇦🇩",fitzpatrick_scale:!1,category:"flags"},angola:{keywords:["ao","flag","nation","country","banner"],char:"🇦🇴",fitzpatrick_scale:!1,category:"flags"},anguilla:{keywords:["ai","flag","nation","country","banner"],char:"🇦🇮",fitzpatrick_scale:!1,category:"flags"},antarctica:{keywords:["aq","flag","nation","country","banner"],char:"🇦🇶",fitzpatrick_scale:!1,category:"flags"},antigua_barbuda:{keywords:["antigua","barbuda","flag","nation","country","banner"],char:"🇦🇬",fitzpatrick_scale:!1,category:"flags"},argentina:{keywords:["ar","flag","nation","country","banner"],char:"🇦🇷",fitzpatrick_scale:!1,category:"flags"},armenia:{keywords:["am","flag","nation","country","banner"],char:"🇦🇲",fitzpatrick_scale:!1,category:"flags"},aruba:{keywords:["aw","flag","nation","country","banner"],char:"🇦🇼",fitzpatrick_scale:!1,category:"flags"},australia:{keywords:["au","flag","nation","country","banner"],char:"🇦🇺",fitzpatrick_scale:!1,category:"flags"},austria:{keywords:["at","flag","nation","country","banner"],char:"🇦🇹",fitzpatrick_scale:!1,category:"flags"},azerbaijan:{keywords:["az","flag","nation","country","banner"],char:"🇦🇿",fitzpatrick_scale:!1,category:"flags"},bahamas:{keywords:["bs","flag","nation","country","banner"],char:"🇧🇸",fitzpatrick_scale:!1,category:"flags"},bahrain:{keywords:["bh","flag","nation","country","banner"],char:"🇧🇭",fitzpatrick_scale:!1,category:"flags"},bangladesh:{keywords:["bd","flag","nation","country","banner"],char:"🇧🇩",fitzpatrick_scale:!1,category:"flags"},barbados:{keywords:["bb","flag","nation","country","banner"],char:"🇧🇧",fitzpatrick_scale:!1,category:"flags"},belarus:{keywords:["by","flag","nation","country","banner"],char:"🇧🇾",fitzpatrick_scale:!1,category:"flags"},belgium:{keywords:["be","flag","nation","country","banner"],char:"🇧🇪",fitzpatrick_scale:!1,category:"flags"},belize:{keywords:["bz","flag","nation","country","banner"],char:"🇧🇿",fitzpatrick_scale:!1,category:"flags"},benin:{keywords:["bj","flag","nation","country","banner"],char:"🇧🇯",fitzpatrick_scale:!1,category:"flags"},bermuda:{keywords:["bm","flag","nation","country","banner"],char:"🇧🇲",fitzpatrick_scale:!1,category:"flags"},bhutan:{keywords:["bt","flag","nation","country","banner"],char:"🇧🇹",fitzpatrick_scale:!1,category:"flags"},bolivia:{keywords:["bo","flag","nation","country","banner"],char:"🇧🇴",fitzpatrick_scale:!1,category:"flags"},caribbean_netherlands:{keywords:["bonaire","flag","nation","country","banner"],char:"🇧🇶",fitzpatrick_scale:!1,category:"flags"},bosnia_herzegovina:{keywords:["bosnia","herzegovina","flag","nation","country","banner"],char:"🇧🇦",fitzpatrick_scale:!1,category:"flags"},botswana:{keywords:["bw","flag","nation","country","banner"],char:"🇧🇼",fitzpatrick_scale:!1,category:"flags"},brazil:{keywords:["br","flag","nation","country","banner"],char:"🇧🇷",fitzpatrick_scale:!1,category:"flags"},british_indian_ocean_territory:{keywords:["british","indian","ocean","territory","flag","nation","country","banner"],char:"🇮🇴",fitzpatrick_scale:!1,category:"flags"},british_virgin_islands:{keywords:["british","virgin","islands","bvi","flag","nation","country","banner"],char:"🇻🇬",fitzpatrick_scale:!1,category:"flags"},brunei:{keywords:["bn","darussalam","flag","nation","country","banner"],char:"🇧🇳",fitzpatrick_scale:!1,category:"flags"},bulgaria:{keywords:["bg","flag","nation","country","banner"],char:"🇧🇬",fitzpatrick_scale:!1,category:"flags"},burkina_faso:{keywords:["burkina","faso","flag","nation","country","banner"],char:"🇧🇫",fitzpatrick_scale:!1,category:"flags"},burundi:{keywords:["bi","flag","nation","country","banner"],char:"🇧🇮",fitzpatrick_scale:!1,category:"flags"},cape_verde:{keywords:["cabo","verde","flag","nation","country","banner"],char:"🇨🇻",fitzpatrick_scale:!1,category:"flags"},cambodia:{keywords:["kh","flag","nation","country","banner"],char:"🇰🇭",fitzpatrick_scale:!1,category:"flags"},cameroon:{keywords:["cm","flag","nation","country","banner"],char:"🇨🇲",fitzpatrick_scale:!1,category:"flags"},canada:{keywords:["ca","flag","nation","country","banner"],char:"🇨🇦",fitzpatrick_scale:!1,category:"flags"},canary_islands:{keywords:["canary","islands","flag","nation","country","banner"],char:"🇮🇨",fitzpatrick_scale:!1,category:"flags"},cayman_islands:{keywords:["cayman","islands","flag","nation","country","banner"],char:"🇰🇾",fitzpatrick_scale:!1,category:"flags"},central_african_republic:{keywords:["central","african","republic","flag","nation","country","banner"],char:"🇨🇫",fitzpatrick_scale:!1,category:"flags"},chad:{keywords:["td","flag","nation","country","banner"],char:"🇹🇩",fitzpatrick_scale:!1,category:"flags"},chile:{keywords:["flag","nation","country","banner"],char:"🇨🇱",fitzpatrick_scale:!1,category:"flags"},cn:{keywords:["china","chinese","prc","flag","country","nation","banner"],char:"🇨🇳",fitzpatrick_scale:!1,category:"flags"},christmas_island:{keywords:["christmas","island","flag","nation","country","banner"],char:"🇨🇽",fitzpatrick_scale:!1,category:"flags"},cocos_islands:{keywords:["cocos","keeling","islands","flag","nation","country","banner"],char:"🇨🇨",fitzpatrick_scale:!1,category:"flags"},colombia:{keywords:["co","flag","nation","country","banner"],char:"🇨🇴",fitzpatrick_scale:!1,category:"flags"},comoros:{keywords:["km","flag","nation","country","banner"],char:"🇰🇲",fitzpatrick_scale:!1,category:"flags"},congo_brazzaville:{keywords:["congo","flag","nation","country","banner"],char:"🇨🇬",fitzpatrick_scale:!1,category:"flags"},congo_kinshasa:{keywords:["congo","democratic","republic","flag","nation","country","banner"],char:"🇨🇩",fitzpatrick_scale:!1,category:"flags"},cook_islands:{keywords:["cook","islands","flag","nation","country","banner"],char:"🇨🇰",fitzpatrick_scale:!1,category:"flags"},costa_rica:{keywords:["costa","rica","flag","nation","country","banner"],char:"🇨🇷",fitzpatrick_scale:!1,category:"flags"},croatia:{keywords:["hr","flag","nation","country","banner"],char:"🇭🇷",fitzpatrick_scale:!1,category:"flags"},cuba:{keywords:["cu","flag","nation","country","banner"],char:"🇨🇺",fitzpatrick_scale:!1,category:"flags"},curacao:{keywords:["curaçao","flag","nation","country","banner"],char:"🇨🇼",fitzpatrick_scale:!1,category:"flags"},cyprus:{keywords:["cy","flag","nation","country","banner"],char:"🇨🇾",fitzpatrick_scale:!1,category:"flags"},czech_republic:{keywords:["cz","flag","nation","country","banner"],char:"🇨🇿",fitzpatrick_scale:!1,category:"flags"},denmark:{keywords:["dk","flag","nation","country","banner"],char:"🇩🇰",fitzpatrick_scale:!1,category:"flags"},djibouti:{keywords:["dj","flag","nation","country","banner"],char:"🇩🇯",fitzpatrick_scale:!1,category:"flags"},dominica:{keywords:["dm","flag","nation","country","banner"],char:"🇩🇲",fitzpatrick_scale:!1,category:"flags"},dominican_republic:{keywords:["dominican","republic","flag","nation","country","banner"],char:"🇩🇴",fitzpatrick_scale:!1,category:"flags"},ecuador:{keywords:["ec","flag","nation","country","banner"],char:"🇪🇨",fitzpatrick_scale:!1,category:"flags"},egypt:{keywords:["eg","flag","nation","country","banner"],char:"🇪🇬",fitzpatrick_scale:!1,category:"flags"},el_salvador:{keywords:["el","salvador","flag","nation","country","banner"],char:"🇸🇻",fitzpatrick_scale:!1,category:"flags"},equatorial_guinea:{keywords:["equatorial","gn","flag","nation","country","banner"],char:"🇬🇶",fitzpatrick_scale:!1,category:"flags"},eritrea:{keywords:["er","flag","nation","country","banner"],char:"🇪🇷",fitzpatrick_scale:!1,category:"flags"},estonia:{keywords:["ee","flag","nation","country","banner"],char:"🇪🇪",fitzpatrick_scale:!1,category:"flags"},ethiopia:{keywords:["et","flag","nation","country","banner"],char:"🇪🇹",fitzpatrick_scale:!1,category:"flags"},eu:{keywords:["european","union","flag","banner"],char:"🇪🇺",fitzpatrick_scale:!1,category:"flags"},falkland_islands:{keywords:["falkland","islands","malvinas","flag","nation","country","banner"],char:"🇫🇰",fitzpatrick_scale:!1,category:"flags"},faroe_islands:{keywords:["faroe","islands","flag","nation","country","banner"],char:"🇫🇴",fitzpatrick_scale:!1,category:"flags"},fiji:{keywords:["fj","flag","nation","country","banner"],char:"🇫🇯",fitzpatrick_scale:!1,category:"flags"},finland:{keywords:["fi","flag","nation","country","banner"],char:"🇫🇮",fitzpatrick_scale:!1,category:"flags"},fr:{keywords:["banner","flag","nation","france","french","country"],char:"🇫🇷",fitzpatrick_scale:!1,category:"flags"},french_guiana:{keywords:["french","guiana","flag","nation","country","banner"],char:"🇬🇫",fitzpatrick_scale:!1,category:"flags"},french_polynesia:{keywords:["french","polynesia","flag","nation","country","banner"],char:"🇵🇫",fitzpatrick_scale:!1,category:"flags"},french_southern_territories:{keywords:["french","southern","territories","flag","nation","country","banner"],char:"🇹🇫",fitzpatrick_scale:!1,category:"flags"},gabon:{keywords:["ga","flag","nation","country","banner"],char:"🇬🇦",fitzpatrick_scale:!1,category:"flags"},gambia:{keywords:["gm","flag","nation","country","banner"],char:"🇬🇲",fitzpatrick_scale:!1,category:"flags"},georgia:{keywords:["ge","flag","nation","country","banner"],char:"🇬🇪",fitzpatrick_scale:!1,category:"flags"},de:{keywords:["german","nation","flag","country","banner"],char:"🇩🇪",fitzpatrick_scale:!1,category:"flags"},ghana:{keywords:["gh","flag","nation","country","banner"],char:"🇬🇭",fitzpatrick_scale:!1,category:"flags"},gibraltar:{keywords:["gi","flag","nation","country","banner"],char:"🇬🇮",fitzpatrick_scale:!1,category:"flags"},greece:{keywords:["gr","flag","nation","country","banner"],char:"🇬🇷",fitzpatrick_scale:!1,category:"flags"},greenland:{keywords:["gl","flag","nation","country","banner"],char:"🇬🇱",fitzpatrick_scale:!1,category:"flags"},grenada:{keywords:["gd","flag","nation","country","banner"],char:"🇬🇩",fitzpatrick_scale:!1,category:"flags"},guadeloupe:{keywords:["gp","flag","nation","country","banner"],char:"🇬🇵",fitzpatrick_scale:!1,category:"flags"},guam:{keywords:["gu","flag","nation","country","banner"],char:"🇬🇺",fitzpatrick_scale:!1,category:"flags"},guatemala:{keywords:["gt","flag","nation","country","banner"],char:"🇬🇹",fitzpatrick_scale:!1,category:"flags"},guernsey:{keywords:["gg","flag","nation","country","banner"],char:"🇬🇬",fitzpatrick_scale:!1,category:"flags"},guinea:{keywords:["gn","flag","nation","country","banner"],char:"🇬🇳",fitzpatrick_scale:!1,category:"flags"},guinea_bissau:{keywords:["gw","bissau","flag","nation","country","banner"],char:"🇬🇼",fitzpatrick_scale:!1,category:"flags"},guyana:{keywords:["gy","flag","nation","country","banner"],char:"🇬🇾",fitzpatrick_scale:!1,category:"flags"},haiti:{keywords:["ht","flag","nation","country","banner"],char:"🇭🇹",fitzpatrick_scale:!1,category:"flags"},honduras:{keywords:["hn","flag","nation","country","banner"],char:"🇭🇳",fitzpatrick_scale:!1,category:"flags"},hong_kong:{keywords:["hong","kong","flag","nation","country","banner"],char:"🇭🇰",fitzpatrick_scale:!1,category:"flags"},hungary:{keywords:["hu","flag","nation","country","banner"],char:"🇭🇺",fitzpatrick_scale:!1,category:"flags"},iceland:{keywords:["is","flag","nation","country","banner"],char:"🇮🇸",fitzpatrick_scale:!1,category:"flags"},india:{keywords:["in","flag","nation","country","banner"],char:"🇮🇳",fitzpatrick_scale:!1,category:"flags"},indonesia:{keywords:["flag","nation","country","banner"],char:"🇮🇩",fitzpatrick_scale:!1,category:"flags"},iran:{keywords:["iran,","islamic","republic","flag","nation","country","banner"],char:"🇮🇷",fitzpatrick_scale:!1,category:"flags"},iraq:{keywords:["iq","flag","nation","country","banner"],char:"🇮🇶",fitzpatrick_scale:!1,category:"flags"},ireland:{keywords:["ie","flag","nation","country","banner"],char:"🇮🇪",fitzpatrick_scale:!1,category:"flags"},isle_of_man:{keywords:["isle","man","flag","nation","country","banner"],char:"🇮🇲",fitzpatrick_scale:!1,category:"flags"},israel:{keywords:["il","flag","nation","country","banner"],char:"🇮🇱",fitzpatrick_scale:!1,category:"flags"},it:{keywords:["italy","flag","nation","country","banner"],char:"🇮🇹",fitzpatrick_scale:!1,category:"flags"},cote_divoire:{keywords:["ivory","coast","flag","nation","country","banner"],char:"🇨🇮",fitzpatrick_scale:!1,category:"flags"},jamaica:{keywords:["jm","flag","nation","country","banner"],char:"🇯🇲",fitzpatrick_scale:!1,category:"flags"},jp:{keywords:["japanese","nation","flag","country","banner"],char:"🇯🇵",fitzpatrick_scale:!1,category:"flags"},jersey:{keywords:["je","flag","nation","country","banner"],char:"🇯🇪",fitzpatrick_scale:!1,category:"flags"},jordan:{keywords:["jo","flag","nation","country","banner"],char:"🇯🇴",fitzpatrick_scale:!1,category:"flags"},kazakhstan:{keywords:["kz","flag","nation","country","banner"],char:"🇰🇿",fitzpatrick_scale:!1,category:"flags"},kenya:{keywords:["ke","flag","nation","country","banner"],char:"🇰🇪",fitzpatrick_scale:!1,category:"flags"},kiribati:{keywords:["ki","flag","nation","country","banner"],char:"🇰🇮",fitzpatrick_scale:!1,category:"flags"},kosovo:{keywords:["xk","flag","nation","country","banner"],char:"🇽🇰",fitzpatrick_scale:!1,category:"flags"},kuwait:{keywords:["kw","flag","nation","country","banner"],char:"🇰🇼",fitzpatrick_scale:!1,category:"flags"},kyrgyzstan:{keywords:["kg","flag","nation","country","banner"],char:"🇰🇬",fitzpatrick_scale:!1,category:"flags"},laos:{keywords:["lao","democratic","republic","flag","nation","country","banner"],char:"🇱🇦",fitzpatrick_scale:!1,category:"flags"},latvia:{keywords:["lv","flag","nation","country","banner"],char:"🇱🇻",fitzpatrick_scale:!1,category:"flags"},lebanon:{keywords:["lb","flag","nation","country","banner"],char:"🇱🇧",fitzpatrick_scale:!1,category:"flags"},lesotho:{keywords:["ls","flag","nation","country","banner"],char:"🇱🇸",fitzpatrick_scale:!1,category:"flags"},liberia:{keywords:["lr","flag","nation","country","banner"],char:"🇱🇷",fitzpatrick_scale:!1,category:"flags"},libya:{keywords:["ly","flag","nation","country","banner"],char:"🇱🇾",fitzpatrick_scale:!1,category:"flags"},liechtenstein:{keywords:["li","flag","nation","country","banner"],char:"🇱🇮",fitzpatrick_scale:!1,category:"flags"},lithuania:{keywords:["lt","flag","nation","country","banner"],char:"🇱🇹",fitzpatrick_scale:!1,category:"flags"},luxembourg:{keywords:["lu","flag","nation","country","banner"],char:"🇱🇺",fitzpatrick_scale:!1,category:"flags"},macau:{keywords:["macao","flag","nation","country","banner"],char:"🇲🇴",fitzpatrick_scale:!1,category:"flags"},macedonia:{keywords:["macedonia,","flag","nation","country","banner"],char:"🇲🇰",fitzpatrick_scale:!1,category:"flags"},madagascar:{keywords:["mg","flag","nation","country","banner"],char:"🇲🇬",fitzpatrick_scale:!1,category:"flags"},malawi:{keywords:["mw","flag","nation","country","banner"],char:"🇲🇼",fitzpatrick_scale:!1,category:"flags"},malaysia:{keywords:["my","flag","nation","country","banner"],char:"🇲🇾",fitzpatrick_scale:!1,category:"flags"},maldives:{keywords:["mv","flag","nation","country","banner"],char:"🇲🇻",fitzpatrick_scale:!1,category:"flags"},mali:{keywords:["ml","flag","nation","country","banner"],char:"🇲🇱",fitzpatrick_scale:!1,category:"flags"},malta:{keywords:["mt","flag","nation","country","banner"],char:"🇲🇹",fitzpatrick_scale:!1,category:"flags"},marshall_islands:{keywords:["marshall","islands","flag","nation","country","banner"],char:"🇲🇭",fitzpatrick_scale:!1,category:"flags"},martinique:{keywords:["mq","flag","nation","country","banner"],char:"🇲🇶",fitzpatrick_scale:!1,category:"flags"},mauritania:{keywords:["mr","flag","nation","country","banner"],char:"🇲🇷",fitzpatrick_scale:!1,category:"flags"},mauritius:{keywords:["mu","flag","nation","country","banner"],char:"🇲🇺",fitzpatrick_scale:!1,category:"flags"},mayotte:{keywords:["yt","flag","nation","country","banner"],char:"🇾🇹",fitzpatrick_scale:!1,category:"flags"},mexico:{keywords:["mx","flag","nation","country","banner"],char:"🇲🇽",fitzpatrick_scale:!1,category:"flags"},micronesia:{keywords:["micronesia,","federated","states","flag","nation","country","banner"],char:"🇫🇲",fitzpatrick_scale:!1,category:"flags"},moldova:{keywords:["moldova,","republic","flag","nation","country","banner"],char:"🇲🇩",fitzpatrick_scale:!1,category:"flags"},monaco:{keywords:["mc","flag","nation","country","banner"],char:"🇲🇨",fitzpatrick_scale:!1,category:"flags"},mongolia:{keywords:["mn","flag","nation","country","banner"],char:"🇲🇳",fitzpatrick_scale:!1,category:"flags"},montenegro:{keywords:["me","flag","nation","country","banner"],char:"🇲🇪",fitzpatrick_scale:!1,category:"flags"},montserrat:{keywords:["ms","flag","nation","country","banner"],char:"🇲🇸",fitzpatrick_scale:!1,category:"flags"},morocco:{keywords:["ma","flag","nation","country","banner"],char:"🇲🇦",fitzpatrick_scale:!1,category:"flags"},mozambique:{keywords:["mz","flag","nation","country","banner"],char:"🇲🇿",fitzpatrick_scale:!1,category:"flags"},myanmar:{keywords:["mm","flag","nation","country","banner"],char:"🇲🇲",fitzpatrick_scale:!1,category:"flags"},namibia:{keywords:["na","flag","nation","country","banner"],char:"🇳🇦",fitzpatrick_scale:!1,category:"flags"},nauru:{keywords:["nr","flag","nation","country","banner"],char:"🇳🇷",fitzpatrick_scale:!1,category:"flags"},nepal:{keywords:["np","flag","nation","country","banner"],char:"🇳🇵",fitzpatrick_scale:!1,category:"flags"},netherlands:{keywords:["nl","flag","nation","country","banner"],char:"🇳🇱",fitzpatrick_scale:!1,category:"flags"},new_caledonia:{keywords:["new","caledonia","flag","nation","country","banner"],char:"🇳🇨",fitzpatrick_scale:!1,category:"flags"},new_zealand:{keywords:["new","zealand","flag","nation","country","banner"],char:"🇳🇿",fitzpatrick_scale:!1,category:"flags"},nicaragua:{keywords:["ni","flag","nation","country","banner"],char:"🇳🇮",fitzpatrick_scale:!1,category:"flags"},niger:{keywords:["ne","flag","nation","country","banner"],char:"🇳🇪",fitzpatrick_scale:!1,category:"flags"},nigeria:{keywords:["flag","nation","country","banner"],char:"🇳🇬",fitzpatrick_scale:!1,category:"flags"},niue:{keywords:["nu","flag","nation","country","banner"],char:"🇳🇺",fitzpatrick_scale:!1,category:"flags"},norfolk_island:{keywords:["norfolk","island","flag","nation","country","banner"],char:"🇳🇫",fitzpatrick_scale:!1,category:"flags"},northern_mariana_islands:{keywords:["northern","mariana","islands","flag","nation","country","banner"],char:"🇲🇵",fitzpatrick_scale:!1,category:"flags"},north_korea:{keywords:["north","korea","nation","flag","country","banner"],char:"🇰🇵",fitzpatrick_scale:!1,category:"flags"},norway:{keywords:["no","flag","nation","country","banner"],char:"🇳🇴",fitzpatrick_scale:!1,category:"flags"},oman:{keywords:["om_symbol","flag","nation","country","banner"],char:"🇴🇲",fitzpatrick_scale:!1,category:"flags"},pakistan:{keywords:["pk","flag","nation","country","banner"],char:"🇵🇰",fitzpatrick_scale:!1,category:"flags"},palau:{keywords:["pw","flag","nation","country","banner"],char:"🇵🇼",fitzpatrick_scale:!1,category:"flags"},palestinian_territories:{keywords:["palestine","palestinian","territories","flag","nation","country","banner"],char:"🇵🇸",fitzpatrick_scale:!1,category:"flags"},panama:{keywords:["pa","flag","nation","country","banner"],char:"🇵🇦",fitzpatrick_scale:!1,category:"flags"},papua_new_guinea:{keywords:["papua","new","guinea","flag","nation","country","banner"],char:"🇵🇬",fitzpatrick_scale:!1,category:"flags"},paraguay:{keywords:["py","flag","nation","country","banner"],char:"🇵🇾",fitzpatrick_scale:!1,category:"flags"},peru:{keywords:["pe","flag","nation","country","banner"],char:"🇵🇪",fitzpatrick_scale:!1,category:"flags"},philippines:{keywords:["ph","flag","nation","country","banner"],char:"🇵🇭",fitzpatrick_scale:!1,category:"flags"},pitcairn_islands:{keywords:["pitcairn","flag","nation","country","banner"],char:"🇵🇳",fitzpatrick_scale:!1,category:"flags"},poland:{keywords:["pl","flag","nation","country","banner"],char:"🇵🇱",fitzpatrick_scale:!1,category:"flags"},portugal:{keywords:["pt","flag","nation","country","banner"],char:"🇵🇹",fitzpatrick_scale:!1,category:"flags"},puerto_rico:{keywords:["puerto","rico","flag","nation","country","banner"],char:"🇵🇷",fitzpatrick_scale:!1,category:"flags"},qatar:{keywords:["qa","flag","nation","country","banner"],char:"🇶🇦",fitzpatrick_scale:!1,category:"flags"},reunion:{keywords:["réunion","flag","nation","country","banner"],char:"🇷🇪",fitzpatrick_scale:!1,category:"flags"},romania:{keywords:["ro","flag","nation","country","banner"],char:"🇷🇴",fitzpatrick_scale:!1,category:"flags"},ru:{keywords:["russian","federation","flag","nation","country","banner"],char:"🇷🇺",fitzpatrick_scale:!1,category:"flags"},rwanda:{keywords:["rw","flag","nation","country","banner"],char:"🇷🇼",fitzpatrick_scale:!1,category:"flags"},st_barthelemy:{keywords:["saint","barthélemy","flag","nation","country","banner"],char:"🇧🇱",fitzpatrick_scale:!1,category:"flags"},st_helena:{keywords:["saint","helena","ascension","tristan","cunha","flag","nation","country","banner"],char:"🇸🇭",fitzpatrick_scale:!1,category:"flags"},st_kitts_nevis:{keywords:["saint","kitts","nevis","flag","nation","country","banner"],char:"🇰🇳",fitzpatrick_scale:!1,category:"flags"},st_lucia:{keywords:["saint","lucia","flag","nation","country","banner"],char:"🇱🇨",fitzpatrick_scale:!1,category:"flags"},st_pierre_miquelon:{keywords:["saint","pierre","miquelon","flag","nation","country","banner"],char:"🇵🇲",fitzpatrick_scale:!1,category:"flags"},st_vincent_grenadines:{keywords:["saint","vincent","grenadines","flag","nation","country","banner"],char:"🇻🇨",fitzpatrick_scale:!1,category:"flags"},samoa:{keywords:["ws","flag","nation","country","banner"],char:"🇼🇸",fitzpatrick_scale:!1,category:"flags"},san_marino:{keywords:["san","marino","flag","nation","country","banner"],char:"🇸🇲",fitzpatrick_scale:!1,category:"flags"},sao_tome_principe:{keywords:["sao","tome","principe","flag","nation","country","banner"],char:"🇸🇹",fitzpatrick_scale:!1,category:"flags"},saudi_arabia:{keywords:["flag","nation","country","banner"],char:"🇸🇦",fitzpatrick_scale:!1,category:"flags"},senegal:{keywords:["sn","flag","nation","country","banner"],char:"🇸🇳",fitzpatrick_scale:!1,category:"flags"},serbia:{keywords:["rs","flag","nation","country","banner"],char:"🇷🇸",fitzpatrick_scale:!1,category:"flags"},seychelles:{keywords:["sc","flag","nation","country","banner"],char:"🇸🇨",fitzpatrick_scale:!1,category:"flags"},sierra_leone:{keywords:["sierra","leone","flag","nation","country","banner"],char:"🇸🇱",fitzpatrick_scale:!1,category:"flags"},singapore:{keywords:["sg","flag","nation","country","banner"],char:"🇸🇬",fitzpatrick_scale:!1,category:"flags"},sint_maarten:{keywords:["sint","maarten","dutch","flag","nation","country","banner"],char:"🇸🇽",fitzpatrick_scale:!1,category:"flags"},slovakia:{keywords:["sk","flag","nation","country","banner"],char:"🇸🇰",fitzpatrick_scale:!1,category:"flags"},slovenia:{keywords:["si","flag","nation","country","banner"],char:"🇸🇮",fitzpatrick_scale:!1,category:"flags"},solomon_islands:{keywords:["solomon","islands","flag","nation","country","banner"],char:"🇸🇧",fitzpatrick_scale:!1,category:"flags"},somalia:{keywords:["so","flag","nation","country","banner"],char:"🇸🇴",fitzpatrick_scale:!1,category:"flags"},south_africa:{keywords:["south","africa","flag","nation","country","banner"],char:"🇿🇦",fitzpatrick_scale:!1,category:"flags"},south_georgia_south_sandwich_islands:{keywords:["south","georgia","sandwich","islands","flag","nation","country","banner"],char:"🇬🇸",fitzpatrick_scale:!1,category:"flags"},kr:{keywords:["south","korea","nation","flag","country","banner"],char:"🇰🇷",fitzpatrick_scale:!1,category:"flags"},south_sudan:{keywords:["south","sd","flag","nation","country","banner"],char:"🇸🇸",fitzpatrick_scale:!1,category:"flags"},es:{keywords:["spain","flag","nation","country","banner"],char:"🇪🇸",fitzpatrick_scale:!1,category:"flags"},sri_lanka:{keywords:["sri","lanka","flag","nation","country","banner"],char:"🇱🇰",fitzpatrick_scale:!1,category:"flags"},sudan:{keywords:["sd","flag","nation","country","banner"],char:"🇸🇩",fitzpatrick_scale:!1,category:"flags"},suriname:{keywords:["sr","flag","nation","country","banner"],char:"🇸🇷",fitzpatrick_scale:!1,category:"flags"},swaziland:{keywords:["sz","flag","nation","country","banner"],char:"🇸🇿",fitzpatrick_scale:!1,category:"flags"},sweden:{keywords:["se","flag","nation","country","banner"],char:"🇸🇪",fitzpatrick_scale:!1,category:"flags"},switzerland:{keywords:["ch","flag","nation","country","banner"],char:"🇨🇭",fitzpatrick_scale:!1,category:"flags"},syria:{keywords:["syrian","arab","republic","flag","nation","country","banner"],char:"🇸🇾",fitzpatrick_scale:!1,category:"flags"},taiwan:{keywords:["tw","flag","nation","country","banner"],char:"🇹🇼",fitzpatrick_scale:!1,category:"flags"},tajikistan:{keywords:["tj","flag","nation","country","banner"],char:"🇹🇯",fitzpatrick_scale:!1,category:"flags"},tanzania:{keywords:["tanzania,","united","republic","flag","nation","country","banner"],char:"🇹🇿",fitzpatrick_scale:!1,category:"flags"},thailand:{keywords:["th","flag","nation","country","banner"],char:"🇹🇭",fitzpatrick_scale:!1,category:"flags"},timor_leste:{keywords:["timor","leste","flag","nation","country","banner"],char:"🇹🇱",fitzpatrick_scale:!1,category:"flags"},togo:{keywords:["tg","flag","nation","country","banner"],char:"🇹🇬",fitzpatrick_scale:!1,category:"flags"},tokelau:{keywords:["tk","flag","nation","country","banner"],char:"🇹🇰",fitzpatrick_scale:!1,category:"flags"},tonga:{keywords:["to","flag","nation","country","banner"],char:"🇹🇴",fitzpatrick_scale:!1,category:"flags"},trinidad_tobago:{keywords:["trinidad","tobago","flag","nation","country","banner"],char:"🇹🇹",fitzpatrick_scale:!1,category:"flags"},tunisia:{keywords:["tn","flag","nation","country","banner"],char:"🇹🇳",fitzpatrick_scale:!1,category:"flags"},tr:{keywords:["turkey","flag","nation","country","banner"],char:"🇹🇷",fitzpatrick_scale:!1,category:"flags"},turkmenistan:{keywords:["flag","nation","country","banner"],char:"🇹🇲",fitzpatrick_scale:!1,category:"flags"},turks_caicos_islands:{keywords:["turks","caicos","islands","flag","nation","country","banner"],char:"🇹🇨",fitzpatrick_scale:!1,category:"flags"},tuvalu:{keywords:["flag","nation","country","banner"],char:"🇹🇻",fitzpatrick_scale:!1,category:"flags"},uganda:{keywords:["ug","flag","nation","country","banner"],char:"🇺🇬",fitzpatrick_scale:!1,category:"flags"},ukraine:{keywords:["ua","flag","nation","country","banner"],char:"🇺🇦",fitzpatrick_scale:!1,category:"flags"},united_arab_emirates:{keywords:["united","arab","emirates","flag","nation","country","banner"],char:"🇦🇪",fitzpatrick_scale:!1,category:"flags"},uk:{keywords:["united","kingdom","great","britain","northern","ireland","flag","nation","country","banner","british","UK","english","england","union jack"],char:"🇬🇧",fitzpatrick_scale:!1,category:"flags"},england:{keywords:["flag","english"],char:"🏴󠁧󠁢󠁥󠁮󠁧󠁿",fitzpatrick_scale:!1,category:"flags"},scotland:{keywords:["flag","scottish"],char:"🏴󠁧󠁢󠁳󠁣󠁴󠁿",fitzpatrick_scale:!1,category:"flags"},wales:{keywords:["flag","welsh"],char:"🏴󠁧󠁢󠁷󠁬󠁳󠁿",fitzpatrick_scale:!1,category:"flags"},us:{keywords:["united","states","america","flag","nation","country","banner"],char:"🇺🇸",fitzpatrick_scale:!1,category:"flags"},us_virgin_islands:{keywords:["virgin","islands","us","flag","nation","country","banner"],char:"🇻🇮",fitzpatrick_scale:!1,category:"flags"},uruguay:{keywords:["uy","flag","nation","country","banner"],char:"🇺🇾",fitzpatrick_scale:!1,category:"flags"},uzbekistan:{keywords:["uz","flag","nation","country","banner"],char:"🇺🇿",fitzpatrick_scale:!1,category:"flags"},vanuatu:{keywords:["vu","flag","nation","country","banner"],char:"🇻🇺",fitzpatrick_scale:!1,category:"flags"},vatican_city:{keywords:["vatican","city","flag","nation","country","banner"],char:"🇻🇦",fitzpatrick_scale:!1,category:"flags"},venezuela:{keywords:["ve","bolivarian","republic","flag","nation","country","banner"],char:"🇻🇪",fitzpatrick_scale:!1,category:"flags"},vietnam:{keywords:["viet","nam","flag","nation","country","banner"],char:"🇻🇳",fitzpatrick_scale:!1,category:"flags"},wallis_futuna:{keywords:["wallis","futuna","flag","nation","country","banner"],char:"🇼🇫",fitzpatrick_scale:!1,category:"flags"},western_sahara:{keywords:["western","sahara","flag","nation","country","banner"],char:"🇪🇭",fitzpatrick_scale:!1,category:"flags"},yemen:{keywords:["ye","flag","nation","country","banner"],char:"🇾🇪",fitzpatrick_scale:!1,category:"flags"},zambia:{keywords:["zm","flag","nation","country","banner"],char:"🇿🇲",fitzpatrick_scale:!1,category:"flags"},zimbabwe:{keywords:["zw","flag","nation","country","banner"],char:"🇿🇼",fitzpatrick_scale:!1,category:"flags"},united_nations:{keywords:["un","flag","banner"],char:"🇺🇳",fitzpatrick_scale:!1,category:"flags"},pirate_flag:{keywords:["skull","crossbones","flag","banner"],char:"🏴‍☠️",fitzpatrick_scale:!1,category:"flags"}}},function(a){a.exports=["grinning","smiley","smile","grin","laughing","sweat_smile","joy","rofl","relaxed","blush","innocent","slightly_smiling_face","upside_down_face","wink","relieved","heart_eyes","smiling_face_with_three_hearts","kissing_heart","kissing","kissing_smiling_eyes","kissing_closed_eyes","yum","stuck_out_tongue","stuck_out_tongue_closed_eyes","stuck_out_tongue_winking_eye","zany","raised_eyebrow","monocle","nerd_face","sunglasses","star_struck","partying","smirk","unamused","disappointed","pensive","worried","confused","slightly_frowning_face","frowning_face","persevere","confounded","tired_face","weary","pleading","cry","sob","triumph","angry","rage","symbols_over_mouth","exploding_head","flushed","hot","cold","scream","fearful","cold_sweat","disappointed_relieved","sweat","hugs","thinking","hand_over_mouth","shushing","lying_face","no_mouth","neutral_face","expressionless","grimacing","roll_eyes","hushed","frowning","anguished","open_mouth","astonished","sleeping","drooling_face","sleepy","dizzy_face","zipper_mouth_face","woozy","nauseated_face","vomiting","sneezing_face","mask","face_with_thermometer","face_with_head_bandage","money_mouth_face","cowboy_hat_face","smiling_imp","imp","japanese_ogre","japanese_goblin","clown_face","poop","ghost","skull","skull_and_crossbones","alien","space_invader","robot","jack_o_lantern","smiley_cat","smile_cat","joy_cat","heart_eyes_cat","smirk_cat","kissing_cat","scream_cat","crying_cat_face","pouting_cat","palms_up","open_hands","raised_hands","clap","handshake","+1","-1","facepunch","fist","fist_left","fist_right","crossed_fingers","v","love_you","metal","ok_hand","point_left","point_right","point_up","point_down","point_up_2","raised_hand","raised_back_of_hand","raised_hand_with_fingers_splayed","vulcan_salute","wave","call_me_hand","muscle","fu","writing_hand","pray","foot","leg","ring","lipstick","kiss","lips","tooth","tongue","ear","nose","footprints","eye","eyes","brain","speaking_head","bust_in_silhouette","busts_in_silhouette","baby","girl","child","boy","woman","adult","man","blonde_woman","blonde_man","bearded_person","older_woman","older_adult","older_man","man_with_gua_pi_mao","woman_with_headscarf","woman_with_turban","man_with_turban","policewoman","policeman","construction_worker_woman","construction_worker_man","guardswoman","guardsman","female_detective","male_detective","woman_health_worker","man_health_worker","woman_farmer","man_farmer","woman_cook","man_cook","woman_student","man_student","woman_singer","man_singer","woman_teacher","man_teacher","woman_factory_worker","man_factory_worker","woman_technologist","man_technologist","woman_office_worker","man_office_worker","woman_mechanic","man_mechanic","woman_scientist","man_scientist","woman_artist","man_artist","woman_firefighter","man_firefighter","woman_pilot","man_pilot","woman_astronaut","man_astronaut","woman_judge","man_judge","bride_with_veil","man_in_tuxedo","princess","prince","woman_superhero","man_superhe]===])
-- Returns a factory that creates a function which returns an existing instance of an object, or returns a new instance of that object. -- Sorry if that was confusing. -- Example for help: -- local GetOrCreateFactory = require(this) -- local GetOrCreateFolder = GetOrCreateFactory("Folder") -- GetOrCreateFolder(game.ReplicatedStorage, "MyFolderName") local function findOrCreate(parent, name, class) local obj = parent:FindFirstChild(name) if obj ~= nil then return obj end local obj = Instance.new(class) obj.Name = name obj.Parent = parent return obj end return function(class, Parent, Name) if not Parent or not Name then return function(parent, name) return findOrCreate(parent, name, class) end else return findOrCreate(Parent, Name, class) end end
local refresh_expiration = function (now, nextRequest, groupTimeout) if groupTimeout ~= nil then local ttl = (nextRequest + groupTimeout) - now for i = 1, #KEYS do redis.call('pexpire', KEYS[i], ttl) end end end
package("mkl") set_homepage("https://software.intel.com/content/www/us/en/develop/tools/oneapi/components/onemkl.html") set_description("Intel® oneAPI Math Kernel Library") if is_plat("windows") then if is_arch("x64") then add_urls("https://anaconda.org/intel/mkl-static/$(version)/download/win-64/mkl-static-$(version)-intel_296.tar.bz2") add_versions("2021.2.0", "54209e5d9c4778381f08b9a90e900c001494db020cda426441cd624cb0f7ebdc") add_resources("2021.2.0", "headers", "https://anaconda.org/intel/mkl-include/2021.2.0/download/win-64/mkl-include-2021.2.0-intel_296.tar.bz2", "ba222ea4ceb9e09976f23a3df39176148b4469b297275f3d05c1ad411b3d54c3") elseif is_arch("x86") then add_urls("https://anaconda.org/intel/mkl-static/$(version)/download/win-32/mkl-static-$(version)-intel_296.tar.bz2") add_versions("2021.2.0", "eaf0df027d58c5fd948f86b83dfc4d608855962cbdb04551712c9aeeb7b26eca") add_resources("2021.2.0", "headers", "https://anaconda.org/intel/mkl-include/2021.2.0/download/win-32/mkl-include-2021.2.0-intel_296.tar.bz2", "8ed173edff75783426de1bbc1d122266047fc84d4cfc5a9b810b1f2792f02c37") end elseif is_plat("macosx") and is_arch("x86_64") then add_urls("https://anaconda.org/intel/mkl-static/$(version)/download/osx-64/mkl-static-$(version)-intel_269.tar.bz2") add_versions("2021.2.0", "b7af248f01799873333cbd388b5efa19601cf6815dc38713509974783f4b1ccd") add_resources("2021.2.0", "headers", "https://anaconda.org/intel/mkl-include/2021.2.0/download/osx-64/mkl-include-2021.2.0-intel_269.tar.bz2", "5215d62cadeb3f8021230163dc35ad38259e3688aa0f39d7da69ebe54ab45624") elseif is_plat("linux") then if is_arch("x86_64") then add_urls("https://anaconda.org/intel/mkl-static/$(version)/download/linux-64/mkl-static-$(version)-intel_296.tar.bz2") add_versions("2021.2.0", "2bcaefefd593e4fb521e1fc88715f672ae5b9d1706babf10e3a10ef43ea0f983") add_resources("2021.2.0", "headers", "https://anaconda.org/intel/mkl-include/2021.2.0/download/linux-64/mkl-include-2021.2.0-intel_296.tar.bz2", "13721fead8a3eddee15b914fd3ae9cf2095966af79bbc2f086462eda9fff4d62") elseif is_arch("x86") then add_urls("https://anaconda.org/intel/mkl-static/$(version)/download/linux-32/mkl-static-$(version)-intel_296.tar.bz2") add_versions("2021.2.0", "34a1bc80a4a39ca5a55d29e9fcc803380fbc4d029ae496e60a918e8d12db68c2") add_resources("2021.2.0", "headers", "https://anaconda.org/intel/mkl-include/2021.2.0/download/linux-32/mkl-include-2021.2.0-intel_296.tar.bz2", "7fcbc945377b486b40d29b170d0b6c39bbc5b430ac7284dae2046bbf610f643d") end end add_configs("threading", {description = "Choose threading modal for mkl.", default = "tbb", type = "string", values = {"tbb", "openmp", "seq"}}) on_fetch("fetch") if is_plat("linux") then add_syslinks("pthread", "dl") end on_load("windows", "macosx", "linux", function (package) package:add("links", package:is_arch("x64", "x86_64") and "mkl_lapack95_ilp64" or "mkl_lapack95") if package:is_plat("windows") then package:add("links", package:is_arch("x64", "x86_64") and "mkl_intel_ilp64" or "mkl_intel_c") else package:add("links", package:is_arch("x64", "x86_64") and "mkl_intel_ilp64" or "mkl_intel") end local threading = package:config("threading") if threading == "tbb" then package:add("links", "mkl_tbb_thread") package:add("deps", "tbb") elseif threading == "seq" then package:add("links", "mkl_sequential") elseif threading == "openmp" then package:add("links", "mkl_intel_thread") end package:add("links", "mkl_core") end) on_install("windows", "macosx", "linux", function (package) local headerdir = package:resourcedir("headers") if package:is_plat("windows") then os.trymv(path.join("Library", "lib"), package:installdir()) os.trymv(path.join(headerdir, "Library", "include"), package:installdir()) else os.trymv(path.join("lib"), package:installdir()) os.trymv(path.join(headerdir, "include"), package:installdir()) end end) on_test(function (package) assert(package:check_csnippets({test = [[ void test() { double A[6] = {1.0,2.0,1.0,-3.0,4.0,-1.0}; double B[6] = {1.0,2.0,1.0,-3.0,4.0,-1.0}; double C[9] = {.5,.5,.5,.5,.5,.5,.5,.5,.5}; cblas_dgemm(CblasColMajor,CblasNoTrans,CblasTrans,3,3,2,1,A,3,B,3,2,C,3); } ]]}, {includes = "mkl_cblas.h"})) end)
require 'nn' require 'lfs' input_params = { data_dir = "/home/prannayk/machine_learning/datasets/", learningRate = 0.1, dropout = 0.2, skip_window = 2, margin = 0.02, num_layers = 3, train_frac = 0.7, valid_frac = 0.2, test_frac = 0.1, input_file = "text8", vocab_file = "vocab.t7", tensor_file = "tensor.t7" } print("Loaded dependencies") local BatchCreator = require 'util.BatchCreator' print(input_params) batch = BatchCreator.create(input_params) print(batch) batch:checkLoadedVectors() print(some) --BatchCreator:checkLoadedVectors() print ("Loaded data, finished building Vocab and Tensors")
local BX_DIR = "%{wks.location}/bx" local BIMG_DIR = "%{wks.location}/bimg" project "bimg" kind "StaticLib" language "C++" cppdialect "C++14" exceptionhandling "Off" rtti "Off" files { BIMG_DIR .. "/include/bimg/*.h", BIMG_DIR .. "/src/image.cpp", BIMG_DIR .. "/src/image_gnf.cpp", BIMG_DIR .. "/src/*.h", BIMG_DIR .. "/3rdparty/astc-codec/src/decoder/*.cc", } includedirs { BX_DIR .. "/include", BIMG_DIR .. "/include", BIMG_DIR .. "/3rdparty/astc-codec", BIMG_DIR .. "/3rdparty/astc-codec/include", } filter "action:vs*" includedirs { BX_DIR .. "/include/compat/msvc" } filter { "system:windows", "action:gmake" } includedirs { BX_DIR .. "/include/compat/mingw" } filter { "system:macosx" } includedirs { BX_DIR .. "/include/compat/osx" } buildoptions { "-x objective-c++" }
local ffi = require('ffi') local keymap = require('fzf.keymap') fzf = {} fzf.results = {} fzf.prompt = {} ffi.cdef[[ typedef struct { char* str; size_t len; } fzf_string; typedef struct { fzf_string results[40]; size_t len; } fzf_output; void fzf_init(char** ignore, int len); void fzf_start(fzf_string* prompt); fzf_output fzf_get_output(); int fzf_char_match(fzf_string* s1, fzf_string* s2); int fzf_fuzzy_match(fzf_string* s1, fzf_string* s2); ]] local lib = {} function fzf.setup() local path = vim.api.nvim_get_runtime_file('bin/libfuzzy.*', false) lib = ffi.load(path[1]) local ignore = ffi.new('char*[?]', 2) ignore[0] = ffi.new('char[?]', #'./.git') ffi.copy(ignore[0], './.git') ignore[1] = ffi.new('char[?]', #'./build') ffi.copy(ignore[1], './build') lib.fzf_init(ignore, 2) end function fzf.create_win() local opts = { relative = 'editor', style = 'minimal', border = 'single' } opts.col = math.ceil(vim.o.columns / 4) opts.row = math.ceil(vim.o.lines / 8) - 2 opts.width = vim.o.columns - opts.col * 2 opts.height = vim.o.lines - opts.row * 2 - 6 fzf.results.buf = vim.api.nvim_create_buf(false, true) fzf.results.win = vim.api.nvim_open_win(fzf.results.buf, false, opts) opts.row = vim.o.lines - math.ceil(vim.o.lines / 8) - 2 opts.height = 1 fzf.prompt.buf = vim.api.nvim_create_buf(false, true) fzf.prompt.win = vim.api.nvim_open_win(fzf.prompt.buf, true, opts) fzf.prompt.tick = vim.api.nvim_buf_get_changedtick(fzf.prompt.buf) fzf.selection = 0 fzf.selected = '' vim.wo.statusline = '%#STLText# fzf' vim.bo.filetype = 'fzf' vim.api.nvim_command('autocmd BufLeave <buffer> lua require("fzf").close()') vim.api.nvim_buf_set_option(fzf.prompt.buf, 'buftype', 'prompt') vim.fn.prompt_setprompt(fzf.prompt.buf, '> ') keymap.bind(fzf.prompt.buf) end function fzf.close() vim.api.nvim_set_current_win(fzf.cwin) vim.api.nvim_set_current_buf(fzf.cbuf) vim.api.nvim_win_close(fzf.results.win, { force = 1 }) vim.api.nvim_win_close(fzf.prompt.win, { force = 1 }) vim.api.nvim_buf_delete(fzf.results.buf, { force = 1 }) vim.api.nvim_buf_delete(fzf.prompt.buf, { force = 1 }) vim.api.nvim_input('<esc>') end function fzf.render() local lines = {} local output = lib.fzf_get_output() local height = vim.api.nvim_win_get_height(fzf.results.win) local len = tonumber(output.len) if len == 0 then return end for i = 1, height - len do table.insert(lines, '') end local start = math.max(len - height, 0) for i = start, len - 1 do local prefix = ' ' local str = output.results[i] if i == len - fzf.selection - 1 then prefix = '> ' fzf.selected = ffi.string(str.str, str.len) end table.insert(lines, prefix .. ffi.string(str.str, str.len)) end vim.api.nvim_buf_set_lines(fzf.results.buf, 0, -1, false, lines) end function fzf.run() fzf.cwin = vim.api.nvim_get_current_win() fzf.cbuf = vim.api.nvim_get_current_buf() fzf.create_win() local timer = vim.loop.new_timer() timer:start(100, 50, vim.schedule_wrap(function() local tick = vim.api.nvim_buf_get_changedtick(fzf.prompt.buf) if tick ~= fzf.prompt.tick then fzf.prompt.tick = tick local lines = vim.api.nvim_buf_get_lines(fzf.prompt.buf, 0, 1, false) local input = string.sub(lines[1], 3):lower() local prompt = ffi.new('fzf_string[?]', 1) prompt[0].str = ffi.new('char[?]', #input + 1) ffi.copy(prompt[0].str, input) prompt[0].len = #input lib.fzf_start(prompt) end if vim.api.nvim_buf_line_count(fzf.prompt.buf) > 1 then vim.api.nvim_buf_set_lines(fzf.prompt.buf, 0, -1, false, {}) end fzf.render() end)) vim.api.nvim_buf_attach(fzf.prompt.buf, false, { on_detach = function() timer:stop() timer:close() end }) vim.api.nvim_input('i') end return fzf
local debug = require("__janosch-lib__.debug") local error = {} -- error types error.no_handler_for_request_type = function (request_type) return { code = 1, message = "No handler found for request_type: " .. request_type, } end error.request_handler_failed = function (request_type, lua_error, handler) local origin if handler then origin = debug.format_info(handler) else origin = "unknown" end return { code = 2, lua_error = lua_error, message = "Handler failed with unexpectedly: " .. origin, } end return error
RoundController = Class { init = function(self) self.roundIndex = 1 self.readyToStart = false self.currentRound = Round(1) self.totalRounds = 30 self.crucible = Crucible(3) self.ENEMY_BLUEPRINTS = require("src.enemy-blueprints") self.bossRounds = { { roundIndex = 5, crucibleSlots = { { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH"] }, } }, { roundIndex = 10, crucibleSlots = { { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-SKULL"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH"] }, } }, { roundIndex = 15, crucibleSlots = { { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-SKULL"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-SKULL"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH"] }, } }, { roundIndex = 20, crucibleSlots = { { blueprint = self.ENEMY_BLUEPRINTS["BLOB-SKULL"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-SKULL"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH-DARK"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-SKULL"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-SKULL"] } } }, { roundIndex = 25, crucibleSlots = { { blueprint = self.ENEMY_BLUEPRINTS["BLOB-SKULL-DARK"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH-DARK"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-SKULL-DARK"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH-DARK"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-EYE"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH-DARK"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-SKULL-DARK"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH-DARK"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-SKULL-DARK"] } } }, { roundIndex = 30, crucibleSlots = { { blueprint = self.ENEMY_BLUEPRINTS["BLOB-EYE"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH-DARK"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-EYE"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-SKULL-DARK"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-EYE"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-SKULL-DARK"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-EYE"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-TEETH-DARK"] }, { blueprint = self.ENEMY_BLUEPRINTS["BLOB-EYE"] } } }, } end; update = function(self, dt) if self.readyToStart then roundController:startRound() self.readyToStart = false end end; canSpawn = function(self) return self.currentRound.enemiesSpawned < #self.currentRound.enemies end; nextEnemy = function(self) local enemy = self.currentRound:getNextEnemy() Timer.after(constants.ENEMY.SPAWN_INTERVAL/2, function() self:updateCauldron() end) return enemy end; enemyDefeated = function(self) self.currentRound.enemiesDefeated = self.currentRound.enemiesDefeated + 1 if self.currentRound.enemiesDefeated == self.currentRound.totalEnemies then self:nextRound() end end; nextRound = function(self) if self.roundIndex + 1 > self.totalRounds then if not playerController.hasLost then playerController:victory() end else self.crucible:reset() self.roundIndex = self.roundIndex + 1 animationController:changeSpriteState(world.spawnAnimation, "DEFAULT") self.currentRound = Round(self.roundIndex) uiController.firstRun = true for i, bossRound in pairs(self.bossRounds) do if bossRound.roundIndex == self.roundIndex then self:prepareBossRound(bossRound) end end self:unlockEnemies() self:lockEnemies() if self.roundIndex == 2 and not configController.settings.seenMultiSelectTutorial then Timer.after(1, function() helpController:addText('Try holding SHIFT to place multiple structures quickly!', 20, {0.2,0.8,0}) configController:updateSetting('seenMultiSelectTutorial', true) end) end if self.roundIndex == 3 and not configController.settings.seenUpgradeTutorial then Timer.after(1, function() helpController:addText('You can create hybrid towers by spending the currency you gain from defeating elemental blobs!', 20, {0.2,0.8,0}) configController:updateSetting('seenUpgradeTutorial', true) end) end if self.roundIndex == 4 and not configController.settings.seenRefundTutorial then Timer.after(1, function() helpController:addText('You can refund any existing towers for the full cost (including upgrades)', 20, {0.2,0.8,0}) configController:updateSetting('seenRefundTutorial', true) end) end if self.roundIndex == 5 and not configController.settings.seenBossTutorial then Timer.after(1, function() helpController:addText('Steady now! Every 5th wave your maze will be tested by powerful boss monsters.', 20, {0.8,0.3,0}) configController:updateSetting('seenBossTutorial', true) end) end if self.roundIndex == 6 then if not configController.settings.seenLargeTutorialOne then Timer.after(1, function() helpController:addText('Large blobs are now available. Be careful though, they are MUCH tougher than regular blobs!', 20, {0.2,0.8,0}) configController:updateSetting('seenLargeTutorial', true) end) end end if self.roundIndex == 7 and not configController.settings.seenBeaconTutorial then Timer.after(1, function() helpController:addText('Beacons can speed up the damage output of any nearby towers.', 20, {0.2,0.8,0}) configController:updateSetting('seenBeaconTutorial', true) end) end if self.roundIndex == 8 and not configController.settings.seenMassResellTutorial then Timer.after(1, function() helpController:addText('Try holding X to quickly sell lots of towers!', 20, {0.2,0.8,0}) configController:updateSetting('seenMassResellTutorial', true) end) end if self.roundIndex == 11 then if not configController.settings.seenLargeTutorialTwo then Timer.after(1, function() helpController:addText('Large elemental enemies are now available! Be careful though, they are MUCH tougher than regular blobs!', 20, {0.2,0.8,0}) configController:updateSetting('seenLargeTutorial', true) end) end end if self.roundIndex == 16 or self.roundIndex == 21 or self.roundIndex == 26 then Timer.after(1, function() helpController:addText('Enemies just got tougher. Don\'t get cocky! ', 20, {0.2,0.8,0}) end) end end end; prepareBossRound = function(self, bossRound) for i, slot in ipairs(bossRound.crucibleSlots) do self.crucible:setSlot(i, slot.blueprint) end self.crucible:lock() end; startRound = function(self) if self:isBuildPhase() then -- build the crucible enemies local roundEnemies = self.crucible:constructEnemies(self.roundIndex, self.totalRounds) if #roundEnemies > 0 then self.currentRound:setEnemies(roundEnemies) world:setupTimers() self.currentRound:start() self:updateCauldron() audioController:playAny("START_ROUND") cameraController:shake(0.5, 3) else helpController:addText("You must select enemies to send before the round can begin!", nil, {0.8,0.3,0}) return end end end; updateCauldron = function(self) local nextEnemy = self.currentRound:peekNextEnemy() if nextEnemy then animationController:changeSpriteState(world.spawnAnimation, "SPAWNING_"..nextEnemy.element) end end; isBuildPhase = function(self) return not self.currentRound.hasStarted end; isEnemyPhase = function(self) return self.currentRound.hasStarted end; unlockEnemies = function(self) for i, enemy in pairs(self.ENEMY_BLUEPRINTS) do if self.roundIndex == enemy.roundLocks[1] then enemy.isUnlocked = true end end end; lockEnemies = function(self) for i, enemy in pairs(self.ENEMY_BLUEPRINTS) do if self.roundIndex == enemy.roundLocks[2] then enemy.isUnlocked = false end end end; }
--[[ Try this file with the following commands lines; example.lua --help example.lua -o myfile -d --compress=gzip inputfile example.lua --__DUMP__ -o myfile -d --compress=gzip inputfile --]] local cli = require "cliargs" -- this is called when the flag -v or --version is set local function print_version() print("cli_example.lua: version 1.2.1") print("lua_cliargs: version " .. cli.VERSION) os.exit(0) end cli:set_name("cli_example.lua") -- Required arguments: cli:argument("OUTPUT", "path to the output file") -- Optional (repetitive) arguments -- only the last argument can be optional. Being set to maximum 3 optionals. cli:splat("INPUTS", "the source files to read from", "/tmp/foo", 3) -- Optional parameters: cli:option("-c, --compress=FILTER", "the filter to use for compressing output: gzip, lzma, bzip2, or none", "gzip") -- cli:option("-o FILE", "path to output file", "/dev/stdout") -- Flags: a flag is a boolean option. Defaults to false -- A flag with short-key notation only cli:flag("-d", "script will run in DEBUG mode") -- A flag with both the short-key and --expanded-key notations, and callback function cli:flag("-v, --version", "prints the program's version and exits", print_version) -- A flag with --expanded-key notation only cli:flag("--verbose", "the script output will be very verbose") -- A flag that can be negated using --no- as a prefix, but you'll still have -- to access its value without that prefix. See below for an example. cli:flag('--[no-]ice-cream', 'ice cream, or not', true) -- Parses from _G['arg'] local args, err = cli:parse(arg) if not args and err then -- something wrong happened and an error was printed print(string.format('%s: %s; re-run with help for usage', cli.name, err)) os.exit(1) elseif not args['ice-cream'] then print('kernel panic: NO ICE CREAM?!11') os.exit(1000) end -- argument parsing was successful, arguments can be found in `args` -- upon successful parsing cliargs will delete itslef to free resources -- for k,item in pairs(args) do print(k .. " => " .. tostring(item)) end print("Output file: " .. args["OUTPUT"]) print("Input files:") for i, out in ipairs(args.INPUTS) do print(" " .. i .. ". " .. out) end print(args.c) if not args['c'] or args['c'] == 'none' then print("Won't be compressing") else print("Compressing using " .. args['c']) end if args['ice-cream'] then print('And, one ice cream for you.') end
local a = require('plenary.async.async') local wrap = a.wrap local void = a.void local scheduler = require('plenary.async.util').scheduler local cache = require('gitsigns.cache').cache local config = require('gitsigns.config').config local BlameInfo = require('gitsigns.git').BlameInfo local api = vim.api local current_buf = api.nvim_get_current_buf local namespace = api.nvim_create_namespace('gitsigns_blame') local timer = vim.loop.new_timer() local M = {} local wait_timer = wrap(vim.loop.timer_start, 4) M.reset = function(bufnr) bufnr = bufnr or current_buf() api.nvim_buf_del_extmark(bufnr, namespace, 1) pcall(api.nvim_buf_del_var, bufnr, 'gitsigns_blame_line_dict') end local max_cache_size = 1000 local BlameCache = {Elem = {}, } BlameCache.contents = {} function BlameCache:init_or_invalidate(bufnr) if not config._blame_cache then return end local tick = api.nvim_buf_get_var(bufnr, 'changedtick') if not self.contents[bufnr] or self.contents[bufnr].tick ~= tick then self.contents[bufnr] = { tick = tick, cache = {}, size = 0 } end end function BlameCache:add(bufnr, lnum, x) if not config._blame_cache then return end local scache = self.contents[bufnr] if scache.size <= max_cache_size then scache.cache[lnum] = x scache.size = scache.size + 1 end end function BlameCache:get(bufnr, lnum) if not config._blame_cache then return end return self.contents[bufnr].cache[lnum] end M.update = void(function() M.reset() local opts = config.current_line_blame_opts wait_timer(timer, opts.delay, 0) scheduler() local bufnr = current_buf() local bcache = cache[bufnr] if not bcache or not bcache.git_obj.object_name then return end local lnum = api.nvim_win_get_cursor(0)[1] BlameCache:init_or_invalidate(bufnr) local result = BlameCache:get(bufnr, lnum) if not result then local buftext = api.nvim_buf_get_lines(bufnr, 0, -1, false) result = bcache.git_obj:run_blame(buftext, lnum, opts.ignore_whitespace) BlameCache:add(bufnr, lnum, result) end scheduler() M.reset(bufnr) local lnum1 = api.nvim_win_get_cursor(0)[1] if bufnr == current_buf() and lnum ~= lnum1 then return end if not api.nvim_buf_is_loaded(bufnr) then return end api.nvim_buf_set_var(bufnr, 'gitsigns_blame_line_dict', result) if opts.virt_text then api.nvim_buf_set_extmark(bufnr, namespace, lnum - 1, 0, { id = 1, virt_text = config.current_line_blame_formatter( bcache.git_obj.repo.username, result, config.current_line_blame_formatter_opts), virt_text_pos = opts.virt_text_pos, hl_mode = 'combine', }) end end) M.setup = function() vim.cmd([[ augroup gitsigns_blame autocmd! augroup END ]]) for k, _ in pairs(cache) do M.reset(k) end if config.current_line_blame then vim.cmd([[autocmd gitsigns_blame FocusGained,BufEnter,CursorMoved,CursorMovedI * lua require("gitsigns.current_line_blame").update()]]) vim.cmd([[autocmd gitsigns_blame FocusLost,BufLeave * lua require("gitsigns.current_line_blame").reset()]]) M.update() end end return M
local composer = require( "composer" ) local scene = composer.newScene() -- ----------------------------------------------------------------------------------- -- Code outside of the scene event functions below will only be executed ONCE unless -- the scene is removed entirely (not recycled) via "composer.removeScene()" -- ----------------------------------------------------------------------------------- -- NOTE: THIS SCENE IS ONLY USED TO REFRESH THE GAME -- ----------------------------------------------------------------------------------- -- Scene event functions -- ----------------------------------------------------------------------------------- -- show() function scene:show( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Code here runs when the scene is still off screen (but is about to come on screen) elseif ( phase == "did" ) then -- Code here runs when the scene is entirely on screen composer.gotoScene( "scenes.game" ) end end -- ----------------------------------------------------------------------------------- -- Scene event function listeners -- ----------------------------------------------------------------------------------- scene:addEventListener( "show", scene ) -- ----------------------------------------------------------------------------------- return scene
--[[ © 2016-2017 TeslaCloud Studios See license in LICENSE.txt. --]] -- A function to include a file based on it's prefix. function util.Include(strFile) if (SERVER) then if (string.find(strFile, "sh_") or string.find(strFile, "shared.lua")) then AddCSLuaFile(strFile) return include(strFile) elseif (string.find(strFile, "cl_")) then AddCSLuaFile(strFile) elseif (string.find(strFile, "sv_") or string.find(strFile, "init.lua")) then return include(strFile) end else if (string.find(strFile, "sh_") or string.find(strFile, "cl_") or string.find(strFile, "shared.lua")) then return include(strFile) end end end -- A function to include all files in a directory. function util.IncludeDirectory(strDirectory, strBase, bIsRecursive) if (isstring(strBase)) then if (!strBase:EndsWith("/")) then strBase = strBase.."/" end strDirectory = strBase..strDirectory end if (!strDirectory:EndsWith("/")) then strDirectory = strDirectory.."/" end if (bIsRecursive) then local files, folders = file.Find(strDirectory.."*", "LUA", "namedesc") -- First include the files. for k, v in ipairs(files) do if (v:GetExtensionFromFilename() == "lua") then util.Include(strDirectory..v) end end -- Then include all directories. for k, v in ipairs(folders) do util.IncludeDirectory(strDirectory..v, bIsRecursive) end else local files, _ = file.Find(strDirectory.."*.lua", "LUA", "namedesc") for k, v in ipairs(files) do util.Include(strDirectory..v) end end end -- A function to check whether all of the arguments in vararg are valid (via IsValid). function util.Validate(...) local validate = {...} if (#validate <= 0) then return false end for k, v in ipairs(validate) do if (!IsValid(v)) then return false end end return true end -- A function to get lowercase type of an object. function typeof(obj) return string.lower(type(obj)) end -- A nicer wrapper for pcall. function Try(id, func, ...) id = id or "Try" local result = {pcall(func, ...)} local success = result[1] table.remove(result, 1) if (!success) then ErrorNoHalt("[Try:"..id.."] Failed to run the function!\n") ErrorNoHalt(unpack(result), "\n") elseif (result[1] != nil) then return unpack(result) end end do local tryCache = {} -- An even nicer wrapper for pcall. function try(tab) tryCache = {} tryCache.f = tab[1] local args = {} for k, v in ipairs(tab) do if (k != 1) then table.insert(args, v) end end tryCache.args = args end function catch(handler) local func = tryCache.f local args = tryCache.args or {} local result = {pcall(func, unpack(args))} local success = result[1] table.remove(result, 1) tryCache = {} if (!success) then if (isfunction(handler[1])) then handler[1](unpack(result)) else ErrorNoHalt("[Try:Exception] Failed to run the function!\n") ErrorNoHalt(unpack(result), "\n") end elseif (result[1] != nil) then return unpack(result) end end --[[ Please note that the try-catch block will only run if you put in the catch function. Example usage: try { function() print("Hello World") end } catch { function(exception) print(exception) end } try { function(arg1, arg2) print(arg1, arg2) end, "arg1", "arg2" } catch { function(exception) print(exception) end } --]] end do local materialCache = {} -- A function to get a material. It caches the material automatically. function util.GetMaterial(mat) if (!materialCache[mat]) then materialCache[mat] = Material(mat) end return materialCache[mat] end end -- A function to do C-style formatted prints. function printf(str, ...) print(Format(str, ...)) end -- A function to determine whether vector from A to B intersects with a -- vector from C to D. function util.VectorsIntersect(vFrom, vTo, vFrom2, vTo2) local d1, d2, a1, a2, b1, b2, c1, c2 a1 = vTo.y - vFrom.y b1 = vFrom.x - vTo.x c1 = (vTo.x * vFrom.y) - (vFrom.x * vTo.y) d1 = (a1 * vFrom2.x) + (b1 * vFrom2.y) + c1 d2 = (a1 * vTo2.x) + (b1 * vTo2.y) + c1 if (d1 > 0 and d2 > 0) then return false end if (d1 < 0 and d2 < 0) then return false end a2 = vTo2.y - vFrom2.y b2 = vFrom2.x - vTo2.x c2 = (vTo2.x * vFrom2.y) - (vFrom2.x * vTo2.y) d1 = (a2 * vFrom.x) + (b2 * vFrom.y) + c2 d2 = (a2 * vTo.x) + (b2 * vTo.y) + c2 if (d1 > 0 and d2 > 0) then return false end if (d1 < 0 and d2 < 0) then return false end -- Vectors are collinear or intersect. -- No need for further checks. return true end -- A function to determine whether a 2D point is inside of a 2D polygon. function util.VectorIsInPoly(point, polyVertices) if (!isvector(point) or !istable(polyVertices) or !isvector(polyVertices[1])) then return end local intersections = 0 for k, v in ipairs(polyVertices) do local nextVert if (k < #polyVertices) then nextVert = polyVertices[k + 1] elseif (k == #polyVertices) then nextVert = polyVertices[1] end if (nextVert and util.VectorsIntersect(point, Vector(99999, 99999, 0), v, nextVert)) then intersections = intersections + 1 end end -- Check whether number of intersections is even or odd. -- If it's odd then the point is inside the polygon. if (intersections % 2 == 0) then return false else return true end end function table.SafeMerge(to, from) local oldIndex, oldIndex2 = to.__index, from.__index to.__index = nil from.__index = nil table.Merge(to, from) to.__index = oldIndex from.__index = oldIndex2 end function util.WaitForEntity(entIndex, callback, delay, waitTime) local entity = Entity(entIndex) if (!IsValid(entity)) then local timerName = CurTime().."_EntWait" timer.Create(timerName, delay or 0, waitTime or 100, function() local entity = Entity(entIndex) if (IsValid(entity)) then callback(entity) timer.Remove(timerName) end end) else callback(entity) end end function util.ToBool(value) return (tonumber(value) == 1 or value == true or value == "true") end
function setup() sb = {} t = Text.new(50, 30) table.insert(sb, t) t:fakeBoot() x, y = 0, 0 end function update() if y > 0 and window.button.downTime["up"] % 5 == 1 then y = y - 1 end if y < 28 and window.button.downTime["down"] % 5 == 1 then y = y + 1 end if x > 0 and window.button.downTime["left"] % 5 == 1 then x = x - 1 end if x < 49 and window.button.downTime["right"] % 5 == 1 then x = x + 1 end for i = 1, #sb do sb[i]:update() end end function draw() love.graphics.clear(0, 0, 0) t:clearScreen() t:locate(x, y) t:print("Hello, world!" .. string.char(10) .. ":D", false) ZSort.clear() for i = 1, #sb do ZSort.add(sb[i]) end ZSort.flush() end
-- returns if a number is even or not return (function(num) if (num % 2 == 0) then return true else return false end end)
local channel_busy = love.thread.getChannel("3DreamEngine_channel_jobs_channel_busy") local channel_jobs = love.thread.getChannel("3DreamEngine_channel_jobs") local channel_results = love.thread.getChannel("3DreamEngine_channel_results") require("love.image") --combine three image datas local function combineImages(red, green, blue, exportFormat, exportPath) local combined = red or green or blue --pixel mapper local function combine(x, y, oldR, oldG, oldB) local r, g, b = 1.0, 1.0, 1.0 if combined == red then r = oldR elseif red then r, _, _ = red:getPixel(x, y) end if combined == green then g = oldG elseif green then _, g, _ = green:getPixel(x, y) end if combined == blue then b = oldB elseif blue then _, _, b = blue:getPixel(x, y) end return r, g, b, 1.0 end --apply and encode combined:mapPixel(combine) combined:encode(exportFormat, exportPath) return combined end while true do local msg = channel_jobs:demand() if msg then channel_busy:push(true) if msg[1] == "image" then local info = love.filesystem.getInfo(msg[2]) assert(info, "Image " .. msg[2] .. " does not exist!") --load image local isCompressed = love.image.isCompressed(msg[2]) local imageData = isCompressed and love.image.newCompressedData(msg[2]) or love.image.newImageData(msg[2]) channel_results:push({"image", msg[2], imageData, isCompressed}) elseif msg[1] == "combine" then local exportFormat = "tga" local dir = "combined" local exportPath = dir .. "/" .. msg[2] .. "." .. exportFormat --check if cache is up to date local combined local info = love.filesystem.getInfo(exportPath) if info then local info1 = msg[3] and love.filesystem.getInfo(msg[3]) local info2 = msg[4] and love.filesystem.getInfo(msg[4]) local info3 = msg[5] and love.filesystem.getInfo(msg[5]) if (not info1 or (info.modtime or 0) > (info1.modtime or 0)) and (not info2 or (info.modtime or 0) > (info2.modtime or 0)) and (not info3 or (info.modtime or 0) > (info3.modtime or 0)) then combined = love.image.newImageData(exportPath) end end --cache is outdated, combine if not combined then print("Requested generation of " .. msg[2] .. "." .. exportFormat .. ". Texture will be exported to save directory, subdirectory " .. dir) love.filesystem.createDirectory(dir .. "/" .. (msg[2]:match("(.*[/\\])") or "")) local red = msg[3] and love.image.newImageData(msg[3]) local green = msg[4] and love.image.newImageData(msg[4]) local blue = msg[5] and love.image.newImageData(msg[5]) combined = combineImages(red, green, blue, exportFormat, exportPath) end --send result channel_results:push({"image", msg[2], combined}) end channel_busy:pop() end end
local unpack, select, type, pairs, tinsert, max, floor, abs = unpack, select, type, pairs, table.insert, math.max, math.floor, math.abs local UnitFactionGroup, DressUpTexturePath, CreateFrame, GetItemIcon, GetSpecializationInfoByID, GetClassInfoByID, GetInventorySlotInfo, UnitStat, BreakUpLargeNumbers, UnitName = UnitFactionGroup, DressUpTexturePath, CreateFrame, GetItemIcon, GetSpecializationInfoByID, GetClassInfoByID, GetInventorySlotInfo, UnitStat, BreakUpLargeNumbers, UnitName local BestInSlot, L, AceGUI = unpack(select(2, ...)) local Preview = BestInSlot:NewModule("Preview Window") local iconsize = 37 Preview.raceids = { Human = 1, Dwarf = 3, Gnome = 7, NightElf = 4, Draenei = 11, Worgen = 22, Orc = 2, Undead = 5, Tauren = 6, Troll = 8, BloodElf = 10, Goblin = 9, Pandaren = 25, } Preview.classes = {} Preview.attributes = PAPERDOLL_STATCATEGORIES[1].stats --AttributesCategory local temp = PAPERDOLL_STATCATEGORIES[2].stats --EnhancementsCategory --local temp = PAPERDOLL_STATINFO.ENHANCEMENTS.stats Preview.enhancements = {} for i=1,#temp do Preview.enhancements[i] = temp[i] end tinsert(Preview.enhancements, "ATTACK_AP") tinsert(Preview.enhancements, "SPELLPOWER") temp = nil local noBenefit = {text = "STAT_NO_BENEFIT_TOOLTIP"} Preview.classinfo = { __default = { basestat = { CRITCHANCE = 5, SPIRIT = 781, }, stats = { STRENGTH = { noBenefit, {text = "DEFAULT_STAT1_TOOLTIP"}, {text = "STAT_TOOLTIP_BONUS_AP_SP"} }, AGILITY = { noBenefit, {text = "DEFAULT_STAT2_TOOLTIP"} }, INTELLECT = { noBenefit, {text = "DEFAULT_STAT4_TOOLTIP"} }, STAMINA = { {text = "DEFAULT_STAT3_TOOLTIP", func = function(str, value) return _G[str]:format(BreakUpLargeNumbers(value * 60)) end} }, CRITCHANCE = { {text = "CR_CRIT_TOOLTIP"}, {text = "CR_CRIT_PARRY_RATING_TOOLTIP"} }, HASTE = { {text = "STAT_HASTE_BASE_TOOLTIP", func = function(str, value1, value2) return _G.STAT_HASTE_TOOLTIP.._G[str]:format(BreakUpLargeNumbers(value1), value2) end}, }, MASTERY = { {text = "", func = function() return L["Mastery tooltips are not supported due to technical limitations"] end}, }, SPIRIT = { noBenefit, {text = "MANA_REGEN_FROM_SPIRIT", func = function(str, value) return _G[str]:format(BreakUpLargeNumbers(floor((961.93469238281 + 0.41220703160998 * value)*5))) end}, }, BONUS_ARMOR = { noBenefit, {text = "STAT_ARMOR_BONUS_ARMOR_BLADED_ARMOR_TOOLTIP"} }, MULTISTRIKE = { {text = "CR_MULTISTRIKE_TOOLTIP"}, }, LIFESTEAL = { {text = "CR_LIFESTEAL_TOOLTIP"}, }, VERSATILITY = { {text = "CR_VERSATILITY_TOOLTIP"}, }, AVOIDANCE = { {text = "CR_AVOIDANCE_TOOLTIP"}, }, SPELLPOWER = { {text = "STAT_SPELLPOWER_TOOLTIP"} }, ATTACK_AP = { {text = "ITEM_MOD_MELEE_ATTACK_POWER_SHORT"} } } }, MAGE = { modifiers = {INTELLECT = "*1.05"}, stats = {INTELLECT = 2} }, [62] = { -- Mage: Arcane basestat = {MASTERY = 550}, modifiers = {MASTERY = "* 1.05"} }, [63] = {-- Mage: Fire basestat = {CRITCHANCE = 15}, modifiers = {CRITCHANCE = "* 1.15"} }, [64] = {-- Mage: Frost basestat = {MULTISTRIKE = 8}, modifiers = {MULTISTRIKE = "* 1.05"} }, --PALADIN = {}, [65] = { -- Paladin: Holy modifiers = {INTELLECT = "* 1.05", CRITCHANCE = "*1.05"}, stats = {INTELLECT = 2, SPIRIT = 2} }, [66] = { -- Paladin: Protection modifiers = {HASTE = "* 1.3", STAMINA = "* 1.15", HASTE = "* 1.3"}, stats = {STRENGTH = 3, BONUS_ARMOR = 2, CRITCHANCE = 2} }, [70] = { -- Paladin: Retribution modifiers = {STRENGTH = "* 1.05", MASTERY = "* 1.05"}, stats = {STRENGTH = 3} }, WARRIOR = { stats = {STRENGTH = 2} }, [71] = { -- Warrior: Arms modifiers = {STRENGTH = "* 1.05", MASTERY = "* 1.05"} }, [72] = { -- Warrior: Fury modifiers = {STRENGTH = "* 1.05", CRITCHANCE = "* 1.05"} }, [73] = { -- Warrior: Protection modifiers = {STAMINA = "* 1.05 * 1.15"}, stats = {BONUS_ARMOR = 2, CRITCHANCE = 2} }, --DRUID = {}, [102] = { -- Druid: Balance modifiers = {INTELLECT = "* 1.05", MASTERY = "* 1.05"}, stats = {INTELLECT = 2} }, [103] = { -- Druid: Feral modifiers = {CRITCHANCE = "* 1.05", AGILITY = "* 1.05"}, stats = {AGILITY = 2} }, [104] = { -- Druid: Guardian modifiers = {STAMINA = "* 1.05 * 1.2", MASTERY = "* 1.05", ARMOR = "* 3.5"}, stats = {AGILITY = 2, BONUS_ARMOR = 2} }, [105] = { -- Druid: Restoration modifiers = {INTELLECT = "* 1.05", HASTE = "* 1.05"}, stats = {INTELLECT = 2, SPIRIT = 2} }, DEATHKNIGHT = { stats = {STRENGTH = 2} }, [250] = { -- Death Knight: Blood modifiers = {STAMINA = "* 1.05", TOTALSTAMINA = "* 1.2", ARMOR = "*1.3", MULTISTRIKE = "* 1.05"}, stats = {BONUS_ARMOR = 2}, basestat = {MULTISTRIKE = 10, HASTE = 10} }, [251] = { -- Death Knight: Frost modifiers = {STRENGTH = "* 1.05", HASTE = "* 1.2"}, basestat = {HASTE = 10} }, [252] = { -- Death Knight: Unholy modifiers = {STRENGTH = "* 1.05", MULTISTRIKE = "* 1.05"}, basestat = {HASTE = 20} }, HUNTER = { modifiers = {AGILITY = "*1.05"}, stats = {AGILITY = 2} }, [253] = { -- Hunter: Beast Mastery modifiers = {MASTERY = "* 1.05"} }, [254] = { -- Hunter: Marksmanship modifiers = {CRITCHANCE = "* 1.05"} }, [255] = { -- Hunter: Survival modifiers = {MULTISTRIKE = "* 1.05", MULTISTRIKEEFFECT = "* 1.2"} }, PRIEST = { modifiers = {INTELLECT = "* 1.05"}, stats = {INTELLECT = 2} }, [256] = { -- Priest: Discipline modifiers = {CRITCHANCE = "* 1.05"}, stats = {SPIRIT = 2} }, [257] = { -- Priest: Holy modifiers = {MULTISTRIKE = "* 1.05"}, stats = {SPIRIT = 2} }, [258] = { -- Priest: Shadow modifiers = {HASTE = "* 1.05"} }, ROGUE = { modifiers = {AGILITY = "*1.05"}, stats = {AGILITY = 2} }, [259] = { -- Rogue: Assassination modifiers = {MASTERY = "* 1.05"} }, [260] = { -- Rogue: Combat modifiers = {HASTE = "* 1.05"}, }, [261] = { -- Rogue: Subtlety modifiers = {TOTALAGILITY = "* 1.15", MULTISTRIKE = "* 1.05"}, }, --SHAMAN = {}, [262] = { -- Shaman: Elemental basestat = {MULTISTRIKE = 20}, modifiers = {MULTISTRIKE = "* 1.05", MULTISTRIKEEFFECT = "* 1.35"}, stats = {INTELLECT = 2, BONUS_ARMOR = 2} }, [263] = { -- Shaman: Enhancement stats = {AGILITY = 2}, modifiers = {HASTE = "* 1.05", AGILITY = "* 1.05"} }, [264] = { -- Shaman: Restoration stats = {INTELLECT = 2, SPIRIT = 2}, modifiers = {INTELLECT = "* 1.05", MASTERY = "* 1.05"} }, WARLOCK = { modifiers = {INTELLECT = "*1.05"}, stats = {INTELLECT = 2} }, [265] = { -- Warlock: Affliction modifiers = {HASTE = "* 1.05"} }, [266] = { -- Warlock: Demonology modifiers = {MASTERY = "* 1.05"} }, [267] = {modifiers = { -- Warlock: Destruction CRITCHANCE = "* 1.15"} }, --MONK = {}, [268] = { -- Monk: Brewmaster modifiers = {ARMOR = "* 1.75", TOTALSTAMINA = "* 1.25", STAMINA = "* 1.05", CRITCHANCE = "* 1.05"}, stats = {AGILITY = 2, BONUS_ARMOR = 2} }, [269] = { -- Monk: Windwalker modifiers = {MULTISTRIKE = "* 1.05", AGILITY = "* 1.05"}, stats = {AGILITY = 2} }, [270] = { -- Monk: Mistweaver modifiers = {MULTISTRIKE = "* 1.05", INTELLECT = "* 1.05"}, stats = {INTELLECT = 2, SPIRIT = 2} }, } local function requestCharInfo(data, channel, source) Preview:SendAddonMessage("charinforeply", Preview:GetPlayerInfo(), "WHISPER", source) end local function charInfoReply(data, channel, source) end local function defaultFormat(str, ...) return str:format(...) end function Preview:GetTooltipForSpec(attrType, class, spec, ...) local tooltips = self.classinfo.__default.stats[attrType] if not tooltips then error("Tried to get tooltip for unknown type!") end local spectooltips = self.classinfo[spec] and self.classinfo[spec].stats and self.classinfo[spec].stats[attrType] local classtooltips = self.classinfo[class] and self.classinfo[class].stats and self.classinfo[class].stats[attrType] local returnString if spectooltips then if type(spectooltips) == "function" then return spectooltips(...) else returnString = tooltips[spectooltips] end elseif classtooltips then if type(classtooltips) == "function" then return classtooltips(...) else returnString = tooltips[classtooltips] end else returnString = tooltips[1] end if type(attrType) == "function" then return attrTywpe(...) end if returnString.func then return returnString.func(returnString.text, ...) else return defaultFormat(_G[returnString.text], ...) end end function Preview:GetBaseStatForSpec(stat, class, spec) for _,v in pairs({class, spec}) do if self.classinfo[v] and self.classinfo[v].basestat and self.classinfo[v].basestat[stat] then return self.classinfo[v].basestat[stat] end end return self.classinfo.__default.basestat[stat] or 0 end function Preview:OnInitialize() BestInSlot.Preview = Preview self:RegisterCommFunction("requestcharinfo", requestCharInfo) self:RegisterCommFunction("charinforeply", charInfoReply) self.slots = CopyTable(self.slots) tinsert(self.slots, 6, "ShirtSlot") tinsert(self.slots, 7, "TabardSlot") for i=1,MAX_CLASSES do local name = select(2, GetClassInfoByID(i)) self.classes[name] = i end local d = date("*t") self.aprilfools = d.day == 1 and d.month == 4 end --[[ function Preview:OnEnable() local unitinfo = self:GetPlayerInfo() unitinfo.spec = self:GetSelected(self.SPECIALIZATION) self:Show(self:GetBestInSlotItems(60001, 2, unitinfo.spec), 2, unitinfo) end ]] local function iconOnEnter(widget) local link = widget:GetUserData("itemlink") local id = widget:GetUserData("id") if link then GameTooltip:SetOwner(widget.frame) GameTooltip:SetAnchorType(id and id <= 8 and "ANCHOR_LEFT" or "ANCHOR_RIGHT") GameTooltip:SetHyperlink(link, Preview.class, Preview.spec) GameTooltip:Show() end end local function iconOnLeave(widget) if GameTooltip:IsShown() then GameTooltip:Hide() end end function Preview:GetClassForSpec(specid) local className = select(7, GetSpecializationInfoByID(specid)) return (self.classes[className] or self.classes[select(3, UnitClass("player"))]), className end function Preview:CreateSlotIcon(id) local slotid, texture = GetInventorySlotInfo(self.slots[id]) local icon = self:QuickCreate("Icon", {SetImage=texture, SetImageSize={iconsize, iconsize}, SetWidth=iconsize, SetHeight=iconsize}) icon:SetUserData("id", id) icon:SetCallback("OnEnter", iconOnEnter) icon:SetCallback("OnLeave", iconOnLeave) self.icons[slotid] = icon return icon end function Preview:GetScanTooltip() if self.scantooltip then return self.scantooltip end if BestInSlotPreviewScanTooltip then self.scantooltip = BestInSlotPreviewScanTooltip return BestInSlotPreviewScanTooltip end local tooltip = CreateFrame("GameTooltip", "BestInSlotPreviewScanTooltip", nil, "GameTooltipTemplate") self.scantooltip = tooltip return tooltip end function Preview:SetCharacter(bislist, difficulty, charname, charspec, charsex, charrace, slots) local playermodel = self.playermodel for i in pairs(bislist) do local item = bislist[i] if type(bislist[i]) == "number" then item = self:GetItem(bislist[i], difficulty) elseif type(bislist[i]) == "table" and bislist[i].item then item = self:GetItem(bislist[i].item, difficulty) end if item then local slotid, slotid2 = slots and slots[i] if not slotid then slotid, slotid2 = self:GetItemSlotID(item.equipSlot, charspec) end if slotid then local icon = self.icons[slotid] local udt = icon:GetUserDataTable() if udt.itemlink and slotid2 then icon = self.icons[slotid2] udt = icon:GetUserDataTable() end icon:SetImage(GetItemIcon(item.itemid)) udt.itemlink = item.link end playermodel:TryOn(item.link) end end end function Preview:Show(bislist, difficulty, charparams, slots) local charname = charparams and charparams.name or UNKNOWN local charrace = charparams and charparams.race or (UnitFactionGroup("player") == "Alliance" and "Human" or "Orc") local charsex = charparams and charparams.sex or 0 local charspec = charparams and charparams.spec or self:GetSelected(self.SPECIALIZATION) self.spec = charspec self.classid, self.classname = self:GetClassForSpec(charspec) if self.previewframe then self:SetCharacter(bislist, difficulty, charparams, charname, charspec, charsex, charrace, slots) return end local frame = AceGUI:Create("Window") frame.frame:SetFrameStrata("DIALOG") frame:SetHeight(400) frame:SetWidth(538) frame:SetTitle("BestInSlot "..PREVIEW) frame:EnableResize(false) frame:SetCallback("OnClose", function() Preview:ClosePreview() end) self.previewframe = frame frame:PauseLayout() local previewPanel = AceGUI:Create("SimpleGroup") previewPanel:SetWidth(338) previewPanel:SetHeight(400) previewPanel:PauseLayout() previewPanel:SetPoint("TOPLEFT", frame.frame, "TOPLEFT", 10, -25) previewPanel:SetPoint("BOTTOMLEFT", frame.frame, "BOTTOMLEFT", 10, 10) frame:AddChild(previewPanel) self.icons = {} for i=1,#self.slots do local icon = self:CreateSlotIcon(i) if i < 17 then local point = i < 9 and "TOPLEFT" or "TOPRIGHT" local yOffset = - (i < 9 and i - 1 or i - 9) * (iconsize + 3) local xOffset = i < 9 and 0 or -10 icon:SetPoint(point, previewPanel.frame, point, xOffset, yOffset) else icon:SetPoint("BOTTOM", previewPanel.frame, "BOTTOM", i == 17 and -iconsize / 2 or iconsize / 2 ,-5) end previewPanel:AddChild(icon) end local panel = AceGUI:Create("SimpleGroup") panel.frame:SetFrameStrata("BACKGROUND") self.oldbackdrop = panel.frame:GetBackdrop() self.panel = panel panel.frame:SetBackdrop({ bgFile = DressUpTexturePath(charrace).."1", tile = false, }) panel:SetPoint("TOPLEFT", self.icons[1].frame, "TOPRIGHT") panel:SetPoint("BOTTOMRIGHT", self.icons[14].frame, "BOTTOMLEFT") previewPanel:AddChild(panel) local playermodel = self:CreatePlayerModel(panel.frame, charrace, charsex) playermodel:SetPoint("BOTTOM", panel.frame) self:SetCharacter(bislist, difficulty, charparams, charname, charspec, charsex, charrace, slots) local statFrame = AceGUI:Create("ScrollFrame") statFrame:SetPoint("TOPLEFT", self.icons[10].frame, "TOPRIGHT", 5, -5) statFrame:SetPoint("BOTTOMRIGHT", frame.frame, -7, 10) frame:AddChild(statFrame) self:FillStatPanel(statFrame, bislist, difficulty, self.classname, charspec) end local function onMouseUp(self, button) if ( button == "RightButton" and self.panning ) then Model_StopPanning(self); elseif ( self.mouseDown ) then self.onMouseUpFunc(self, button); end end local function onMouseDown(self, button) if ( button == "RightButton" and not self.mouseDown ) then Model_StartPanning(self); else Model_OnMouseDown(self, button); end end local function onMouseWheel(self, delta) Model_OnMouseWheel(self, delta); end local function onReleaseGroup(widg) widg.frame:SetScript("OnEnter", nil) --Remove the hooked script widg.frame:SetScript("OnLeave", nil) widg.frame.ace = nil widg.value.label:SetJustifyH("LEFT") --reset justify H widg.value = nil widg.descr = nil end local function onEnterStatGroup(frame) GameTooltip:ClearLines() GameTooltip:SetOwner(frame) GameTooltip:SetAnchorType("ANCHOR_RIGHT") GameTooltip:AddLine(frame.ace.tooltip, nil, nil, nil, true) GameTooltip:AddLine(frame.ace.tooltip2, nil, nil, nil, true) GameTooltip:Show() GameTooltip:SetWidth(250) end local function onLeaveStatGroup(frame) GameTooltip:Hide() end local function errorHandler(error) Preview.console:AddError("Error caught", error) end function Preview:ApplyStatModifier(statName, class, spec, value) local modifiers = {self.classinfo[spec] and self.classinfo[spec].modifiers, self.classinfo[class] and self.classinfo[class].modifiers} if #modifiers == 0 then return value end for _, modifier in pairs(modifiers) do if modifier[statName] then local f, err = loadstring("return "..value..modifier[statName]) if err then self.console:AddError("Failed to add modifier.", statName, class, spec, value, err) else local success, result = xpcall(f, errorHandler) if success then value = result else self.console:AddError("Failed to add modifier.") end end end end return value end function Preview:FillStatPanel(panel, bislist, difficulty, class, spec) panel:SetLayout("Flow") self:QuickCreate("Heading", {SetText=STAT_CATEGORY_ATTRIBUTES, SetFullWidth=true}, panel) local bonusStats = self:GetTotalStats(bislist, difficulty, class, spec) for i=1,#self.attributes do local locName = self.attributes[i] local attrId = _G["LE_UNIT_STAT_"..locName] local attrName = _G["SPELL_STAT"..attrId.."_NAME"] local group = self:QuickCreate("SimpleGroup", {SetWidth=200, PauseLayout=true}, panel) local stat, effectiveStat, posBuff, negBuff = UnitStat("player", attrId) local baseStat = stat - posBuff + negBuff local bonusStat = bonusStats[attrName] or 0 bonusStat = floor(self:ApplyStatModifier(locName, class, spec, bonusStat)) local totalStat = floor(self:ApplyStatModifier("TOTAL"..locName, class, spec, baseStat + bonusStat)) group.frame:SetScript("OnEnter", onEnterStatGroup) group.frame:SetScript("OnLeave", onLeaveStatGroup) group:SetCallback("OnRelease", onReleaseGroup) group.frame.ace = group group.descr = self:QuickCreate("Label", {SetWidth=150, SetText=attrName}, group, "TOPLEFT") group.value = self:QuickCreate("Label", {SetWidth=50, SetText=BreakUpLargeNumbers(totalStat)}, group, "TOPRIGHT") if bonusStat > 0 then group.value:SetColor(GREEN_FONT_COLOR.r, GREEN_FONT_COLOR.g, GREEN_FONT_COLOR.b) end group.value.label:SetJustifyH("RIGHT") group.tooltip, group.tooltip2 = self:GetTooltipForStat(attrId, attrName, locName, baseStat, bonusStat, totalStat, class, spec) group:SetHeight(max(group.value.frame:GetHeight(), group.descr.frame:GetHeight())) end self:QuickCreate("Heading", {SetText=STAT_CATEGORY_ENHANCEMENTS, SetFullWidth=true}, panel) for i=1,#self.enhancements do local group = self:QuickCreate("SimpleGroup", {SetWidth=200, PauseLayout=true}, panel) local locName = self.enhancements[i] local enhanceName = _G["STAT_"..locName] if not enhanceName then if locName == "CRITCHANCE" then enhanceName = STAT_CRITICAL_STRIKE elseif locName == "SPIRIT" then enhanceName = SPELL_STAT5_NAME elseif locName == "ATTACK_AP" then enhanceName = ATTACK_POWER_TOOLTIP end end local baseStat; if locName == "BONUS_ARMOR" then baseStat = self:ApplyStatModifier("ARMOR", class, spec, bonusStats.ARMOR or 0) else baseStat = self:GetBaseStatForSpec(locName, class, spec) end local bonusStat = bonusStats[enhanceName] or 0 bonusStat = floor(self:ApplyStatModifier(locName, class, spec, bonusStat)) local totalStat = baseStat + bonusStat group.frame:SetScript("OnEnter", onEnterStatGroup) group.frame:SetScript("OnLeave", onLeaveStatGroup) group:SetCallback("OnRelease", onReleaseGroup) group.frame.ace = group group.descr = self:QuickCreate("Label", {SetWidth=150, SetText=enhanceName}, group, "TOPLEFT") group.value = self:QuickCreate("Label", {SetWidth=50}, group, "TOPRIGHT") group.value.label:SetJustifyH("RIGHT") group:SetHeight(max(group.value.frame:GetHeight(), group.descr.frame:GetHeight())) group.tooltip, group.tooltip2 = self:GetTooltipForEnhancement(enhanceName, locName, baseStat, bonusStat, class, spec, group.value) end local label = self:QuickCreate("Label", {SetFullWidth=true, SetText=self.colorHighlight.."BETA NOTICE: Stats are in beta and calculation might differ slightly. Please report huge differences."}, panel) end function Preview:GetTooltipForEnhancement(name, locName, baseStat, bonusStat, class, spec, valueWidget) local header local content if locName == "SPIRIT" then header = self:GetTooltipHeader(name, baseStat, bonusStat) content = self:GetTooltipForSpec(locName, class, spec, baseStat + bonusStat) valueWidget:SetText(BreakUpLargeNumbers(baseStat + bonusStat)) elseif locName == "BONUS_ARMOR" then header = self:GetTooltipHeader(name, 0, bonusStat) --use 0 here, because baseStat contains the armor value of gear content = self:GetTooltipForSpec(locName, class, spec, PaperDollFrame_GetArmorReduction(baseStat + bonusStat, 100), bonusStat) valueWidget:SetText(BreakUpLargeNumbers(bonusStat)) elseif locName == "CRITCHANCE" then local effectiveStat = 0.009090908809347 * bonusStat header = self:GetTooltipHeader(name, baseStat, effectiveStat, true) content = self:GetTooltipForSpec(locName, class, spec, bonusStat, effectiveStat, effectiveStat) valueWidget:SetText(("%.2F%%"):format(baseStat + effectiveStat)) elseif locName == "HASTE" then local effectiveStat = bonusStat / 90 header = self:GetTooltipHeader(name, baseStat, effectiveStat, true) content = self:GetTooltipForSpec(locName, class, spec, bonusStat, effectiveStat) valueWidget:SetText(("%.2F%%"):format(baseStat + effectiveStat)) elseif locName == "MASTERY" then header = self:GetTooltipHeader(name, baseStat, bonusStat) content = self:GetTooltipForSpec(locName, class, spec, baseStat + bonusStat) valueWidget:SetText(BreakUpLargeNumbers(baseStat + bonusStat)) elseif locName == "MULTISTRIKE" then local effectiveStat = bonusStat / 66 local multistrikeEffect = self:ApplyStatModifier("MULTISTRIKEEFFECT", class, spec, 30) local totalEffect = effectiveStat + baseStat header = self:GetTooltipHeader(name, baseStat, effectiveStat, true) content = self:GetTooltipForSpec(locName, class, spec, totalEffect, multistrikeEffect, BreakUpLargeNumbers(bonusStat), effectiveStat) valueWidget:SetText(("%.2F%%"):format(totalEffect)) elseif locName == "VERSATILITY" then local effectiveStat = bonusStat / 130 local totalStat = baseStat + effectiveStat header = self:GetTooltipHeader(name, baseStat, effectiveStat, true) content = self:GetTooltipForSpec(locName, class, spec, totalStat, totalStat / 2, BreakUpLargeNumbers(bonusStat), effectiveStat, effectiveStat / 2) valueWidget:SetText(("%.2F%%"):format(totalStat)) elseif locName == "LIFESTEAL" or locName == "AVOIDANCE" then header = self:GetTooltipHeader(name, 0, 0) content = self:GetTooltipForSpec(locName, class, spec, 0, 0, 0) valueWidget:SetText(("%.2F%%"):format(0)) elseif locName == "ATTACK_AP" or locName == "SPELLPOWER" then header = self:GetTooltipHeader(name, bonusStat, 0) content = self:GetTooltipForSpec(locName, class, spec, bonusStat) valueWidget:SetText(BreakUpLargeNumbers(bonusStat)) end return header or "NYI", content or "NYI" end local function BreakUpLargeNumbersWithPercentage(value) return BreakUpLargeNumbers(value) .. "%" end function Preview:GetTooltipHeader(name, baseStat, bonusStat, isPercentage, totalStat) local tooltip = HIGHLIGHT_FONT_COLOR_CODE..PAPERDOLLFRAME_TOOLTIP_FORMAT:format(name).." " totalStat = totalStat or baseStat + bonusStat local formatFunc = isPercentage and BreakUpLargeNumbersWithPercentage or BreakUpLargeNumbers bonusStat = formatFunc(bonusStat) if bonusStat == "0" then tooltip = tooltip .. formatFunc(baseStat) .. FONT_COLOR_CODE_CLOSE elseif isPercentage then tooltip = tooltip .. formatFunc(totalStat) .. FONT_COLOR_CODE_CLOSE else tooltip = tooltip .. formatFunc(totalStat) .. " ( " .. (baseStat > 0 and formatFunc(baseStat) or "") .. FONT_COLOR_CODE_CLOSE .. GREEN_FONT_COLOR_CODE .. "+" .. bonusStat .. FONT_COLOR_CODE_CLOSE .. HIGHLIGHT_FONT_COLOR_CODE .. ")" end return tooltip end function Preview:GetTooltipForStat(statId, statName, locName, baseStat, bonusStat, totalStat, class, spec) return self:GetTooltipHeader(statName, baseStat, bonusStat, false, totalStat), self:GetTooltipForSpec(locName, class, spec, totalStat) end local function isColorDisabledColor(r,g,b) r = (floor(r * 10)) g = (floor(g * 10)) b = (floor(b * 10)) return abs(r - GRAY_FONT_COLOR.r * 10) <= 5 and abs(g - GRAY_FONT_COLOR.g * 10) <= 5 and abs(b - GRAY_FONT_COLOR.b * 10) <= 1 end local searchPattern1 = "+(%d+) (.+)" local searchPattern2 = "+(%d+),(%d%d%d) (.+)" local searchArmorPattern = ARMOR_TEMPLATE:format("(%d+)") local function readLine(line, arr) local text = line:GetText() if not text then return end if text:find(DISABLED_FONT_COLOR_CODE) then return end local thousands, amount, statName = text:match(searchPattern2) if not thousands then amount, statName = text:match(searchPattern1) if not amount then amount = text:match(searchArmorPattern) if not amount then return else statName = "ARMOR" end end else amount = amount + thousands * 1000 end local r,g,b = line:GetTextColor() if isColorDisabledColor(r,g,b) then return end arr[statName] = (arr[statName] or 0) + amount end function Preview:GetTotalStats(bislist, difficulty, class, spec) local totalStats = {} local tooltip = self:GetScanTooltip() --[[Normal functionality for i in pairs(bislist) do local item = self:GetItem(bislist[i].item, difficulty) if item then tooltip:SetOwner(UIParent, "ANCHOR_NONE") tooltip:ClearLines() tooltip:SetHyperlink(item.itemstr, class, spec) tooltip:Show() local line = _G["BestInSlotPreviewScanTooltipTextLeft1"] local i = 1 while line do readLine(line, totalStats) i = i + 1 line = _G["BestInSlotPreviewScanTooltipTextLeft"..i] end tooltip:Hide() end end --]] --DEBUG WITH CURRENT GEAR for j=1,19 do local link = GetInventoryItemLink("player", j) if link then tooltip:SetOwner(UIParent, "ANCHOR_NONE") tooltip:ClearLines() tooltip:SetHyperlink(link, class, spec) tooltip:Show() local line = _G["BestInSlotPreviewScanTooltipTextLeft1"] local i = 1 while line do readLine(line, totalStats) i = i + 1 line = _G["BestInSlotPreviewScanTooltipTextLeft"..i] end tooltip:Hide() end end--]] return totalStats end function Preview:CreatePlayerModel(parent, race, sex) local playermodel = self.playermodel if not playermodel then playermodel = CreateFrame("DressUpModel", "BestInSlotPlayerModel", UIParent) playermodel:SetHeight(self.panel.frame:GetHeight()) playermodel:SetFrameStrata("FULLSCREEN") playermodel:SetWidth(244) playermodel:SetScript("OnLoad", Model_OnLoad) playermodel:SetScript("OnEvent", Model_OnEvent) playermodel:SetScript("OnUpdate", Model_OnUpdate) playermodel:SetScript("OnMouseUp", onMouseUp) playermodel:SetScript("OnMouseDown", onMouseDown) playermodel:SetScript("OnMouseWheel", onMouseWheel) Model_OnLoad(playermodel) self.playermodel = playermodel end playermodel:Show() playermodel:SetUnit("PLAYER") if self.aprilfools then playermodel:SetCreature(1211) else playermodel:SetCustomRace(self.raceids[race], sex) end playermodel:Undress() return playermodel end function Preview:ClosePreview() local frame = self.previewframe self.panel.frame:SetBackdrop(self.oldbackdrop) frame:Release() self.previewframe = nil self.panel = nil self.oldbackdrop = nil self.icons = nil self.spec = nil self.class = nil self.playermodel:Hide() end
Thread.jump("lib/thread/invalid.lua") finished = true
return function() local evaluate = require(script.Parent) it("should return 10", function() expect(evaluate("10")).to.equal(10) end) it("should return -10", function() expect(evaluate("-10")).to.equal(-10) end) it("should return +10", function() expect(evaluate("+10")).to.equal(10) end) it("should add 1 to 2", function() expect(evaluate("1 + 2")).to.equal(1 + 2) end) it("should subtract 1 from 3", function() expect(evaluate("3 - 1")).to.equal(3 - 1) end) it("should multiply 2 by 3", function() expect(evaluate("2 * 3")).to.equal(2 * 3) end) it("should divide 9 by 2", function() expect(evaluate("9 / 2")).to.equal(9 / 2) end) it("should take 3 to the power of 2", function() expect(evaluate("3 ^ 2")).to.equal(3 ^ 2) end) it("should take 5 modulo 2", function() expect(evaluate("5 % 2")).to.equal(5 % 2) end) it("should evaluate inner expression", function() expect(evaluate("(((((5 + 4 * 2)))))")).to.equal(5 + 4 * 2) end) it("should evaluate function", function() expect(evaluate("abs(-4)")).to.equal(4) end) it("should evaluate function with multiple arguments", function() expect(evaluate("min(2, 4, 1, 5, 3, 10)")).to.equal(math.min(2, 4, 1, 5, 3, 10)) end) it("should solve composite functions", function() expect(evaluate("pow(4, max(5, clamp(10, 1, 3)))")).to.equal(math.pow(4, math.max(5, math.clamp(10, 1, 3)))) end) it("should evaluate constant", function() expect(evaluate("pi")).to.equal(math.pi) end) it("should evaluate variable", function() expect(evaluate("foo", { foo = 5 })).to.equal(5) end) it("should use variable instead of constant", function() expect(evaluate("pi", { pi = 6 })).to.equal(6) end) it("should evaluate correctly", function() expect(evaluate("5 + ((1 + 2) * 4) - 3")).to.equal(5 + ((1 + 2) * 4) - 3) expect(evaluate("3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3")).to.equal(3 + 4 * 2 / (1 - 5) ^ 2 ^ 3) expect(evaluate("10 + 4 ^ 3 * 2 % 4 / ( 1 - 5 ) ^ 2 ^ 3")).to.equal(10 + 4 ^ 3 * 2 % 4 / (1 - 5) ^ 2 ^ 3) expect(evaluate("4 + 4.5 ^ 3 * 2 ^ 2.2 ^ 3")).to.equal(4 + 4.5 ^ 3 * 2 ^ 2.2 ^ 3) expect(evaluate("sqrt(4) + 3")).to.equal(math.sqrt(4) + 3) expect(evaluate("1+sqrt(4)")).to.equal(1 + math.sqrt(4)) expect(evaluate("sin(0.5) + sqrt(4 + 5 * 3)")).to.equal(math.sin(0.5) + math.sqrt(4 + 5 * 3)) expect(evaluate("sin(0.5) + var", { var = 2.35 })).to.equal(math.sin(0.5) + 2.35) expect(evaluate("var1*var2", { var1 = 3, var2 = 5 })).to.equal(3 * 5) expect(evaluate("(3 * (foo+2)) / 2", { foo = 3 })).to.equal((3 * (3 + 2)) / 2) end) it("should throw when input is empty", function() expect(function() evaluate("") end).to.throw("Input empty") end) it("should throw when unary has no value", function() expect(function() evaluate("-") end).to.throw("Expected value after unary") end) it("should throw when parentheses are empty", function() expect(function() evaluate("()") end).to.throw("Expected value within parentheses") end) it("should throw when binary operation has no right hand side", function() expect(function() evaluate("1 + ") end).to.throw("Expected value after +") end) it("should throw when variable does not exist", function() expect(function() evaluate("foo") end).to.throw("'foo' is not defined") end) it("should throw when function does not exist", function() expect(function() evaluate("foo()") end).to.throw("'foo' is not defined") end) it("should throw when there is no closing parenthesis", function() expect(function() evaluate("(5") end).to.throw("Expected Close Parenthesis") end) it("should throw when function has no close parenthesis", function() expect(function() evaluate("rad(5") end).to.throw("Expected Close Parenthesis") end) it("should throw when it encounters an unknown sequence", function() expect(function() evaluate("1+2&") end).to.throw("Unexpected sequence: &") end) end
entities.require("entity") class "structure" ("entity") function structure:structure() entity.entity(self) if (_CLIENT) then local sprite = sprite("images.obj.structures") sprite:setFilter("nearest", "nearest") self:setSprite(sprite) end end function structure:use(activator, value) -- return true so derived classes can check if this handles the call if (construction.check(self, activator)) then return true end end function structure:spawn() entity.spawn( self ) local tileSize = game.tileSize local min = vector() local max = vector( tileSize, -tileSize ) self:initializePhysics() self:setCollisionBounds( min, max ) end
cgilua.htmlheader() cgilua.put"Oi!" --io.write"something\n" cgilua.errorlog ("eca", "emerg")
local Vector = require "vector" local physics = {} local g = 9.81 local pi = 3.14159265359 function math.clamp(low, n, high) return math.min(math.max(n, low), high) end function physics.calculatePhysics(objects, step, width, height) for i, object in ipairs(objects) do -- check horizontal bounds if object.position.x + object.width >= width or object.position.x <= 0 then -- bounce from the sides object.velocity.x = -object.velocity.x end -- check vertical bounds if object.position.y + object.height >= height and object.acceleration.y >= 0 then -- bounce from the bottom object.acceleration.y = -(object.acceleration.y * 0.75) object.velocity.y = -object.velocity.y end -- usual stuff local scale = step / 100 --????? why not 1000? t: author object.acceleration.y = object.acceleration.y + scale * g object.velocity.y = scale * (object.velocity.y + object.acceleration.y) object.position.y = object.position.y + object.velocity.y object.position.x = object.position.x + object.velocity.x -- keep the objects from going out of screen bounds object.position.x = math.clamp(0, object.position.x, width - object.width) object.position.y = math.clamp(0, object.position.y, height - object.height) for j, otherObject in ipairs(objects) do if i == j then goto continue end -- check for balls touching balls here if physics.colliding(object, otherObject) then physics.resolveCollision(object, otherObject) end end ::continue:: end end function physics.colliding(object, otherObject) local xd = object.position.x - otherObject.position.x local yd = object.position.y - otherObject.position.y local radiuses = object.radius + otherObject.radius local radiusesSquared = radiuses * radiuses local distance = (xd * xd) + (yd * yd) return distance <= radiusesSquared end function physics.resolveCollision(object, otherObject) -- from here: http://stackoverflow.com/questions/345838/ball-to-ball-collision-detection-and-handling local collision = object.getCenterPosition() - otherObject.getCenterPosition() local distance = collision:len() local mtdX = collision.x * (((object.radius + otherObject.radius)-distance)/distance) local mtdY = collision.y * (((object.radius + otherObject.radius)-distance)/distance) -- move the objects away from each other object.position.x = object.position.x + mtdX object.position.y = object.position.y + mtdY otherObject.position.x = otherObject.position.x - mtdX otherObject.position.y = otherObject.position.y - mtdY if distance == 0.0 then return end if distance < 128 then -- resolve objects being inside each other? distance = 135 end collision.x = collision.x / distance collision.y = collision.y / distance local aci = object.velocity:dot(collision) local bci = otherObject.velocity:dot(collision) local acf = bci local bcf = aci local firstCollision = collision + Vector.zero local secondCollision = collision + Vector.zero firstCollision.x = firstCollision.x * (acf - aci) firstCollision.y = firstCollision.y * (acf - aci) secondCollision.x = secondCollision.x * (bcf - bci) secondCollision.y = secondCollision.y * (bcf - bci) object.velocity = object.velocity + firstCollision otherObject.velocity = otherObject.velocity + secondCollision end return physics
local me = peripheral.wrap("top") local function getCraftable() local gold = me.getItemDetail({id="minecraft:gold_ingot"},false) if gold == nil then return 0 else return math.floor(gold.qty / 3) end end while true do local cpus = me.getCraftingCPUs() local free = 0 for i=1, #cpus do if not cpus[i].busy then free = free + 1 end end local craftable = getCraftable() local i = 1 while i <= craftable and i<=free do i = i + 1 me.requestCrafting({id="Forestry:chipsets", dmg=3}, 1) end sleep(0.5) end
return { sharp = { 18, 9, 6 } }
#!/usr/bin/env lua package.path = package.path..";../?.lua" local glfw = require("moonglfw") local gl = require("moongl") local glmath = require("moonglmath") local new_objmesh = require("common.objmesh") local vec3, vec4 = glmath.vec3, glmath.vec4 local mat3, mat4 = glmath.mat3, glmath.mat4 local pi, rad = math.pi, math.rad local sin, cos = math.sin, math.cos local exp, log = math.exp, math.log local fmt = string.format local TITLE = "Chapter 6 - Gamma correction" local W, H = 800, 600 -- GLFW/GL initializations glfw.version_hint(4, 6, 'core') glfw.window_hint('opengl forward compat', true) local window = glfw.create_window(W, H, TITLE .." (on)") glfw.make_context_current(window) gl.init() local angle, speed = pi/2, pi/8 -- rad, rad/s local animate = false local gamma_correction = true glfw.set_key_callback(window, function(window, key, scancode, action) if key == 'escape' and action == 'press' then glfw.set_window_should_close(window, true) elseif key == 'space' and action == 'press' then animate = not animate elseif key == 'g' and action == 'press' then gamma_correction = not gamma_correction glfw.set_window_title(window, TITLE ..(gamma_correction and " (on)" or " (off)")) end end) local projection local function resize(window, w, h) W, H = w, h gl.viewport(0, 0, w, h) local c = 2.5 projection = glmath.ortho(-0.4*c, 0.4*c, -0.3*c, 0.3*c, 0.1, 100.0) end glfw.set_window_size_callback(window, resize) -- Create the shader program local prog, vsh, fsh = gl.make_program('vertex', "shaders/gamma.vert", 'fragment', "shaders/gamma.frag") gl.delete_shaders(vsh, fsh) gl.use_program(prog) -- Get the locations of the uniform variables local uniforms = { "Gamma", "Light.Intensity", "Light.Position", "Material.Kd", "Material.Ks", "Material.Ka", "Material.Shininess", "ModelViewMatrix", "NormalMatrix", "MVP", } local loc = {} for _,name in ipairs(uniforms) do loc[name] = gl.get_uniform_location(prog, name) end -- Initialize the uniform variables resize(window, W, H) -- creates projection local function set_matrices(model, view, projection) local mv = view * model local normal_mv = mat3(mv):inv():transpose() gl.uniform_matrix4f(loc["ModelViewMatrix"], true, mv) gl.uniform_matrix3f(loc["NormalMatrix"], true, normal_mv) gl.uniform_matrix4f(loc["MVP"], true, projection * mv) end local function set_material(kd, ks, ka, shininess) gl.uniformf(loc["Material.Kd"], kd) gl.uniformf(loc["Material.Ks"], ks) gl.uniformf(loc["Material.Ka"], ka) gl.uniformf(loc["Material.Shininess"], shininess) end set_material(vec3(1, 1, 1), vec3(0, 0, 0), vec3(0, 0, 0), 100.0) gl.uniformf(loc["Light.Intensity"], 1.0, 1.0, 1.0) -- Generate the meshes local ogre = new_objmesh("../media/bs_ears.obj") -- Event loop ----------------------------------------------------------------- print("Press space to toggle animation on/off") print("Press G to toggle gamma correction on/off") local t0 = glfw.now() local model = mat4() gl.clear_color(.5, .5, .5, 1) gl.enable('depth test') while not glfw.window_should_close(window) do glfw.poll_events() -- Update local t = glfw.now() local dt = t - t0 t0 = t if animate then angle = angle + speed*dt if angle >= 2*pi then angle = angle - 2*pi end end gl.uniformf(loc["Gamma"], gamma_correction and 2.2 or 0.0) -- Render ----------------------------------------------- gl.clear('color', 'depth') local view = glmath.look_at(vec3(3.0*cos(angle),0.0,3.0*sin(angle)), vec3(0,0,0), vec3(0,1,0)) gl.uniformf(loc["Light.Position"], view*vec4(10.0,0.0,0.0,1.0)) set_matrices(model, view, projection) ogre:render() gl.finish() glfw.swap_buffers(window) end
------------------------------------------------------------------------------ -- kong-plugin-soap2rest 1.0.2-1 ------------------------------------------------------------------------------ -- Copyright 2021 adesso SE -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ------------------------------------------------------------------------------ -- Author: Daniel Kraft <daniel.kraft@adesso.de> ------------------------------------------------------------------------------ local lyaml = require "lyaml" local utils = require "kong.plugins.soap2rest.utils" --local inspect = require "inspect" local _M = {} -- Builds the REST request path -- @param plugin_conf Plugin configuration -- @param RequestAction SOAP OperationId -- @retrun 1. HTTP-Action -- 2. REST-Request path local function getRequestPath(plugin_conf, RequestAction) local action, RequestPath= "", "" for word in string.gmatch(RequestAction, "%u%l*") do word = string.lower(word) if word == "get" or word == "post" or word == "delete" or word == "put" then action = word else RequestPath = RequestPath..word.."/" end end RequestPath = string.sub(RequestPath, 1, -2) if plugin_conf.operation_mapping ~= nil and plugin_conf.operation_mapping[RequestAction] ~= nil then RequestPath = plugin_conf.operation_mapping[RequestAction] end return action, plugin_conf.rest_base_path..RequestPath end -- Identifying the content type of the request and response of a REST operation -- @param operationName OperationId -- @param operation Excerpt from the OpenAPI -- @retrun 1. Content-Type of the request -- 2. Content-Type of the response local function parseOperation(operationName, operation) local request, response = {type = "application/json"}, {type = "application/json"} if operation.requestBody ~= nil then kong.log.debug("Parsing body of the operation: "..operationName) -- Identification of the content type of the request if operation["x-contentType"] ~= nil then kong.log.debug("Found x-contenttype") request.type = operation["x-contentType"] else request.type = next(operation.requestBody.content) kong.log.debug("Use plain content: "..request.type) end -- Identification of the encoding if it is a file if string.find(request.type, "multipart/") ~= nil then kong.log.debug("Found Multipart: "..request.type) local encoding = operation.requestBody.content[request.type].encoding request["encoding"] = { file = encoding.datei.contentType, meta = encoding.metadaten.contentType } kong.log.debug("Encoding: file = "..encoding.datei.contentType..", meta = "..encoding.metadaten.contentType) end end kong.log.debug("Request Type: "..request.type) -- Identification of the content type of the response if (operation.responses ~= nil and operation.responses["200"] ~= nil) then response.type = next(operation.responses["200"].content) elseif (operation.responses ~= nil and operation.responses[200] ~= nil) then response.type = next(operation.responses[200].content) end kong.log.debug("Response Type: "..response.type) return request, response end -- Analysing the OpenAPI file -- @param plugin_conf Plugin configuration function _M.parse(plugin_conf) -- Reading out the OpenAPI file local status, yaml_content = pcall(utils.read_file, plugin_conf.openapi_yaml_path) if not status then kong.log.err("Unable to read OpenAPI file '"..plugin_conf.openapi_yaml_path.."' \n\t", yaml_content) return end -- Converting the OpenAPI file into a Lua table local status, openapi_table = pcall(lyaml.load, yaml_content) if not status then kong.log.err("Unable to parse OpenAPI yaml\n\t", openapi_table) return end -- Completing the cached plugin configuration for requestAction, operation in pairs(plugin_conf.operations) do local action, path = getRequestPath(plugin_conf, requestAction) for key, value in pairs(openapi_table.paths) do kong.log.debug("API Path: "..key) if string.find(path, key) then local status, request, response = pcall(parseOperation, action, value[action]) if status then operation["rest"] = { action = action, path = path, request = request, response = response } else kong.log.debug("Error While Parsing Method: "..tostring(request)) operation["rest"] = { action = action, path = path } end break end end end end return _M
local L = select(2, ...).L('esES') L['ALT key'] = ALT_KEY L['ALT + CTRL key'] = ALT_KEY_TEXT .. ' + ' .. CTRL_KEY L['ALT + SHIFT key'] = ALT_KEY_TEXT .. ' + ' .. SHIFT_KEY L['You can\'t do that while in combat'] = ERR_NOT_IN_COMBAT -- config -- L['Modified to use %s'] -- MISSING! %s = "Molinari" -- L['Item Blocklist'] = '' -- MISSING! -- L['Block Item'] = '' -- MISSING! -- L['Items in this list will not be processed.'] = '' -- MISSING! -- L['Block a new item by ID'] = '' -- MISSING!
-- Block users from switching to other skins function FadeVariantMixin:SetVariant() end
--- -- @module factory local types = require("lualife.types") local PlacedField = require("lualife.models.placedfield") local FieldSettings = require("biohazardcore.models.fieldsettings") local random = require("lualife.random") local factory = {} --- -- @tparam FieldSettings settings -- @treturn lualife.models.PlacedField function factory.create_field(settings) assert(types.is_instance(settings, FieldSettings)) local field_sample = PlacedField:new(settings.size, settings.initial_offset) return random.generate_with_limits( field_sample, settings.filling, settings.minimal_count, settings.maximal_count ) end return factory
stormtrooper_common = { description = "", minimumLevel = 0, maximumLevel = 0, lootItems = { {itemTemplate = "painting_bw_stormtrooper", weight = 2500000}, {itemTemplate = "painting_han_wanted", weight = 2500000}, {itemTemplate = "painting_leia_wanted", weight = 2500000}, {itemTemplate = "painting_luke_wanted", weight = 2500000} } } addLootGroupTemplate("stormtrooper_common", stormtrooper_common)
--[[ The MIT License (MIT) Copyright (c) 2015 Xaymar 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. --]] --! This file defines the Seeker player class. -- A seeker is someone who is looking for the hiders, using weapons or other -- means of detecting idiots. Also someone who looks like a diaper baby. -- Weapons and Ammo are granted upon spawn and have to be used sparingly or -- they'll be stuck with the crowbar. Bad seeker, bad. -- Gain health upon killing a hider, lose health when attacking non-hiders. -- Death upon health reaching 0. DEFINE_BASECLASS( "Default" ) local CLASS = {} CLASS.DisplayName = "Seeker" CLASS.CanUseFlashlight = true -- Can we use the flashlight CLASS.MaxHealth = 100 CLASS.StartHealth = 100 CLASS.StartArmor = 0 CLASS.DropWeaponOnDie = true -- ------------------------------------------------------------------------- -- --! Server-Side -- ------------------------------------------------------------------------- -- -- Spawn function CLASS:Spawn() if (GAMEMODE.Config:DebugLog()) then print("Prop Hunt: Seeker '"..self.Player:GetName().."' (SteamID: "..self.Player:SteamID()..") spawned.") end BaseClass.Spawn(self) -- Settings self.Player:SetMaxHealth(GAMEMODE.Config.Seeker:HealthMax()) self.Player:SetHealth(GAMEMODE.Config.Seeker:Health()) self.Player:SetRenderMode(RENDERMODE_NORMAL) self.Player:SetColor(Color(255,255,255,255)) -- Speed and Jump Power self.Player:SetWalkSpeed(GAMEMODE.Config.Seeker:WalkSpeed()) if (GAMEMODE.Config.Seeker:Sprint()) then self.Player:SetRunSpeed(GAMEMODE.Config.Seeker:SprintSpeed()) else self.Player:SetRunSpeed(GAMEMODE.Config.Seeker:WalkSpeed()) end self.Player:SetJumpPower(GAMEMODE.Config.Seeker:JumpPower()) -- Hull & View Offset GAMEMODE:PlayerHullFromEntity(self.Player, nil) GAMEMODE:PlayerSetViewOffset(self.Player, Vector(0,0,64), Vector(0,0,32)) end function CLASS:Loadout() -- Give the weapons the admin told us to. local weapons = GAMEMODE.Config.Seeker:Weapons() for i,weapon in ipairs(weapons) do self.Player:Give(weapon) end -- Give the ammo the admin told us to. local ammos = GAMEMODE.Config.Seeker:Ammo() for i,ammo in ipairs(ammos) do local typeCount = string.Split(ammo, ":") self.Player:GiveAmmo(tonumber(typeCount[2]), typeCount[1], true) end -- Default weapon stuff local cl_defaultweapon = self.Player:GetInfo("cl_defaultweapon") if self.Player:HasWeapon(cl_defaultweapon) then self.Player:SelectWeapon(cl_defaultweapon) end end -- Damage function CLASS:ShouldTakeDamage(attacker) if (IsValid(attacker)) then if (attacker:IsPlayer()) then if (attacker:Team() == self.Player:Team()) then local ffmode = GetConVarNumber("mp_friendlyfire") if (ffmode == 0) then -- Not Allowed return false end end end end return true end function CLASS:Damage(victim, attacker, healthRemaining, damageDealt) if ((victim != attacker) && victim:IsPlayer() && attacker:IsPlayer() && (attacker:Team() == victim:Team())) then if (GAMEMODE.Config:DebugLog()) then print("Prop Hunt: Seeker '"..attacker:GetName().."' (SteamID: "..attacker:SteamID()..") damaged seeker '"..victim:GetName().."' (SteamID: "..victim:SteamID()..") with "..damageDealt.." damage.") end end end function CLASS:Hurt(victim, attacker, healthRemaining, damageTaken) if ((victim != attacker) && victim:IsPlayer() && attacker:IsPlayer() && (attacker:Team() == victim:Team())) then if (GAMEMODE.Config:DebugLog()) then print("Prop Hunt: Seeker '"..victim:GetName().."' (SteamID: "..victim:SteamID()..") was hurt by seeker '"..attacker:GetName().."' (SteamID: "..attacker:SteamID()..") with "..damageTaken.." damage.") end if (GetConVarNumber("mp_friendlyfire") == 2) then victim:SetHealth(healthRemaining + damageTaken) attacker:TakeDamage(damageTaken, attacker, attacker) print("Prop Hunt: Seeker '"..victim:GetName().."' (SteamID: "..victim:SteamID()..") reflected "..damageTaken.." to seeker '"..attacker:GetName().."' (SteamID: "..attacker:SteamID()..").") end end end function CLASS:DamageEntity(ent, att, dmg) if (GAMEMODE.Config:DebugLog()) then print("Prop Hunt: Seeker '"..self.Player:GetName().."' (SteamID: "..self.Player:SteamID()..") damaged entity "..ent:GetClass()..".") end if (GAMEMODE:GetRoundState() != GAMEMODE.States.Seek) then return end if (!IsValid(ent) || !IsValid(att)) then return end if (att == ent) then return end -- Only take damage during this phase. if IsValid(ent) && (!(ent:IsPlayer())) then if (ent:GetClass() == "ph_prop") then ent:GetOwner():TakeDamageInfo(dmg) self.Player.Data.RandomWeight = self.Player.Data.RandomWeight - 1 elseif (ent:GetClass() == "func_breakable") then elseif (ent:GetClass() == "prop_ragdoll") then else att:TakeDamage(GAMEMODE.Config.Seeker:HealthPenalty(), ent, ent) end end end -- Death function CLASS:DoDeath(attacker, dmginfo) BaseClass.DoDeath(self, attacker, dmginfo) if GAMEMODE.Config:DebugLog() then if (IsValid(attacker) && attacker:IsPlayer() && attacker != self.Player) then print("Prop Hunt: Seeker '"..self.Player:GetName().."' (SteamID: "..self.Player:SteamID()..") killed by '"..attacker:GetName().."' (SteamID: "..attacker:SteamID()..").") end end if SERVER then self.Player:SetShouldServerRagdoll(true) --self.Player:CreateRagdoll() end end function CLASS:PostDeath() if (GAMEMODE.Config:DebugLog()) then print("Prop Hunt: Seeker '"..self.Player:GetName().."' (SteamID: "..self.Player:SteamID()..") died.") end BaseClass.PostDeath(self, inflictor, attacker) self.Player:UnLock() end function CLASS:CanSuicide() return true end function CLASS:DeathThink() if (CurTime() - self.Player.Data.AliveTime) > 1 then self.Player:Spawn() return true end return false end -- Visible Stuff function CLASS:SetModel() local cl_playermodel = self.Player:GetInfo( "cl_playermodel" ) local modelname = player_manager.TranslatePlayerModel( cl_playermodel ) if !(util.IsValidModel(modelname)) then modelname = "models/player/combine_super_soldier.mdl" end util.PrecacheModel(modelname) self.Player:SetModel(modelname) -- Hands self.Player:SetupHands() end -- Interaction function CLASS:AllowPickup(ent) return true end function CLASS:CanPickupItem(ent) return true end function CLASS:CanPickupWeapon(ent) return true end -- Menu Buttons function CLASS:ShowSpare1() if BaseClass.ShowSpare1(self) then return end -- Play a taunt local tauntList = GAMEMODE.Config.Taunt:Seekers() local index = math.random(#tauntList) self.Player:EmitSound(tauntList[index], SNDLVL_NORM, 100, 1, CHAN_VOICE) if GAMEMODE.Config:DebugLog() then print("Prop Hunt: Seeker '"..self.Player:GetName().."' (SteamID: "..self.Player:SteamID()..") taunted with sound '"..tauntList[index].."'.") end end -- ------------------------------------------------------------------------- -- --! Shared -- ------------------------------------------------------------------------- -- function CLASS:Alive() return true end -- ------------------------------------------------------------------------- -- --! Client-Side -- ------------------------------------------------------------------------- -- function CLASS:ClientSpawn() if (GAMEMODE.Config:DebugLog()) then print("Prop Hunt CL: Seeker '"..self.Player:GetName().."' (SteamID: "..self.Player:SteamID()..") spawned.") end BaseClass.ClientSpawn(self) end function CLASS:HUDPaint() BaseClass.HUDPaint(self) local State = GetGlobalInt("RoundState", GAMEMODE.States.PreMatch) if (State == GAMEMODE.States.Hide) then local intTime = math.ceil(GetGlobalInt("RoundTime")) local strTime = tostring(intTime) -- Show Status at the center surface.SetTextColor( 255, 255, 255, 255 ) if (intTime >= 1) then surface.SetFont("CloseCaption_Bold") local w,h = surface.GetTextSize("Unblinded in "..strTime.." seconds...") surface.SetTextPos( ScrW()/2 - w / 2, ScrH()/2 - h / 2) surface.DrawText("Unblinded in "..strTime.." seconds...") else surface.SetFont("PHHugeAssFont") local w,h = surface.GetTextSize("NOW") surface.SetTextPos( ScrW()/2 - w / 2, ScrH()/2 - h / 2) surface.DrawText("NOW") end end end function CLASS:ShouldDrawLocal() return (self.Player.Data.ViewDistance or 0) >= 10 end -- Register player_manager.RegisterClass("Seeker", CLASS, "Default")
-- -- Created by IntelliJ IDEA. -- User: RJ -- Date: 21/09/16 -- Time: 10:19 -- To change this template use File | Settings | File Templates. -- --*********************************************************** --** ROBERT JOHNSON ** --*********************************************************** require "ISUI/ISPanel" ---@class ISPlayerStatsWarningPointUI : ISPanel ISPlayerStatsWarningPointUI = ISPanel:derive("ISPlayerStatsWarningPointUI"); --************************************************************************-- --** ISPanel:initialise --** --************************************************************************-- function ISPlayerStatsWarningPointUI:initialise() ISPanel.initialise(self); self:create(); end function ISPlayerStatsWarningPointUI:setVisible(visible) -- self.parent:setVisible(visible); self.javaObject:setVisible(visible); end function ISPlayerStatsWarningPointUI:render() local z = 20; self:drawText(getText("IGUI_PlayerStats_WarningPointTitle"), self.width/2 - (getTextManager():MeasureStringX(UIFont.Medium, getText("IGUI_PlayerStats_WarningPointTitle")) / 2), z, 1,1,1,1, UIFont.Medium); z = z + 30; self:drawText(getText("IGUI_PlayerStats_Reason"), 10, self.reason.y - self.reason.height + 2, 1,1,1,1, UIFont.Small); self:drawText(getText("IGUI_PlayerStats_Amount"), 10, self.amount.y - self.amount.height + 2, 1,1,1,1, UIFont.Small); end function ISPlayerStatsWarningPointUI:create() self.reason = ISTextEntryBox:new("", 10, 30 + self.zOffsetSmallFont + 2, 250, 20); self.reason.font = UIFont.Small; self.reason:initialise(); self.reason:instantiate(); self:addChild(self.reason); self.amount = ISTextEntryBox:new("1", 10, 80 + self.zOffsetSmallFont + 2, 50, 20); self.amount.font = UIFont.Small; self.amount:initialise(); self.amount:instantiate(); self.amount:setOnlyNumbers(true); self:addChild(self.amount); local btnWid = 100 local btnHgt = 25 local padBottom = 10 self.ok = ISButton:new((self:getWidth() / 2) - 100 - 5, self:getHeight() - padBottom - btnHgt, btnWid, btnHgt, getText("UI_Ok"), self, ISPlayerStatsWarningPointUI.onOptionMouseDown); self.ok.internal = "OK"; self.ok:initialise(); self.ok:instantiate(); self.ok.borderColor = {r=1, g=1, b=1, a=0.1}; self:addChild(self.ok); self.cancel = ISButton:new((self:getWidth() / 2) + 5, self:getHeight() - padBottom - btnHgt, btnWid, btnHgt, getText("UI_Cancel"), self, ISPlayerStatsWarningPointUI.onOptionMouseDown); self.cancel.internal = "CANCEL"; self.cancel:initialise(); self.cancel:instantiate(); self.cancel.borderColor = {r=1, g=1, b=1, a=0.1}; self:addChild(self.cancel); end function ISPlayerStatsWarningPointUI:onOptionMouseDown(button, x, y) if button.internal == "OK" then self:setVisible(false); self:removeFromUIManager(); if self.onclick ~= nil then self.onclick(self.target, button, self.reason:getText(), self.amount:getText()); end end if button.internal == "CANCEL" then self:setVisible(false); self:removeFromUIManager(); end end function ISPlayerStatsWarningPointUI:new(x, y, width, height, target, onclick) local o = {}; o = ISPanel:new(x, y, width, height); setmetatable(o, self); self.__index = self; o.variableColor={r=0.9, g=0.55, b=0.1, a=1}; o.borderColor = {r=0.4, g=0.4, b=0.4, a=1}; o.backgroundColor = {r=0, g=0, b=0, a=0.8}; o.target = target; o.onclick = onclick; o.zOffsetSmallFont = 25; o.moveWithMouse = true; return o; end
local module1 = ... print("loading module 1") function module1.test() print("running module 1 test") end
---@class RGB @R, G, B 값을 나타냅니다. ---@field R number @Red value ---@field G number @Green value ---@field B number @Blue value RGB = {} ---@param color number @RGB 값 ---@return RGB function numberToRGB(color) return { R = color % 0x100, G = math.floor(color / 0x100) % 0x100, B = math.floor(color / 0x10000) % 0x100 } end
----------------------------------------------------------------------------- -- JSONRPC4MinetestLua: JSONRPC4Lua modified for minetest engine. -- json-rpc Module. -- This module is released under the MIT License (MIT). -- -- Requires JSON4MinetestLua to be installed. -- -- USAGE: -- This module exposes two functions: -- rpc.proxy( 'url', callback) -- Returns a proxy object for calling the -- JSON RPC Service at the given url with -- given callback. -- rpc.call ( 'url', 'method', callback, ...) -- Calls the JSON RPC server at the given url, -- invokes the appropriate method, and passes the -- remaining parameters. Minetest HTTPApiTable is -- used to fetch pages and calls a callback. -- Callback function receives result from -- decoded httpResponse.data as callback(res) rpc = {} local http = minetest.request_http_api() function rpc.call(url, method, callback, ...) local jsonRequest = json.encode( { ["id"]=tostring(math.random()), ["method"] = method, ["params"] = {...}, } ) --debug --minetest.debug("jsonRequest: "..jsonRequest) http.fetch( { ['url'] = url, ['method'] = 'POST', ['extra_headers'] = { ['content-type']='application/json-rpc', ['content-length']=string.len(jsonRequest)}, ['post_data'] = jsonRequest }, function(httpResponse) if httpResponse.code ~= 200 then return end if not callback then return end local data = json.decode(httpResponse.data) local res = data.result callback(res) end) end function rpc.proxy(url, callback) local serverProxy = {} local proxyMeta = { __index = function(self, key) return function(...) return rpc.call(url, key, callback, ...) end end } setmetatable(serverProxy, proxyMeta) return serverProxy end
-- kalimba -- follow a real kalimba -- with a synthesized one engine.name='Kalimba' local SCREEN_FRAMERATE=15 local DEBOUNCE_TIME=0.1 local debounce_timer={0,0,0,0} local current_freq=-1 local last_freq=-1 local currrent_amp=-1 local last_amp=-1 local amp_min=0.01 local amp_max=0.06 local note_activated=false local viewport={width=128,height=64,time=0} -- A2 C3 E3 F3 A3 B3 C4 E4 local frequency_percent_tolerance=0.2 local frequency_available={229,261,328,350,440,494,523,660} -- Encoder input function enc(n,delta) end -- Key input function key(n,z) end function init() engine.amp(0) -- Polls --update pitch local pitch_poll_l=poll.set("pitch_in_l",function(value) update_freq(value) end) pitch_poll_l:start() -- initiate engine playback on incoming audio p_amp_in=poll.set("amp_in_l") p_amp_in.time=0.1 p_amp_in.callback=function(val) -- print(val) -- local filetest=io.open("/tmp/test.data","a") -- io.output(filetest) -- io.write(val.."\n") -- io.close(filetest) current_amp_diff=val-last_amp if current_amp_diff>amp_min then debounce_timer[4]=util.time() if debounce_timer[4]-debounce_timer[3]>DEBOUNCE_TIME then -- TODO: scale amplitude based on amp threshold local amp_set=(current_amp_diff-amp_min)/amp_max if amp_set>1 then amp_set=1 end print("amp_set "..amp_set) engine.amp(amp_set) debounce_timer[3]=util.time() note_activated=true end end last_amp=val end p_amp_in:start() -- update screen re=metro.init() re.time=0.1 re.event=function() viewport.time=viewport.time+0.1 redraw() end re:start() end function redraw() screen.clear() screen.move(64,32) screen.text_center("kalimba") screen.update() end function update_freq(freq) current_freq=freq if current_freq>0 then debounce_timer[2]=util.time() -- add debounce time for each note if debounce_timer[2]-debounce_timer[1]>DEBOUNCE_TIME and note_activated then -- quantize notes to available notes hzs=snap_to_frequency(current_freq) print("new freq "..current_freq) for k,v in pairs(hzs) do if v>0 then print("playing "..v) engine.hz(v) end end debounce_timer[1]=util.time() note_activated=false end end if current_freq>0 then last_freq=current_freq end end function snap_to_frequency(hz) -- is within tolerance of any? for k,v in pairs(frequency_available) do if hz>v*(1-frequency_percent_tolerance) and hz<v*(1+frequency_percent_tolerance) then return {hz} end end -- is in between any pair? for k,v in pairs(frequency_available) do if k>1 then if hz>frequency_available[k-1] and hz<v then return {frequency_available[k-1],v} end end end return {-1} end
local propText = script:GetCustomProperty("Text"):WaitForObject() local propShadowText = script:GetCustomProperty("ShadowText"):WaitForObject() local LOCAL_PLAYER = Game.GetLocalPlayer() Events.Connect("PlayerWins_Event", function(player) local textToDisplay = player.name .. " wins!!" if player == LOCAL_PLAYER then textToDisplay = "You win!" end propText.text = textToDisplay propShadowText.text = textToDisplay Task.Wait(3) propText.text = "" propShadowText.text = "" end)
local cmp = require "cmp" local luasnip = require "luasnip" local kind_icons = { Text = "", Method = "", Function = "", Constructor = "", Field = "", Variable = "", Class = "ﴯ", Interface = "", Module = "", Property = "ﰠ", Unit = "", Value = "", Enum = "", Keyword = "", Snippet = "", Color = "", File = "", Reference = "", Folder = "", EnumMember = "", Constant = "", Struct = "", Event = "", Operator = "", TypeParameter = "" } cmp.setup({ snippet = { expand = function(args) luasnip.lsp_expand(args.body) end, }, mapping = { ['<C-b>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }), -- Helps scrolling left I guess ['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }), -- Helps scrolling right I guess ['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 'c' }), -- Open completion menu without typing ['<C-y>'] = cmp.config.disable, -- I do not know what it does, does not matter ['<C-e>'] = cmp.mapping.close(), -- Close completion menu ["<Tab>"] = cmp.mapping(cmp.mapping.select_next_item(), { "i", "s" }), -- Scrolling down with Tab in the menu ["<S-Tab>"] = cmp.mapping(cmp.mapping.select_prev_item(), { "i", "s" }), -- Scrolling up with S-TAB ['<CR>'] = cmp.mapping.confirm({ select = true }), -- ENTER to select the selected completion option }, sources = cmp.config.sources{ { name = 'nvim_lsp'}, -- From that lsp completion source { name = 'luasnip' }, -- From luasnip plugin { name = 'buffer'}, -- From that buffer completion source { name = 'path'}, -- From that path completion source documentation = { border = { "╭", "─", "╮", "│", "╯", "─", "╰", "│" }, }, }, formatting = { format = function(entry, vim_item) vim_item.kind = string.format('%s %s', kind_icons[vim_item.kind], vim_item.kind) vim_item.menu = ({ nvim_lsp = "[LSP]", luasnip = "[Snippet]", buffer = "[Buffer]", path = "[Path]" })[entry.source.name] return vim_item end }, })
return {'vrijheidsbeeld','vriend','vriendelijk','vriendelijkheid','vriendenclub','vriendendienst','vriendenfeest','vriendengroep','vriendengroet','vriendenkring','vriendenmaal','vriendenmatch','vriendenpaar','vriendenploeg','vriendenprijsje','vriendenschaar','vriendin','vriendinnenkring','vriendinnetje','vriendjespolitiek','vriendschap','vriendschappelijk','vriendschappelijkheid','vriendschapsband','vriendschapsbetuiging','vriendschapsrelatie','vriendschapsverdrag','vriesbak','vriescel','vriesdrogen','vrieshuis','vrieskamer','vrieskast','vrieskist','vrieskou','vrieskoude','vrieslucht','vriesnacht','vriespunt','vriesruimte','vriesvak','vriesweder','vriesweer','vrieswind','vriezen','vriezer','vrij','vrijaf','vrijage','vrijberoepsbeoefenaar','vrijbiljet','vrijblijvend','vrijblijvendheid','vrijbrief','vrijbuiten','vrijbuiter','vrijbuiterij','vrijdag','vrijdagavond','vrijdaggebed','vrijdagmiddag','vrijdagmorgen','vrijdagnacht','vrijdagnamiddag','vrijdagochtend','vrijdags','vrijdagse','vrijdagsgebed','vrijdenkend','vrijdenker','vrijdenkerij','vrijdenkster','vrijdom','vrijdragend','vrije','vrijelijk','vrijemarkteconomie','vrijemarktprincipe','vrijemarktsector','vrijemarktwerking','vrijen','vrijer','vrijerij','vrijesectorwoning','vrijetijdsactiviteit','vrijetijdsauto','vrijetijdsbesteding','vrijetijdscentrum','vrijetijdsgedrag','vrijetijdsindustrie','vrijetijdskleding','vrijetijdskunde','vrijetijdsmarkt','vrijetijdsprobleem','vrijetijdssector','vrijetrappenspecialist','vrijgave','vrijgeboren','vrijgeborene','vrijgeest','vrijgeesterij','vrijgelatene','vrijgeleide','vrijgeleidebrief','vrijgemaakt','vrijgespeeld','vrijgesteld','vrijgestelde','vrijgevallen','vrijgeven','vrijgevestigd','vrijgevig','vrijgevigheid','vrijgevochten','vrijgevochtenheid','vrijgezel','vrijgezellenavond','vrijgezellenbelasting','vrijgezellenbestaan','vrijgezellenflat','vrijgezellenstaat','vrijhandel','vrijhandelaar','vrijhandelsakkoord','vrijhandelsassociatie','vrijhandelsgebied','vrijhandelsovereenkomst','vrijhandelstelsel','vrijhandelsverdrag','vrijhandelszone','vrijhaven','vrijheer','vrijheid','vrijheidlievend','vrijheidsbeginsel','vrijheidsbeneming','vrijheidsbeperking','vrijheidsberoving','vrijheidsbeweging','vrijheidsboom','vrijheidsdrang','vrijheidsgeest','vrijheidsgevoel','vrijheidsgraad','vrijheidsheld','vrijheidshoed','vrijheidsideaal','vrijheidsliefde','vrijheidslievend','vrijheidsmuts','vrijheidsoorlog','vrijheidsrechten','vrijheidsstraf','vrijheidsstreven','vrijheidsstrijd','vrijheidsstrijder','vrijheidsstrijdster','vrijheidszin','vrijheidszucht','vrijhouden','vrijkaart','vrijkomen','vrijkopen','vrijkoping','vrijkorps','vrijlaten','vrijlating','vrijlatingsregeling','vrijleen','vrijliggend','vrijloop','vrijlopen','vrijlot','vrijloten','vrijmacht','vrijmachtig','vrijmaken','vrijmaking','vrijmarkt','vrijmetselaar','vrijmetselaarsloge','vrijmetselaarsteken','vrijmetselarij','vrijmoedig','vrijmoedigheid','vrijpartij','vrijpion','vrijplaats','vrijpleiten','vrijpostig','vrijpostigheid','vrijschop','vrijscene','vrijspelen','vrijspraak','vrijspreken','vrijspreking','vrijstaan','vrijstaand','vrijstaat','vrijstad','vrijstellen','vrijstelling','vrijstellingenvariant','vrijstellingsregeling','vrijster','vrijsterschap','vrijthof','vrijuit','vrijval','vrijvallen','vrijvechten','vrijverklaard','vrijverklaren','vrijwaren','vrijwaring','vrijwaringsbewijs','vrijwel','vrijwiel','vrijwielen','vrijwillig','vrijwilliger','vrijwilligersbeleid','vrijwilligerscentrale','vrijwilligersdag','vrijwilligersgroep','vrijwilligerskorps','vrijwilligerskrijgsmacht','vrijwilligersleger','vrijwilligersorganisatie','vrijwilligersproject','vrijwilligersvergoeding','vrijwilligerswerk','vrijwilligheid','vrijwilligster','vrijwilligsterswerk','vrijzinnig','vrijzinnige','vrijzinnigheid','vrille','vrind','vrijkous','vrijekeuzeruimte','vrijeluchtinspectie','vrijemarktkapitalisme','vrijerig','vrijstellingsprocedure','vrijgezellenfeest','vrijspreker','vriendenlijst','vriendennetwerk','vriendlief','vriesgedeelte','vrijboord','vrijgezellendag','vrijwaringsclausule','vriendenboek','vriendendag','vriendenprijs','vriendensite','vriendenteam','vriendinlief','vriendinnendag','vriestemperatuur','vrijdageditie','vrijdagmarkt','vrijdagmiddagborrel','vrijdagmiddaggebed','vrijdagpreek','vrijdagtraining','vrijdagvoormiddag','vrijdenken','vrijgezellenleven','vrijgezellenparty','vrijheidsbegrip','vrijheidsconcept','vrijheidsdenken','vrijheidsgedachte','vrijheidsontneming','vrijheidsprijs','vrijheidsrecht','vrijstellingsbepaling','vrijstellingsbesluit','vrijstellingsbevoegdheid','vrijstellingslijst','vrijstellingsmogelijkheid','vrijstellingsverordening','vrijstellingsverzoek','vrijwaringsverklaring','vrijwilligersavond','vrijwilligerscoordinator','vrijwilligersfunctie','vrijwilligershulp','vrijwilligersprijs','vrijwilligersregeling','vrijwilligersteam','vrijwilligersverzekering','vrijwilligerswerkbeleid','vrijwilligerswerking','vrijwilligerszorg','vrijwilligerswet','vriendinnenclub','vrijwording','vrijzetting','vriendenbezoek','vrijwilligersvereniging','vrijkwartier','vrieskoelwals','vrijstellingsmethode','vrijmetselaarsorde','vrijetijdseconomie','vriendenpagina','vries','vriezenveen','vriezenveens','vriezenvener','vrieling','vriens','vrielink','vriends','vriesema','vrieze','vriezen','vrijenhoek','vrind','vriezema','vrijsen','vrins','vriese','vriesen','vriezekolk','vrijens','vrijs','vringer','vriesde','vrijhoeven','vrisekoop','vriendelijke','vriendelijker','vriendelijkere','vriendelijkheden','vriendelijks','vriendelijkst','vriendelijkste','vrienden','vriendendiensten','vriendenfeesten','vriendengroepen','vriendenkringen','vriendinnen','vriendinnenkringen','vriendinnetjes','vriendje','vriendjes','vriendschappelijke','vriendschappelijker','vriendschappelijkere','vriendschappelijkst','vriendschappelijkste','vriendschappen','vriendschapsbanden','vriendschapsbetuigingen','vries','vriesbakken','vriescellen','vriesganzen','vrieshuizen','vrieskamers','vrieskasten','vrieskisten','vriespunten','vriesruimtes','vriest','vriezend','vriezers','vrijages','vrijbiljetten','vrijblijvende','vrijblijvender','vrijbrieven','vrijbuit','vrijbuiters','vrijdagavonden','vrijdagen','vrijdagochtenden','vrijde','vrijden','vrijdenkers','vrijdommen','vrijemarkteconomieen','vrijere','vrijerijen','vrijerijtje','vrijerijtjes','vrijers','vrijersvoeten','vrijertje','vrijertjes','vrijesectorwoningen','vrijgaf','vrijgaven','vrijgeef','vrijgeeft','vrijgeesten','vrijgegeven','vrijgehouden','vrijgekocht','vrijgekochte','vrijgekomen','vrijgelaten','vrijgelatenen','vrijgeleidebrieven','vrijgeleiden','vrijgeleides','vrijgeloot','vrijgelopen','vrijgelote','vrijgemaakte','vrijgepleit','vrijgepleite','vrijgesproken','vrijgestaan','vrijgestelden','vrijgevige','vrijgeviger','vrijgevigst','vrijgevigste','vrijgevochtener','vrijgevochtenere','vrijgezellen','vrijhandelaars','vrijhandelaren','vrijhandelsakkoorden','vrijhavens','vrijheden','vrijheidlievende','vrijheidminnende','vrijheidsbeperkende','vrijheidsbeperkingen','vrijheidsbomen','vrijheidsgraden','vrijheidsoorlogen','vrijheidsstraffen','vrijheidsstrijders','vrijheren','vrijhield','vrijhoud','vrijhoudt','vrijkaarten','vrijkaartje','vrijkocht','vrijkom','vrijkomend','vrijkomende','vrijkomt','vrijkoop','vrijkoopt','vrijkopingen','vrijkorpsen','vrijkwam','vrijkwamen','vrijlaat','vrijlatingen','vrijliep','vrijliepen','vrijliet','vrijliggende','vrijloopt','vrijmaak','vrijmaakt','vrijmaakte','vrijmaakten','vrijmachtige','vrijmakingen','vrijmarkten','vrijmetselaars','vrijmetselaarsloges','vrijmetselaren','vrijmoedige','vrijmoediger','vrijmoedigheden','vrijmoedigste','vrijplaatsen','vrijpleit','vrijpleitte','vrijpleitten','vrijpostige','vrijpostiger','vrijsprak','vrijspraken','vrijspreek','vrijspreekt','vrijst','vrijsta','vrijstaande','vrijstaten','vrijste','vrijsteden','vrijstel','vrijstelde','vrijstelden','vrijstellingen','vrijstelt','vrijsters','vrijstertje','vrijstond','vrijt','vrijvallende','vrijvalt','vrijvecht','vrijverklaarde','vrijviel','vrijvielen','vrijvocht','vrijwaar','vrijwaarde','vrijwaart','vrijwaringen','vrijwielt','vrijwillige','vrijwilligere','vrijwilligers','vrijwilligerscentrales','vrijwilligerskorpsen','vrijwilligersorganisaties','vrijwilligersprojecten','vrijwilligst','vrijwilligste','vrijwilligsters','vrijzinnigen','vrijzinniger','vrijzinnigere','vrijzinnigste','vrilles','vrinden','vriendenclubje','vriendenmatchen','vriendschappelijkheden','vriendschapsrelaties','vriendschapsverdragen','vriesdroogde','vriesnachten','vriesruimten','vriesvakken','vrijberoepsbeoefenaars','vrijblijvendheden','vrijbuiterijen','vrijbuitte','vrijdaggebeden','vrijend','vrijende','vrijetijdsactiviteiten','vrijetijdsbestedingen','vrijgeborenen','vrijgezellenavonden','vrijhandelsgebieden','vrijhandelsovereenkomsten','vrijhandelszones','vrijheidsbewegingen','vrijheidshelden','vrijheidsidealen','vrijheidslievende','vrijkaartjes','vrijlopende','vrijmachten','vrijmetselaarstekens','vrijpartijen','vrijpartijtje','vrijpionnen','vrijpostigheden','vrijschoppen','vrijthoven','vrijwilligerslegers','vrijwilligs','vrijdagmiddagen','vrijdenkende','vriendenprijsjes','vriendenparen','vrijdagsgebeden','vrijerige','vrijgezellenflats','vrijhandelsassociaties','vrijkousen','vrijgezelle','vriendenboekje','vriendengroepje','vriestemperaturen','vrijgezellenfeestje','vriendenboekjes','vriendenclubs','vriendenlijstje','vriesvakje','vrijgezellenfeestjes','vrijhandelsverdragen','vrijwaringsclausules','vrijwilligersgroepen','vrijstellingsmogelijkheden','vriendinnenclubje','vrijbriefje','vrijstaatje','vrijstellingsprocedures','vrijdagje','vrijscenes','vriendensites','vriendennetwerken','vriendengroepjes','vrijpartijtjes','vriendenclubjes','vrijstellingsverordeningen','vrijwilligersvergoedingen','vrijwilligersdagen','vriendenteams','vrijheidsberovingen','vrijdagtrainingen','vrijwilligersverenigingen','vrijwilligersfuncties','vrieskistje','vrijstellingsverzoeken','vrijstellingsbepalingen','vrijdagmiddagborrels','vrijwaringsbewijzen','vrijwilligersteams','vrijsprekers','vrijgezellenavondjes','vriendenbezoekjes','vrijheidsbeginselen','vrijwilligersprijzen','vriezenveense','vrijgevestigde'}
-- All the net messages defined here util.AddNetworkString("xAdminNetworkIDRank") util.AddNetworkString("xAdminNetworkExistingUsers") util.AddNetworkString("xAdminNetworkCommands") util.AddNetworkString("xAdminAFKCheck") util.AddNetworkString("xAdminAFKConfirm") util.AddNetworkString("xAdminChatMessage") util.AddNetworkString("xAdminSpectate") util.AddNetworkString("xAdminStartAnnouncement") util.AddNetworkString("xAdminKnownAliases") util.AddNetworkString("xAdminScanHit") util.AddNetworkString("xAdminRequestAlts") util.AddNetworkString("xAdminRequestFriends") util.AddNetworkString("xAdminRequestFocus")
add_requires("spdlog 1.8.5") target("log") set_kind("shared") set_pcxxheader("../pch.h") add_includedirs("$(projectdir)/deps/headeronly", "$(projectdir)/deps/libs", "$(projectdir)/deps/src", "$(projectdir)/src") add_files("*.cpp") add_packages("spdlog")
-- double-ended stack? local m = {} function m.new() return { [0] = {}, from = 0, to = -1 } end function m.empty(l) return l.to < l.from end function m.is(l) return l.to and l.from and type(l[0]) == "table" end function m.len(l) return l.to - l.from + 1 end function m.get(l, p) if p < 0 then return l[0][-p] end return l[p+1] end function m.set(l, p, v) if p < 0 then l[0][-p] = v end l[p+1] = v end function m.first(l) -- index 0 m.get(l, l.from) end function m.last(l) -- index -1 m.get(l, l.to) end function m.index(l, p) if p < 0 then return m.get(l, l.to + p + 1) end return m.get(l, l.from + p) end function m.prepend(l, v) l.from = l.from - 1 m.set(l, l.from, v) end function m.append(l, v) l.to = l.to + 1 m.set(l, l.to, v) end function m.popstart(l) local v if l.from < 0 then v = l[0][-l.from] l[0][-l.from] = nil end v = l[l.from+1] l[l.from+1] = nil l.from = l.from + 1 return v end function m.pop(l) local v if l.to < 0 then v = l[0][-l.to] l[0][-l.to] = nil end v = l[l.to+1] l[l.to+1] = nil l.to = l.to - 1 return v end function m.fromtable(t) local l = m.new() for i,v in ipairs(t) do l[i] = v end l.to = #l - 1 return l end return m
-- Each time a judgment occurs during gameplay, the engine broadcasts some relevant data -- as a key/value table that themeside Lua can listen for via JudgmentMessageCommand() -- -- The details of *what* gets broadcast is complicated and not documented anywhere I've found, -- but you can grep the src for "Judgment" (quotes included) to get a sense of what gets sent -- to Lua in different circumstances. -- -- This file, PerColumnJudgmentTracking.lua exists so that ScreenEvaluation can have a pane -- that displays a per-column judgment breakdown. -- -- We have a local table, judgments, that has as many sub-tables as the current game has panels -- per player (4 for dance-single, 8 for dance-double, 5 for pump-single, etc.) -- and each of those sub-tables stores the number of judgments that occur during gameplay on -- that particular panel. -- -- This doesn't override or recreate the engine's judgment system in any way. It just allows -- transient judgment data to persist beyond ScreenGameplay. ------------------------------------------------------------ -- don't bother tracking per-column judgment data in Casual gamemode if SL.Global.GameMode == "Casual" then return end local player = ... local track_missbcheld = SL[ToEnumShortString(player)].ActiveModifiers.MissBecauseHeld local judgments = {} local heldTimes = {} for i=1,GAMESTATE:GetCurrentStyle():ColumnsPerPlayer() do judgments[#judgments+1] = { W0=0, W1=0, W2=0, W3=0, W4=0, W5=0, Miss=0 } end local actor = Def.Actor{ OffCommand=function(self) local storage = SL[ToEnumShortString(player)].Stages.Stats[SL.Global.Stages.PlayedThisGame + 1] storage.column_judgments = judgments -- if gameplay ends while buttons are still held we won't have values for length. Check the last -- hold time for each button and if it only has one value use the current time to determine the length if heldTimes[player] then for _,button in pairs(heldTimes[player]) do if next(button) and #button[#button] == 1 then -- next(button) checks if there's anything at all table.insert(button[#button],GAMESTATE:GetCurMusicSeconds() - button[#button][1]) end end end storage.heldTimes = heldTimes[player] end } -- if the player doesn't care about MissBecauseHeld, keep it simple if not track_missbcheld then actor.JudgmentMessageCommand=function(self, params) local health_state = GAMESTATE:GetPlayerState(params.Player):GetHealthState() if params.Player == player and params.Notes and health_state ~= 'HealthState_Dead' then for col,tapnote in pairs(params.Notes) do local tnt = tapnote:GetTapNoteType() -- we don't want to consider TapNoteTypes like Mine, HoldTail, Attack, etc. when counting judgments -- we do want to consider normal tapnotes, hold heads, and lifts -- see: https://quietly-turning.github.io/Lua-For-SM5/LuaAPI#Enums-TapNoteType if tnt == "TapNoteType_Tap" or tnt == "TapNoteType_HoldHead" or tnt == "TapNoteType_Lift" then local tns = ToEnumShortString(params.TapNoteScore) -- count FAP here whether or not we end up using it if tns == 'W1' and math.abs(params.TapNoteOffset) < SL.Global.TimingWindowSecondsW0 * PREFSMAN:GetPreference("TimingWindowScale") + SL.Preferences[SL.Global.GameMode]["TimingWindowAdd"] then judgments[col]['W0'] = judgments[col]['W0'] + 1 else judgments[col][tns] = judgments[col][tns] + 1 end end end end end -- if the player wants to track MissBecauseHeld, we need to do a lot more work else -- add MissBecauseHeld as a possible judgment for all columns for i,col_judgments in ipairs(judgments) do col_judgments.MissBecauseHeld=0 end local buttons = {} local style = GAMESTATE:GetCurrentStyle() local num_columns = style:ColumnsPerPlayer() for i=1,num_columns do local col = style:GetColumnInfo(player, i) table.insert(buttons, col.Name) end local held = {} -- initialize to handle both players, regardless of whether both are actually joined. -- the engine's InputCallback gives you ALL input, so even if only P1 is joined, the -- InputCallback will report someone spamming input on P2 as valid events, so we have -- to ensure that doesn't cause Lua errors here for player in ivalues( PlayerNumber ) do held[player] = {} heldTimes[player] = {} -- initialize all buttons available to this game for this player to be "not held" for button in ivalues(buttons) do held[player][button] = false heldTimes[player][button] = {} end end local InputHandler = function(event) -- if any of these, don't attempt to handle input if not event.PlayerNumber or not event.button then return false end local buttonTable = heldTimes[event.PlayerNumber][event.button] if buttonTable then --start/back aren't part of the table. only procede if it's a button we care about if event.type == "InputEventType_FirstPress" then held[event.PlayerNumber][event.button] = true buttonTable[#buttonTable+1] = {GAMESTATE:GetCurMusicSeconds()} elseif event.type == "InputEventType_Release" then held[event.PlayerNumber][event.button] = false if buttonTable[#buttonTable] then table.insert(buttonTable[#buttonTable],GAMESTATE:GetCurMusicSeconds() - buttonTable[#buttonTable][1]) end end end end actor.OnCommand=function(self) SCREENMAN:GetTopScreen():AddInputCallback( InputHandler ) end actor.JudgmentMessageCommand=function(self, params) local health_state = GAMESTATE:GetPlayerState(params.Player):GetHealthState() if params.Player == player and params.Notes and health_state ~= 'HealthState_Dead' then for col,tapnote in pairs(params.Notes) do local tnt = tapnote:GetTapNoteType() -- we don't want to consider TapNoteTypes like Mine, HoldTail, Attack, etc. when counting judgments -- we do want to consider normal tapnotes, hold heads, and lifts -- see: https://quietly-turning.github.io/Lua-For-SM5/LuaAPI#Enums-TapNoteType if tnt == "TapNoteType_Tap" or tnt == "TapNoteType_HoldHead" or tnt == "TapNoteType_Lift" then local tns = ToEnumShortString(params.TapNoteScore) -- count FAP here if its enabled if SL.Global.GameMode == "Experiment" and SL[ToEnumShortString(player)].ActiveModifiers.EnableFAP and tns == 'W1' and math.abs(params.TapNoteOffset) < SL.Global.TimingWindowSecondsW0 * PREFSMAN:GetPreference("TimingWindowScale") + SL.Preferences[SL.Global.GameMode]["TimingWindowAdd"] then judgments[col]['W0'] = judgments[col]['W0'] + 1 else judgments[col][tns] = judgments[col][tns] + 1 end if tns == "Miss" and held[params.Player][ buttons[col] ] then judgments[col].MissBecauseHeld = judgments[col].MissBecauseHeld + 1 end end end end end end return actor
class.name = "rotateAlongX" class.base = "engine.monoBehaviour" function class:awake() self.meshRenderer = self.gameObject:getComponent(engine.meshRenderer) self.meshRenderer.colour:set(1.0, 0.0, 0.0, 1.0) end function class:update(dt) self.transform.rotation:rotate(1, 0, 0, dt) end
local get_request = require("resty.core.base").get_request local ngx_var = ngx.var local _M = { _version = 0.1, } function _M.request() local r = get_request() if not r then return nil, "no request found" end return r end function _M.fetch(name, request) return ngx_var[name] end return _M
--------------------------------------------------------------------------------------------------- -- Issue: https://github.com/smartdevicelink/sdl_core/issues/3136 -- -- Description: Successful 2nd PTU if it's triggered within failed retry for the 1st PTU -- Note: script is applicable for PROPRIETARY policy flow -- -- Preconditions: -- 1) SDL and HMI are started -- 2) App_1 is registered -- SDL does: -- - start PTU sequence -- -- Steps: -- 1) App_1 doesn't provide PTU update -- 2) App_2 is registered within PTU retry sequence -- SDL does: -- - postpone new PTU sequence until the previous one is finished -- 3) App_1 still doesn't provide PTU update -- SDL does: -- - finish 1st PTU retry sequence with `UPDATE_NEEDED` status -- - start new PTU sequence with `UPDATE_NEEDED` status and send `BC.PolicyUpdate` request to HMI -- 4) Mobile provides valid PTU update -- SDL does: -- - finish 2nd PTU sequence successfully with `UP_TO_DATE` status --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require("user_modules/sequences/actions") local utils = require("user_modules/utils") local color = require("user_modules/consts").color --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false runner.testSettings.restrictions.sdlBuildOptions = { { extendedPolicy = { "PROPRIETARY" } } } --[[ Local Variables ]] local secondsBetweenRetries = { 1, 2 } local timeout_after_x_seconds = 4 local expNumOfOnSysReq = #secondsBetweenRetries + 1 --[[ Local Functions ]] local function log(...) local str = "[" .. atf_logger.formated_time(true) .. "]" for i, p in pairs({...}) do local delimiter = "\t" if i == 1 then delimiter = " " end str = str .. delimiter .. p end utils.cprint(color.magenta, str) end local function updatePreloadedTimeout(pTbl) pTbl.policy_table.module_config.timeout_after_x_seconds = timeout_after_x_seconds pTbl.policy_table.module_config.seconds_between_retries = secondsBetweenRetries end local function updatePreloaded(pUpdFunc) local preloadedTable = common.sdl.getPreloadedPT() preloadedTable.policy_table.functional_groupings["DataConsent-2"].rpcs = common.json.null pUpdFunc(preloadedTable) common.sdl.setPreloadedPT(preloadedTable) end local function checkPTUStatus(pExpStatus) local cid = common.hmi.getConnection():SendRequest("SDL.GetStatusUpdate") common.hmi.getConnection():ExpectResponse(cid, { result = { status = pExpStatus }}) end local function unsuccessfulPTUviaMobile() local timeout = 60000 common.hmi.getConnection():SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = "files/ptu.json" }) common.mobile.getSession():ExpectNotification("OnSystemRequest", { requestType = "PROPRIETARY" }) :Do(function() log("SDL->MOB:", "OnSystemRequest") end) :Times(expNumOfOnSysReq) :Timeout(timeout) local isBCPUReceived = false common.hmi.getConnection():ExpectRequest("BasicCommunication.PolicyUpdate") :Do(function(_, data) log("SDL->HMI:", "BC.PolicyUpdate") isBCPUReceived = true common.hmi.getConnection():SendResponse(data.id, data.method, "SUCCESS", { }) log("HMI->SDL:", "SUCCESS BC.PolicyUpdate") end) :Timeout(timeout) local exp = { { status = "UPDATE_NEEDED" }, { status = "UPDATING" }, { status = "UPDATE_NEEDED" }, { status = "UPDATING" }, { status = "UPDATE_NEEDED" }, { status = "UPDATE_NEEDED" }, -- new PTU sequence { status = "UPDATING" } } common.hmi.getConnection():ExpectNotification("SDL.OnStatusUpdate", table.unpack(exp)) :Times(#exp) :Timeout(timeout) :Do(function(e, data) log("SDL->HMI:", "SDL.OnStatusUpdate(" .. data.params.status .. ")") if e.occurences == 2 then checkPTUStatus("UPDATING") common.sdl.deletePTS() end if e.occurences == 3 then common.app.registerNoPTU(2) log("SDL->MOB2:", "RAI2") end end) :ValidIf(function(e) if e.occurences == #exp - 1 and isBCPUReceived == true then return false, "BC.PolicyUpdate is sent before new PTU sequence" end if e.occurences == #exp - 3 and common.sdl.getPTS() ~= nil then return false, "PTS was created before new PTU sequence" end return true end) end local function policyTableUpdate() if common.sdl.getPTS == nil then common.run.fail("PTS was not created within new PTU sequence") end local function expNotifFunc() common.hmi.getConnection():ExpectRequest("VehicleInfo.GetVehicleData", { odometer = true }) common.hmi.getConnection():ExpectNotification("SDL.OnStatusUpdate", { status = "UP_TO_DATE" }) :Times(1) end common.ptu.policyTableUpdate(nil, expNotifFunc) end local function unsuccessfulPTUviaHMI() local requestId = common.hmi.getConnection():SendRequest("SDL.GetPolicyConfigurationData", { policyType = "module_config", property = "endpoints" }) common.hmi.getConnection():ExpectResponse(requestId) :Do(function() common.hmi.getConnection():ExpectNotification("SDL.OnStatusUpdate") :Times(0) common.mobile.getSession():ExpectNotification("OnPermissionsChange") :Times(0) end) common.run.wait(500) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Preloaded update with retry parameters", updatePreloaded, { updatePreloadedTimeout }) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Title("Test") runner.Step("Register App", common.app.register) runner.Step("Activate App", common.app.activate) runner.Step("Unsuccessful PTU via a HMI", unsuccessfulPTUviaHMI) runner.Step("Unsuccessful PTU via a mobile device", unsuccessfulPTUviaMobile) runner.Step("Unsuccessful PTU via a HMI", unsuccessfulPTUviaHMI) runner.Step("Successful PTU via Mobile", policyTableUpdate) runner.Step("Check PTU status UP_TO_DATE", checkPTUStatus, { "UP_TO_DATE" }) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
-------------------------------------------------------------------------------- -- ARS-MP safety system -------------------------------------------------------------------------------- -- Copyright (C) 2013-2018 Metrostroi Team & FoxWorks Aerospace s.r.o. -- Contains proprietary code. See license.txt for additional information. -------------------------------------------------------------------------------- Metrostroi.DefineSystem("ARS_MP") TRAIN_SYSTEM.DontAccelerateSimulation = false function TRAIN_SYSTEM:Initialize() self.Train:LoadSystem("UOS","Relay","Switch", {bass = true}) self.Train:LoadSystem("ALSFreq","Relay","Switch",{bass=true}) self.Train:LoadSystem("AB1","Relay","Switch",{bass=true}) self.Train:LoadSystem("AB2","Relay","Switch",{bass=true}) self.Train:LoadSystem("EPKContacts","Relay","",{close_time = 3}) self.Train:LoadSystem("ROT1","Relay","", { bass = true}) self.Train:LoadSystem("ROT2","Relay","", { bass = true}) self.Train:LoadSystem("EPKC","Relay") -- Internal state self.SpeedLimit = 0 self.NextLimit = 0 self.AB = 0 self.AV = 0 self.AV1 = 0 self.ARSRing = 0 self.KRT = 0 self.KRO = 0 self.KRH = 0 --[[ self.Overspeed = false self.RUVD = false self.PneumaticBrake1 = false self.PneumaticBrake2 = true self.AttentionPedal = false--]] self.KVT = false self.LN = 0 self["2"] = 0 self["25"] = 0 self["20"] = 0 self["33G"] = 0 self["33"] = 0 self["17"] = 0 self["8"] = 0 self["44"] = 0 self["48"] = 0 self.EK = 1 self.F6 = 0 self.F5 = 0 self.PrevF5 = 0 self.F4 = 0 self.F3 = 0 self.F2 = 0 self.F1 = 0 self.NoFreq = 0 self.PrevNoFreq = 0 self.ARS = 0 self.AB = 0 self.AV = 0 self.AV1 = 0 self.ABReady = 0 -- Lamps ---self.LKT = false self.LVD = 0 self.Ring = 0 end function TRAIN_SYSTEM:Outputs() return { --"2","25","20","33G","33","17","8","44","48", "NoFreq","F1","F2","F3","F4","F5","F6","LN","ARS","AB","KT","LVD","ABReady" } end function TRAIN_SYSTEM:Inputs() return { "IgnoreThisARS","AttentionPedal","Ring" } end function TRAIN_SYSTEM:TriggerInput(name,value) end function TRAIN_SYSTEM:Think(dT) local Train = self.Train local ALS = Train.ALSCoil local speed = math.Round(ALS.Speed or 0,1) local power = self.GE > 0 local TwoToSix = self.Freq > 0 -- ALS, ARS state if power and not self.EnableARSTimer then self.EnableARSTimer = CurTime()+1+math.random()*9 elseif not power and self.EnableARSTimer then self.EnableARSTimer = nil end if ALS.Enabled~=self.ALS then ALS:TriggerInput("Enable",self.ALS) end local Power = self.EnableARSTimer and CurTime()-self.EnableARSTimer > 0 local KVT = self.KB > 0 local F1 = ALS.F1*self.ALS local F2 = ALS.F2*self.ALS local F3 = ALS.F3*self.ALS local F4 = ALS.F4*self.ALS local F5 = ALS.F5*self.ALS local F6 = ALS.F6*self.ALS local FreqCount = F1+F2+F3+F4+F5+F6 local TwoFreq = FreqCount==2 if self.AB > 0 then if FreqCount>0 then self.AB = 0 end F1 = 1 F2 = 0 F3 = 0 F4 = 0 F5 = 0 F6 = 0 elseif TwoToSix and not TwoFreq then F1 = 0 F2 = 0 F3 = 0 F4 = math.min(1,F1+F2+F3+F4) elseif not TwoToSix and TwoFreq then F1 = 0 F2 = 0 F3 = 0 F4 = 0 F5 = 0 F6 = 0 end local FreqCode = bit.bor(F1*1,F2*2,F3*4,F4*8,F5*16,F6*32,self.ALS*64,self.GE*128) if self.FreqCode ~= FreqCode then if not self.FreqCodeTimer then self.FreqCodeTimer = CurTime() end if self.FreqCodeTimer and CurTime()-self.FreqCodeTimer>0.8 then self.FreqCode = FreqCode self.FreqCodeTimer = nil self.F1 = F1 self.F2 = F2 self.F3 = F3 self.F4 = F4 self.F5 = F5 self.F6 = F6 self.NoFreq = (1-math.min(1,(self.F1+self.F2+self.F3+self.F4+self.F5+self.F6)))*math.min(1,self.ALS+self.GE) end elseif self.FreqCodeTimer then self.FreqCodeTimer = nil end if power or self.ALS > 0 --[[ or self.AB > 0--]] then local Vlimit = 20 if self.F4 > 0 then Vlimit = 40 end if self.F3 > 0 then Vlimit = 60 end if self.F2 > 0 then Vlimit = 70 end if self.F1 > 0 then Vlimit = 80 end -- Determine next limit and current limit self.SpeedLimit = Vlimit self.NextLimit = Vlimit if self.F1 > 0 then self.NextLimit = 80 end if self.F2 > 0 then self.NextLimit = 70 end if self.F3 > 0 then self.NextLimit = 60 end if self.F4 > 0 then self.NextLimit = 40 end if self.F5 > 0 then self.NextLimit = 20 end if self.F4 > 0 and self.F6 > 0 then self.NG = true end if TwoToSix and self.LN==0 and self.AB==0 then self.SpeedLimit=20 end if KVT and self.SpeedLimit <= 40 then self.SpeedLimit = 20 end if KVT and self.SpeedLimit > 40 then self.SpeedLimit = 40 end else self.F1 = 0 self.F2 = 0 self.F3 = 0 self.F4 = 0 self.F5 = 0 self.F6 = 0 self.SpeedLimit = 0 self.NextLimit = 0 self.NoFreq = 0 self.FreqCodeTimer = nil self.FreqCode = 0 end if Power then self.ABReady = (1-self.AB)*(FreqCount*self.ALS == 0 and 1 or 0) local ABAccept = self.ABReady > 0 --self.NoFreq--[[ *ALS.Enabled--]] > 0 if ABAccept and not self.ABPressed1 and Train.AB1.Value > 0 then self.ABPressed1 = CurTime() end if ABAccept and not self.ABPressed2 and Train.AB2.Value > 0 then self.ABPressed2 = CurTime() end if not ABAccept or Train.AB1.Value == 0 then self.ABPressed1 = nil end if not ABAccept or Train.AB2.Value == 0 then self.ABPressed2 = nil end if self.ABPressed1 and self.ABPressed2 and math.abs(self.ABPressed1-self.ABPressed2) < 1 then self.AB = 1 end self.ARS = 1-self.AB local NoFreq = (self.Freq>0 and self.LN==0) or self.NoFreq>0 self.BR2 = KVT and NoFreq and not self.BR1 self.BR1 = KVT and (self.BR1 or not NoFreq) and not self.BR2 local SpeedLimit = self.SpeedLimit if (speed > SpeedLimit) and not self.RUVD or SpeedLimit<=20 and not (self.BR1 or self.BR2) then self.RUVD = true self.RNT = self.RNT or self.KRT==0 elseif speed < SpeedLimit-0.5 and self.RUVD and not self.RNT then self.RUVD = false end if (self.BR1 or self.BR2) and self.RNT then self.RNT = false end if self.RO==true and self.KRH > 0 then self.RO = CurTime() end if self.RO and self.RO~=true and CurTime()-self.RO >7 then self.RO = false if speed<5 and not NoFreq then self.ROBrake = true end end if self.RO and speed > 5 then self.RO = false end if self.RO~=true and speed <= 5 and self.KRH == 0 then self.RO = true end if self.RO and self.BR2 then self.RO = false end if self.RUVD then if not self.PN1Timer then self.PN1Timer = CurTime()+3.5-math.max(0,(speed-20))/60*2.5 end if not self.TW8Timer then self.TW8Timer = self.SpeedLimit<=20 and CurTime()-3 or CurTime() end end if not self.RUVD then if self.PN1Timer then self.PN1Timer = false end if self.TW8Timer then self.TW8Timer = false end end local brake = (self.RUVD or self.ROBrake) and 1 or 0 local pn1 = (self.RO == true or (self.PN1Timer and CurTime()-self.PN1Timer < 0)) and 1 or 0 local pn2 = (self.TW8Timer and CurTime()-self.TW8Timer > 2.7) and 1 or 0 self["33"] = (1-self.LVD) self["33G"] = brake self["17"] = (1-self.LVD) self["2"] = brake*self.KRT self["20"] = brake self["25"] = (1-self.LVD) self["44"] = pn1 self["48"] = pn1 self["8"] = brake*pn2 self.Ring = self.RNT and 1 or 0 local delay = 3.5 if 10 < speed and speed < 30 then delay = 5.5 end if speed < 3 then delay = 10 end if (self.RUVD or speed<5 and not NoFreq) and self.KT == 0 then if not self.EPKTimer then self.EPKTimer = CurTime() end else self.EPKTimer = nil end if self.EPKTimer and CurTime()-self.EPKTimer > delay then self.EK = 0 end self.LVD = math.min(1-self.KRO,self.LVD+brake) self.LN = self.NG and self.Freq or 0 else self.BR1 = 0 self.BR2 = 0 self.EK = 1 self.AB = 0 self.ARS = 0 self.LN = 0 self.NG = false self.ABPressed1 = nil self.ABPressed2 = nil self.Ring = 0 self.ROBrake = false self.LVD = 0 self.ABReady = 0 self.RUVD = true self.RNT = true self["33"] = 0 self["33G"] = 0 self["17"] = 0 self["2"] = 0 self["20"] = 0 self["25"] = 0 self["44"] = 0 self["48"] = 0 self["8"] = 0 end self.EPK = self.GE*self.EK --Train:WriteTrainWire(90,self.EPK*(1-Train.ARS.Value)) --Train.EPKC:TriggerInput("Set",self.EPK+Train:ReadTrainWire(90)) Train.EPKC:TriggerInput("Set",self.EPK) end
local M = {} -- Get files from an exact filepath and return them as -- a lua module path -- @param path string -- @param modulepath string - A module path that can be appended -- @returns table function M.get_files_as_modules(path, modulepath) if vim.endswith(modulepath, '.') then error('[FileSystem] Cannot have `modulepath` end with `.`') end local files = {} local fs, fail = vim.loop.fs_scandir(path) if fail then error(fail) end local name, type = vim.loop.fs_scandir_next(fs) while name ~= nil do if type == 'file' then local namelist = vim.split(name, '.', true) local module = namelist[1] table.insert(files, modulepath .. '.' .. module) end -- next iterator name, type = vim.loop.fs_scandir_next(fs) end return files end return M
local test = require 'pl.test' local lapp = require 'pl.lapp' local k = 1 function check (spec,args,match) local args = lapp(spec,args) for k,v in pairs(args) do if type(v) == 'userdata' then args[k]:close(); args[k] = '<file>' end end test.asserteq(args,match) end -- force Lapp to throw an error, rather than just calling os.exit() lapp.show_usage_error = 'throw' function check_error(spec,args,msg) arg = args local ok,err = pcall(lapp,spec) test.assertmatch(err,msg) end local parmtest = [[ Testing 'array' parameter handling -o,--output... (string) -v... ]] check (parmtest,{'-o','one'},{output={'one'},v={false}}) check (parmtest,{'-o','one','-v'},{output={'one'},v={true}}) check (parmtest,{'-o','one','-vv'},{output={'one'},v={true,true}}) check (parmtest,{'-o','one','-o','two'},{output={'one','two'},v={false}}) local simple = [[ Various flags and option types -p A simple optional flag, defaults to false -q,--quiet A simple flag with long name -o (string) A required option with argument <input> (default stdin) Optional input file parameter... ]] check(simple, {'-o','in'}, {quiet=false,p=false,o='in',input='<file>'}) check(simple, {'-o','help','-q','test-lapp.lua'}, {quiet=true,p=false,o='help',input='<file>',input_name='test-lapp.lua'}) local longs = [[ --open (string) ]] check(longs,{'--open','folder'},{open='folder'}) local extras1 = [[ <files...> (string) A bunch of files ]] check(extras1,{'one','two'},{files={'one','two'}}) -- any extra parameters go into the array part of the result local extras2 = [[ <file> (string) A file ]] check(extras2,{'one','two'},{file='one','two'}) local extended = [[ --foo (string default 1) -s,--speed (slow|medium|fast default medium) -n (1..10 default 1) -p print -v verbose ]] check(extended,{},{foo='1',speed='medium',n=1,p=false,v=false}) check(extended,{'-pv'},{foo='1',speed='medium',n=1,p=true,v=true}) check(extended,{'--foo','2','-s','fast'},{foo='2',speed='fast',n=1,p=false,v=false}) check(extended,{'--foo=2','-s=fast','-n2'},{foo='2',speed='fast',n=2,p=false,v=false}) check_error(extended,{'--speed','massive'},"value 'massive' not in slow|medium|fast") check_error(extended,{'-n','x'},"unable to convert to number: x") check_error(extended,{'-n','12'},"n out of range")
local skynet = require "skynet" local mysql = require "skynet.db.mysql" require "skynet.manager" require "common.util" --[[ 用法: local dbserver = skynet.localname(".your db name") local is_succeed = skynet.call(dbserver, "lua", "insert", "insert into Table(Id) values(1)") --]] local db local function ping() while true do if db then db:query("select l;") end skynet.sleep(3600*1000) end end local CMD = {} function CMD.open( conf ) db = mysql.connect(conf) skynet.fork(ping) skynet.register(conf.name or "."..conf.database) end function CMD.close( conf ) if db then db:disconnect() db = nil end end function CMD.insert( sql ) local result = db:query(sql) if result.errno then skynet.error(result.err) return false end return true end function CMD.delete( sql ) local result = db:query(sql) if result.errno then skynet.error(result.err) return false end return true end function CMD.select( sql ) local result = db:query(sql) if result.errno then skynet.error(result.err) return false end return true, result end function CMD.update( sql ) local result = db:query(sql) if result.errno then skynet.error(result.err) return false end return true end skynet.start(function() skynet.dispatch("lua", function(session, source, cmd, ...) local f = assert(CMD[cmd], "can't not find cmd :"..(cmd or "empty")) if session == 0 then f(...) else skynet.ret(skynet.pack(f(...))) end end) end)
--[[ @ filename : master_db.lua @ author : zhangshiqian1214@163.com @ modify : 2017-08-23 17:53 @ company : zhangshiqian1214 ]] require "skynet.manager" local skynet = require "skynet" local db_config = require "config.db_config" local command = {} local db_pool = {} local db_pool_index = {} local function init_db_pool() for _, conf in pairs(db_config) do local svc_count = conf.svc_count for i=1, svc_count do local svc = skynet.newservice("master_db_svc", conf.svc_name) if conf.get_svc == GET_SVC_TYPE.unique then skynet.name(conf.service_name, svc) else skynet.name(conf.service_name..i, svc) end db_pool[conf.svc_name] = db_pool[conf.svc_name] or {} table.insert(db_pool[conf.svc_name], svc) end end end local function dispatch(session, addr, cmd, ...) local func = command[cmd] if not func then return end if session > 0 then skynet.retpack(func(...)) else func(...) end end function command.get_db_svc(svc_name) if not svc_name or not db_pool[svc_name] then return nil end db_pool_index[svc_name] = db_pool_index[svc_name] or 1 local index = db_pool_index[svc_name] local svc = db_pool[svc_name][index] if not svc then return nil end db_pool_index[svc_name] = db_pool_index[svc_name] + 1 if db_pool_index[svc_name] > #db_pool[svc_name] then db_pool_index[svc_name] = 1 end return svc end function command.start() init_db_pool() end skynet.start(function() skynet.dispatch("lua", dispatch) skynet.register(SERVICE.MASTER_DB) end)
local stf=dofile "gstuff/pwm.lua" local menu_sgn={ {name="Signal 0", ind_t=stf.ind, act=stf.acts, par=6}, {name="Signal 1", ind_t=stf.ind, act=stf.acts, par=5}, {name=" ..main menu"} } stf=nil return menu_sgn
-- pastebin run -f B5pvDmYi -- openDHD from Asher9 -- https://github.com/Asher9/Asher9-s-Programms/tree/master/openDHD local fs = fs or require("filesystem") local NEU = ... local standard = loadfile("/stargate/Sicherungsdatei.lua") local Sicherung = {} local sprachen = {} local ALT = {} if fs.exists("/einstellungen/Sicherungsdatei.lua") then ALT = loadfile("/einstellungen/Sicherungsdatei.lua")() end if type(ALT) ~= "table" then ALT = {} end if standard then standard = standard() else standard = {autoclosetime = 60, IDC = "", time = 5, RF = false, Sprache = "", side = "unten", autoUpdate = true, StargateName = "", Port = 645, debug = false, control = "On", installieren = false} end local function reset() return { speichern = 'zum speichern drücke "Strg + S"', schliessen = 'zum schließen drücke "Strg + W"', autoclosetime = "in Sekunden -- false für keine automatische Schließung", IDC = "Iris Deaktivierungscode", time = "second for self destruction", RF = "zeige Energie in RF anstatt in EU", Sprache = "deutsch / english / russian / czech", side = "unten, oben, hinten, vorne, rechts oder links", autoUpdate = "aktiviere automatische Aktualisierungen", Port = "standard 645", debug = "zum debuggen", nichtsAendern = "verändere nichts ab hier", StargateName = "der Name dieses Stargates", } end if type(NEU) == "table" then sprachen = loadfile("/stargate/sprache/" .. tostring(NEU.Sprache) .. ".lua") or loadfile("/stargate/sprache/" .. tostring(ALT.Sprache) .. ".lua") or loadfile("/stargate/sprache/deutsch.lua") or reset local _, sprachen = pcall(sprachen) if type(sprachen) ~= "table" then sprachen = reset() end if type(NEU.autoclosetime) == "number" or NEU.autoclosetime == false then Sicherung.autoclosetime = NEU.autoclosetime elseif type(ALT.autoclosetime) == "number" or ALT.autoclosetime == false then Sicherung.autoclosetime = ALT.autoclosetime else Sicherung.autoclosetime = standard.autoclosetime end local function check(typ, name) if type(NEU[name]) == typ then Sicherung[name] = NEU[name] elseif type(ALT[name]) == typ then Sicherung[name] = ALT[name] else Sicherung[name] = standard[name] end end check("string" , "StargateName") check("string" , "IDC") check("number" , "time") check("boolean", "RF") check("string" , "Sprache") check("string" , "side") check("boolean", "autoUpdate") check("number" , "Port") check("boolean", "debug") check("string" , "control") check("boolean", "installieren") local f = io.open ("/einstellungen/Sicherungsdatei.lua", "w") f:write('-- pastebin run -f B5pvDmYi\n') f:write('-- openDHD from Asher9\n') f:write('-- https://github.com/Asher9/Asher9-s-Programms/tree/master/openDHD\n--\n') f:write('-- ' .. tostring(sprachen.speichern) .. '\n') f:write('-- ' .. tostring(sprachen.schliessen) .. '\n--\n\n') f:write('return {\n') if Sicherung.autoclosetime == false then f:write(' autoclosetime = false, -- ' .. tostring(sprachen.autoclosetime) .. '\n') else f:write(' autoclosetime = ' .. tostring(Sicherung.autoclosetime).. ', -- ' .. tostring(sprachen.autoclosetime) .. '\n') end f:write(' IDC = "' .. tostring(Sicherung.IDC) .. '", -- ' .. tostring(sprachen.IDC) .. '\n') f:write(' time = ' .. tostring(Sicherung.time) .. ', -- Countdown for self destruction\n') f:write(' RF = ' .. tostring(Sicherung.RF) .. ', -- ' .. tostring(sprachen.RF) .. '\n') f:write(' Sprache = "' .. tostring(Sicherung.Sprache) .. '", -- deutsch / english / russian / czech\n') f:write(' side = "' .. tostring(Sicherung.side) .. '", -- ' .. tostring(sprachen.side) .. '\n') f:write(' autoUpdate = ' .. tostring(Sicherung.autoUpdate) .. ', -- ' .. tostring(sprachen.autoUpdate) .. '\n') f:write(' StargateName = "' .. tostring(Sicherung.StargateName) .. '", -- ' .. tostring(sprachen.StargateName) .. '\n') f:write(' Port = ' .. tostring(Sicherung.Port) .. ', -- ' .. tostring(sprachen.Port) .. '\n') f:write('\n') f:write(string.rep("-", 10) .. tostring(sprachen.nichtsAendern) .. string.rep("-", 60 - string.len(tostring(sprachen.nichtsAendern))) .. '\n') f:write('\n') f:write(' debug = ' .. tostring(Sicherung.debug) .. ', -- ' .. tostring(sprachen.debug) .. '\n') f:write(' control = "' .. tostring(Sicherung.control) .. '",\n') f:write(' installieren = ' .. tostring(Sicherung.installieren) .. ',\n') f:write('}') f:close() return true end
-- https://github.com/Lautenschlager-id/prepdir local prepdir do local format = string.format local gsub = string.gsub local match = string.match local sub = string.sub local rep = string.rep local conditionalSymbols = { ['&'] = "and", ['|'] = "or", ['!'] = "not ", ["!="] = "~=" } local symbolReplace = "[&|!]=?" local prefix = "()\t*@#" local endOfLine = "\r?\n()" local expression = "([%w_ %+%-%*/%[%]%(%){}&|!%.<>~='\"]+)" local tokenCallbacks = { } local tokenMatchers = { IF = prefix .. "IF " .. expression .. endOfLine, ELIF = prefix .. "ELIF " .. expression .. endOfLine, ELSE = prefix .. "ELSE" .. endOfLine, ENDIF = prefix .. "ENDIF" .. endOfLine, __NEXT = prefix .. "(%S+)" } local READING_CHUNK, chunks = false tokenCallbacks.IF = function(src, endPos) if READING_CHUNK then return end local iniPos, condition, endPos = match(src, tokenMatchers.IF, endPos) if not iniPos then return end READING_CHUNK = true chunks[#chunks + 1] = { __len = 1, c = { [1] = { iniPos = iniPos, endPos = endPos, condition = condition } } } return endPos end tokenCallbacks.ELIF = function(src, endPos) if not READING_CHUNK then return end local iniPos, condition, endPos = match(src, tokenMatchers.ELIF, endPos) assert(iniPos) local chunk = chunks[#chunks] chunk.__len = chunk.__len + 1 chunk.c[chunk.__len] = { iniPos = iniPos, endPos = endPos, condition = condition } return endPos end tokenCallbacks.ELSE = function(src, endPos) if not READING_CHUNK then return end local iniPos, endPos = match(src, tokenMatchers.ELSE, endPos) assert(iniPos) local chunk = chunks[#chunks] chunk.__len = chunk.__len + 1 chunk.c[chunk.__len] = { iniPos = iniPos, endPos = endPos, condition = "true" } return endPos end tokenCallbacks.ENDIF = function(src, endPos) if not READING_CHUNK then return end local iniPos, endPos = match(src, tokenMatchers.ENDIF, endPos) if not iniPos then return end READING_CHUNK = false local chunk = chunks[#chunks] chunk.c.endif = { iniPos = iniPos, endPos = endPos } return endPos end tokenCallbacks.__NEXT = function(src, endPos) local iniPos, token = match(src, tokenMatchers.__NEXT, endPos) if not iniPos then return end return token end local parser = function(src) READING_CHUNK, chunks = false, { } local endPos, ifPos repeat -- Opens the conditional endPos = tokenCallbacks.IF(src, endPos) if not endPos then break end ifPos = endPos -- Gets all sub conditionals local nextToken repeat nextToken = tokenCallbacks.__NEXT(src, endPos) if nextToken == "ELIF" then endPos = tokenCallbacks.ELIF(src, endPos) else break end until false -- Check of else if nextToken == "ELSE" then endPos = tokenCallbacks.ELSE(src, endPos) nextToken = nil end -- Finish conditional nextToken = nextToken or tokenCallbacks.__NEXT(src, endPos) if nextToken ~= "ENDIF" then error(string.format("[PREPDIR] @[%d:] Mandatory token ENDIF to close \z token IF in @[%d]", endPos, ifPos)) end endPos = tokenCallbacks.ENDIF(src, endPos) until false local cc for c = 1, #chunks do c = chunks[c] cc = c.c for sc = 1, c.__len do sc = cc[sc] sc.condition = gsub(sc.condition, symbolReplace, conditionalSymbols) end end end local evaluateCondition = function(condition, settings) return load("return " .. condition, '', 't', settings)() end local sliceString = function(str, boundaries) assert(#boundaries % 2 == 0) for b = #boundaries, 1, -2 do local _, totalLines = gsub(sub(str, boundaries[b - 1], boundaries[b] - 1), '\n', '') str = sub(str, 1, boundaries[b - 1] - 1) .. rep('\n', totalLines) .. sub(str, boundaries[b]) end return str end local matcher = function(src, settings) local boundaries, totalBoundaries = { }, 0 local cc, scObj for c = 1, #chunks do c = chunks[c] cc = c.c totalBoundaries = totalBoundaries + 1 boundaries[totalBoundaries] = cc[1].iniPos for sc = 1, c.__len do scObj = cc[sc] if evaluateCondition(scObj.condition, settings) then totalBoundaries = totalBoundaries + 1 boundaries[totalBoundaries] = scObj.endPos totalBoundaries = totalBoundaries + 1 boundaries[totalBoundaries] = (cc[sc + 1] or cc.endif).iniPos break end end totalBoundaries = totalBoundaries + 1 boundaries[totalBoundaries] = cc.endif.endPos end return sliceString(src, boundaries) end prepdir = function(src, settings) -- Retrieve src = src .. "\n" -- For pattern matching -- Get chunks parser(src) src = matcher(src, settings) return sub(src, 1, -2) end end return prepdir
local resolver_cache = require 'resty.resolver.cache' describe('resty.resolver.cache', function() local answers = { { class = 1, cname = "elb.example.com", name = "www.example.com", section = 1, ttl = 599, type = 5 }, { class = 1, cname = "example.us-east-1.elb.amazonaws.com", name = "elb.example.com", section = 1, ttl = 299, type = 5 }, { address = "54.221.208.116", class = 1, name = "example.us-east-1.elb.amazonaws.com", section = 1, ttl = 59, type = 1 }, { address = "54.221.221.16", class = 1, name = "example.us-east-1.elb.amazonaws.com", section = 1, ttl = 59, type = 1 } } describe('.save', function() local c = resolver_cache.new() it('returns compacted answers', function() local keys = {} for _,v in ipairs(c:save(answers)) do table.insert(keys, v.name) end assert.same( {'www.example.com', 'elb.example.com', 'example.us-east-1.elb.amazonaws.com' }, keys) end) it('stores the result', function() c.store = spy.new(c.store) c:save(answers) assert.spy(c.store).was.called(3) -- TODO: proper called_with(args) end) end) describe('.store', function() local cache = {} local c = resolver_cache.new(cache) it('writes to the cache', function() local record = { 'someting' } local answer = { record, ttl = 60, name = 'foo.example.com' } c.cache.set = spy.new(function(_, key, value, ttl) assert.same('foo.example.com', key) assert.same(answer, value) assert.same(60, ttl) end) c:store(answer) assert.spy(c.cache.set).was.called(1) end) it('works with -1 ttl', function() local answer = { { 'something' }, ttl = -1, name = 'foo.example.com' } c.cache.set = spy.new(function(_, key, value, ttl) assert.same('foo.example.com', key) assert.same(answer, value) assert.same(nil, ttl) end) c:store(answer) assert.spy(c.cache.set).was.called(1) end) end) describe('.get', function() local c = resolver_cache.new() it('returns answers', function() c:save(answers) local ans = c:get('www.example.com') assert.same({ "54.221.208.116", "54.221.221.16" }, ans.addresses) end) end) end)
function stdout(...) print(...) end
--MoveCurve --H_Tohka/curve_Attack_3 curve_Attack_3 return { filePath = "H_Tohka/curve_Attack_3", startTime = Fixed64(17825792) --[[17]], startRealTime = Fixed64(267387) --[[0.255]], endTime = Fixed64(24117248) --[[23]], endRealTime = Fixed64(361759) --[[0.345]], isZoom = false, isCompensate = false, curve = { [1] = { time = 0 --[[0]], value = 0 --[[0]], inTangent = 4194304 --[[4]], outTangent = 4194304 --[[4]], }, [2] = { time = 1048576 --[[1]], value = 4194304 --[[4]], inTangent = 4194304 --[[4]], outTangent = 4194304 --[[4]], }, }, }
-- script containing supporting code/methods local utils = {}; cjson = require 'cjson' -- right align the question tokens in 3d volume function utils.rightAlign(sequences, lengths) -- clone the sequences local rAligned = sequences:clone():fill(0); local numDims = sequences:dim(); if numDims == 3 then local M = sequences:size(3); -- maximum length of question local numImgs = sequences:size(1); -- number of images local maxCount = sequences:size(2); -- number of questions / image for imId = 1, numImgs do for quesId = 1, maxCount do -- do only for non zero sequence counts if lengths[imId][quesId] == 0 then break; end -- copy based on the sequence length rAligned[imId][quesId][{{M - lengths[imId][quesId] + 1, M}}] = sequences[imId][quesId][{{1, lengths[imId][quesId]}}]; end end else if numDims == 2 then -- handle 2 dimensional matrices as well local M = sequences:size(2); -- maximum length of question local numImgs = sequences:size(1); -- number of images for imId = 1, numImgs do -- do only for non zero sequence counts if lengths[imId] > 0 then -- copy based on the sequence length rAligned[imId][{{M - lengths[imId] + 1, M}}] = sequences[imId][{{1, lengths[imId]}}]; end end end end return rAligned; end -- translate a table of words to index tensor function utils.wordsToId(words, word2ind, max_len) local len = max_len or 15 local vector = torch.LongTensor(len):zero() for i = 1, #words do if word2ind[words[i]] ~= nil then vector[len - #words + i] = word2ind[words[i]] else vector[len - #words + i] = word2ind['UNK'] end end return vector end -- translate a given tensor/table to sentence function utils.idToWords(vector, ind2word) local sentence = ''; local nextWord; for wordId = 1, vector:size(1) do if vector[wordId] > 0 then nextWord = ind2word[vector[wordId]]; sentence = sentence..' '..nextWord; end -- stop if end of token is attained if nextWord == '<END>' then break; end end return sentence; end -- read a json file and lua table function utils.readJSON(fileName) local file = io.open(fileName, 'r'); local text = file:read(); file:close(); -- convert and save information return cjson.decode(text); end -- save a lua table to the json function utils.writeJSON(fileName, luaTable) -- serialize lua table local text = cjson.encode(luaTable) local file = io.open(fileName, 'w'); file:write(text); file:close(); end -- compute the likelihood given the gt words and predicted probabilities function utils.computeLhood(words, predProbs) -- compute the probabilities for each answer, based on its tokens -- convert to 2d matrix local predVec = predProbs:view(-1, predProbs:size(3)); local indices = words:contiguous():view(-1, 1); local mask = indices:eq(0); -- assign proxy values to avoid 0 index errors indices[mask] = 1; local logProbs = predVec:gather(2, indices); -- neutralize other values logProbs[mask] = 0; logProbs = logProbs:viewAs(words); -- sum up for each sentence logProbs = logProbs:sum(1):squeeze(); return logProbs; end -- process the scores and obtain the ranks -- input: scores for all options, ground truth positions function utils.computeRanks(scores, gtPos) local gtScore = scores:gather(2, gtPos); local ranks = scores:gt(gtScore:expandAs(scores)); ranks = ranks:sum(2) + 1; -- convert into double return ranks:double(); end -- process the ranks and print metrics function utils.processRanks(ranks) -- print the results local numQues = ranks:size(1) * ranks:size(2); local numOptions = 100; -- convert ranks to double, vector and remove zeros ranks = ranks:double():view(-1); -- non of the values should be 0, there is gt in options if torch.sum(ranks:le(0)) > 0 then numZero = torch.sum(ranks:le(0)); print(string.format('Warning: some of ranks are zero : %d', numZero)) ranks = ranks[ranks:gt(0)]; end if torch.sum(ranks:ge(numOptions + 1)) > 0 then numGreater = torch.sum(ranks:ge(numOptions + 1)); print(string.format('Warning: some of ranks >100 : %d', numGreater)) ranks = ranks[ranks:le(numOptions + 1)]; end ------------------------------------------------ print(string.format('\tNo. questions: %d', numQues)) print(string.format('\tr@1: %f', torch.sum(torch.le(ranks, 1))/numQues)) print(string.format('\tr@5: %f', torch.sum(torch.le(ranks, 5))/numQues)) print(string.format('\tr@10: %f', torch.sum(torch.le(ranks, 10))/numQues)) print(string.format('\tmedianR: %f', torch.median(ranks:view(-1))[1])) print(string.format('\tmeanR: %f', torch.mean(ranks))) print(string.format('\tmeanRR: %f', torch.mean(ranks:cinv()))) end function utils.preprocess(path, width, height) local width = width or 224 local height = height or 224 -- load image local orig_image = image.load(path) -- handle greyscale and rgba images if orig_image:size(1) == 1 then orig_image = orig_image:repeatTensor(3, 1, 1) elseif orig_image:size(1) == 4 then orig_image = orig_image[{{1,3},{},{}}] end -- get the dimensions of the original image local im_height = orig_image:size(2) local im_width = orig_image:size(3) -- scale and subtract mean local img = image.scale(orig_image, width, height):double() local mean_pixel = torch.DoubleTensor({103.939, 116.779, 123.68}) img = img:index(1, torch.LongTensor{3, 2, 1}):mul(255.0) mean_pixel = mean_pixel:view(3, 1, 1):expandAs(img) img:add(-1, mean_pixel) return img, im_height, im_width end return utils;
return { [1] = {x4=1,x1=true,x2=4,x3=128,x5=112233445566,x6=1.3,x7=1112232.43123,x8_0=123,x8=112233,x9=112334,x10='yf',x12={x1=1,},x13=4,x14={ _name='DemoD2',x1=1,x2=2,},s1='xml text',v2={x=1,y=2},v3={x=1.2,y=2.3,z=3.4},v4={x=1.2,y=2.2,z=3.2,w=4.3},t1=-28800,k1={1,2,},k2={1,2,},k3={1,2,},k4={1,2,},k5={1,2,},k6={1,2,},k7={1,3,},k8={[2]=10,[3]=30,},k9={{y1=1,y2=true,},{y1=2,y2=false,},},k15={{ _name='DemoD2',x1=1,x2=2,},},}, [2] = {x4=2,x1=true,x2=4,x3=128,x5=112233445566,x6=1.3,x7=1112232.43123,x8_0=123,x8=112233,x9=112334,x10='yf',x12={x1=1,},x13=4,x14={ _name='DemoD2',x1=1,x2=2,},s1='xml text222',v2={x=1,y=2},v3={x=1.2,y=2.3,z=3.4},v4={x=1.2,y=2.2,z=3.2,w=4.3},t1=-28800,k1={1,2,},k2={1,2,},k3={1,2,},k4={1,2,},k5={1,2,},k6={1,2,},k7={1,3,},k8={[2]=10,[3]=30,},k9={{y1=1,y2=true,},{y1=2,y2=false,},},k15={{ _name='DemoD2',x1=1,x2=2,},},}, }
-- 迭代器 function values( t ) local i = 0 return function () i = i + 1; return t[i] end end -- 使用迭代器 t = {10, 20, 30} iter = values(t) while true do local element = iter() if element == nil then break end print(element) end -- 泛型for for element in values(t) do print(element) end
local com = require("component") local debug = com.debug local modem = com.modem local module = require("ut3-gm.module") local config = module.load("config") local events = module.load("events") local store = module.load("store") local engine = events.engine modem.setStrength(400) engine:subscribe("debug-message", events.priority.high, function(hdr, evt) local data = evt:get() -- process messages here end) engine:subscribe("send-message", events.priority.low, function(hdr, evt) if evt.to == "drone" then local addresses if evt.addresses then addresses = evt.addresses else addresses = {} for k, v in pairs(store.drones) do if (not v.team or v.team == evt.team) and (not evt.aliveOnly or v.alive) then table.insert(addresses, v.address) end end end for k, v in pairs(addresses) do modem.send(v, config.network.port, "gm", table.unpack(evt:get())) end elseif evt.to == "checkpoint" then -- send the message to the checkpoint elseif not evt.to then -- broadcast modem.broadcast(config.network.port, "gm", table.unpack(evt:get())) else local address if evt.to == "control" then address = config.addresses.control[evt.team] elseif evt.to == "infopanel" then address = config.addresses.infopanels[evt.infopanel] elseif evt.to == "glasses" then address = config.addresses.glasses elseif evt.to == "lamp" then address = config.addresses.lamp elseif evt.to == "radio" then address = config.addresses.radio end debug.sendToDebugCard(address, "gm", table.unpack(evt:get())) end end)
local Suite = require "loop.test.Suite" local Template = require "oil.dtests.Template" local template = Template{"Client"} -- master process name Server = [=====================================================================[ checks = oil.dtests.checks Interceptor = {} function Interceptor:receiverequest(request) if request.object_key == "object" and request.operation_name == "concat" then request.success = false request.results = { orb:newexcept{ "CORBA::NO_PERMISSION", completed = "COMPLETED_NO", minor = 321, } } end end function Interceptor:sendreply(request) if request.object_key == "object" and request.operation_name == "concat" then assert(request.success == false) checks.assert(request.results[1], checks.like{ _repid = "IDL:omg.org/CORBA/NO_PERMISSION:1.0", completed = "COMPLETED_NO", minor = 321, }) request.results[1].minor = 123 end end orb = oil.dtests.init{ port = 2809 } orb:setserverinterceptor(Interceptor) orb:loadidl[[ interface MyInterface { string concat(in string str1, in string str2); }; ]] orb:newservant({}, "object", "::MyInterface") orb:run() --[Server]=====================================================================] Client = [=====================================================================[ checks = oil.dtests.checks orb = oil.dtests.init() sync = oil.dtests.resolve("Server", 2809, "object") async = orb:newproxy(sync, "asynchronous") prot = orb:newproxy(sync, "protected") ok, res = pcall(sync.concat, sync, "first", "second") assert(ok == false) checks.assert(res, checks.like{ _repid = "IDL:omg.org/CORBA/NO_PERMISSION:1.0", completed = "COMPLETED_NO", minor = 123, }) ok, res = async:concat("first", "second"):results() assert(ok == false) checks.assert(res, checks.like{ _repid = "IDL:omg.org/CORBA/NO_PERMISSION:1.0", completed = "COMPLETED_NO", minor = 123, }) ok, res = prot:concat("first", "second") assert(ok == false) checks.assert(res, checks.like{ _repid = "IDL:omg.org/CORBA/NO_PERMISSION:1.0", completed = "COMPLETED_NO", minor = 123, }) orb:shutdown() --[Client]=====================================================================] return template:newsuite{ corba = true, interceptedcorba = true }
local Block = {} Block.__index = Block function Block.create(def, game) local block = { x = def.x, y = def.y, width = def.width, height = def.height, game = game } setmetatable(block, Block) game.world:add(block, block.x, block.y, block.width, block.height) return block end function Block:update(dt) end function Block:draw() end return Block
-- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!! -- This file is automaticly generated. Don't edit manualy! -- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!! ---@class C_ScenarioInfo C_ScenarioInfo = {} ---@alias JailersTowerType number|"Enum.JailersTowerType.TwistingCorridors"|"Enum.JailersTowerType.SkoldusHalls"|"Enum.JailersTowerType.FractureChambers"|"Enum.JailersTowerType.Soulforges"|"Enum.JailersTowerType.Coldheart"|"Enum.JailersTowerType.Mortregar"|"Enum.JailersTowerType.UpperReaches"
local server = require "nvim-lsp-installer.server" local path = require "nvim-lsp-installer.path" local zx = require "nvim-lsp-installer.installers.zx" local root_dir = server.get_server_root_path "terraform" return server.Server:new { name = "terraformls", root_dir = root_dir, installer = zx.file "./install.mjs", default_options = { cmd = { path.concat { root_dir, "terraform-ls", "terraform-ls" }, "serve" }, }, }
local AddonName, AddonTable = ... AddonTable.freehold = { -- Skycap'n Kragg 159633, -- Sharkbait's Fishhook 155884, -- Parrotfeather Cloak 159227, -- Silk Cuffs of the Skycap'm 159353, -- Chain-Linked Safety Cord 158360, -- Sharkbait Harness Girdle 155862, -- Kragg's Rigging Scalers -- Council o' Captains 159132, -- Jolly's Boot Dagger 159130, -- Captain's Diplomacy 158311, -- Concealed Fencing Plates 159356, -- Raoul's Barrelhook Bracers 158346, -- Sailcloth Waistband 159297, -- Silver-Trimmed Breeches 158351, -- Dashing Bilge Rat Shoes 158314, -- Seal of Questionable Loyalties -- Ring of Booty 159634, -- Jeweled Sharksplitter 158305, -- Sea Dog's Cuffs 155892, -- Bite-Resistant Chain Gloves 155891, -- Greasy Bacon-Grabbers 155889, -- Sharkhide Grips 155890, -- Sharktooth-Knuckled Grips 158302, -- Chum-Coated Leggings 158361, -- Sharkwater Waders 158356, -- Shell-Kickers -- Harlan Sweete 159842, -- Sharkbait's Favorite Crackers [Mount] 159635, -- Bloody Tideturner 155888, -- Irontide Captain's Hat 155885, -- Sea-Brawler's Greathelm 155886, -- Smartly Plumed Cap 155887, -- Sweete's Jeweled Headgear 159352, -- Gaping Maw Shoulderguard 159299, -- Gold-Tasseled Epaulets 159407, -- Lockjaw Shoulderpads 158301, -- Ruffled Poet Blouse 155881, -- Harlan's Loaded Dice }
local awful = require("awful") local wibox = require("wibox") local wb = awful.wibar { position = 'top' } wb:setup { layout = wibox.layout.align.horizontal, { -- Rotate the widgets with the container { mytaglist, direction = 'west', widget = wibox.container.rotate }, layout = wibox.layout.fixed.horizontal, }, mytasklist, { layout = wibox.layout.fixed.horizontal, { -- Rotate the widgets with the container { mykeyboardlayout, mytextclock, layout = wibox.layout.fixed.horizontal }, direction = 'west', widget = wibox.container.rotate } }, }
--[[ Licensed under GNU General Public License v2 * (c) 2014, Luke Bonham --]] local helpers = require("lain.helpers") local textbox = require("wibox.widget.textbox") local setmetatable = setmetatable -- Template for custom asynchronous widgets -- lain.widgets.abase local function worker(args) local abase = {} local args = args or {} local timeout = args.timeout or 5 local nostart = args.nostart or false local stoppable = args.stoppable or false local cmd = args.cmd local settings = args.settings or function() widget:set_text(output) end abase.widget = args.widget or textbox() function abase.update() helpers.async(cmd, function(f) output = f if output ~= abase.prev then widget = abase.widget settings() abase.prev = output end end) end abase.timer = helpers.newtimer(cmd, timeout, abase.update, nostart, stoppable) return abase end return setmetatable({}, { __call = function(_, ...) return worker(...) end })
-- Copyright (C) by lework local next = next local type = type local pairs = pairs local lower = string.lower local tostring = tostring local ngx_re_find = ngx.re.find local _M = {} function _M.string_filter(str, filter) local result = 0 if str ~= nil and filter ~= nil then for _,subReg in pairs(filter) do if ngx_re_find(lower(str), subReg, "iojs") then ngx.log(ngx.ERR, "Match waf rule: " .. subReg .. ':' .. str) result = 1 break end end end return result end function _M.table_filter(table, filter) if table ~= nil and next(filter) and next(table) then for _, val in pairs(table) do if val ~= nil and type(val) == "table" then if _M.table_filter(val, filter) == 1 then return 1 end elseif val ~= nil then if val == true then val = _ end if _M.string_filter(tostring(val),filter) == 1 then return 1 end end end end return 0 end return _M
function ExistsInTbl(haystack, needle) for i=1,#haystack do if haystack[i] == needle then return true end end return false end Settings = GetSettings() dofile(GetModPath() .. "/Resources/lib/P3D.lua") dofile(GetModPath() .. "/Resources/lib/P3DFunctions.lua") ModifierType = Settings.ModifierType if ModifierType == 1 then Modifier = Settings.ModifyAmount if Modifier > 2147483647 then Modifier = Modifier - 4294967296 end print("Using modifier: " .. Modifier) elseif ModifierType == 2 then Percentage = Settings.PercentageAmount / 100 print("Using percentage: " .. Settings.PercentageAmount .. "%") elseif ModifierType == 3 then local Value = Settings.FixedColour Alpha = Value >> 24 Red = (Value >> 16) & 0xFF Green = (Value >> 8) & 0xFF Blue = Value & 0xFF print("Using ARGB: " .. Alpha .. "," .. Red .. "," .. Green .. "," .. Blue) end PreLoad = Settings.PreLoadData Cache = {} if Settings.ModSandbox and not EnvIsModSandbox then dofile(GetModPath() .. "/Resources/lib/ModSandbox.lua") MainModSandbox = ModSandbox.Sandbox:InitFromMainMod(true) IsSandbox = MainModSandbox ~= nil end if PreLoad then Alert("Pre-loading files. Please wait.") local files = {} local function GetFiles(tbl, dir, extensions) if dir:sub(-1) ~= "/" then dir = dir .. "/" end DirectoryGetEntries(dir, function(name, directory) if directory then if name:sub(-1) ~= "/" then name = name .. "/" end GetFiles(tbl, dir .. name, extensions) elseif extensions then for i = 1, #extensions do local extension = extensions[i] if GetFileExtension(name) == extension then tbl[#tbl + 1] = FixSlashes(dir .. name, false, true) break end end else tbl[#tbl + 1] = FixSlashes(dir .. name, false, true) end return true end) end local startTime = GetTime() GetFiles(files, "/GameData/art", {".p3d"}) local filesN = #files local count = 0 for i=1,filesN do local filePath = files[i] if WildcardMatch(filePath, "/GameData/Art/l*", true, true) or WildcardMatch(filePath, "/GameData/art/nis/gags/*", true, true) or WildcardMatch(filePath, "/GameData/art/frontend/scrooby/resource/pure3d/camset*", true, true) then local file, modified if ModifierType == 1 then file, modified = BrightenModel(ReadFile(filePath), Modifier, false) elseif ModifierType == 2 then file, modified = BrightenModel(ReadFile(filePath), Percentage, true) elseif ModifierType == 3 then file, modified = SetModelRGB(ReadFile(filePath), Alpha, Red, Green, Blue) end if modified then count = count + 1 Cache[filePath] = file end end print("Processed file \"" .. GetFileName(filePath) .. "\" (" .. i .. "/" .. filesN .. ")") end local endTime = GetTime() Alert(count .. " files cached in " .. (endTime - startTime) .. " seconds.") print("Cached " .. count .. " files.") end
--[[ Copyright (C) 2015 Real-Time Innovations, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --- Datatypes in Lua. -- Uses the `ddsl` core primitives to implement datatypes (a.k.a. `xtypes`) as -- defined by the OMG X-Types specification in Lua. -- -- The datatypes are equivalent to those described by the [X-Types]( -- http://www.omg.org/spec/DDS-XTypes/) specification. Thus, this module -- can serve as an alternative for defining types in Lua, instead of in [IDL]( -- https://en.wikipedia.org/wiki/Interface_description_language) or XML. -- -- A datatype is a blueprint for a data structure. Any -- number of data-objects or instances (a.k.a. `xinstance`) can be created -- from a datatype. Each instance is backed by the underlying datatype from -- which it was created. The datatype constraints are enforced on the -- instances---for example a `struct` instance can only have the fields defined -- in the `struct` datatype; sequence and array bounds are enforced. -- Furthermore, if the datatype structure changes, those changes are propagated -- to all the instances. -- -- Operators to manipulate datatypes (i.e. structure) are also provided. Thus, -- for a `struct` datatype, new members can be added, existing ones can be -- removed or modified. Since every instance is backed by a datatype, any -- instance can be used as a handle to manipulate the underlying datatype. -- Changes are propagated to all the other instances, to ensure consistency. -- -- Since every instance is backed by a datatype, a new instance can be created -- from any instance using `new_instance`. A datatype constructor returns -- a *template instance* (a.k.a. `xtemplate`) that can be used as cannonical -- instance to refer to the datatype. -- -- Each field in the template instance is -- initialized to a flattened out accessor `string` that can be used retrive -- that field's value in some storage system. For example, the accessor strings -- can be directly used for data access in Lua scripts used with the -- *RTI Connext DDS Prototyper* (see **Section 8.4, Data Access API** in the -- [RTI Connext DDS Prototyper Getting Started Guide]( -- https://community.rti.com/static/documentation/connext-dds/5.2.0/doc/manuals/connext_dds/prototyper/RTI_ConnextDDS_CoreLibraries_Prototyper_GettingStarted.pdf)). -- -- -- **General Syntax** -- -- Since `ddsl` does not impose any specific syntax on how datatypes are -- expressed in Lua, this module defines the syntax. The general syntax and -- patterns common to all datatypes are illsurated below. -- -- local xtypes = require 'ddsl.xtypes' -- -- -- create a datatype of kind 'kind' with the name 'MyType' -- -- NOTE: `mytype` is the template instance for `MyType` (i.e. `xtemplate`) -- local mytype = xtypes.<kind>{ -- MyType = { <definition_syntax_for_kind> } -- } -- -- -- -- create an instance to use in user application code -- local myinstance = xtypes.`new_instance`(mytype) -- -- -- print the datatype underlying an instance -- print(tostring(myinstance)) -- or simply -- print(myinstance) -- -- -- -- get the template instance -- assert(xtypes.`template`(myinstance) == mytype) -- -- -- -- print the kind of a datatype -- -- NOTE: the kind is immutable, i.e. cannot be changed after creation -- print(mytype[xtypes.`KIND`]()) -- -- -- -- get the name of a datatype -- print(mytype[xtypes.`NAME`]) -- -- -- set the name of a datatype -- mytype[xtypes.`NAME`] = 'MyTypeNewName' -- -- -- -- get the enclosing namespace of a datatype -- print(mytype[xtypes.`NS`]) -- -- -- set the enclosing namespace of a datatype -- mytype[xtypes.`NS`] = `YourType` -- defined elsewhere; maybe `nil` -- -- -- -- get the qualifiers associated with a datatype -- print(mytype[xtypes.`QUALIFIERS`]) -- -- -- set the qualifiers associated with a datatype -- mytype[xtypes.`QUALIFIERS`] = { -- xtypes.`Nested`, -- xtypes.`Extensibility`{'FINAL_EXTENSIBILITY'}, -- } -- -- -- Get the qualified name (i.e. scoped name) of a datatype: -- print(xtypes.`nsname`(mytype) -- -- -- Get the outermost enclosing scope of a datatype: -- print(xtypes.`nsroot`(mytype) -- -- The datatype constructors provide more usage examples, specific to each type. -- -- @module ddsl.xtypes -- @alias xtypes.builtin -- @author Rajive Joshi local xtypes = { --- Datatype Kinds. -- -- Use these to get and set the corresponding datatype attribute. -- @usage -- -- get the kind of a datatype -- print(mytype[`KIND`]()) -- evaluate the kind to get the description -- -- -- use the kind of a datatype to make decisions -- if `STRUCT` == mytype[`KIND`] then -- ... -- else -- ... -- end -- @section Kind --- Annotation kind. -- @treturn string 'annotation' ANNOTATION = function() return 'annotation' end, --- `atom` kind. -- @treturn string 'atom' ATOM = function() return 'atom' end, --- `enum`eration kind. -- @treturn string 'enum' ENUM = function() return 'enum' end, --- `struct` kind. -- @treturn string 'struct' STRUCT = function() return 'struct' end, --- `union` kind. -- @treturn string 'union' UNION = function() return 'union' end, --- `typedef` kind. -- @treturn string 'typedef' TYPEDEF = function() return 'typedef' end, --- `const`ant kind. -- @treturn string 'const' CONST = function() return 'const' end, --- `module` kind. -- @treturn string 'module' MODULE = function() return 'module' end, --- @section end --==========================================================================-- --- Concrete X-Types model info interface. -- @local info = {}, --- Meta-tables that define/control the Public API for the X-Types. -- @local API = {}, --- Builtins. -- @local builtin = {}, } --============================================================================-- -- Local bindings for selected DDSL functionality -- Instantiate the DDSL core, using the 'info' interface defined here: local _ = require('ddsl')(xtypes.info) local log = _.log --- `ddsl.EMPTY`: Empty datatype definition for use as initializer in -- datatype constructors. -- @usage -- local xtypes = require 'ddsl.xtypes' -- -- -- create an empty datatype of kind 'kind' with the name 'MyType' -- local mytype = xtypes.<kind>{ -- MyType = EMPTY -- } -- @table EMPTY local EMPTY = _.EMPTY --- Datatype Attributes. -- -- Use these to get and set the corresponding datatype attribute. -- @usage -- -- get the name of a datatype -- print(mytype[NAME]) -- -- -- set the name of a datatype -- mytype[NAME] = 'MyTypeNewName' -- @section DatatypeAttributes --- `ddsl.KIND`: Datatype kind. -- @function KIND local KIND = _.KIND --- `ddsl.NAME`: Datatype name. -- @function NAME local NAME = _.NAME --- `ddsl.NS`: Datatype enclosing namespace (enclosing scope). -- @function NS local NS = _.NS --- `ddsl.QUALIFIERS`: Datatype qualifiers (annotations). -- @function QUALIFIERS local QUALIFIERS = _.QUALIFIERS --- Datatype of the base `struct` (inheritance) -- @treturn string ' : ' -- @function BASE local BASE = function() return ' : ' end --- Datatype of a `union` discriminator (switch). -- @treturn string 'switch' -- @function SWITCH local SWITCH = function() return 'switch' end --- @section end --============================================================================-- -- DDSL info interface implementation for X-Types --- Is the given model element a qualifier? -- NOTE: collections are qualifiers -- @xinstance value the model element to check -- @treturn xinstance the value (qualifier), or nil if it is not a qualifier -- @function info.is_qualifier_kind -- @local function xtypes.info.is_qualifier_kind(value) local kind = _.kind(value) return (xtypes.ANNOTATION == kind) and value or nil end --- Is the given model element a collection? -- @xinstance value the model element to check -- @treturn xinstance the value (collection), or nil if it is not a collection -- @function info.is_collection_kind -- @local function xtypes.info.is_collection_kind(value) local model = _.model(value) return (xtypes.ARRAY == model or xtypes.SEQUENCE == model) and value or nil end --- Is the given model element an alias (for another type)? -- @xinstance value the model element to check -- @treturn xinstance the value (alias), or nil if it is not an alias -- @function info.is_alias_kind -- @local function xtypes.info.is_alias_kind(value) local kind = _.kind(value) return (xtypes.TYPEDEF == kind) and value or nil end --- Is the given model element a leaf (ie primitive) type? -- @xinstance value the model element to check -- @treturn xinstance the value (leaf), or nil if it is not a leaf type -- @function info.is_leaf_kind -- @local function xtypes.info.is_leaf_kind(value) local kind = _.kind(value) return (xtypes.ATOM == kind or xtypes.ENUM == kind) and value or nil end --- Is the given model element a template type? -- @xinstance value the model element to check -- @treturn xinstance the value (template), or nil if it is not a template type -- @function info.is_template_kind -- @local function xtypes.info.is_template_kind(value) local kind = _.kind(value) return (xtypes.ATOM == kind or xtypes.ENUM == kind or xtypes.STRUCT == kind or xtypes.UNION == kind or xtypes.TYPEDEF == kind) and value or nil end --============================================================================-- -- Helpers -- --- Ensure that we have a valid declaration, and if so, split it into a -- name and an underlying definition. -- @tparam {[string]=...} decl a table containing at least one {name=defn} -- entry where *name* is a string model name -- and *defn* is a table containing the definition. -- @treturn string name -- @treturn table defn -- @local function xtypes.parse_decl(decl) -- pre-condition: decl is a table assert('table' == type(decl), table.concat{'parse_decl(): invalid declaration: ', tostring(decl)}) local name, defn = next(decl) assert('string' == type(name), table.concat{'parse_decl(): invalid model name: ', tostring(name)}) assert('table' == type(defn), table.concat{'parse_decl(): invalid model definition: ', tostring(defn)}) return name, defn end --============================================================================-- -- Qualifiers -- --- Datatype Qualifiers. -- @section DatatypeQualifiers -- Annotations -- --- Create an annotation. -- Annotations qualify a datatype or a member of the datatype. Except for -- `array` and `sequence` qualifiers, annotation contents are opaque to -- DDSL; they are kept intact and may be interpreted in the user's context. -- @tparam {[string]=...} decl a table containing an annotation name and -- definition, where ... are the optional *default* attributes -- of the annotation. -- @treturn table an annotation datatype template (`xtemplate`) -- @usage -- -- Create user defined annotation @MyAnnotation(value1 = 42, value2 = 42.0) -- local MyAnnotation = xtypes.`annotation`{ -- MyAnnotation = {value1 = 42, value2 = 9.0} -- default attributes -- } -- -- -- Use user defined annotation with custom attributes -- MyAnnotation{value1 = 942, value2 = 999.0} -- -- -- Print the annotation contents (value1, value2) -- for k, v in pairs(MyAnnotation) do -- print(k, v) -- end -- -- -- Use builtin annotation `Key` -- xtypes.Key -- -- -- Use builtin annotation `Extensibility` -- xtypes.Extensibility{'EXTENSIBLE_EXTENSIBILITY'} function xtypes.annotation(decl) local name, defn = xtypes.parse_decl(decl) -- create the template local template = _.new_template(name, xtypes.ANNOTATION, xtypes.API[xtypes.ANNOTATION]) local model = _.model(template) -- annotation definition function (closure) -- NOTE: the attributes passed to the annotation are not interpreted, -- and are kept intact; we simply add the MODEL definition -- A function that returns a model table, with user defined -- annotation attributes passed as a table of {name = value} pairs -- eg: xtypes.MyAnnotation{value1 = 42, value2 = 42.0} model[_.DEFN] = function (attributes) -- parameters to the annotation if attributes then assert('table' == type(attributes), table.concat{'table with {name=value, ...} attributes expected: ', tostring(attributes)}) end local instance = attributes ~= EMPTY and attributes or template setmetatable(instance, model) -- not caching the instance in model[_.INSTANCES] because we don't need it return instance end -- initialize template with the attributes template = template(defn) return template end -- Annotations API meta-table xtypes.API[xtypes.ANNOTATION] = { __tostring = function(annotation) -- output the attributes if any local output = nil -- assertions for i, v in ipairs(annotation) do output = string.format('%s%s%s', output or '', -- output or nothing output and ',' or '', -- put a comma or not? tostring(v)) end -- name value pairs {name=value} for k, v in pairs(annotation) do if 'string' == type(k) then output = string.format('%s%s%s=%s', output or '', -- output or nothing output and ',' or '', -- put a comma or not? tostring(k), tostring(v)) end end local model = _.model(annotation) if output then output = string.format('@%s(%s)', model[NAME] or '', output) else output = string.format('@%s', model[NAME] or '') end return output end, __index = function (template, key) local model = _.model(template) return model[key] end, __newindex = function (template, key, value) -- immutable: do-nothing end, -- create an annotation instance __call = function(template, ...) local model = _.model(template) return model[_.DEFN](...) end } -- Collections: Arrays & Sequences -- -- Arrays are implemented as a special annotations, whose -- attributes are positive integer constants, that specify the dimension bounds -- NOTE: Since an array is an annotation, it can appear anywhere -- after a member type declaration; the 1st one is used local array = xtypes.annotation{array=EMPTY} xtypes.ARRAY = _.model(array) --- Create an array qualifier with the specified dimensions. -- Ensures that a valid set of dimension values is passed in. Returns the -- array datatype qualifier, initialized with the specified dimensions. -- An array qualifier is interpreted by DDSL as a *collection* qualifier. -- @int n the first dimension -- @param ... the remaining dimensions -- @treturn table the array qualifier instance (`xtemplate`) function xtypes.array(n, ...) return xtypes.make_collection_qualifier(array, n, ...) end -- Sequences are implemented as a special annotations, whose -- attributes are positive integer constants, that specify the dimension bounds -- NOTE: Since a sequence is an annotation, it can appear anywhere -- after a member type declaration; the 1st one is used local sequence = xtypes.annotation{sequence=EMPTY} xtypes.SEQUENCE = _.model(sequence) --- Create a sequence qualifier with the specified dimensions. -- Ensures that a valid set of dimension values is passed in. Returns the -- sequence datatype qualifier, initialized with the specified dimensions. -- A sequence qualifier is interpreted by DDSL as a *collection* qualifier. -- @int n the first dimension -- @param ... the remaining dimensions -- @treturn table the sequence qualifier instance (`xtemplate`) function xtypes.sequence(n, ...) return xtypes.make_collection_qualifier(sequence, n, ...) end --- @section end --- Make a collection qualifier instance. -- Ensures that a valid set of dimension values is passed in. Returns the -- annotation instance, initialized with the specified dimensions. -- -- NOTE: a new annotation instance is created for each call. There may be -- room for optimization by caching the annotation instances. -- -- @xinstance annotation the underlying annotation ARRAY or SEQUENCE -- @int n the first dimension -- @param ... the remaining dimensions -- @treturn table the qualifier annotation instance describing the collection -- @local function xtypes.make_collection_qualifier(annotation, n, ...) -- ensure that we have an array of positive numbers local dimensions = {...} table.insert(dimensions, 1, n) -- insert n at the beginning for i, v in ipairs(dimensions) do local dim = v -- if the dim is a CONST, use its value for validation if xtypes.CONST == _.kind(v) then dim = v() end -- check if the 'dim' is valid if not(type(dim)=='number') then error(table.concat{'invalid collection bound: ', tostring(dim)}, 2) end if not(dim > 0 and dim - math.floor(dim) == 0) then -- positive integer error(table.concat{'collection bound must be an integer > 0: ', dim}, 2) end end -- return the predefined annotation instance, whose attributes are -- the collection dimension bounds return annotation(dimensions) end --============================================================================-- -- Atoms -- --- Create an atomic datatype. -- There are two kinds of atomic types: -- -- - un-dimensioned -- - dimensioned, e.g. bounded size/length (e.g. `string`<n>) -- -- @tparam {[string]=EMPTY|{int}|const} decl a table containing an atom name -- mapped to and `EMPTY` initializer (for undimensioned atoms) or a a table -- containing an integral *dimension* (for dimensioned atoms). The dimension -- could also be an integral `const` datatype. -- @treturn table an atom datatype template (`xtemplate`) -- @usage -- -- Create an un-dimensioned atomic datatype named 'MyAtom': -- local MyAtom = xtypes.atom{ -- MyAtom = EMPTY -- } -- -- -- Create a dimensioned atomic type: -- local string10 = xtypes.atom{string={10}} -- bounded length string -- local wstring10 = xtypes.atom{wstring={10}} -- bounded length wstring -- -- -- Create a dimensioned atomic type, where 'MAXLEN' is a `const`: -- local StringMaxlen = xtypes.atom{string=MAXLEN} -- bounded length string -- @within Datatypes function xtypes.atom(decl) local name, defn = xtypes.parse_decl(decl) local dim, dim_kind = defn[1], _.kind(defn[1]) -- pre-condition: validate the dimension local dim_value = xtypes.CONST == dim_kind and dim() or dim if nil ~= dim then if type(dim_value) ~='number' then error(table.concat{'invalid dimension: ',tostring(dim), ' = ', dim_value}, 2) end if not(dim_value > 0 and dim_value - math.floor(dim_value) == 0) then error(table.concat{'dimension must be an integer > 0: ', tostring(dim)}, 2) end end -- build up the atom template name: if xtypes.CONST == dim_kind then name = table.concat{name, '<', _.nsname(dim), '>'} elseif nil ~= dim then name = table.concat{name, '<', tostring(dim), '>'} end -- lookup the atom name in the builtins local template = xtypes.builtin[name] if nil == template then -- not found => create it local model template, model = _.new_template(name, xtypes.ATOM, xtypes.API[xtypes.ATOM]) model[_.DEFN][1] = dim -- may be nil xtypes.builtin[name] = template -- NOTE: install it in the builtin module end return template end -- Atom API meta-table xtypes.API[xtypes.ATOM] = { __tostring = function(template) -- the name or the kind (if no name has been assigned) local model = _.model(template) return model[NAME] or model[KIND]() -- evaluate the function end, __index = function (template, key) local model = _.model(template) return model[key] end, __newindex = function (template, key, value) -- immutable: do-nothing end } --============================================================================-- -- Enums -- --- Create an enum datatype. -- @tparam {[string]={string,string,[string]=int,[string]=int,...} decl a -- table containing an enum name mapped to a table (which is an array of -- strings or a map of strings to ordinal values, or a mix of both). -- For example, -- { MyEnum = { { str1 = ord1 }, { str2 = ord2 }, ... } } -- or -- { MyEnum = { str1, str2, ... } } -- or a mix of the above -- { MyEnum = { strA, strB, { str1 = ord1 }, { str2 = ord2 }, ... } } -- @treturn table an enum datatype template (`xtemplate`) -- The table is a map of enumerator strings to their ordinal values. -- @usage -- -- Create enum: declarative style -- local MyEnum = xtypes.`enum`{ -- MyEnum = { -- { enumerator_1 = ordinal_1 }, -- : -- { enumerator_M = ordinal_M }, -- -- -- OR -- -- -- enumerator_A, -- : -- enumerator_Z, -- -- -- OPTIONAL -- -- `annotation`_x, -- : -- `annotation`_z, -- } -- } -- -- -- Create enum: imperative style (start with `EMPTY`) -- MyEnum = xtypes.`enum`{ -- MyEnum = xtypes.`EMPTY` -- } -- -- -- Set the i-th member: -- MyEnum[i] = { enumerator_i = ordinal_i } -- -- OR -- -- MyEnum[i] = enumerator_i -- default: `ordinal`_i = #MyEnum -- -- -- After setting the i-th member, the following post-conditions hold: -- MyEnum[enumerator_i] == ordinal_i -- MyEnum(ordinal_i) == enumerator_i -- -- -- -- Delete the i-th member: -- MyEnum[i] = nil -- -- -- -- Get the number of enumerators in the enum: -- print(#MyEnum) -- -- -- -- Get the i-th member: -- local enumerator, ordinal = next(MyEnum[i]) -- print(enumerator, ordinal) -- -- -- Get the enumerator's ordinal value: -- print(MyEnum[enumerator]) -- -- -- -- Iterate over the model definition (ordered): -- for i = 1, #MyEnum do print(next(MyEnum[i])) end -- -- -- Iterate over enum and ordinal values (unordered): -- for enumerator, ordinal in pairs(MyEnum) do print(enumerator, ordinal) end -- -- -- Lookup the enumerator name for an ordinal value: -- print(MyEnum(ordinal)) -- @within Datatypes function xtypes.enum(decl) local name, defn = xtypes.parse_decl(decl) -- create the template local template = _.new_template(name, xtypes.ENUM, xtypes.API[xtypes.ENUM]) -- populate the template return _.populate_template(template, defn) end -- Enum API meta-table xtypes.API[xtypes.ENUM] = { __tostring = function(template) -- the name or the kind (if no name has been assigned) local model = _.model(template) return model[NAME] or model[KIND]() -- evaluate the function end, __len = function (template) local model = _.model(template) return #model[_.DEFN] end, __index = function (template, key) local model = _.model(template) local value = model[key] if value then -- does the model have it? (KIND, NAME, NS) return value elseif 'number' == type(key) then -- get from the model definition and pack -- enumerator, ordinal_value local enumerator, ordinal = next(model[_.DEFN][key]) -- Format: -- { enumerator = ordinal_value } local result = {} result[enumerator] = ordinal return result else -- delegate to the model definition return model[_.DEFN][key] end end, __newindex = function (template, key, value) local model = _.model(template) local model_defn = model[_.DEFN] if NAME == key then -- set the model name rawset(model, NAME, value) elseif QUALIFIERS == key then -- annotation definition -- set the new qualifiers in the model definition (may be nil) model_defn[QUALIFIERS] = _.assert_qualifier_array(value) elseif 'number' == type(key) then -- member definition -- clear the old member definition and instance fields if model_defn[key] then local old_role = next(model_defn[key]) -- update instances: remove the old_role rawset(template, old_role, nil) end -- set the new member definition if nil == value then -- nil => remove the key-th member definition table.remove(model_defn, key) -- do not want holes in array else -- Format: -- { enumerator = ordinal_value } -- OR -- enumerator local role, role_defn if 'table' == type(value) then role, role_defn = next(value) -- { enumerator = ordinal_value } else role, role_defn = value, #template -- enumerator end -- role must be a string assert(type(role) == 'string', table.concat{template[NAME] or '', ' : invalid member name: ', tostring(role)}) -- ensure the definition is an ordinal value assert('number' == type(role_defn) and math.floor(role_defn) == role_defn, -- integer table.concat{template[NAME] or '', ' : invalid definition: ', tostring(role), ' = ', tostring(role_defn) }) -- is the role already defined? assert(nil == rawget(template, role),-- check template table.concat{template[NAME] or '', ' : member name already defined: "', role, '"'}) -- insert the new role rawset(template, role, role_defn) -- insert the new member definition model_defn[key] = { [role] = role_defn -- map with one entry } end end end, -- Lookup the enumerator string, given an ordinal value -- @param ordinal the ordinal value -- @return the enumerator string or 'nil' if it is not a valid ordinal value __call = function(template, ordinal) for k, v in pairs(template) do if v == ordinal then return k end end return nil end, } --============================================================================-- -- Structs -- --- Create a struct datatype. -- @tparam {[string]={[string]={...},{[string]={...},...} decl a table -- containing a struct name mapped to a table (which is an array of strings -- mapped to member definitions). For example, -- { MyStruct = { { role1 = {...}, { role2 = {...} }, ... } } -- where the member definition for a role is, -- { role = { xtemplate, [array | sequence,] [annotation, ...] } } -- @treturn table a struct datatype template (`xtemplate`). -- The table is a map of the role names to flattened out strings that -- represent the path from the enclosing top-level struct scope to the role. -- The string values may be be used to retrieve the field values from -- some storage system. -- @usage -- -- Create struct: declarative style -- local MyStruct = xtypes.`struct`{ -- MyStruct = { -- [<optional base `struct`>], -- base `struct` must be the 1st item -- -- {role_1={xtemplate_1, [`array`_1|`sequence`_1,] [`annotation`_1,...]}}, -- : -- {role_M={xtemplate_M, [`array`_M|`sequence`_M,] [`annotation`_M,...]}}, -- -- -- OPTIONAL -- -- `annotation`_x, -- : -- `annotation`_z, -- } -- } -- -- -- OR Create struct: imperative style (start with base `struct` or `EMPTY`) -- local MyStruct = xtypes.`struct`{ -- MyStruct = { <optional base `struct`> } | xtypes.`EMPTY` -- } -- -- -- Set the i-th member: -- MyStruct[i] = { new_role = { new_xtemplate, -- [new_`array` | new_`sequence`,] -- [new_`annotation`, ...] } } -- -- -- After setting the i-th member, the following post-condition holds: -- -- NOTE: also holds for roles defined in the base `struct` datatype -- MyStruct[role] == 'prefix.enclosing.scope.path.to.role' -- MyStruct(role) == <the role definition> -- -- -- -- Delete the i-th member: -- MyStruct[i] = nil -- -- -- -- Set base class: -- MyStruct[xtypes.`BASE`] = `YourStruct` -- defined elsewhere -- -- --- -- Get the number of members in the struct (not including base struct): -- print(#MyStruct) -- -- -- -- Get the i-th member: -- -- { -- -- role = {template, [array|sequence,] [annotation1, annotation2, ...] -- -- } -- local member = MyStruct[i] -- local role, roledef = next(member) -- print(role, table.unpack(roledef)) -- -- -- Get a member definition by role name. The return value is a table -- -- in the same format that is used to define a member role: -- -- { template, [array|sequence,] [annotation1, annotation2, ...] } -- local roledef = MyStruct(role) -- print(table.unpack(roledef)) -- -- -- -- Get the member role's value -- print(MyStruct[role]) -- an accessor string into some storage system -- -- -- -- Get the base class: -- print(MyStruct[xtypes.`BASE`]) -- -- -- -- Iterate over the model definition (ordered): -- -- NOTE: does NOT show the roles defined in the base `struct` datatype -- for i = 1, #MyStruct do -- local role, roledef = next(MyStruct[i]) -- print(role, table.unpack(roledef)) -- end -- -- -- Iterate over instance members and the indexes (unordered): -- -- NOTE: shows roles defined in the base `struct` datatype -- for role, value in pairs(MyStruct) do -- print(role, value, table.unpack(MyStruct(role))) -- end -- @within Datatypes function xtypes.struct(decl) local name, defn = xtypes.parse_decl(decl) -- create the template local template, model = _.new_template(name, xtypes.STRUCT, xtypes.API[xtypes.STRUCT]) model[_.INSTANCES] = {} -- OPTIONAL base: pop the next element if it is a base model element local base if xtypes.STRUCT == _.kind(_.resolve(defn[1])) then base = defn[1] table.remove(defn, 1) -- insert the base class: template[BASE] = base -- invokes the meta-table __newindex() end -- populate the template return _.populate_template(template, defn) end -- Struct API meta-table xtypes.API[xtypes.STRUCT] = { __tostring = function(template) -- the name or the kind (if no name has been assigned) local model = _.model(template) return model[NAME] or model[KIND]() -- evaluate the function end, __len = function (template) local model = _.model(template) return #model[_.DEFN] end, __index = function (template, key) local model = _.model(template) local value = model[key] if value then -- does the model have it? (KIND, NAME, NS) return value elseif 'number' == type(key) then -- get from the model definition and pack local role, roledef = next(model[_.DEFN][key]) -- Format: -- { role = {template, [array|sequence,] [annotation1, annotation2, ...]}} local result = {} result[role] = { table.unpack(roledef) } return result else -- delegate to the model definition return model[_.DEFN][key] end end, __newindex = function (template, key, value) local model = _.model(template) local model_defn = model[_.DEFN] if NAME == key then -- set the model name rawset(model, NAME, value) elseif QUALIFIERS == key then -- annotation definition -- set the new qualifiers in the model definition (may be nil) model_defn[QUALIFIERS] = _.assert_qualifier_array(value) elseif 'number' == type(key) then -- member definition -- Format: -- { role = {template, [array|sequence,] [annotation1, annotation2, ...]}} -- clear the old member definition and instance fields if model_defn[key] then local old_role = next(model_defn[key]) -- update instances: remove the old_role if old_role then _.update_instances(model, old_role, nil) -- clear the role end end -- set the new member definition if nil == value then -- nil => remove the key-th member definition table.remove(model_defn, key) -- do not want holes in array else -- get the new role and role_defn local role, role_defn = next(value) -- is the role already defined? assert(nil == rawget(template, role),-- check template table.concat{template[NAME] or '', ' : member name already defined: "', role, '"'}) -- create role instance (checks for pre-conditions, may fail!) local role_instance = _.create_role_instance(role, role_defn) -- update instances: add the new role_instance _.update_instances(model, role, role_instance) -- insert the new member definition local role_defn_copy = {} -- make our own local copy for i, v in ipairs(role_defn) do role_defn_copy[i] = v end model_defn[key] = { [role] = role_defn_copy -- map with one entry } end elseif BASE == key then -- inherits from 'base' struct -- clear the instance fields from the old base struct (if any) local old_base = _.resolve(model_defn[BASE]) while old_base do for k, v in pairs(old_base) do if 'string' == type(k) then -- copy only the base instance fields -- update instances: remove the old_base role _.update_instances(model, k, nil) -- clear the role end end -- template is no longer an instance of the base struct local old_base_model = _.model(old_base) old_base_model[_.INSTANCES][template] = nil -- visit up the base model inheritance hierarchy old_base = _.resolve(old_base[BASE]) -- parent base end -- get the base model, if any: local new_base if nil ~=value and _.assert_kind(xtypes.STRUCT, _.resolve(value)) then new_base = value end -- populate the instance fields from the base model struct local base = new_base while base do local base_model = _.model(_.resolve(base)) -- base may be a typedef for i = 1, #base_model[_.DEFN] do local base_role, base_role_defn = next(base_model[_.DEFN][i]) -- is the base_role already defined? assert(nil == rawget(template, base_role),-- check template table.concat{template[NAME] or '', ' : member name already defined: "', base_role, '"'}) -- create base role instance (checks for pre-conditions, may fail) local base_role_instance = _.create_role_instance(base_role, base_role_defn) -- update instances: add the new base_role_instance _.update_instances(model, base_role, base_role_instance) end -- visit up the base model inheritance hierarchy base = base_model[_.DEFN][BASE] -- parent base end -- set the new base in the model definition (may be nil) model_defn[BASE] = new_base -- template is an instance of the base structs (inheritance hierarchy) base = new_base while base do local base_model = _.model(_.resolve(base)) -- base may be a typedef -- NOTE: Use empty string as the 'instance' name of the base struct base_model[_.INSTANCES][template] = '' -- empty instance name -- visit up the base model inheritance hierarchy base = base_model[_.DEFN][BASE] -- parent base end else -- accept the key if it is defined in the model definition -- e.g. could have been an optional member that was removed for i = 1, #model_defn do if key == next(model_defn[i]) then rawset(template, key, value) end end end end, -- Get a member definition. -- @string role the member name to lookup -- @return the role definition in the format -- { template, [array|sequence,] [annotation1, annotation2, ...] } -- or nil if the role is not defined. __call = function(template, role) for i = 1, #template do local role_i, roledef_i = next(template[i]) if role_i == role then return roledef_i end end return nil end, } --============================================================================-- -- Unions -- --- Create a union datatype. -- @tparam {[string]={xtemplate,{caseDisc1,...caseDiscN,string]={...}},...}} decl -- a table containing a union name mapped to a table as follows. -- { -- MyUnion = { -- xtemplate, -- { caseDisc11, ..., caseDisc1N, role1 = {...} }, -- { caseDisc21, ..., caseDisc2N, role2 = {...} }, -- ... -- { xtypes.EMPTY, [..., caseDiscN,] role = {...} } -- default -- } -- } -- where the member definition for a role is, -- { role = { xtemplate, [array | sequence,] [annotation, ...] } } -- and `xtypes.EMPTY` is treated as the built-in **default** discriminator. -- @treturn table an union datatype template (`xtemplate`). -- The table is a map of the role names to flattened out strings that -- represent the path from the enclosing top-level union scope to the role. -- The string values may be be used to retrieve the field values from -- some storage system. -- @usage -- -- Create union: declarative style -- local MyUnion = xtypes.`union`{ -- MyUnion = { -- <discriminator `atom` or `enum`>, -- must be the 1st item -- -- { caseDiscriminator11, caseDiscriminator12, ... caseDiscriminator1N, -- role_1 = {xtemplate_1,[`array`_1|`sequence`_1,][`annotation`_1,...]} -- }, -- : -- { caseDiscriminatorM1, caseDiscriminatorM2, ... caseDiscriminatorMN, -- role_M = {xtemplate_M,[`array`_M|`sequence`_M,][`annotation`_M,...]} -- }, -- -- { `xtypes.EMPTY`, [..., caseDiscriminatorN, ] -- default -- role = { xtemplate,[`array`|`sequence`,][`annotation`,...]} -- -- -- OPTIONAL -- -- `annotation`_x, -- : -- `annotation`_z, -- } -- } -- -- -- OR Create union: imperative style (start with `EMPTY`) -- local MyUnion = xtypes.`union`{ -- MyUnion = { <discriminator `atom` or `enum`> } -- } -- -- -- Set the i-th case: -- -- { -- -- caseDiscriminator1, caseDiscriminator2, ... caseDiscriminatorN, -- -- role = { template, [array|sequence,] [annotation1, annotation2, ...] } -- -- } -- MyUnion[i] = { -- caseDiscriminator1, ... caseDiscriminatorN, -- role = { xtemplate, [`array` | `sequence`,] [`annotation`, ...] } -- }, -- -- -- After setting the i-th member, the following post-condition holds: -- MyUnion[role] == 'prefix.enclosing.scope.path.to.role' -- MyUnion(role) == <the role definition> -- -- -- -- Delete the i-th case: -- MyUnion[i] = nil -- -- -- -- Set the discriminator type definition: -- MyUnion[xtypes.`SWITCH`] = <discriminator `atom` or `enum`> -- -- -- After setting the discriminator, the following post-condition holds: -- MyUnion._d == '#' -- -- -- -- Get the number of cases in the union: -- print(#MyUnion) -- -- -- -- Get the i-th case: -- -- { -- -- caseDiscriminator1, caseDiscriminator2, ... caseDiscriminatorN, -- -- role = { template, [array|sequence,] [annotation1, annotation2, ...] } -- -- } -- local case = MyUnion[i] -- print(table.unpack(case)) -- local role, roledef = next(case, #case) -- print('\t', role, table.unpack(roledef)) -- -- -- Get a member definition by role name. The return value is a table -- -- in the same format that is used to define a member role: -- -- { template, [array|sequence,] [annotation1, annotation2, ...] } -- local roledef = MyUnion(role) -- print(table.unpack(roledef)) -- -- -- Get the member role's value -- print(MyUnion[role]) -- an accessor string into some storage system -- -- -- Get the discriminator type definition: -- print(MyUnion[xtypes.`SWITCH`]) -- -- -- Get the discriminator's value -- print(MyUnion._d) -- an accessor string into some storage system -- -- -- Get the currectly selected member's value. -- -- i.e. the member selected by current discriminator value, `MyUnion._d` -- print(MyUnion()) -- may be `nil`, e.g. when there is no default discriminator -- -- -- -- Iterate over the model definition (ordered): -- for i = 1, #MyUnion do -- local case = MyUnion[i] -- local role, roledef = next(case, #case) -- print(role, table.unpack(roledef), ':', table.unpack(case)) -- end -- -- -- Iterate over instance members and the indexes (unordered): -- for role, value in pairs(MyUnion) do -- print(role, value, table.unpack(MyUnion(role))) -- end -- @within Datatypes function xtypes.union(decl) local name, defn = xtypes.parse_decl(decl) -- create the template local template, model = _.new_template(name, xtypes.UNION, xtypes.API[xtypes.UNION]) model[_.INSTANCES] = {} -- pop the discriminator template[SWITCH] = defn[1] -- invokes meta-table __newindex() table.remove(defn, 1) -- populate the template return _.populate_template(template, defn) end -- Union API meta-table xtypes.API[xtypes.UNION] = { __tostring = function(template) -- the name or the kind (if no name has been assigned) local model = _.model(template) return model[NAME] or model[KIND]() -- evaluate the function end, __len = function (template) local model = _.model(template) return #model[_.DEFN] end, __index = function (template, key) local model = _.model(template) local value = model[key] if value then -- does the model have it? (KIND, NAME, NS) return value elseif 'number' == type(key) then -- get from the model definition and pack local case = model[_.DEFN][key] local role, roledef = next(case, #case) -- member -- Format: -- { caseDiscriminator1, caseDiscriminator2, ... caseDiscriminatorN, -- role = {template, [array|sequence,] [annotation1, annotation2, ...]} -- } local result = { table.unpack(case) } result[role] = { table.unpack(roledef) } return result else -- delegate to the model definition return model[_.DEFN][key] end end, __newindex = function (template, key, value) local model = _.model(template) local model_defn = model[_.DEFN] if NAME == key then -- set the model name model[NAME] = value elseif QUALIFIERS == key then -- annotation definition -- set the new qualifiers in the model definition (may be nil) model_defn[QUALIFIERS] = _.assert_qualifier_array(value) elseif SWITCH == key then -- switch definition local discriminator = value -- pre-condition: ensure discriminator is of a valid type xtypes.assert_case(discriminator, nil)-- nil => validate discriminator -- pre-condition: ensure that caseDiscriminators are compatible for _, case in ipairs(model_defn) do for __, caseDiscriminator in ipairs(case) do if EMPTY ~= caseDiscriminator then -- not default xtypes.assert_case(discriminator, caseDiscriminator) end end end -- update the discriminator model[_.DEFN][SWITCH] = discriminator rawset(template, '_d', '#') elseif 'number' == type(key) then -- member definition -- Format: -- { caseDiscriminator1, caseDiscriminator2, ... caseDiscriminatorN, -- role = {template, [array|sequence,] [annotation1, annotation2, ...]} -- } -- clear the old member definition if model_defn[key] then local case = model_defn[key] local old_role = next(case, #case) -- member -- update instances: remove the old_role if old_role then _.update_instances(model, old_role, nil) -- clear the role end end if nil == value then -- remove the key-th member definition table.remove(model_defn, key) -- do not want holes in array else local case_copy = {} -- make our own local copy -- ensure at least one 'caseDiscriminator': assert(0 < #value, table.concat{template[NAME] or '', ' : expecting at least one case discriminator'}) for _, caseDiscriminator in ipairs(value) do if EMPTY ~= caseDiscriminator then -- not default caseDiscriminator = xtypes.assert_case(model_defn[SWITCH], caseDiscriminator) end -- is the caseDiscriminator already defined? for __, case in ipairs(model_defn) do for i = 1, #case do assert(caseDiscriminator ~= case[i], table.concat{template[NAME] or '', ' : case discriminator exists: "', tostring(caseDiscriminator), '"'}) end end table.insert(case_copy, caseDiscriminator) end -- get the role and definition: after the 'caseDiscriminator' array local role, role_defn = next(value, #value) assert(nil ~= role_defn, table.concat{template[NAME] or '', ' : member must be defined: "', role, '"'}) -- is the role already defined? assert(nil == rawget(template, role),-- check template table.concat{template[NAME] or '', ' : member name already defined: "', role, '"'}) local role_instance = _.create_role_instance(role, role_defn) -- insert the new member definition case_copy[role] = {} -- make our own local copy of role defn for i, v in ipairs(role_defn) do case_copy[role][i] = v end model_defn[key] = case_copy -- update instances: add the new role_instance _.update_instances(model, role, role_instance) end else -- accept the key if it is a discriminator value: if '_d' == key then rawset(template, key, value) -- accept the key if it is defined in the model definition -- e.g. could have been an optional member that was removed else for _, case in ipairs(model_defn) do if key == next(case, #case > 0 and #case or nil) then rawset(template, key, value) end end end end end, -- Get the currently selected member OR Get a member definition. -- @string role[opt=nil] the member name to lookup OR -- **nil** to lookup the currently selected member -- @return When called with out an argument, returns the selected -- member, based on the current discriminator value _d, or 'nil' if the -- discriminator does not match any case (no default). -- When called with an argument, returns the role definition in the format -- { template, [array|sequence,] [annotation1, annotation2, ...] } -- or nil if the role is not defined. __call = function(template, role) local function lookup_selected_member() local model = _.model(template) local default_role = nil for _, case in ipairs(model[_.DEFN]) do for i = 1, #case do if template._d == case[i] then local role = next(case, #case) -- matched member role return template[role] end if EMPTY == case[i] then default_role = next(case, #case) -- default member role end end end return default_role and template[default_role] or nil -- default end local function lookup_role_definition(role) for i = 1, #template do local case = template[i] local role_i, roledef_i = next(case, #case) if role_i == role then return roledef_i end end return nil end if nil ~= role then -- member lookup? return '_d' ~= role and lookup_role_definition(role) or nil end return lookup_selected_member() end, } --- Ensure that case and discriminator are valid and compatible, and if so, -- return the case value to use. -- The input case value may be converted to the correct type required -- by the discriminator. -- @xinstance discriminator a discriminator datatype -- @param case a case value -- @return nil if the discriminator or the case is not valid or if the case is -- not compatible with the discriminator; otherwise the (coverted) case -- value to use. -- @local function xtypes.assert_case(discriminator, case) local err_msg if nil == case then err_msg = table.concat{'invalid union discriminator: "', tostring(discriminator), '"' } else err_msg = table.concat{'invalid union case: "', tostring(case), '"'} end -- resolve the discriminator to the underlying type: local discriminator = _.resolve(discriminator) -- enum if xtypes.ENUM == discriminator[KIND] then -- enum assert(nil == case or nil ~= discriminator(case), err_msg) -- boolean elseif xtypes.builtin.boolean == discriminator then if 'false' == case or '0' == case then case = false elseif 'true' == case or '1' == case then case = true end assert(nil == case or true == case or false == case, err_msg) -- character elseif xtypes.builtin.char == discriminator or xtypes.builtin.wchar == discriminator then assert(nil == case or 'string' == type(case) and 1 == string.len(case) or math.floor(tonumber(case)) == tonumber(case), -- ordinal value err_msg) -- integral signed elseif xtypes.builtin.octet == discriminator or xtypes.builtin.short == discriminator or xtypes.builtin.long == discriminator or xtypes.builtin.long_long == discriminator then local int_case = tonumber(case) assert(nil == case or nil ~= int_case and math.floor(int_case) == int_case, err_msg) case = int_case -- integral unsigned elseif xtypes.builtin.unsigned_short == discriminator or xtypes.builtin.unsigned_long == discriminator or xtypes.builtin.unsigned_long_long == discriminator then local uint_case = tonumber(case) assert(nil == case or nil ~= uint_case and math.floor(uint_case) == uint_case and uint_case >= 0, err_msg) case = uint_case else -- invalid assert(false, err_msg) end return case end --============================================================================-- -- Typedefs -- --- Create a typedef `alias` datatype. -- Typedefs are aliases for underlying datatypes. -- @tparam {[string]={xtemplate,[array|sequence,][annotation,...]}} decl a table -- containing a typedef mapped to an array as follows. -- { MyTypedef = { xtemplate, [array | sequence,] [annotation, ...] } } -- where `xtemplate` is the underlying type definition, optionally followed by -- and `array` or `sequence` qualifiers to specify the multiplicity, -- optionally followed by annotations. -- @treturn table an typedef datatype template (`xtemplate`). -- @usage -- -- Create a typedef datatype: -- local MyTypedef = xtypes.`typedef`{ -- MyTypedef = { `xtemplate`, [`array` | `sequence`,] [`annotation`, ...] } -- } -- -- -- Retreive the typedef definition -- print(MyTypedef()) -- `xtemplate`, [`array` | `sequence`] -- -- -- Resolve a typedef to the underlying non-typedef datatype and a list -- -- of collection qualifiers -- print(xtypes.`resolve`(MyTypedef)) -- -- -- -- Example: typedef sequence<MyStruct> MyStructSeq -- local MyStructSeq = xtypes.`typedef`{ -- MyStructSeq = { xtypes.MyStruct, xtypes.`sequence`() } -- } -- -- print(MyStructSeq()) -- MyStruct @sequence(10) -- -- -- -- Example: typedef MyStruct MyStructArray[10][20] -- local MyStructArray = xtypes.`typedef`{ -- MyStructArray = { xtypes.MyStruct, xtypes.`array`(10, 20) } -- } -- -- print(MyStructArray()) -- MyStruct @array(10, 20) -- @within Datatypes function xtypes.typedef(decl) local name, defn = xtypes.parse_decl(decl) -- pre-condition: ensure that the 1st defn element is a valid type local alias = defn[1] _.assert_template_kind(alias) -- pre-condition: ensure that the 2nd defn element if present -- is a 'collection' kind local collection_qualifier = defn[2] if collection and not xtypes.info.is_collection_kind(collection) then error(table.concat{'expected sequence or array, got: ', tostring(value)}, 2) end -- create the template local template, model = _.new_template(name, xtypes.TYPEDEF, xtypes.API[xtypes.TYPEDEF]) model[_.DEFN] = { alias, collection_qualifier } return template end -- Atom API meta-table xtypes.API[xtypes.TYPEDEF] = { __tostring = function(template) -- the name or the kind (if no name has been assigned) local model = _.model(template) return model[NAME] or model[KIND]() -- evaluate the function end, __index = function (template, key) local model = _.model(template) return model[key] end, __newindex = function (template, key, value) -- immutable: do-nothing end, -- alias and collection information is obtained by evaluating the table: -- @return alias, collection_qualifier -- eg: my_typedef() __call = function(template) local model = _.model(template) return model[_.DEFN][1], model[_.DEFN][2] -- datatype, collection_qualifier end, } --============================================================================-- -- Constants -- --- Create a constant. -- @tparam {[string]={atom,value}} decl a table containing a constant name -- mapped to an array containing an `atom` and a value of the atom datatype. -- NOTE: this method will try to convert the value to the correct type, -- if not already so (for example, if the value is a string). -- @treturn table a constant. -- @usage -- -- Create a constant datatype -- local MY_CONST = xtypes.`const`{ -- MY_CONST = { `atom`, <const_value> } -- } -- -- -- Get the const value and the underlying atomic datatype -- print(MY_CONST()) -- value `atom` -- -- -- -- Examples: -- local MAXLEN = xtypes.`const`{ -- MAXLEN = { xtypes.short, 128 } -- } -- print(MAXLEN()) -- 128 short -- -- local PI = xtypes.`const`{ -- PI = { xtypes.`double`, 3.14 } -- } -- print(PI()) -- 3.14 double -- -- local MY_STRING = xtypes.`const`{ -- MY_STRING = { xtypes.`string`(128), "My String Constant" } -- } -- print(MY_STRING()) -- My String Constant string<128> -- -- -- -- Use a const datatype -- local MyStringSeq = xtypes.`typedef`{ -- MyStringSeq = { xtypes.`string`, xtypes.`sequence`(MAXLEN) } -- } -- @within Datatypes function xtypes.const(decl) local name, defn = xtypes.parse_decl(decl) -- pre-condition: ensure that the 1st defn declaration is a valid type local atom = _.assert_kind(xtypes.ATOM, _.resolve(defn[1])) -- pre-condition: ensure that the 2nd defn declaration is a valid value local value = defn[2] assert(nil ~= value, table.concat{name, ' : const value must be non-nil: ', tostring(value)}) -- convert value to the correct type: local coercedvalue = nil if xtypes.builtin.boolean == atom then if 'boolean' ~= type(value) then if 'false' == value or '0' == value then coercedvalue = false elseif 'true' == value or '1' == value then coercedvalue = true else coercedvalue = not not value -- toboolean end if nil ~= coercedvalue then log.info(table.concat{name, ' : converting to boolean: "', value, '" -> ', tostring(coercedvalue)}) else log.notice(table.concat{name, ' : converting to boolean: "', value, '" -> nil'}) end end elseif xtypes.string() == atom or xtypes.wstring() == atom or xtypes.builtin.char == atom then if 'string' ~= type(value) then coercedvalue = tostring(value) if nil ~= coercedvalue then log.info(table.concat{name, ' : converting to string: "', value, '" -> "', coercedvalue, '"'}) else log.notice(table.concat{name, ' : converting to string: "', value, '" -> nil'}) end end elseif xtypes.builtin.short == atom or xtypes.builtin.unsigned_short == atom or xtypes.builtin.long == atom or xtypes.builtin.unsigned_long == atom or xtypes.builtin.long_long == atom or xtypes.builtin.unsigned_long_long == atom or xtypes.builtin.float == atom or xtypes.builtin.double == atom or xtypes.builtin.long_double == atom then if 'number' ~= type(value) then coercedvalue = tonumber(value) if nil ~= coercedvalue then log.info(table.concat{name, ' : converting to number: "', value, '" -> ', coercedvalue}) else log.notice(table.concat{name, ' : converting to number: "', value, '" -> nil'}) end end end if nil ~= coercedvalue then value = coercedvalue end local model = _.model(atom) if xtypes.builtin.unsigned_short == atom or xtypes.builtin.unsigned_long == atom or xtypes.builtin.unsigned_long_long == atom then if value < 0 then log.notice(table.concat{name, ' : const value of "', value, ' of type "', type(value), '" must be non-negative and of the type: ', model[NAME] or ''}) end end -- char: truncate value to 1st char; warn if truncated if (xtypes.builtin.char == atom or xtypes.builtin.wchar == atom) and #value > 1 then value = string.sub(value, 1, 1) log.notice(table.concat{name, ' : truncating string value for ', model[NAME] or '', ' constant to: ', value}) end -- integer: truncate value to integer; warn if truncated if (xtypes.builtin.short == atom or xtypes.builtin.unsigned_short == atom or xtypes.builtin.long == atom or xtypes.builtin.unsigned_long == atom or xtypes.builtin.long_long == atom or xtypes.builtin.unsigned_long_long == atom) and 'number' == type(value) and value - math.floor(value) ~= 0 then value = math.floor(value) log.notice(table.concat{name, ' : truncating decimal value for integer constant', ' to: ', value}) end -- create the template local template, model = _.new_template(name, xtypes.CONST, xtypes.API[xtypes.CONST]) model[_.DEFN] = { atom, value } -- { atom, value [,expression] } return template end -- Const API meta-table xtypes.API[xtypes.CONST] = { __tostring = function(template) local model = _.model(template) return model[NAME] or model[KIND]() -- evaluate the function end, __index = function (template, key) local model = _.model(template) return model[key] end, __newindex = function (template, key, value) -- immutable: do-nothing end, -- instance value and datatype is obtained by evaluating the table: -- eg: MY_CONST() __call = function(template) local model = _.model(template) return model[_.DEFN][2], model[_.DEFN][1] -- value, datatype end, } --============================================================================-- -- Modules -- --- Create a module namespace. -- A module is an name-space for holding (enclosing) datatypes. -- @tparam {[string]={xtemplate,...} decl a table containing a module name -- mapped to an array of datatypes (`xtemplate`) -- @treturn table a module namespace. -- The table is a map of the datatype names to `xtemplate` canonical -- instances. -- @usage -- -- Create module: declarative style -- local MyModule = xtypes.`module`{ -- MyModule = { -- xtypes.`const`{...}, -- : -- xtypes.`enum`{...}, -- : -- xtypes.`struct`{...}, -- : -- xtypes.`union`{...}, -- : -- xtypes.`typedef`{...}, -- : -- xtypes.`module`{...}, -- nested module name-space -- : -- } -- } -- -- -- Create module: imperative style (start with `EMPTY`) -- local MyModule = xtypes.`module`{ -- MyModule = xtypes.EMPTY -- } -- -- -- Get the i-th member: -- print(MyModule[i]) -- -- -- Set the i-th member: -- MyModule[i] = `xtemplate` -- -- -- After setting the i-th member, the following post-condition holds: -- MyModule.name == `xtemplate` -- where: name = `xtemplate`[xtypes.`NAME`] -- -- -- Delete the i-th member: -- MyModule[i] = nil -- -- -- -- Get the number of members in the module: -- print(#MyModule) -- -- -- Iterate over the module definition (ordered): -- for i = 1, #MyModule do print(MyModule[i]) end -- -- -- Iterate over module namespace (unordered): -- for k, v in pairs(MyModule) do print(k, v) end -- @within Datatypes function xtypes.module(decl) local name, defn = xtypes.parse_decl(decl) --create the template local template = _.new_template(name, xtypes.MODULE, xtypes.API[xtypes.MODULE]) -- populate the template return _.populate_template(template, defn) end -- Module API meta-table xtypes.API[xtypes.MODULE] = { __tostring = function(template) -- the name or the kind (if no name has been assigned) local model = _.model(template) return model[NAME] or model[KIND]() -- evaluate the function end, __len = function (template) local model = _.model(template) return #model[_.DEFN] end, __index = function (template, key) local model = _.model(template) local value = model[key] if value then -- does the model have it? (KIND, NAME, NS) return value else -- delegate to the model definition return model[_.DEFN][key] end end, __newindex = function (template, key, value) local model = _.model(template) local model_defn = model[_.DEFN] if NAME == key then -- set the model name rawset(model, NAME, value) elseif QUALIFIERS == key then -- annotation definition -- set the new qualifiers in the model definition (may be nil) model_defn[QUALIFIERS] = _.assert_qualifier_array(value) elseif 'number' == type(key) then -- member definition -- clear the old member definition and instance fields if model_defn[key] then local old_role_model = _.model(model_defn[key]) local old_role = old_role_model[NAME] -- update namespace: remove the old_role rawset(template, old_role, nil) end -- set the new member definition if nil == value then -- nil => remove the key-th member definition table.remove(model_defn, key) -- do not want holes in array else -- Format: -- role_template -- pre-condition: value must be a model instance (template) assert(nil ~= _.kind(value), table.concat{template[NAME] or '', ' : invalid template: ', tostring(value)}) local role_template = value local role = role_template[NAME] -- is the role already defined? assert(nil == rawget(template, role), table.concat{template[NAME] or '', ' : member name already defined: "', role, '"'}) -- update the module definition model_defn[key] = role_template -- move the model element to this module local role_model = _.model(role_template) role_model[NS] = template -- update namespace: add the role rawset(template, role, role_template) end end end, } --============================================================================-- -- Built-in atomic types --- Builtin Datatypes. -- Builtin *atomic* datatypes. -- @section BuiltinTypes --- boolean. xtypes.builtin.boolean = xtypes.atom{boolean=EMPTY} --- octet. xtypes.builtin.octet = xtypes.atom{octet=EMPTY} --- char. xtypes.builtin.char= xtypes.atom{char=EMPTY} --- wide char. xtypes.builtin.wchar = xtypes.atom{wchar=EMPTY} --- float. xtypes.builtin.float = xtypes.atom{float=EMPTY} --- double. xtypes.builtin.double = xtypes.atom{double=EMPTY} --- long double. xtypes.builtin.long_double = xtypes.atom{['long double']=EMPTY} --- short. xtypes.builtin.short = xtypes.atom{short=EMPTY} --- long. xtypes.builtin.long = xtypes.atom{long=EMPTY} --- long long. xtypes.builtin.long_long = xtypes.atom{['long long']=EMPTY} --- unsigned short. xtypes.builtin.unsigned_short = xtypes.atom{['unsigned short']=EMPTY} --- unsigned long. xtypes.builtin.unsigned_long = xtypes.atom{['unsigned long']=EMPTY} --- unsigned long long. xtypes.builtin.unsigned_long_long = xtypes.atom{['unsigned long long']=EMPTY} -- strings and wstrings -- --- `string<n>`: string of length n. -- @int n the maximum length of the string -- @treturn xtemplate the string datatype function xtypes.string(n) return xtypes.atom{string={n}} --NOTE: installed as xtypes.builtin.wstring<n> end --- `wstring<n>`:wstring of length n. -- @int n the maximum length of the wstring -- @treturn xtemplate the wstring datatype function xtypes.wstring(n) return xtypes.atom{wstring={n}} --NOTE: installed as xtypes.builtin.wstring<n> end --- @section end --============================================================================-- -- Built-in annotations --- Builtin Annotations. -- -- Use these to qualify the datatype structure. Some apply to datatypes, -- while others apply to datatype members. -- -- @section BuiltinAnnotations --- Datatype member is a *key* field. `@Key` xtypes.builtin.Key = xtypes.annotation{Key=EMPTY} --- Datatype member id. `@ID{n}` xtypes.builtin.ID = xtypes.annotation{ID=EMPTY} --- Datatype member is optional. `@Optional` xtypes.builtin.Optional = xtypes.annotation{Optional=EMPTY} --- Datatype member is required. `@MustUnderstand` xtypes.builtin.MustUnderstand = xtypes.annotation{MustUnderstand=EMPTY} --- Datatype member is shared. `@Shared` xtypes.builtin.Shared = xtypes.annotation{Shared=EMPTY} --- `enum` datatype is bit-bound. `@BitBound{n}` xtypes.builtin.BitBound = xtypes.annotation{BitBound=EMPTY} --- `enum` datatype is a bit-set. `@BitSet` xtypes.builtin.BitSet = xtypes.annotation{BitSet=EMPTY} --- Datatype extensibility. -- `@Extensibility{'EXTENSIBLE_EXTENSIBILITY'|'MUTABLE_EXTENSIBILITY'|'FINAL_EXTENSIBILITY}` xtypes.builtin.Extensibility = xtypes.annotation{Extensibility=EMPTY} --- Datatype is not top-level it is nexted. `@Nested` xtypes.builtin.Nested = xtypes.annotation{Nested=EMPTY} --- Datatype may (or may not) be top-level. `@top_level{false}` xtypes.builtin.top_level = xtypes.annotation{['top-level']=EMPTY} -- legacy --- @section end --============================================================================-- -- xtypes public interface return { --- `logger` to log messages and get/set the verbosity levels log = log, EMPTY = EMPTY, --==========================================================================-- -- Datatype Attributes KIND = KIND, NAME = NAME, NS = NS, QUALIFIERS = QUALIFIERS, BASE = BASE, SWITCH = SWITCH, --==========================================================================-- -- Datatype Operations --- `ddsl.nsname`: fully qualified name within the enclosing scope. -- @function nsname nsname = _.nsname, --- `ddsl.nsroot`: outermost enclosing `root` namespace. -- @function nsroot nsroot = _.nsroot, --- `ddsl.resolve`: resolve a typedef -- @function resolve resolve = _.resolve, --- `ddsl.template`: get the *cannonical* template instance (`xtemplate`) -- @function template template = _.template, --- `ddsl.new_instance`: create a new instance (`xinstance`) -- @function new_instance new_instance = _.new_instance, --- `ddsl.new_collection`: create a new collection of instances (`xinstances`) -- @function new_collection new_collection = _.new_collection, --- `ddsl.is_collection`: is this a collection of instances (`xinstances`) ? -- @function is_collection is_collection = _.is_collection, --==========================================================================-- -- Datatype Kinds ANNOTATION = xtypes.ANNOTATION, ATOM = xtypes.ATOM, CONST = xtypes.CONST, ENUM = xtypes.ENUM, STRUCT = xtypes.STRUCT, UNION = xtypes.UNION, MODULE = xtypes.MODULE, TYPEDEF = xtypes.TYPEDEF, --==========================================================================-- -- Datatypes -- NOTE: the doc comments are already exported for these items -- composite types const = xtypes.const, enum = xtypes.enum, struct = xtypes.struct, union = xtypes.union, module = xtypes.module, -- typedefs (aliases) typedef = xtypes.typedef, -- qualifiers annotation = xtypes.annotation, array = xtypes.array, sequence = xtypes.sequence, -- pre-defined annotations Key = xtypes.builtin.Key, Extensibility = xtypes.builtin.Extensibility, ID = xtypes.builtin.ID, Optional = xtypes.builtin.Optional, MustUnderstand = xtypes.builtin.MustUnderstand, Shared = xtypes.builtin.Shared, BitBound = xtypes.builtin.BitBound, BitSet = xtypes.builtin.BitSet, Nested = xtypes.builtin.Nested, top_level = xtypes.builtin.top_level, -- pre-defined atomic types boolean = xtypes.builtin.boolean, octet = xtypes.builtin.octet, char = xtypes.builtin.char, wchar = xtypes.builtin.wchar, float = xtypes.builtin.float, double = xtypes.builtin.double, long_double = xtypes.builtin.long_double, short = xtypes.builtin.short, long = xtypes.builtin.long, long_long = xtypes.builtin.long_long, unsigned_short = xtypes.builtin.unsigned_short, unsigned_long = xtypes.builtin.unsigned_long, unsigned_long_long = xtypes.builtin.unsigned_long_long, string = xtypes.string, wstring = xtypes.wstring, }
if UI == nil then UI = {} end ---Deprecated since UIListeners were moved to the regular Listeners. ---Registers a function to call when a specific Lua LeaderLib UI event fires. ---@param event string OnTooltipPositioned ---@param callback function function UI.RegisterListener(event, callback, ...) RegisterListener(event, callback, ...) end ---@param ui UIObject Ext.RegisterListener("UIObjectCreated", function(ui) if ui:GetTypeId() == Data.UIType.msgBox_c then if not Vars.ControllerEnabled then Vars.ControllerEnabled = true Ext.Print("[LeaderLib] Controller mod enabled.") InvokeListenerCallbacks(Listeners.ControllerModeEnabled) end end end) -- Should exist before SessionLoaded Vars.ControllerEnabled = (Ext.GetBuiltinUI("Public/Game/GUI/msgBox_c.swf") or Ext.GetUIByType(Data.UIType.msgBox_c)) ~= nil -- if controllerUI ~= nil then -- Ext.Require("Client/UI/Game.Tooltip.Controllers.lua") -- end Ext.Require("Client/Classes/_Init.lua") Ext.Require("Client/Data/_Init.lua") Ext.Require("Client/ClientHelpers.lua") Ext.Require("Client/ClientNetMessages.lua") Ext.Require("Client/InputManager.lua") Ext.Require("Client/UI/UITypeWorkaround.lua") Ext.Require("Client/UI/UIListeners.lua") Ext.Require("Client/UI/StatusHider.lua") Ext.Require("Client/UI/Tooltips/Game.Tooltip.Extended.lua") Ext.Require("Client/UI/CharacterSheet.lua") Ext.Require("Client/UI/ModMenu/_Init.lua") Ext.Require("Client/UI/Tooltips/TooltipHandler.lua") Ext.Require("Client/UI/Tooltips/TooltipInfoExpander.lua") Ext.Require("Client/UI/ControllerUIHelpers.lua") Ext.Require("Client/UI/UIFeatures.lua") Ext.Require("Client/UI/UIExtensions.lua") Ext.Require("Client/UI/InterfaceCommands.lua") Ext.Require("Client/UI/ContextMenu.lua") if Vars.DebugMode then Ext.Require("Client/UI/DialogKeywords.lua") -- TODO Ext.Require("Client/Debug/UIGeneralDebug.lua") Ext.Require("Client/Debug/UIDebugListeners.lua") Ext.Require("Client/Debug/ClientConsoleCommands.lua") end --Temp Workaround for mods calling this still on the client side if not Data.AddPreset then Data.AddPreset = function() end end if not Classes.PresetData then Classes.PresetData = {Create = function() end} end Ext.RegisterListener("SessionLoading", function() if Vars.ControllerEnabled then InvokeListenerCallbacks(Listeners.ControllerModeEnabled) end end)
local l = { "common.zproto", } return l
return { entities = { {"straight-rail", {x = -1, y = -3}, {dir = "southwest", }}, {"straight-rail", {x = -1, y = -1}, {dir = "northeast", }}, {"curved-rail", {x = 0, y = 0}, {dir = "southeast", }}, {"straight-rail", {x = 1, y = -1}, {dir = "southwest", }}, {"straight-rail", {x = 1, y = 1}, {dir = "northeast", }}, {"straight-rail", {x = 3, y = 1}, {dir = "southwest", }}, }, }
MARS = { onConnect = nil, onDisconnect = nil, onOutputEvent = nil, peers = {}, interfaces = nil, incoming_payload = nil, } function map (instFrom, evtFrom, instTo, evtTo, transform) if instFrom.__mapping [evtFrom] == nil then instFrom.__mapping [evtFrom] = {} end table.insert (instFrom.__mapping[evtFrom], { to = instTo.id, evt = evtTo, transform = transform }) end function mapping (M) MARS.interfaces = type(M) == 'table' and M or nil end
-- mods/default/nodes.lua minetest.register_node("default:stone", { description = "Stone", tiles = {"default_stone.png"}, is_ground_content = true, groups = {cracky=3, stone=1}, drop = 'default:cobble', legacy_mineral = true, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:desert_stone", { description = "Desert Stone", tiles = {"default_desert_stone.png"}, is_ground_content = true, groups = {cracky=3, stone=1}, drop = 'default:desert_stone', legacy_mineral = true, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:stone_with_coal", { description = "Coal Ore", tiles = {"default_stone.png^default_mineral_coal.png"}, is_ground_content = true, groups = {cracky=3}, drop = 'default:coal_lump', sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:stone_with_iron", { description = "Iron Ore", tiles = {"default_stone.png^default_mineral_iron.png"}, is_ground_content = true, groups = {cracky=2}, drop = 'default:iron_lump', sounds = default.node_sound_stone_defaults(), skill=SKILL_METAL, }) minetest.register_abm({ nodenames = {"default:stone_with_iron"}, neighbors = {"group:lava"}, interval = 1.0, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) -- change to a fused iron node if abm_limiter() then return end minetest.set_node(pos, {name = "default:cobble"}) end, }) minetest.register_node("default:stone_with_copper", { description = "Copper Ore", tiles = {"default_stone.png^default_mineral_copper.png"}, is_ground_content = true, groups = {cracky=2}, drop = 'default:copper_lump', sounds = default.node_sound_stone_defaults(), skill=SKILL_METAL, }) minetest.register_node("default:stone_with_mese", { description = "Mese Ore", tiles = {"default_stone.png^default_mineral_mese.png"}, is_ground_content = true, groups = {cracky=1}, drop = "default:mese_crystal", sounds = default.node_sound_stone_defaults(), skill=SKILL_CRYSTAL, }) minetest.register_node("default:stone_with_gold", { description = "Gold Ore", tiles = {"default_stone.png^default_mineral_gold.png"}, is_ground_content = true, groups = {cracky=2}, drop = "default:gold_lump", sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:stone_with_diamond", { description = "Diamond Ore", tiles = {"default_stone.png^default_mineral_diamond.png"}, is_ground_content = true, groups = {cracky=1}, drop = "default:diamond", sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:stonebrick", { description = "Stone Brick", tiles = {"default_stone_brick.png"}, groups = {cracky=2, stone=1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:desert_stonebrick", { description = "Desert Stone Brick", tiles = {"default_desert_stone_brick.png"}, groups = {cracky=2, stone=1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:dirt_with_grass", { description = "Dirt with Grass", tiles = {"default_grass.png", "default_dirt.png", "default_dirt.png^default_grass_side.png"}, is_ground_content = true, groups = {crumbly=3,soil=1}, drop = 'default:dirt', sounds = default.node_sound_dirt_defaults({ footstep = {name="default_grass_footstep", gain=0.25}, }), }) minetest.register_node("default:dirt_with_grass_footsteps", { description = "Dirt with Grass and Footsteps", tiles = {"default_grass_footsteps.png", "default_dirt.png", "default_dirt.png^default_grass_side.png"}, is_ground_content = true, groups = {crumbly=3,soil=1,not_in_creative_inventory=1}, drop = 'default:dirt', sounds = default.node_sound_dirt_defaults({ footstep = {name="default_grass_footstep", gain=0.25}, }), }) minetest.register_node("default:dirt_with_snow", { description = "Dirt with Snow", tiles = {"default_snow.png", "default_dirt.png", "default_dirt.png^default_snow_side.png"}, is_ground_content = true, groups = {crumbly=3,puts_out_fire=1}, drop = 'default:dirt', sounds = default.node_sound_dirt_defaults({ footstep = {name="default_snow_footstep", gain=0.25}, }), }) minetest.register_node("default:dirt", { description = "Dirt", tiles = {"default_dirt.png"}, is_ground_content = true, groups = {crumbly=3,soil=1}, sounds = default.node_sound_dirt_defaults(), }) minetest.register_abm({ nodenames = {"default:dirt"}, neighbors = {"default:dirt_with_grass","default:water_source","default:water_flowing","default:dirt_with_snow","default:snow","default:snowblock"}, interval = 2, chance = 200, action = function(pos, node) if abm_limiter() then return end local above = {x=pos.x, y=pos.y+1, z=pos.z} local name = minetest.get_node(above).name local nodedef = minetest.registered_nodes[name] if nodedef and (nodedef.sunlight_propagates or nodedef.paramtype == "light") and nodedef.liquidtype == "none" and (minetest.get_node_light(above) or 0) >= 13 then if name == "default:snow" or name == "default:snowblock" then minetest.set_node(pos, {name = "default:dirt_with_snow"}) else minetest.set_node(pos, {name = "default:dirt_with_grass"}) end end end }) minetest.register_abm({ nodenames = {"default:dirt"}, neighbors = {"mg:dirt_with_dry_grass"}, interval = 6, chance = 200, action = function(pos, node) if abm_limiter() then return end local above = {x=pos.x, y=pos.y+1, z=pos.z} local name = minetest.get_node(above).name local nodedef = minetest.registered_nodes[name] if nodedef and (nodedef.sunlight_propagates or nodedef.paramtype == "light") and nodedef.liquidtype == "none" and (minetest.get_node_light(above) or 0) >= 13 then minetest.set_node(pos, {name = "mg:dirt_with_dry_grass"}) end end }) minetest.register_abm({ nodenames = {"default:dirt_with_grass","default:dirt_with_snow"}, interval = 2, chance = 20, action = function(pos, node) if abm_limiter() then return end local above = {x=pos.x, y=pos.y+1, z=pos.z} local name = minetest.get_node(above).name local nodedef = minetest.registered_nodes[name] if name ~= "ignore" and nodedef and not ((nodedef.sunlight_propagates or nodedef.paramtype == "light") and nodedef.liquidtype == "none") then minetest.set_node(pos, {name = "default:dirt"}) end end }) minetest.register_node("default:sand", { description = "Sand", tiles = {"default_sand.png"}, is_ground_content = true, groups = {crumbly=3, falling_node=1, sand=1}, sounds = default.node_sound_sand_defaults(), }) minetest.register_node("default:desert_sand", { description = "Desert Sand", tiles = {"default_desert_sand.png"}, is_ground_content = true, groups = {crumbly=3, falling_node=1, sand=1}, sounds = default.node_sound_sand_defaults(), }) minetest.register_node("default:gravel", { description = "Gravel", tiles = {"default_gravel.png"}, is_ground_content = true, groups = {crumbly=2, falling_node=1}, sounds = default.node_sound_dirt_defaults({ footstep = {name="default_gravel_footstep", gain=0.5}, dug = {name="default_gravel_footstep", gain=1.0}, }), }) minetest.register_node("default:river_gravel", { description = "Gravel", tiles = {"default_river_gravel.png"}, is_ground_content = true, groups = {crumbly=2, falling_node=1}, sounds = default.node_sound_dirt_defaults({ footstep = {name="default_gravel_footstep", gain=0.5}, dug = {name="default_gravel_footstep", gain=1.0}, }), }) minetest.register_node("default:sandstone", { description = "Sandstone", tiles = {"default_sandstone.png"}, is_ground_content = true, groups = {crumbly=2,cracky=3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:sandstonebrick", { description = "Sandstone Brick", tiles = {"default_sandstone_brick.png"}, is_ground_content = true, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:clay", { description = "Clay", tiles = {"default_clay.png"}, is_ground_content = true, groups = {crumbly=3}, drop = 'default:clay_lump 4', sounds = default.node_sound_dirt_defaults(), }) -- Regenerative clay minetest.register_abm({ nodenames = {"default:sand"}, neighbors = {"default:dirt"}, interval = 2, chance = 600, action = function(pos, node) if abm_limiter() then return end local above = {x=pos.x, y=pos.y+1, z=pos.z} local name = minetest.get_node(above).name if name == "default:water_source" then minetest.set_node(pos, {name = "default:clay"}) end end }) minetest.register_node("default:brick", { description = "Brick Block", tiles = {"default_brick.png"}, is_ground_content = false, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:tree", { description = "Tree", tiles = {"default_tree_top.png", "default_tree_top.png", "default_tree.png"}, paramtype2 = "facedir", is_ground_content = false, groups = {tree=1,choppy=2,flammable=2}, sounds = default.node_sound_wood_defaults(), on_place = minetest.rotate_node }) minetest.register_node("default:jungletree", { description = "Jungle Tree", tiles = {"default_jungletree_top.png", "default_jungletree_top.png", "default_jungletree.png"}, paramtype2 = "facedir", is_ground_content = false, groups = {tree=1,choppy=2,flammable=2}, sounds = default.node_sound_wood_defaults(), on_place = minetest.rotate_node }) minetest.register_node("default:junglewood", { description = "Junglewood Planks", tiles = {"default_junglewood.png"}, groups = {choppy=2,oddly_breakable_by_hand=2,flammable=3,wood=1}, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:jungleleaves", { description = "Jungle Leaves", drawtype = "allfaces_optional", visual_scale = 1.3, tiles = {"default_jungleleaves.png"}, paramtype = "light", waving = 1, walkable=false, climbable=true, is_ground_content = false, groups = {snappy=3, leafdecay=3, flammable=2, leaves=1}, drop = { max_items = 1, items = { { -- player will get sapling with 1/20 chance items = {'default:junglesapling'}, rarity = 20, }, { -- player will get leaves only if he get no saplings, -- this is because max_items is 1 items = {'default:jungleleaves'}, } } }, sounds = default.node_sound_leaves_defaults(), }) minetest.register_node("default:junglesapling", { description = "Jungle Sapling", drawtype = "plantlike", visual_scale = 1.0, tiles = {"default_junglesapling.png"}, inventory_image = "default_junglesapling.png", wield_image = "default_junglesapling.png", paramtype = "light", walkable = false, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.35, 0.3} }, groups = {snappy=2,dig_immediate=3,flammable=2,attached_node=1}, sounds = default.node_sound_leaves_defaults(), }) minetest.register_node("default:junglegrass", { description = "Jungle Grass", drawtype = "plantlike", visual_scale = 1.3, tiles = {"default_junglegrass.png"}, inventory_image = "default_junglegrass.png", wield_image = "default_junglegrass.png", paramtype = "light", walkable = false, buildable_to = true, is_ground_content = true, groups = {snappy=3,flammable=2,flora=1,attached_node=1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, }) minetest.register_node("default:leaves", { description = "Leaves", drawtype = "allfaces_optional", visual_scale = 1.3, tiles = {"default_leaves.png"}, paramtype = "light", waving = 1, is_ground_content = false, groups = {snappy=3, leafdecay=3, flammable=2, leaves=1}, walkable=false, climbable=true, drop = { max_items = 1, items = { { -- player will get sapling with 1/20 chance items = {'default:sapling'}, rarity = 20, }, { items = {'default:stick'}, rarity = 40, }, { -- player will get leaves only if he get no saplings, -- this is because max_items is 1 items = {'default:leaves'}, } } }, sounds = default.node_sound_leaves_defaults(), }) minetest.register_node("default:cactus", { description = "Cactus", tiles = {"default_cactus_top.png", "default_cactus_top.png", "default_cactus_side.png"}, paramtype2 = "facedir", is_ground_content = true, groups = {snappy=1,choppy=3,flammable=2}, sounds = default.node_sound_wood_defaults(), on_place = minetest.rotate_node }) minetest.register_node("default:papyrus", { description = "Papyrus", drawtype = "plantlike", tiles = {"default_papyrus.png"}, inventory_image = "default_papyrus.png", wield_image = "default_papyrus.png", paramtype = "light", walkable = false, is_ground_content = true, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.5, 0.3} }, groups = {snappy=3,flammable=2}, sounds = default.node_sound_leaves_defaults(), }) minetest.register_node("default:bookshelf", { description = "Bookshelf", tiles = {"default_wood.png", "default_wood.png", "default_bookshelf.png"}, is_ground_content = false, groups = {choppy=3,oddly_breakable_by_hand=2,flammable=3}, sounds = default.node_sound_wood_defaults(), on_rightclick = function(pos, node, clicker) minetest.show_formspec( clicker:get_player_name(), "skills_form", skills.get_skills_formspec(clicker) ) end, }) minetest.register_node("default:glass", { description = "Glass", drawtype = "glasslike", tiles = {"default_glass.png"}, inventory_image = minetest.inventorycube("default_glass.png"), paramtype = "light", sunlight_propagates = true, is_ground_content = false, groups = {cracky=3,oddly_breakable_by_hand=3}, sounds = default.node_sound_glass_defaults(), ground = "vessels:glass_fragments", }) minetest.register_node("default:fence_wood", { description = "Wooden Fence", drawtype = "fencelike", tiles = {"default_wood.png"}, inventory_image = "default_fence.png", wield_image = "default_fence.png", paramtype = "light", is_ground_content = false, selection_box = { type = "fixed", fixed = {-1/7, -1/2, -1/7, 1/7, 1/2, 1/7}, }, groups = {choppy=2,oddly_breakable_by_hand=2,flammable=2}, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:rail", { description = "Rail", drawtype = "raillike", tiles = {"default_rail.png", "default_rail_curved.png", "default_rail_t_junction.png", "default_rail_crossing.png"}, inventory_image = "default_rail.png", wield_image = "default_rail.png", paramtype = "light", walkable = false, is_ground_content = false, selection_box = { type = "fixed", -- but how to specify the dimensions for curved and sideways rails? fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2}, }, groups = {bendy=2,dig_immediate=2,attached_node=1}, }) minetest.register_node("default:ladder", { description = "Ladder", drawtype = "signlike", tiles = {"default_ladder.png"}, inventory_image = "default_ladder.png", wield_image = "default_ladder.png", paramtype = "light", paramtype2 = "wallmounted", walkable = false, climbable = true, is_ground_content = false, selection_box = { type = "wallmounted", --wall_top = = <default> --wall_bottom = = <default> --wall_side = = <default> }, groups = {choppy=2,oddly_breakable_by_hand=3,flammable=2}, legacy_wallmounted = true, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:wood", { description = "Wooden Planks", tiles = {"default_wood.png"}, groups = {choppy=2,oddly_breakable_by_hand=2,flammable=3,wood=1}, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:cloud", { description = "Cloud", tiles = {"default_cloud.png"}, sounds = default.node_sound_defaults(), groups = {not_in_creative_inventory=1}, }) minetest.register_node("default:water_flowing", { description = "Flowing Water", inventory_image = minetest.inventorycube("default_water.png"), drawtype = "flowingliquid", tiles = {"default_water.png"}, special_tiles = { { image="default_water_flowing_animated.png", backface_culling=false, animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=0.8} }, { image="default_water_flowing_animated.png", backface_culling=true, animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=0.8} }, }, alpha = WATER_ALPHA, paramtype = "light", paramtype2 = "flowingliquid", walkable = false, pointable = false, diggable = false, buildable_to = true, drop = "", drowning = 1, liquidtype = "flowing", liquid_alternative_flowing = "default:water_flowing", liquid_alternative_source = "default:water_source", liquid_viscosity = WATER_VISC, freezemelt = "default:snow", post_effect_color = {a=64, r=100, g=100, b=200}, groups = {water=3, liquid=3, puts_out_fire=1, not_in_creative_inventory=1, freezes=1, melt_around=1}, }) minetest.register_node("default:water_source", { description = "Water Source", inventory_image = minetest.inventorycube("default_water.png"), drawtype = "liquid", tiles = { {name="default_water_source_animated.png", animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}} }, special_tiles = { -- New-style water source material (mostly unused) { name="default_water_source_animated.png", animation={type="vertical_frames", aspect_w=128, aspect_h=128, length=2.0}, backface_culling = false, } }, alpha = WATER_ALPHA, paramtype = "light", walkable = false, pointable = false, diggable = false, buildable_to = true, drop = "", drowning = 1, liquidtype = "source", liquid_alternative_flowing = "default:water_flowing", liquid_alternative_source = "default:water_source", liquid_viscosity = WATER_VISC, freezemelt = "default:ice", post_effect_color = {a=64, r=100, g=100, b=200}, groups = {water=3, liquid=3, puts_out_fire=1, freezes=1}, }) minetest.register_node("default:lava_flowing", { description = "Flowing Lava", inventory_image = minetest.inventorycube("default_lava.png"), drawtype = "flowingliquid", tiles = {"default_lava.png"}, special_tiles = { { image="default_lava_flowing_animated.png", backface_culling=false, animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=3.3} }, { image="default_lava_flowing_animated.png", backface_culling=true, animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=3.3} }, }, paramtype = "light", paramtype2 = "flowingliquid", light_source = LIGHT_MAX - 1, walkable = false, pointable = false, diggable = false, buildable_to = true, drop = "", drowning = 1, liquidtype = "flowing", liquid_alternative_flowing = "default:lava_flowing", liquid_alternative_source = "default:lava_source", liquid_viscosity = LAVA_VISC, liquid_renewable = false, damage_per_second = 4*2, post_effect_color = {a=192, r=255, g=64, b=0}, groups = {lava=3, liquid=2, hot=3, igniter=1, not_in_creative_inventory=1}, }) minetest.register_node("default:lava_source", { description = "Lava Source", inventory_image = minetest.inventorycube("default_lava.png"), drawtype = "liquid", tiles = { {name="default_lava_source_animated.png", animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=3.0}} }, special_tiles = { -- New-style lava source material (mostly unused) { name="default_lava_source_animated.png", animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=3.0}, backface_culling = false, } }, paramtype = "light", light_source = LIGHT_MAX - 1, walkable = false, pointable = false, diggable = false, buildable_to = true, drop = "", drowning = 1, liquidtype = "source", liquid_alternative_flowing = "default:lava_flowing", liquid_alternative_source = "default:lava_source", liquid_viscosity = LAVA_VISC, liquid_renewable = false, damage_per_second = 4*2, post_effect_color = {a=192, r=255, g=64, b=0}, groups = {lava=3, liquid=2, hot=3, igniter=1}, }) minetest.register_node("default:torch", { description = "Torch", drawtype = "torchlike", --tiles = {"default_torch_on_floor.png", "default_torch_on_ceiling.png", "default_torch.png"}, tiles = { {name="default_torch_on_floor_animated.png", animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=3.0}}, {name="default_torch_on_ceiling_animated.png", animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=3.0}}, {name="default_torch_animated.png", animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=3.0}} }, inventory_image = "default_torch_on_floor.png", wield_image = "default_torch_on_floor.png", paramtype = "light", paramtype2 = "wallmounted", sunlight_propagates = true, is_ground_content = false, walkable = false, light_source = LIGHT_MAX-1, selection_box = { type = "wallmounted", wall_top = {-0.1, 0.5-0.6, -0.1, 0.1, 0.5, 0.1}, wall_bottom = {-0.1, -0.5, -0.1, 0.1, -0.5+0.6, 0.1}, wall_side = {-0.5, -0.3, -0.1, -0.5+0.3, 0.3, 0.1}, }, groups = {choppy=2,dig_immediate=3,flammable=1,attached_node=1,hot=2}, legacy_wallmounted = true, sounds = default.node_sound_defaults(), }) minetest.register_node("default:sign_wall", { description = "Sign", drawtype = "signlike", tiles = {"default_sign_wall.png"}, inventory_image = "default_sign_wall.png", wield_image = "default_sign_wall.png", paramtype = "light", paramtype2 = "wallmounted", sunlight_propagates = true, is_ground_content = false, walkable = false, selection_box = { type = "wallmounted", --wall_top = <default> --wall_bottom = <default> --wall_side = <default> }, groups = {choppy=2,dig_immediate=2,attached_node=1}, legacy_wallmounted = true, sounds = default.node_sound_defaults(), on_construct = function(pos) --local n = minetest.get_node(pos) local meta = minetest.get_meta(pos) meta:set_string("formspec", "field[text;;${text}]") meta:set_string("infotext", "\"\"") end, on_receive_fields = function(pos, formname, fields, sender) --print("Sign at "..minetest.pos_to_string(pos).." got "..dump(fields)) if minetest.is_protected(pos, sender:get_player_name()) then minetest.record_protection_violation(pos, sender:get_player_name()) return end local meta = minetest.get_meta(pos) fields.text = fields.text or "" minetest.log("action", (sender:get_player_name() or "").." wrote \""..fields.text.. "\" to sign at "..minetest.pos_to_string(pos)) meta:set_string("text", fields.text) meta:set_string("infotext", '"'..fields.text..'"') end, }) default.chest_formspec = "size[8,9]".. "list[current_name;main;0,0;8,4;]".. "list[current_player;main;0,5;8,4;]" function default.get_locked_chest_formspec(pos) local spos = pos.x .. "," .. pos.y .. "," ..pos.z local formspec = "size[8,9]".. "list[nodemeta:".. spos .. ";main;0,0;8,4;]".. "list[current_player;main;0,5;8,4;]" return formspec end minetest.register_node("default:chest", { description = "Chest", tiles = {"default_chest_top.png", "default_chest_top.png", "default_chest_side.png", "default_chest_side.png", "default_chest_side.png", "default_chest_front.png"}, paramtype2 = "facedir", groups = {choppy=2,oddly_breakable_by_hand=2}, legacy_facedir_simple = true, is_ground_content = false, sounds = default.node_sound_wood_defaults(), on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("formspec",default.chest_formspec) meta:set_string("infotext", "Chest") local inv = meta:get_inventory() inv:set_size("main", 8*4) end, after_dig_node = function(pos, oldnode, oldmetadata, digger) local meta = minetest:get_meta(pos) meta:from_table(oldmetadata) local inv = meta:get_inventory() default.dump_inv(pos,"main",inv) end, on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) minetest.log("action", player:get_player_name().. " moves stuff in chest at "..minetest.pos_to_string(pos)) end, on_metadata_inventory_put = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name().. " moves stuff to chest at "..minetest.pos_to_string(pos)) end, on_metadata_inventory_take = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name().. " takes stuff from chest at "..minetest.pos_to_string(pos)) end, }) minetest.register_node("default:npc_chest", { description = "Chest", tiles = {"default_chest_top.png", "default_chest_top.png", "default_chest_side.png", "default_chest_side.png", "default_chest_side.png", "default_chest_front.png"}, paramtype2 = "facedir", groups = {choppy=2,oddly_breakable_by_hand=2}, drop = "default:chest", legacy_facedir_simple = true, is_ground_content = false, sounds = default.node_sound_wood_defaults(), on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("formspec",default.chest_formspec) meta:set_string("infotext", "Chest") local inv = meta:get_inventory() inv:set_size("main", 8*4) end, after_dig_node = function(pos, oldnode, oldmetadata, digger) local meta = minetest:get_meta(pos) meta:from_table(oldmetadata) local inv = meta:get_inventory() default.dump_inv(pos,"main",inv) end, on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) minetest.log("action", player:get_player_name().. " moves stuff in chest at "..minetest.pos_to_string(pos)) end, on_metadata_inventory_put = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name().. " moves stuff to chest at "..minetest.pos_to_string(pos)) end, on_metadata_inventory_take = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name().. " takes stuff from chest at "..minetest.pos_to_string(pos)) end, }) -- respawn random items in the npc chests minetest.register_abm({ nodenames = {"default:npc_chest"}, interval = 10, chance = 600, action = function(pos, node, active_object_count, active_object_count_wider) if abm_limiter() then return end local item_count = math.random(0,5) local items_available = { [0] = "default:apple", [1] = "mobs:meat_raw", [2]="farming:bread",[3]="bushes:berry_pie_cooked",[4]="bushes:basket_empty",[5]="farming:wheat",[6]="throwing:arrow",[7]="default:torch",[8]="farming:string"} local meta = minetest.get_meta(pos) local inv = meta:get_inventory() for i = 0, item_count do local item_idx = math.random(0,8) inv:add_item("main",items_available[item_idx]) end end, }) local function has_locked_chest_privilege(meta, player) if meta ~= nil then if (player:get_player_name() == meta:get_string("owner")) or (minetest.check_player_privs(player:get_player_name(), {server=true})) then return true end end return false end minetest.register_node("default:chest_locked", { description = "Locked Chest", tiles = {"default_chest_top.png", "default_chest_top.png", "default_chest_side.png", "default_chest_side.png", "default_chest_side.png", "default_chest_lock.png"}, paramtype2 = "facedir", groups = {choppy=2,oddly_breakable_by_hand=2}, legacy_facedir_simple = true, is_ground_content = false, sounds = default.node_sound_wood_defaults(), after_place_node = function(pos, placer) local meta = minetest.get_meta(pos) meta:set_string("owner", placer:get_player_name() or "") meta:set_string("infotext", "Locked Chest (owned by ".. meta:get_string("owner")..")") end, on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("infotext", "Locked Chest") meta:set_string("owner", "") local inv = meta:get_inventory() inv:set_size("main", 8*4) end, can_dig = function(pos,player) local meta = minetest.get_meta(pos); local inv = meta:get_inventory() if has_locked_chest_privilege(meta, player) then if inv:is_empty("main") == false then default.dump_inv(pos,"main") end return true else return false end end, allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) local meta = minetest.get_meta(pos) if not has_locked_chest_privilege(meta, player) then minetest.log("action", player:get_player_name().. " tried to access a locked chest belonging to ".. meta:get_string("owner").." at ".. minetest.pos_to_string(pos)) return 0 end return count end, allow_metadata_inventory_put = function(pos, listname, index, stack, player) local meta = minetest.get_meta(pos) if not has_locked_chest_privilege(meta, player) then minetest.log("action", player:get_player_name().. " tried to access a locked chest belonging to ".. meta:get_string("owner").." at ".. minetest.pos_to_string(pos)) return 0 end return stack:get_count() end, allow_metadata_inventory_take = function(pos, listname, index, stack, player) local meta = minetest.get_meta(pos) if not has_locked_chest_privilege(meta, player) then minetest.log("action", player:get_player_name().. " tried to access a locked chest belonging to ".. meta:get_string("owner").." at ".. minetest.pos_to_string(pos)) return 0 end return stack:get_count() end, on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) minetest.log("action", player:get_player_name().. " moves stuff in locked chest at "..minetest.pos_to_string(pos)) end, on_metadata_inventory_put = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name().. " moves stuff to locked chest at "..minetest.pos_to_string(pos)) end, on_metadata_inventory_take = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name().. " takes stuff from locked chest at "..minetest.pos_to_string(pos)) end, on_rightclick = function(pos, node, clicker) local meta = minetest.get_meta(pos) if has_locked_chest_privilege(meta, clicker) then minetest.show_formspec( clicker:get_player_name(), "default:chest_locked", default.get_locked_chest_formspec(pos) ) end end, }) function default.get_furnace_active_formspec(pos, percent) local formspec = "size[8,9]".. "image[2,2;1,1;default_furnace_fire_bg.png^[lowpart:".. (100-percent)..":default_furnace_fire_fg.png]".. "list[current_name;fuel;2,3;1,1;]".. "list[current_name;src;2,1;1,1;]".. "list[current_name;dst;5,1;2,2;]".. "list[current_player;main;0,5;8,4;]" return formspec end function default.furnace_available(pos) local meta = minetest.get_meta(pos) print("Furnace in_use: "..tostring(meta:get_int("in_use"))) if meta:get_int("in_use") == 1 then return false else return true end end default.furnace_inactive_formspec = "size[8,9]".. "image[2,2;1,1;default_furnace_fire_bg.png]".. "list[current_name;fuel;2,3;1,1;]".. "list[current_name;src;2,1;1,1;]".. "list[current_name;dst;5,1;2,2;]".. "list[current_player;main;0,5;8,4;]" minetest.register_node("default:furnace", { description = "Furnace", tiles = {"default_furnace_top.png", "default_furnace_bottom.png", "default_furnace_side.png", "default_furnace_side.png", "default_furnace_side.png", "default_furnace_front.png"}, paramtype2 = "facedir", groups = {cracky=2}, legacy_facedir_simple = true, is_ground_content = false, sounds = default.node_sound_stone_defaults(), on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("formspec", default.furnace_inactive_formspec) meta:set_string("infotext", "Furnace") local inv = meta:get_inventory() inv:set_size("fuel", 1) inv:set_size("src", 1) inv:set_size("dst", 4) end, after_dig_node = function(pos, oldnode, oldmetadata, digger) local meta = minetest:get_meta(pos) meta:from_table(oldmetadata) local inv = meta:get_inventory() default.dump_inv(pos,"fuel",inv) default.dump_inv(pos,"dst",inv) default.dump_inv(pos,"src",inv) end, allow_metadata_inventory_put = function(pos, listname, index, stack, player) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() if listname == "fuel" then if minetest.get_craft_result({method="fuel",width=1,items={stack}}).time ~= 0 then if inv:is_empty("src") then meta:set_string("infotext","Furnace is empty") end return stack:get_count() else return 0 end elseif listname == "src" then print(player:get_player_name().." put item into furnace") meta:set_string("owner",player:get_player_name()) return stack:get_count() elseif listname == "dst" then return 0 end end, allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local stack = inv:get_stack(from_list, from_index) if to_list == "fuel" then if minetest.get_craft_result({method="fuel",width=1,items={stack}}).time ~= 0 then if inv:is_empty("src") then meta:set_string("infotext","Furnace is empty") end return count else return 0 end elseif to_list == "src" then return count elseif to_list == "dst" then return 0 end end, }) minetest.register_node("default:furnace_active", { description = "Furnace", tiles = { "default_furnace_top.png", "default_furnace_bottom.png", "default_furnace_side.png", "default_furnace_side.png", "default_furnace_side.png", { image = "default_furnace_front_active.png", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1.5 }, } }, paramtype2 = "facedir", light_source = 8, drop = "default:furnace", groups = {cracky=2, not_in_creative_inventory=1,hot=1}, legacy_facedir_simple = true, is_ground_content = false, sounds = default.node_sound_stone_defaults(), on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("formspec", default.furnace_inactive_formspec) meta:set_string("infotext", "Furnace"); local inv = meta:get_inventory() inv:set_size("fuel", 1) inv:set_size("src", 1) inv:set_size("dst", 4) end, can_dig = function(pos,player) if default.furnace_available(pos) then local meta = minetest.get_meta(pos); local inv = meta:get_inventory() if not inv:is_empty("fuel") then return false elseif not inv:is_empty("dst") then return false elseif not inv:is_empty("src") then return false end return true else return false end end, allow_metadata_inventory_put = function(pos, listname, index, stack, player) if default.furnace_available(pos) then local meta = minetest.get_meta(pos) local inv = meta:get_inventory() if listname == "fuel" then if minetest.get_craft_result({method="fuel",width=1,items={stack}}).time ~= 0 then if inv:is_empty("src") then meta:set_string("infotext","Furnace is empty") end return stack:get_count() else return 0 end elseif listname == "src" then print(player:get_player_name().." put item into furnace") meta:set_string("owner",player:get_player_name()) return stack:get_count() elseif listname == "dst" then return 0 end else return 0 end end, allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) if default.furnace_available(pos) then local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local stack = inv:get_stack(from_list, from_index) if to_list == "fuel" then if minetest.get_craft_result({method="fuel",width=1,items={stack}}).time ~= 0 then if inv:is_empty("src") then meta:set_string("owner","") meta:set_string("infotext","Furnace is empty") end return count else return 0 end elseif to_list == "src" then return count elseif to_list == "dst" then return 0 end else return 0 end end, allow_metadata_inventory_take = function(pos, listname, index, stack, player) if not default.furnace_available(pos) then return 0 else return stack:get_count() end end }) local function swap_node(pos,name) local node = minetest.get_node(pos) if node.name == name then return end node.name = name minetest.swap_node(pos,node) end minetest.register_abm({ nodenames = {"default:furnace","default:furnace_active"}, interval = 1.0, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local meta = minetest.get_meta(pos) for i, name in ipairs({ "fuel_totaltime", "fuel_time", "src_totaltime", "src_time" }) do if meta:get_string(name) == "" then meta:set_float(name, 0.0) end end local owner = meta:get_string("owner") local inv = meta:get_inventory() local srclist = inv:get_list("src") local cooked = nil local aftercooked if srclist then cooked, aftercooked = minetest.get_craft_result({method = "cooking", width = 1, items = srclist}) end local was_active = false if meta:get_float("fuel_time") < meta:get_float("fuel_totaltime") then was_active = true meta:set_float("fuel_time", meta:get_float("fuel_time") + 1) meta:set_float("src_time", meta:get_float("src_time") + 1) if cooked and cooked.item and meta:get_float("src_time") >= cooked.time then -- check their skills local probability = 100 local skilled_item = false if cooked.item:get_definition().groups["skill"] ~= nil and owner ~= "" then probability = skills.get_probability(owner,SKILL_SMELTING,cooked.item:get_definition().groups["skill"]) skilled_item = true end math.randomseed(os.time() + probability) local r = math.random(1,99) if r < probability then -- check if there's room for output in "dst" list if inv:room_for_item("dst",cooked.item) then -- Put result in "dst" list inv:add_item("dst", cooked.item) -- take stuff from "src" list inv:set_stack("src", 1, aftercooked.items[1]) if r < 30 and skilled_item == true and cooked.item:get_name() ~= "" then -- 30% chance they will gain some experience local fdir = minetest.facedir_to_dir(node.param2) local npos = {} npos.x = pos.x + ( (fdir.x * 1.5) * -1 ) npos.y = pos.y + ( (fdir.y * 1.5) * -1 ) + 0.25 npos.z = pos.z + ( (fdir.z * 1.5) * -1 ) default.drop_item(npos,"experience:1_exp") end else --print("Could not insert '"..cooked.item:to_string().."'") end else -- 90% chance they will lose the item they are trying to smelt if r < 90 then inv:set_stack("src", 1, aftercooked.items[1]) end end meta:set_string("src_time", 0) end end if meta:get_float("fuel_time") < meta:get_float("fuel_totaltime") then local percent = math.floor(meta:get_float("fuel_time") / meta:get_float("fuel_totaltime") * 100) meta:set_string("infotext","Furnace active: "..percent.."%") swap_node(pos,"default:furnace_active") meta:set_string("formspec",default.get_furnace_active_formspec(pos, percent)) if meta:get_int("sound_played") == nil or ( os.time() - meta:get_int("sound_played") ) >= 4 then minetest.sound_play("default_furnace",{pos=pos}) meta:set_string("sound_played",os.time()) end return end local fuel = nil local afterfuel local cooked = nil local fuellist = inv:get_list("fuel") local srclist = inv:get_list("src") if srclist then cooked = minetest.get_craft_result({method = "cooking", width = 1, items = srclist}) end if fuellist then fuel, afterfuel = minetest.get_craft_result({method = "fuel", width = 1, items = fuellist}) end if not fuel or fuel.time <= 0 then meta:set_string("infotext","Furnace out of fuel") swap_node(pos,"default:furnace") meta:set_string("formspec", default.furnace_inactive_formspec) meta:set_int("in_use",0) return end if cooked.item:is_empty() then if was_active then meta:set_string("infotext","Furnace is empty") swap_node(pos,"default:furnace") meta:set_string("formspec", default.furnace_inactive_formspec) meta:set_string("owner","") end return end meta:set_string("fuel_totaltime", fuel.time) meta:set_string("fuel_time", 0) inv:set_stack("fuel", 1, afterfuel.items[1]) end, }) minetest.register_node("default:cobble", { description = "Cobblestone", tiles = {"default_cobble.png"}, is_ground_content = true, groups = {cracky=3, stone=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:mossycobble", { description = "Mossy Cobblestone", tiles = {"default_mossycobble.png"}, is_ground_content = true, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:coalblock", { description = "Coal Block", tiles = {"default_coal_block.png"}, is_ground_content = true, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:steelblock", { description = "Steel Block", tiles = {"default_steel_block.png"}, is_ground_content = true, groups = {cracky=1,level=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:copperblock", { description = "Copper Block", tiles = {"default_copper_block.png"}, is_ground_content = true, groups = {cracky=1,level=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:bronzeblock", { description = "Bronze Block", tiles = {"default_bronze_block.png"}, is_ground_content = true, groups = {cracky=1,level=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:mese", { description = "Mese Block", tiles = {"default_mese_block.png"}, is_ground_content = true, groups = {cracky=1,level=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_alias("default:mese_block", "default:mese") minetest.register_node("default:goldblock", { description = "Gold Block", tiles = {"default_gold_block.png"}, is_ground_content = true, groups = {cracky=1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:diamondblock", { description = "Diamond Block", tiles = {"default_diamond_block.png"}, is_ground_content = true, groups = {cracky=1,level=3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:obsidian_glass", { description = "Obsidian Glass", drawtype = "glasslike", tiles = {"default_obsidian_glass.png"}, paramtype = "light", is_ground_content = false, sunlight_propagates = true, sounds = default.node_sound_glass_defaults(), groups = {cracky=3,oddly_breakable_by_hand=3}, }) minetest.register_node("default:obsidian", { description = "Obsidian", tiles = {"default_obsidian.png"}, is_ground_content = true, sounds = default.node_sound_stone_defaults(), groups = {cracky=1,level=2}, }) minetest.register_node("default:nyancat", { description = "Nyan Cat", tiles = {"default_nc_side.png", "default_nc_side.png", "default_nc_side.png", "default_nc_side.png", "default_nc_back.png", "default_nc_front.png"}, paramtype2 = "facedir", groups = {cracky=2}, is_ground_content = false, legacy_facedir_simple = true, sounds = default.node_sound_defaults(), }) minetest.register_node("default:nyancat_rainbow", { description = "Nyan Cat Rainbow", tiles = {"default_nc_rb.png^[transformR90", "default_nc_rb.png^[transformR90", "default_nc_rb.png", "default_nc_rb.png"}, paramtype2 = "facedir", groups = {cracky=2}, is_ground_content = false, sounds = default.node_sound_defaults(), }) minetest.register_node("default:sapling", { description = "Sapling", drawtype = "plantlike", visual_scale = 1.0, tiles = {"default_sapling.png"}, inventory_image = "default_sapling.png", wield_image = "default_sapling.png", paramtype = "light", walkable = false, is_ground_content = true, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.35, 0.3} }, groups = {snappy=2,dig_immediate=3,flammable=2,attached_node=1}, sounds = default.node_sound_leaves_defaults(), }) minetest.register_node("default:apple", { description = "Apple", drawtype = "plantlike", visual_scale = 1.0, tiles = {"default_apple.png"}, inventory_image = "default_apple.png", paramtype = "light", sunlight_propagates = true, walkable = false, is_ground_content = true, selection_box = { type = "fixed", fixed = {-0.2, -0.5, -0.2, 0.2, 0, 0.2} }, groups = {fleshy=3,dig_immediate=3,flammable=2,leafdecay=3,leafdecay_drop=1}, on_use = minetest.item_eat(1), sounds = default.node_sound_leaves_defaults(), after_place_node = function(pos, placer, itemstack) if placer:is_player() then minetest.set_node(pos, {name="default:apple", param2=1}) end end, }) minetest.register_node("default:dry_shrub", { description = "Dry Shrub", drawtype = "plantlike", visual_scale = 1.0, tiles = {"default_dry_shrub.png"}, inventory_image = "default_dry_shrub.png", wield_image = "default_dry_shrub.png", paramtype = "light", waving = 1, walkable = false, is_ground_content = true, buildable_to = true, groups = {snappy=3,flammable=3,attached_node=1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, }) minetest.register_node("default:grass_1", { description = "Grass", drawtype = "plantlike", tiles = {"default_grass_1.png"}, -- use a bigger inventory image inventory_image = "default_grass_3.png", wield_image = "default_grass_3.png", paramtype = "light", walkable = false, is_ground_content = true, buildable_to = true, groups = {snappy=3,flammable=3,flora=1,attached_node=1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, on_place = function(itemstack, placer, pointed_thing) -- place a random grass node local stack = ItemStack("default:grass_"..math.random(1,5)) local ret = minetest.item_place(stack, placer, pointed_thing) return ItemStack("default:grass_1 "..itemstack:get_count()-(1-ret:get_count())) end, }) minetest.register_node("default:grass_2", { description = "Grass", drawtype = "plantlike", tiles = {"default_grass_2.png"}, inventory_image = "default_grass_2.png", wield_image = "default_grass_2.png", paramtype = "light", walkable = false, buildable_to = true, is_ground_content = true, drop = "default:grass_1", groups = {snappy=3,flammable=3,flora=1,attached_node=1,not_in_creative_inventory=1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, }) minetest.register_node("default:grass_3", { description = "Grass", drawtype = "plantlike", tiles = {"default_grass_3.png"}, inventory_image = "default_grass_3.png", wield_image = "default_grass_3.png", paramtype = "light", walkable = false, buildable_to = true, is_ground_content = true, drop = "default:grass_1", groups = {snappy=3,flammable=3,flora=1,attached_node=1,not_in_creative_inventory=1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, }) minetest.register_node("default:grass_4", { description = "Grass", drawtype = "plantlike", tiles = {"default_grass_4.png"}, inventory_image = "default_grass_4.png", wield_image = "default_grass_4.png", paramtype = "light", walkable = false, buildable_to = true, is_ground_content = true, drop = "default:grass_1", groups = {snappy=3,flammable=3,flora=1,attached_node=1,not_in_creative_inventory=1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, }) minetest.register_node("default:grass_5", { description = "Grass", drawtype = "plantlike", tiles = {"default_grass_5.png"}, inventory_image = "default_grass_5.png", wield_image = "default_grass_5.png", paramtype = "light", walkable = false, buildable_to = true, is_ground_content = true, drop = "default:grass_1", groups = {snappy=3,flammable=3,flora=1,attached_node=1,not_in_creative_inventory=1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, }) minetest.register_node("default:ice", { description = "Ice", tiles = {"default_ice.png"}, is_ground_content = true, paramtype = "light", freezemelt = "default:water_source", groups = {choppy=3,cracky=3, melts=1}, sounds = default.node_sound_glass_defaults(), }) minetest.register_node("default:snow", { description = "Snow", tiles = {"default_snow.png"}, inventory_image = "default_snowball.png", wield_image = "default_snowball.png", is_ground_content = true, paramtype = "light", buildable_to = true, leveled = 7, drawtype = "nodebox", freezemelt = "default:water_flowing", walkable=false, node_box = { type = "leveled", fixed = { {-0.5, -0.5, -0.5, 0.5, -0.5+2/16, 0.5}, }, }, groups = {crumbly=3,falling_node=1, melts=1, float=1,puts_out_fire=1}, sounds = default.node_sound_dirt_defaults({ footstep = {name="default_snow_footstep", gain=0.25}, dug = {name="default_snow_footstep", gain=0.75}, }), }) minetest.register_alias("snow", "default:snow") minetest.register_node("default:snowblock", { description = "Snow Block", tiles = {"default_snow.png"}, is_ground_content = true, freezemelt = "default:water_source", groups = {crumbly=3, melts=1, puts_out_fire=1}, sounds = default.node_sound_dirt_defaults({ footstep = {name="default_snow_footstep", gain=0.25}, dug = {name="default_snow_footstep", gain=0.75}, }), })
---------------------------------------------------------------------------- -- @author Lucas de Vries &lt;lucas@tuple-typed.org&gt; -- @copyright 2009-2010 Lucas de Vries -- Licensed under the WTFPL ---------------------------------------------------------------------------- -- Load awful require("awful") -- Load beautiful require("beautiful") ---- {{{ Grab environment local ipairs = ipairs local pairs = pairs local print = print local type = type local tonumber = tonumber local tostring = tostring local unpack = unpack local math = math local table = table local awful = awful local os = os local io = io local string = string local awful = awful local beautiful = beautiful -- Grab C API local capi = { root = root, awesome = awesome, screen = screen, client = client, mouse = mouse, button = button, titlebar = titlebar, widget = widget, hooks = hooks, keygrabber = keygrabber, wibox = wibox, widget = widget, } -- }}} --- Utilities for controlling the cursor module("rodentbane") -- Local data local bindings = {} local history = {} local current = nil local wiboxes = nil --- Create the wiboxes to display. function init() -- Wiboxes table wiboxes = {} -- Borders local borders = {"horiz", "vert", "left", "right", "top", "bottom"} -- Create wibox for each border for i, border in ipairs(borders) do wiboxes[border] = capi.wibox({ bg = beautiful.rodentbane_bg or beautiful.border_focus or "#C50B0B", ontop = true, }) end end --- Draw the guidelines on screen using wiboxes. -- @param area The area of the screen to draw on, defaults to current area. function draw(area) -- Default to current area local ar = area or current -- Get numbers local rwidth = beautiful.rodentbane_width or 2 -- Stop if the area is too small if ar.width < rwidth*3 or ar.height < rwidth*3 then stop() return false end -- Put the wiboxes on the correct screen for border, box in pairs(wiboxes) do box.screen = ar.screen end -- Horizontal border wiboxes.horiz:geometry({ x = ar.x+rwidth, y = ar.y+math.floor(ar.height/2), height = rwidth, width = ar.width-(rwidth*2), }) -- Vertical border wiboxes.vert:geometry({ x = ar.x+math.floor(ar.width/2), y = ar.y+rwidth, width = rwidth, height = ar.height-(rwidth*2), }) -- Left border wiboxes.left:geometry({ x = ar.x, y = ar.y, width = rwidth, height = ar.height, }) -- Right border wiboxes.right:geometry({ x = ar.x+ar.width-rwidth, y = ar.y, width = rwidth, height = ar.height, }) -- Top border wiboxes.top:geometry({ x = ar.x, y = ar.y, height = rwidth, width = ar.width, }) -- Bottom border wiboxes.bottom:geometry({ x = ar.x, y = ar.y+ar.height-rwidth, height = rwidth, width = ar.width, }) end --- Cut the navigation area into a direction. -- @param dir Direction to cut to {"up", "right", "down", "left"}. function cut(dir) -- Store previous area table.insert(history, 1, awful.util.table.join(current)) -- Cut in a direction if dir == "up" then current.height = math.floor(current.height/2) elseif dir == "down" then current.y = current.y+math.floor(current.height/2) current.height = math.floor(current.height/2) elseif dir == "left" then current.width = math.floor(current.width/2) elseif dir == "right" then current.x = current.x+math.floor(current.width/2) current.width = math.floor(current.width/2) end -- Redraw the box draw() end --- Move the navigation area in a direction. -- @param dir Direction to move to {"up", "right", "down", "left"}. -- @param ratio Ratio of movement, multiplied by the size of the current area, -- defaults to 0.5 (ie. half the area size. function move(dir, ratio) -- Store previous area table.insert(history, 1, awful.util.table.join(current)) -- Default to ratio 0.5 local rt = ratio or 0.5 -- Move to a direction if dir == "up" then current.y = current.y-math.floor(current.height*rt) elseif dir == "down" then current.y = current.y+math.floor(current.height*rt) elseif dir == "left" then current.x = current.x-math.floor(current.width*rt) elseif dir == "right" then current.x = current.x+math.floor(current.width*rt) end -- Redraw the box draw() end --- Bind a key in rodentbane mode. -- @param modkeys Modifier key combination to bind to. -- @param key Main key to bind to. -- @param func Function to bind the keys to. function bind(modkeys, key, func) -- Create binding local bind = {modkeys, key, func} -- Add to bindings table table.insert(bindings, bind) end --- Callback function for the keygrabber. -- @param modkeys Modkeys that were pressed. -- @param key Main key that was pressed. -- @param evtype Pressed or released event. function keyevent(modkeys, key, evtype) -- Ignore release events and modifier keys if evtype == "release" or key == "Shift_L" or key == "Shift_R" or key == "Control_L" or key == "Control_R" or key == "Super_L" or key == "Super_R" or key == "Hyper_L" or key == "Hyper_R" or key == "Alt_L" or key == "Alt_R" or key == "Meta_L" or key == "Meta_R" then return true end -- Special cases for printable characters -- HACK: Maybe we need a keygrabber that gives keycodes ? if key == " " then key = "Space" end -- Figure out what to call for ind, bind in ipairs(bindings) do if bind[2]:lower() == key:lower() and table_equals(bind[1], modkeys) then -- Call the function if type(bind[3]) == "table" then -- Allow for easy passing of arguments local func = bind[3][1] local args = {} -- Add the rest of the arguments for i, arg in ipairs(bind[3]) do if i > 1 then table.insert(args, arg) end end -- Call function with args func(unpack(args)) else -- Call function directly bind[3]() end -- A bind was found, continue grabbing return true end end -- No key was found, stop grabbing stop() return false end --- Check if two tables have the same values. -- @param t1 First table to check. -- @param t2 Second table to check. -- @return True if the tables are equivalent, false otherwise. function table_equals(t1, t2) -- Check first table for i, item in ipairs(t1) do if item ~= "Mod2" and awful.util.table.hasitem(t2, item) == nil then -- An unequal item was found return false end end -- Check second table for i, item in ipairs(t2) do if item ~= "Mod2" and awful.util.table.hasitem(t1, item) == nil then -- An unequal item was found return false end end -- All items were equal return true end --- Warp the mouse to the center of the navigation area function warp() capi.mouse.coords({ x = current.x+(current.width/2), y = current.y+(current.height/2), }) end --- Click with a button -- @param button Button number to click with, defaults to left (1) function click(button) -- Default to left click local b = button or 1 -- TODO: Figure out a way to use fake_input for clicks --capi.root.fake_input("button_press", button) --capi.root.fake_input("button_release", button) -- Use xdotool when available, otherwise try xte command = "xdotool click "..b.." &> /dev/null" .." || xte 'mouseclick "..b.."' &> /dev/null" .." || echo 'W: rodentbane: either xdotool or xte" .." is required to emulate mouse clicks, neither was found.'" awful.util.spawn_with_shell(command) end --- Undo a change to the area function undo() -- Restore area if #history > 0 then current = history[1] table.remove(history, 1) draw() end end --- Convenience function to bind to default keys. function binddefault() -- Cut with hjkl bind({}, "h", {cut, "left"}) bind({}, "j", {cut, "down"}) bind({}, "k", {cut, "up"}) bind({}, "l", {cut, "right"}) -- Move with Shift+hjkl bind({"Shift"}, "h", {move, "left"}) bind({"Shift"}, "j", {move, "down"}) bind({"Shift"}, "k", {move, "up"}) bind({"Shift"}, "l", {move, "right"}) -- Undo with u bind({}, "u", undo) -- Left click with space bind({}, "Space", function () warp() click() stop() end) -- Double Left click with alt+space bind({"Mod1"}, "Space", function () warp() click() click() stop() end) -- Middle click with Control+space bind({"Control"}, "Space", function () warp() click(2) stop() end) -- Right click with shift+space bind({"Shift"}, "Space", function () warp() click(3) stop() end) -- Only warp with return bind({}, "Return", function () warp() end) end --- Start the navigation sequence. -- @param screen Screen to start navigation on, defaults to current screen. -- @param recall Whether the previous area should be recalled (defaults to -- false). function start(screen, recall) -- Default to current screen local scr = screen or capi.mouse.screen -- Initialise if not already done if wiboxes == nil then -- Add default bindings if we have none ourselves if #bindings == 0 then binddefault() end -- Create the wiboxes init() end -- Empty current area if needed if not recall then -- Start with a complete area current = capi.screen[scr].workarea -- Empty history history = {} end -- Move to the right screen current.screen = scr -- Start the keygrabber capi.keygrabber.run(keyevent) -- Draw the box draw() end --- Stop the navigation sequence without doing anything. function stop() -- Stop the keygrabber capi.keygrabber.stop() -- Hide all wiboxes for border, box in pairs(wiboxes) do box.screen = nil end end
SDL2_DIR = "sdl2" SDL2_INCLUDE = SDL2_DIR.."/include" local solution_name = _ACTION if _ACTION == "ios" then solution_name = _ACTION _ACTION = "xcode4" system "ios" end workspace "sdl2" targetdir "bin/%{_ACTION}-%{cfg.platform}-%{cfg.buildcfg}/%{prj.name}" objdir "temp/%{_ACTION}-%{cfg.platform}-%{cfg.buildcfg}/%{prj.name}" location (path.join("project", solution_name)) configurations { "Release", "Debug" } project "sdl2" kind "StaticLib" language "C" defines "HAVE_LIBC" -- StaticLib --defines "SDL_SHARED" -- SharedLib includedirs { path.join(SDL2_DIR, "include"), } files { path.join(SDL2_DIR, "include/**"), path.join(SDL2_DIR, "src/*.c"), path.join(SDL2_DIR, "src/*.h"), path.join(SDL2_DIR, "src/cpuinfo/**"), path.join(SDL2_DIR, "src/dynapi/**"), path.join(SDL2_DIR, "src/atomic/**"), path.join(SDL2_DIR, "src/libm/**"), path.join(SDL2_DIR, "src/stdlib/**"), path.join(SDL2_DIR, "src/filesystem/dummy/**"), path.join(SDL2_DIR, "src/loadso/dummy/**"), -- AUDIO -- path.join(SDL2_DIR, "src/audio/*.c"), path.join(SDL2_DIR, "src/audio/*.h"), path.join(SDL2_DIR, "src/audio/dummy/**"), -- EVENTS -- path.join(SDL2_DIR, "src/events/*"), -- FILE -- path.join(SDL2_DIR, "src/file/*.c"), -- HAPTIC -- path.join(SDL2_DIR, "src/haptic/*.c"), path.join(SDL2_DIR, "src/haptic/*.h"), path.join(SDL2_DIR, "src/haptic/dummy/**"), -- joystick -- path.join(SDL2_DIR, "src/joystick/*.c"), path.join(SDL2_DIR, "src/joystick/*.h"), path.join(SDL2_DIR, "src/joystick/dummy/**"), path.join(SDL2_DIR, "src/joystick/hidapi/*.c"), path.join(SDL2_DIR, "src/joystick/hidapi/*.h"), path.join(SDL2_DIR, "src/joystick/virtual/*"), -- LOCALE -- path.join(SDL2_DIR, "src/locale/*.c"), path.join(SDL2_DIR, "src/locale/*.h"), path.join(SDL2_DIR, "src/locale/dummy/**"), -- POWER -- path.join(SDL2_DIR, "src/power/*.c"), path.join(SDL2_DIR, "src/power/*.h"), -- RENDER -- path.join(SDL2_DIR, "src/render/*.c"), path.join(SDL2_DIR, "src/render/*.h"), path.join(SDL2_DIR, "src/render/software/**"), path.join(SDL2_DIR, "src/render/opengl/**"), path.join(SDL2_DIR, "src/render/opengles2/**"), -- SENSOR -- path.join(SDL2_DIR, "src/sensor/*.c"), path.join(SDL2_DIR, "src/sensor/*.h"), path.join(SDL2_DIR, "src/sensor/dummy/**"), -- THREAD -- path.join(SDL2_DIR, "src/thread/*.c"), path.join(SDL2_DIR, "src/thread/*.h"), -- TIMER -- path.join(SDL2_DIR, "src/timer/*.c"), path.join(SDL2_DIR, "src/timer/*.h"), path.join(SDL2_DIR, "src/timer/dummy/**"), -- VIDEO -- path.join(SDL2_DIR, "src/video/*.c"), path.join(SDL2_DIR, "src/video/*.h"), path.join(SDL2_DIR, "src/video/dummy/**"), path.join(SDL2_DIR, "src/video/yuv2rgb/**"), } filter "system:windows" links { "setupapi", "winmm", "imm32", "version" } files { path.join(SDL2_DIR, "src/audio/directsound/**"), path.join(SDL2_DIR, "src/audio/disk/**"), path.join(SDL2_DIR, "src/audio/winmm/**"), path.join(SDL2_DIR, "src/audio/wasapi/**"), path.join(SDL2_DIR, "src/core/windows/**"), path.join(SDL2_DIR, "src/events/scancodes_windows.h"), path.join(SDL2_DIR, "src/filesystem/windows/**"), path.join(SDL2_DIR, "src/haptic/windows/**"), path.join(SDL2_DIR, "src/hidapi/windows/hid.c"), path.join(SDL2_DIR, "src/joystick/windows/**"), path.join(SDL2_DIR, "src/loadso/windows/**"), path.join(SDL2_DIR, "src/locale/windows/**"), path.join(SDL2_DIR, "src/power/windows/**"), path.join(SDL2_DIR, "src/render/direct3d/**"), path.join(SDL2_DIR, "src/render/direct3d11/**"), path.join(SDL2_DIR, "src/sensor/windows/**"), path.join(SDL2_DIR, "src/thread/generic/SDL_syscond.c"), path.join(SDL2_DIR, "src/thread/windows/**"), path.join(SDL2_DIR, "src/timer/windows/**"), path.join(SDL2_DIR, "src/video/windows/**"), } removefiles { "**/SDL_render_winrt.*" } defines { "SDL_DISABLE_WINDOWS_IME", "WIN32", "__WIN32__", } links { "user32", "gdi32", "winmm", "imm32", "ole32", "oleaut32", "version", "uuid" } filter "system:linux" files { path.join(SDL2_DIR, "src/core/windows/**"), path.join(SDL2_DIR, "src/events/scancodes_linux.h"), path.join(SDL2_DIR, "src/haptic/linux/**"), path.join(SDL2_DIR, "src/joystick/linux/**"), path.join(SDL2_DIR, "src/locale/unix/**"), path.join(SDL2_DIR, "src/power/linux/**"), } filter "system:macosx" includedirs { path.join(SDL2_DIR, "src/video/khronos") } xcodebuildsettings { ["ALWAYS_SEARCH_USER_PATHS"] = "YES", } files { path.join(SDL2_DIR, "src/audio/coreaudio/**"), path.join(SDL2_DIR, "src/audio/disk/**"), path.join(SDL2_DIR, "src/events/scancodes_darwin.h"), path.join(SDL2_DIR, "src/file/cocoa/**"), path.join(SDL2_DIR, "src/filesystem/cocoa/**"), path.join(SDL2_DIR, "src/haptic/darwin/**"), path.join(SDL2_DIR, "src/hidapi/*.c"), path.join(SDL2_DIR, "src/hidapi/hidapi/*.h"), path.join(SDL2_DIR, "src/hidapi/mac/*.c"), path.join(SDL2_DIR, "src/hidapi/ios/*.c"), path.join(SDL2_DIR, "src/joystick/darwin/**"), path.join(SDL2_DIR, "src/loadso/dlopen/**"), path.join(SDL2_DIR, "src/locale/macosx/**"), path.join(SDL2_DIR, "src/power/macosx/**"), path.join(SDL2_DIR, "src/render/opengles/**"), path.join(SDL2_DIR, "src/render/metal/**"), path.join(SDL2_DIR, "src/sensor/coremotion/**"), path.join(SDL2_DIR, "src/thread/pthread/**"), path.join(SDL2_DIR, "src/timer/unix/**"), path.join(SDL2_DIR, "src/video/cocoa/**"), path.join(SDL2_DIR, "src/video/khronos/**"), path.join(SDL2_DIR, "src/video/offscreen/**"), path.join(SDL2_DIR, "src/video/uikit/**"), path.join(SDL2_DIR, "src/video/x11/**"), } defines { "SDL_POWER_MACOSX", "SDL_VIDEO_DRIVER_COCOA", "SDL_VIDEO_OPENGL_GLX", "SDL_LOADSO_DLOPEN", "SDL_TIMER_UNIX", "SDL_FRAMEWORK_COCOA", "SDL_FRAMEWORK_CARBON", "SDL_FILESYSTEM_COCOA", } buildoptions {"-fPIC"} filter "system:android" files { path.join(SDL2_DIR, "src/audio/android/**"), path.join(SDL2_DIR, "src/audio/openslES/**"), path.join(SDL2_DIR, "src/core/android/**"), path.join(SDL2_DIR, "src/filesystem/android/**"), path.join(SDL2_DIR, "src/haptic/android/**"), path.join(SDL2_DIR, "src/hidapi/android/hid.cpp"), path.join(SDL2_DIR, "src/joystick/android/**"), path.join(SDL2_DIR, "src/locale/android/**"), path.join(SDL2_DIR, "src/power/android/**"), path.join(SDL2_DIR, "src/sensor/android/**"), path.join(SDL2_DIR, "src/video/android/**"), path.join(SDL2_DIR, "src/loadso/dlopen/**"), path.join(SDL2_DIR, "src/thread/pthread/**"), path.join(SDL2_DIR, "src/timer/unix/**"), path.join(SDL2_DIR, "src/render/opengles/**"), } filter "system:ios" files { path.join(SDL2_DIR, "src/joystick/iphoneos/**"), } filter "action:vs*" defines { "_CRT_SECURE_NO_WARNINGS", "VC_EXTRALEAN", } project "sdl2_test_common" kind "StaticLib" files { path.join(SDL2_DIR, "src/test/**") } includedirs { SDL2_INCLUDE } project "sdl2_main" kind "StaticLib" includedirs { SDL2_INCLUDE } filter "system:windows" files { SDL2_DIR.."src/main/windows/*.c" } filter "system:macosx" files { SDL2_DIR.."src/main/dummy/*.c" } SDL2_TEST_DIR = path.join(SDL2_DIR, "test") project "Test" kind "WindowedApp" links { "sdl2", "sdl2_test_common" } filter "system:windows" links { "sdl2_main" } files { path.join(SDL2_DIR,"test/testsprite2.c"), } xcodebuildresources { path.join(SDL2_DIR, "test/*.bmp"), } includedirs { SDL2_INCLUDE } debugdir (SDL2_TEST_DIR) filter "system:macosx" links { "AudioToolbox.framework", "AudioUnit.framework", "Carbon.framework", "Cocoa.framework", "CoreAudio.framework", "CoreFoundation.framework", "CoreVideo.framework", "ForceFeedback.framework", "IOKit.framework", "Metal.framework", "dl" -- ? }